use std::path::PathBuf; use eframe::egui; use posprint::config::AppConfig; use posprint::dsl::{self, parse}; use posprint::editor_assist::{ apply_directive_completion, at_directive_prefix, barcode_insert_options, byte_index_to_char, char_index_to_byte, complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options, insert_at_cursor, parameter_insert_options, qr_insert_options, }; use posprint::help_view; use posprint::io::{PosFile, PosMetadata}; use posprint::undo::TextUndo; use posprint::HELP_MARKDOWN; use crate::preview_panel::show_preview_panel; use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult}; #[derive(Clone, Copy, PartialEq, Eq)] enum ViewMode { Design, Help, Settings, } pub struct PosPrintApp { view_mode: ViewMode, body: String, metadata: PosMetadata, file_path: Option, dirty: bool, parse_error: Option, action_error: Option, show_print_dialog: bool, print_dialog: PrintDialog, editor_cursor: usize, undo: TextUndo, preview_zoom: f32, config: AppConfig, settings_status: Option, } impl Default for PosPrintApp { fn default() -> Self { let config = AppConfig::load(); let mut metadata = PosMetadata::default(); metadata.page_width_mm = config.default_page_width_mm; Self { view_mode: ViewMode::Design, body: default_template(), metadata, file_path: None, dirty: false, parse_error: None, action_error: None, show_print_dialog: false, print_dialog: PrintDialog::default(), editor_cursor: 0, undo: TextUndo::default(), preview_zoom: 1.0, config, settings_status: None, } } } impl PosPrintApp { pub fn new_with_file(path: Option) -> Self { let mut app = Self::default(); if let Some(path) = path { match PosFile::load_from_path(&path) { Ok(file) => app.load_pos_file(path, file), Err(e) => app.action_error = Some(format!("Open failed: {e:?}")), } } app } fn title(&self) -> String { let name = self .file_path .as_ref() .and_then(|p| p.file_name()) .map(|s| s.to_string_lossy().to_string()) .or_else(|| self.metadata.title.clone()) .unwrap_or_else(|| "Untitled".into()); if self.dirty { format!("* {name} — posprint") } else { format!("{name} — posprint") } } fn pos_file(&self) -> PosFile { PosFile { version: 1, metadata: self.metadata.clone(), body: self.body.clone(), } } fn load_pos_file(&mut self, path: PathBuf, file: PosFile) { self.body = file.body; self.metadata = file.metadata; self.file_path = Some(path); self.dirty = false; self.parse_error = None; self.action_error = None; self.undo = TextUndo::default(); } fn new_document(&mut self) { *self = Self::default(); } fn show_settings(&mut self, ui: &mut egui::Ui) { ui.heading("Settings"); ui.separator(); ui.heading("New documents"); ui.horizontal(|ui| { ui.label("Default page width (mm):"); let mut width = self.config.default_page_width_mm; if ui .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0)) .changed() { self.config.default_page_width_mm = width; self.settings_status = None; } }); ui.label("Applies when you choose New. The current document width is unchanged."); ui.add_space(16.0); ui.heading("LAN network printers"); ui.label( "Discover POS printers on the local network via raw ESC/POS TCP port 9100 (not CUPS).", ); let mut lan = self.config.lan_printers_enabled; if ui .checkbox(&mut lan, "Enable LAN printer discovery (default: off)") .changed() { self.config.lan_printers_enabled = lan; self.settings_status = None; } ui.label(format!( "Cached LAN printers: {}", self.config.lan_printer_cache.len() )); if !self.config.lan_printer_cache.is_empty() { egui::ScrollArea::vertical() .id_salt("settings_lan_cache") .max_height(100.0) .show(ui, |ui| { for entry in &self.config.lan_printer_cache { ui.label(format!("{}:{}", entry.host, entry.port)); } }); if ui.button("Clear LAN cache").clicked() { self.config.clear_lan_printer_cache(); self.settings_status = Some("LAN printer cache cleared (save to persist).".into()); } } ui.add_space(16.0); ui.heading("Trusted sites (noconfirm)"); ui.label( "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.", ); if self.config.trusted_origins.is_empty() { ui.label("No trusted sites yet."); } else { let origins = self.config.trusted_origins.clone(); for origin in origins { ui.horizontal(|ui| { ui.label(&origin); if ui.button("Revoke").clicked() { self.config.revoke_origin(&origin); match self.config.save() { Ok(()) => { self.settings_status = Some(format!("Revoked trust for {origin}")) } Err(e) => { self.settings_status = Some(format!("Save failed: {e}")) } } } }); } if ui.button("Revoke all").clicked() { self.config.trusted_origins.clear(); match self.config.save() { Ok(()) => { self.settings_status = Some("Cleared all trusted sites.".into()) } Err(e) => self.settings_status = Some(format!("Save failed: {e}")), } } } ui.add_space(16.0); if ui.button("Save settings").clicked() { match self.config.save() { Ok(()) => self.settings_status = Some("Settings saved.".into()), Err(e) => self.settings_status = Some(format!("Save failed: {e}")), } } if let Some(status) = &self.settings_status { ui.label(status); } } fn open_file_dialog(&mut self) { if let Some(path) = rfd::FileDialog::new() .add_filter("POS template", &["pos"]) .pick_file() { match PosFile::load_from_path(&path) { Ok(file) => self.load_pos_file(path, file), Err(e) => self.action_error = Some(format!("Open failed: {e:?}")), } } } fn save(&mut self) { if let Some(path) = self.file_path.clone() { self.save_to_path(path); } else { self.save_as(); } } fn save_as(&mut self) { if let Some(path) = rfd::FileDialog::new() .add_filter("POS template", &["pos"]) .set_file_name("document.pos") .save_file() { self.save_to_path(path); } } fn save_to_path(&mut self, path: PathBuf) { if let Err(e) = self.pos_file().save_to_path(&path) { self.action_error = Some(format!("Save failed: {e:?}")); } else { self.file_path = Some(path); self.dirty = false; self.action_error = None; } } fn validate_parse(&mut self) { self.parse_error = match parse(&self.body) { Ok(_) => None, Err(e) => Some(e.to_string()), }; } fn handle_shortcuts(&mut self, ctx: &egui::Context) { let mut new_doc = false; let mut open = false; let mut save = false; let mut undo = false; let mut redo = false; ctx.input(|i| { if i.modifiers.command { if i.key_pressed(egui::Key::S) { save = true; } if i.key_pressed(egui::Key::N) { new_doc = true; } if i.key_pressed(egui::Key::O) { open = true; } if i.key_pressed(egui::Key::Z) { if i.modifiers.shift { redo = true; } else { undo = true; } } if i.modifiers.shift && i.key_pressed(egui::Key::Y) { redo = true; } } }); if new_doc { self.new_document(); } if open { self.open_file_dialog(); } if save { self.save(); } if undo { if let Some(prev) = self.undo.undo(&self.body) { self.body = prev; self.dirty = true; } } if redo { if let Some(next) = self.undo.redo(&self.body) { self.body = next; self.dirty = true; } } } fn apply_print_dialog_params_to_preview(&mut self) { self.print_dialog.apply_inputs_to_last_params(); } fn close_print_dialog(&mut self) { self.apply_print_dialog_params_to_preview(); self.show_print_dialog = false; } fn open_print_dialog(&mut self) { match self.print_dialog.prepare(&self.body) { Ok(()) => self.show_print_dialog = true, Err(e) => self.parse_error = Some(e), } } fn execute_print(&mut self) { if self.print_dialog.execute_print( &self.body, &self.metadata, self.file_path.as_ref(), ) == PrintExecuteResult::Printed { self.show_print_dialog = false; } } } impl eframe::App for PosPrintApp { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.validate_parse(); if !self.show_print_dialog { self.handle_shortcuts(ctx); } self.print_dialog.poll_printer_discovery(ctx); let main_enabled = !self.show_print_dialog; egui::TopBottomPanel::top("menu").show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { ui.horizontal_wrapped(|ui| { if ui.button("New").clicked() { self.new_document(); } if ui.button("Open").clicked() { self.open_file_dialog(); } if ui.button("Save").clicked() { self.save(); } if ui.button("Save As").clicked() { self.save_as(); } if ui.button("Print").clicked() { self.open_print_dialog(); } ui.menu_button("Insert", |ui| { for opt in image_insert_options() { if ui.button(format!("Image — {}", opt.label)).clicked() { self.insert_snippet(&opt.snippet); ui.close_menu(); } } ui.separator(); ui.menu_button("Barcode", |ui| { for opt in barcode_insert_options() { if ui.button(&opt.label).clicked() { self.insert_snippet(&opt.snippet); ui.close_menu(); } } }); ui.menu_button("QR code", |ui| { for opt in qr_insert_options() { if ui.button(&opt.label).clicked() { self.insert_snippet(&opt.snippet); ui.close_menu(); } } }); ui.menu_button("Date / time", |ui| { for opt in date_time_insert_options() { if ui.button(&opt.label).clicked() { self.insert_snippet(&opt.snippet); ui.close_menu(); } } }); ui.menu_button("Parameters", |ui| { for opt in parameter_insert_options(&self.body) { if ui.button(&opt.label).clicked() { self.insert_snippet(&opt.snippet); ui.close_menu(); } } }); ui.separator(); if ui.button("@feed").clicked() { self.insert_snippet("@feed 3\n"); ui.close_menu(); } if ui.button("@cut").clicked() { self.insert_snippet("@cut\n"); ui.close_menu(); } }); }); ui.separator(); ui.horizontal(|ui| { ui.label("Page width (mm):"); let mut width = self.metadata.page_width_mm; if ui .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0)) .changed() { self.metadata.page_width_mm = width; self.dirty = true; } }); }); if let Some(err) = &self.parse_error { ui.colored_label(egui::Color32::RED, err); } if let Some(err) = &self.action_error { ui.colored_label(egui::Color32::RED, err); } }); egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { ui.horizontal(|ui| { ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design"); ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help"); ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings"); if let Ok(doc) = parse(&self.body) { if !dsl::document_ends_with_cut(&doc) { ui.colored_label( egui::Color32::RED, "Warning: No @cut directive at end of file.", ); } } }); }); }); match self.view_mode { ViewMode::Design => { egui::SidePanel::right("preview_panel") .resizable(main_enabled) .min_width(260.0) .default_width(380.0) .show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { ui.heading("Preview"); ui.horizontal(|ui| { ui.label(format!( "Page width: {:.0} mm", self.metadata.page_width_mm )); ui.separator(); ui.label("Zoom:"); ui.add( egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0) .logarithmic(true) .show_value(true), ); if ui.button("100%").clicked() { self.preview_zoom = 1.0; } }); ui.separator(); self.show_preview(ui, ctx); }); }); egui::CentralPanel::default().show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { ui.heading("Editor"); self.show_editor(ui); }); }); } ViewMode::Help => { egui::CentralPanel::default().show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { help_view::show_help(ui, HELP_MARKDOWN); }); }); } ViewMode::Settings => { egui::CentralPanel::default().show(ctx, |ui| { ui.add_enabled_ui(main_enabled, |ui| { self.show_settings(ui); }); }); } } if self.show_print_dialog { let mut open = true; egui::Window::new("Print") .collapsible(false) .resizable(true) .default_size([420.0, 520.0]) .open(&mut open) .show(ctx, |ui| { match self.print_dialog.show_ui(ui) { PrintDialogAction::Print => self.execute_print(), PrintDialogAction::None => {} } }); if !open { self.close_print_dialog(); } } ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title())); } } impl PosPrintApp { fn insert_snippet(&mut self, snippet: &str) { let before = self.body.clone(); let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet); self.body = body; self.editor_cursor = cursor; self.undo.record(before); self.dirty = true; self.view_mode = ViewMode::Design; } fn show_editor(&mut self, ui: &mut egui::Ui) { let before = self.body.clone(); let cursor_before = self.editor_cursor; // Autocomplete steals focus every frame; keep it off while the print dialog is open. let autocomplete_enabled = !self.show_print_dialog; let directive_ctx = autocomplete_enabled .then(|| at_directive_prefix(&self.body, cursor_before)) .flatten(); let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| { complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some() }); let mut tab_completion: Option<(usize, String)> = None; if autocomplete_active { if let Some((at_index, prefix)) = directive_ctx.clone() { ui.input_mut(|input| { if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() { tab_completion = Some((at_index, prefix)); input.consume_key(egui::Modifiers::NONE, egui::Key::Tab); } }); } } let font_id = egui::TextStyle::Monospace.resolve(ui.style()); let row_height = ui.fonts(|f| f.row_height(&font_id)).max(1.0); let rows = ((ui.available_height() / row_height).floor() as usize).clamp(8, 500); let output = egui::TextEdit::multiline(&mut self.body) .id_salt("main_editor") .desired_width(f32::INFINITY) .desired_rows(rows) .font(egui::TextStyle::Monospace) .lock_focus(autocomplete_active) .show(ui); // Do not call request_focus every frame — that fights paste/IME and can freeze the UI. // lock_focus(true) above is enough to keep Tab-completion working. self.editor_cursor = output .cursor_range .as_ref() .map(|r| char_index_to_byte(&self.body, r.primary.ccursor.index)) .or_else(|| { output.state.cursor.char_range().map(|r| { char_index_to_byte(&self.body, r.primary.index) }) }) .unwrap_or(self.body.len()); if let Some((at_index, prefix)) = tab_completion { if let Some(completed) = complete_directive(&prefix) { let undo_before = self.body.clone(); // Use the pre-TextEdit cursor: that is the end of the typed prefix. self.editor_cursor = apply_directive_completion( &mut self.body, at_index, cursor_before, completed, ); // Sync egui TextEdit caret to the end of the completed directive. let char_idx = byte_index_to_char(&self.body, self.editor_cursor); let mut state = output.state; state.cursor.set_char_range(Some(egui::text::CCursorRange::one( egui::text::CCursor::new(char_idx), ))); state.store(ui.ctx(), output.response.id); self.undo.record(undo_before); self.dirty = true; } } else if output.response.changed() { self.undo.record(before); self.dirty = true; } if autocomplete_enabled { if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) { if let Some(suffix) = directive_ghost_suffix(&prefix) { if let Some(cursor_range) = &output.cursor_range { let font_id = egui::TextStyle::Monospace.resolve(ui.style()); let pos = output.galley.pos_from_cursor(&cursor_range.primary); let ghost_pos = output.galley_pos + pos.min.to_vec2(); let ghost_color = ui.visuals().weak_text_color(); ui.painter().text( ghost_pos, egui::Align2::LEFT_TOP, suffix, font_id, ghost_color, ); } } } } } fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { let base_dir = self.file_path.as_ref().and_then(|p| p.parent()); // Prefer live dialog inputs while the print dialog is open. let params = if self.show_print_dialog { &self.print_dialog.param_inputs } else { &self.print_dialog.last_params }; show_preview_panel( ui, ctx, &self.body, &self.metadata, base_dir, params, self.preview_zoom, "design_preview_", ); } } fn default_template() -> String { String::new() } #[cfg(test)] mod tests { use super::*; #[test] fn default_template_is_empty() { let app = PosPrintApp::default(); assert!(app.body.is_empty()); assert!(parse(&app.body).is_ok()); } #[test] fn title_shows_asterisk_before_name_when_dirty() { let mut app = PosPrintApp::default(); app.dirty = true; assert!(app.title().starts_with("* ")); } }