BlueGit

timfa posprint

Files

posprint / src / app.rs

app.rs

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