native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Sendable UI-thread command proxy for background work.
//!
//! Background threads never borrow or mutate [`crate::Ui`]. Instead they hold
//! a cloneable, `Send` [`UiProxy`] and post [`TaskCommand`] values into a
//! bounded channel. The UI thread drains that channel inside its event
//! functions (`wait_event`, `poll_event`, `dispatch_events`,
//! `run_until_closed`), applies widget mutations through the same `set_*`
//! paths as direct calls, and surfaces task lifecycle notifications as
//! [`crate::UiEvent::Task`] values.
//!
//! ```
//! use native_gui_mock::MockBackend;
//! use native_gui_core::{Ui, UiEvent, WidgetKind};
//!
//! let mut ui = Ui::new(MockBackend::default());
//! let label = ui.create(WidgetKind::Label, Some("idle"))?;
//! let proxy = ui.task_proxy();
//!
//! let token = proxy.start_task();
//! let worker_proxy = proxy.clone();
//! std::thread::spawn(move || {
//!     // Do the slow work here, then publish the result.
//!     let _ = worker_proxy.set_text(label, "done");
//!     let _ = worker_proxy.finish(&token);
//! });
//!
//! // The UI thread applies queued commands while it waits for events.
//! while let Ok(event) = ui.wait_event() {
//!     if matches!(event, UiEvent::Task(_)) {
//!         break;
//!     }
//! }
//! assert_eq!(ui.widget(label).and_then(|spec| spec.text.as_deref()), Some("done"));
//! # Ok::<(), native_gui_core::GuiError>(())
//! ```
//!
//! Guarantees:
//! - commands are applied in FIFO post order;
//! - the queue is bounded (see [`DEFAULT_TASK_QUEUE_CAPACITY`]) and overflow
//!   is reported as [`TaskSendError::Full`] instead of blocking or growing
//!   without bound;
//! - once the owning [`crate::Ui`] is dropped, posts fail with
//!   [`TaskSendError::Closed`], so stale workers stop deterministically;
//! - drop contract: dropping a `Ui` (or calling [`crate::Ui::shutdown`])
//!   closes the channel immediately. Commands already accepted but not yet
//!   drained are discarded unapplied — a post that returned `Ok(())` before
//!   teardown is *accepted*, not *applied*; call
//!   [`crate::Ui::drain_task_commands`] first, and use the count returned by
//!   [`crate::Ui::shutdown`] to detect lost commits;
//! - commands that target removed widgets are rejected (counted in
//!   [`TaskDrainReport::rejected`]) and never panic; every rejected command
//!   also surfaces as [`TaskEvent::Aborted`], so a teardown race cannot
//!   swallow a worker's commit silently.
//!
//! # Lossy vs. lossless backpressure
//!
//! A bounded queue must distinguish what it may drop from what it must not:
//!
//! | Class | Examples | Under pressure |
//! |---|---|---|
//! | [`TaskClass::Lossy`] — coalescent telemetry | `Progress`, intermediate `SetText`/`SetValue` samples | sent with [`UiProxy::post`]; on [`TaskSendError::Full`] the worker skips the sample (the next one supersedes it) |
//! | [`TaskClass::Lossless`] — essential lifecycle | `Finished`, `Failed`, and final transactional commits | sent with [`UiProxy::send_lossless`], which blocks (with backoff) until the queue accepts the command, the UI is gone, or the caller's timeout expires |
//!
//! Dropping a lossless token strands the UI state machine (a progress bar
//! that never completes, a worker whose result never lands), so
//! [`TaskCommand::class`] names the default class of every command and
//! [`UiProxy::send_lossless`] is the guaranteed path. A lossless send never
//! waits forever: a worker that cannot make progress reports
//! [`TaskSendError::Full`] to its caller instead of hanging, and a worker
//! whose UI is gone stops on [`TaskSendError::Closed`].

use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::error::GuiError;
use crate::widgets::WidgetId;

/// Default capacity of the UI command channel created by
/// [`crate::Ui::task_proxy`].
///
/// The bound keeps a runaway worker from growing the queue without limit; a
/// full queue is reported to the worker as [`TaskSendError::Full`] so it can
/// back off or drop intermediate progress updates.
pub const DEFAULT_TASK_QUEUE_CAPACITY: usize = 256;

/// Initial retry backoff for [`UiProxy::send_lossless`].
const LOSSLESS_RETRY_BACKOFF_START: Duration = Duration::from_micros(50);

/// Upper bound for the [`UiProxy::send_lossless`] retry backoff.
const LOSSLESS_RETRY_BACKOFF_MAX: Duration = Duration::from_millis(2);

/// Identifier for one background operation started through
/// [`UiProxy::start_task`].
///
/// IDs are allocated by the proxy (unique per proxy, starting at 1) and are
/// stable for the whole operation, matching the "operation IDs" contract
/// shared across async operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TaskId(pub u64);

impl fmt::Display for TaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "task-{}", self.0)
    }
}

/// A command posted from a worker thread to the UI thread.
///
/// Widget commands mutate a widget exactly like the matching
/// `Ui::set_*` call; lifecycle commands produce
/// [`crate::UiEvent::Task`] notifications instead of touching natives.
#[derive(Debug, Clone, PartialEq)]
pub enum TaskCommand {
    /// Replaces rows in a DataList/ListView widget.
    SetDataListItems {
        widget_id: WidgetId,
        items: Vec<String>,
    },
    /// Replaces rows in a DataGrid widget.
    SetDataGridRows {
        widget_id: WidgetId,
        rows: Vec<Vec<String>>,
    },
    /// Updates text content for a widget.
    SetText { widget_id: WidgetId, text: String },
    /// Sets numeric value for Slider/SpinBox/ProgressBar widgets.
    SetValue { widget_id: WidgetId, value: i32 },
    /// Sets checked state for check-capable widgets.
    SetChecked { widget_id: WidgetId, checked: bool },
    /// Enables or disables a widget.
    SetEnabled { widget_id: WidgetId, enabled: bool },
    /// Shows or hides a widget.
    SetVisible { widget_id: WidgetId, visible: bool },
    /// Reports intermediate progress for a task (0.0–100.0 by convention).
    Progress { task: TaskId, value: f64 },
    /// Reports that a task finished; posted once per task (duplicates are
    /// delivered as-is so the UI layer can decide how strict to be).
    Finished { task: TaskId },
    /// Reports that a task failed with a human-readable message.
    Failed { task: TaskId, message: String },
}

/// Channel class of a [`TaskCommand`] under queue pressure.
///
/// The bounded queue (see [`DEFAULT_TASK_QUEUE_CAPACITY`]) rejects posts when
/// it is full. What the *sender* should do about that depends on the command:
///
/// - [`TaskClass::Lossy`] commands are coalescent telemetry. Skipping one is
///   harmless because the next sample supersedes it, so workers send them
///   with [`UiProxy::post`] and drop on [`TaskSendError::Full`].
/// - [`TaskClass::Lossless`] commands are essential lifecycle tokens. Losing
///   one strands the UI state machine (a task that never completes), so
///   workers send them with [`UiProxy::send_lossless`], which waits for room
///   with backoff.
///
/// The class is a *default*, not a straitjacket: a widget mutation that
/// commits a transaction (for example the final result of a search) should
/// also travel through [`UiProxy::send_lossless`] even though its command
/// class is [`TaskClass::Lossy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskClass {
    /// Coalescent telemetry: safe to drop under pressure.
    Lossy,
    /// Essential lifecycle: must not be silently dropped.
    Lossless,
}

/// The widget-targeting [`TaskCommand`] family.
///
/// Carried by [`TaskEvent::Aborted`] as a lightweight name for the command
/// that did not apply, so applications can tell an aborted intermediate
/// telemetry sample from an aborted final commit without matching the full
/// payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskCommandKind {
    SetDataListItems,
    SetDataGridRows,
    SetText,
    SetValue,
    SetChecked,
    SetEnabled,
    SetVisible,
}

impl TaskCommand {
    /// The command's default channel class (see [`TaskClass`]).
    ///
    /// `Finished` and `Failed` are lossless because the UI state machine
    /// depends on them; every other command is coalescent telemetry by
    /// default (intermediate state publishes that the next sample or the
    /// final commit supersedes).
    pub fn class(&self) -> TaskClass {
        match self {
            TaskCommand::Finished { .. } | TaskCommand::Failed { .. } => TaskClass::Lossless,
            TaskCommand::SetDataListItems { .. }
            | TaskCommand::SetDataGridRows { .. }
            | TaskCommand::SetText { .. }
            | TaskCommand::SetValue { .. }
            | TaskCommand::SetChecked { .. }
            | TaskCommand::SetEnabled { .. }
            | TaskCommand::SetVisible { .. }
            | TaskCommand::Progress { .. } => TaskClass::Lossy,
        }
    }

    /// The widget this command mutates, with its kind name; `None` for
    /// lifecycle commands (`Progress`/`Finished`/`Failed`) that carry no
    /// widget target.
    pub fn widget_target(&self) -> Option<(WidgetId, TaskCommandKind)> {
        match self {
            TaskCommand::SetDataListItems { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetDataListItems))
            }
            TaskCommand::SetDataGridRows { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetDataGridRows))
            }
            TaskCommand::SetText { widget_id, .. } => Some((*widget_id, TaskCommandKind::SetText)),
            TaskCommand::SetValue { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetValue))
            }
            TaskCommand::SetChecked { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetChecked))
            }
            TaskCommand::SetEnabled { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetEnabled))
            }
            TaskCommand::SetVisible { widget_id, .. } => {
                Some((*widget_id, TaskCommandKind::SetVisible))
            }
            TaskCommand::Progress { .. }
            | TaskCommand::Finished { .. }
            | TaskCommand::Failed { .. } => None,
        }
    }
}

/// Why a queued widget command never reached the shared model.
///
/// [`TaskEvent::Aborted`] carries this so a worker that committed through
/// [`UiProxy::send_lossless`] can distinguish "the widget is gone" from
/// "the command landed": the dead-letter half of the lossless guarantees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskAbortReason {
    /// The target widget had already been removed when the drain ran - the
    /// teardown race that used to be swallowed by
    /// [`TaskDrainReport::rejected`].
    WidgetRemoved,
    /// The target widget is live but refused the mutation (kind guard,
    /// validated range, ...); the typed error is preserved for the
    /// application.
    Refused(GuiError),
}

/// Lifecycle notification for one background task, delivered to the UI
/// thread as [`crate::UiEvent::Task`].
#[derive(Debug, Clone, PartialEq)]
pub enum TaskEvent {
    /// Intermediate progress reported through [`UiProxy::progress`].
    Progress { task: TaskId, value: f64 },
    /// The task finished (completed or cancelled — the app decides which).
    Finished { task: TaskId },
    /// The task failed; `message` is app-defined (e.g. an I/O error).
    Failed { task: TaskId, message: String },
    /// A queued widget command was aborted before it could apply:
    /// its target was tombstoned by a teardown, or a
    /// live target refused the mutation.
    ///
    /// One event is emitted per aborted command, in drain order, and the
    /// same commands are counted by [`TaskDrainReport::rejected`]. This is
    /// the dead-letter notification the lossless guarantees need: a worker
    /// whose final commit lost its widget learns about it instead of facing
    /// silence. Treat the first abort for a tombstoned widget as the signal
    /// to stop that worker.
    Aborted {
        /// The widget the aborted command targeted.
        widget_id: WidgetId,
        /// Which command was aborted.
        command: TaskCommandKind,
        /// Why the command did not apply.
        reason: TaskAbortReason,
    },
}

/// Why a [`UiProxy`] post was not accepted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskSendError {
    /// The bounded queue is full.
    ///
    /// [`UiProxy::post`] reports it immediately — the lossy caller drops the
    /// sample or retries later. [`UiProxy::send_lossless`] reports it only
    /// after its retry deadline expired, so a lossless caller knows the
    /// command was **not** queued.
    Full,
    /// The owning [`crate::Ui`] is gone; the worker should stop.
    Closed,
}

impl fmt::Display for TaskSendError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskSendError::Full => write!(f, "background task queue is full"),
            TaskSendError::Closed => write!(f, "UI thread command channel is closed"),
        }
    }
}

impl std::error::Error for TaskSendError {}

/// Outcome of one [`crate::Ui::drain_task_commands`] call.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TaskDrainReport {
    /// Commands applied successfully (including lifecycle notifications).
    pub applied: usize,
    /// Commands rejected because their target widget is gone or the backend
    /// refused the mutation. Rejections never panic and never stop the drain.
    pub rejected: usize,
}

impl TaskDrainReport {
    /// Total number of commands processed by the drain.
    pub fn total(&self) -> usize {
        self.applied + self.rejected
    }
}

/// Cancellation handle shared between the UI thread and one worker.
///
/// The UI thread keeps a clone and calls [`TaskToken::cancel`]; the worker
/// keeps another clone and polls [`TaskToken::is_cancelled`] between chunks
/// of work. Cancellation is cooperative: the worker decides where it is safe
/// to stop and then posts its final [`TaskCommand::Finished`].
#[derive(Debug, Clone)]
pub struct TaskToken {
    id: TaskId,
    cancelled: Arc<AtomicBool>,
}

impl TaskToken {
    /// The identifier of the task this token belongs to.
    pub fn id(&self) -> TaskId {
        self.id
    }

    /// Requests cancellation. Safe to call from any thread; idempotent.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Returns `true` once [`TaskToken::cancel`] was called.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    /// Sleeps for up to `duration`, returning early if cancellation is requested.
    ///
    /// Returns `true` if the full `duration` elapsed without cancellation, or `false`
    /// immediately if cancellation was requested (either prior to this call or during the sleep).
    /// Polling quantum is bounded (at most 25ms) to guarantee prompt cancellation response
    /// without CPU spinning.
    pub fn sleep_or_cancelled(&self, duration: Duration) -> bool {
        if self.is_cancelled() {
            return false;
        }
        let start = Instant::now();
        let quantum = Duration::from_millis(25);
        while start.elapsed() < duration {
            if self.is_cancelled() {
                return false;
            }
            let remaining = duration.saturating_sub(start.elapsed());
            let step = remaining.min(quantum);
            std::thread::sleep(step);
        }
        !self.is_cancelled()
    }
}

/// Handle returned by [`crate::Ui::spawn_task_with_callback`] representing an active background
/// task.
///
/// Can be retained on the UI thread to query status, obtain the task ID, or cancel the task.
#[derive(Debug, Clone)]
pub struct TaskHandle {
    token: TaskToken,
    finished: Arc<AtomicBool>,
}

impl TaskHandle {
    /// Creates a new task handle wrapping `token`.
    pub fn new(token: TaskToken) -> Self {
        Self {
            token,
            finished: Arc::new(AtomicBool::new(false)),
        }
    }

    /// The identifier of the background operation.
    pub fn id(&self) -> TaskId {
        self.token.id()
    }

    /// Requests cancellation of the background operation.
    pub fn cancel(&self) {
        self.token.cancel();
    }

    /// Returns `true` if cancellation has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.token.is_cancelled()
    }

    /// Returns `true` if the background operation has completed.
    pub fn is_finished(&self) -> bool {
        self.finished.load(Ordering::SeqCst)
    }

    /// Borrows the inner [`TaskToken`].
    pub fn token(&self) -> &TaskToken {
        &self.token
    }

    /// Marks the handle as finished.
    pub(crate) fn mark_finished(&self) {
        self.finished.store(true, Ordering::SeqCst);
    }
}

/// Cloneable, `Send + Sync` handle used by background threads to post
/// [`TaskCommand`]s to the UI thread.
///
/// Obtained from [`crate::Ui::task_proxy`]. Clones share one bounded queue
/// and one task-ID counter. Every successful post invokes the backend's wake
/// hook (when the backend has one) so a blocked `wait_event` returns promptly
/// and the UI thread can drain the queue.
#[derive(Clone)]
pub struct UiProxy {
    inner: Arc<UiProxyInner>,
}

struct UiProxyInner {
    sender: SyncSender<TaskCommand>,
    wake: Option<Arc<dyn Fn() + Send + Sync>>,
    next_task: AtomicU64,
    capacity: usize,
}

impl fmt::Debug for UiProxy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UiProxy")
            .field("capacity", &self.inner.capacity)
            .field("has_wake_hook", &self.inner.wake.is_some())
            .finish()
    }
}

impl UiProxy {
    /// Creates a proxy plus the receiving end owned by the UI thread.
    ///
    /// `wake` is the backend's event-loop wake hook ([`crate::Backend::wake_handle`]);
    /// `capacity` is clamped to at least 1.
    pub(crate) fn new(
        wake: Option<Arc<dyn Fn() + Send + Sync>>,
        capacity: usize,
    ) -> (Self, Receiver<TaskCommand>) {
        let capacity = capacity.max(1);
        let (sender, receiver) = sync_channel(capacity);
        let proxy = Self {
            inner: Arc::new(UiProxyInner {
                sender,
                wake,
                next_task: AtomicU64::new(1),
                capacity,
            }),
        };
        (proxy, receiver)
    }

    /// Posts a command to the UI thread (lossy path).
    ///
    /// Returns [`TaskSendError::Full`] when the bounded queue is full and
    /// [`TaskSendError::Closed`] after the owning `Ui` was dropped. This is
    /// the right path for [`TaskClass::Lossy`] telemetry: on `Full`, skip the
    /// sample — the next one supersedes it. Essential lifecycle tokens use
    /// [`UiProxy::send_lossless`] instead.
    pub fn post(&self, command: TaskCommand) -> Result<(), TaskSendError> {
        match self.inner.sender.try_send(command) {
            Ok(()) => {
                self.wake();
                Ok(())
            }
            Err(TrySendError::Full(_)) => Err(TaskSendError::Full),
            Err(TrySendError::Disconnected(_)) => Err(TaskSendError::Closed),
        }
    }

    /// Posts a command losslessly: waits (with backoff) until the bounded
    /// queue has room.
    ///
    /// This is the guaranteed path for [`TaskClass::Lossless`] commands
    /// (`Finished`, `Failed`, final transactional commits). [`UiProxy::post`]
    /// is the lossy counterpart for coalescent telemetry.
    ///
    /// The wait is bounded by `timeout`, so a stalled UI thread can never
    /// hang the worker forever:
    ///
    /// - `Ok(())` — the command is queued and will be applied in FIFO order
    ///   (the backend wake hook is signalled, so a parked `wait_event`
    ///   returns promptly);
    /// - `Err(TaskSendError::Closed)` — the owning `Ui` is gone; stop the
    ///   worker;
    /// - `Err(TaskSendError::Full)` — `timeout` elapsed while the queue
    ///   stayed full. The command was **not** queued, so the caller decides
    ///   what to do (surface the error, retry with a longer timeout, or
    ///   degrade explicitly); it is never reported as success and never
    ///   silently dropped.
    ///
    /// ```
    /// use native_gui_mock::MockBackend;
    /// use native_gui_core::{TaskEvent, Ui, UiEvent};
    /// use std::time::Duration;
    ///
    /// let mut ui = Ui::new(MockBackend::default());
    /// let proxy = ui.task_proxy();
    /// let token = proxy.start_task();
    ///
    /// let worker_proxy = proxy.clone();
    /// let worker = std::thread::spawn(move || {
    ///     // ... do the slow work ...
    ///     worker_proxy
    ///         .finish_lossless(&token, Duration::from_secs(5))
    ///         .expect("the completion token must reach the UI thread");
    /// });
    /// worker.join().expect("worker thread");
    ///
    /// ui.drain_task_commands();
    /// let event = ui.poll_event().expect("poll").expect("lifecycle event");
    /// assert!(matches!(event, UiEvent::Task(TaskEvent::Finished { .. })));
    /// ```
    pub fn send_lossless(
        &self,
        command: TaskCommand,
        timeout: Duration,
    ) -> Result<(), TaskSendError> {
        let deadline = Instant::now() + timeout;
        let mut backoff = LOSSLESS_RETRY_BACKOFF_START;
        let mut pending = command;
        loop {
            match self.inner.sender.try_send(pending) {
                Ok(()) => {
                    self.wake();
                    return Ok(());
                }
                Err(TrySendError::Full(command)) => {
                    if Instant::now() >= deadline {
                        return Err(TaskSendError::Full);
                    }
                    pending = command;
                    std::thread::sleep(backoff);
                    backoff = (backoff * 2).min(LOSSLESS_RETRY_BACKOFF_MAX);
                }
                Err(TrySendError::Disconnected(_)) => return Err(TaskSendError::Closed),
            }
        }
    }

    /// Signals the backend wake hook (when the backend has one) so a parked
    /// `wait_event` returns promptly and the UI thread drains the queue.
    fn wake(&self) {
        if let Some(wake) = &self.inner.wake {
            wake();
        }
    }

    /// Starts a new background operation and returns its cancellation token.
    ///
    /// IDs are unique per proxy; clone a token to the worker and keep one
    /// clone on the UI thread for [`TaskToken::cancel`].
    pub fn start_task(&self) -> TaskToken {
        let id = TaskId(self.inner.next_task.fetch_add(1, Ordering::SeqCst));
        TaskToken {
            id,
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// The bounded capacity of this proxy's command queue.
    pub fn capacity(&self) -> usize {
        self.inner.capacity
    }

    /// Posts [`TaskCommand::SetText`].
    pub fn set_text(
        &self,
        widget_id: WidgetId,
        text: impl Into<String>,
    ) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetText {
            widget_id,
            text: text.into(),
        })
    }

    /// Posts a collection replacement for a list widget.
    pub fn set_data_list_items(
        &self,
        widget_id: WidgetId,
        items: impl IntoIterator<Item = String>,
    ) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetDataListItems {
            widget_id,
            items: items.into_iter().collect(),
        })
    }

    /// Posts a row-major collection replacement for a data grid.
    pub fn set_data_grid_rows(
        &self,
        widget_id: WidgetId,
        rows: impl IntoIterator<Item = Vec<String>>,
    ) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetDataGridRows {
            widget_id,
            rows: rows.into_iter().collect(),
        })
    }

    /// Posts [`TaskCommand::SetValue`].
    pub fn set_value(&self, widget_id: WidgetId, value: i32) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetValue { widget_id, value })
    }

    /// Posts [`TaskCommand::SetChecked`].
    pub fn set_checked(&self, widget_id: WidgetId, checked: bool) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetChecked { widget_id, checked })
    }

    /// Posts [`TaskCommand::SetEnabled`].
    pub fn set_enabled(&self, widget_id: WidgetId, enabled: bool) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetEnabled { widget_id, enabled })
    }

    /// Posts [`TaskCommand::SetVisible`].
    pub fn set_visible(&self, widget_id: WidgetId, visible: bool) -> Result<(), TaskSendError> {
        self.post(TaskCommand::SetVisible { widget_id, visible })
    }

    /// Posts [`TaskCommand::Progress`] for the given task (lossy sample).
    ///
    /// Progress is coalescent telemetry: on [`TaskSendError::Full`] skip the
    /// sample — the next one supersedes it. The completion token still
    /// arrives through [`UiProxy::finish_lossless`].
    pub fn progress(&self, token: &TaskToken, value: f64) -> Result<(), TaskSendError> {
        self.post(TaskCommand::Progress {
            task: token.id(),
            value,
        })
    }

    /// Posts [`TaskCommand::Finished`] for the given task (lossy path).
    ///
    /// Prefer [`UiProxy::finish_lossless`] in real workers: a completion
    /// token dropped at queue capacity can strand the UI state machine.
    pub fn finish(&self, token: &TaskToken) -> Result<(), TaskSendError> {
        self.post(TaskCommand::Finished { task: token.id() })
    }

    /// Posts [`TaskCommand::Failed`] for the given task (lossy path).
    ///
    /// Prefer [`UiProxy::fail_lossless`] in real workers: an error token
    /// dropped at queue capacity can strand the UI state machine.
    pub fn fail(&self, token: &TaskToken, message: impl Into<String>) -> Result<(), TaskSendError> {
        self.post(TaskCommand::Failed {
            task: token.id(),
            message: message.into(),
        })
    }

    /// Posts [`TaskCommand::Finished`] losslessly (see
    /// [`UiProxy::send_lossless`]).
    pub fn finish_lossless(
        &self,
        token: &TaskToken,
        timeout: Duration,
    ) -> Result<(), TaskSendError> {
        self.send_lossless(TaskCommand::Finished { task: token.id() }, timeout)
    }

    /// Posts [`TaskCommand::Failed`] losslessly (see
    /// [`UiProxy::send_lossless`]).
    pub fn fail_lossless(
        &self,
        token: &TaskToken,
        message: impl Into<String>,
        timeout: Duration,
    ) -> Result<(), TaskSendError> {
        self.send_lossless(
            TaskCommand::Failed {
                task: token.id(),
                message: message.into(),
            },
            timeout,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn proxy(capacity: usize) -> (UiProxy, Receiver<TaskCommand>) {
        UiProxy::new(None, capacity)
    }

    #[test]
    fn task_ids_are_unique_and_monotonic() {
        let (proxy, _receiver) = proxy(4);
        let first = proxy.start_task();
        let second = proxy.start_task();
        let clone = proxy.clone();
        let third = clone.start_task();

        assert_eq!(first.id(), TaskId(1));
        assert_eq!(second.id(), TaskId(2));
        assert_eq!(third.id(), TaskId(3));
        // Clones share the ID counter.
        assert_ne!(first.id(), third.id());
    }

    #[test]
    fn cancellation_flag_is_visible_across_clones() {
        let (proxy, _receiver) = proxy(4);
        let ui_side = proxy.start_task();
        let worker_side = ui_side.clone();

        assert!(!worker_side.is_cancelled());
        ui_side.cancel();
        assert!(worker_side.is_cancelled());
        // Idempotent.
        ui_side.cancel();
        assert!(worker_side.is_cancelled());
    }

    #[test]
    fn posts_fail_closed_after_receiver_drops() {
        let (proxy, receiver) = proxy(4);
        drop(receiver);
        assert_eq!(
            proxy.post(TaskCommand::Finished { task: TaskId(1) }),
            Err(TaskSendError::Closed)
        );
        assert_eq!(
            proxy.finish(&TaskToken {
                id: TaskId(1),
                cancelled: Arc::new(AtomicBool::new(false))
            }),
            Err(TaskSendError::Closed)
        );
    }

    #[test]
    fn queue_bound_rejects_then_recovers() {
        let (proxy, receiver) = proxy(3);
        assert_eq!(proxy.capacity(), 3);

        for _ in 0..3 {
            assert_eq!(proxy.set_value(WidgetId(1), 1), Ok(()));
        }
        assert_eq!(proxy.set_value(WidgetId(1), 1), Err(TaskSendError::Full));

        // Draining one slot lets the next post through again.
        let _ = receiver.try_recv().expect("queued command");
        assert_eq!(proxy.set_value(WidgetId(1), 2), Ok(()));
    }

    #[test]
    fn commands_are_received_in_fifo_order() {
        let (proxy, receiver) = proxy(8);
        let token = proxy.start_task();

        proxy.set_text(WidgetId(1), "first").expect("post");
        proxy.progress(&token, 50.0).expect("post");
        proxy.set_text(WidgetId(1), "second").expect("post");

        assert_eq!(
            receiver.try_recv().expect("cmd"),
            TaskCommand::SetText {
                widget_id: WidgetId(1),
                text: "first".to_owned()
            }
        );
        assert_eq!(
            receiver.try_recv().expect("cmd"),
            TaskCommand::Progress {
                task: token.id(),
                value: 50.0
            }
        );
        assert_eq!(
            receiver.try_recv().expect("cmd"),
            TaskCommand::SetText {
                widget_id: WidgetId(1),
                text: "second".to_owned()
            }
        );
    }

    #[test]
    fn lifecycle_helpers_carry_the_task_id() {
        let (proxy, receiver) = proxy(4);
        let token = proxy.start_task();

        proxy.finish(&token).expect("post");
        proxy.fail(&token, "boom").expect("post");

        assert_eq!(
            receiver.try_recv().expect("cmd"),
            TaskCommand::Finished { task: token.id() }
        );
        assert_eq!(
            receiver.try_recv().expect("cmd"),
            TaskCommand::Failed {
                task: token.id(),
                message: "boom".to_owned()
            }
        );
    }

    #[test]
    fn proxy_and_token_are_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<UiProxy>();
        assert_send_sync::<TaskToken>();
        assert_send_sync::<TaskSendError>();
    }

    #[test]
    fn drain_report_totals_add_up() {
        let report = TaskDrainReport {
            applied: 3,
            rejected: 2,
        };
        assert_eq!(report.total(), 5);
    }

    #[test]
    fn command_class_taxonomy_matches_the_documented_split() {
        let task = TaskId(1);
        let lossless = [
            TaskCommand::Finished { task },
            TaskCommand::Failed {
                task,
                message: "boom".to_owned(),
            },
        ];
        for command in lossless {
            assert_eq!(command.class(), TaskClass::Lossless, "{command:?}");
        }

        let lossy = [
            TaskCommand::SetDataListItems {
                widget_id: WidgetId(1),
                items: vec!["row".to_owned()],
            },
            TaskCommand::SetDataGridRows {
                widget_id: WidgetId(1),
                rows: vec![vec!["cell".to_owned()]],
            },
            TaskCommand::SetText {
                widget_id: WidgetId(1),
                text: "text".to_owned(),
            },
            TaskCommand::SetValue {
                widget_id: WidgetId(1),
                value: 1,
            },
            TaskCommand::SetChecked {
                widget_id: WidgetId(1),
                checked: true,
            },
            TaskCommand::SetEnabled {
                widget_id: WidgetId(1),
                enabled: true,
            },
            TaskCommand::SetVisible {
                widget_id: WidgetId(1),
                visible: false,
            },
            TaskCommand::Progress { task, value: 50.0 },
        ];
        for command in lossy {
            assert_eq!(command.class(), TaskClass::Lossy, "{command:?}");
        }
    }

    #[test]
    fn lossless_send_waits_for_capacity_instead_of_dropping() {
        let (proxy, receiver) = proxy(2);
        proxy.set_value(WidgetId(1), 1).expect("fills slot 1");
        proxy.set_value(WidgetId(1), 2).expect("fills slot 2");
        assert_eq!(proxy.set_value(WidgetId(1), 3), Err(TaskSendError::Full));

        let worker_proxy = proxy.clone();
        let worker = std::thread::spawn(move || {
            worker_proxy.send_lossless(
                TaskCommand::Finished { task: TaskId(9) },
                Duration::from_secs(5),
            )
        });

        // The queue is saturated, so the lossless send must still be waiting.
        std::thread::sleep(Duration::from_millis(20));
        let _ = receiver.try_recv().expect("drained slot 1");
        let _ = receiver.try_recv().expect("drained slot 2");
        worker
            .join()
            .expect("worker thread")
            .expect("lossless send must succeed once capacity frees up");

        assert_eq!(
            receiver.try_recv().expect("queued completion"),
            TaskCommand::Finished { task: TaskId(9) },
            "the lossless command is queued after the drained samples"
        );
    }

    #[test]
    fn lossless_send_times_out_without_silently_dropping() {
        let (proxy, receiver) = proxy(1);
        proxy.set_value(WidgetId(1), 1).expect("fills the queue");

        let error = proxy
            .send_lossless(TaskCommand::Finished { task: TaskId(9) }, Duration::ZERO)
            .expect_err("a full queue with no slack must report Full");
        assert_eq!(error, TaskSendError::Full);

        // The command was not queued behind the blocked sample.
        assert_eq!(
            receiver.try_recv().expect("original sample"),
            TaskCommand::SetValue {
                widget_id: WidgetId(1),
                value: 1
            }
        );
        assert!(
            receiver.try_recv().is_err(),
            "a timed-out lossless send must not leave a partial post behind"
        );

        // With capacity, the same call succeeds immediately.
        proxy
            .send_lossless(TaskCommand::Finished { task: TaskId(10) }, Duration::ZERO)
            .expect("zero timeout succeeds when there is room");
        assert_eq!(
            receiver.try_recv().expect("queued completion"),
            TaskCommand::Finished { task: TaskId(10) }
        );
    }

    #[test]
    fn lossless_send_fails_fast_when_the_ui_is_gone() {
        let (proxy, receiver) = proxy(1);
        drop(receiver);
        assert_eq!(
            proxy.send_lossless(
                TaskCommand::Finished { task: TaskId(1) },
                Duration::from_secs(30)
            ),
            Err(TaskSendError::Closed),
            "a closed channel must not wait out the timeout"
        );
    }

    #[test]
    fn task_handle_lifecycle_and_cancellation() {
        let (proxy, _receiver) = proxy(4);
        let token = proxy.start_task();
        let handle = TaskHandle::new(token.clone());

        assert_eq!(handle.id(), token.id());
        assert!(!handle.is_cancelled());
        assert!(!handle.is_finished());

        handle.cancel();
        assert!(handle.is_cancelled());
        assert!(token.is_cancelled());

        handle.mark_finished();
        assert!(handle.is_finished());
    }

    #[test]
    fn test_b1491_sleep_or_cancelled_completes_when_not_cancelled() {
        let (proxy, _receiver) = proxy(4);
        let token = proxy.start_task();
        let start = Instant::now();
        let ok = token.sleep_or_cancelled(Duration::from_millis(60));
        assert!(ok, "un-cancelled sleep should return true");
        assert!(start.elapsed() >= Duration::from_millis(50));
    }

    #[test]
    fn test_b1491_sleep_or_cancelled_returns_immediately_if_already_cancelled() {
        let (proxy, _receiver) = proxy(4);
        let token = proxy.start_task();
        token.cancel();
        let start = Instant::now();
        let ok = token.sleep_or_cancelled(Duration::from_secs(10));
        assert!(!ok, "pre-cancelled sleep should return false");
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "pre-cancelled sleep must return without waiting out the 10s sleep"
        );
    }

    #[test]
    fn test_b1491_sleep_or_cancelled_awakens_early_on_cancellation() {
        let (proxy, _receiver) = proxy(4);
        let token = proxy.start_task();
        let cancel_token = token.clone();

        let cancel_thread = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(40));
            cancel_token.cancel();
        });

        let start = Instant::now();
        // Request a 5-second sleep; cancellation at 40ms must cut it short. The
        // bound sits well below the full sleep but leaves room for slow, shared
        // CI runners, where thread wake-ups can lag by hundreds of milliseconds.
        let ok = token.sleep_or_cancelled(Duration::from_secs(5));
        assert!(!ok, "sleep interrupted by cancel should return false");
        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_secs(2),
            "expected early cancellation awakening, took {elapsed:?}"
        );
        cancel_thread.join().unwrap();
    }
}