BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

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