perf(harness): run audits on parallel threads

Keep each audit case on its own session. Replay earlier frames at the same
window size before a selected gallery shot. Test the slash menu audit
with two threads.
This commit is contained in:
DarkSky committed 2026-12-02 09:14:07 +09:00
1 parent 2814923c96
commit 56b8204000
6 files changed
+975 -504

No files matched your search

@@ -38,11 +38,14 @@ use playground::{
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use ui::EntityInputHandler;
use ui::{
Application, ApplicationHandle, Bounds, FrameSnapshot, HeadlessPlatform, HeadlessWindow,
WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, point, prelude::*, px, size,
Platform as _, PlatformTextSystem, WindowBounds, WindowHandle, WindowOptions,
audit_frame_snapshot, point, prelude::*, px, size,
};
pub(crate) struct HeadlessSession {
@@ -52,19 +55,34 @@ pub(crate) struct HeadlessSession {
pub(crate) headless_win: HeadlessWindow,
}
thread_local! {
/// The text system that the first session of this thread created and loaded with the
/// bundled fonts. Later sessions of the thread use it again instead of parsing the fonts.
static TEXT_SYSTEM: RefCell<Option<Arc<dyn PlatformTextSystem>>> = const { RefCell::new(None) };
}
pub(crate) fn start_headless_session(
width: u32,
height: u32,
options: PlaygroundOptions,
) -> Result<HeadlessSession> {
let platform = HeadlessPlatform::new(width, height, 1.0);
let text_system = TEXT_SYSTEM.with_borrow(Clone::clone);
let fonts_loaded = text_system.is_some();
let platform = match text_system {
Some(text_system) => {
HeadlessPlatform::new_with_text_system(width, height, 1.0, text_system)
}
None => HeadlessPlatform::new(width, height, 1.0),
};
let init_cell: Rc<RefCell<Option<Result<WindowHandle<PlaygroundView>>>>> =
Rc::new(RefCell::new(None));
let init_out = init_cell.clone();
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
let res = (|| -> Result<WindowHandle<PlaygroundView>> {
register_bundled_fonts(cx).context("registering bundled fonts")?;
if !fonts_loaded {
register_bundled_fonts(cx).context("registering bundled fonts")?;
}
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
@@ -95,6 +113,9 @@ pub(crate) fn start_headless_session(
.into_iter()
.next()
.context("headless window not registered")?;
if !fonts_loaded {
TEXT_SYSTEM.set(Some(platform.text_system()));
}
Ok(HeadlessSession {
platform,
@@ -366,6 +387,62 @@ pub(crate) fn probe_doc<'a>(texts: impl IntoIterator<Item = &'a str>) -> Result<
Ok(doc)
}
/// Worker threads for the audit commands: the available cores, at most 4, so that memory
/// stays bounded and the workers do not queue on the shared headless GPU device.
fn default_jobs() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.min(4)
}
/// Runs `work` on every item across `jobs` threads and returns the results in item order,
/// whichever worker finishes first. Each worker keeps its own text system for its items.
pub(crate) fn run_in_order<T: Sync, R: Send>(
items: &[T],
jobs: usize,
work: impl Fn(&T) -> R + Sync,
) -> Vec<R> {
if jobs <= 1 {
return items.iter().map(work).collect();
}
let next = AtomicUsize::new(0);
let mut results: Vec<Option<R>> = items.iter().map(|_| None).collect();
std::thread::scope(|scope| {
let workers: Vec<_> = (0..jobs.min(items.len()))
.map(|index| {
std::thread::Builder::new()
.name(format!("bs-harness-{index}"))
// The same stack as the main thread, which ran these items before.
.stack_size(8 << 20)
.spawn_scoped(scope, || {
let mut done = Vec::new();
loop {
let index = next.fetch_add(1, Ordering::Relaxed);
let Some(item) = items.get(index) else {
return done;
};
done.push((index, work(item)));
}
})
.expect("spawning a harness worker thread")
})
.collect();
for worker in workers {
let done = worker
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
for (index, result) in done {
results[index] = Some(result);
}
}
});
results
.into_iter()
.map(|result| result.expect("every item has a result"))
.collect()
}
pub(crate) fn run_audit(snapshot_path: PathBuf) -> Result<()> {
let raw = std::fs::read_to_string(&snapshot_path)
.with_context(|| format!("reading snapshot {}", snapshot_path.display()))?;
@@ -597,7 +674,27 @@ fn main() -> Result<()> {
record_demo(dir.into(), theme)
}
"probes" => run_probes(),
"audit-states" => run_audit_states(),
"audit-states" => {
let mut jobs = default_jobs();
let mut only = None;
let mut snapshots = None;
while let Some(arg) = args.next() {
match arg.as_str() {
"--jobs" => {
jobs = args.next().context("--jobs requires a count")?.parse()?;
anyhow::ensure!(jobs >= 1, "--jobs must be at least 1");
}
"--only" => only = Some(args.next().context("--only requires a pattern")?),
"--snapshots" => {
snapshots = Some(PathBuf::from(
args.next().context("--snapshots requires a directory")?,
))
}
other => bail!("unknown audit-states flag: {other}"),
}
}
run_audit_states(jobs, only.as_deref(), snapshots.as_deref())
}
"fps-check" => run_fps_check(),
"bench" => {
let mut out_json = PathBuf::from("perf-metrics.json");
@@ -642,7 +739,12 @@ mod tests {
#[test]
fn every_overlay_state_audits_clean_in_both_themes_and_on_a_narrow_window() {
run_audit_states().unwrap();
run_audit_states(1, None, None).unwrap();
}
#[test]
fn slash_menu_open_audits_clean_on_two_threads() {
run_audit_states(2, Some("slash_menu_open"), None).unwrap();
}
#[test]
@@ -502,107 +502,168 @@ pub(super) fn apply_overlay_state(session: &HeadlessSession, state: OverlayState
}
/// Audit every overlay state in both themes on a regular and a narrow window.
pub(super) fn run_audit_states() -> Result<()> {
let mut audited = 0_usize;
/// What one audited state shows: an overlay state in Page or Edgeless mode, or the
/// Edgeless canvas at a fixed zoom.
#[derive(Clone, Copy)]
enum AuditView {
Page(OverlayState),
EdgelessZoom(&'static str, Option<f32>),
Edgeless(OverlayState),
}
#[derive(Clone, Copy)]
struct AuditCase {
width: u32,
height: u32,
theme: PlaygroundTheme,
view: AuditView,
}
impl AuditCase {
fn context(&self) -> String {
let name = match self.view {
AuditView::Page(state) | AuditView::Edgeless(state) => state.name(),
AuditView::EdgelessZoom(label, _) => label,
};
format!(
"{name} {}x{} {}",
self.width,
self.height,
self.theme.as_str()
)
}
}
/// Every audited state, in the order of the report.
fn audit_cases() -> Vec<AuditCase> {
let mut cases = Vec::new();
for (width, height) in [(1280_u32, 800_u32), (320, 800)] {
for theme in [PlaygroundTheme::Light, PlaygroundTheme::Dark] {
for state in OverlayState::ALL {
let context = format!("{} {width}x{height} {}", state.name(), theme.as_str());
let session = start_headless_session(
width,
height,
PlaygroundOptions {
theme,
..PlaygroundOptions::default()
},
)?;
apply_overlay_state(&session, state).with_context(|| context.clone())?;
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
let views = OverlayState::ALL
.iter()
.map(|&state| AuditView::Page(state))
// Edgeless default and zoomed states (0.5x, 2.0x).
.chain([
AuditView::EdgelessZoom("edgeless_default", None),
AuditView::EdgelessZoom("edgeless_zoom_0.5x", Some(0.5)),
AuditView::EdgelessZoom("edgeless_zoom_2.0x", Some(2.0)),
])
// Edgeless interactive authoring states.
.chain(
OverlayState::ALL_EDGELESS
.iter()
.map(|&state| AuditView::Edgeless(state)),
);
// Nothing an overlay draws leaves the window.
for (id, element) in &snapshot.elements {
if id.starts_with("overlay.") {
anyhow::ensure!(
element.bounds.x >= 0.0
&& element.bounds.y >= 0.0
&& element.bounds.right() <= snapshot.viewport.width
&& element.bounds.bottom() <= snapshot.viewport.height,
"{id} leaves the window in {context}: {:?}",
element.bounds
);
}
}
audited += 1;
}
cases.extend(views.map(|view| AuditCase {
width,
height,
theme,
view,
}));
}
}
cases
}
// Audit Edgeless default + zoomed states (0.5x, 2.0x) in both themes and widths.
for (label, zoom_opt) in [
("edgeless_default", None),
("edgeless_zoom_0.5x", Some(0.5_f32)),
("edgeless_zoom_2.0x", Some(2.0_f32)),
] {
let context = format!("{label} {width}x{height} {}", theme.as_str());
let session = start_headless_session(
width,
height,
PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
)?;
let _ = session.frame()?;
if let Some(z) = zoom_opt {
session.update(|v, _, cx| v.set_edgeless_zoom(z, cx))?;
}
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
);
anyhow::ensure!(
snapshot.elements.contains_key("edgeless.viewport"),
"edgeless.viewport missing in {context}"
);
anyhow::ensure!(
snapshot.elements.contains_key("chrome.edgeless_zoom"),
"chrome.edgeless_zoom missing in {context}"
);
anyhow::ensure!(
snapshot.elements.contains_key("chrome.edgeless_toolbar"),
"chrome.edgeless_toolbar missing in {context}"
);
audited += 1;
}
// Audit Edgeless interactive authoring states in both themes and widths.
for state in OverlayState::ALL_EDGELESS {
let context = format!("{} {width}x{height} {}", state.name(), theme.as_str());
let session = start_headless_session(
width,
height,
PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
)?;
apply_overlay_state(&session, state).with_context(|| context.clone())?;
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
);
audited += 1;
/// Starts a session in `case`, checks its frame, and returns the frame.
fn audit_case(case: &AuditCase) -> Result<FrameSnapshot> {
let context = case.context();
let mode = match case.view {
AuditView::Page(_) => PlaygroundMode::Page,
AuditView::EdgelessZoom(..) | AuditView::Edgeless(_) => PlaygroundMode::Edgeless,
};
let session = start_headless_session(
case.width,
case.height,
PlaygroundOptions {
theme: case.theme,
mode,
..PlaygroundOptions::default()
},
)?;
match case.view {
AuditView::Page(state) | AuditView::Edgeless(state) => {
apply_overlay_state(&session, state).with_context(|| context.clone())?;
}
AuditView::EdgelessZoom(_, zoom) => {
let _ = session.frame()?;
if let Some(z) = zoom {
session.update(|v, _, cx| v.set_edgeless_zoom(z, cx))?;
}
}
}
println!("audit-states passed: 0 violations across {audited} states");
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
);
match case.view {
AuditView::Page(_) => {
// Nothing an overlay draws leaves the window.
for (id, element) in &snapshot.elements {
if id.starts_with("overlay.") {
anyhow::ensure!(
element.bounds.x >= 0.0
&& element.bounds.y >= 0.0
&& element.bounds.right() <= snapshot.viewport.width
&& element.bounds.bottom() <= snapshot.viewport.height,
"{id} leaves the window in {context}: {:?}",
element.bounds
);
}
}
}
AuditView::EdgelessZoom(..) => {
for id in [
"edgeless.viewport",
"chrome.edgeless_zoom",
"chrome.edgeless_toolbar",
] {
anyhow::ensure!(
snapshot.elements.contains_key(id),
"{id} missing in {context}"
);
}
}
AuditView::Edgeless(_) => {}
}
Ok(snapshot)
}
/// Audits every state whose context contains `only` (all states without it) on `jobs`
/// threads. With `snapshots`, writes the frame of each state there as JSON.
pub(super) fn run_audit_states(
jobs: usize,
only: Option<&str>,
snapshots: Option<&std::path::Path>,
) -> Result<()> {
let mut cases = audit_cases();
if let Some(pattern) = only {
let total = cases.len();
cases.retain(|case| case.context().contains(pattern));
anyhow::ensure!(
!cases.is_empty(),
"--only {pattern:?} matches none of the {total} audit states"
);
}
if let Some(dir) = snapshots {
std::fs::create_dir_all(dir)
.with_context(|| format!("creating snapshot directory {}", dir.display()))?;
}
for (case, snapshot) in cases.iter().zip(run_in_order(&cases, jobs, audit_case)) {
let snapshot = snapshot?;
if let Some(dir) = snapshots {
let name = case.context().replace(' ', "_");
std::fs::write(
dir.join(format!("{name}.json")),
serde_json::to_string_pretty(&snapshot)?,
)?;
}
}
println!(
"audit-states passed: 0 violations across {} states",
cases.len()
);
Ok(())
}
@@ -0,0 +1,369 @@
//! `mobile-harness audit-matrix`: the frame audit, touch targets, accessibility tree, and
//! breadcrumb checks of every viewport, theme, and locale, plus the 1.35x font scale.
use std::path::Path;
use affine_client::{AccessibilityRole, DirectKind, Origin};
use affine_mobile::{
MobileAppState, MobileLocale, MobileSheet, MobileTab, build_accessibility_tree,
seed_showcase_state, validate_accessibility_tree,
};
use anyhow::{Result, bail};
use serde_json::json;
use ui::{Direction, FrameSnapshot, audit_frame_snapshot};
use ui_kit::{BreadcrumbBarConfig, BreadcrumbItem, BreadcrumbItemKind, layout_breadcrumb_bar};
use ui_tokens::ThemeMode;
use super::{VIEWPORTS, open_doclink_multi, run_in_order, select_only, start_session};
fn check_snapshot_bounds(
snapshot: &FrameSnapshot,
vp_w: f32,
vp_h: f32,
context: &str,
) -> Vec<String> {
let mut violations = Vec::new();
for v in audit_frame_snapshot(snapshot) {
violations.push(format!("{context}: frame-audit {v:?}"));
}
for (id, el) in &snapshot.elements {
let b = &el.bounds;
if b.x < -0.5 || b.y < -0.5 || b.x + b.width > vp_w + 0.5 || b.y + b.height > vp_h + 0.5 {
violations.push(format!(
"{context}: element {id} out of bounds ({:.1},{:.1},{:.1}x{:.1}) in {vp_w}x{vp_h}",
b.x, b.y, b.width, b.height
));
}
let is_touch_control = id.contains(".btn")
|| id.contains("_btn")
|| id.starts_with("mobile.tab.")
|| id.starts_with("mobile.journals.day.")
|| id.starts_with("mobile.settings.row.")
|| id == "mobile.page.backlinks_pill"
|| id == "mobile.page.breadcrumb_bar";
if is_touch_control && (b.height < 43.5 || b.width < 43.5) {
violations.push(format!(
"{context}: touch target {id} size {:.1}x{:.1} < 44x44pt",
b.width, b.height
));
}
}
violations
}
fn check_doclink_switcher(
snap: &FrameSnapshot,
tree: &affine_client::AccessibilityTree,
measured_bc: Option<&ui_kit::BreadcrumbBarLayout>,
locale: MobileLocale,
ctx: &str,
violations: &mut Vec<String>,
) {
if snap
.elements
.contains_key("mobile.page.breadcrumb.slot.breadcrumb.ellipsis")
{
violations.push(format!(
"{ctx}: doclink multi-location switcher degraded to bare ellipsis"
));
}
let ok = tree
.nodes
.get("app.nav.breadcrumb")
.and_then(|nav| nav.children.first())
.and_then(|id| tree.nodes.get(id))
.is_some_and(|n| {
n.id != "breadcrumb.slot.breadcrumb.ellipsis"
&& n.role == AccessibilityRole::Link
&& n.state.expanded.is_some()
});
if !ok {
violations.push(format!(
"{ctx}: expected Switcher as first breadcrumb slot in accessibility tree"
));
}
let expected_unit = match locale {
MobileLocale::En | MobileLocale::RtlFallback => "2 places",
MobileLocale::ZhHans => "2 处",
MobileLocale::Ar => "2 مواقع",
};
match measured_bc.and_then(|bc| bc.slots.first()) {
Some(slot) if slot.kind == ui_kit::BreadcrumbSlotKind::Switcher => {
let text = slot
.display_text
.trim_matches(|c| c == ui_kit::BIDI_FSI || c == ui_kit::BIDI_PDI);
let has_unit = text.contains(expected_unit);
let has_owner_prefix = text.rsplit_once(" · ").is_some_and(|(prefix, _)| {
!prefix
.trim_matches(|c: char| c.is_whitespace() || c == '…')
.is_empty()
});
if !has_unit || !has_owner_prefix {
violations.push(format!(
"{ctx}: switcher text `{text}` must preserve owner prefix and `{expected_unit}`"
));
}
}
_ => violations.push(format!("{ctx}: missing measured Switcher slot")),
}
}
/// One unit of `audit-matrix`, in the order of the report.
#[derive(Clone, Copy)]
enum MatrixCase {
/// RTL mirror symmetry of the breadcrumb bar at one viewport width.
Mirror { vp: (u32, u32) },
/// The nine routes of one viewport, theme and locale.
Routes {
vp: (u32, u32),
theme: ThemeMode,
locale: MobileLocale,
},
/// The 1.35x dynamic font scale on the narrowest 320x568 viewport.
FontScale { locale: MobileLocale },
}
impl MatrixCase {
fn tag(&self) -> String {
match *self {
Self::Mirror { vp: (w, h) } => format!("{w}x{h}/rtl_mirror"),
Self::Routes {
vp: (w, h),
theme,
locale,
} => format!("{w}x{h}/{theme:?}/{}", locale.code()),
Self::FontScale { locale } => format!("320x568@1.35x/Light/{}", locale.code()),
}
}
}
fn matrix_cases() -> Vec<MatrixCase> {
let mut cases = Vec::new();
for vp in VIEWPORTS {
cases.push(MatrixCase::Mirror { vp });
for theme in [ThemeMode::Light, ThemeMode::Dark] {
for locale in MobileLocale::ALL {
cases.push(MatrixCase::Routes { vp, theme, locale });
}
}
}
cases.extend(
MobileLocale::ALL
.into_iter()
.map(|locale| MatrixCase::FontScale { locale }),
);
cases
}
fn write_snapshot(dir: Option<&Path>, ctx: &str, snap: &FrameSnapshot) -> Result<()> {
if let Some(dir) = dir {
let name: String = ctx
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '.' || c == '@' {
c
} else {
'_'
}
})
.collect();
std::fs::write(
dir.join(format!("{name}.json")),
serde_json::to_string_pretty(snap)?,
)?;
}
Ok(())
}
/// The violations and the number of audited frames of one case.
fn audit_case(case: &MatrixCase, snapshots: Option<&Path>) -> Result<(Vec<String>, usize)> {
let mut violations = Vec::new();
let mut frames = 0usize;
let tag_prefix = case.tag();
match *case {
MatrixCase::Mirror { vp: (vp_w, vp_h) } => {
let sample_bc_items = [
("f-eng", "Engineering", BreadcrumbItemKind::Segment, true),
("f-mob", "Mobile", BreadcrumbItemKind::Segment, true),
("doc-arch", "Spec", BreadcrumbItemKind::Current, false),
]
.map(|(id, label, kind, clickable)| BreadcrumbItem {
id: id.into(),
label: label.into(),
kind,
clickable,
});
let ltr = layout_breadcrumb_bar(
&sample_bc_items,
&BreadcrumbBarConfig::new(vp_w as f32, Direction::Ltr),
);
let rtl = layout_breadcrumb_bar(
&sample_bc_items,
&BreadcrumbBarConfig::new(vp_w as f32, Direction::Rtl),
);
for (l, r) in ltr.slots.iter().zip(rtl.slots.iter()) {
if ((r.x + r.width) - (vp_w as f32 - l.x)).abs() > 1e-3 {
violations.push(format!(
"RTL mirror violation at {vp_w}x{vp_h} for slot {}",
l.id
));
}
}
}
MatrixCase::Routes {
vp: (vp_w, vp_h),
theme,
locale,
} => {
let state = seed_showcase_state(locale, theme, "2026-11-25");
let session = start_session(vp_w, vp_h, 1.0, state)?;
let routes: [(&str, Box<dyn Fn(&mut MobileAppState)>); 9] = [
("home", Box::new(|s| s.switch_tab(MobileTab::Home, 0.0))),
(
"explorer",
Box::new(|s| s.switch_tab(MobileTab::Explorer, 50.0)),
),
(
"journals",
Box::new(|s| s.switch_tab(MobileTab::Journals, 75.0)),
),
(
"page_multi",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
}),
),
("page_doclink_multi", Box::new(open_doclink_multi)),
(
"page_trash",
Box::new(|s| {
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
}),
),
(
"location_sheet",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::LocationAndTrail, 100.0);
s.settle_animations(500.0);
}),
),
(
"search",
Box::new(|s| {
s.close_sheet(600.0);
s.settle_animations(1000.0);
s.switch_tab(MobileTab::Search, 1000.0);
}),
),
("settings", Box::new(|s| s.open_settings())),
];
for (route_name, setup) in &routes {
session.update_state(|s| setup(s))?;
let snap = session.frame()?;
frames += 1;
let ctx = format!("{tag_prefix}/{route_name}");
write_snapshot(snapshots, &ctx, &snap)?;
violations.extend(check_snapshot_bounds(&snap, vp_w as f32, vp_h as f32, &ctx));
let (a11y_errors, tree) = session.update_state(|s| {
let tree = build_accessibility_tree(s, vp_w as f32, vp_h as f32);
let errs = validate_accessibility_tree(&tree);
(errs, tree)
})?;
if *route_name == "page_doclink_multi" {
let measured_bc = session.measured_breadcrumb()?;
check_doclink_switcher(
&snap,
&tree,
measured_bc.as_ref(),
locale,
&ctx,
&mut violations,
);
}
for err in a11y_errors {
violations.push(format!("{ctx}: a11y {err}"));
}
}
}
MatrixCase::FontScale { locale } => {
let mut state = seed_showcase_state(locale, ThemeMode::Light, "2026-11-25");
state.font_scale = 1.35;
let session = start_session(320, 568, 1.0, state)?;
for route_name in ["page_multi", "page_doclink_multi", "location_sheet"] {
session.update_state(|s| match route_name {
"page_doclink_multi" => open_doclink_multi(s),
"location_sheet" => {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::LocationAndTrail, 100.0);
s.settle_animations(500.0);
}
_ => s.open_doc("doc-arch", Origin::Direct(DirectKind::Home)),
})?;
let snap = session.frame()?;
frames += 1;
let ctx = format!("{tag_prefix}/{route_name}");
write_snapshot(snapshots, &ctx, &snap)?;
violations.extend(check_snapshot_bounds(&snap, 320.0, 568.0, &ctx));
if route_name == "page_doclink_multi" {
let tree =
session.update_state(|s| build_accessibility_tree(s, 320.0, 568.0))?;
let measured_bc = session.measured_breadcrumb()?;
check_doclink_switcher(
&snap,
&tree,
measured_bc.as_ref(),
locale,
&ctx,
&mut violations,
);
}
}
}
}
Ok((violations, frames))
}
/// Audits every case whose tag contains `only` (all cases without it) on `jobs` threads.
/// With `snapshots`, writes the frame of each route there as JSON.
pub(super) fn run_audit_matrix(
jobs: usize,
only: Option<&str>,
snapshots: Option<&Path>,
) -> Result<()> {
let mut cases = matrix_cases();
select_only(&mut cases, only, MatrixCase::tag)?;
if let Some(dir) = snapshots {
std::fs::create_dir_all(dir)?;
}
let mut all_violations: Vec<String> = Vec::new();
let mut states_audited = 0usize;
let mut frames_audited = 0usize;
for (case, result) in cases.iter().zip(run_in_order(&cases, jobs, |case| {
audit_case(case, snapshots)
})) {
let (violations, frames) = result?;
if !matches!(case, MatrixCase::Mirror { .. }) {
states_audited += 1;
}
frames_audited += frames;
all_violations.extend(violations);
}
let report = json!({
"states_audited": states_audited,
"frames_audited": frames_audited,
"violations": all_violations.len(),
"details": all_violations,
});
println!("{}", serde_json::to_string_pretty(&report)?);
if !all_violations.is_empty() {
bail!(
"audit-matrix failed with {} violations",
all_violations.len()
);
}
Ok(())
}
@@ -5,25 +5,32 @@
//! - `scale-probe [--json <path>] [--png <dir>]`: 10 / 100 / 1,000-document frame costs and
//! work counters, or 1,000-document list PNGs
mod audit_matrix;
mod scale;
mod shell_gallery;
use std::{cell::RefCell, path::PathBuf, rc::Rc, time::Duration};
use std::{
cell::RefCell,
path::{Path, PathBuf},
rc::Rc,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use affine_client::{AccessibilityRole, DirectKind, Origin};
use affine_client::{DirectKind, Origin};
use affine_mobile::{
BackOutcome, MobileAppState, MobileBackCoordinator, MobileLocale, MobileSheet, MobileShellView,
MobileTab, build_accessibility_tree, register_mobile_fonts, seed_showcase_state,
validate_accessibility_tree,
MobileTab, register_mobile_fonts, seed_showcase_state,
};
use anyhow::{Context as _, Result, bail};
use serde_json::json;
use ui::{
Application, ApplicationHandle, Bounds, Direction, FrameSnapshot, HeadlessPlatform,
HeadlessWindow, WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, point,
Application, ApplicationHandle, Bounds, FrameSnapshot, HeadlessPlatform, HeadlessWindow,
Platform as _, PlatformTextSystem, WindowBounds, WindowHandle, WindowOptions, point,
prelude::*, px, size,
};
use ui_kit::{BreadcrumbBarConfig, BreadcrumbItem, BreadcrumbItemKind, layout_breadcrumb_bar};
use ui_tokens::ThemeMode;
const VIEWPORTS: [(u32, u32); 6] = [
@@ -43,13 +50,26 @@ pub(crate) struct MobileSession {
headless_win: HeadlessWindow,
}
thread_local! {
/// The text system that the first session of this thread created and loaded with the
/// mobile fonts. Later sessions of the thread use it again instead of parsing the fonts.
static TEXT_SYSTEM: RefCell<Option<Arc<dyn PlatformTextSystem>>> = const { RefCell::new(None) };
}
pub(crate) fn start_session(
width: u32,
height: u32,
scale_factor: f32,
state: MobileAppState,
) -> Result<MobileSession> {
let platform = HeadlessPlatform::new(width, height, scale_factor);
let text_system = TEXT_SYSTEM.with_borrow(Clone::clone);
let fonts_loaded = text_system.is_some();
let platform = match text_system {
Some(text_system) => {
HeadlessPlatform::new_with_text_system(width, height, scale_factor, text_system)
}
None => HeadlessPlatform::new(width, height, scale_factor),
};
let init_cell: Rc<RefCell<Option<Result<WindowHandle<MobileShellView>>>>> =
Rc::new(RefCell::new(None));
let init_out = init_cell.clone();
@@ -57,7 +77,9 @@ pub(crate) fn start_session(
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
let res = (|| -> Result<WindowHandle<MobileShellView>> {
register_mobile_fonts(cx).context("registering mobile fonts")?;
if !fonts_loaded {
register_mobile_fonts(cx).context("registering mobile fonts")?;
}
let initial_state = state_cell
.borrow_mut()
.take()
@@ -86,6 +108,9 @@ pub(crate) fn start_session(
.into_iter()
.next()
.context("headless window not registered")?;
if !fonts_loaded {
TEXT_SYSTEM.set(Some(platform.text_system()));
}
Ok(MobileSession {
platform,
@@ -128,7 +153,9 @@ impl MobileSession {
})
}
pub(crate) fn render_png(&self, out_path: &PathBuf) -> Result<usize> {
/// Renders the window into a PNG at `out_path`. With `fast_png`, the encoder uses the
/// `Sub` filter instead of the default adaptive one: same pixels, larger file.
pub(crate) fn render_png(&self, out_path: &Path, fast_png: bool) -> Result<usize> {
self.headless_win.request_frame();
let (image, glyph_count) = self.app.update(|cx| {
self.window_handle.update(cx, |_, window, _| {
@@ -147,48 +174,26 @@ impl MobileSession {
{
std::fs::create_dir_all(parent)?;
}
image
.save(out_path)
.with_context(|| format!("writing PNG {}", out_path.display()))?;
let written = if fast_png {
std::fs::File::create(out_path)
.map_err(anyhow::Error::from)
.and_then(|file| {
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
let encoder = PngEncoder::new_with_quality(
std::io::BufWriter::new(file),
CompressionType::Fast,
FilterType::Sub,
);
Ok(image.write_with_encoder(encoder)?)
})
} else {
image.save(out_path).map_err(anyhow::Error::from)
};
written.with_context(|| format!("writing PNG {}", out_path.display()))?;
Ok(glyph_count)
}
}
fn check_snapshot_bounds(
snapshot: &FrameSnapshot,
vp_w: f32,
vp_h: f32,
context: &str,
) -> Vec<String> {
let mut violations = Vec::new();
for v in audit_frame_snapshot(snapshot) {
violations.push(format!("{context}: frame-audit {v:?}"));
}
for (id, el) in &snapshot.elements {
let b = &el.bounds;
if b.x < -0.5 || b.y < -0.5 || b.x + b.width > vp_w + 0.5 || b.y + b.height > vp_h + 0.5 {
violations.push(format!(
"{context}: element {id} out of bounds ({:.1},{:.1},{:.1}x{:.1}) in {vp_w}x{vp_h}",
b.x, b.y, b.width, b.height
));
}
let is_touch_control = id.contains(".btn")
|| id.contains("_btn")
|| id.starts_with("mobile.tab.")
|| id.starts_with("mobile.journals.day.")
|| id.starts_with("mobile.settings.row.")
|| id == "mobile.page.backlinks_pill"
|| id == "mobile.page.breadcrumb_bar";
if is_touch_control && (b.height < 43.5 || b.width < 43.5) {
violations.push(format!(
"{context}: touch target {id} size {:.1}x{:.1} < 44x44pt",
b.width, b.height
));
}
}
violations
}
fn current_seq(s: &MobileAppState) -> u64 {
s.active_workspace().history.current().map_or(1, |e| e.seq)
}
@@ -205,238 +210,75 @@ pub(crate) fn open_doclink_multi(s: &mut MobileAppState) {
);
}
fn check_doclink_switcher(
snap: &FrameSnapshot,
tree: &affine_client::AccessibilityTree,
measured_bc: Option<&ui_kit::BreadcrumbBarLayout>,
locale: MobileLocale,
ctx: &str,
violations: &mut Vec<String>,
) {
if snap
.elements
.contains_key("mobile.page.breadcrumb.slot.breadcrumb.ellipsis")
{
violations.push(format!(
"{ctx}: doclink multi-location switcher degraded to bare ellipsis"
));
}
let ok = tree
.nodes
.get("app.nav.breadcrumb")
.and_then(|nav| nav.children.first())
.and_then(|id| tree.nodes.get(id))
.is_some_and(|n| {
n.id != "breadcrumb.slot.breadcrumb.ellipsis"
&& n.role == AccessibilityRole::Link
&& n.state.expanded.is_some()
});
if !ok {
violations.push(format!(
"{ctx}: expected Switcher as first breadcrumb slot in accessibility tree"
));
}
let expected_unit = match locale {
MobileLocale::En | MobileLocale::RtlFallback => "2 places",
MobileLocale::ZhHans => "2 处",
MobileLocale::Ar => "2 مواقع",
};
match measured_bc.and_then(|bc| bc.slots.first()) {
Some(slot) if slot.kind == ui_kit::BreadcrumbSlotKind::Switcher => {
let text = slot
.display_text
.trim_matches(|c| c == ui_kit::BIDI_FSI || c == ui_kit::BIDI_PDI);
let has_unit = text.contains(expected_unit);
let has_owner_prefix = text.rsplit_once(" · ").is_some_and(|(prefix, _)| {
!prefix
.trim_matches(|c: char| c.is_whitespace() || c == '…')
.is_empty()
});
if !has_unit || !has_owner_prefix {
violations.push(format!(
"{ctx}: switcher text `{text}` must preserve owner prefix and `{expected_unit}`"
));
}
}
_ => violations.push(format!("{ctx}: missing measured Switcher slot")),
}
/// Worker threads for the audit and gallery commands: the available cores, at most 4, so
/// that memory stays bounded and the workers do not queue on the shared headless GPU device.
fn default_jobs() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.min(4)
}
fn run_audit_matrix() -> Result<()> {
let mut all_violations: Vec<String> = Vec::new();
let mut states_audited = 0usize;
let mut frames_audited = 0usize;
let sample_bc_items = vec![
BreadcrumbItem {
id: "f-eng".into(),
label: "Engineering".into(),
kind: BreadcrumbItemKind::Segment,
clickable: true,
},
BreadcrumbItem {
id: "f-mob".into(),
label: "Mobile".into(),
kind: BreadcrumbItemKind::Segment,
clickable: true,
},
BreadcrumbItem {
id: "doc-arch".into(),
label: "Spec".into(),
kind: BreadcrumbItemKind::Current,
clickable: false,
},
];
for (vp_w, vp_h) in VIEWPORTS {
// Verify RTL mirror symmetry for this viewport width.
let ltr = layout_breadcrumb_bar(
&sample_bc_items,
&BreadcrumbBarConfig::new(vp_w as f32, Direction::Ltr),
);
let rtl = layout_breadcrumb_bar(
&sample_bc_items,
&BreadcrumbBarConfig::new(vp_w as f32, Direction::Rtl),
);
for (l, r) in ltr.slots.iter().zip(rtl.slots.iter()) {
if ((r.x + r.width) - (vp_w as f32 - l.x)).abs() > 1e-3 {
all_violations.push(format!(
"RTL mirror violation at {vp_w}x{vp_h} for slot {}",
l.id
));
}
}
for theme in [ThemeMode::Light, ThemeMode::Dark] {
for locale in MobileLocale::ALL {
states_audited += 1;
let state = seed_showcase_state(locale, theme, "2026-11-25");
let session = start_session(vp_w, vp_h, 1.0, state)?;
let tag_prefix = format!("{vp_w}x{vp_h}/{:?}/{}", theme, locale.code());
let routes: [(&str, Box<dyn Fn(&mut MobileAppState)>); 9] = [
("home", Box::new(|s| s.switch_tab(MobileTab::Home, 0.0))),
(
"explorer",
Box::new(|s| s.switch_tab(MobileTab::Explorer, 50.0)),
),
(
"journals",
Box::new(|s| s.switch_tab(MobileTab::Journals, 75.0)),
),
(
"page_multi",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
}),
),
("page_doclink_multi", Box::new(open_doclink_multi)),
(
"page_trash",
Box::new(|s| {
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
}),
),
(
"location_sheet",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::LocationAndTrail, 100.0);
s.settle_animations(500.0);
}),
),
(
"search",
Box::new(|s| {
s.close_sheet(600.0);
s.settle_animations(1000.0);
s.switch_tab(MobileTab::Search, 1000.0);
}),
),
("settings", Box::new(|s| s.open_settings())),
];
for (route_name, setup) in &routes {
session.update_state(|s| setup(s))?;
let snap = session.frame()?;
frames_audited += 1;
let ctx = format!("{tag_prefix}/{route_name}");
all_violations.extend(check_snapshot_bounds(
&snap,
vp_w as f32,
vp_h as f32,
&ctx,
));
let (a11y_errors, tree) = session.update_state(|s| {
let tree = build_accessibility_tree(s, vp_w as f32, vp_h as f32);
let errs = validate_accessibility_tree(&tree);
(errs, tree)
})?;
if *route_name == "page_doclink_multi" {
let measured_bc = session.measured_breadcrumb()?;
check_doclink_switcher(
&snap,
&tree,
measured_bc.as_ref(),
locale,
&ctx,
&mut all_violations,
);
}
for err in a11y_errors {
all_violations.push(format!("{ctx}: a11y {err}"));
}
}
}
}
/// Runs `work` on every item across `jobs` threads and returns the results in item order,
/// whichever worker finishes first. Each worker keeps its own text system for its items.
pub(crate) fn run_in_order<T: Sync, R: Send>(
items: &[T],
jobs: usize,
work: impl Fn(&T) -> R + Sync,
) -> Vec<R> {
if jobs <= 1 {
return items.iter().map(work).collect();
}
// Extra 1.35x dynamic font-scale audit on the narrowest 320x568 viewport across all 3 locales.
for locale in MobileLocale::ALL {
states_audited += 1;
let mut state = seed_showcase_state(locale, ThemeMode::Light, "2026-11-25");
state.font_scale = 1.35;
let session = start_session(320, 568, 1.0, state)?;
for route_name in ["page_multi", "page_doclink_multi", "location_sheet"] {
session.update_state(|s| match route_name {
"page_doclink_multi" => open_doclink_multi(s),
"location_sheet" => {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::LocationAndTrail, 100.0);
s.settle_animations(500.0);
}
_ => s.open_doc("doc-arch", Origin::Direct(DirectKind::Home)),
})?;
let snap = session.frame()?;
frames_audited += 1;
let ctx = format!("320x568@1.35x/Light/{}/{route_name}", locale.code());
all_violations.extend(check_snapshot_bounds(&snap, 320.0, 568.0, &ctx));
if route_name == "page_doclink_multi" {
let tree = session.update_state(|s| build_accessibility_tree(s, 320.0, 568.0))?;
let measured_bc = session.measured_breadcrumb()?;
check_doclink_switcher(
&snap,
&tree,
measured_bc.as_ref(),
locale,
&ctx,
&mut all_violations,
);
let next = AtomicUsize::new(0);
let mut results: Vec<Option<R>> = items.iter().map(|_| None).collect();
std::thread::scope(|scope| {
let workers: Vec<_> = (0..jobs.min(items.len()))
.map(|index| {
std::thread::Builder::new()
.name(format!("mobile-harness-{index}"))
// The same stack as the main thread, which ran these items before.
.stack_size(8 << 20)
.spawn_scoped(scope, || {
let mut done = Vec::new();
loop {
let index = next.fetch_add(1, Ordering::Relaxed);
let Some(item) = items.get(index) else {
return done;
};
done.push((index, work(item)));
}
})
.expect("spawning a harness worker thread")
})
.collect();
for worker in workers {
let done = worker
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
for (index, result) in done {
results[index] = Some(result);
}
}
}
let report = json!({
"states_audited": states_audited,
"frames_audited": frames_audited,
"violations": all_violations.len(),
"details": all_violations,
});
println!("{}", serde_json::to_string_pretty(&report)?);
if !all_violations.is_empty() {
bail!(
"audit-matrix failed with {} violations",
all_violations.len()
results
.into_iter()
.map(|result| result.expect("every item has a result"))
.collect()
}
/// Keeps the items whose name contains `only` (all items without it), and fails when no
/// item is left, so that a misspelt pattern cannot pass with nothing checked.
pub(crate) fn select_only<T>(
items: &mut Vec<T>,
only: Option<&str>,
name: impl Fn(&T) -> String,
) -> Result<()> {
if let Some(pattern) = only {
let total = items.len();
items.retain(|item| name(item).contains(pattern));
anyhow::ensure!(
!items.is_empty(),
"--only {pattern:?} matches none of the {total} items"
);
}
Ok(())
@@ -589,23 +431,48 @@ fn run_fps_replay() -> Result<()> {
Ok(())
}
pub(crate) fn parse_jobs(value: Option<String>) -> Result<usize> {
let jobs: usize = value.context("--jobs requires a count")?.parse()?;
anyhow::ensure!(jobs >= 1, "--jobs must be at least 1");
Ok(jobs)
}
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let Some(cmd) = args.next() else {
bail!(
"usage: mobile-harness <audit-matrix | fps-replay | gallery | shell-gallery --out <dir> | scale-probe [--json <path>] [--png <dir>]>"
"usage: mobile-harness <audit-matrix [--jobs <n>] [--only <pattern>] [--snapshots <dir>] | fps-replay | gallery [--out <dir>] [--fast-png] | shell-gallery [--out <dir>] [--jobs <n>] [--only <pattern>] [--fast-png] | scale-probe [--json <path>] [--png <dir>]>"
);
};
match cmd.as_str() {
"audit-matrix" => run_audit_matrix(),
"audit-matrix" => {
let mut jobs = default_jobs();
let mut only = None;
let mut snapshots = None;
while let Some(arg) = args.next() {
match arg.as_str() {
"--jobs" => jobs = parse_jobs(args.next())?,
"--only" => only = Some(args.next().context("--only requires a pattern")?),
"--snapshots" => {
snapshots = Some(PathBuf::from(
args.next().context("--snapshots requires a directory")?,
))
}
other => bail!("unknown audit-matrix flag `{other}`"),
}
}
audit_matrix::run_audit_matrix(jobs, only.as_deref(), snapshots.as_deref())
}
"fps-replay" => run_fps_replay(),
"gallery" => shell_gallery::run_gallery(shell_gallery::parse_out_dir(
"gallery" => shell_gallery::run_gallery(shell_gallery::parse_gallery_args(
&mut args,
"evidence/mobile-gallery",
false,
)?),
"shell-gallery" => shell_gallery::run_shell_gallery(shell_gallery::parse_out_dir(
"shell-gallery" => shell_gallery::run_shell_gallery(shell_gallery::parse_gallery_args(
&mut args,
"evidence/mobile-shell",
true,
)?),
"scale-probe" => {
let rest: Vec<String> = args.collect();
@@ -291,7 +291,10 @@ fn render_scale_pngs(out_dir: &std::path::Path) -> Result<()> {
session.update_state(|s| {
s.explorer_scroll_y = scroll;
})?;
session.render_png(&out_dir.join(format!("scale-{route}-{tag}-{scroll}.png")))?;
session.render_png(
&out_dir.join(format!("scale-{route}-{tag}-{scroll}.png")),
false,
)?;
}
}
}
@@ -5,6 +5,11 @@
//! - Document switch before (`doc-arch`) and after (`doc-sync`) via `open_document`
//! - Inserted `affine:image` + `affine:attachment` blocks with blob metadata & upload badges
//! - Live `SpaceSync` status indicator (`Synced`, `Syncing (2)`)
//!
//! `--only <pattern>` renders the shots whose file name contains the pattern, `--jobs <n>`
//! sets the thread count (default: the available cores, at most 4; the phone and the tablet
//! shots use one thread each), and `--fast-png` writes the same pixels with a faster PNG
//! filter for local viewing.
use std::path::PathBuf;
@@ -15,19 +20,43 @@ use affine_mobile::{
use anyhow::{Context as _, Result};
use ui_tokens::ThemeMode;
use super::{open_doclink_multi, start_session};
use super::{default_jobs, open_doclink_multi, parse_jobs, run_in_order, start_session};
pub(crate) fn parse_out_dir(
/// Options of `gallery` and `shell-gallery`.
pub(crate) struct GalleryArgs {
pub(crate) out_dir: PathBuf,
pub(crate) only: Option<String>,
pub(crate) jobs: usize,
pub(crate) fast_png: bool,
}
/// Parses `--out <dir>`, `--fast-png`, and, with `select`, `--only <pattern>` and
/// `--jobs <n>`.
pub(crate) fn parse_gallery_args(
args: &mut std::iter::Skip<std::env::Args>,
default_dir: &str,
) -> Result<PathBuf> {
let mut out_dir = PathBuf::from(default_dir);
select: bool,
) -> Result<GalleryArgs> {
let mut parsed = GalleryArgs {
out_dir: PathBuf::from(default_dir),
only: None,
jobs: default_jobs(),
fast_png: false,
};
while let Some(arg) = args.next() {
if arg == "--out" {
out_dir = PathBuf::from(args.next().context("--out requires a directory")?);
match arg.as_str() {
"--out" => {
parsed.out_dir = PathBuf::from(args.next().context("--out requires a directory")?)
}
"--fast-png" => parsed.fast_png = true,
"--only" if select => {
parsed.only = Some(args.next().context("--only requires a pattern")?)
}
"--jobs" if select => parsed.jobs = parse_jobs(args.next())?,
other => anyhow::bail!("unknown gallery flag `{other}`"),
}
}
Ok(out_dir)
Ok(parsed)
}
fn attach_sample_media_blocks(state: &mut MobileAppState) {
@@ -55,129 +84,166 @@ fn attach_sample_media_blocks(state: &mut MobileAppState) {
}
}
pub(super) fn run_shell_gallery(out_dir: PathBuf) -> Result<()> {
std::fs::create_dir_all(&out_dir)?;
/// One shell gallery shot: its file, its logical window size, and the state it shows.
struct ShellShot {
filename: &'static str,
size: (u32, u32),
theme: ThemeMode,
setup: fn(&mut MobileAppState),
}
type ShotSetup = Box<dyn Fn(&mut MobileAppState)>;
let phone_shots: Vec<(&str, ThemeMode, ShotSetup)> = vec![
(
"mobile-phone-drawer-light.png",
ThemeMode::Light,
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_workspace_drawer(Some("mobile.page.drawer_btn"), 0.0);
s.settle_animations(500.0);
}),
),
(
"mobile-phone-drawer-dark.png",
ThemeMode::Dark,
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_workspace_drawer(Some("mobile.page.drawer_btn"), 0.0);
s.settle_animations(500.0);
}),
),
(
"mobile-phone-doc-before-light.png",
ThemeMode::Light,
Box::new(|s| {
s.open_document("doc-arch", 0.0);
}),
),
(
"mobile-phone-doc-after-light.png",
ThemeMode::Light,
Box::new(|s| {
s.open_document("doc-arch", 0.0);
s.open_document("doc-sync", 10.0);
}),
),
(
"mobile-phone-media-blocks-light.png",
ThemeMode::Light,
Box::new(attach_sample_media_blocks),
),
(
"mobile-phone-media-blocks-dark.png",
ThemeMode::Dark,
Box::new(attach_sample_media_blocks),
),
];
const PHONE: (u32, u32) = (390, 844);
const TABLET: (u32, u32) = (1024, 768);
let phone_session = start_session(
390,
844,
2.0,
seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28"),
)?;
for (filename, theme, setup) in phone_shots {
let mut next = seed_showcase_state(MobileLocale::En, theme, "2026-11-28");
setup(&mut next);
phone_session.update_state(|s| *s = next)?;
let out_path = out_dir.join(filename);
let glyphs = phone_session.render_png(&out_path)?;
println!(
"shell-gallery: rendered {} (780x1688, {glyphs} glyphs)",
out_path.display()
);
static SHELL_SHOTS: [ShellShot; 10] = [
ShellShot {
filename: "mobile-phone-drawer-light.png",
size: PHONE,
theme: ThemeMode::Light,
setup: open_phone_drawer,
},
ShellShot {
filename: "mobile-phone-drawer-dark.png",
size: PHONE,
theme: ThemeMode::Dark,
setup: open_phone_drawer,
},
ShellShot {
filename: "mobile-phone-doc-before-light.png",
size: PHONE,
theme: ThemeMode::Light,
setup: |s| s.open_document("doc-arch", 0.0),
},
ShellShot {
filename: "mobile-phone-doc-after-light.png",
size: PHONE,
theme: ThemeMode::Light,
setup: |s| {
s.open_document("doc-arch", 0.0);
s.open_document("doc-sync", 10.0);
},
},
ShellShot {
filename: "mobile-phone-media-blocks-light.png",
size: PHONE,
theme: ThemeMode::Light,
setup: attach_sample_media_blocks,
},
ShellShot {
filename: "mobile-phone-media-blocks-dark.png",
size: PHONE,
theme: ThemeMode::Dark,
setup: attach_sample_media_blocks,
},
ShellShot {
filename: "mobile-tablet-drawer-light.png",
size: TABLET,
theme: ThemeMode::Light,
setup: open_tablet_drawer,
},
ShellShot {
filename: "mobile-tablet-drawer-dark.png",
size: TABLET,
theme: ThemeMode::Dark,
setup: open_tablet_drawer,
},
ShellShot {
filename: "mobile-tablet-media-sync-light.png",
size: TABLET,
theme: ThemeMode::Light,
setup: attach_sample_media_blocks,
},
ShellShot {
filename: "mobile-tablet-media-sync-dark.png",
size: TABLET,
theme: ThemeMode::Dark,
setup: attach_sample_media_blocks,
},
];
fn open_phone_drawer(s: &mut MobileAppState) {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_workspace_drawer(Some("mobile.page.drawer_btn"), 0.0);
s.settle_animations(500.0);
}
fn open_tablet_drawer(s: &mut MobileAppState) {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::WorkspaceDrawer, 0.0);
s.settle_animations(500.0);
}
/// Renders the selected shots at 2x with one session for each window size, the phone and
/// the tablet sessions on parallel threads. Each session renders its shots in list order,
/// because a shot can depend on the shots that its session rendered before it.
pub(super) fn run_shell_gallery(args: GalleryArgs) -> Result<()> {
let matches = |shot: &ShellShot| {
args.only
.as_deref()
.is_none_or(|pattern| shot.filename.contains(pattern))
};
let mut sizes = Vec::new();
for (index, shot) in SHELL_SHOTS
.iter()
.enumerate()
.filter(|(_, shot)| matches(shot))
{
if let Some((_, last)) = sizes.iter_mut().find(|(size, _)| *size == shot.size) {
*last = index;
} else {
sizes.push((shot.size, index));
}
}
let tablet_shots: Vec<(&str, ThemeMode, ShotSetup)> = vec![
(
"mobile-tablet-drawer-light.png",
ThemeMode::Light,
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::WorkspaceDrawer, 0.0);
s.settle_animations(500.0);
}),
),
(
"mobile-tablet-drawer-dark.png",
ThemeMode::Dark,
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::WorkspaceDrawer, 0.0);
s.settle_animations(500.0);
}),
),
(
"mobile-tablet-media-sync-light.png",
ThemeMode::Light,
Box::new(attach_sample_media_blocks),
),
(
"mobile-tablet-media-sync-dark.png",
ThemeMode::Dark,
Box::new(attach_sample_media_blocks),
),
];
let tablet_session = start_session(
1024,
768,
2.0,
seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28"),
)?;
for (filename, theme, setup) in tablet_shots {
let mut next = seed_showcase_state(MobileLocale::En, theme, "2026-11-28");
setup(&mut next);
tablet_session.update_state(|s| *s = next)?;
let out_path = out_dir.join(filename);
let glyphs = tablet_session.render_png(&out_path)?;
println!(
"shell-gallery: rendered {} (2048x1536, {glyphs} glyphs)",
out_path.display()
);
anyhow::ensure!(
!sizes.is_empty(),
"--only {:?} matches none of the {} items",
args.only.as_deref().unwrap_or_default(),
SHELL_SHOTS.len()
);
std::fs::create_dir_all(&args.out_dir)?;
let rendered = run_in_order(&sizes, args.jobs, |&((width, height), last)| {
let session = start_session(
width,
height,
2.0,
seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28"),
)?;
let mut shots = Vec::new();
for shot in SHELL_SHOTS[..=last]
.iter()
.filter(|shot| shot.size == (width, height))
{
let mut next = seed_showcase_state(MobileLocale::En, shot.theme, "2026-11-28");
(shot.setup)(&mut next);
session.update_state(|s| *s = next)?;
if matches(shot) {
let glyphs =
session.render_png(&args.out_dir.join(shot.filename), args.fast_png)?;
shots.push((shot, glyphs));
} else {
session.frame()?;
}
}
Ok::<_, anyhow::Error>(shots)
});
for shots in rendered {
for (shot, glyphs) in shots? {
let (width, height) = shot.size;
println!(
"shell-gallery: rendered {} ({}x{}, {glyphs} glyphs)",
args.out_dir.join(shot.filename).display(),
width * 2,
height * 2
);
}
}
Ok(())
}
pub(crate) fn run_narrow_gallery(
out_dir: &std::path::Path,
open_doclink_multi: fn(&mut MobileAppState),
fast_png: bool,
) -> Result<()> {
let narrow_session = start_session(
320,
@@ -205,7 +271,7 @@ pub(crate) fn run_narrow_gallery(
setup(&mut next_state);
narrow_session.update_state(|s| *s = next_state)?;
let out_path = out_dir.join(filename);
let glyphs = narrow_session.render_png(&out_path)?;
let glyphs = narrow_session.render_png(&out_path, fast_png)?;
println!(
"gallery: rendered {} (640x1136, {glyphs} glyphs)",
out_path.display()
@@ -215,7 +281,10 @@ pub(crate) fn run_narrow_gallery(
}
/// Render the 390×844 route gallery and the narrow-viewport gallery into `out_dir`.
pub(super) fn run_gallery(out_dir: PathBuf) -> Result<()> {
pub(super) fn run_gallery(args: GalleryArgs) -> Result<()> {
let GalleryArgs {
out_dir, fast_png, ..
} = args;
std::fs::create_dir_all(&out_dir)?;
type ShotSetup = Box<dyn Fn(&mut MobileAppState)>;
@@ -368,13 +437,13 @@ pub(super) fn run_gallery(out_dir: PathBuf) -> Result<()> {
setup(&mut next_state);
session.update_state(|s| *s = next_state)?;
let out_path = out_dir.join(filename);
let glyphs = session.render_png(&out_path)?;
let glyphs = session.render_png(&out_path, fast_png)?;
println!(
"gallery: rendered {} (780x1688, {glyphs} glyphs)",
out_path.display()
);
}
run_narrow_gallery(&out_dir, open_doclink_multi)?;
run_narrow_gallery(&out_dir, open_doclink_multi, fast_png)?;
Ok(())
}