BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

cfe7435b History
app.rs 24.3 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,
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 self.handle_shortcuts(ctx);
245 self.print_dialog.poll_printer_discovery(ctx);
246
247 egui::TopBottomPanel::top("menu").show(ctx, |ui| {
248 ui.horizontal_wrapped(|ui| {
249 if ui.button("New").clicked() {
250 self.new_document();
251 }
252 if ui.button("Open").clicked() {
253 self.open_file_dialog();
254 }
255 if ui.button("Save").clicked() {
256 self.save();
257 }
258 if ui.button("Save As").clicked() {
259 self.save_as();
260 }
261 if ui.button("Print").clicked() {
262 self.open_print_dialog();
263 }
264
265 ui.menu_button("Insert", |ui| {
266 for opt in image_insert_options() {
267 if ui.button(format!("Image — {}", opt.label)).clicked() {
268 self.insert_snippet(&opt.snippet);
269 ui.close_menu();
270 }
271 }
272 ui.separator();
273 ui.menu_button("Barcode", |ui| {
274 for opt in barcode_insert_options() {
275 if ui.button(&opt.label).clicked() {
276 self.insert_snippet(&opt.snippet);
277 ui.close_menu();
278 }
279 }
280 });
281 ui.menu_button("QR code", |ui| {
282 for opt in qr_insert_options() {
283 if ui.button(&opt.label).clicked() {
284 self.insert_snippet(&opt.snippet);
285 ui.close_menu();
286 }
287 }
288 });
289 ui.menu_button("Date / time", |ui| {
290 for opt in date_time_insert_options() {
291 if ui.button(&opt.label).clicked() {
292 self.insert_snippet(&opt.snippet);
293 ui.close_menu();
294 }
295 }
296 });
297 ui.menu_button("Parameters", |ui| {
298 for opt in parameter_insert_options(&self.body) {
299 if ui.button(&opt.label).clicked() {
300 self.insert_snippet(&opt.snippet);
301 ui.close_menu();
302 }
303 }
304 });
305 ui.separator();
306 if ui.button("@feed").clicked() {
307 self.insert_snippet("@feed 3\n");
308 ui.close_menu();
309 }
310 if ui.button("@cut").clicked() {
311 self.insert_snippet("@cut\n");
312 ui.close_menu();
313 }
314 });
315 });
316
317 ui.separator();
318 ui.horizontal(|ui| {
319 ui.label("Page width (mm):");
320 let mut width = self.metadata.page_width_mm;
321 if ui
322 .add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
323 .changed()
324 {
325 self.metadata.page_width_mm = width;
326 self.dirty = true;
327 }
328 });
329
330 if let Some(err) = &self.parse_error {
331 ui.colored_label(egui::Color32::RED, err);
332 }
333 if let Some(err) = &self.action_error {
334 ui.colored_label(egui::Color32::RED, err);
335 }
336 });
337
338 egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
339 ui.horizontal(|ui| {
340 ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
341 ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
342 if let Ok(doc) = parse(&self.body) {
343 if !dsl::document_ends_with_cut(&doc) {
344 ui.colored_label(
345 egui::Color32::RED,
346 "Warning: No @cut directive at end of file.",
347 );
348 }
349 }
350 });
351 });
352
353 match self.view_mode {
354 ViewMode::Design => {
355 egui::SidePanel::right("preview_panel")
356 .resizable(true)
357 .min_width(260.0)
358 .default_width(380.0)
359 .show(ctx, |ui| {
360 ui.heading("Preview");
361 ui.horizontal(|ui| {
362 ui.label(format!(
363 "Page width: {:.0} mm",
364 self.metadata.page_width_mm
365 ));
366 ui.separator();
367 ui.label("Zoom:");
368 ui.add(
369 egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0)
370 .logarithmic(true)
371 .show_value(true),
372 );
373 if ui.button("100%").clicked() {
374 self.preview_zoom = 1.0;
375 }
376 });
377 ui.separator();
378 self.show_preview(ui, ctx);
379 });
380
381 egui::CentralPanel::default().show(ctx, |ui| {
382 ui.heading("Editor");
383 self.show_editor(ui);
384 });
385 }
386 ViewMode::Help => {
387 egui::CentralPanel::default().show(ctx, |ui| {
388 help_view::show_help(ui, HELP_MARKDOWN);
389 });
390 }
391 }
392
393 if self.show_print_dialog {
394 let mut open = true;
395 egui::Window::new("Print")
396 .collapsible(false)
397 .resizable(true)
398 .open(&mut open)
399 .show(ctx, |ui| {
400 match self.print_dialog.show_ui(ui, "Cancel") {
401 PrintDialogAction::Cancel => self.close_print_dialog(),
402 PrintDialogAction::Print => self.execute_print(),
403 PrintDialogAction::None => {}
404 }
405 });
406 if !open {
407 self.apply_print_dialog_params_to_preview();
408 }
409 self.show_print_dialog = open;
410 }
411
412 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
413 }
414}
415
416impl PosPrintApp {
417 fn insert_snippet(&mut self, snippet: &str) {
418 let before = self.body.clone();
419 let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
420 self.body = body;
421 self.editor_cursor = cursor;
422 self.undo.record(before);
423 self.dirty = true;
424 self.view_mode = ViewMode::Design;
425 }
426
427 fn show_editor(&mut self, ui: &mut egui::Ui) {
428 let before = self.body.clone();
429 let cursor_before = self.editor_cursor;
430
431 let directive_ctx = at_directive_prefix(&self.body, cursor_before);
432 let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
433 complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
434 });
435
436 let mut tab_completion: Option<(usize, String)> = None;
437 if autocomplete_active {
438 if let Some((at_index, prefix)) = directive_ctx.clone() {
439 ui.input_mut(|input| {
440 if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
441 tab_completion = Some((at_index, prefix));
442 input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
443 }
444 });
445 }
446 }
447
448 let output = egui::TextEdit::multiline(&mut self.body)
449 .id_salt("main_editor")
450 .desired_width(f32::INFINITY)
451 .desired_rows(30)
452 .font(egui::TextStyle::Monospace)
453 .lock_focus(true)
454 .show(ui);
455
456 if autocomplete_active {
457 output.response.request_focus();
458 }
459
460 self.editor_cursor = output
461 .cursor_range
462 .as_ref()
463 .map(|r| r.primary.ccursor.index)
464 .or_else(|| {
465 output
466 .state
467 .cursor
468 .char_range()
469 .map(|r| r.primary.index)
470 })
471 .unwrap_or(self.body.len());
472
473 if let Some((at_index, prefix)) = tab_completion {
474 if let Some(completed) = complete_directive(&prefix) {
475 let undo_before = self.body.clone();
476 self.editor_cursor =
477 apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
478 self.undo.record(undo_before);
479 self.dirty = true;
480 }
481 } else if output.response.changed() {
482 self.undo.record(before);
483 self.dirty = true;
484 }
485
486 if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
487 if let Some(suffix) = directive_ghost_suffix(&prefix) {
488 if let Some(cursor_range) = &output.cursor_range {
489 let font_id = egui::TextStyle::Monospace.resolve(ui.style());
490 let pos = output.galley.pos_from_cursor(&cursor_range.primary);
491 let ghost_pos = output.galley_pos + pos.min.to_vec2();
492 let ghost_color = ui.visuals().weak_text_color();
493 ui.painter().text(
494 ghost_pos,
495 egui::Align2::LEFT_TOP,
496 suffix,
497 font_id,
498 ghost_color,
499 );
500 }
501 }
502 }
503 }
504
505 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
506 let Ok(doc) = parse(&self.body) else {
507 ui.label("Fix parse errors to preview.");
508 return;
509 };
510
511 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
512 let model = render_preview(
513 &doc,
514 &self.metadata,
515 base_dir,
516 &self.print_dialog.last_params,
517 );
518 let visual_scale = preview_visual_scale(self.preview_zoom);
519 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
520 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
521 let line_spacing = preview_line_spacing_px(self.preview_zoom);
522 // No horizontal padding: wrap columns must match the full paper width.
523 let pad_y = 4.0 * visual_scale;
524
525 egui::ScrollArea::both()
526 .auto_shrink([false; 2])
527 .show(ui, |ui| {
528 egui::Frame::canvas(ui.style()).show(ui, |ui| {
529 let mut total_height = pad_y * 2.0;
530 for line in &model.lines {
531 total_height +=
532 preview_line_height_estimate(line, &self.metadata, self.preview_zoom);
533 }
534 total_height = total_height.max(100.0);
535
536 let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
537 let painter = ui.painter_at(rect);
538 painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
539 painter.rect_stroke(
540 rect,
541 4.0,
542 egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
543 egui::StrokeKind::Inside,
544 );
545
546 let mut y = rect.min.y + pad_y;
547 let inner_width = content_width;
548
549 for (idx, line) in model.lines.iter().enumerate() {
550 match line {
551 PreviewLine::Text {
552 content,
553 align,
554 style,
555 } => {
556 let font_id = preview_text_font(*style, char_width);
557 let galley = painter.layout_no_wrap(
558 content.clone(),
559 font_id,
560 egui::Color32::BLACK,
561 );
562 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
563 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
564 y += preview_text_advance_px(*style, self.preview_zoom);
565 }
566 PreviewLine::Rule => {
567 painter.line_segment(
568 [
569 egui::pos2(rect.min.x, y),
570 egui::pos2(rect.max.x, y),
571 ],
572 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
573 );
574 y += preview_line_spacing_px(self.preview_zoom);
575 }
576 PreviewLine::Graphic { image, align } => {
577 let tex = gray_to_texture(
578 ctx,
579 &format!("preview_graphic_{idx}"),
580 image,
581 );
582 let size = egui::vec2(
583 tex.size()[0] as f32 * visual_scale,
584 tex.size()[1] as f32 * visual_scale,
585 );
586 let x = align_x(*align, rect.min.x, inner_width, size.x);
587 painter.image(
588 tex.id(),
589 egui::Rect::from_min_size(egui::pos2(x, y), size),
590 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
591 egui::Color32::WHITE,
592 );
593 y += size.y;
594 }
595 PreviewLine::Error { message, align } => {
596 let galley = painter.layout(
597 message.clone(),
598 egui::FontId::proportional(12.0 * visual_scale),
599 egui::Color32::RED,
600 inner_width,
601 );
602 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
603 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
604 y += preview_line_spacing_px(self.preview_zoom);
605 }
606 PreviewLine::Spacer(n) => {
607 y += line_spacing * (*n as f32);
608 }
609 }
610 }
611 });
612 });
613 }
614}
615
616fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
617 let normal = preview_font_size_px(char_width);
618 match style {
619 // GS ! 0x11 — double width and double height
620 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
621 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
622 }
623}
624
625fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
626 match align {
627 dsl::Align::Left => left,
628 dsl::Align::Center => left + (inner_width - item_width) / 2.0,
629 dsl::Align::Right => left + inner_width - item_width,
630 }
631}
632
633fn gray_to_texture(
634 ctx: &egui::Context,
635 id: &str,
636 image: &image::GrayImage,
637) -> egui::TextureHandle {
638 let (w, h) = image.dimensions();
639 let pixels: Vec<egui::Color32> = image
640 .pixels()
641 .map(|p| egui::Color32::from_gray(p.0[0]))
642 .collect();
643 let color_image = egui::ColorImage {
644 size: [w as usize, h as usize],
645 pixels,
646 };
647 ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
648}
649
650fn default_template() -> String {
651 String::new()
652}
653
654#[cfg(test)]
655mod tests {
656 use super::*;
657
658 #[test]
659 fn default_template_is_empty() {
660 let app = PosPrintApp::default();
661 assert!(app.body.is_empty());
662 assert!(parse(&app.body).is_ok());
663 }
664
665 #[test]
666 fn title_shows_asterisk_before_name_when_dirty() {
667 let mut app = PosPrintApp::default();
668 app.dirty = true;
669 assert!(app.title().starts_with("* "));
670 }
671}