1#[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
41const REPORT_URL: &str = "https://next.brep.io/api/report";
45
46const FEATURE: &str = "Bug report";
48
49const MAX_DESC: usize = 20_000;
56
57const CAPTURE_TIMEOUT_FRAMES: u32 = 60;
62
63const DIALOG_WIDTH_FRACTION: f32 = 0.90;
65const DIALOG_HEIGHT_FRACTION: f32 = 0.95;
66
67const DESCRIPTION_ROWS: usize = 12;
70
71const DESCRIPTION_MARGIN: egui::Margin = egui::Margin::symmetric(4, 2);
74
75const FOOTER_GAP: f32 = 10.0;
77const STATUS_GAP: f32 = 6.0;
78
79const MENU_REACHES_CLIPBOARD: bool = cfg!(not(target_arch = "wasm32"));
85
86#[derive(Default, PartialEq)]
88enum Phase {
89 #[default]
91 Idle,
92 Capturing { frames: u32 },
94 Editing,
96 Marking,
98 Sending,
100}
101
102pub struct BugReportPanel {
103 phase: Phase,
104 description: String,
106 email: String,
108 status: String,
110 screenshot_png: Option<Vec<u8>>,
112 thumb: Option<egui::TextureHandle>,
114 markup: Option<markup::Markup>,
116 model_json: String,
118 diagnostics: String,
123 response_rx: Option<Receiver<Result<Option<String>, String>>>,
126 submitted: Option<(String, String)>,
129 hits: std::collections::HashMap<String, egui::Rect>,
131 description_scroll: DescriptionScroll,
135}
136
137#[derive(Clone, Copy, Default, Debug, PartialEq)]
139struct DescriptionScroll {
140 content: f32,
142 viewport: f32,
144 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn send(&mut self, ctx: &egui::Context) {
522 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 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 pub fn take_submitted(&mut self) -> Option<(String, String)> {
560 self.submitted.take()
561 }
562
563 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 fn hit(&mut self, key: &str, resp: &egui::Response) {
581 self.hits.insert(key.to_string(), resp.interact_rect);
582 }
583
584 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 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
626fn error_description(dialog: &str, error: &str) -> String {
630 let dialog = dialog.split_whitespace().collect::<Vec<_>>().join(" ");
631 format!("{dialog}: {error}\n\n")
632}
633
634fn 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 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
654fn 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 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
686fn 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
747pub 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