BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

app.rs 22.9 KiB Download Raw
1use std::path::PathBuf;
2
3use eframe::egui;
4
5use posprint::config::AppConfig;
6use posprint::dsl::{self, parse};
7use posprint::editor_assist::{
8 apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
9 complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options,
10 insert_at_cursor, parameter_insert_options, qr_insert_options,
11};
12use posprint::help_view;
13use posprint::io::{PosFile, PosMetadata};
14use posprint::undo::TextUndo;
15use posprint::HELP_MARKDOWN;
16
17use crate::preview_panel::show_preview_panel;
18use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
19
20#[derive(Clone, Copy, PartialEq, Eq)]
21enum ViewMode {
22 Design,
23 Help,
24 Settings,
25}
26
27pub struct PosPrintApp {
28 view_mode: ViewMode,
29 body: String,
30 metadata: PosMetadata,
31 file_path: Option<PathBuf>,
32 dirty: bool,
33 parse_error: Option<String>,
34 action_error: Option<String>,
35 show_print_dialog: bool,
36 print_dialog: PrintDialog,
37 editor_cursor: usize,
38 undo: TextUndo,
39 preview_zoom: f32,
40 config: AppConfig,
41 settings_status: Option<String>,
42}
43
44impl Default for PosPrintApp {
45 fn default() -> Self {
46 let config = AppConfig::load();
47 let mut metadata = PosMetadata::default();
48 metadata.page_width_mm = config.default_page_width_mm;
49 Self {
50 view_mode: ViewMode::Design,
51 body: default_template(),
52 metadata,
53 file_path: None,
54 dirty: false,
55 parse_error: None,
56 action_error: None,
57 show_print_dialog: false,
58 print_dialog: PrintDialog::default(),
59 editor_cursor: 0,
60 undo: TextUndo::default(),
61 preview_zoom: 1.0,
62 config,
63 settings_status: None,
64 }
65 }
66}
67
68impl PosPrintApp {
69 pub fn new_with_file(path: Option<PathBuf>) -> Self {
70 let mut app = Self::default();
71 if let Some(path) = path {
72 match PosFile::load_from_path(&path) {
73 Ok(file) => app.load_pos_file(path, file),
74 Err(e) => app.action_error = Some(format!("Open failed: {e:?}")),
75 }
76 }
77 app
78 }
79
80 fn title(&self) -> String {
81 let name = self
82 .file_path
83 .as_ref()
84 .and_then(|p| p.file_name())
85 .map(|s| s.to_string_lossy().to_string())
86 .or_else(|| self.metadata.title.clone())
87 .unwrap_or_else(|| "Untitled".into());
88 if self.dirty {
89 format!("* {name} — posprint")
90 } else {
91 format!("{name} — posprint")
92 }
93 }
94
95 fn pos_file(&self) -> PosFile {
96 PosFile {
97 version: 1,
98 metadata: self.metadata.clone(),
99 body: self.body.clone(),
100 }
101 }
102
103 fn load_pos_file(&mut self, path: PathBuf, file: PosFile) {
104 self.body = file.body;
105 self.metadata = file.metadata;
106 self.file_path = Some(path);
107 self.dirty = false;
108 self.parse_error = None;
109 self.action_error = None;
110 self.undo = TextUndo::default();
111 }
112
113 fn new_document(&mut self) {
114 *self = Self::default();
115 }
116
117 fn show_settings(&mut self, ui: &mut egui::Ui) {
118 ui.heading("Settings");
119 ui.separator();
120
121 ui.heading("New documents");
122 ui.horizontal(|ui| {
123 ui.label("Default page width (mm):");
124 let mut width = self.config.default_page_width_mm;
125 if ui
126 .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
127 .changed()
128 {
129 self.config.default_page_width_mm = width;
130 self.settings_status = None;
131 }
132 });
133 ui.label("Applies when you choose New. The current document width is unchanged.");
134
135 ui.add_space(16.0);
136 ui.heading("Trusted sites (noconfirm)");
137 ui.label(
138 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
139 );
140
141 if self.config.trusted_origins.is_empty() {
142 ui.label("No trusted sites yet.");
143 } else {
144 let origins = self.config.trusted_origins.clone();
145 for origin in origins {
146 ui.horizontal(|ui| {
147 ui.label(&origin);
148 if ui.button("Revoke").clicked() {
149 self.config.revoke_origin(&origin);
150 match self.config.save() {
151 Ok(()) => {
152 self.settings_status =
153 Some(format!("Revoked trust for {origin}"))
154 }
155 Err(e) => {
156 self.settings_status = Some(format!("Save failed: {e}"))
157 }
158 }
159 }
160 });
161 }
162 if ui.button("Revoke all").clicked() {
163 self.config.trusted_origins.clear();
164 match self.config.save() {
165 Ok(()) => {
166 self.settings_status = Some("Cleared all trusted sites.".into())
167 }
168 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
169 }
170 }
171 }
172
173 ui.add_space(16.0);
174 if ui.button("Save settings").clicked() {
175 match self.config.save() {
176 Ok(()) => self.settings_status = Some("Settings saved.".into()),
177 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
178 }
179 }
180 if let Some(status) = &self.settings_status {
181 ui.label(status);
182 }
183 }
184
185 fn open_file_dialog(&mut self) {
186 if let Some(path) = rfd::FileDialog::new()
187 .add_filter("POS template", &["pos"])
188 .pick_file()
189 {
190 match PosFile::load_from_path(&path) {
191 Ok(file) => self.load_pos_file(path, file),
192 Err(e) => self.action_error = Some(format!("Open failed: {e:?}")),
193 }
194 }
195 }
196
197 fn save(&mut self) {
198 if let Some(path) = self.file_path.clone() {
199 self.save_to_path(path);
200 } else {
201 self.save_as();
202 }
203 }
204
205 fn save_as(&mut self) {
206 if let Some(path) = rfd::FileDialog::new()
207 .add_filter("POS template", &["pos"])
208 .set_file_name("document.pos")
209 .save_file()
210 {
211 self.save_to_path(path);
212 }
213 }
214
215 fn save_to_path(&mut self, path: PathBuf) {
216 if let Err(e) = self.pos_file().save_to_path(&path) {
217 self.action_error = Some(format!("Save failed: {e:?}"));
218 } else {
219 self.file_path = Some(path);
220 self.dirty = false;
221 self.action_error = None;
222 }
223 }
224
225 fn validate_parse(&mut self) {
226 self.parse_error = match parse(&self.body) {
227 Ok(_) => None,
228 Err(e) => Some(e.to_string()),
229 };
230 }
231
232 fn handle_shortcuts(&mut self, ctx: &egui::Context) {
233 let mut new_doc = false;
234 let mut open = false;
235 let mut save = false;
236 let mut undo = false;
237 let mut redo = false;
238
239 ctx.input(|i| {
240 if i.modifiers.command {
241 if i.key_pressed(egui::Key::S) {
242 save = true;
243 }
244 if i.key_pressed(egui::Key::N) {
245 new_doc = true;
246 }
247 if i.key_pressed(egui::Key::O) {
248 open = true;
249 }
250 if i.key_pressed(egui::Key::Z) {
251 if i.modifiers.shift {
252 redo = true;
253 } else {
254 undo = true;
255 }
256 }
257 if i.modifiers.shift && i.key_pressed(egui::Key::Y) {
258 redo = true;
259 }
260 }
261 });
262
263 if new_doc {
264 self.new_document();
265 }
266 if open {
267 self.open_file_dialog();
268 }
269 if save {
270 self.save();
271 }
272 if undo {
273 if let Some(prev) = self.undo.undo(&self.body) {
274 self.body = prev;
275 self.dirty = true;
276 }
277 }
278 if redo {
279 if let Some(next) = self.undo.redo(&self.body) {
280 self.body = next;
281 self.dirty = true;
282 }
283 }
284 }
285
286 fn apply_print_dialog_params_to_preview(&mut self) {
287 self.print_dialog.apply_inputs_to_last_params();
288 }
289
290 fn close_print_dialog(&mut self) {
291 self.apply_print_dialog_params_to_preview();
292 self.show_print_dialog = false;
293 }
294
295 fn open_print_dialog(&mut self) {
296 match self.print_dialog.prepare(&self.body) {
297 Ok(()) => self.show_print_dialog = true,
298 Err(e) => self.parse_error = Some(e),
299 }
300 }
301
302 fn execute_print(&mut self) {
303 if self.print_dialog.execute_print(
304 &self.body,
305 &self.metadata,
306 self.file_path.as_ref(),
307 ) == PrintExecuteResult::Printed
308 {
309 self.show_print_dialog = false;
310 }
311 }
312}
313
314impl eframe::App for PosPrintApp {
315 fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
316 self.validate_parse();
317 if !self.show_print_dialog {
318 self.handle_shortcuts(ctx);
319 }
320 self.print_dialog.poll_printer_discovery(ctx);
321
322 let main_enabled = !self.show_print_dialog;
323
324 egui::TopBottomPanel::top("menu").show(ctx, |ui| {
325 ui.add_enabled_ui(main_enabled, |ui| {
326 ui.horizontal_wrapped(|ui| {
327 if ui.button("New").clicked() {
328 self.new_document();
329 }
330 if ui.button("Open").clicked() {
331 self.open_file_dialog();
332 }
333 if ui.button("Save").clicked() {
334 self.save();
335 }
336 if ui.button("Save As").clicked() {
337 self.save_as();
338 }
339 if ui.button("Print").clicked() {
340 self.open_print_dialog();
341 }
342
343 ui.menu_button("Insert", |ui| {
344 for opt in image_insert_options() {
345 if ui.button(format!("Image — {}", opt.label)).clicked() {
346 self.insert_snippet(&opt.snippet);
347 ui.close_menu();
348 }
349 }
350 ui.separator();
351 ui.menu_button("Barcode", |ui| {
352 for opt in barcode_insert_options() {
353 if ui.button(&opt.label).clicked() {
354 self.insert_snippet(&opt.snippet);
355 ui.close_menu();
356 }
357 }
358 });
359 ui.menu_button("QR code", |ui| {
360 for opt in qr_insert_options() {
361 if ui.button(&opt.label).clicked() {
362 self.insert_snippet(&opt.snippet);
363 ui.close_menu();
364 }
365 }
366 });
367 ui.menu_button("Date / time", |ui| {
368 for opt in date_time_insert_options() {
369 if ui.button(&opt.label).clicked() {
370 self.insert_snippet(&opt.snippet);
371 ui.close_menu();
372 }
373 }
374 });
375 ui.menu_button("Parameters", |ui| {
376 for opt in parameter_insert_options(&self.body) {
377 if ui.button(&opt.label).clicked() {
378 self.insert_snippet(&opt.snippet);
379 ui.close_menu();
380 }
381 }
382 });
383 ui.separator();
384 if ui.button("@feed").clicked() {
385 self.insert_snippet("@feed 3\n");
386 ui.close_menu();
387 }
388 if ui.button("@cut").clicked() {
389 self.insert_snippet("@cut\n");
390 ui.close_menu();
391 }
392 });
393 });
394
395 ui.separator();
396 ui.horizontal(|ui| {
397 ui.label("Page width (mm):");
398 let mut width = self.metadata.page_width_mm;
399 if ui
400 .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
401 .changed()
402 {
403 self.metadata.page_width_mm = width;
404 self.dirty = true;
405 }
406 });
407 });
408
409 if let Some(err) = &self.parse_error {
410 ui.colored_label(egui::Color32::RED, err);
411 }
412 if let Some(err) = &self.action_error {
413 ui.colored_label(egui::Color32::RED, err);
414 }
415 });
416
417 egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
418 ui.add_enabled_ui(main_enabled, |ui| {
419 ui.horizontal(|ui| {
420 ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
421 ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
422 ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
423 if let Ok(doc) = parse(&self.body) {
424 if !dsl::document_ends_with_cut(&doc) {
425 ui.colored_label(
426 egui::Color32::RED,
427 "Warning: No @cut directive at end of file.",
428 );
429 }
430 }
431 });
432 });
433 });
434
435 match self.view_mode {
436 ViewMode::Design => {
437 egui::SidePanel::right("preview_panel")
438 .resizable(main_enabled)
439 .min_width(260.0)
440 .default_width(380.0)
441 .show(ctx, |ui| {
442 ui.add_enabled_ui(main_enabled, |ui| {
443 ui.heading("Preview");
444 ui.horizontal(|ui| {
445 ui.label(format!(
446 "Page width: {:.0} mm",
447 self.metadata.page_width_mm
448 ));
449 ui.separator();
450 ui.label("Zoom:");
451 ui.add(
452 egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0)
453 .logarithmic(true)
454 .show_value(true),
455 );
456 if ui.button("100%").clicked() {
457 self.preview_zoom = 1.0;
458 }
459 });
460 ui.separator();
461 self.show_preview(ui, ctx);
462 });
463 });
464
465 egui::CentralPanel::default().show(ctx, |ui| {
466 ui.add_enabled_ui(main_enabled, |ui| {
467 ui.heading("Editor");
468 self.show_editor(ui);
469 });
470 });
471 }
472 ViewMode::Help => {
473 egui::CentralPanel::default().show(ctx, |ui| {
474 ui.add_enabled_ui(main_enabled, |ui| {
475 help_view::show_help(ui, HELP_MARKDOWN);
476 });
477 });
478 }
479 ViewMode::Settings => {
480 egui::CentralPanel::default().show(ctx, |ui| {
481 ui.add_enabled_ui(main_enabled, |ui| {
482 self.show_settings(ui);
483 });
484 });
485 }
486 }
487
488 if self.show_print_dialog {
489 let mut open = true;
490 egui::Window::new("Print")
491 .collapsible(false)
492 .resizable(true)
493 .default_size([420.0, 520.0])
494 .open(&mut open)
495 .show(ctx, |ui| {
496 match self.print_dialog.show_ui(ui) {
497 PrintDialogAction::Print => self.execute_print(),
498 PrintDialogAction::None => {}
499 }
500 });
501 if !open {
502 self.close_print_dialog();
503 }
504 }
505
506 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
507 }
508}
509
510impl PosPrintApp {
511 fn insert_snippet(&mut self, snippet: &str) {
512 let before = self.body.clone();
513 let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
514 self.body = body;
515 self.editor_cursor = cursor;
516 self.undo.record(before);
517 self.dirty = true;
518 self.view_mode = ViewMode::Design;
519 }
520
521 fn show_editor(&mut self, ui: &mut egui::Ui) {
522 let before = self.body.clone();
523 let cursor_before = self.editor_cursor;
524
525 // Autocomplete steals focus every frame; keep it off while the print dialog is open.
526 let autocomplete_enabled = !self.show_print_dialog;
527 let directive_ctx = autocomplete_enabled
528 .then(|| at_directive_prefix(&self.body, cursor_before))
529 .flatten();
530 let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
531 complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
532 });
533
534 let mut tab_completion: Option<(usize, String)> = None;
535 if autocomplete_active {
536 if let Some((at_index, prefix)) = directive_ctx.clone() {
537 ui.input_mut(|input| {
538 if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
539 tab_completion = Some((at_index, prefix));
540 input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
541 }
542 });
543 }
544 }
545
546 let font_id = egui::TextStyle::Monospace.resolve(ui.style());
547 let row_height = ui.fonts(|f| f.row_height(&font_id)).max(1.0);
548 let rows = ((ui.available_height() / row_height).floor() as usize).clamp(8, 500);
549
550 let output = egui::TextEdit::multiline(&mut self.body)
551 .id_salt("main_editor")
552 .desired_width(f32::INFINITY)
553 .desired_rows(rows)
554 .font(egui::TextStyle::Monospace)
555 .lock_focus(autocomplete_active)
556 .show(ui);
557
558 // Do not call request_focus every frame — that fights paste/IME and can freeze the UI.
559 // lock_focus(true) above is enough to keep Tab-completion working.
560
561 self.editor_cursor = output
562 .cursor_range
563 .as_ref()
564 .map(|r| char_index_to_byte(&self.body, r.primary.ccursor.index))
565 .or_else(|| {
566 output.state.cursor.char_range().map(|r| {
567 char_index_to_byte(&self.body, r.primary.index)
568 })
569 })
570 .unwrap_or(self.body.len());
571
572 if let Some((at_index, prefix)) = tab_completion {
573 if let Some(completed) = complete_directive(&prefix) {
574 let undo_before = self.body.clone();
575 self.editor_cursor =
576 apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
577 self.undo.record(undo_before);
578 self.dirty = true;
579 }
580 } else if output.response.changed() {
581 self.undo.record(before);
582 self.dirty = true;
583 }
584
585 if autocomplete_enabled {
586 if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
587 if let Some(suffix) = directive_ghost_suffix(&prefix) {
588 if let Some(cursor_range) = &output.cursor_range {
589 let font_id = egui::TextStyle::Monospace.resolve(ui.style());
590 let pos = output.galley.pos_from_cursor(&cursor_range.primary);
591 let ghost_pos = output.galley_pos + pos.min.to_vec2();
592 let ghost_color = ui.visuals().weak_text_color();
593 ui.painter().text(
594 ghost_pos,
595 egui::Align2::LEFT_TOP,
596 suffix,
597 font_id,
598 ghost_color,
599 );
600 }
601 }
602 }
603 }
604 }
605
606 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
607 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
608 // Prefer live dialog inputs while the print dialog is open.
609 let params = if self.show_print_dialog {
610 &self.print_dialog.param_inputs
611 } else {
612 &self.print_dialog.last_params
613 };
614 show_preview_panel(
615 ui,
616 ctx,
617 &self.body,
618 &self.metadata,
619 base_dir,
620 params,
621 self.preview_zoom,
622 "design_preview_",
623 );
624 }
625}
626
627fn default_template() -> String {
628 String::new()
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 #[test]
636 fn default_template_is_empty() {
637 let app = PosPrintApp::default();
638 assert!(app.body.is_empty());
639 assert!(parse(&app.body).is_ok());
640 }
641
642 #[test]
643 fn title_shows_asterisk_before_name_when_dirty() {
644 let mut app = PosPrintApp::default();
645 app.dirty = true;
646 assert!(app.title().starts_with("* "));
647 }
648}