zsui 0.3.0-alpha.2

Rust-first feature-gated native UI framework for Win32, AppKit, and Linux.
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
use serde::Serialize;

use crate::{
    NativeTypographyProfile, NativeWindowSmokeRunReport, ViewHitTarget, ViewHitTargetKind,
};

pub const NATIVE_PROOF_SCHEMA: &str = "zsui.native-proof/v1";
pub const NATIVE_PROOF_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NativeProofRunnerEvidence {
    pub image_os: Option<String>,
    pub image_version: Option<String>,
}

impl NativeProofRunnerEvidence {
    pub fn from_environment() -> Self {
        Self {
            image_os: std::env::var("ImageOS").ok(),
            image_version: std::env::var("ImageVersion").ok(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct NativeProofWindowEvidence {
    pub width: u32,
    pub height: u32,
    pub logical_width: u32,
    pub logical_height: u32,
    pub pixel_width: u32,
    pub pixel_height: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NativeProofWidgetEvidence {
    pub id: String,
    pub role: String,
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
    pub enabled: bool,
    pub focused: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NativeProofProcessMemoryEvidence {
    pub source: &'static str,
    pub sample_point: &'static str,
    pub resident_bytes: u64,
    pub peak_resident_bytes: u64,
    pub private_bytes: Option<u64>,
    pub peak_private_bytes: Option<u64>,
    pub proportional_set_size_bytes: Option<u64>,
    pub virtual_bytes: Option<u64>,
}

impl NativeProofProcessMemoryEvidence {
    pub fn capture() -> Option<Self> {
        Self::capture_at("proof_document_serialization")
    }

    pub(crate) fn capture_at(sample_point: &'static str) -> Option<Self> {
        crate::desktop_runtime::capture_process_memory(sample_point)
    }
}

impl NativeProofWidgetEvidence {
    fn from_hit_target(
        target: ViewHitTarget,
        focused_widget: Option<u64>,
        content_offset_y: i32,
    ) -> Self {
        Self {
            id: native_proof_widget_id(target.widget.0),
            role: native_proof_role(target.kind),
            x: target.bounds.x,
            y: target.bounds.y.saturating_add(content_offset_y),
            width: target.bounds.width,
            height: target.bounds.height,
            enabled: true,
            focused: focused_widget == Some(target.widget.0),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct NativeProofDocument {
    pub schema: &'static str,
    pub schema_version: u32,
    pub application: String,
    pub scenario: String,
    pub theme: String,
    pub platform: String,
    pub backend: String,
    pub capture_backend: String,
    pub display_server: Option<String>,
    pub os_family: String,
    pub architecture: String,
    pub runner: NativeProofRunnerEvidence,
    pub scale_factor: f64,
    pub typography_scale: f32,
    pub typography: NativeTypographyProfile,
    pub process_memory: Option<NativeProofProcessMemoryEvidence>,
    pub window: NativeProofWindowEvidence,
    pub focused_widget: Option<String>,
    pub widgets: Vec<NativeProofWidgetEvidence>,
    pub messages: Vec<String>,
    pub unhandled_commands: Vec<String>,
    pub errors: Vec<String>,
    pub runtime: NativeWindowSmokeRunReport,
}

impl NativeProofDocument {
    pub fn new(
        application: impl Into<String>,
        scenario: impl Into<String>,
        theme: impl Into<String>,
        requested_width: u32,
        requested_height: u32,
        widgets: impl IntoIterator<Item = ViewHitTarget>,
        runtime: NativeWindowSmokeRunReport,
    ) -> Self {
        let capture = runtime.native_view_capture.as_ref();
        let platform = capture
            .map(|capture| capture.platform)
            .unwrap_or(std::env::consts::OS)
            .to_string();
        let capture_backend = capture
            .map(|capture| capture.backend)
            .unwrap_or("unavailable")
            .to_string();
        let logical_width = capture
            .map(|capture| capture.logical_width)
            .unwrap_or(requested_width);
        let logical_height = capture
            .map(|capture| capture.logical_height)
            .unwrap_or(requested_height);
        let scale_factor = capture.map(|capture| capture.scale_factor).unwrap_or(1.0);
        let typography_scale = capture
            .map(|capture| capture.typography_scale)
            .unwrap_or(1.0);
        let typography = native_proof_typography(capture, typography_scale);
        let focused_widget = runtime.native_view_focused_widget;
        let content_offset_y = runtime.window_menu_surface_height.min(i32::MAX as u32) as i32;
        let errors = native_proof_errors(&runtime);
        let unhandled_commands = native_proof_unhandled_commands(&runtime);

        Self {
            schema: NATIVE_PROOF_SCHEMA,
            schema_version: NATIVE_PROOF_SCHEMA_VERSION,
            application: application.into(),
            scenario: scenario.into(),
            theme: theme.into(),
            backend: native_proof_backend(&capture_backend).to_string(),
            capture_backend,
            display_server: capture
                .and_then(|capture| capture.display_server)
                .map(str::to_string),
            os_family: std::env::var("ZSUI_NATIVE_PROOF_OS_FAMILY")
                .unwrap_or_else(|_| platform.clone()),
            architecture: native_proof_architecture(std::env::consts::ARCH).to_string(),
            runner: NativeProofRunnerEvidence::from_environment(),
            scale_factor,
            typography_scale,
            typography,
            process_memory: runtime
                .process_memory_during_runtime
                .clone()
                .or_else(NativeProofProcessMemoryEvidence::capture),
            window: NativeProofWindowEvidence {
                width: logical_width,
                height: logical_height,
                logical_width,
                logical_height,
                pixel_width: capture
                    .map(|capture| capture.pixel_width)
                    .unwrap_or(logical_width),
                pixel_height: capture
                    .map(|capture| capture.pixel_height)
                    .unwrap_or(logical_height),
            },
            focused_widget: focused_widget.map(native_proof_widget_id),
            widgets: widgets
                .into_iter()
                .map(|target| {
                    NativeProofWidgetEvidence::from_hit_target(
                        target,
                        focused_widget,
                        content_offset_y,
                    )
                })
                .collect(),
            messages: Vec::new(),
            unhandled_commands,
            errors,
            platform,
            runtime,
        }
    }

    pub fn os_family(mut self, os_family: impl Into<String>) -> Self {
        self.os_family = os_family.into();
        self
    }

    pub fn runner(mut self, runner: NativeProofRunnerEvidence) -> Self {
        self.runner = runner;
        self
    }

    pub fn messages(mut self, messages: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.messages = messages.into_iter().map(Into::into).collect();
        self
    }
}

fn native_proof_typography(
    capture: Option<&crate::NativeViewCaptureEvidence>,
    typography_scale: f32,
) -> NativeTypographyProfile {
    if let Some(capture) = capture {
        return capture.typography.clone();
    }
    crate::desktop_runtime::native_proof_typography(typography_scale)
}

fn native_proof_widget_id(widget: u64) -> String {
    format!("widget-{widget}")
}

fn native_proof_role(kind: ViewHitTargetKind) -> String {
    let variant = match serde_json::to_value(kind) {
        Ok(serde_json::Value::String(variant)) => variant,
        Ok(serde_json::Value::Object(fields)) => fields
            .into_iter()
            .next()
            .map(|(variant, _)| variant)
            .unwrap_or_else(|| "Unknown".to_string()),
        _ => "Unknown".to_string(),
    };
    let mut role = String::with_capacity(variant.len() + 4);
    for (index, character) in variant.chars().enumerate() {
        if character.is_ascii_uppercase() {
            if index > 0 {
                role.push('_');
            }
            role.push(character.to_ascii_lowercase());
        } else {
            role.push(character);
        }
    }
    role
}

fn native_proof_backend(capture_backend: &str) -> &'static str {
    if capture_backend.starts_with("appkit_") {
        "appkit"
    } else if capture_backend.starts_with("winit_softbuffer_") {
        "linux-direct"
    } else if capture_backend.starts_with("gtk_") {
        "gtk4"
    } else if capture_backend.starts_with("win32_") || capture_backend.starts_with("windows_") {
        "win32"
    } else {
        crate::desktop_runtime::native_proof_backend_name()
    }
}

fn native_proof_architecture(architecture: &str) -> &str {
    match architecture {
        "aarch64" => "arm64",
        value => value,
    }
}

fn native_proof_errors(runtime: &NativeWindowSmokeRunReport) -> Vec<String> {
    let mut errors = Vec::new();
    for (name, error) in [
        ("startup", runtime.startup_error.as_deref()),
        ("screenshot", runtime.screenshot_error.as_deref()),
        (
            "native_window_resize",
            runtime.native_window_resize_error.as_deref(),
        ),
        ("window_menu", runtime.window_menu_command_error.as_deref()),
        ("status_item", runtime.status_item_error.as_deref()),
        ("status_menu", runtime.status_menu_command_error.as_deref()),
        (
            "status_menu_popup",
            runtime.status_menu_popup_error.as_deref(),
        ),
    ] {
        if let Some(error) = error {
            errors.push(format!("{name}: {error}"));
        }
    }
    errors.extend(
        runtime
            .native_view_ui_command_errors
            .iter()
            .map(|error| format!("ui_command: {error}")),
    );
    errors.extend(
        runtime
            .native_view_app_command_errors
            .iter()
            .map(|error| format!("app_command: {error}")),
    );
    errors.extend(
        runtime
            .native_view_text_edit_command_errors
            .iter()
            .map(|error| format!("text_edit: {error}")),
    );
    errors
}

fn native_proof_unhandled_commands(runtime: &NativeWindowSmokeRunReport) -> Vec<String> {
    let mut unhandled = Vec::new();
    for (name, count) in [
        (
            "native_view_ui_command",
            runtime.native_view_ui_command_unhandled_count,
        ),
        (
            "native_view_app_command",
            runtime.native_view_app_command_unhandled_count,
        ),
        (
            "native_view_click",
            runtime.native_view_unhandled_click_count,
        ),
        ("native_view_key", runtime.native_view_unhandled_key_count),
        (
            "native_view_scroll",
            runtime.native_view_unhandled_scroll_count,
        ),
    ] {
        if count > 0 {
            unhandled.push(format!("{name}:{count}"));
        }
    }
    unhandled
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Dp, NativeViewCaptureEvidence, NativeWindowSmokeRunOptions, Rect, ViewHitTarget,
        ViewHitTargetKind, WidgetId, ZsTypographyPlatformStyle,
    };

    #[test]
    fn proof_document_flattens_native_capture_focus_and_widget_roles() {
        let mut runtime = NativeWindowSmokeRunReport::empty(NativeWindowSmokeRunOptions::quick());
        runtime.native_view_capture = Some(NativeViewCaptureEvidence {
            platform: "macos",
            backend: "appkit_nsview_bitmap_cache",
            display_server: None,
            logical_width: 960,
            logical_height: 640,
            pixel_width: 1920,
            pixel_height: 1280,
            scale_factor: 2.0,
            typography_scale: 1.0,
            typography: NativeTypographyProfile::fallback(ZsTypographyPlatformStyle::Macos, 1.0),
        });
        runtime.native_view_focused_widget = Some(7);

        let document = NativeProofDocument::new(
            "gallery",
            "inputs-light",
            "light",
            960,
            640,
            [ViewHitTarget::with_kind(
                WidgetId::new(7),
                Rect {
                    x: 12,
                    y: 20,
                    width: 200,
                    height: 28,
                },
                ViewHitTargetKind::Textbox,
            )],
            runtime,
        )
        .os_family("macos-15")
        .messages(["SearchFocused", "SearchChanged"]);

        assert_eq!(document.backend, "appkit");
        assert_eq!(document.capture_backend, "appkit_nsview_bitmap_cache");
        assert_eq!(
            document.architecture,
            native_proof_architecture(std::env::consts::ARCH)
        );
        assert_eq!(document.scale_factor, 2.0);
        assert_eq!(
            document.typography.platform,
            ZsTypographyPlatformStyle::Macos
        );
        assert_eq!(document.typography.body_metrics.size, 13.0);
        assert_eq!(document.window.pixel_width, 1920);
        assert_eq!(document.focused_widget.as_deref(), Some("widget-7"));
        assert_eq!(document.widgets[0].role, "textbox");
        assert!(document.widgets[0].focused);
        assert_eq!(document.messages, ["SearchFocused", "SearchChanged"]);
        assert!(document.errors.is_empty());
        assert!(document.unhandled_commands.is_empty());
    }

    #[test]
    fn proof_document_surfaces_errors_and_unhandled_counts() {
        let mut runtime = NativeWindowSmokeRunReport::empty(NativeWindowSmokeRunOptions::quick());
        runtime.screenshot_error = Some("capture failed".to_string());
        runtime.native_view_unhandled_key_count = 2;
        runtime
            .native_view_text_edit_command_errors
            .push("bad edit".to_string());

        let document =
            NativeProofDocument::new("notepad", "interaction", "system", 960, 640, [], runtime);

        assert_eq!(
            document.errors,
            ["screenshot: capture failed", "text_edit: bad edit"]
        );
        assert_eq!(document.unhandled_commands, ["native_view_key:2"]);
    }

    #[test]
    fn proof_window_falls_back_to_requested_geometry_without_capture() {
        let runtime = NativeWindowSmokeRunReport::empty(NativeWindowSmokeRunOptions::new(10));
        let document =
            NativeProofDocument::new("gallery", "catalog", "light", 1024, 640, [], runtime);

        assert_eq!(document.window.width, 1024);
        assert_eq!(document.window.height, 640);
        assert_eq!(document.backend, native_proof_backend("unavailable"));
        assert_eq!(document.scale_factor, 1.0);
        assert_eq!(Dp::new(document.typography_scale), Dp::new(1.0));
    }

    #[cfg(any(
        all(target_os = "windows", feature = "windows-gdi"),
        all(target_os = "macos", feature = "macos-appkit"),
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    #[test]
    fn process_memory_capture_reports_real_resident_bytes() {
        let memory = NativeProofProcessMemoryEvidence::capture()
            .expect("supported desktop target should expose process memory");
        assert!(memory.resident_bytes > 0);
        assert!(memory.peak_resident_bytes >= memory.resident_bytes);
    }
}