BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

app.rs 24.7 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, byte_index_to_char,
9 char_index_to_byte, complete_directive, date_time_insert_options, directive_ghost_suffix,
10 image_insert_options, 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("LAN network printers");
137 ui.label(
138 "Discover POS printers on the local network via raw ESC/POS TCP port 9100 (not CUPS).",
139 );
140 let mut lan = self.config.lan_printers_enabled;
141 if ui
142 .checkbox(&mut lan, "Enable LAN printer discovery (default: off)")
143 .changed()
144 {
145 self.config.lan_printers_enabled = lan;
146 self.settings_status = None;
147 }
148 ui.label(format!(
149 "Cached LAN printers: {}",
150 self.config.lan_printer_cache.len()
151 ));
152 if !self.config.lan_printer_cache.is_empty() {
153 egui::ScrollArea::vertical()
154 .id_salt("settings_lan_cache")
155 .max_height(100.0)
156 .show(ui, |ui| {
157 for entry in &self.config.lan_printer_cache {
158 ui.label(format!("{}:{}", entry.host, entry.port));
159 }
160 });
161 if ui.button("Clear LAN cache").clicked() {
162 self.config.clear_lan_printer_cache();
163 self.settings_status = Some("LAN printer cache cleared (save to persist).".into());
164 }
165 }
166
167 ui.add_space(16.0);
168 ui.heading("Trusted sites (noconfirm)");
169 ui.label(
170 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
171 );
172
173 if self.config.trusted_origins.is_empty() {
174 ui.label("No trusted sites yet.");
175 } else {
176 let origins = self.config.trusted_origins.clone();
177 for origin in origins {
178 ui.horizontal(|ui| {
179 ui.label(&origin);
180 if ui.button("Revoke").clicked() {
181 self.config.revoke_origin(&origin);
182 match self.config.save() {
183 Ok(()) => {
184 self.settings_status =
185 Some(format!("Revoked trust for {origin}"))
186 }
187 Err(e) => {
188 self.settings_status = Some(format!("Save failed: {e}"))
189 }
190 }
191 }
192 });
193 }
194 if ui.button("Revoke all").clicked() {
195 self.config.trusted_origins.clear();
196 match self.config.save() {
197 Ok(()) => {
198 self.settings_status = Some("Cleared all trusted sites.".into())
199 }
200 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
201 }
202 }
203 }
204
205 ui.add_space(16.0);
206 if ui.button("Save settings").clicked() {
207 match self.config.save() {
208 Ok(()) => self.settings_status = Some("Settings saved.".into()),
209 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
210 }
211 }
212 if let Some(status) = &self.settings_status {
213 ui.label(status);
214 }
215 }
216
217 fn open_file_dialog(&mut self) {
218 if let Some(path) = rfd::FileDialog::new()
219 .add_filter("POS template", &["pos"])
220 .pick_file()
221 {
222 match PosFile::load_from_path(&path) {
223 Ok(file) => self.load_pos_file(path, file),
224 Err(e) => self.action_error = Some(format!("Open failed: {e:?}")),
225 }
226 }
227 }
228
229 fn save(&mut self) {
230 if let Some(path) = self.file_path.clone() {
231 self.save_to_path(path);
232 } else {
233 self.save_as();
234 }
235 }
236
237 fn save_as(&mut self) {
238 if let Some(path) = rfd::FileDialog::new()
239 .add_filter("POS template", &["pos"])
240 .set_file_name("document.pos")
241 .save_file()
242 {
243 self.save_to_path(path);
244 }
245 }
246
247 fn save_to_path(&mut self, path: PathBuf) {
248 if let Err(e) = self.pos_file().save_to_path(&path) {
249 self.action_error = Some(format!("Save failed: {e:?}"));
250 } else {
251 self.file_path = Some(path);
252 self.dirty = false;
253 self.action_error = None;
254 }
255 }
256
257 fn validate_parse(&mut self) {
258 self.parse_error = match parse(&self.body) {
259 Ok(_) => None,
260 Err(e) => Some(e.to_string()),
261 };
262 }
263
264 fn handle_shortcuts(&mut self, ctx: &egui::Context) {
265 let mut new_doc = false;
266 let mut open = false;
267 let mut save = false;
268 let mut undo = false;
269 let mut redo = false;
270
271 ctx.input(|i| {
272 if i.modifiers.command {
273 if i.key_pressed(egui::Key::S) {
274 save = true;
275 }
276 if i.key_pressed(egui::Key::N) {
277 new_doc = true;
278 }
279 if i.key_pressed(egui::Key::O) {
280 open = true;
281 }
282 if i.key_pressed(egui::Key::Z) {
283 if i.modifiers.shift {
284 redo = true;
285 } else {
286 undo = true;
287 }
288 }
289 if i.modifiers.shift && i.key_pressed(egui::Key::Y) {
290 redo = true;
291 }
292 }
293 });
294
295 if new_doc {
296 self.new_document();
297 }
298 if open {
299 self.open_file_dialog();
300 }
301 if save {
302 self.save();
303 }
304 if undo {
305 if let Some(prev) = self.undo.undo(&self.body) {
306 self.body = prev;
307 self.dirty = true;
308 }
309 }
310 if redo {
311 if let Some(next) = self.undo.redo(&self.body) {
312 self.body = next;
313 self.dirty = true;
314 }
315 }
316 }
317
318 fn apply_print_dialog_params_to_preview(&mut self) {
319 self.print_dialog.apply_inputs_to_last_params();
320 }
321
322 fn close_print_dialog(&mut self) {
323 self.apply_print_dialog_params_to_preview();
324 self.show_print_dialog = false;
325 }
326
327 fn open_print_dialog(&mut self) {
328 match self.print_dialog.prepare(&self.body) {
329 Ok(()) => self.show_print_dialog = true,
330 Err(e) => self.parse_error = Some(e),
331 }
332 }
333
334 fn execute_print(&mut self) {
335 if self.print_dialog.execute_print(
336 &self.body,
337 &self.metadata,
338 self.file_path.as_ref(),
339 ) == PrintExecuteResult::Printed
340 {
341 self.show_print_dialog = false;
342 }
343 }
344}
345
346impl eframe::App for PosPrintApp {
347 fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
348 self.validate_parse();
349 if !self.show_print_dialog {
350 self.handle_shortcuts(ctx);
351 }
352 self.print_dialog.poll_printer_discovery(ctx);
353
354 let main_enabled = !self.show_print_dialog;
355
356 egui::TopBottomPanel::top("menu").show(ctx, |ui| {
357 ui.add_enabled_ui(main_enabled, |ui| {
358 ui.horizontal_wrapped(|ui| {
359 if ui.button("New").clicked() {
360 self.new_document();
361 }
362 if ui.button("Open").clicked() {
363 self.open_file_dialog();
364 }
365 if ui.button("Save").clicked() {
366 self.save();
367 }
368 if ui.button("Save As").clicked() {
369 self.save_as();
370 }
371 if ui.button("Print").clicked() {
372 self.open_print_dialog();
373 }
374
375 ui.menu_button("Insert", |ui| {
376 for opt in image_insert_options() {
377 if ui.button(format!("Image — {}", opt.label)).clicked() {
378 self.insert_snippet(&opt.snippet);
379 ui.close_menu();
380 }
381 }
382 ui.separator();
383 ui.menu_button("Barcode", |ui| {
384 for opt in barcode_insert_options() {
385 if ui.button(&opt.label).clicked() {
386 self.insert_snippet(&opt.snippet);
387 ui.close_menu();
388 }
389 }
390 });
391 ui.menu_button("QR code", |ui| {
392 for opt in qr_insert_options() {
393 if ui.button(&opt.label).clicked() {
394 self.insert_snippet(&opt.snippet);
395 ui.close_menu();
396 }
397 }
398 });
399 ui.menu_button("Date / time", |ui| {
400 for opt in date_time_insert_options() {
401 if ui.button(&opt.label).clicked() {
402 self.insert_snippet(&opt.snippet);
403 ui.close_menu();
404 }
405 }
406 });
407 ui.menu_button("Parameters", |ui| {
408 for opt in parameter_insert_options(&self.body) {
409 if ui.button(&opt.label).clicked() {
410 self.insert_snippet(&opt.snippet);
411 ui.close_menu();
412 }
413 }
414 });
415 ui.separator();
416 if ui.button("@feed").clicked() {
417 self.insert_snippet("@feed 3\n");
418 ui.close_menu();
419 }
420 if ui.button("@cut").clicked() {
421 self.insert_snippet("@cut\n");
422 ui.close_menu();
423 }
424 });
425 });
426
427 ui.separator();
428 ui.horizontal(|ui| {
429 ui.label("Page width (mm):");
430 let mut width = self.metadata.page_width_mm;
431 if ui
432 .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
433 .changed()
434 {
435 self.metadata.page_width_mm = width;
436 self.dirty = true;
437 }
438 });
439 });
440
441 if let Some(err) = &self.parse_error {
442 ui.colored_label(egui::Color32::RED, err);
443 }
444 if let Some(err) = &self.action_error {
445 ui.colored_label(egui::Color32::RED, err);
446 }
447 });
448
449 egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
450 ui.add_enabled_ui(main_enabled, |ui| {
451 ui.horizontal(|ui| {
452 ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
453 ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
454 ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
455 if let Ok(doc) = parse(&self.body) {
456 if !dsl::document_ends_with_cut(&doc) {
457 ui.colored_label(
458 egui::Color32::RED,
459 "Warning: No @cut directive at end of file.",
460 );
461 }
462 }
463 });
464 });
465 });
466
467 match self.view_mode {
468 ViewMode::Design => {
469 egui::SidePanel::right("preview_panel")
470 .resizable(main_enabled)
471 .min_width(260.0)
472 .default_width(380.0)
473 .show(ctx, |ui| {
474 ui.add_enabled_ui(main_enabled, |ui| {
475 ui.heading("Preview");
476 ui.horizontal(|ui| {
477 ui.label(format!(
478 "Page width: {:.0} mm",
479 self.metadata.page_width_mm
480 ));
481 ui.separator();
482 ui.label("Zoom:");
483 ui.add(
484 egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0)
485 .logarithmic(true)
486 .show_value(true),
487 );
488 if ui.button("100%").clicked() {
489 self.preview_zoom = 1.0;
490 }
491 });
492 ui.separator();
493 self.show_preview(ui, ctx);
494 });
495 });
496
497 egui::CentralPanel::default().show(ctx, |ui| {
498 ui.add_enabled_ui(main_enabled, |ui| {
499 ui.heading("Editor");
500 self.show_editor(ui);
501 });
502 });
503 }
504 ViewMode::Help => {
505 egui::CentralPanel::default().show(ctx, |ui| {
506 ui.add_enabled_ui(main_enabled, |ui| {
507 help_view::show_help(ui, HELP_MARKDOWN);
508 });
509 });
510 }
511 ViewMode::Settings => {
512 egui::CentralPanel::default().show(ctx, |ui| {
513 ui.add_enabled_ui(main_enabled, |ui| {
514 self.show_settings(ui);
515 });
516 });
517 }
518 }
519
520 if self.show_print_dialog {
521 let mut open = true;
522 egui::Window::new("Print")
523 .collapsible(false)
524 .resizable(true)
525 .default_size([420.0, 520.0])
526 .open(&mut open)
527 .show(ctx, |ui| {
528 match self.print_dialog.show_ui(ui) {
529 PrintDialogAction::Print => self.execute_print(),
530 PrintDialogAction::None => {}
531 }
532 });
533 if !open {
534 self.close_print_dialog();
535 }
536 }
537
538 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
539 }
540}
541
542impl PosPrintApp {
543 fn insert_snippet(&mut self, snippet: &str) {
544 let before = self.body.clone();
545 let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
546 self.body = body;
547 self.editor_cursor = cursor;
548 self.undo.record(before);
549 self.dirty = true;
550 self.view_mode = ViewMode::Design;
551 }
552
553 fn show_editor(&mut self, ui: &mut egui::Ui) {
554 let before = self.body.clone();
555 let cursor_before = self.editor_cursor;
556
557 // Autocomplete steals focus every frame; keep it off while the print dialog is open.
558 let autocomplete_enabled = !self.show_print_dialog;
559 let directive_ctx = autocomplete_enabled
560 .then(|| at_directive_prefix(&self.body, cursor_before))
561 .flatten();
562 let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
563 complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
564 });
565
566 let mut tab_completion: Option<(usize, String)> = None;
567 if autocomplete_active {
568 if let Some((at_index, prefix)) = directive_ctx.clone() {
569 ui.input_mut(|input| {
570 if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
571 tab_completion = Some((at_index, prefix));
572 input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
573 }
574 });
575 }
576 }
577
578 let font_id = egui::TextStyle::Monospace.resolve(ui.style());
579 let row_height = ui.fonts(|f| f.row_height(&font_id)).max(1.0);
580 let rows = ((ui.available_height() / row_height).floor() as usize).clamp(8, 500);
581
582 let output = egui::TextEdit::multiline(&mut self.body)
583 .id_salt("main_editor")
584 .desired_width(f32::INFINITY)
585 .desired_rows(rows)
586 .font(egui::TextStyle::Monospace)
587 .lock_focus(autocomplete_active)
588 .show(ui);
589
590 // Do not call request_focus every frame — that fights paste/IME and can freeze the UI.
591 // lock_focus(true) above is enough to keep Tab-completion working.
592
593 self.editor_cursor = output
594 .cursor_range
595 .as_ref()
596 .map(|r| char_index_to_byte(&self.body, r.primary.ccursor.index))
597 .or_else(|| {
598 output.state.cursor.char_range().map(|r| {
599 char_index_to_byte(&self.body, r.primary.index)
600 })
601 })
602 .unwrap_or(self.body.len());
603
604 if let Some((at_index, prefix)) = tab_completion {
605 if let Some(completed) = complete_directive(&prefix) {
606 let undo_before = self.body.clone();
607 // Use the pre-TextEdit cursor: that is the end of the typed prefix.
608 self.editor_cursor = apply_directive_completion(
609 &mut self.body,
610 at_index,
611 cursor_before,
612 completed,
613 );
614 // Sync egui TextEdit caret to the end of the completed directive.
615 let char_idx = byte_index_to_char(&self.body, self.editor_cursor);
616 let mut state = output.state;
617 state.cursor.set_char_range(Some(egui::text::CCursorRange::one(
618 egui::text::CCursor::new(char_idx),
619 )));
620 state.store(ui.ctx(), output.response.id);
621 self.undo.record(undo_before);
622 self.dirty = true;
623 }
624 } else if output.response.changed() {
625 self.undo.record(before);
626 self.dirty = true;
627 }
628
629 if autocomplete_enabled {
630 if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
631 if let Some(suffix) = directive_ghost_suffix(&prefix) {
632 if let Some(cursor_range) = &output.cursor_range {
633 let font_id = egui::TextStyle::Monospace.resolve(ui.style());
634 let pos = output.galley.pos_from_cursor(&cursor_range.primary);
635 let ghost_pos = output.galley_pos + pos.min.to_vec2();
636 let ghost_color = ui.visuals().weak_text_color();
637 ui.painter().text(
638 ghost_pos,
639 egui::Align2::LEFT_TOP,
640 suffix,
641 font_id,
642 ghost_color,
643 );
644 }
645 }
646 }
647 }
648 }
649
650 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
651 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
652 // Prefer live dialog inputs while the print dialog is open.
653 let params = if self.show_print_dialog {
654 &self.print_dialog.param_inputs
655 } else {
656 &self.print_dialog.last_params
657 };
658 show_preview_panel(
659 ui,
660 ctx,
661 &self.body,
662 &self.metadata,
663 base_dir,
664 params,
665 self.preview_zoom,
666 "design_preview_",
667 );
668 }
669}
670
671fn default_template() -> String {
672 String::new()
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678
679 #[test]
680 fn default_template_is_empty() {
681 let app = PosPrintApp::default();
682 assert!(app.body.is_empty());
683 assert!(parse(&app.body).is_ok());
684 }
685
686 #[test]
687 fn title_shows_asterisk_before_name_when_dirty() {
688 let mut app = PosPrintApp::default();
689 app.dirty = true;
690 assert!(app.title().starts_with("* "));
691 }
692}