use std::path::PathBuf; use eframe::egui; use posprint::dsl::{self, parse}; use posprint::editor_assist::{ apply_directive_completion, at_directive_prefix, barcode_insert_options, 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::preview::{ preview_char_width_px, preview_content_width_px, preview_font_size_px, preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px, preview_visual_scale, render_preview, PreviewLine, TextStyle, }; use posprint::undo::TextUndo; use posprint::HELP_MARKDOWN; use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult}; #[derive(Clone, Copy, PartialEq, Eq)] enum ViewMode { Design, Help, } 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, } impl Default for PosPrintApp { fn default() -> Self { Self { view_mode: ViewMode::Design, body: default_template(), metadata: PosMetadata::default(), 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, } } } 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 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(); self.handle_shortcuts(ctx); self.print_dialog.poll_printer_discovery(ctx); egui::TopBottomPanel::top("menu").show(ctx, |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.horizontal(|ui| { ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design"); ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help"); 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(true) .min_width(260.0) .default_width(380.0) .show(ctx, |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.heading("Editor"); self.show_editor(ui); }); } ViewMode::Help => { egui::CentralPanel::default().show(ctx, |ui| { help_view::show_help(ui, HELP_MARKDOWN); }); } } if self.show_print_dialog { let mut open = true; egui::Window::new("Print") .collapsible(false) .resizable(true) .open(&mut open) .show(ctx, |ui| { match self.print_dialog.show_ui(ui, "Cancel") { PrintDialogAction::Cancel => self.close_print_dialog(), PrintDialogAction::Print => self.execute_print(), PrintDialogAction::None => {} } }); if !open { self.apply_print_dialog_params_to_preview(); } self.show_print_dialog = open; } 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; let directive_ctx = at_directive_prefix(&self.body, cursor_before); 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 output = egui::TextEdit::multiline(&mut self.body) .id_salt("main_editor") .desired_width(f32::INFINITY) .desired_rows(30) .font(egui::TextStyle::Monospace) .lock_focus(true) .show(ui); if autocomplete_active { output.response.request_focus(); } self.editor_cursor = output .cursor_range .as_ref() .map(|r| r.primary.ccursor.index) .or_else(|| { output .state .cursor .char_range() .map(|r| 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(); self.editor_cursor = apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed); self.undo.record(undo_before); self.dirty = true; } } else if output.response.changed() { self.undo.record(before); self.dirty = true; } 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 Ok(doc) = parse(&self.body) else { ui.label("Fix parse errors to preview."); return; }; let base_dir = self.file_path.as_ref().and_then(|p| p.parent()); let model = render_preview( &doc, &self.metadata, base_dir, &self.print_dialog.last_params, ); let visual_scale = preview_visual_scale(self.preview_zoom); let content_width = preview_content_width_px(&self.metadata) * visual_scale; let char_width = preview_char_width_px(&self.metadata, self.preview_zoom); let line_spacing = preview_line_spacing_px(self.preview_zoom); // No horizontal padding: wrap columns must match the full paper width. let pad_y = 4.0 * visual_scale; egui::ScrollArea::both() .auto_shrink([false; 2]) .show(ui, |ui| { egui::Frame::canvas(ui.style()).show(ui, |ui| { let mut total_height = pad_y * 2.0; for line in &model.lines { total_height += preview_line_height_estimate(line, &self.metadata, self.preview_zoom); } total_height = total_height.max(100.0); let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height)); let painter = ui.painter_at(rect); painter.rect_filled(rect, 4.0, egui::Color32::WHITE); painter.rect_stroke( rect, 4.0, egui::Stroke::new(1.0_f32, egui::Color32::GRAY), egui::StrokeKind::Inside, ); let mut y = rect.min.y + pad_y; let inner_width = content_width; for (idx, line) in model.lines.iter().enumerate() { match line { PreviewLine::Text { content, align, style, } => { let font_id = preview_text_font(*style, char_width); let galley = painter.layout_no_wrap( content.clone(), font_id, egui::Color32::BLACK, ); let x = align_x(*align, rect.min.x, inner_width, galley.size().x); painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK); y += preview_text_advance_px(*style, self.preview_zoom); } PreviewLine::Rule => { painter.line_segment( [ egui::pos2(rect.min.x, y), egui::pos2(rect.max.x, y), ], egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY), ); y += preview_line_spacing_px(self.preview_zoom); } PreviewLine::Graphic { image, align } => { let tex = gray_to_texture( ctx, &format!("preview_graphic_{idx}"), image, ); let size = egui::vec2( tex.size()[0] as f32 * visual_scale, tex.size()[1] as f32 * visual_scale, ); let x = align_x(*align, rect.min.x, inner_width, size.x); painter.image( tex.id(), egui::Rect::from_min_size(egui::pos2(x, y), size), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE, ); y += size.y; } PreviewLine::Error { message, align } => { let galley = painter.layout( message.clone(), egui::FontId::proportional(12.0 * visual_scale), egui::Color32::RED, inner_width, ); let x = align_x(*align, rect.min.x, inner_width, galley.size().x); painter.galley(egui::pos2(x, y), galley, egui::Color32::RED); y += preview_line_spacing_px(self.preview_zoom); } PreviewLine::Spacer(n) => { y += line_spacing * (*n as f32); } } } }); }); } } fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId { let normal = preview_font_size_px(char_width); match style { // GS ! 0x11 — double width and double height TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0), TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal), } } fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 { match align { dsl::Align::Left => left, dsl::Align::Center => left + (inner_width - item_width) / 2.0, dsl::Align::Right => left + inner_width - item_width, } } fn gray_to_texture( ctx: &egui::Context, id: &str, image: &image::GrayImage, ) -> egui::TextureHandle { let (w, h) = image.dimensions(); let pixels: Vec = image .pixels() .map(|p| egui::Color32::from_gray(p.0[0])) .collect(); let color_image = egui::ColorImage { size: [w as usize, h as usize], pixels, }; ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST) } 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("* ")); } }