BlueGit

timfa posprint

Files

posprint / src / print_only_app.rs

print_only_app.rs

print_only_app.rs 9.8 KiB Download Raw
1//! Print dialog + live preview, then exit.
2
3use std::path::PathBuf;
4
5use eframe::egui;
6
7use posprint::config::AppConfig;
8use posprint::io::{PosFile, PosMetadata};
9use posprint::protocol_url::PosprintLaunch;
10
11use crate::preview_panel::show_preview_panel;
12use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
13
14pub struct PrintOnlyApp {
15 body: String,
16 metadata: PosMetadata,
17 /// When set, used as title and as `@image` base directory parent.
18 file_path: Option<PathBuf>,
19 title_override: Option<String>,
20 dialog: PrintDialog,
21 preview_zoom: f32,
22 fatal_error: Option<String>,
23 exit_requested: bool,
24 /// Auto-print once printers are ready (after trust if needed).
25 auto_print: bool,
26 /// Pending first-time trust confirmation for this hostname.
27 pending_trust: Option<String>,
28 auto_print_attempted: bool,
29}
30
31impl PrintOnlyApp {
32 pub fn new(path: PathBuf) -> Self {
33 let mut app = Self::blank();
34 app.file_path = Some(path.clone());
35
36 match PosFile::load_from_path(&path) {
37 Ok(file) => {
38 app.body = file.body;
39 app.metadata = file.metadata;
40 if let Err(e) = app.dialog.prepare(&app.body) {
41 app.fatal_error = Some(e);
42 }
43 }
44 Err(e) => app.fatal_error = Some(format!("Could not open file: {e:?}")),
45 }
46
47 app
48 }
49
50 pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
51 let mut app = Self::blank();
52 app.body = file.body;
53 app.metadata = file.metadata;
54 app.title_override = Some(source_label.into());
55 if let Err(e) = app.dialog.prepare(&app.body) {
56 app.fatal_error = Some(e);
57 }
58 app
59 }
60
61 pub fn from_launch(launch: PosprintLaunch) -> Self {
62 let label = launch
63 .file
64 .metadata
65 .title
66 .clone()
67 .unwrap_or_else(|| "posprint://".into());
68 let mut app = Self::from_pos_file(launch.file, label);
69 if !launch.noconfirm {
70 return app;
71 }
72
73 match launch.origin.as_deref() {
74 None => {
75 app.fatal_error = Some(
76 "noconfirm=1 requires origin=<hostname> so posprint can ask whether to trust that site."
77 .into(),
78 );
79 }
80 Some(origin) => {
81 let cfg = AppConfig::load();
82 if cfg.is_trusted(origin) {
83 app.auto_print = true;
84 } else {
85 app.pending_trust = Some(origin.to_string());
86 }
87 }
88 }
89 app
90 }
91
92 pub fn from_error(message: impl Into<String>) -> Self {
93 let mut app = Self::blank();
94 app.title_override = Some("posprint://".into());
95 app.fatal_error = Some(message.into());
96 app
97 }
98
99 fn blank() -> Self {
100 Self {
101 body: String::new(),
102 metadata: PosMetadata::default(),
103 file_path: None,
104 title_override: None,
105 dialog: PrintDialog::default(),
106 preview_zoom: 1.0,
107 fatal_error: None,
108 exit_requested: false,
109 auto_print: false,
110 pending_trust: None,
111 auto_print_attempted: false,
112 }
113 }
114
115 fn title(&self) -> String {
116 if let Some(label) = &self.title_override {
117 return format!("Print — {label}");
118 }
119 let name = self
120 .file_path
121 .as_ref()
122 .and_then(|p| p.file_name())
123 .map(|s| s.to_string_lossy().to_string())
124 .unwrap_or_else(|| "Print".into());
125 format!("Print — {name}")
126 }
127
128 fn request_exit(&mut self) {
129 self.exit_requested = true;
130 }
131
132 fn try_auto_print(&mut self, ctx: &egui::Context) {
133 if !self.auto_print || self.auto_print_attempted || self.fatal_error.is_some() {
134 return;
135 }
136 if self.dialog.printers_loading {
137 ctx.request_repaint();
138 return;
139 }
140 self.auto_print_attempted = true;
141 if self
142 .dialog
143 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
144 == PrintExecuteResult::Printed
145 {
146 self.request_exit();
147 }
148 // On failure, keep the dialog open so the user can fix params/printer.
149 }
150}
151
152impl eframe::App for PrintOnlyApp {
153 fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
154 if self.exit_requested {
155 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
156 return;
157 }
158
159 self.dialog.poll_printer_discovery(ctx);
160 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
161
162 if let Some(origin) = self.pending_trust.clone() {
163 egui::CentralPanel::default().show(ctx, |ui| {
164 ui.heading("Trust this site?");
165 ui.separator();
166 ui.label(format!(
167 "A page from “{origin}” wants to print without confirmation (noconfirm)."
168 ));
169 ui.label(
170 "If you trust this site, posprint will allow future noconfirm prints from this domain without asking again.",
171 );
172 ui.add_space(12.0);
173 ui.horizontal(|ui| {
174 if ui.button("Trust and print").clicked() {
175 let mut cfg = AppConfig::load();
176 cfg.trust_origin(&origin);
177 if let Err(e) = cfg.save() {
178 self.fatal_error = Some(format!("Could not save trust setting: {e}"));
179 self.pending_trust = None;
180 } else {
181 self.pending_trust = None;
182 self.auto_print = true;
183 }
184 }
185 if ui.button("Cancel").clicked() {
186 self.request_exit();
187 }
188 });
189 ui.add_space(8.0);
190 ui.label("You can revoke trust later under Settings in the designer.");
191 });
192 return;
193 }
194
195 if let Some(err) = self.fatal_error.clone() {
196 egui::CentralPanel::default().show(ctx, |ui| {
197 ui.heading("Print");
198 ui.separator();
199 ui.colored_label(egui::Color32::RED, err);
200 if ui.button("Close").clicked() {
201 self.request_exit();
202 }
203 });
204 return;
205 }
206
207 self.try_auto_print(ctx);
208
209 let mut action = PrintDialogAction::None;
210
211 egui::CentralPanel::default().show(ctx, |ui| {
212 let available = ui.available_size();
213 // Preview left (~55%), print controls right.
214 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
215
216 ui.horizontal(|ui| {
217 ui.allocate_ui_with_layout(
218 egui::vec2(preview_width, available.y),
219 egui::Layout::top_down(egui::Align::Min),
220 |ui| {
221 ui.horizontal(|ui| {
222 ui.heading("Preview");
223 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
224 egui::ComboBox::from_id_salt("print_only_zoom")
225 .selected_text(format!("{:.0}%", self.preview_zoom * 100.0))
226 .show_ui(ui, |ui| {
227 for pct in [50, 75, 100, 125, 150, 200] {
228 let z = pct as f32 / 100.0;
229 ui.selectable_value(
230 &mut self.preview_zoom,
231 z,
232 format!("{pct}%"),
233 );
234 }
235 });
236 });
237 });
238 ui.separator();
239 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
240 show_preview_panel(
241 ui,
242 ctx,
243 &self.body,
244 &self.metadata,
245 base_dir,
246 &self.dialog.param_inputs,
247 self.preview_zoom,
248 "print_only_preview_",
249 );
250 },
251 );
252
253 ui.separator();
254
255 ui.allocate_ui_with_layout(
256 egui::vec2(ui.available_width(), available.y),
257 egui::Layout::top_down(egui::Align::Min),
258 |ui| {
259 // No outer ScrollArea: nested scroll steals wheel events from the printer list.
260 action = self.dialog.show_ui(ui);
261 },
262 );
263 });
264 });
265
266 match action {
267 PrintDialogAction::Print => {
268 if self
269 .dialog
270 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
271 == PrintExecuteResult::Printed
272 {
273 self.request_exit();
274 }
275 }
276 PrintDialogAction::None => {}
277 }
278 }
279}