BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

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