| 1 | use std::path::PathBuf;
|
| 2 |
|
| 3 | use eframe::egui;
|
| 4 |
|
| 5 | use posprint::dsl::{self, parse};
|
| 6 | use 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 | };
|
| 11 | use posprint::help_view;
|
| 12 | use posprint::io::{PosFile, PosMetadata};
|
| 13 | use posprint::undo::TextUndo;
|
| 14 | use posprint::HELP_MARKDOWN;
|
| 15 |
|
| 16 | use crate::preview_panel::show_preview_panel;
|
| 17 | use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
|
| 18 |
|
| 19 | #[derive(Clone, Copy, PartialEq, Eq)]
|
| 20 | enum ViewMode {
|
| 21 | Design,
|
| 22 | Help,
|
| 23 | }
|
| 24 |
|
| 25 | pub 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 |
|
| 40 | impl 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 |
|
| 59 | impl 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 |
|
| 237 | impl 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 | .open(&mut open)
|
| 409 | .show(ctx, |ui| {
|
| 410 | match self.print_dialog.show_ui(ui, "Cancel") {
|
| 411 | PrintDialogAction::Cancel => self.close_print_dialog(),
|
| 412 | PrintDialogAction::Print => self.execute_print(),
|
| 413 | PrintDialogAction::None => {}
|
| 414 | }
|
| 415 | });
|
| 416 | if !open {
|
| 417 | self.apply_print_dialog_params_to_preview();
|
| 418 | }
|
| 419 | self.show_print_dialog = open;
|
| 420 | }
|
| 421 |
|
| 422 | ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
|
| 423 | }
|
| 424 | }
|
| 425 |
|
| 426 | impl PosPrintApp {
|
| 427 | fn insert_snippet(&mut self, snippet: &str) {
|
| 428 | let before = self.body.clone();
|
| 429 | let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
|
| 430 | self.body = body;
|
| 431 | self.editor_cursor = cursor;
|
| 432 | self.undo.record(before);
|
| 433 | self.dirty = true;
|
| 434 | self.view_mode = ViewMode::Design;
|
| 435 | }
|
| 436 |
|
| 437 | fn show_editor(&mut self, ui: &mut egui::Ui) {
|
| 438 | let before = self.body.clone();
|
| 439 | let cursor_before = self.editor_cursor;
|
| 440 |
|
| 441 | // Autocomplete steals focus every frame; keep it off while the print dialog is open.
|
| 442 | let autocomplete_enabled = !self.show_print_dialog;
|
| 443 | let directive_ctx = autocomplete_enabled
|
| 444 | .then(|| at_directive_prefix(&self.body, cursor_before))
|
| 445 | .flatten();
|
| 446 | let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
|
| 447 | complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
|
| 448 | });
|
| 449 |
|
| 450 | let mut tab_completion: Option<(usize, String)> = None;
|
| 451 | if autocomplete_active {
|
| 452 | if let Some((at_index, prefix)) = directive_ctx.clone() {
|
| 453 | ui.input_mut(|input| {
|
| 454 | if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
|
| 455 | tab_completion = Some((at_index, prefix));
|
| 456 | input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
|
| 457 | }
|
| 458 | });
|
| 459 | }
|
| 460 | }
|
| 461 |
|
| 462 | let font_id = egui::TextStyle::Monospace.resolve(ui.style());
|
| 463 | let row_height = ui.fonts(|f| f.row_height(&font_id)).max(1.0);
|
| 464 | let rows = ((ui.available_height() / row_height).floor() as usize).clamp(8, 500);
|
| 465 |
|
| 466 | let output = egui::TextEdit::multiline(&mut self.body)
|
| 467 | .id_salt("main_editor")
|
| 468 | .desired_width(f32::INFINITY)
|
| 469 | .desired_rows(rows)
|
| 470 | .font(egui::TextStyle::Monospace)
|
| 471 | .lock_focus(autocomplete_active)
|
| 472 | .show(ui);
|
| 473 |
|
| 474 | // Do not call request_focus every frame — that fights paste/IME and can freeze the UI.
|
| 475 | // lock_focus(true) above is enough to keep Tab-completion working.
|
| 476 |
|
| 477 | self.editor_cursor = output
|
| 478 | .cursor_range
|
| 479 | .as_ref()
|
| 480 | .map(|r| char_index_to_byte(&self.body, r.primary.ccursor.index))
|
| 481 | .or_else(|| {
|
| 482 | output.state.cursor.char_range().map(|r| {
|
| 483 | char_index_to_byte(&self.body, r.primary.index)
|
| 484 | })
|
| 485 | })
|
| 486 | .unwrap_or(self.body.len());
|
| 487 |
|
| 488 | if let Some((at_index, prefix)) = tab_completion {
|
| 489 | if let Some(completed) = complete_directive(&prefix) {
|
| 490 | let undo_before = self.body.clone();
|
| 491 | self.editor_cursor =
|
| 492 | apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
|
| 493 | self.undo.record(undo_before);
|
| 494 | self.dirty = true;
|
| 495 | }
|
| 496 | } else if output.response.changed() {
|
| 497 | self.undo.record(before);
|
| 498 | self.dirty = true;
|
| 499 | }
|
| 500 |
|
| 501 | if autocomplete_enabled {
|
| 502 | if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
|
| 503 | if let Some(suffix) = directive_ghost_suffix(&prefix) {
|
| 504 | if let Some(cursor_range) = &output.cursor_range {
|
| 505 | let font_id = egui::TextStyle::Monospace.resolve(ui.style());
|
| 506 | let pos = output.galley.pos_from_cursor(&cursor_range.primary);
|
| 507 | let ghost_pos = output.galley_pos + pos.min.to_vec2();
|
| 508 | let ghost_color = ui.visuals().weak_text_color();
|
| 509 | ui.painter().text(
|
| 510 | ghost_pos,
|
| 511 | egui::Align2::LEFT_TOP,
|
| 512 | suffix,
|
| 513 | font_id,
|
| 514 | ghost_color,
|
| 515 | );
|
| 516 | }
|
| 517 | }
|
| 518 | }
|
| 519 | }
|
| 520 | }
|
| 521 |
|
| 522 | fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
| 523 | let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
|
| 524 | // Prefer live dialog inputs while the print dialog is open.
|
| 525 | let params = if self.show_print_dialog {
|
| 526 | &self.print_dialog.param_inputs
|
| 527 | } else {
|
| 528 | &self.print_dialog.last_params
|
| 529 | };
|
| 530 | show_preview_panel(
|
| 531 | ui,
|
| 532 | ctx,
|
| 533 | &self.body,
|
| 534 | &self.metadata,
|
| 535 | base_dir,
|
| 536 | params,
|
| 537 | self.preview_zoom,
|
| 538 | "design_preview_",
|
| 539 | );
|
| 540 | }
|
| 541 | }
|
| 542 |
|
| 543 | fn default_template() -> String {
|
| 544 | String::new()
|
| 545 | }
|
| 546 |
|
| 547 | #[cfg(test)]
|
| 548 | mod tests {
|
| 549 | use super::*;
|
| 550 |
|
| 551 | #[test]
|
| 552 | fn default_template_is_empty() {
|
| 553 | let app = PosPrintApp::default();
|
| 554 | assert!(app.body.is_empty());
|
| 555 | assert!(parse(&app.body).is_ok());
|
| 556 | }
|
| 557 |
|
| 558 | #[test]
|
| 559 | fn title_shows_asterisk_before_name_when_dirty() {
|
| 560 | let mut app = PosPrintApp::default();
|
| 561 | app.dirty = true;
|
| 562 | assert!(app.title().starts_with("* "));
|
| 563 | }
|
| 564 | }
|