Skip to main content

brep_app/panels/
bug_report.rs

1//! In-app **Submit Bug** report.
2//!
3//! A toolbar button opens this flow. It captures, WITHOUT the report dialog in
4//! the shot:
5//!   * a **screenshot** of the whole application (egui UI + the 3D model) as it
6//!     looked the instant the button was pressed,
7//!   * the current **model** (the `.nbrep` recipe), and
8//!   * a user **description** (+ an optional email), and
9//!   * the session's **diagnostics** — which renderer is actually in use and
10//!     what it is running on, appended to the description (see
11//!     `compose_description` for why they travel inside that field),
12//! then POSTs them to the public reports endpoint (`next.brep.io/api/report`).
13//! ONE code path runs on both native and wasm.
14//!
15//! ## Screenshot-before-dialog
16//! egui/eframe captures a screenshot of the FRAME (the composited surface, so it
17//! includes the 3D viewport, which is an `egui_wgpu` paint callback into egui's
18//! frame — see [`crate::viewport`]). We must not let the dialog appear in that
19//! frame, so the flow is a small state machine:
20//!   1. Button click → snapshot the model, send `ViewportCommand::Screenshot`,
21//!      enter `Phase::Capturing`. The dialog is NOT drawn while capturing.
22//!   2. A later frame delivers `Event::Screenshot`; we encode it to PNG, build a
23//!      preview thumbnail, and enter `Phase::Editing` — only NOW is the dialog
24//!      drawn, so the captured frame(s) never contain it.
25//!   3. Submit builds a small multipart body by hand (no extra deps) and fires
26//!      it through `net.rs`; the reply marshals back over an mpsc channel +
27//!      `request_repaint`, exactly like [`crate::panels::step_parts`].
28
29#[path = "bug_report_markup.rs"]
30mod markup;
31
32use crate::automation::hit_keys::HitKeyDoc;
33use crate::diagnostics::Diagnostics;
34use std::sync::mpsc::Receiver;
35
36use brep_render::engine_state::EngineState;
37use crate::icon_text::IconTextUi as _;
38use crate::ui_kit::Button;
39use eframe::egui;
40
41/// The public reports endpoint the button posts to (fronted
42/// by next.brep.io). Accepts the multipart fields
43/// `description`,`email`,`model`,`screenshot`.
44const REPORT_URL: &str = "https://next.brep.io/api/report";
45
46/// The feature name [`crate::offsite`]'s refusal sentence starts with.
47const FEATURE: &str = "Bug report";
48
49/// The server's cap on the `description` field, in CHARACTERS
50/// (`description.chars().take(MAX_DESC)` in the endpoint's own
51/// `routes/reports.rs`). It truncates the TAIL, and the diagnostics block is at
52/// the tail — so [`compose_description`] clamps the user's own text to leave
53/// room rather than letting a very long description silently cut the
54/// diagnostics off.
55const MAX_DESC: usize = 20_000;
56
57/// Frames to wait for the screenshot event before giving up and opening the
58/// dialog anyway (so a device that never delivers the capture can't hang the
59/// flow). ~1s at 60fps; the persistent offscreen 3D means the capture normally
60/// lands within a few frames.
61const CAPTURE_TIMEOUT_FRAMES: u32 = 60;
62
63/// The report and markup views occupy this fraction of the application window.
64const DIALOG_WIDTH_FRACTION: f32 = 0.90;
65const DIALOG_HEIGHT_FRACTION: f32 = 0.95;
66
67/// How many rows of text the description shows before it scrolls instead of
68/// growing.
69const DESCRIPTION_ROWS: usize = 12;
70
71/// The description field's own text margin (egui's default, named so the
72/// field's cap can count it).
73const DESCRIPTION_MARGIN: egui::Margin = egui::Margin::symmetric(4, 2);
74
75/// The gap above the button row, and between it and the status line.
76const FOOTER_GAP: f32 = 10.0;
77const STATUS_GAP: f32 = 6.0;
78
79/// Whether the description's Cut / Copy / Paste menu can reach the clipboard.
80/// Native eframe turns those requests into the same input as the keyboard
81/// shortcuts; the web runner does not handle them at all, and a browser only
82/// hands a page the clipboard inside its own copy/paste events — so there the
83/// menu says which keys to press instead.
84const MENU_REACHES_CLIPBOARD: bool = cfg!(not(target_arch = "wasm32"));
85
86/// Where the flow is between "button pressed" and "dialog closed".
87#[derive(Default, PartialEq)]
88enum Phase {
89    /// Nothing in progress.
90    #[default]
91    Idle,
92    /// Screenshot requested; dialog intentionally hidden so it isn't captured.
93    Capturing { frames: u32 },
94    /// Screenshot in hand; dialog open, collecting description + email.
95    Editing,
96    /// Dedicated screenshot editor, with the report form hidden.
97    Marking,
98    /// POST in flight.
99    Sending,
100}
101
102pub struct BugReportPanel {
103    phase: Phase,
104    /// The problem description (required to submit).
105    description: String,
106    /// Optional reporter email.
107    email: String,
108    /// A short status / error line under the buttons.
109    status: String,
110    /// PNG bytes of the pre-dialog screenshot (UI + 3D), including markup.
111    screenshot_png: Option<Vec<u8>>,
112    /// A preview texture of the screenshot shown in the dialog.
113    thumb: Option<egui::TextureHandle>,
114    /// Original capture and editable annotations.
115    markup: Option<markup::Markup>,
116    /// The model (`.nbrep`) snapshotted at button-press time.
117    model_json: String,
118    /// The session diagnostics block, taken from the app's ONE
119    /// [`Diagnostics`] at button-press time — the same text the Info window
120    /// shows, so a report can never describe a different machine from the one
121    /// the user was reading about.
122    diagnostics: String,
123    /// The in-flight POST reply channel (drained each frame).
124    /// `Ok` carries the new report's id when the server's reply names one.
125    response_rx: Option<Receiver<Result<Option<String>, String>>>,
126    /// A report just submitted: `(id, summary)`, for the app to remember
127    /// (`crate::report_followup`). Taken by [`Self::take_submitted`].
128    submitted: Option<(String, String)>,
129    /// Per-frame widget rects for the headed verifier (wasm only).
130    hits: std::collections::HashMap<String, egui::Rect>,
131    /// How the description's scroll area stood on the last drawn frame, for the
132    /// verifier: whether a long report overflows the field and where it is
133    /// scrolled to.
134    description_scroll: DescriptionScroll,
135}
136
137/// The description field's scroll extent, in points.
138#[derive(Clone, Copy, Default, Debug, PartialEq)]
139struct DescriptionScroll {
140    /// The height of the text.
141    content: f32,
142    /// The height of the field that shows it.
143    viewport: f32,
144    /// How far down the text is scrolled.
145    offset: f32,
146}
147
148impl BugReportPanel {
149    pub fn new() -> Self {
150        Self {
151            phase: Phase::Idle,
152            description: String::new(),
153            email: String::new(),
154            status: String::new(),
155            screenshot_png: None,
156            thumb: None,
157            markup: None,
158            model_json: String::new(),
159            diagnostics: String::new(),
160            response_rx: None,
161            submitted: None,
162            hits: std::collections::HashMap::new(),
163            description_scroll: DescriptionScroll::default(),
164        }
165    }
166
167    /// Toolbar entry point: snapshot the model + the session diagnostics,
168    /// request a screenshot of THIS frame (before the dialog exists), and begin
169    /// capturing. Ignored if a report flow is already in progress.
170    ///
171    /// `diagnostics` is the app's ONE instance — the report renders it here
172    /// rather than collecting anything of its own, which is what keeps the
173    /// submitted text and the Info window's rows the same rows.
174    pub fn request(&mut self, ctx: &egui::Context, state: &EngineState, diagnostics: &Diagnostics) {
175        if self.phase != Phase::Idle {
176            return;
177        }
178        self.description.clear();
179        self.email.clear();
180        self.status.clear();
181        self.screenshot_png = None;
182        self.thumb = None;
183        self.markup = None;
184        self.response_rx = None;
185        // The model can't change while the modal is open, but snapshot it now so
186        // the report reflects exactly the state the user was looking at.
187        self.model_json = state.history_request_json();
188        self.diagnostics = diagnostics.report_text();
189        ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::default()));
190        self.phase = Phase::Capturing { frames: 0 };
191        ctx.request_repaint();
192    }
193
194    /// [`Self::request`] from a dialog's Report problem button: the same flow,
195    /// with the description already naming the dialog and its error.
196    pub fn request_for_error(
197        &mut self,
198        ctx: &egui::Context,
199        state: &EngineState,
200        diagnostics: &Diagnostics,
201        dialog: &str,
202        error: &str,
203    ) {
204        if self.phase != Phase::Idle {
205            return;
206        }
207        self.request(ctx, state, diagnostics);
208        self.description = error_description(dialog, error);
209    }
210
211    /// Draw + drive the flow. Called once per frame at ctx level (like the file
212    /// dialog). Idempotent while `Phase::Idle`.
213    pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState) {
214        self.hits.clear();
215
216        self.poll_capture(ctx);
217        self.drain_response(state);
218
219        if !matches!(self.phase, Phase::Editing | Phase::Marking | Phase::Sending) {
220            return;
221        }
222
223        let sending = self.phase == Phase::Sending;
224        let mut submit = false;
225        let mut cancel = false;
226        let marking = self.phase == Phase::Marking;
227        let mut finish = false;
228        let window = ctx.content_rect();
229        let frame = crate::ui_kit::chrome_parts::dialog_frame(&crate::theme::current(ctx));
230        let content_size = egui::vec2(
231            window.width() * DIALOG_WIDTH_FRACTION,
232            window.height() * DIALOG_HEIGHT_FRACTION,
233        ) - frame.total_margin().sum();
234        let modal = egui::Modal::new(egui::Id::new("brep-bug-report"))
235            .frame(frame)
236            .show(ctx, |ui| {
237                ui.set_width(content_size.x);
238                let content_rect = egui::Rect::from_min_size(ui.min_rect().min, content_size);
239                if marking {
240                    let finish_btn = ui.add(Button::primary("Finish"));
241                    self.hit("markup:finish", &finish_btn);
242                    finish = finish_btn.clicked();
243                    ui.separator();
244                    let height =
245                        (content_size.y - ui.min_rect().height() - ui.spacing().item_spacing.y)
246                            .max(0.0);
247                    let budget = egui::Rect::from_min_size(
248                        ui.cursor().min,
249                        egui::vec2(content_size.x, height),
250                    );
251                    ui.scope_builder(egui::UiBuilder::new().max_rect(budget), |ui| {
252                        if let (Some(markup), Some(tex)) = (&mut self.markup, &self.thumb) {
253                            if let Some(image) = markup.show(ui, tex, &mut self.hits) {
254                                self.screenshot_png = encode_png(&image);
255                                self.thumb
256                                    .as_mut()
257                                    .unwrap()
258                                    .set(image, egui::TextureOptions::LINEAR);
259                            }
260                        }
261                    });
262                    ui.expand_to_include_rect(content_rect);
263                    return;
264                }
265                // `icon_label`, not `heading`: U+1F41E is a catalogued COLOUR icon, so
266                // this draws the real artwork inline with the title instead of the
267                // font's monochrome outline.
268                ui.icon_label(egui::RichText::new("\u{1F41E}  Submit a bug report").heading());
269                ui.add_space(4.0);
270                ui.label(
271                    "Describe what went wrong. Your current model and a screenshot of \
272                 the app (UI + 3D view) are attached automatically.",
273                );
274                ui.add_space(2.0);
275                ui.weak("Your report and its screenshot may be shown publicly on the bug list.");
276                ui.add_space(8.0);
277
278                // Keep the body at a fixed height within the proportional modal,
279                // leaving the footer visible even when the report body scrolls.
280                let chrome = ui.min_rect().height();
281                let body_height = (content_size.y - chrome - self.footer_height(ui)).max(0.0);
282                let budget = egui::Rect::from_min_size(
283                    ui.cursor().min,
284                    egui::vec2(ui.available_width(), body_height),
285                );
286                ui.scope_builder(egui::UiBuilder::new().max_rect(budget), |ui| {
287                    egui::ScrollArea::vertical()
288                        .id_salt("brep-bug-body")
289                        .min_scrolled_height(body_height)
290                        .max_height(body_height)
291                        .auto_shrink([false, false])
292                        .show(ui, |ui| self.body(ui));
293                });
294
295                ui.add_space(FOOTER_GAP);
296                ui.horizontal(|ui| {
297                    let can_submit = !self.description.trim().is_empty() && !sending;
298                    let label = if sending {
299                        "Sending\u{2026}"
300                    } else {
301                        "Submit report"
302                    };
303                    let submit_btn = ui.add(Button::primary(label).enabled(can_submit));
304                    self.hit("submit", &submit_btn);
305                    if submit_btn.clicked() {
306                        submit = true;
307                    }
308                    let cancel_btn = ui.add(Button::new("Cancel").enabled(!sending));
309                    self.hit("cancel", &cancel_btn);
310                    if cancel_btn.clicked() {
311                        cancel = true;
312                    }
313                });
314                // The status line's row is always there, empty or not, so a status
315                // appearing ("Submitting…") does not change the dialog's size either.
316                ui.add_space(STATUS_GAP);
317                ui.weak(if self.status.is_empty() {
318                    " "
319                } else {
320                    self.status.as_str()
321                });
322                ui.expand_to_include_rect(content_rect);
323            });
324
325        if marking {
326            if finish || modal.should_close() {
327                self.phase = Phase::Editing;
328            }
329        } else if submit {
330            self.send(ctx);
331        } else if cancel || (modal.should_close() && !sending) {
332            self.reset();
333        }
334    }
335
336    /// The height [`Self::show`] draws under the body: the gap, the button row
337    /// and the status line's row, which is always drawn. Worked out from the
338    /// style the footer is drawn with, so the body's budget is right on the
339    /// first frame.
340    fn footer_height(&self, ui: &egui::Ui) -> f32 {
341        let spacing = ui.spacing();
342        let buttons = spacing
343            .interact_size
344            .y
345            .max(ui.text_style_height(&egui::TextStyle::Button) + 2.0 * spacing.button_padding.y);
346        let status = STATUS_GAP
347            + ui.text_style_height(&egui::TextStyle::Body)
348            + 2.0 * spacing.item_spacing.y;
349        FOOTER_GAP + buttons + 2.0 * spacing.item_spacing.y + status
350    }
351
352    /// The dialog's scrolling body: the description, the email, the attached
353    /// screenshot and the diagnostics.
354    fn body(&mut self, ui: &mut egui::Ui) {
355        ui.label("What happened?");
356        self.description_field(ui);
357
358        ui.add_space(6.0);
359        ui.label("Email (optional)");
360        let email = ui.add(
361            egui::TextEdit::singleline(&mut self.email)
362                .desired_width(f32::INFINITY)
363                .hint_text("so we can follow up — optional"),
364        );
365        self.hit("field:email", &email);
366
367        ui.add_space(8.0);
368        if let Some(tex) = &self.thumb {
369            ui.label("Attached screenshot:");
370            ui.add_space(2.0);
371            if self.markup.is_some() {
372                let button = ui.add(Button::new("Mark up screenshot").enabled(self.phase != Phase::Sending));
373                self.hits
374                    .insert("markup:toggle".into(), button.interact_rect);
375                if button.clicked() {
376                    self.phase = Phase::Marking;
377                }
378            }
379            let size = tex.size_vec2();
380            let scale = (ui.available_width() / size.x).min(240.0 / size.y).min(1.0);
381            ui.add(egui::Image::new((tex.id(), size * scale)));
382        } else {
383            ui.weak("(screenshot unavailable — the model + description will still be sent)");
384        }
385
386        // What the report will carry about this machine, shown before it is
387        // sent rather than attached invisibly. Collapsed: it is for the
388        // triager, and the user has already read it in the Info window if
389        // they wanted to.
390        ui.add_space(8.0);
391        let diag = egui::CollapsingHeader::new("Diagnostics attached to this report")
392            .id_salt("brep-bug-diagnostics")
393            .show(ui, |ui| {
394                ui.add(
395                    egui::Label::new(egui::RichText::new(&self.diagnostics).monospace().small())
396                        .wrap(),
397                );
398            });
399        self.hits.insert(
400            "diagnostics".to_string(),
401            diag.header_response.interact_rect,
402        );
403    }
404
405    /// The description. It grows with its text up to [`DESCRIPTION_ROWS`] rows
406    /// and then scrolls inside its own bar, so a long report never grows the
407    /// dialog; the field follows the caret as the user types.
408    ///
409    /// A bare scroll area is enough here because the body it sits in was given
410    /// an explicit budget: the room it measures is that budget, not the size
411    /// the modal happened to have last frame.
412    fn description_field(&mut self, ui: &mut egui::Ui) {
413        let cap = DESCRIPTION_ROWS as f32 * ui.text_style_height(&egui::TextStyle::Body)
414            + DESCRIPTION_MARGIN.sum().y;
415        let scroll = egui::ScrollArea::vertical()
416            .id_salt("brep-bug-description")
417            .max_height(cap)
418            .auto_shrink([false, true])
419            .show(ui, |ui| {
420                ui.add(
421                    egui::TextEdit::multiline(&mut self.description)
422                        .margin(DESCRIPTION_MARGIN)
423                        .desired_rows(5)
424                        .desired_width(f32::INFINITY)
425                        .hint_text("Steps, what you expected, and what actually happened"),
426                )
427            });
428        self.description_scroll = DescriptionScroll {
429            content: scroll.content_size.y,
430            viewport: scroll.inner_rect.height(),
431            offset: scroll.state.offset.y,
432        };
433        let field = scroll.inner;
434        self.hit("field:description", &field);
435        field.context_menu(|ui| self.edit_menu(ui, &field));
436    }
437
438    /// The description's right-click menu: Cut, Copy and Paste. An egui text
439    /// field has no menu of its own, and right-click → Paste is how a lot of
440    /// people paste — on a Mac especially, where the reporter looked for it.
441    ///
442    /// Each entry asks the platform for exactly what its keyboard shortcut
443    /// does, and first hands focus back to the field: clicking the menu took
444    /// focus away, and a text field ignores a paste it is not focused for. The
445    /// platform delivers the action as input on the NEXT frame, by which time
446    /// the field has focus again.
447    fn edit_menu(&mut self, ui: &mut egui::Ui, field: &egui::Response) {
448        let entries = [
449            ("menu:cut", "Cut", egui::ViewportCommand::RequestCut),
450            ("menu:copy", "Copy", egui::ViewportCommand::RequestCopy),
451            ("menu:paste", "Paste", egui::ViewportCommand::RequestPaste),
452        ];
453        for (key, label, command) in entries {
454            let item = ui.add_enabled_ui(MENU_REACHES_CLIPBOARD, |ui| crate::ui_kit::chrome_parts::menu_entry(ui, label)).inner;
455            self.hit(key, &item);
456            if item.clicked() {
457                field.request_focus();
458                ui.ctx().send_viewport_cmd(command);
459                ui.close();
460            }
461        }
462        if !MENU_REACHES_CLIPBOARD {
463            ui.weak("In the browser, use Ctrl+X / C / V (Cmd on a Mac).");
464        }
465    }
466
467    /// While capturing, look for the delivered screenshot; time out gracefully.
468    fn poll_capture(&mut self, ctx: &egui::Context) {
469        let frames = match &mut self.phase {
470            Phase::Capturing { frames } => {
471                *frames += 1;
472                *frames
473            }
474            _ => return,
475        };
476        // eframe injects `Event::Screenshot` into the frame's raw input once the
477        // async framebuffer readback completes. Take the newest one.
478        let shot = ctx.input(|i| {
479            i.raw.events.iter().rev().find_map(|e| match e {
480                egui::Event::Screenshot { image, .. } => Some(image.clone()),
481                _ => None,
482            })
483        });
484        if let Some(img) = shot {
485            self.screenshot_png = encode_png(&img);
486            self.markup = Some(markup::Markup::new((*img).clone()));
487            self.thumb = Some(ctx.load_texture(
488                "brep-bug-shot",
489                (*img).clone(),
490                egui::TextureOptions::LINEAR,
491            ));
492            self.phase = Phase::Editing;
493        } else if frames > CAPTURE_TIMEOUT_FRAMES {
494            self.status = "(screenshot unavailable)".into();
495            self.phase = Phase::Editing;
496        } else {
497            ctx.request_repaint();
498        }
499    }
500
501    /// Drain the POST reply: success closes the dialog with a toast; an error
502    /// stays open so the user can retry.
503    fn drain_response(&mut self, state: &mut EngineState) {
504        let Some(rx) = &self.response_rx else { return };
505        let Ok(result) = rx.try_recv() else { return };
506        self.response_rx = None;
507        match result {
508            Ok(id) => {
509                state.push_notice("Bug report submitted — thank you!".to_string());
510                self.submitted = id.map(|id| (id, crate::report_followup::summary_of(&self.description)));
511                self.reset();
512            }
513            Err(e) => {
514                self.status = crate::offsite::explain(FEATURE, REPORT_URL, format!("Submit failed: {e}"));
515                self.phase = Phase::Editing;
516            }
517        }
518    }
519
520    /// Build the multipart body and fire the POST (native + wasm via net.rs).
521    fn send(&mut self, ctx: &egui::Context) {
522        // On a PLM-hosted app that does not allow the report site, say so
523        // instead of letting the browser refuse the request (crate::offsite).
524        if let Some(sentence) = crate::offsite::refusal(FEATURE, REPORT_URL) {
525            self.status = sentence;
526            return;
527        }
528        self.status = "Submitting\u{2026}".into();
529        self.phase = Phase::Sending;
530
531        let (content_type, body) = build_multipart(
532            &compose_description(&self.description, &self.diagnostics),
533            &self.email,
534            &self.model_json,
535            self.screenshot_png.as_deref(),
536        );
537        let mut req = crate::net::Request::post(REPORT_URL, body);
538        // `Request::post` sets text/plain; replace it with our multipart type.
539        req.headers
540            .headers
541            .retain(|(k, _)| !k.eq_ignore_ascii_case("content-type"));
542        req.headers.headers.push(("Content-Type".to_string(), content_type));
543
544        let (tx, rx) = std::sync::mpsc::channel();
545        let ctx = ctx.clone();
546        crate::net::fetch(req, move |result| {
547            let out = match result {
548                Ok(resp) if resp.ok => Ok(crate::report_followup::id_of_reply(&resp.bytes)),
549                Ok(resp) => Err(format!("HTTP {} {}", resp.status, resp.status_text)),
550                Err(err) => Err(err),
551            };
552            let _ = tx.send(out);
553            ctx.request_repaint();
554        });
555        self.response_rx = Some(rx);
556    }
557
558    /// The report submitted since the last call: `(id, summary)`.
559    pub fn take_submitted(&mut self) -> Option<(String, String)> {
560        self.submitted.take()
561    }
562
563    /// Back to idle, dropping the screenshot + preview texture.
564    fn reset(&mut self) {
565        self.phase = Phase::Idle;
566        self.description.clear();
567        self.email.clear();
568        self.status.clear();
569        self.diagnostics.clear();
570        self.screenshot_png = None;
571        self.thumb = None;
572        self.markup = None;
573        self.response_rx = None;
574        self.description_scroll = DescriptionScroll::default();
575    }
576
577    /// Record a widget's screen rect for the verifier — its VISIBLE part: the
578    /// body and the description both scroll, and a click at the centre of a
579    /// rect that runs past its scroll area's clip lands on nothing.
580    fn hit(&mut self, key: &str, resp: &egui::Response) {
581        self.hits.insert(key.to_string(), resp.interact_rect);
582    }
583
584    /// Logical state for the headed verifier: which phase + whether a shot was
585    /// captured.
586    pub fn state_json(&self) -> String {
587        let phase = match self.phase {
588            Phase::Idle => "idle",
589            Phase::Capturing { .. } => "capturing",
590            Phase::Editing => "editing",
591            Phase::Marking => "marking",
592            Phase::Sending => "sending",
593        };
594        serde_json::json!({
595            "phase": phase,
596            "hasScreenshot": self.screenshot_png.is_some(),
597            "description": self.description,
598            "annotationCount": self.markup.as_ref().map_or(0, markup::Markup::count),
599            "diagnostics": self.diagnostics,
600            "status": self.status,
601            "descriptionScroll": {
602                "content": self.description_scroll.content,
603                "viewport": self.description_scroll.viewport,
604                "offset": self.description_scroll.offset,
605            },
606        })
607        .to_string()
608    }
609
610    /// The published widget hit-rects (egui points) for the headed verifier.
611    pub fn hits_json(&self) -> String {
612        let map: serde_json::Map<String, serde_json::Value> = self
613            .hits
614            .iter()
615            .map(|(k, r)| {
616                (
617                    k.clone(),
618                    serde_json::json!([r.center().x, r.center().y, r.width(), r.height()]),
619                )
620            })
621            .collect();
622        serde_json::Value::Object(map).to_string()
623    }
624}
625
626/// The description a dialog's Report problem button starts from. The dialog and
627/// the error lead, because the server's list and notification summarise a report
628/// by its first line; the blank line leaves the user room to add to it.
629fn error_description(dialog: &str, error: &str) -> String {
630    let dialog = dialog.split_whitespace().collect::<Vec<_>>().join(" ");
631    format!("{dialog}: {error}\n\n")
632}
633
634/// Encode an egui `ColorImage` (the screenshot) to PNG bytes via the pure-Rust
635/// `image` crate (wasm-safe). `None` on a zero-size image or encode error.
636fn encode_png(color: &egui::ColorImage) -> Option<Vec<u8>> {
637    use image::ImageEncoder;
638    let [w, h] = color.size;
639    if w == 0 || h == 0 {
640        return None;
641    }
642    let mut rgba = Vec::with_capacity(w * h * 4);
643    for px in &color.pixels {
644        // Straight (un-premultiplied) sRGBA, matching a normal PNG.
645        rgba.extend_from_slice(&px.to_srgba_unmultiplied());
646    }
647    let mut png = Vec::new();
648    image::codecs::png::PngEncoder::new(&mut png)
649        .write_image(&rgba, w as u32, h as u32, image::ExtendedColorType::Rgba8)
650        .ok()?;
651    Some(png)
652}
653
654/// The `description` the report actually submits: what the user typed, then the
655/// diagnostics block.
656///
657/// **Why inside `description` and not its own part.** The endpoint
658/// (`next.brep.io/api/report`) parses multipart into a fixed four-field record
659/// and its match ends `_ => {}` — an unknown part is accepted and silently
660/// DROPPED, never rejected. A `diagnostics` part would therefore submit cleanly
661/// and arrive nowhere, which is the worst of both: a client that looks like it
662/// reports the renderer and a server that never stores it. `description` is
663/// stored verbatim in `report.json` and is what a triager reads first, so the
664/// block goes there until the server grows a field of its own.
665///
666/// APPENDED, never prepended: the server's push notification and its public
667/// report list both summarise a report by its FIRST LINE, and a list where every
668/// row reads "--- diagnostics ---" tells a reader nothing.
669///
670/// The user's own text is clamped so the block survives the server's
671/// [`MAX_DESC`] tail truncation. A description long enough to hit that cap has
672/// already said what it has to say; the diagnostics are the part that cannot be
673/// re-derived later.
674fn compose_description(description: &str, diagnostics: &str) -> String {
675    if diagnostics.is_empty() {
676        return description.chars().take(MAX_DESC).collect();
677    }
678    const SEPARATOR: &str = "\n\n";
679    // `chars`, matching the server's own `chars().take(MAX_DESC)`.
680    let block_len = diagnostics.chars().count() + SEPARATOR.chars().count();
681    let room = MAX_DESC.saturating_sub(block_len);
682    let user: String = description.chars().take(room).collect();
683    format!("{user}{SEPARATOR}{diagnostics}")
684}
685
686/// Hand-build a `multipart/form-data` body (no multipart crate:
687/// one pulls `rand`→`getrandom`, which would need the wasm `js` feature). The
688/// boundary carries a distinctive ASCII prefix plus the payload lengths so it
689/// can't collide with the (text) model JSON or the PNG bytes.
690fn build_multipart(
691    description: &str,
692    email: &str,
693    model: &str,
694    screenshot: Option<&[u8]>,
695) -> (String, Vec<u8>) {
696    let boundary = format!(
697        "----BREPBugReport{:x}x{:x}Boundary",
698        model.len(),
699        screenshot.map(|s| s.len()).unwrap_or(0)
700    );
701    let mut body = Vec::new();
702    push_text_field(&mut body, &boundary, "description", description);
703    push_text_field(&mut body, &boundary, "email", email);
704    push_file_field(
705        &mut body,
706        &boundary,
707        "model",
708        "model.nbrep",
709        "application/json",
710        model.as_bytes(),
711    );
712    if let Some(png) = screenshot {
713        push_file_field(&mut body, &boundary, "screenshot", "screenshot.png", "image/png", png);
714    }
715    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
716    (format!("multipart/form-data; boundary={boundary}"), body)
717}
718
719fn push_text_field(body: &mut Vec<u8>, boundary: &str, name: &str, value: &str) {
720    body.extend_from_slice(
721        format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n")
722            .as_bytes(),
723    );
724    body.extend_from_slice(value.as_bytes());
725    body.extend_from_slice(b"\r\n");
726}
727
728fn push_file_field(
729    body: &mut Vec<u8>,
730    boundary: &str,
731    name: &str,
732    filename: &str,
733    content_type: &str,
734    bytes: &[u8],
735) {
736    body.extend_from_slice(
737        format!(
738            "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; \
739             filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
740        )
741        .as_bytes(),
742    );
743    body.extend_from_slice(bytes);
744    body.extend_from_slice(b"\r\n");
745}
746
747/// The hit keys this panel publishes (see `automation::hit_keys`).
748pub static HIT_KEYS: &[HitKeyDoc] = &[
749    HitKeyDoc { panel: "bug", prefix: "markup:", meaning: "screenshot markup toggle, markup:tool (the pen/arrow/rectangle dropdown; its open entries markup:tool#pen, #arrow, #rectangle), image drawing area, undo and clear", command: None },
750    HitKeyDoc { panel: "bug", prefix: "field:description", meaning: "the description field (its visible part; right-click opens its Cut / Copy / Paste menu)", command: None },
751    HitKeyDoc { panel: "bug", prefix: "menu:cut", meaning: "cut the description's selection, from its right-click menu (native; disabled in the browser)", command: None },
752    HitKeyDoc { panel: "bug", prefix: "menu:copy", meaning: "copy the description's selection, from its right-click menu (native; disabled in the browser)", command: None },
753    HitKeyDoc { panel: "bug", prefix: "menu:paste", meaning: "paste the clipboard into the description, from its right-click menu (native; disabled in the browser)", command: None },
754    HitKeyDoc { panel: "bug", prefix: "field:email", meaning: "the email field", command: None },
755    HitKeyDoc { panel: "bug", prefix: "diagnostics", meaning: "expand the diagnostics block the report will carry (the `diagnostics` command returns the same rows, but expanding a header is not what it does)", command: None },
756    HitKeyDoc { panel: "bug", prefix: "submit", meaning: "submit the report", command: None },
757    HitKeyDoc { panel: "bug", prefix: "cancel", meaning: "close the report", command: None },
758];
759