rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Status bar widget.
//!
//! # The two messages are two columns of one assembled row
//!
//! BLUE22 §B.8 lists this control's defect as "multiple segments by hand, the last position
//! hard-coded". The strip really is a row of segments — a transient message on the leading side and
//! a permanent one on the trailing side — so `StatusBar::segment_boxes` derives both boxes from
//! one set of terms: the strip's padding, the grip's own box, and the trailing edge. The permanent
//! column is as wide as the grip's reserve and ends at the trailing edge (the `FlexEnd` statement),
//! and the transient column fills the room that is left (the `fill` statement). Neither position is
//! a literal, and neither segment is placed against the other's assumption.
//!
//! The grip keeps its own derived box (it is a corner affordance, not a row segment), and its
//! reserve is read from that box — the reserve is a width the permanent column carries rather than
//! a subtraction from the message's width.

use crate::compat::{Rc, RefCell, String, ToString, Vec};
use crate::core::{Color, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::expect_string;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{dimensions, effective_font};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Status bar widget — shows status messages and permanent widgets.
///
/// Holds two independent strings: a transient `message` on the left and a
/// `permanent_message` on the right. The transient message is cleared when its
/// caller-supplied timeout elapses; the permanent message stays until replaced.
/// See [`StatusBar::show_message`].
///
pub struct StatusBar {
    base: BaseWidget,
    message: String,
    permanent_message: String,
    size_grip_enabled: bool,
    /// Remaining lifetime of the transient message, or `None` for "until replaced".
    ///
    /// Stored as the timeout itself plus [`StatusBar::elapsed_ms`] rather than an
    /// absolute deadline: the widget is driven by `Widget::tick(delta_ms)`, which has
    /// no clock, so a deadline in milliseconds-since-start would need one it does not
    /// have.
    message_deadline_ms: Option<u64>,
    /// Milliseconds accumulated against [`StatusBar::message_deadline_ms`].
    elapsed_ms: u64,
    /// Emitted with the new message text whenever a **visible** message change occurs —
    /// including the empty string emitted by [`StatusBar::clear_message`]. A disabled status
    /// bar shows no message, so [`StatusBar::show_message`] stores the value without emitting;
    /// see that method's "Disabled contract" section. Changing the permanent message does
    /// **not** emit it.
    pub message_changed: Signal1<String>,
    /// Child widgets shown on the strip.
    widgets: Vec<StatusSlot>,
    /// The press origin of an active size-grip drag and the last delta reported.
    grip_drag: Option<(Point, (i32, i32))>,
    /// Emitted while the size grip is dragged, with the total delta since the press.
    ///
    /// The status bar does not resize anything itself: it has no window handle and no
    /// layout authority, so it reports the gesture and the host applies it. Emitting a
    /// total delta (rather than per-frame increments) lets a host that missed a frame
    /// still resize to the right place.
    pub size_grip_dragged: Signal1<(i32, i32)>,
    /// The cached child boxes, keyed by [`Self::slot_signature`].
    ///
    /// `slot_bands` is read by the painter, the hit test, `text_area` and `widget_rect` in one
    /// frame. Deriving it once per geometry/child-set revision means those readers share one
    /// run instead of each allocating a fresh `Vec` (G-P04).
    slot_bands_cache: SlotBandsCache,
}

/// The cached child boxes and the signature they were built for.
type SlotBandsCache = RefCell<Option<(u64, Rc<Vec<(usize, Rect)>>)>>;

/// One child placed on the status strip.
struct StatusSlot {
    widget: Box<dyn Widget>,
    permanent: bool,
}
impl StatusBar {
    /// Creates an empty status bar with the size grip enabled.
    ///
    /// `geometry` is in parent-relative logical pixels; the size hint is 400x24.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::StatusBar, geometry, "StatusBar"),
            message: String::new(),
            permanent_message: String::new(),
            size_grip_enabled: true,
            message_deadline_ms: None,
            elapsed_ms: 0,
            message_changed: Signal1::new(),
            widgets: Vec::new(),
            grip_drag: None,
            size_grip_dragged: Signal1::new(),
            slot_bands_cache: RefCell::new(None),
        }
    }
    /// Returns the transient message, or `""` when none is shown.
    pub fn message(&self) -> &str {
        &self.message
    }
    /// Returns the permanent message, or `""` when none is set.
    pub fn permanent_message(&self) -> &str {
        &self.permanent_message
    }
    /// Returns whether the resize grip is drawn. Defaults to `true`.
    ///
    /// The grip is the three diagonals [`StatusBar::draw`] paints in the strip's
    /// trailing corner, and `StatusBar::size_grip_rect` reserves the message's room
    /// for it. Disabling this flag removes both the ink and the reserve.
    pub fn size_grip_enabled(&self) -> bool {
        self.size_grip_enabled
    }
    /// Shows a transient message for `timeout_ms` milliseconds.
    ///
    /// A non-zero timeout schedules clearing through [`Widget::tick`]: the widget
    /// accumulates the frame deltas the runtime already delivers and calls
    /// [`StatusBar::clear_message`] when the timeout elapses. `0` keeps the message
    /// until it is replaced or cleared explicitly, which is what the property writer
    /// and the existing callers expect.
    ///
    /// Emits `message_changed` and requests a redraw.
    ///
    /// # Disabled contract
    ///
    /// A status message is user-visible text; a disabled status bar does not show it, so
    /// announcing the change would report a transition the user never saw. The message is
    /// still stored (the host owns the data) and the suppression is queryable through
    /// [`StatusBar::message_changed_suppression_reason`].
    pub fn show_message(&mut self, message: impl Into<String>, timeout_ms: u64) {
        self.message = message.into();
        self.elapsed_ms = 0;
        self.message_deadline_ms = (timeout_ms > 0).then_some(timeout_ms);
        // The strip paints the message, so a change to it is visible whether or not a host is
        // listening on `message_changed`. Request the repaint **before** the enabled check, so a
        // message stored while disabled still paints when the control is re-enabled.
        self.base.request_redraw();
        if !self.base.is_enabled() {
            // See `message_changed_suppression_reason`.
            return;
        }
        self.message_changed.emit(self.message.clone());
    }
    /// Clears the transient message and emits `message_changed` with an empty
    /// string. The permanent message is untouched.
    ///
    /// Gated by `enabled` for the same reason as [`StatusBar::show_message`].
    pub fn clear_message(&mut self) {
        self.message.clear();
        self.message_deadline_ms = None;
        self.elapsed_ms = 0;
        self.base.request_redraw();
        if !self.base.is_enabled() {
            // See `message_changed_suppression_reason`.
            return;
        }
        self.message_changed.emit(String::new());
    }

    /// Reports why the next message change would **not** emit `message_changed`, or `None`
    /// when the signal will fire.
    ///
    /// Without this, a host that wrote a message and observed no signal could not tell
    /// "the status bar is disabled" from "the message was already what I wrote".
    pub fn message_changed_suppression_reason(&self) -> Option<&'static str> {
        if !self.base.is_enabled() {
            return Some(
                "message_changed suppressed: the status bar is disabled, so the message is \
                 not user-visible",
            );
        }
        None
    }
    /// Replaces the permanent message and requests a redraw.
    ///
    /// Unlike the transient message this is not reported through
    /// `message_changed`, so a listener relying on that signal will miss it.
    pub fn set_permanent_message(&mut self, msg: impl Into<String>) {
        let msg = msg.into();
        if self.permanent_message == msg {
            return;
        }
        self.permanent_message = msg;
        self.base.request_redraw();
    }
    /// Enables or disables the resize grip and requests a redraw. See
    /// [`StatusBar::size_grip_enabled`] — the flag removes both the grip's ink and the
    /// room its box reserves for the permanent message.
    pub fn set_size_grip_enabled(&mut self, enabled: bool) {
        if self.size_grip_enabled == enabled {
            return;
        }
        self.size_grip_enabled = enabled;
        self.base.request_redraw();
    }
    /// Appends a transient child widget and returns its index.
    ///
    /// A transient widget sits in the message column, right-aligned, and yields to the
    /// permanent segment and the grip. It does not affect the default strip: with no
    /// children installed every box is exactly where it was.
    pub fn add_widget(&mut self, widget: Box<dyn Widget>) -> usize {
        self.widgets.push(StatusSlot { widget, permanent: false });
        self.base.request_redraw();
        self.widgets.len() - 1
    }

    /// Appends a permanent child widget and returns its index.
    ///
    /// A permanent widget sits in the permanent column, right-aligned before the grip.
    pub fn add_permanent_widget(&mut self, widget: Box<dyn Widget>) -> usize {
        self.widgets.push(StatusSlot { widget, permanent: true });
        self.base.request_redraw();
        self.widgets.len() - 1
    }

    /// Removes the child at `index`, returning it when the index was in range.
    pub fn remove_widget(&mut self, index: usize) -> Option<Box<dyn Widget>> {
        if index >= self.widgets.len() {
            return None;
        }
        let slot = self.widgets.remove(index);
        self.base.request_redraw();
        Some(slot.widget)
    }

    /// The number of child widgets on the strip.
    pub fn widget_count(&self) -> usize {
        self.widgets.len()
    }

    /// The child at `index`.
    pub fn widget(&self, index: usize) -> Option<&dyn Widget> {
        self.widgets.get(index).map(|slot| slot.widget.as_ref())
    }

    /// The child at `index`, mutably.
    pub fn widget_mut(&mut self, index: usize) -> Option<&mut (dyn Widget + '_)> {
        self.widgets.get_mut(index).map(|slot| slot.widget.as_mut())
    }

    /// Whether the child at `index` is permanent.
    pub fn widget_is_permanent(&self, index: usize) -> Option<bool> {
        self.widgets.get(index).map(|slot| slot.permanent)
    }

    /// The box every child occupies, in insertion order.
    fn slot_bands(&self) -> Rc<Vec<(usize, Rect)>> {
        let key = self.slot_signature();
        if let Some((cached_key, bands)) = self.slot_bands_cache.borrow().as_ref() {
            if *cached_key == key {
                return Rc::clone(bands);
            }
        }
        let bands = Rc::new(self.compute_slot_bands());
        *self.slot_bands_cache.borrow_mut() = Some((key, Rc::clone(&bands)));
        bands
    }

    /// A fold over the facts [`Self::compute_slot_bands`] reads.
    fn slot_signature(&self) -> u64 {
        let rect = self.geometry();
        let mut signature = (rect.x as u32 as u64).rotate_left(7)
            ^ (rect.y as u32 as u64).rotate_left(15)
            ^ (rect.width as u64).rotate_left(27)
            ^ (rect.height as u64).rotate_left(39);
        for (index, slot) in self.widgets.iter().enumerate() {
            let hint = slot.widget.size_hint();
            signature = signature.rotate_left(4)
                ^ (index as u64)
                ^ (hint.width as u64).rotate_left(20)
                ^ ((slot.permanent as u64) << 52);
        }
        signature
    }

    /// Rebuilds the child boxes; [`Self::slot_bands`] is the cached entry point.
    fn compute_slot_bands(&self) -> Vec<(usize, Rect)> {
        let band = self.geometry();
        let (message, permanent) = self.segment_boxes(band);
        let mut placed = Vec::with_capacity(self.widgets.len());
        for want_permanent in [true, false] {
            let area = if want_permanent { permanent } else { message };
            let mut cursor = area.x + area.width as i32;
            for (index, slot) in self.widgets.iter().enumerate() {
                if slot.permanent != want_permanent {
                    continue;
                }
                let width = slot.widget.size_hint().width.min(area.width);
                let rect = Rect::new(cursor - width as i32, area.y, width, area.height);
                cursor = rect.x - 4;
                placed.push((index, rect));
            }
        }
        placed.sort_by_key(|(index, _)| *index);
        placed
    }

    /// The box of the child at `index`, or `None` when the index is out of range.
    pub fn widget_rect(&self, index: usize) -> Option<Rect> {
        self.slot_bands().iter().copied().find(|(slot, _)| *slot == index).map(|(_, rect)| rect)
    }

    /// The part of `area` left after the children of one kind on its trailing side.
    fn text_area(&self, area: Rect, permanent: bool) -> Rect {
        let mut right = area.x + area.width as i32;
        for (index, rect) in self.slot_bands().iter().copied() {
            if self.widgets[index].permanent != permanent {
                continue;
            }
            right = right.min(rect.x - 4);
        }
        Rect::new(area.x, area.y, (right - area.x).max(0) as u32, area.height)
    }

    /// The size grip's public geometry, or `None` when the grip is disabled.
    ///
    /// A host that resizes its window from the status bar reads this instead of reconstructing
    /// the strip's arithmetic: the exposed box and the painted grip are one derivation (M-10).
    pub fn grip_rect(&self) -> Option<Rect> {
        self.size_grip_rect(self.geometry())
    }

    /// Whether `pos` lies in the size grip's hit region.
    pub fn grip_at(&self, pos: Point) -> bool {
        self.grip_rect().is_some_and(|grip| grip.contains_point(pos))
    }

    /// Whether a size-grip drag is in progress.
    pub fn is_grip_dragging(&self) -> bool {
        self.grip_drag.is_some()
    }

    /// The size grip's own box, or `None` when the grip is off.
    ///
    /// # Why the grip is a box and not a `- 14` literal
    ///
    /// The grip was drawn from `rect.x + width - 14` with three lines spanning 12 px, while the
    /// permanent message reserved `20` for it — two unrelated numbers for one object, so the
    /// measure of "how much room does the grip need" and the measure of "how much room does the
    /// grip use" could not be kept in agreement by inspection. The reserve and the drawing now
    /// read the same box.
    ///
    /// `STATUS_GRIP_SIZE` is a named constant because it is also the answer to "how far from the
    /// strip's corner does the grip sit", which is what the reserve is derived from.
    fn size_grip_rect(&self, band: Rect) -> Option<Rect> {
        if !self.size_grip_enabled {
            return None;
        }
        let size = dimensions::STATUS_GRIP_SIZE.min(band.width).min(band.height);
        // Inset from the corner by the strip's own padding, so the grip's distance from the edge
        // is the same fact as the message's distance from the edge.
        let inset = dimensions::STATUS_BAR_PADDING_H;
        Some(Rect::new(
            band.x + band.width.saturating_sub(size + inset) as i32,
            band.y + band.height.saturating_sub(size + inset) as i32,
            size,
            size,
        ))
    }

    /// The width the permanent message must leave for the grip: 0 when there is no grip.
    ///
    /// Derived from the grip's own box (plus its leading gap), so a wider grip narrows the
    /// message rather than the two overlapping. It is handed to the row as the trailing column's
    /// own width, so the message column's `fill` cannot absorb it.
    fn grip_reserve(&self, band: Rect) -> u32 {
        match self.size_grip_rect(band) {
            Some(grip) => {
                { band.x + band.width as i32 - grip.x + dimensions::STATUS_BAR_PADDING_H as i32 }
                    .max(0) as u32
            }
            None => 0,
        }
    }

    /// The transient message's box and the permanent message's box.
    ///
    /// # Why the segments are assembled rather than subtracted
    ///
    /// The permanent message used to be drawn at `rect.x + 6` with a width of
    /// `rect.width - reserved` and `HorizontalAlignment::Right` — a right-anchored label expressed
    /// as "start at the leading edge and be as wide as everything except the grip", which is a
    /// different statement from "sit against the trailing edge". The two agree only while nothing
    /// else is on the strip; the moment the message needs a box of its own, or the grip's reserve
    /// changes, the spelling has to be re-derived. Anchoring the column to the trailing edge makes
    /// the anchor a property of the derivation, which is how it cannot be forgotten at a call site.
    ///
    /// # The row, expressed as arithmetic
    ///
    /// The two columns used to be handed to a `FlexLayout` rebuilt on every call — two widgets, a
    /// composite, a layout and a `Vec` of results per frame, to place two rectangles whose
    /// relationship is three numbers. The row was `JustifyContent::FlexEnd` with a `fill` leading
    /// column and zero gap, and that resolves to exactly this:
    ///
    /// * the trailing column's drawn width is `max(reserve, padding)`: the `fill` column cannot
    ///   absorb it, so "the reserve is a size the column carries" and "the column is at least that
    ///   wide" are the same statement;
    /// * its box ends at the strip's trailing edge — the `FlexEnd` anchor;
    /// * both columns declare the strip's padding as a leading margin, so the transient box starts
    ///   one padding inside the leading edge and stops one padding short of the trailing column.
    ///   The two leading margins are the gap between the columns.
    ///
    /// The trailing column is clamped to the strip's own width, and the leading one to the strip's
    /// own box: a strip narrower than the reserve would otherwise place a column outside the
    /// control it belongs to (`FlexLayout` resolves the same squeeze by scaling both columns).
    fn segment_boxes(&self, band: Rect) -> (Rect, Rect) {
        let padding = dimensions::STATUS_BAR_PADDING_H;
        let permanent_width = self.grip_reserve(band).max(padding).min(band.width);
        let permanent_x = band.x + band.width.saturating_sub(permanent_width) as i32;
        let message_x = band.x + padding.min(band.width) as i32;
        let message_width = (permanent_x - padding as i32 - message_x).max(0) as u32;
        (
            Rect::new(message_x, band.y, message_width, band.height),
            Rect::new(permanent_x, band.y, permanent_width, band.height),
        )
    }
}

impl Widget for StatusBar {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(400, 24)
    }

    /// Advances the transient message's timeout.
    ///
    /// Returns `true` while the message still has time left, which is the same
    /// "a frame is owed" contract every animating control uses. The timeout is the
    /// widget's own promise (`show_message(_, timeout_ms)`), so it must be honoured
    /// here rather than by a caller that already passed the value in.
    fn tick(&mut self, delta_ms: u32) -> bool {
        let Some(timeout_ms) = self.message_deadline_ms else {
            return false;
        };
        self.elapsed_ms = self.elapsed_ms.saturating_add(u64::from(delta_ms));
        if self.elapsed_ms >= timeout_ms {
            self.clear_message();
            false
        } else {
            true
        }
    }

    fn is_animating(&self) -> bool {
        self.message_deadline_ms.is_some()
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit per control
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
    /// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
    /// make impossible. The arm set is checked against the capability's published names, so this
    /// list cannot drift from what the control advertises.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        #[allow(unused_imports)]
        use crate::widget::capability::CapabilityValue;
        match name {
            "message_changed" => {
                Some(EventSignalRef::mapped("message_changed", &self.message_changed, |v| {
                    CapabilityValue::String(v.clone())
                }))
            }
            "size_grip_dragged" => {
                Some(EventSignalRef::mapped("size_grip_dragged", &self.size_grip_dragged, |v| {
                    crate::widget::capability::CapabilityValue::Tuple(crate::compat::Vec::from([
                        crate::widget::capability::CapabilityValue::Int(v.0 as i64),
                        crate::widget::capability::CapabilityValue::Int(v.1 as i64),
                    ]))
                }))
            }
            _ => None,
        }
    }
}

impl WidgetProperties for StatusBar {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "message" => Ok(CapabilityValue::String(self.message().to_string())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "message" => {
                // Timeout 0 means "until replaced", which is what a property
                // write means: the caller wants this text to stay put, not to
                // expire on a timer it never asked for.
                self.show_message(expect_string(value)?, 0);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["message", BASE_PROPERTY_NAMES]
    }
}

impl EventHandler for StatusBar {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        match event {
            Event::MousePress { pos, button: 1, .. } => {
                if self
                    .size_grip_rect(self.geometry())
                    .is_some_and(|grip| grip.contains_point(*pos))
                {
                    self.grip_drag = Some((*pos, (0, 0)));
                }
            }
            Event::MouseMove { pos } => {
                let Some((origin, _)) = self.grip_drag else {
                    return;
                };
                let delta = (pos.x - origin.x, pos.y - origin.y);
                if let Some((_, last)) = self.grip_drag.as_mut() {
                    *last = delta;
                }
                self.size_grip_dragged.emit(delta);
            }
            Event::MouseRelease { .. } => {
                self.grip_drag = None;
            }
            _ => {}
        }
        // A child takes the events aimed at its own box. The boxes are recomputed here
        // rather than cached, so a relayout cannot leave a stale hit region behind.
        if let Event::MousePress { pos, .. }
        | Event::MouseRelease { pos, .. }
        | Event::MouseMove { pos } = event
        {
            let bands = self.slot_bands();
            for (index, band) in bands.iter().copied() {
                if band.contains_point(*pos) {
                    let slot = &mut self.widgets[index];
                    slot.widget.set_geometry(band);
                    slot.widget.handle_event(event);
                }
            }
        }
    }
}

impl Draw for StatusBar {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let style = self.style();
        // Background
        //
        // From the style, not a literal. This painted `Color::rgb(240, 240, 240)` and so
        // stayed light in a dark theme — a light band across the bottom of a dark window.
        // The literal survives only as the fallback for a style with no colour set.
        let band = style.background_color.unwrap_or(Color::rgb(240, 240, 240));
        context.face_with_gradient(
            rect,
            band,
            self.style().background_gradient.as_ref(),
            self.style().surface.unwrap_or_default(),
            self.style().border_radius.unwrap_or(0),
            Color::BLACK,
        );
        context.draw_line(
            Point::new(rect.x, rect.y),
            Point::new(rect.x + rect.width as i32, rect.y),
            style.border_color.unwrap_or_else(|| band.contrast_color().with_alpha(60)),
        );

        // The **effective font** — the resolved theme/caller font — so both messages honour the
        // theme body font and the user's text scale (D09-STYLE-01).
        let font = effective_font(style);

        // Glue the strip's ink to the strip's own fill, rather than to a literal: the fill is
        // what the theme resolved, so the ink follows it into either appearance.
        let ink = style.text_color.unwrap_or_else(|| band.contrast_color());

        // The two segments: the message fills the room the permanent column and the grip leave,
        // and the permanent message is anchored to the trailing edge. One derivation for both, so
        // neither can be positioned against the other's assumption.
        let (message_box, permanent_box) = self.segment_boxes(rect);
        // Temporary message (left side). Child widgets occupy the column's trailing
        // side, so the text yields to them; with no children the box is unchanged.
        let message_box = self.text_area(message_box, false);
        if !self.message.is_empty() {
            context.draw_text_fitted_cow(
                context.text_line(message_box, font),
                &self.message,
                font,
                ink,
                HorizontalAlignment::Left,
            );
        }
        // Permanent message (right side, before the size grip).
        let permanent_box = self.text_area(permanent_box, true);
        if !self.permanent_message.is_empty() {
            // Muted relative to the main message. The old form blended the ink *toward the
            // band*, which on a dark appearance pulled light text 40% of the way toward a dark
            // band — i.e. it lowered the contrast it was meant to preserve, and the light-mode
            // fallback was a hardcoded `rgb(80,80,80)`, so the two branches disagreed about
            // which appearance they were describing. Blending toward the *band* by a smaller
            // amount, then asserting a legible ratio, is the same visual intent without the
            // direction error.
            let muted = ink.blend(&band, 0.25).legible_on(band, 4.5);
            // The box is the column's own interior, panned to the right within it: the column is at
            // least as wide as the grip's reserve, and the text is anchored to the column's
            // trailing edge rather than to the strip's.
            context.draw_text_fitted_cow(
                context.text_line(permanent_box, font),
                &self.permanent_message,
                font,
                muted,
                HorizontalAlignment::Right,
            );
        }
        // Size grip (bottom-right corner). Drawn inside the box the reserve above was derived
        // from, so the message stops exactly where the grip begins.
        if let Some(grip) = self.size_grip_rect(rect) {
            let grip_ink =
                style.border_color.unwrap_or_else(|| band.contrast_color().with_alpha(120));
            // Three diagonals across the grip's own box, so the ink scales with the box rather
            // than with three separate `i * 4` and `+ 12` literals.
            let step = (grip.width / 3).max(1) as i32;
            for i in 0..3 {
                let offset = i * step;
                context.draw_line(
                    Point::new(grip.x + offset, grip.y + grip.height as i32 - 1),
                    Point::new(grip.x + grip.width as i32 - 1, grip.y + offset),
                    grip_ink,
                );
            }
        }

        // Child widgets are painted last, each in the box the same band derivation reports,
        // so their hit boxes and their pixels agree.
        let bands = self.slot_bands();
        for (index, band) in bands.iter().copied() {
            let slot = &mut self.widgets[index];
            slot.widget.set_geometry(band);
            if let Some(drawable) = crate::widget::draw_bridge::draw_of(slot.widget.as_mut()) {
                drawable.draw(context);
            }
        }
    }
}

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

    /// The grip's drawn box and the room reserved for it are one derivation.
    ///
    /// They were two unrelated numbers: the grip was drawn from `rect.x + width - 14` with three
    /// lines spanning 12 px, while the permanent message reserved `20` for it. A wider grip, or
    /// a strip narrow enough for the difference to show, put the message on top of the grip.
    #[test]
    fn the_size_grip_and_its_reserve_are_one_derivation() {
        let band = Rect::new(0, 0, 240, 24);
        let mut bar = StatusBar::new(band);

        // A fresh status bar shows a grip; turning it off reserves nothing at all, which is the
        // half the previous code could not express (it reserved `4` for a grip it never drew).
        bar.set_size_grip_enabled(false);
        assert!(bar.size_grip_rect(band).is_none(), "a disabled grip has no box");
        assert_eq!(bar.grip_reserve(band), 0, "and nothing is reserved for it");

        bar.set_size_grip_enabled(true);
        let grip = bar.size_grip_rect(band).expect("the grip is enabled");
        let reserve = bar.grip_reserve(band);

        // The grip is inside the strip, and the reserve reaches from the strip's trailing edge
        // to the grip's own leading edge (plus the strip's padding as the gap).
        assert!(grip.x >= band.x, "the grip must not leave the strip: {grip:?}");
        assert!(
            grip.x + grip.width as i32 <= band.x + band.width as i32,
            "and must not run past it: {grip:?}"
        );
        assert_eq!(
            reserve,
            (band.x + band.width as i32 - grip.x) as u32 + dimensions::STATUS_BAR_PADDING_H,
            "the message's reserve is measured from the grip's own box"
        );
        // The message's box therefore stops at or before the grip's leading edge.
        let message_right = band.x + band.width as i32 - reserve as i32;
        assert!(
            message_right <= grip.x,
            "a right-aligned message must not be painted under the grip:              message ends at {message_right}, grip starts at {}",
            grip.x
        );
    }

    /// The grip scales with the shared size rather than a private set of literals.
    #[test]
    fn the_grip_uses_the_shared_size() {
        let band = Rect::new(0, 0, 240, 24);
        let mut bar = StatusBar::new(band);
        bar.set_size_grip_enabled(true);
        let grip = bar.size_grip_rect(band).expect("enabled");
        assert_eq!(grip.width, dimensions::STATUS_GRIP_SIZE);
        assert_eq!(grip.height, dimensions::STATUS_GRIP_SIZE);
        assert_eq!(
            band.x + band.width as i32 - (grip.x + grip.width as i32),
            dimensions::STATUS_BAR_PADDING_H as i32,
            "the grip keeps the strip's own padding from the corner"
        );
    }

    #[test]
    fn statusbar_creation_defaults() {
        let sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert!(sb.message().is_empty());
        assert!(sb.permanent_message().is_empty());
        assert!(sb.size_grip_enabled());
    }

    #[test]
    fn statusbar_show_message() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert!(sb.message().is_empty());
        sb.show_message("Ready", 3000);
        assert_eq!(sb.message(), "Ready");
    }

    #[test]
    fn statusbar_message_timeout_clears_on_tick() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        sb.show_message("Busy", 50);
        assert!(sb.is_animating(), "a timed message owes frames");
        assert!(sb.tick(20), "still inside the timeout");
        assert_eq!(sb.message(), "Busy");
        assert!(!sb.tick(40), "the frame that crosses the deadline is the last");
        assert!(sb.message().is_empty(), "the timeout must clear the message");
        assert!(!sb.is_animating());
    }

    #[test]
    fn statusbar_message_without_timeout_persists() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        sb.show_message("Ready", 0);
        assert!(!sb.is_animating());
        assert!(!sb.tick(10_000));
        assert_eq!(sb.message(), "Ready", "timeout 0 means until replaced");
    }

    #[test]
    fn statusbar_clear_message() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        sb.show_message("Busy", 5000);
        assert_eq!(sb.message(), "Busy");
        sb.clear_message();
        assert!(sb.message().is_empty());
    }

    #[test]
    fn statusbar_permanent_message() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert!(sb.permanent_message().is_empty());
        sb.set_permanent_message("Line: 1  Col: 1");
        assert_eq!(sb.permanent_message(), "Line: 1  Col: 1");
        sb.set_permanent_message("");
        assert!(sb.permanent_message().is_empty());
    }

    #[test]
    fn statusbar_size_grip() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert!(sb.size_grip_enabled());
        sb.set_size_grip_enabled(false);
        assert!(!sb.size_grip_enabled());
        sb.set_size_grip_enabled(true);
        assert!(sb.size_grip_enabled());
    }

    #[test]
    fn statusbar_geometry_delegation() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        sb.set_geometry(Rect::new(0, 700, 800, 24));
        assert_eq!(sb.geometry(), Rect::new(0, 700, 800, 24));
    }

    #[test]
    fn statusbar_visibility() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert!(sb.is_visible());
        sb.hide();
        assert!(!sb.is_visible());
        sb.show();
        assert!(sb.is_visible());
    }

    #[test]
    fn statusbar_signal_accessors() {
        let sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        let _ = &sb.message_changed;
    }

    #[test]
    fn statusbar_id_kind() {
        let sb_a = StatusBar::new(Rect::new(0, 0, 800, 24));
        let sb_b = StatusBar::new(Rect::new(0, 0, 800, 24));
        assert_ne!(sb_a.id(), sb_b.id());
        assert_eq!(sb_a.kind(), WidgetKind::StatusBar);
        assert_eq!(sb_b.kind(), WidgetKind::StatusBar);
    }

    #[test]
    fn statusbar_draw_produces_svg_output() {
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        sb.show_message("Ready", 3000);
        let svg = crate::widget::svg::render_to_svg(&mut sb);
        assert!(svg.starts_with("<svg"));
    }

    /// The permanent message is anchored to the strip's trailing edge, clear of the grip.
    ///
    /// # What this pins
    ///
    /// BLUE22 §F.2.2 records this control's defect as "the last segment's position hard-coded".
    /// The old form drew the permanent message from `rect.x + 6` with a width of
    /// `rect.width - reserved` and right alignment — a *right-anchored* label expressed as "start at
    /// the leading edge and be wide" — so the anchor was width arithmetic rather than a statement
    /// about the edge. The row now expresses it as `justify_content = FlexEnd`.
    ///
    /// The assertion is the relation that matters: the segment reaches the strip's trailing edge,
    /// and the grip sits inside the room it reserved. The segment's drawn width is
    /// `max(reserve, padding)`, so the test states the containment rather than an equality that
    /// would encode the derivation's arithmetic.
    #[test]
    fn the_permanent_segment_reaches_the_trailing_edge_and_clears_the_grip() {
        let strip = Rect::new(0, 0, 400, 24);
        let mut sb = StatusBar::new(strip);
        sb.set_size_grip_enabled(true);
        sb.set_permanent_message("Line: 1");

        let (_, permanent) = sb.segment_boxes(strip);
        let grip = sb.size_grip_rect(strip).expect("the grip is enabled");
        assert_eq!(
            permanent.x + permanent.width as i32,
            strip.x + strip.width as i32,
            "the permanent segment must reach the strip's trailing edge: {permanent:?}"
        );
        assert!(
            grip.x >= permanent.x,
            "and the grip must still be inside it, so the message clears the corner: \
             segment {permanent:?}, grip {grip:?}"
        );
        assert!(
            permanent.width >= sb.grip_reserve(strip),
            "the segment carries at least the grip's reserve, so the message cannot reach the \
             corner: segment width {}, reserve {}",
            permanent.width,
            sb.grip_reserve(strip)
        );
    }

    /// The transient message fills the room the permanent one and the grip leave.
    #[test]
    fn the_transient_segment_yields_to_the_permanent_one_and_the_grip() {
        let strip = Rect::new(0, 0, 400, 24);
        let mut sb = StatusBar::new(strip);
        sb.show_message("Ready", 0);
        sb.set_permanent_message("Line: 1");

        let (message, permanent) = sb.segment_boxes(strip);
        assert_eq!(
            message.x,
            dimensions::STATUS_BAR_PADDING_H as i32,
            "the message starts at the strip's own padding: {message:?}"
        );
        assert!(
            message.x + message.width as i32 <= permanent.x,
            "the two segments must not overlap: message {message:?}, permanent {permanent:?}"
        );
        assert_eq!(
            permanent.x + permanent.width as i32,
            strip.x + strip.width as i32,
            "and the permanent one keeps the trailing edge"
        );
    }

    /// Turning the grip off lets the permanent message use the room the grip reserved.
    ///
    /// The reserve is derived from the grip's own box, so a strip with no grip reserves nothing
    /// rather than keeping a constant's worth of empty space.
    #[test]
    fn without_a_grip_the_permanent_segment_reaches_the_corner() {
        let strip = Rect::new(0, 0, 400, 24);
        let mut sb = StatusBar::new(strip);
        sb.set_size_grip_enabled(false);
        sb.set_permanent_message("Line: 1");
        assert_eq!(sb.grip_reserve(strip), 0, "no grip reserves no room");
        let (_, permanent) = sb.segment_boxes(strip);
        assert_eq!(
            permanent.x + permanent.width as i32,
            strip.x + strip.width as i32,
            "the segment now reaches the strip's trailing edge: {permanent:?}"
        );
    }

    // ── Enabled contract (BLUE19 T-5 follow-up) ───────────────────────────

    #[test]
    fn statusbar_disabled_does_not_announce_a_message_the_user_cannot_see() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let seen = Arc::new(AtomicUsize::new(0));
        let mut sb = StatusBar::new(Rect::new(0, 0, 800, 24));
        {
            let seen = seen.clone();
            sb.message_changed.connect(move |_| {
                seen.fetch_add(1, Ordering::SeqCst);
            });
        }

        sb.show_message("Ready", 0);
        assert_eq!(seen.load(Ordering::SeqCst), 1, "the enabled path must reach a listener");
        assert_eq!(sb.message(), "Ready");

        sb.set_enabled(false);
        sb.show_message("Hidden", 0);
        assert_eq!(sb.message(), "Hidden", "the message is still stored; the host owns the data");
        assert_eq!(
            seen.load(Ordering::SeqCst),
            1,
            "a disabled status bar must not announce text the user cannot see"
        );
        assert!(sb.message_changed_suppression_reason().is_some());

        sb.set_enabled(true);
        assert!(sb.message_changed_suppression_reason().is_none());
        sb.clear_message();
        assert_eq!(seen.load(Ordering::SeqCst), 2, "re-enabling restores the signal");
        assert_eq!(sb.message(), "");
    }

    /// Child widgets take the trailing side of their own segment; with none, both
    /// message boxes are exactly where they always were.
    #[test]
    fn child_widgets_claim_the_trailing_side_of_their_segment() {
        use crate::widget::Label;

        let band = Rect::new(0, 0, 300, 24);
        let mut bar = StatusBar::new(band);
        let (before_message, before_permanent) = bar.segment_boxes(band);

        let transient =
            bar.add_widget(Box::new(Label::new("st".to_string(), Rect::new(0, 0, 0, 0))));
        assert_eq!(bar.widget_count(), 1);
        assert_eq!(bar.widget_is_permanent(transient), Some(false));
        let transient_box = bar.widget_rect(transient).expect("a placed child has a box");
        assert_eq!(
            transient_box.x + transient_box.width as i32,
            before_message.x + before_message.width as i32,
            "a transient child is right-aligned in the message column"
        );
        let message = bar.text_area(before_message, false);
        assert!(message.width <= before_message.width);
        assert_eq!(message.x, before_message.x);

        let permanent =
            bar.add_permanent_widget(Box::new(Label::new("p".to_string(), Rect::new(0, 0, 0, 0))));
        assert_eq!(bar.widget_is_permanent(permanent), Some(true));
        let permanent_box = bar.widget_rect(permanent).expect("the permanent child has a box");
        assert_eq!(
            permanent_box.x + permanent_box.width as i32,
            before_permanent.x + before_permanent.width as i32,
            "a permanent child is right-aligned in the permanent column"
        );

        assert!(bar.remove_widget(transient).is_some());
        assert!(bar.remove_widget(99).is_none());
        assert_eq!(bar.widget_count(), 1);
    }

    /// Dragging the grip reports the total delta since the press and stops on release.
    #[test]
    fn the_size_grip_reports_a_drag() {
        use std::sync::{Arc, Mutex};

        let band = Rect::new(0, 0, 300, 24);
        let mut bar = StatusBar::new(band);
        let drags = Arc::new(Mutex::new(Vec::new()));
        let sink = drags.clone();
        bar.size_grip_dragged.connect(move |delta| {
            sink.lock().unwrap().push(*delta);
        });

        let grip = bar.size_grip_rect(band).expect("the grip is enabled");
        bar.handle_event(&Event::mouse_press(grip.x + 2, grip.y + 2, 1));
        assert!(bar.is_grip_dragging());
        bar.handle_event(&Event::mouse_move(grip.x + 12, grip.y + 7));
        bar.handle_event(&Event::mouse_move(grip.x + 22, grip.y + 9));
        assert_eq!(
            &*drags.lock().unwrap(),
            &[(10, 5), (20, 7)],
            "deltas are from the press origin"
        );
        bar.handle_event(&Event::mouse_release(grip.x + 22, grip.y + 9, 1));
        assert!(!bar.is_grip_dragging());
        bar.handle_event(&Event::mouse_move(grip.x + 40, grip.y + 40));
        assert_eq!(drags.lock().unwrap().len(), 2, "a released grip reports nothing more");
    }
}