BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

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