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
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
use std::{
    any::Any,
    fmt,
    path::PathBuf,
    sync::{
        atomic::{AtomicBool, AtomicU8, Ordering},
        Arc, OnceLock, Weak,
    },
};

use crate::{
    DialogResponse, DirectoryDialogSpec, FileDialogService, FileDialogSpec,
    NativeDesktopDialogService, NativeDialogService, NativeDialogSpec, NativeFileDialogService,
    SaveFileDialogSpec, ZsuiResult,
};

/// A platform-neutral native effect requested from `update` through
/// [`AppCx`](crate::AppCx).
///
/// Desktop hosts always execute effects outside the live-view and route locks,
/// so a synchronous modal dialog cannot re-enter a held update. Each queued
/// effect produces exactly one [`AppEffectOutcome`] that is delivered back to
/// the typed update at most once; outcomes are dropped when the window is
/// destroyed before the dialog finishes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AppEffect {
    /// Opens the native file-open dialog. `Ok(None)` means the user cancelled.
    OpenFileDialog(FileDialogSpec),
    /// Opens the native save dialog. `Ok(None)` means the user cancelled.
    SaveFileDialog(SaveFileDialogSpec),
    /// Opens a native directory picker. `Ok(None)` means the user cancelled.
    PickDirectory(DirectoryDialogSpec),
    /// Shows a native message/confirmation dialog and reports the typed
    /// [`DialogResponse`].
    ShowDialog(NativeDialogSpec),
}

/// The typed result of one executed [`AppEffect`].
///
/// The outcome variant always matches the request variant. Cancellation is
/// `Ok(None)` for pickers and the corresponding [`DialogResponse`] for message
/// dialogs; backend failures surface as `Err(ZsuiError)` instead of panicking.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AppEffectOutcome {
    /// Result of [`AppEffect::OpenFileDialog`].
    OpenFileDialog(ZsuiResult<Option<Vec<PathBuf>>>),
    /// Result of [`AppEffect::SaveFileDialog`].
    SaveFileDialog(ZsuiResult<Option<PathBuf>>),
    /// Result of [`AppEffect::PickDirectory`].
    PickDirectory(ZsuiResult<Option<PathBuf>>),
    /// Result of [`AppEffect::ShowDialog`].
    ShowDialog(ZsuiResult<DialogResponse>),
}

fn claim_terminal(state: &AtomicU8, terminal: u8) -> bool {
    let mut current = state.load(Ordering::Acquire);
    loop {
        if current >= 2 {
            return false;
        }
        match state.compare_exchange_weak(current, terminal, Ordering::AcqRel, Ordering::Acquire) {
            Ok(_) => return true,
            Err(next) => current = next,
        }
    }
}

#[derive(Debug, Default)]
struct EffectLifecycle {
    status: AtomicU8,
    window: OnceLock<Weak<EffectWindowState>>,
}
impl EffectLifecycle {
    fn window_alive(&self) -> bool {
        self.window.get().is_none_or(|window| {
            window
                .upgrade()
                .is_some_and(|window| !window.closed.load(Ordering::Acquire))
        })
    }
}

/// A cloneable cancellation token. Cancellation prevents execution if still
/// queued, and suppresses delivery if a native modal service is already running.
/// It does not forcibly close the operating system's modal dialog.
#[derive(Debug, Clone)]
pub struct AppEffectCancellation {
    state: Arc<EffectLifecycle>,
}
impl AppEffectCancellation {
    /// Returns true only for the first cancellation before delivery completes.
    pub fn cancel(&self) -> bool {
        claim_terminal(&self.state.status, 3)
    }
    /// Whether explicit cancellation or window destruction terminated delivery.
    pub fn is_cancelled(&self) -> bool {
        let status = self.state.status.load(Ordering::Acquire);
        status == 3 || (status != 2 && !self.state.window_alive())
    }
}

#[derive(Debug, Default)]
struct EffectWindowState {
    closed: AtomicBool,
    draining: AtomicBool,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct EffectWindow {
    state: Arc<EffectWindowState>,
}
impl EffectWindow {
    pub fn close(&self) {
        self.state.closed.store(true, Ordering::Release);
    }
    pub fn is_closed(&self) -> bool {
        self.state.closed.load(Ordering::Acquire)
    }
    pub fn begin_turn(&self) -> Option<EffectTurn> {
        if self.is_closed() || self.state.draining.swap(true, Ordering::AcqRel) {
            return None;
        }
        Some(EffectTurn(Arc::downgrade(&self.state)))
    }
    pub fn is_draining(&self) -> bool {
        self.state.draining.load(Ordering::Acquire)
    }
}
pub(crate) struct EffectTurn(Weak<EffectWindowState>);
impl EffectTurn {
    pub fn is_alive(&self) -> bool {
        self.0
            .upgrade()
            .is_some_and(|state| !state.closed.load(Ordering::Acquire))
    }
}
impl Drop for EffectTurn {
    fn drop(&mut self) {
        if let Some(state) = self.0.upgrade() {
            state.draining.store(false, Ordering::Release);
        }
    }
}

/// Turns an [`AppEffectOutcome`] into a boxed application message. Returning
/// `None` drops the outcome (for example when the outcome kind does not match
/// the request, which hosts never produce for well-formed dispatches).
type AppEffectResponder =
    Arc<dyn Fn(AppEffectOutcome) -> Option<Box<dyn Any + Send>> + Send + Sync>;

/// One queued [`AppEffect`] plus the responder that maps its outcome back into
/// the application's typed message type.
///
/// Requests are created by the [`AppCx`](crate::AppCx) effect helpers and are
/// consumed exactly once by the desktop host: it executes
/// [`AppEffectRequest::effect`] outside the live-view lock and then delivers
/// the outcome through the stored responder.
#[derive(Clone)]
pub struct AppEffectRequest {
    effect: AppEffect,
    responder: Option<AppEffectResponder>,
    state: Arc<EffectLifecycle>,
}

impl AppEffectRequest {
    /// Queues `effect` without a responder; its outcome is discarded after the
    /// dialog finishes.
    pub fn new(effect: AppEffect) -> Self {
        Self {
            effect,
            responder: None,
            state: Arc::new(EffectLifecycle::default()),
        }
    }

    /// The platform-neutral effect the host executes outside the update lock.
    pub fn effect(&self) -> &AppEffect {
        &self.effect
    }

    pub(crate) fn typed<Msg, Respond>(effect: AppEffect, respond: Respond) -> Self
    where
        Msg: Send + 'static,
        Respond: Fn(AppEffectOutcome) -> Option<Msg> + Send + Sync + 'static,
    {
        Self::with_responder(
            effect,
            Arc::new(move |outcome| {
                respond(outcome).map(|message| Box::new(message) as Box<dyn Any + Send>)
            }),
        )
    }

    pub(crate) fn with_responder(effect: AppEffect, responder: AppEffectResponder) -> Self {
        Self {
            effect,
            responder: Some(responder),
            state: Arc::new(EffectLifecycle::default()),
        }
    }

    /// A token sharing the lifecycle of this request and all its clones.
    pub fn cancellation(&self) -> AppEffectCancellation {
        AppEffectCancellation {
            state: self.state.clone(),
        }
    }

    pub(crate) fn bind_window(&mut self, window: &EffectWindow) {
        // Admission binds all request/token clones to one window permanently.
        let _ = self.state.window.set(Arc::downgrade(&window.state));
    }
    fn window_alive(&self) -> bool {
        self.state.window_alive()
    }
    #[allow(dead_code)] // Used by the optional native desktop hosts.
    pub(crate) fn try_begin(&self) -> bool {
        if !self.window_alive() {
            self.cancellation().cancel();
            return false;
        }
        self.state
            .status
            .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }
    /// Claims one matching outcome. Duplicate or cancelled deliveries never
    /// invoke the responder. Custom hosts may deliver directly without begin.
    pub(crate) fn respond(self, outcome: AppEffectOutcome) -> Option<Box<dyn Any + Send>> {
        let matches = matches!(
            (&self.effect, &outcome),
            (
                AppEffect::OpenFileDialog(_),
                AppEffectOutcome::OpenFileDialog(_)
            ) | (
                AppEffect::SaveFileDialog(_),
                AppEffectOutcome::SaveFileDialog(_)
            ) | (
                AppEffect::PickDirectory(_),
                AppEffectOutcome::PickDirectory(_)
            ) | (AppEffect::ShowDialog(_), AppEffectOutcome::ShowDialog(_))
        );
        if !matches {
            return None;
        }
        if !self.window_alive() {
            self.cancellation().cancel();
            return None;
        }
        if !claim_terminal(&self.state.status, 2) {
            return None;
        }
        self.responder.and_then(|responder| responder(outcome))
    }
}

impl fmt::Debug for AppEffectRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AppEffectRequest")
            .field("effect", &self.effect)
            .field("has_responder", &self.responder.is_some())
            .finish()
    }
}

/// Executes one queued effect against the selected desktop backend.
///
/// Desktop hosts call this only after releasing the live-view/route lock, so
/// the synchronous modal dialog runs on the UI thread without re-entering a
/// held update. The returned outcome is then delivered through
/// `dispatch_app_effect_outcome` exactly once.
#[allow(dead_code)] // Called by the per-host pending-effect drain patches.
pub(crate) fn execute_native_app_effect(effect: &AppEffect) -> AppEffectOutcome {
    match effect {
        AppEffect::OpenFileDialog(spec) => {
            AppEffectOutcome::OpenFileDialog(NativeFileDialogService::new().open_file_dialog(spec))
        }
        AppEffect::SaveFileDialog(spec) => {
            AppEffectOutcome::SaveFileDialog(NativeFileDialogService::new().save_file_dialog(spec))
        }
        AppEffect::PickDirectory(spec) => AppEffectOutcome::PickDirectory(
            NativeFileDialogService::new().pick_directory_dialog(spec),
        ),
        AppEffect::ShowDialog(spec) => {
            AppEffectOutcome::ShowDialog(NativeDesktopDialogService::new().show_native_dialog(spec))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{live_view_runtime, AppCx, Dpi, Rect};

    #[test]
    fn request_clones_and_tokens_share_window_termination_even_before_admission() {
        let mut request = AppEffectRequest::typed(
            AppEffect::ShowDialog(NativeDialogSpec::message("x", "y")),
            |_| Some(()),
        );
        let escaped = request.clone();
        let cancellation = escaped.cancellation();
        let window = EffectWindow::default();
        request.bind_window(&window);
        assert!(request.try_begin());
        window.close();
        assert!(cancellation.is_cancelled());
        assert!(escaped
            .respond(AppEffectOutcome::ShowDialog(Ok(DialogResponse::Ok)))
            .is_none());
        assert!(!request.try_begin());

        let mut completed = AppEffectRequest::typed(
            AppEffect::ShowDialog(NativeDialogSpec::message("x", "y")),
            |_| Some(()),
        );
        let window = EffectWindow::default();
        completed.bind_window(&window);
        let cancellation = completed.cancellation();
        assert!(completed
            .respond(AppEffectOutcome::ShowDialog(Ok(DialogResponse::Ok)))
            .is_some());
        window.close();
        assert!(!cancellation.is_cancelled());
        assert!(!cancellation.cancel());

        let mut abandoned =
            AppEffectRequest::new(AppEffect::ShowDialog(NativeDialogSpec::message("x", "y")));
        let window = EffectWindow::default();
        let turn = window.begin_turn().unwrap();
        abandoned.bind_window(&window);
        drop(window);
        assert!(!turn.is_alive());
        assert!(abandoned.cancellation().is_cancelled());
        assert!(!abandoned.try_begin());
    }

    #[derive(Debug, Clone, PartialEq)]
    enum Msg {
        Opened(ZsuiResult<Option<Vec<PathBuf>>>),
        Saved(ZsuiResult<Option<PathBuf>>),
        Confirmed(ZsuiResult<DialogResponse>),
    }

    fn recording_runtime(seen: Arc<std::sync::Mutex<Vec<Msg>>>) -> crate::SharedLiveViewRuntime {
        live_view_runtime(
            (),
            |_: &()| crate::spacer(),
            move |_: &mut (), message: Msg, _cx: &mut AppCx| {
                seen.lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .push(message);
            },
            Rect {
                x: 0,
                y: 0,
                width: 200,
                height: 100,
            },
            Dpi::standard(),
        )
    }

    fn take_effects(cx: &AppCx) -> Vec<AppEffectRequest> {
        cx.effects().to_vec()
    }

    #[test]
    fn app_cx_queues_native_effects_in_request_order() {
        let mut cx = AppCx::new();
        cx.open_file_dialog(FileDialogSpec::new("Open"), Msg::Opened);
        cx.save_file_dialog(SaveFileDialogSpec::new("Save"), Msg::Saved);
        cx.pick_directory(DirectoryDialogSpec::new("Folder"), |result| {
            Msg::Saved(result)
        });
        cx.show_dialog(
            NativeDialogSpec::message("Confirm", "Continue?"),
            Msg::Confirmed,
        );
        cx.effect(AppEffect::ShowDialog(NativeDialogSpec::message(
            "Note", "Done",
        )));

        let effects = take_effects(&cx);
        assert_eq!(effects.len(), 5);
        assert!(matches!(
            effects[0].effect(),
            AppEffect::OpenFileDialog(spec) if spec.title == "Open"
        ));
        assert!(matches!(
            effects[1].effect(),
            AppEffect::SaveFileDialog(spec) if spec.title == "Save"
        ));
        assert!(matches!(
            effects[2].effect(),
            AppEffect::PickDirectory(spec) if spec.title == "Folder"
        ));
        assert!(matches!(
            effects[3].effect(),
            AppEffect::ShowDialog(spec) if spec.title == "Confirm"
        ));
        assert!(matches!(effects[4].effect(), AppEffect::ShowDialog(_)));
    }

    #[test]
    fn app_effect_outcome_returns_to_typed_update_exactly_once() {
        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = recording_runtime(seen.clone());
        let mut cx = AppCx::new();
        cx.open_file_dialog(FileDialogSpec::new("Open"), Msg::Opened);
        let request = take_effects(&cx).into_iter().next().unwrap();

        let update = runtime.dispatch_app_effect(
            request,
            AppEffectOutcome::OpenFileDialog(Ok(Some(vec![PathBuf::from("picked.txt")]))),
        );

        assert_eq!(update.message_count, 1);
        assert!(update.redraw);
        assert_eq!(
            seen.lock().unwrap().as_slice(),
            &[Msg::Opened(Ok(Some(vec![PathBuf::from("picked.txt")])))]
        );
    }

    #[test]
    fn app_effect_without_responder_discards_the_outcome() {
        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = recording_runtime(seen.clone());
        let request =
            AppEffectRequest::new(AppEffect::PickDirectory(DirectoryDialogSpec::new("Folder")));

        let update = runtime.dispatch_app_effect(
            request,
            AppEffectOutcome::PickDirectory(Ok(Some(PathBuf::from("dir")))),
        );

        assert_eq!(update.message_count, 0);
        assert!(seen.lock().unwrap().is_empty());
    }

    #[test]
    fn app_effect_outcome_kind_mismatch_is_dropped() {
        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = recording_runtime(seen.clone());
        let responder: AppEffectResponder = Arc::new(|outcome| match outcome {
            AppEffectOutcome::ShowDialog(result) => {
                Some(Box::new(Msg::Confirmed(result)) as Box<dyn Any + Send>)
            }
            _ => None,
        });
        let request = AppEffectRequest::with_responder(
            AppEffect::ShowDialog(NativeDialogSpec::message("Confirm", "Continue?")),
            responder,
        );

        let update = runtime.dispatch_app_effect(
            request,
            AppEffectOutcome::PickDirectory(Ok(Some(PathBuf::from("dir")))),
        );

        assert_eq!(update.message_count, 0);
        assert!(seen.lock().unwrap().is_empty());
    }

    #[test]
    fn update_queued_effects_are_deferred_into_the_live_view_update() {
        let runtime = live_view_runtime(
            (),
            |_: &()| crate::spacer(),
            |_: &mut (), message: Msg, cx: &mut AppCx| {
                if let Msg::Confirmed(_) = message {
                    cx.open_file_dialog(FileDialogSpec::new("Next"), Msg::Opened);
                }
            },
            Rect {
                x: 0,
                y: 0,
                width: 200,
                height: 100,
            },
            Dpi::standard(),
        );
        let mut cx = AppCx::new();
        cx.show_dialog(
            NativeDialogSpec::message("Confirm", "Continue?"),
            Msg::Confirmed,
        );
        let request = take_effects(&cx).into_iter().next().unwrap();

        let update = runtime.dispatch_app_effect(
            request,
            AppEffectOutcome::ShowDialog(Ok(DialogResponse::Ok)),
        );

        assert_eq!(update.message_count, 1);
        assert_eq!(update.effects.len(), 1);
        assert!(matches!(
            update.effects[0].effect(),
            AppEffect::OpenFileDialog(spec) if spec.title == "Next"
        ));
    }

    #[test]
    fn suspended_view_still_applies_the_effect_outcome_to_state() {
        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = recording_runtime(seen.clone());
        runtime.suspend();
        let mut cx = AppCx::new();
        cx.show_dialog(
            NativeDialogSpec::message("Confirm", "Continue?"),
            Msg::Confirmed,
        );
        let request = take_effects(&cx).into_iter().next().unwrap();

        let update = runtime.dispatch_app_effect(
            request,
            AppEffectOutcome::ShowDialog(Ok(DialogResponse::Yes)),
        );

        assert_eq!(update.message_count, 1);
        assert!(!update.redraw);
        assert_eq!(
            seen.lock().unwrap().as_slice(),
            &[Msg::Confirmed(Ok(DialogResponse::Yes))]
        );
    }

    #[test]
    fn directory_picker_default_service_reports_unsupported() {
        struct NoopDialogs;

        impl FileDialogService for NoopDialogs {
            fn open_file_dialog(
                &mut self,
                _spec: &FileDialogSpec,
            ) -> ZsuiResult<Option<Vec<PathBuf>>> {
                Ok(None)
            }

            fn save_file_dialog(
                &mut self,
                _spec: &SaveFileDialogSpec,
            ) -> ZsuiResult<Option<PathBuf>> {
                Ok(None)
            }
        }

        let result = NoopDialogs.pick_directory_dialog(&DirectoryDialogSpec::new("Folder"));
        assert!(matches!(
            result,
            Err(crate::ZsuiError::Unsupported { capability, .. }) if capability == "pick_directory_dialog"
        ));
    }
}