1
//! The `SysDialogType::ReportProblem` dialog: user message + optional
2
//! screenshot of the CURRENT window + optional system information, delivered
3
//! to the app's support mailbox (`AppConfig.report_problem`) — or saved to
4
//! disk when no mailbox / no mail transport is available. Nothing leaves the
5
//! machine before the user presses **Send**.
6
//!
7
//! The screenshot is captured IN-PROCESS at invoke time
8
//! (`CallbackInfo::take_screenshot` re-renders the current display list on
9
//! the CPU), so it shows the user's real situation — no state
10
//! serialization round-trip needed for the common case.
11

            
12
// fn-item -> fn-pointer casts: required for the Into<Callback> generics;
13
// the annotated-temporary alternative buries the callback wiring.
14
#![allow(trivial_casts)]
15
use azul_core::{
16
    callbacks::{LayoutCallbackInfo, LayoutCallbackType, Update},
17
    dom::Dom,
18
    refany::RefAny,
19
    task::{ThreadId, ThreadReceiver},
20
};
21
use azul_css::AzString;
22

            
23
use super::{cpu_dialog_window, style};
24
use crate::{
25
    callbacks::CallbackInfo,
26
    thread::{
27
        Thread, ThreadCallbackType, ThreadReceiveMsg, ThreadSender, ThreadWriteBackMsg,
28
        WriteBackCallbackType,
29
    },
30
    widgets::{
31
        button::{Button, ButtonOnClickCallbackType},
32
        check_box::{CheckBox, CheckBoxOnToggleCallbackType, CheckBoxState},
33
        text_area::{TextArea, TextAreaOnTextInputCallbackType, TextAreaState},
34
        text_input::{OnTextInputReturn, TextInputValid},
35
    },
36
};
37

            
38
/// Where the report currently is.
39
#[derive(Debug, Clone, PartialEq, Eq)]
40
pub enum ReportStatus {
41
    /// The user is typing.
42
    Editing,
43
    /// The send worker is running.
44
    Sending,
45
    /// Delivered (or saved) — the message names where it went.
46
    Done(String),
47
    /// Transport failed; the report stays editable for a retry.
48
    Failed(String),
49
}
50

            
51
/// Shared dialog state.
52
// Each bool is one independent opt-in checkbox in the dialog.
53
#[allow(clippy::struct_excessive_bools)]
54
#[derive(Debug, Clone)]
55
pub struct ReportProblemState {
56
    /// Destination mailbox (from `AppConfig.report_problem`); None = save to
57
    /// disk instead of mailing.
58
    pub email: Option<String>,
59
    /// The user's description.
60
    pub message: String,
61
    /// Attach the best-effort hardware/OS block.
62
    pub include_sysinfo: bool,
63
    /// Attach the screenshot below.
64
    pub attach_screenshot: bool,
65
    /// PNG of the window the dialog was invoked from, captured at invoke
66
    /// time (None when the capture failed).
67
    pub screenshot_png: Option<Vec<u8>>,
68
    /// Attach the ACTION JOURNAL (handler names + nodes, no user content).
69
    pub include_actions: bool,
70
    /// Attach the app's serialized state. DEFAULT OFF: this is the one
71
    /// section that can carry the user's actual document.
72
    pub include_app_data: bool,
73
    /// Blackout rectangles the user drew on the preview, in PREVIEW
74
    /// coordinates. Applied to the PNG that is actually sent.
75
    pub redactions: Vec<crate::dialogs::report::RedactRect>,
76
    /// First corner of the blackout currently being dragged.
77
    pub drag_start: Option<(f32, f32)>,
78
    /// `image_px / preview_px`, so a rectangle drawn on the preview lands on
79
    /// the right pixels of the full-size capture.
80
    pub preview_scale: f32,
81
    /// Preview size in logical pixels (width, height).
82
    pub preview_size: (f32, f32),
83
    pub status: ReportStatus,
84
}
85

            
86
/// Opens the dialog. `screenshot_png` is the already-captured window
87
/// screenshot (the capture happens in `invoke_system_dialog`, BEFORE this
88
/// window exists, so the dialog itself is never in the picture).
89
pub fn open(info: &mut CallbackInfo, screenshot_png: Option<Vec<u8>>) {
90
    let env = crate::appenv::app_env();
91
    // Fit the capture into the dialog: the preview is a scaled copy, and the
92
    // scale is REMEMBERED so a blackout drawn here maps to the real pixels.
93
    const PREVIEW_MAX_W: f32 = 460.0;
94
    let (preview_size, preview_scale) = screenshot_png
95
        .as_deref()
96
        .and_then(|png| crate::cpurender::AzulPixmap::decode_png(png).ok())
97
        .map_or(((0.0, 0.0), 1.0), |p| {
98
            #[allow(clippy::cast_precision_loss)]
99
            let (w, h) = (p.width() as f32, p.height() as f32);
100
            if w <= 0.0 || h <= 0.0 {
101
                return ((0.0, 0.0), 1.0);
102
            }
103
            let scale = (w / PREVIEW_MAX_W).max(1.0);
104
            ((w / scale, h / scale), scale)
105
        });
106
    let state = RefAny::new(ReportProblemState {
107
        email: env.report_problem,
108
        message: String::new(),
109
        include_sysinfo: true,
110
        attach_screenshot: screenshot_png.is_some(),
111
        screenshot_png,
112
        // The journal carries handler names and node ids, never user
113
        // content, so it defaults ON; app data is the user's document and
114
        // defaults OFF.
115
        include_actions: crate::journal::is_enabled(),
116
        include_app_data: false,
117
        redactions: Vec::new(),
118
        drag_start: None,
119
        preview_scale,
120
        preview_size,
121
        status: ReportStatus::Editing,
122
    });
123
    info.create_window(cpu_dialog_window(
124
        "Report a Problem",
125
        (520.0, 480.0),
126
        dialog_layout as LayoutCallbackType,
127
        state,
128
    ));
129
}
130

            
131
// --- widget callbacks -----------------------------------------------------
132

            
133
extern "C" fn on_message_input(
134
    mut state: RefAny,
135
    _info: CallbackInfo,
136
    text_state: TextAreaState,
137
) -> OnTextInputReturn {
138
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
139
        s.message = text_state.get_text();
140
    }
141
    OnTextInputReturn {
142
        update: Update::DoNothing,
143
        valid: TextInputValid::Yes,
144
    }
145
}
146

            
147
extern "C" fn on_toggle_sysinfo(
148
    mut state: RefAny,
149
    _info: CallbackInfo,
150
    cb: CheckBoxState,
151
) -> Update {
152
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
153
        s.include_sysinfo = cb.checked;
154
    }
155
    Update::DoNothing
156
}
157

            
158
extern "C" fn on_toggle_screenshot(
159
    mut state: RefAny,
160
    _info: CallbackInfo,
161
    cb: CheckBoxState,
162
) -> Update {
163
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
164
        s.attach_screenshot = cb.checked;
165
    }
166
    Update::DoNothing
167
}
168

            
169
extern "C" fn on_toggle_actions(
170
    mut state: RefAny,
171
    _info: CallbackInfo,
172
    cb: CheckBoxState,
173
) -> Update {
174
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
175
        s.include_actions = cb.checked;
176
    }
177
    Update::DoNothing
178
}
179

            
180
extern "C" fn on_toggle_app_data(
181
    mut state: RefAny,
182
    _info: CallbackInfo,
183
    cb: CheckBoxState,
184
) -> Update {
185
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
186
        s.include_app_data = cb.checked;
187
    }
188
    Update::DoNothing
189
}
190

            
191
/// First corner of a blackout drag.
192
extern "C" fn on_preview_mouse_down(mut state: RefAny, mut info: CallbackInfo) -> Update {
193
    let Some(pos) = info.get_cursor_relative_to_node().into_option() else {
194
        return Update::DoNothing;
195
    };
196
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
197
        s.drag_start = Some((pos.x, pos.y));
198
    }
199
    Update::DoNothing
200
}
201

            
202
/// Second corner: the rectangle is added and drawn over the preview. It is
203
/// applied to the PNG at SEND time (see `on_send`) — the overlay here is a
204
/// preview of a redaction that really happens, not the redaction itself.
205
extern "C" fn on_preview_mouse_up(mut state: RefAny, mut info: CallbackInfo) -> Update {
206
    let Some(pos) = info.get_cursor_relative_to_node().into_option() else {
207
        return Update::DoNothing;
208
    };
209
    let Some(mut s) = state.downcast_mut::<ReportProblemState>() else {
210
        return Update::DoNothing;
211
    };
212
    let Some((sx, sy)) = s.drag_start.take() else {
213
        return Update::DoNothing;
214
    };
215
    let rect = crate::dialogs::report::RedactRect::from_corners(sx, sy, pos.x, pos.y);
216
    if rect.is_empty() {
217
        return Update::DoNothing;
218
    }
219
    s.redactions.push(rect);
220
    Update::RefreshDomAllWindows
221
}
222

            
223
extern "C" fn on_clear_redactions(mut state: RefAny, _info: CallbackInfo) -> Update {
224
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
225
        s.redactions.clear();
226
        s.drag_start = None;
227
    }
228
    Update::RefreshDomAllWindows
229
}
230

            
231
extern "C" fn on_cancel(mut _state: RefAny, mut info: CallbackInfo) -> Update {
232
    info.close_window();
233
    Update::DoNothing
234
}
235

            
236
extern "C" fn on_send(mut state: RefAny, mut info: CallbackInfo) -> Update {
237
    let task = {
238
        let Some(mut s) = state.downcast_mut::<ReportProblemState>() else {
239
            return Update::DoNothing;
240
        };
241
        if s.status == ReportStatus::Sending {
242
            return Update::DoNothing;
243
        }
244
        s.status = ReportStatus::Sending;
245
        // The redactions are applied HERE, to the bytes that will be
246
        // attached. If the blackout cannot be applied, the screenshot is
247
        // DROPPED rather than sent unredacted.
248
        let screenshot = if s.attach_screenshot {
249
            match (&s.screenshot_png, s.redactions.is_empty()) {
250
                (Some(png), true) => Some(png.clone()),
251
                (Some(png), false) => {
252
                    crate::dialogs::report::redact_png(png, &s.redactions, s.preview_scale).ok()
253
                }
254
                (None, _) => None,
255
            }
256
        } else {
257
            None
258
        };
259
        SendTask {
260
            email: s.email.clone(),
261
            report: build_report_text(&s.message, s.include_sysinfo, s.include_actions),
262
            screenshot,
263
            recent_actions: if s.include_actions {
264
                Some(crate::journal::recent_json(
265
                    crate::journal::DEFAULT_CAPACITY,
266
                ))
267
            } else {
268
                None
269
            },
270
            app_data: if s.include_app_data {
271
                app_data_json(&info)
272
            } else {
273
                None
274
            },
275
        }
276
    };
277
    info.add_thread(
278
        ThreadId::unique(),
279
        Thread::create(
280
            RefAny::new(task),
281
            state.clone(),
282
            send_worker as ThreadCallbackType,
283
        ),
284
    );
285
    Update::RefreshDomAllWindows
286
}
287

            
288
/// The report body: user message + app identity + (optional) system block.
289
/// Plain text by design — it is read by a HUMAN at the support mailbox.
290
5
fn build_report_text(message: &str, include_sysinfo: bool, include_actions: bool) -> String {
291
    use std::fmt::Write as _;
292
5
    let env = crate::appenv::app_env();
293
5
    let mut out = String::new();
294
5
    let _ = writeln!(
295
5
        out,
296
5
        "Problem report — {} {}",
297
        env.app_name, env.current_version
298
    );
299
5
    let _ = writeln!(out, "----------------------------------------");
300
5
    if message.trim().is_empty() {
301
1
        let _ = writeln!(out, "(no user message)");
302
4
    } else {
303
4
        let _ = writeln!(out, "{}", message.trim());
304
4
    }
305
5
    if include_sysinfo {
306
2
        let _ = writeln!(out, "\nSystem information:");
307
        #[cfg(feature = "telemetry")]
308
        for (k, v) in crate::telemetry::sysinfo::get().as_attributes() {
309
            let _ = writeln!(out, "  {k} = {v}");
310
        }
311
        #[cfg(not(feature = "telemetry"))]
312
2
        {
313
2
            let _ = writeln!(out, "  os = {}", std::env::consts::OS);
314
2
            let _ = writeln!(out, "  arch = {}", std::env::consts::ARCH);
315
2
        }
316
3
    }
317
5
    if include_actions {
318
1
        let _ = writeln!(out, "\nRecent actions are attached as recent-actions.json.");
319
4
    }
320
5
    out
321
5
}
322

            
323
/// The app's serialized state, when the app registered a JSON serializer
324
/// (`RefAny::set_serialize_fn`) — the honest reading of "include app data".
325
/// Without a serializer there is nothing to include and the report says so
326
/// rather than attaching an empty file.
327
#[cfg(feature = "json")]
328
fn app_data_json(info: &CallbackInfo) -> Option<String> {
329
    let data = info.get_ctx().into_option()?;
330
    let json = crate::json::serialize_refany_to_json(&data)?;
331
    Some(json.to_json_string().as_str().to_owned())
332
}
333

            
334
/// Without the `json` feature there is no serializer to ask.
335
#[cfg(not(feature = "json"))]
336
const fn app_data_json(_info: &CallbackInfo) -> Option<String> {
337
    None
338
}
339

            
340
struct SendTask {
341
    email: Option<String>,
342
    report: String,
343
    screenshot: Option<Vec<u8>>,
344
    recent_actions: Option<String>,
345
    app_data: Option<String>,
346
}
347

            
348
struct NewStatus(ReportStatus);
349

            
350
/// Background transport ladder: mail (crash-mail feature + mailbox set) →
351
/// save to disk. Either way the user gets told exactly where it went.
352
extern "C" fn send_worker(mut init: RefAny, mut sender: ThreadSender, _recv: ThreadReceiver) {
353
    let Some(task) = init.downcast_ref::<SendTask>() else {
354
        return;
355
    };
356
    let email = task.email.clone();
357
    let report = task.report.clone();
358
    let screenshot = task.screenshot.clone();
359
    let recent_actions = task.recent_actions.clone();
360
    let app_data = task.app_data.clone();
361
    drop(task);
362

            
363
    let mut attachments: Vec<(String, Vec<u8>)> =
364
        vec![("report.txt".to_owned(), report.clone().into_bytes())];
365
    if let Some(png) = screenshot {
366
        attachments.push(("screenshot.png".to_owned(), png));
367
    }
368
    if let Some(actions) = recent_actions {
369
        attachments.push(("recent-actions.json".to_owned(), actions.into_bytes()));
370
    }
371
    if let Some(data) = app_data {
372
        attachments.push(("app-data.json".to_owned(), data.into_bytes()));
373
    }
374

            
375
    let status = deliver(email.as_deref(), &report, &attachments);
376

            
377
    let _ = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
378
        apply_status as WriteBackCallbackType,
379
        RefAny::new(NewStatus(status)),
380
    )));
381
}
382

            
383
#[cfg(feature = "crash-mail")]
384
fn deliver(email: Option<&str>, _report: &str, attachments: &[(String, Vec<u8>)]) -> ReportStatus {
385
    match email {
386
        Some(to) => {
387
            let domain = to.split('@').nth(1).unwrap_or("localhost").to_owned();
388
            let config = crate::telemetry::crash_mail::CrashMailConfig::new(
389
                to.to_owned(),
390
                format!("problem-reporter@{domain}"),
391
                domain,
392
            );
393
            match crate::telemetry::crash_mail::send_attachments(
394
                &config,
395
                "Problem report attached (report.txt).",
396
                attachments,
397
            ) {
398
                Ok(()) => ReportStatus::Done(format!("Report sent to {to}.")),
399
                Err(e) => ReportStatus::Failed(format!("Sending failed: {e}")),
400
            }
401
        }
402
        None => save_to_disk(attachments),
403
    }
404
}
405

            
406
#[cfg(not(feature = "crash-mail"))]
407
fn deliver(_email: Option<&str>, _report: &str, attachments: &[(String, Vec<u8>)]) -> ReportStatus {
408
    // Built without the mail transport: saving to disk is the honest path.
409
    save_to_disk(attachments)
410
}
411

            
412
/// Disk fallback: `{data_dir}/{app}/problem-reports/report-<unix>[.-]*`.
413
fn save_to_disk(attachments: &[(String, Vec<u8>)]) -> ReportStatus {
414
    let env = crate::appenv::app_env();
415
    let dir = report_dir(&env.app_name);
416
    if let Err(e) = std::fs::create_dir_all(&dir) {
417
        return ReportStatus::Failed(format!("cannot create {}: {e}", dir.display()));
418
    }
419
    let stamp = std::time::SystemTime::now()
420
        .duration_since(std::time::UNIX_EPOCH)
421
        .map_or(0, |d| d.as_secs());
422
    for (name, bytes) in attachments {
423
        let path = dir.join(format!("report-{stamp}-{name}"));
424
        if let Err(e) = std::fs::write(&path, bytes) {
425
            return ReportStatus::Failed(format!("cannot write {}: {e}", path.display()));
426
        }
427
    }
428
    ReportStatus::Done(format!("Report saved to {}.", dir.display()))
429
}
430

            
431
/// Where disk-fallback reports go (public so apps can point users at it).
432
#[must_use]
433
pub fn report_dir(app_name: &str) -> std::path::PathBuf {
434
    #[cfg(feature = "updater")]
435
    {
436
        crate::updater::default_state_dir(app_name).join("problem-reports")
437
    }
438
    #[cfg(not(feature = "updater"))]
439
    {
440
        std::env::temp_dir().join(app_name).join("problem-reports")
441
    }
442
}
443

            
444
extern "C" fn apply_status(mut state: RefAny, mut msg: RefAny, _info: CallbackInfo) -> Update {
445
    let Some(new_status) = msg.downcast_ref::<NewStatus>().map(|s| s.0.clone()) else {
446
        return Update::DoNothing;
447
    };
448
    if let Some(mut s) = state.downcast_mut::<ReportProblemState>() {
449
        s.status = new_status;
450
    }
451
    Update::RefreshDomAllWindows
452
}
453

            
454
// --- the dialog DOM -------------------------------------------------------
455

            
456
extern "C" fn dialog_layout(_data: RefAny, info: LayoutCallbackInfo) -> Dom {
457
    let Some(mut ctx) = info.get_ctx().into_option() else {
458
        return Dom::create_body();
459
    };
460
    let snapshot = match ctx.downcast_ref::<ReportProblemState>() {
461
        Some(s) => s.clone(),
462
        None => return Dom::create_body(),
463
    };
464
    drop(ctx);
465
    let state = info
466
        .get_ctx()
467
        .into_option()
468
        .unwrap_or_else(|| RefAny::new(()));
469

            
470
    use azul_css::props::{
471
        basic::pixel::PixelValue,
472
        layout::{LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop},
473
    };
474
    let pad = style(vec![
475
        azul_css::props::property::CssProperty::padding_left(LayoutPaddingLeft {
476
            inner: PixelValue::px(16.0),
477
        }),
478
        azul_css::props::property::CssProperty::padding_right(LayoutPaddingRight {
479
            inner: PixelValue::px(16.0),
480
        }),
481
        azul_css::props::property::CssProperty::padding_top(LayoutPaddingTop {
482
            inner: PixelValue::px(16.0),
483
        }),
484
        azul_css::props::property::CssProperty::padding_bottom(LayoutPaddingBottom {
485
            inner: PixelValue::px(16.0),
486
        }),
487
    ]);
488

            
489
    let mut children: Vec<Dom> = vec![Dom::create_h2_with_text("Report a problem")];
490
    match &snapshot.email {
491
        Some(to) => children.push(Dom::create_p_with_text(format!(
492
            "Describe what went wrong. The report goes to {to} — nothing is sent until you press \
493
             Send."
494
        ))),
495
        None => children.push(Dom::create_p_with_text(
496
            "Describe what went wrong. The report is saved to disk (no support address is \
497
             configured).",
498
        )),
499
    }
500

            
501
    match &snapshot.status {
502
        ReportStatus::Editing | ReportStatus::Failed(_) => {
503
            if let ReportStatus::Failed(e) = &snapshot.status {
504
                children.push(Dom::create_p_with_text(format!(
505
                    "Previous attempt failed: {e}"
506
                )));
507
            }
508
            children.push(
509
                TextArea::create()
510
                    .with_text(AzString::from(snapshot.message.as_str()))
511
                    .with_placeholder(AzString::from(
512
                        "What were you doing when the problem happened?",
513
                    ))
514
                    .with_on_text_input(
515
                        state.clone(),
516
                        on_message_input as TextAreaOnTextInputCallbackType,
517
                    )
518
                    .dom(),
519
            );
520
            children.push(check_row(
521
                snapshot.include_sysinfo,
522
                "Include system information (CPU, GPU, OS, RAM)",
523
                on_toggle_sysinfo,
524
                state.clone(),
525
            ));
526
            children.push(check_row(
527
                snapshot.include_actions,
528
                "Include recent actions (which handlers ran - no typed text)",
529
                on_toggle_actions,
530
                state.clone(),
531
            ));
532
            children.push(check_row(
533
                snapshot.include_app_data,
534
                "Include application data (your document - off by default)",
535
                on_toggle_app_data,
536
                state.clone(),
537
            ));
538
            if snapshot.screenshot_png.is_some() {
539
                children.push(check_row(
540
                    snapshot.attach_screenshot,
541
                    "Attach a screenshot of the window",
542
                    on_toggle_screenshot,
543
                    state.clone(),
544
                ));
545
            }
546
            if snapshot.attach_screenshot {
547
                children.extend(preview_section(&snapshot, &state));
548
            }
549
            children.push(button_row(vec![
550
                ("Send", on_send, state.clone()),
551
                ("Cancel", on_cancel, state),
552
            ]));
553
        }
554
        ReportStatus::Sending => {
555
            children.push(Dom::create_p_with_text("Sending the report…"));
556
        }
557
        ReportStatus::Done(msg) => {
558
            children.push(Dom::create_p_with_text(msg.as_str()));
559
            children.push(button_row(vec![("Close", on_cancel, state)]));
560
        }
561
    }
562

            
563
    Dom::create_body().with_child(
564
        Dom::create_div()
565
            .with_css_props(pad)
566
            .with_children(children.into()),
567
    )
568
}
569

            
570
/// The screenshot preview plus its blackout overlay.
571
///
572
/// Drag on the image to cover anything private; the rectangles are drawn
573
/// here and applied to the attached PNG at send time. Nothing about the
574
/// preview is decorative: what you black out is what leaves the machine.
575
fn preview_section(snapshot: &ReportProblemState, state: &RefAny) -> Vec<Dom> {
576
    use azul_core::{
577
        callbacks::{CoreCallback, CoreCallbackType},
578
        dom::{EventFilter, HoverEventFilter},
579
    };
580
    use azul_css::{
581
        dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
582
        props::{
583
            basic::color::ColorU,
584
            layout::{LayoutHeight, LayoutLeft, LayoutPosition, LayoutTop, LayoutWidth},
585
            property::CssProperty,
586
            style::StyleBackgroundContent,
587
        },
588
    };
589

            
590
    let Some(png) = snapshot.screenshot_png.as_deref() else {
591
        return Vec::new();
592
    };
593
    let (pw, ph) = snapshot.preview_size;
594
    if pw <= 0.0 || ph <= 0.0 {
595
        return Vec::new();
596
    }
597
    let Ok(pixmap) = crate::cpurender::AzulPixmap::decode_png(png) else {
598
        return vec![Dom::create_p_with_text(
599
            "The screenshot could not be decoded for preview; it will not be attached.",
600
        )];
601
    };
602
    let raw = azul_core::resources::RawImage {
603
        pixels: azul_core::resources::RawImageData::U8(pixmap.data().to_vec().into()),
604
        width: pixmap.width() as usize,
605
        height: pixmap.height() as usize,
606
        premultiplied_alpha: false,
607
        data_format: azul_core::resources::RawImageFormat::RGBA8,
608
        tag: Vec::new().into(),
609
    };
610
    let Some(image_ref) = azul_core::resources::ImageRef::new_rawimage(raw) else {
611
        return vec![Dom::create_p_with_text(
612
            "The screenshot could not be prepared for preview.",
613
        )];
614
    };
615

            
616
    let sized = |w: f32, h: f32| {
617
        style(vec![
618
            CssProperty::width(LayoutWidth::px(w)),
619
            CssProperty::height(LayoutHeight::px(h)),
620
        ])
621
    };
622

            
623
    // The image, listening for the two drag corners.
624
    let image = Dom::create_image(image_ref)
625
        .with_css_props(sized(pw, ph))
626
        .with_callback(
627
            EventFilter::Hover(HoverEventFilter::MouseDown),
628
            state.clone(),
629
            CoreCallback {
630
                cb: on_preview_mouse_down as *const () as CoreCallbackType,
631
                ctx: azul_core::refany::OptionRefAny::None,
632
            },
633
        )
634
        .with_callback(
635
            EventFilter::Hover(HoverEventFilter::MouseUp),
636
            state.clone(),
637
            CoreCallback {
638
                cb: on_preview_mouse_up as *const () as CoreCallbackType,
639
                ctx: azul_core::refany::OptionRefAny::None,
640
            },
641
        );
642

            
643
    // Absolutely-positioned black rectangles over it.
644
    let mut stack: Vec<Dom> = vec![image];
645
    for rect in &snapshot.redactions {
646
        let r = rect.normalized();
647
        stack.push(Dom::create_div().with_css_props(style(vec![
648
                CssProperty::position(LayoutPosition::Absolute),
649
                CssProperty::left(LayoutLeft::px(r.x)),
650
                CssProperty::top(LayoutTop::px(r.y)),
651
                CssProperty::width(LayoutWidth::px(r.width)),
652
                CssProperty::height(LayoutHeight::px(r.height)),
653
                CssProperty::background_content(
654
                    vec![StyleBackgroundContent::Color(ColorU {
655
                        r: 0,
656
                        g: 0,
657
                        b: 0,
658
                        a: 255,
659
                    })]
660
                    .into(),
661
                ),
662
            ])));
663
    }
664

            
665
    vec![
666
        Dom::create_p_with_text(
667
            "Drag on the preview to black out anything private - the blackout is applied to the \
668
             image that is sent.",
669
        ),
670
        Dom::create_div()
671
            .with_css_props({
672
                let mut props = sized(pw, ph).as_ref().to_vec();
673
                props.push(CssPropertyWithConditions::simple(CssProperty::position(
674
                    LayoutPosition::Relative,
675
                )));
676
                CssPropertyWithConditionsVec::from_vec(props)
677
            })
678
            .with_children(stack.into()),
679
        button_row(vec![(
680
            "Clear blackouts",
681
            on_clear_redactions as ButtonOnClickCallbackType,
682
            state.clone(),
683
        )]),
684
    ]
685
}
686

            
687
fn check_row(checked: bool, label: &str, cb: CheckBoxOnToggleCallbackType, state: RefAny) -> Dom {
688
    Dom::create_div().with_children(
689
        vec![
690
            CheckBox::create(checked).with_on_toggle(state, cb).dom(),
691
            Dom::create_p_with_text(label),
692
        ]
693
        .into(),
694
    )
695
}
696

            
697
fn button_row(buttons: Vec<(&str, ButtonOnClickCallbackType, RefAny)>) -> Dom {
698
    let children: Vec<Dom> = buttons
699
        .into_iter()
700
        .map(|(label, cb, state)| {
701
            Button::create(AzString::from(label))
702
                .with_on_click(state, cb)
703
                .dom()
704
        })
705
        .collect();
706
    Dom::create_div().with_children(children.into())
707
}
708

            
709
#[cfg(test)]
710
mod tests {
711
    use super::*;
712

            
713
    #[test]
714
1
    fn report_text_carries_message_and_sysinfo_toggle_is_respected() {
715
1
        crate::appenv::set_app_env(crate::appenv::AppEnv {
716
1
            app_name: "reporttest".to_owned(),
717
1
            current_version: "9.9.9".to_owned(),
718
1
            ..Default::default()
719
1
        });
720
1
        let with = build_report_text("it broke while saving", true, false);
721
1
        assert!(with.contains("reporttest 9.9.9"), "{with}");
722
1
        assert!(with.contains("it broke while saving"), "{with}");
723
1
        assert!(with.contains("System information"), "{with}");
724

            
725
        // The toggle is a PRIVACY control: off must mean ABSENT, not empty.
726
1
        let without = build_report_text("msg", false, false);
727
1
        assert!(!without.contains("System information"), "{without}");
728
1
    }
729

            
730
    /// LAW: every opt-in section is ABSENT when declined — the report must
731
    /// never mention data the user chose not to send.
732
    #[test]
733
1
    fn the_recent_actions_section_follows_its_toggle() {
734
1
        let on = build_report_text("msg", false, true);
735
1
        assert!(on.contains("recent-actions.json"), "{on}");
736
1
        let off = build_report_text("msg", false, false);
737
1
        assert!(!off.contains("recent-actions"), "{off}");
738
1
    }
739

            
740
    #[test]
741
1
    fn empty_message_is_labeled_not_blank() {
742
1
        let text = build_report_text("   ", true, false);
743
1
        assert!(text.contains("(no user message)"), "{text}");
744
1
    }
745
}