BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! The desktop app's HELP, downloaded to this machine the first time Help is
//! pressed (owner 2026-11-27). The browser build serves the help site beside
//! the page (`help/index.html`); a desktop build has nothing there, so:
//!
//! 1. Help with a copy for THIS app version already in
//!    `<data dir>/brep-app/help/<version>/` opens its `index.html` in the
//!    default browser at once, offline.
//! 2. Otherwise the app asks the site for `brep-help-<version>.json`, the help
//!    bundle's manifest (`./build.sh app` writes it and the archive beside the
//!    published web build, `web/help-bundle/`). When this version is not on the
//!    site any more it asks for `brep-help-latest.json` instead, opens that,
//!    and says the help is for another version.
//! 3. The archive (`.tar.gz`) is fetched over HTTPS from the same server as the
//!    updates, with progress and **Cancel** in a notice; it must match the
//!    manifest's length and sha256 before anything is unpacked. It unpacks
//!    into `.partial-*` and only a complete tree is renamed to `<version>/`,
//!    so a half copy is never opened. Only plain files and folders are
//!    taken: no links, no absolute or `..` paths.
//! 4. A failure (offline, a bad hash, no bundle) opens the newest copy already
//!    on this machine if there is one, and otherwise says why and offers the
//!    online help.
//!
//! Nothing is fetched unless a desktop `main` turned the source on
//! ([`HelpDownloader::start_site`](crate::help_local::HelpDownloader::start_site)); a headless or embedded app keeps the old
//! behaviour (the relative help URL) until a script points it at a test server
//! (`help_fixture`).

use std::collections::HashMap;
use std::ffi::OsString;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::sync::Arc;
use std::time::Duration;

use eframe::egui;
use sha2::{Digest, Sha256};

#[cfg(feature = "automation")]
pub mod fixture;

/// The first field of every bundle manifest.
pub const FORMAT: &str = "brep-help-bundle-v1";
/// This app's version: the help copy it looks for.
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Where the published web build keeps the bundle, on the update server.
pub const BUNDLE_PATH: &str = "/public/app/master/web/help-bundle";
/// The help site of the published web build, for when nothing downloads.
pub const ONLINE_PATH: &str = "/public/app/master/web/help/index.html";
/// The name of the manifest kept inside an installed copy.
const MARKER: &str = ".bundle.json";
/// No help bundle is this large; a manifest that says so is refused.
const MAX_BYTES: u64 = 1 << 30;

/// What `brep-help-<version>.json` says about the archive beside it.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct BundleManifest {
    pub format: String,
    pub version: String,
    pub file: String,
    pub sha256: String,
    pub bytes: u64,
}

/// A plain file or folder name: letters, digits and `._-+`, not hidden.
fn safe_name(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 128
        && !s.starts_with('.')
        && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-+".contains(c))
}

impl BundleManifest {
    pub fn parse(text: &str) -> Result<BundleManifest, String> {
        let m: BundleManifest = serde_json::from_str(text).map_err(|e| format!("help manifest: {e}"))?;
        if m.format != FORMAT {
            return Err(format!("help manifest format {:?} is not {FORMAT}", m.format));
        }
        if !safe_name(&m.version) {
            return Err(format!("help manifest version {:?} is not a plain name", m.version));
        }
        if !safe_name(&m.file) || !m.file.ends_with(".tar.gz") {
            return Err(format!("help manifest file {:?} is not a plain .tar.gz name", m.file));
        }
        if m.sha256.len() != 64 || !m.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err("help manifest sha256 is not 64 hex digits".into());
        }
        if m.bytes == 0 || m.bytes > MAX_BYTES {
            return Err(format!("help manifest size {} is out of range", m.bytes));
        }
        Ok(m)
    }
}

/// Where a bundle comes from: the manifests' and archive's base URL, and the
/// online help offered when nothing downloads.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Source {
    pub base: String,
    pub online: String,
}

impl Source {
    /// The published web build on `server` (`https://next.brep.io`).
    pub fn site(server: &str) -> Source {
        let server = server.trim_end_matches('/');
        Source { base: format!("{server}{BUNDLE_PATH}"), online: format!("{server}{ONLINE_PATH}") }
    }
}

/// The per-user data directory (`brep-app` under it), from the environment.
pub fn data_dir() -> PathBuf {
    let os = if cfg!(windows) {
        "windows"
    } else if cfg!(target_os = "macos") {
        "macos"
    } else {
        "linux"
    };
    data_dir_from(&|name| std::env::var_os(name), os)
}

/// [`data_dir`] with the environment and system passed in: `XDG_DATA_HOME`,
/// else `%LOCALAPPDATA%` (Windows), `~/Library/Application Support` (macOS)
/// or `~/.local/share`.
pub fn data_dir_from(env: &dyn Fn(&str) -> Option<OsString>, os: &str) -> PathBuf {
    let var = |name: &str| env(name).filter(|v| !v.is_empty()).map(PathBuf::from);
    var("XDG_DATA_HOME")
        .or_else(|| if os == "windows" { var("LOCALAPPDATA").or_else(|| var("APPDATA")) } else { None })
        .or_else(|| {
            var("HOME").map(|h| if os == "macos" { h.join("Library/Application Support") } else { h.join(".local/share") })
        })
        .unwrap_or_else(|| PathBuf::from("."))
        .join("brep-app")
}

/// A `file://` URL for a local path, percent-encoded (spaces, non-ASCII), with
/// a Windows drive path as `file:///C:/…`.
pub fn file_url(path: &Path) -> String {
    let s = path.to_string_lossy().replace('\\', "/");
    let mut out = String::from("file://");
    if !s.starts_with('/') {
        out.push('/');
    }
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b':' => out.push(b as char),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// The installed copy of `version` under `root`: its `index.html`, when the
/// copy is complete (unpacked whole and renamed into place).
pub fn installed(root: &Path, version: &str) -> Option<PathBuf> {
    let dir = root.join(version);
    (safe_name(version) && dir.join("index.html").is_file() && dir.join(MARKER).is_file()).then(|| dir.join("index.html"))
}

fn installed_manifest(root: &Path, version: &str) -> Option<BundleManifest> {
    installed(root, version)?;
    serde_json::from_str(&std::fs::read_to_string(root.join(version).join(MARKER)).ok()?).ok()
}

/// "0.34.0" → [0, 34, 0], for ordering versions; a part without a number is 0.
fn version_key(v: &str) -> Vec<u64> {
    v.split(['.', '-', '+'])
        .map(|p| p.chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0))
        .collect()
}

/// The newest complete copy under `root`, of any version.
pub fn newest_installed(root: &Path) -> Option<(String, PathBuf)> {
    let mut best: Option<(String, PathBuf)> = None;
    for entry in std::fs::read_dir(root).ok()?.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if let Some(index) = installed(root, &name) {
            if best.as_ref().is_none_or(|(v, _)| version_key(&name) > version_key(v)) {
                best = Some((name, index));
            }
        }
    }
    best
}

/// What a running download reports, and its cancel switch.
#[derive(Default)]
pub struct Progress {
    pub received: AtomicU64,
    pub total: AtomicU64,
    pub cancel: AtomicBool,
}

/// The error a cancelled download ends with.
pub const CANCELLED: &str = "the download was cancelled";

/// A copy ready to open.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fetched {
    pub index: PathBuf,
    pub version: String,
}

/// `Ok(None)` for a 404 (no such manifest), the manifest, or why not.
fn get_manifest(url: &str) -> Result<Option<BundleManifest>, String> {
    let response = crate::net::fetch_blocking(&crate::net::Request::get(url))?;
    if response.status == 404 {
        return Ok(None);
    }
    if !response.ok {
        return Err(format!("the help manifest: HTTP {} {}", response.status, response.status_text));
    }
    BundleManifest::parse(&String::from_utf8_lossy(&response.bytes)).map(Some)
}

/// Fetch, check and unpack the help for `want` (else the latest) from
/// `source` into `root`. Blocking: run it off the UI thread.
pub fn fetch_bundle(source: &Source, root: &Path, want: &str, progress: &Progress) -> Result<Fetched, String> {
    let base = source.base.trim_end_matches('/');
    let manifest = match get_manifest(&format!("{base}/brep-help-{want}.json"))? {
        Some(m) => m,
        None => get_manifest(&format!("{base}/brep-help-latest.json"))?
            .ok_or_else(|| format!("the server has no help bundle (neither {want}'s nor the latest)"))?,
    };
    // Already here (the latest, fetched on an earlier press): open it.
    if let Some(have) = installed_manifest(root, &manifest.version) {
        if have.sha256 == manifest.sha256 {
            if let Some(index) = installed(root, &manifest.version) {
                return Ok(Fetched { index, version: manifest.version });
            }
        }
    }
    progress.total.store(manifest.bytes, Ordering::Relaxed);
    let bytes = download(&format!("{base}/{}", manifest.file), &manifest, progress)?;
    let index = unpack(&bytes, root, &manifest)?;
    Ok(Fetched { index, version: manifest.version })
}

fn download(url: &str, m: &BundleManifest, progress: &Progress) -> Result<Vec<u8>, String> {
    let agent = ureq::AgentBuilder::new()
        .timeout_connect(Duration::from_secs(15))
        .timeout_read(Duration::from_secs(60))
        .build();
    // Identity: the sha256 is of the archive's own bytes, not a re-encoding.
    let reply = agent.get(url).set("Accept-Encoding", "identity").call().map_err(|e| match e {
        ureq::Error::Status(code, r) => format!("the help archive: HTTP {code} {}", r.status_text()),
        ureq::Error::Transport(t) => t.to_string(),
    })?;
    let mut reader = reply.into_reader();
    let mut buf = vec![0u8; 64 * 1024];
    let mut out = Vec::with_capacity(m.bytes as usize);
    let mut hash = Sha256::new();
    loop {
        if progress.cancel.load(Ordering::Relaxed) {
            return Err(CANCELLED.into());
        }
        let n = reader.read(&mut buf).map_err(|e| format!("the help download stopped: {e}"))?;
        if n == 0 {
            break;
        }
        if out.len() as u64 + n as u64 > m.bytes {
            return Err(format!("the server sent more than the {} bytes the manifest names", m.bytes));
        }
        hash.update(&buf[..n]);
        out.extend_from_slice(&buf[..n]);
        progress.received.store(out.len() as u64, Ordering::Relaxed);
    }
    if out.len() as u64 != m.bytes {
        return Err(format!("the help download stopped at {} of {} bytes", out.len(), m.bytes));
    }
    let got: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();
    if !got.eq_ignore_ascii_case(&m.sha256) {
        return Err(format!("the help download does not match its sha256 (got {got}, expected {})", m.sha256));
    }
    Ok(out)
}

/// `p` as a plain relative path (`./` dropped), or `None` when it climbs out,
/// is absolute or names a drive.
fn clean_relative(p: &Path) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            std::path::Component::Normal(part) => out.push(part),
            std::path::Component::CurDir => {}
            _ => return None,
        }
    }
    Some(out)
}

/// Unpack a checked archive into `root/<version>/`, whole or not at all.
pub fn unpack(gz: &[u8], root: &Path, m: &BundleManifest) -> Result<PathBuf, String> {
    std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
    let partial = root.join(format!(".partial-{}-{}", m.version, std::process::id()));
    let _ = std::fs::remove_dir_all(&partial);
    let result = (|| -> Result<PathBuf, String> {
        let io = |e: std::io::Error| format!("unpacking the help: {e}");
        std::fs::create_dir_all(&partial).map_err(io)?;
        let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(gz));
        for entry in archive.entries().map_err(io)? {
            let mut entry = entry.map_err(io)?;
            let path = entry.path().map_err(io)?.into_owned();
            let rel = clean_relative(&path).ok_or_else(|| format!("the help archive holds an unsafe path {}", path.display()))?;
            if rel.as_os_str().is_empty() {
                continue;
            }
            let to = partial.join(&rel);
            match entry.header().entry_type() {
                tar::EntryType::Regular | tar::EntryType::Continuous => {
                    if let Some(parent) = to.parent() {
                        std::fs::create_dir_all(parent).map_err(io)?;
                    }
                    let mut file = std::fs::File::create(&to).map_err(io)?;
                    std::io::copy(&mut entry, &mut file).map_err(io)?;
                }
                tar::EntryType::Directory => std::fs::create_dir_all(&to).map_err(io)?,
                // Links, devices, fifos: never taken.
                _ => {}
            }
        }
        if !partial.join("index.html").is_file() {
            return Err("the help archive has no index.html".into());
        }
        std::fs::write(partial.join(MARKER), serde_json::to_string_pretty(m).unwrap_or_default()).map_err(io)?;
        let dest = root.join(&m.version);
        if dest.exists() {
            std::fs::remove_dir_all(&dest).map_err(io)?;
        }
        std::fs::rename(&partial, &dest).map_err(io)?;
        Ok(dest.join("index.html"))
    })();
    if result.is_err() {
        let _ = std::fs::remove_dir_all(&partial);
    }
    result
}

/// Where Help stands, as the notice and `__brepHelp` show it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Phase {
    /// Not pressed yet (or a download was cancelled).
    None,
    Downloading,
    Ready { index: PathBuf, version: String },
    Failed { error: String },
}

struct Job {
    progress: Arc<Progress>,
    rx: Receiver<Result<Fetched, String>>,
}

/// The Help button's desktop half: the local copy, the download and its notice.
pub struct HelpDownloader {
    source: Option<Source>,
    root: PathBuf,
    phase: Phase,
    job: Option<Job>,
    /// The notice is up (downloading, a failure, or a note about the copy).
    notice: bool,
    /// What the notice says beside the phase (another version, a fallback,
    /// a cancel).
    note: Option<String>,
    /// The last URL Help opened.
    opened: Option<String>,
    hits: HashMap<String, egui::Rect>,
    #[cfg(feature = "automation")]
    fixture: Option<fixture::FixtureServer>,
    /// The fresh folders `help_fixture` made, removed with the app.
    #[cfg(feature = "automation")]
    fixture_dirs: Vec<PathBuf>,
}

#[cfg(feature = "automation")]
impl Drop for HelpDownloader {
    fn drop(&mut self) {
        self.cancel_job();
        for dir in &self.fixture_dirs {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

impl Default for HelpDownloader {
    fn default() -> Self {
        Self::inert()
    }
}

impl HelpDownloader {
    /// No source: Help opens the relative help URL as the browser build does.
    pub fn inert() -> HelpDownloader {
        HelpDownloader {
            source: None,
            root: data_dir().join("help"),
            phase: Phase::None,
            job: None,
            notice: false,
            note: None,
            opened: None,
            hits: HashMap::new(),
            #[cfg(feature = "automation")]
            fixture: None,
            #[cfg(feature = "automation")]
            fixture_dirs: Vec::new(),
        }
    }

    /// The desktop app: download from the update server (`BREP_UPDATE_URL`,
    /// else next.brep.io) into the per-user data directory.
    pub fn start_site(&mut self) {
        self.source = Some(Source::site(&crate::update::server()));
    }

    /// Point at another source and folder (a test server).
    pub fn configure(&mut self, source: Source, root: PathBuf) {
        self.cancel_job();
        self.source = Some(source);
        self.root = root;
        self.phase = Phase::None;
        self.notice = false;
        self.note = None;
        self.opened = None;
    }

    fn open(&mut self, ctx: &egui::Context, url: String) {
        ctx.open_url(egui::OpenUrl::new_tab(url.clone()));
        self.opened = Some(url);
    }

    /// Help was pressed. Returns the URL it opened at once, if any.
    pub fn press(&mut self, ctx: &egui::Context) -> Option<String> {
        self.drain(ctx);
        let Some(source) = self.source.clone() else {
            self.open(ctx, crate::automation::HELP_URL.to_string());
            return self.opened.clone();
        };
        if let Some(index) = installed(&self.root, APP_VERSION) {
            self.open(ctx, file_url(&index));
            self.phase = Phase::Ready { index, version: APP_VERSION.to_string() };
            self.notice = false;
            self.note = None;
            return self.opened.clone();
        }
        self.notice = true;
        if self.job.is_some() {
            return None;
        }
        let progress = Arc::new(Progress::default());
        let (tx, rx) = channel();
        let (thread_progress, root, ctx2) = (progress.clone(), self.root.clone(), ctx.clone());
        let spawned = std::thread::Builder::new().name("brep-help-download".into()).spawn(move || {
            let result = fetch_bundle(&source, &root, APP_VERSION, &thread_progress);
            let _ = tx.send(result);
            ctx2.request_repaint();
        });
        match spawned {
            Ok(_) => {
                self.job = Some(Job { progress, rx });
                self.phase = Phase::Downloading;
                self.note = None;
            }
            Err(e) => self.fail(ctx, format!("could not start the download: {e}")),
        }
        None
    }

    fn cancel_job(&mut self) {
        if let Some(job) = self.job.take() {
            job.progress.cancel.store(true, Ordering::Relaxed);
        }
    }

    /// Cancel a running download: the notice closes at once; the thread
    /// stops at its next read and its result is dropped.
    pub fn cancel(&mut self) {
        if self.job.is_some() {
            self.cancel_job();
            self.phase = Phase::None;
            self.note = Some("The help download was cancelled.".into());
            self.notice = false;
        }
    }

    fn fail(&mut self, ctx: &egui::Context, error: String) {
        if let Some((version, index)) = newest_installed(&self.root) {
            self.open(ctx, file_url(&index));
            self.note = Some(format!(
                "The help for this version could not be downloaded ({error}). Opened the copy for version {version} on this computer."
            ));
            self.phase = Phase::Ready { index, version };
        } else {
            self.phase = Phase::Failed { error };
            self.note = None;
        }
        self.notice = true;
    }

    fn drain(&mut self, ctx: &egui::Context) {
        let Some(job) = &self.job else { return };
        let result = match job.rx.try_recv() {
            Ok(result) => result,
            Err(TryRecvError::Empty) => return,
            Err(TryRecvError::Disconnected) => Err("the download stopped unexpectedly".into()),
        };
        self.job = None;
        match result {
            Ok(fetched) => {
                self.open(ctx, file_url(&fetched.index));
                if fetched.version == APP_VERSION {
                    self.note = None;
                    self.notice = false;
                } else {
                    let relation = if version_key(&fetched.version) > version_key(APP_VERSION) { "newer than" } else { "not" };
                    self.note = Some(format!(
                        "This help is for version {}, {relation} this app ({APP_VERSION}): the server no longer has this version's.",
                        fetched.version
                    ));
                    self.notice = true;
                }
                self.phase = Phase::Ready { index: fetched.index, version: fetched.version };
            }
            Err(error) => self.fail(ctx, error),
        }
    }

    /// The online help, for the failure notice.
    pub fn online_url(&self) -> String {
        self.source.as_ref().map(|s| s.online.clone()).unwrap_or_else(|| crate::automation::HELP_URL.to_string())
    }

    /// Draw the notice (bottom right, above the updater's).
    pub fn show(&mut self, ctx: &egui::Context) {
        self.drain(ctx);
        self.hits.clear();
        if !self.notice {
            return;
        }
        enum Act {
            Cancel,
            Online,
            Close,
        }
        let mut act = None;
        let hits = &mut self.hits;
        let (received, total) = self
            .job
            .as_ref()
            .map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
            .unwrap_or((0, 0));
        egui::Area::new(egui::Id::new("brep-help-notice"))
            .anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-12.0, -150.0))
            .order(egui::Order::Foreground)
            .show(ctx, |ui| {
                egui::Frame::popup(ui.style()).show(ui, |ui| {
                    ui.set_max_width(360.0);
                    match &self.phase {
                        Phase::Downloading => {
                            ui.strong("Downloading the help");
                            let mb = |b: u64| b as f64 / 1_000_000.0;
                            let (fraction, text) = if total > 0 {
                                (received as f32 / total as f32, format!("{:.1} of {:.1} MB", mb(received), mb(total)))
                            } else {
                                (0.0, "Asking the server…".to_string())
                            };
                            ui.add(egui::ProgressBar::new(fraction).text(text));
                            ui.label("Once, for this version: later it opens from this computer, offline.");
                            let r = ui.button("Cancel");
                            hits.insert("help:cancel".into(), r.rect);
                            if r.clicked() {
                                act = Some(Act::Cancel);
                            }
                        }
                        Phase::Failed { error } => {
                            ui.strong("The help could not be downloaded");
                            ui.label(error);
                            ui.horizontal(|ui| {
                                let r = ui.button("Open the online help");
                                hits.insert("help:online".into(), r.rect);
                                if r.clicked() {
                                    act = Some(Act::Online);
                                }
                                let r = ui.button("Close");
                                hits.insert("help:close".into(), r.rect);
                                if r.clicked() {
                                    act = Some(Act::Close);
                                }
                            });
                        }
                        Phase::Ready { .. } | Phase::None => {
                            if let Some(note) = &self.note {
                                ui.label(note);
                            }
                            let r = ui.button("Close");
                            hits.insert("help:close".into(), r.rect);
                            if r.clicked() {
                                act = Some(Act::Close);
                            }
                        }
                    }
                });
            });
        match act {
            Some(Act::Cancel) => self.cancel(),
            Some(Act::Online) => {
                let url = self.online_url();
                self.open(ctx, url);
                self.notice = false;
            }
            Some(Act::Close) => self.notice = false,
            None => {}
        }
        if self.job.is_some() {
            ctx.request_repaint_after(Duration::from_millis(200));
        }
    }

    /// `__brepHelp`: `state` none|downloading|ready|failed, the folder, the
    /// opened copy's path and version, progress, the error and the notice.
    pub fn state_json(&self) -> serde_json::Value {
        let (received, total) = self
            .job
            .as_ref()
            .map(|j| (j.progress.received.load(Ordering::Relaxed), j.progress.total.load(Ordering::Relaxed)))
            .unwrap_or((0, 0));
        let (state, path, version, error) = match &self.phase {
            Phase::None => ("none", None, None, None),
            Phase::Downloading => ("downloading", None, None, None),
            Phase::Ready { index, version } => ("ready", Some(index.display().to_string()), Some(version.clone()), None),
            Phase::Failed { error } => ("failed", None, None, Some(error.clone())),
        };
        serde_json::json!({
            "state": state,
            "source": self.source.as_ref().map(|s| s.base.clone()),
            "appVersion": APP_VERSION,
            "dir": self.root.display().to_string(),
            "path": path,
            "version": version,
            "received": received,
            "total": total,
            "error": error,
            "note": self.note,
            "notice": self.notice,
            "opened": self.opened,
        })
    }

    /// `__brepHelpHit`: the notice's buttons (help:cancel, help:online, help:close).
    pub fn hits_json(&self) -> String {
        crate::automation::hit_rects::hits_json(&self.hits)
    }

    /// `help_fixture`: start (or restart) the local test server in `variant`
    /// and point Help at it and at a fresh folder (`keep_dir`: the folder it
    /// had); `stop` it (the app stays pointed at it, now unreachable);
    /// `hold`/`release` the archive halfway.
    #[cfg(feature = "automation")]
    pub fn fixture_action(&mut self, action: &str, variant: Option<&str>, keep_dir: bool) -> Result<serde_json::Value, String> {
        match action {
            "start" => {
                let variant = fixture::Variant::parse(variant.unwrap_or("ok"))?;
                let server = match self.fixture.take() {
                    Some(server) => server.restart(variant)?,
                    None => fixture::FixtureServer::start(variant)?,
                };
                let url = server.url.clone();
                let root = if keep_dir && self.source.is_some() {
                    self.root.clone()
                } else {
                    let dir = std::env::temp_dir().join(format!("brep-help-fixture-{}", uuid::Uuid::new_v4()));
                    self.fixture_dirs.push(dir.clone());
                    dir
                };
                self.configure(Source { base: url.clone(), online: format!("{url}/online/index.html") }, root);
                self.fixture = Some(server);
                Ok(serde_json::json!({ "url": url, "dir": self.root.display().to_string() }))
            }
            "stop" => {
                let server = self.fixture.as_mut().ok_or("no help fixture is running")?;
                server.stop();
                Ok(serde_json::json!({ "stopped": true }))
            }
            "hold" | "release" => {
                let server = self.fixture.as_ref().ok_or("no help fixture is running")?;
                server.set_hold(action == "hold");
                Ok(serde_json::json!({ "hold": action == "hold", "requests": server.requests() }))
            }
            other => Err(format!("`help_fixture` action `{other}`: expected start, stop, hold or release")),
        }
    }
}