iced-cube 0.0.7

Themeable application components for the iced GUI library, with Lucide icons
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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
//! What the data views share: a [`Scope`] that takes focus
//! when pressed and resolves keys only while it has it, a [`Pressable`] row
//! that reports clicks with the modifiers held, and a [`RowMenu`] that
//! gives every row the same context menu.

#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
use std::rc::Rc;

use iced::advanced::layout::{self, Layout};
use iced::advanced::mouse::{Click, click};
use iced::advanced::overlay;
use iced::advanced::renderer::{self, Quad};
use iced::advanced::widget::operation::Focusable;
use iced::advanced::widget::{Operation, Tree, Widget, tree};
use iced::advanced::{Clipboard, Renderer as _, Shell};
use iced::keyboard::{self, Modifiers};
use iced::touch::{self, Finger};
use iced::widget;
use iced::{
    Background, Border, Color, Element, Event, Length, Point, Rectangle, Renderer, Shadow, Size,
    Theme, Vector, mouse,
};

use crate::keys;
#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
use crate::keys::Keymap;
#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
use crate::overlay::context_menu;

type OnKey<'a, Message> = Box<dyn Fn(&keys::Event) -> Option<Message> + 'a>;
type OnFocus<'a, Message> = Box<dyn Fn(bool) -> Message + 'a>;

/// Wraps content that takes focus when pressed and loses it on a press
/// elsewhere. While focused, key presses the content leaves go through
/// `on_key`; a returned message is sent and the key captured.
pub(crate) struct Scope<'a, Message> {
    content: Element<'a, Message>,
    on_key: Option<OnKey<'a, Message>>,
    on_focus: Option<OnFocus<'a, Message>>,
    escapes: Vec<(widget::Id, Box<dyn Fn() -> Message + 'a>)>,
}

pub(crate) fn scope<'a, Message>(content: impl Into<Element<'a, Message>>) -> Scope<'a, Message> {
    Scope {
        content: content.into(),
        on_key: None,
        on_focus: None,
        escapes: Vec::new(),
    }
}

impl<'a, Message> Scope<'a, Message> {
    pub(crate) fn on_key(mut self, on_key: impl Fn(&keys::Event) -> Option<Message> + 'a) -> Self {
        self.on_key = Some(Box::new(on_key));
        self
    }

    pub(crate) fn on_focus(mut self, on_focus: impl Fn(bool) -> Message + 'a) -> Self {
        self.on_focus = Some(Box::new(on_focus));
        self
    }

    /// Sends `message` for Escape while the text field `id` has focus,
    /// before the field can take the key and lose focus. Without a message
    /// Escape reaches the field as usual.
    #[cfg(feature = "property-grid")]
    pub(crate) fn escape(mut self, id: widget::Id, message: Option<Message>) -> Self
    where
        Message: Clone + 'a,
    {
        if let Some(message) = message {
            self.escapes.push((id, Box::new(move || message.clone())));
        }
        self
    }
}

/// Finds whether the field with an id has focus.
struct Probe<'a> {
    target: &'a widget::Id,
    focused: bool,
}

impl Operation for Probe<'_> {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
        operate(self);
    }

    fn focusable(
        &mut self,
        id: Option<&widget::Id>,
        _bounds: Rectangle,
        state: &mut dyn Focusable,
    ) {
        if id == Some(self.target) && state.is_focused() {
            self.focused = true;
        }
    }
}

fn is_escape(event: &Event) -> bool {
    matches!(
        event,
        Event::Keyboard(keyboard::Event::KeyPressed {
            key: keyboard::Key::Named(keyboard::key::Named::Escape),
            ..
        })
    )
}

/// Whether a scope has focus, and what it last told the app.
#[derive(Debug, Default)]
struct Focus {
    focused: bool,
    reported: bool,
}

impl Focusable for Focus {
    fn is_focused(&self) -> bool {
        self.focused
    }

    fn focus(&mut self) {
        self.focused = true;
    }

    fn unfocus(&mut self) {
        self.focused = false;
    }
}

/// Where a press landed, if the event is a press with a known position. A
/// press over a floating layer leaves the cursor unavailable underneath.
fn press_at(event: &Event, cursor: mouse::Cursor) -> Option<Point> {
    match event {
        Event::Mouse(mouse::Event::ButtonPressed(_))
        | Event::Touch(touch::Event::FingerPressed { .. }) => cursor.position(),
        _ => None,
    }
}

fn key_press(event: &Event) -> Option<keys::Event> {
    let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
        return None;
    };
    Some(keys::Event {
        key: key.clone(),
        modifiers: *modifiers,
    })
}

impl<Message> Widget<Message, Theme, Renderer> for Scope<'_, Message> {
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<Focus>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(Focus::default())
    }

    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children(std::slice::from_ref(&self.content));
    }

    fn size(&self) -> Size<Length> {
        self.content.as_widget().size()
    }

    fn size_hint(&self) -> Size<Length> {
        self.content.as_widget().size_hint()
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.content
            .as_widget_mut()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.content.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            style,
            layout,
            cursor,
            viewport,
        );
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation,
    ) {
        let Tree {
            state, children, ..
        } = tree;
        operation.focusable(None, layout.bounds(), state.downcast_mut::<Focus>());
        operation.traverse(&mut |operation| {
            self.content
                .as_widget_mut()
                .operate(&mut children[0], layout, renderer, operation);
        });
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        let Tree {
            state, children, ..
        } = tree;
        let focus = state.downcast_mut::<Focus>();
        if let Some(position) = press_at(event, cursor) {
            focus.focused = layout.bounds().contains(position);
        }
        if focus.focused != focus.reported {
            focus.reported = focus.focused;
            if let Some(on_focus) = &self.on_focus {
                shell.publish(on_focus(focus.focused));
            }
        }
        if is_escape(event) {
            for (id, message) in &self.escapes {
                let mut probe = Probe {
                    target: id,
                    focused: false,
                };
                self.content.as_widget_mut().operate(
                    &mut children[0],
                    layout,
                    renderer,
                    &mut probe,
                );
                if probe.focused {
                    shell.publish(message());
                    shell.capture_event();
                    return;
                }
            }
        }

        self.content.as_widget_mut().update(
            &mut children[0],
            event,
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );
        if shell.is_event_captured() || !focus.focused {
            return;
        }
        let Some(press) = key_press(event) else {
            return;
        };
        let Some(message) = self.on_key.as_ref().and_then(|on_key| on_key(&press)) else {
            return;
        };
        shell.publish(message);
        shell.capture_event();
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.content.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor,
            viewport,
            renderer,
        )
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        self.content.as_widget_mut().overlay(
            &mut tree.children[0],
            layout,
            renderer,
            viewport,
            translation,
        )
    }
}

impl<'a, Message: 'a> From<Scope<'a, Message>> for Element<'a, Message> {
    fn from(scope: Scope<'a, Message>) -> Self {
        Element::new(scope)
    }
}

#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
type Wrap<'a, Key, Message> = dyn Fn(Key, Element<'a, Message>) -> Element<'a, Message> + 'a;
#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
type MenuKey<'a, Key, Message> = dyn Fn(&keys::Event, Key) -> Option<Message> + 'a;
#[cfg(feature = "data-table")]
type Open<'a, Key, Message> = dyn Fn(Key) -> Message + 'a;

/// One context menu shared by every row, told apart by the row's key.
#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
pub(crate) struct RowMenu<'a, Key, Message> {
    wrap: Box<Wrap<'a, Key, Message>>,
    key: Box<MenuKey<'a, Key, Message>>,
    target: Box<dyn Fn() -> Option<Key> + 'a>,
    #[cfg(feature = "data-table")]
    open: Box<Open<'a, Key, Message>>,
}

#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
impl<'a, Key, Message> RowMenu<'a, Key, Message> {
    /// Makes a row an area of the menu.
    pub(crate) fn wrap(&self, key: Key, row: Element<'a, Message>) -> Element<'a, Message> {
        (self.wrap)(key, row)
    }

    /// Resolves the opening chord, opening the menu on `target`.
    pub(crate) fn key(&self, press: &keys::Event, target: Key) -> Option<Message> {
        (self.key)(press, target)
    }

    /// The message that opens the menu below the row `key`, for a button.
    #[cfg(feature = "data-table")]
    pub(crate) fn open(&self, key: Key) -> Message {
        (self.open)(key)
    }

    /// The row the menu is open on, if it is open.
    pub(crate) fn target(&self) -> Option<Key> {
        (self.target)()
    }
}

/// Whether the row `key` carries the ring: the row a context menu is open
/// on, or else the keyboard highlight.
#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
pub(crate) fn ringed<Key: PartialEq>(
    menu_target: Option<&Key>,
    key: &Key,
    highlighted: bool,
) -> bool {
    match menu_target {
        Some(target) => target == key,
        None => highlighted,
    }
}

#[cfg(any(
    feature = "data-table",
    feature = "json-viewer",
    feature = "property-grid",
    feature = "tree",
    feature = "virtual-list"
))]
pub(crate) fn row_menu<'a, Id, Key, Message>(
    state: &'a context_menu::State<Id, Key>,
    keymap: Keymap<context_menu::Action>,
    on_event: Rc<dyn Fn(context_menu::Event<Id, Key>) -> Message + 'a>,
) -> RowMenu<'a, Key, Message>
where
    Id: Copy + PartialEq + 'a,
    Key: Clone + PartialEq + 'a,
    Message: Clone + 'a,
{
    let wrap = {
        let keymap = keymap.clone();
        let on_event = on_event.clone();
        move |key: Key, row: Element<'a, Message>| -> Element<'a, Message> {
            let on_event = on_event.clone();
            context_menu::keyed(state, key, row)
                .keymap(keymap.clone())
                .on_event(move |event| on_event(event))
                .into()
        }
    };
    let key = {
        let on_event = on_event.clone();
        move |press: &keys::Event, target: Key| {
            state
                .key_event(&keymap, press, target)
                .map(|event| on_event(event))
        }
    };
    RowMenu {
        wrap: Box::new(wrap),
        key: Box::new(key),
        target: Box::new(move || state.target().filter(|_| state.is_open()).cloned()),
        #[cfg(feature = "data-table")]
        open: Box::new(move |key| on_event(context_menu::Event::OpenFromKeyboard(key))),
    }
}

/// What a key press means to a focused search field.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchKey {
    /// Escape: clear the text, or leave the field when it is empty.
    Clear,
    /// Enter or F3.
    Next,
    /// Shift+Enter or Shift+F3.
    Previous,
    /// Ctrl+F, or Cmd+F on macOS: select the text rather than type.
    SelectAll,
}

#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
fn search_key(press: &keys::Event) -> Option<SearchKey> {
    use keyboard::key::Named;

    let shift = press.modifiers.shift();
    match &press.key {
        keyboard::Key::Named(Named::Escape) => Some(SearchKey::Clear),
        keyboard::Key::Named(Named::Enter | Named::F3) if shift => Some(SearchKey::Previous),
        keyboard::Key::Named(Named::Enter | Named::F3) => Some(SearchKey::Next),
        keyboard::Key::Character(c) if press.modifiers.command() && c.eq_ignore_ascii_case("f") => {
            Some(SearchKey::SelectAll)
        }
        _ => None,
    }
}

/// Wraps a search field so it follows the search convention every data
/// view shares while it has focus:
///
/// - Escape clears the text, and on an empty field leaves it.
/// - Enter and F3 step to the next match, Shift+Enter and Shift+F3 to the
///   previous one, where the view steps through matches.
/// - Ctrl+F, or Cmd+F on macOS, selects the text instead of typing it.
///
/// A key without a message reaches the field as usual.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
pub(crate) struct SearchKeys<'a, Message> {
    content: Element<'a, Message>,
    id: widget::Id,
    clear: Option<Message>,
    next: Option<Message>,
    previous: Option<Message>,
}

#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
pub(crate) fn search_keys<'a, Message>(
    content: impl Into<Element<'a, Message>>,
    id: widget::Id,
) -> SearchKeys<'a, Message> {
    SearchKeys {
        content: content.into(),
        id,
        clear: None,
        next: None,
        previous: None,
    }
}

#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
impl<Message> SearchKeys<'_, Message> {
    /// Sent for Escape. `None`, as for an empty field, leaves Escape to the
    /// field, which then loses focus.
    pub(crate) fn on_clear(mut self, message: Option<Message>) -> Self {
        self.clear = message;
        self
    }

    /// Sent for Enter and F3.
    pub(crate) fn on_next(mut self, message: Option<Message>) -> Self {
        self.next = message;
        self
    }

    /// Sent for Shift+Enter and Shift+F3.
    pub(crate) fn on_previous(mut self, message: Option<Message>) -> Self {
        self.previous = message;
        self
    }

    fn message(&self, key: SearchKey) -> Option<&Message> {
        match key {
            SearchKey::Clear => self.clear.as_ref(),
            SearchKey::Next => self.next.as_ref(),
            SearchKey::Previous => self.previous.as_ref(),
            SearchKey::SelectAll => None,
        }
    }

    /// Whether the field has focus.
    fn is_focused(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> bool {
        let mut probe = Probe {
            target: &self.id,
            focused: false,
        };
        self.content
            .as_widget_mut()
            .operate(&mut tree.children[0], layout, renderer, &mut probe);
        probe.focused
    }
}

#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
impl<Message: Clone> Widget<Message, Theme, Renderer> for SearchKeys<'_, Message> {
    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children(std::slice::from_ref(&self.content));
    }

    fn size(&self) -> Size<Length> {
        self.content.as_widget().size()
    }

    fn size_hint(&self) -> Size<Length> {
        self.content.as_widget().size_hint()
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.content
            .as_widget_mut()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.content.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            style,
            layout,
            cursor,
            viewport,
        );
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation,
    ) {
        self.content
            .as_widget_mut()
            .operate(&mut tree.children[0], layout, renderer, operation);
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        let key = key_press(event).as_ref().and_then(search_key);
        let handled = key.filter(|&key| key == SearchKey::SelectAll || self.message(key).is_some());
        if let Some(key) = handled
            && self.is_focused(tree, layout, renderer)
        {
            match self.message(key).cloned() {
                Some(message) => shell.publish(message),
                None => {
                    let mut select = iced::advanced::widget::operation::text_input::select_all::<()>(
                        self.id.clone(),
                    );
                    self.content.as_widget_mut().operate(
                        &mut tree.children[0],
                        layout,
                        renderer,
                        &mut select,
                    );
                    shell.request_redraw();
                }
            }
            shell.capture_event();
            return;
        }
        self.content.as_widget_mut().update(
            &mut tree.children[0],
            event,
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.content.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor,
            viewport,
            renderer,
        )
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        self.content.as_widget_mut().overlay(
            &mut tree.children[0],
            layout,
            renderer,
            viewport,
            translation,
        )
    }
}

#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
impl<'a, Message: Clone + 'a> From<SearchKeys<'a, Message>> for Element<'a, Message> {
    fn from(keys: SearchKeys<'a, Message>) -> Self {
        Element::new(keys)
    }
}

/// The count beside a search that steps through matches: "3 of 12" once a
/// match is current, counted from one, "12 found" before that, "None" when
/// nothing matches, and nothing without a search.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
pub(crate) fn match_count_label(query: &str, total: usize, current: Option<usize>) -> String {
    if query.trim().is_empty() {
        return String::new();
    }
    match (total, current) {
        (0, _) => NO_MATCHES.to_owned(),
        (_, Some(position)) => format!("{position} of {total}"),
        (_, None) => format!("{total} found"),
    }
}

/// The count when nothing matches a search.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
const NO_MATCHES: &str = "None";

/// The room kept beside a search box for its count, such as "3 of 12", so
/// the box keeps its width when the count appears.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
pub(crate) const COUNT_WIDTH: f32 = 64.0;

/// A search box's count in its fixed slot, ending in an ellipsis when it
/// does not fit.
#[cfg(any(
    feature = "json-viewer",
    feature = "log-viewer",
    feature = "property-grid"
))]
pub(crate) fn search_count<'a, Message: 'a>(label: String) -> Element<'a, Message> {
    use crate::data::ellipsis::ellipsis;
    use crate::theme::{Tokens, text_size};

    iced::widget::container(
        ellipsis(label)
            .size(text_size::XS, 16.0)
            .align_x(iced::widget::text::Alignment::Center)
            .colour(|theme| Tokens::of(theme).muted_foreground),
    )
    .width(COUNT_WIDTH)
    .into()
}

/// How far, in logical pixels, a finger may drift before a tap on a row
/// counts as a scroll instead.
pub(crate) const TAP_SLOP: f32 = 10.0;

/// How a [`Pressable`] row is painted: a background under the content, and
/// a border and a line along the bottom over it.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Look {
    pub background: Option<Color>,
    pub border: Border,
    pub divider: Option<Color>,
}

type Paint<'a> = Box<dyn Fn(&Theme, bool) -> Look + 'a>;

/// A row that paints itself for the pointer hovering over it and reports
/// presses with the modifiers held, and double clicks. A tap only counts
/// when the finger lifts without moving, so a list still scrolls by touch.
pub(crate) struct Pressable<'a, Message> {
    content: Element<'a, Message>,
    on_press: Option<Box<dyn Fn(Modifiers) -> Message + 'a>>,
    on_double_click: Option<Message>,
    look: Paint<'a>,
}

pub(crate) fn pressable<'a, Message>(
    content: impl Into<Element<'a, Message>>,
    look: impl Fn(&Theme, bool) -> Look + 'a,
) -> Pressable<'a, Message> {
    Pressable {
        content: content.into(),
        on_press: None,
        on_double_click: None,
        look: Box::new(look),
    }
}

impl<'a, Message> Pressable<'a, Message> {
    pub(crate) fn on_press(mut self, on_press: impl Fn(Modifiers) -> Message + 'a) -> Self {
        self.on_press = Some(Box::new(on_press));
        self
    }

    pub(crate) fn on_double_click(mut self, message: Option<Message>) -> Self {
        self.on_double_click = message;
        self
    }
}

#[derive(Debug, Default)]
struct Press {
    modifiers: Modifiers,
    hovered: bool,
    last_click: Option<Click>,
    finger: Option<(Finger, Point)>,
}

impl<Message: Clone> Widget<Message, Theme, Renderer> for Pressable<'_, Message> {
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<Press>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(Press::default())
    }

    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children(std::slice::from_ref(&self.content));
    }

    fn size(&self) -> Size<Length> {
        self.content.as_widget().size()
    }

    fn size_hint(&self) -> Size<Length> {
        self.content.as_widget().size_hint()
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.content
            .as_widget_mut()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        let bounds = layout.bounds();
        let look = (self.look)(theme, self.on_press.is_some() && cursor.is_over(bounds));
        if let Some(background) = look.background {
            renderer.fill_quad(
                Quad {
                    bounds,
                    border: Border {
                        width: 0.0,
                        ..look.border
                    },
                    shadow: Shadow::default(),
                    snap: true,
                },
                Background::Color(background),
            );
        }
        self.content.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            style,
            layout,
            cursor,
            viewport,
        );
        if let Some(divider) = look.divider {
            renderer.fill_quad(
                Quad {
                    bounds: Rectangle {
                        y: bounds.y + bounds.height - 1.0,
                        height: 1.0,
                        ..bounds
                    },
                    snap: true,
                    ..Quad::default()
                },
                Background::Color(divider),
            );
        }
        if look.border.width > 0.0 {
            renderer.fill_quad(
                Quad {
                    bounds,
                    border: look.border,
                    shadow: Shadow::default(),
                    snap: true,
                },
                Background::Color(Color::TRANSPARENT),
            );
        }
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation,
    ) {
        operation.container(None, layout.bounds());
        operation.traverse(&mut |operation| {
            self.content.as_widget_mut().operate(
                &mut tree.children[0],
                layout,
                renderer,
                operation,
            );
        });
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        let bounds = layout.bounds();
        let press = tree.state.downcast_mut::<Press>();
        if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
            press.modifiers = *modifiers;
        }
        let hovered = cursor.is_over(bounds);
        if hovered != press.hovered {
            press.hovered = hovered;
            shell.request_redraw();
        }

        self.content.as_widget_mut().update(
            &mut tree.children[0],
            event,
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );
        let press = tree.state.downcast_mut::<Press>();
        if shell.is_event_captured() {
            press.finger = None;
            return;
        }
        let Some(on_press) = &self.on_press else {
            return;
        };

        match event {
            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
                let Some(position) = cursor.position_over(bounds) else {
                    return;
                };
                shell.publish(on_press(press.modifiers));
                let click = Click::new(position, mouse::Button::Left, press.last_click);
                press.last_click = Some(click);
                if click.kind() == click::Kind::Double
                    && let Some(message) = &self.on_double_click
                {
                    shell.publish(message.clone());
                }
                shell.capture_event();
            }
            Event::Touch(touch::Event::FingerPressed { id, .. }) => {
                press.finger = cursor.position_over(bounds).map(|position| (*id, position));
            }
            Event::Touch(touch::Event::FingerMoved { id, .. }) => {
                let drifted = press.finger.is_some_and(|(finger, origin)| {
                    finger == *id
                        && cursor
                            .position()
                            .is_some_and(|position| origin.distance(position) > TAP_SLOP)
                });
                if drifted {
                    press.finger = None;
                }
            }
            Event::Touch(touch::Event::FingerLifted { id, .. }) => {
                let tapped = press.finger.take().is_some_and(|(finger, _)| finger == *id)
                    && cursor.is_over(bounds);
                if tapped {
                    shell.publish(on_press(Modifiers::empty()));
                    shell.capture_event();
                }
            }
            Event::Touch(touch::Event::FingerLost { .. }) => press.finger = None,
            _ => {}
        }
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        let inner = self.content.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor,
            viewport,
            renderer,
        );
        if inner != mouse::Interaction::None
            || self.on_press.is_none()
            || !cursor.is_over(layout.bounds())
        {
            return inner;
        }
        mouse::Interaction::Pointer
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        self.content.as_widget_mut().overlay(
            &mut tree.children[0],
            layout,
            renderer,
            viewport,
            translation,
        )
    }
}

impl<'a, Message: Clone + 'a> From<Pressable<'a, Message>> for Element<'a, Message> {
    fn from(pressable: Pressable<'a, Message>) -> Self {
        Element::new(pressable)
    }
}

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

    #[test]
    fn a_press_only_counts_with_a_known_position() {
        let pressed = Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left));
        let at = Point::new(4.0, 5.0);
        assert_eq!(press_at(&pressed, mouse::Cursor::Available(at)), Some(at));
        assert_eq!(press_at(&pressed, mouse::Cursor::Levitating(at)), None);
        assert_eq!(press_at(&pressed, mouse::Cursor::Unavailable), None);
        let moved = Event::Mouse(mouse::Event::CursorMoved { position: at });
        assert_eq!(press_at(&moved, mouse::Cursor::Available(at)), None);
    }

    #[cfg(any(
        feature = "json-viewer",
        feature = "log-viewer",
        feature = "property-grid"
    ))]
    #[test]
    fn search_fields_share_one_set_of_keys() {
        use keyboard::key::Named;

        let named = |name, modifiers| keys::Event {
            key: keyboard::Key::Named(name),
            modifiers,
        };
        let character = |c: &str, modifiers| keys::Event {
            key: keyboard::Key::Character(c.into()),
            modifiers,
        };
        let none = Modifiers::empty();
        assert_eq!(
            search_key(&named(Named::Escape, none)),
            Some(SearchKey::Clear)
        );
        assert_eq!(
            search_key(&named(Named::Enter, none)),
            Some(SearchKey::Next)
        );
        assert_eq!(search_key(&named(Named::F3, none)), Some(SearchKey::Next));
        assert_eq!(
            search_key(&named(Named::Enter, Modifiers::SHIFT)),
            Some(SearchKey::Previous)
        );
        assert_eq!(
            search_key(&named(Named::F3, Modifiers::SHIFT)),
            Some(SearchKey::Previous)
        );
        assert_eq!(
            search_key(&character("f", Modifiers::COMMAND)),
            Some(SearchKey::SelectAll)
        );
        assert_eq!(
            search_key(&character("F", Modifiers::COMMAND | Modifiers::SHIFT)),
            Some(SearchKey::SelectAll)
        );
        assert_eq!(search_key(&character("f", none)), None, "typing");
        assert_eq!(search_key(&named(Named::Home, none)), None);
    }

    #[cfg(any(feature = "json-viewer", feature = "log-viewer"))]
    #[test]
    fn stepping_search_counts_read_the_same_everywhere() {
        assert_eq!(match_count_label("", 4, None), "");
        assert_eq!(match_count_label("  ", 4, None), "");
        assert_eq!(match_count_label("a", 12, None), "12 found");
        assert_eq!(match_count_label("a", 12, Some(3)), "3 of 12");
        assert_eq!(match_count_label("a", 0, None), "None");
    }

    #[test]
    fn an_open_menu_moves_the_ring_to_its_row() {
        assert!(ringed(None, &1, true), "the keyboard highlight");
        assert!(!ringed(None, &1, false));
        assert!(ringed(Some(&2), &2, false), "the row the menu opened on");
        assert!(
            !ringed(Some(&2), &1, true),
            "the highlight gives way while the menu is open elsewhere"
        );
    }

    #[test]
    fn focus_follows_the_focusable_calls() {
        let mut focus = Focus::default();
        assert!(!focus.is_focused());
        focus.focus();
        assert!(focus.is_focused());
        focus.unfocus();
        assert!(!focus.is_focused());
    }

    #[test]
    fn key_presses_carry_their_modifiers() {
        let event = Event::Keyboard(keyboard::Event::KeyPressed {
            key: keyboard::Key::Character("a".into()),
            modified_key: keyboard::Key::Character("a".into()),
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers: Modifiers::CTRL,
            text: None,
            repeat: false,
        });
        let press = key_press(&event).expect("a key press");
        assert_eq!(press.modifiers, Modifiers::CTRL);
        assert_eq!(key_press(&Event::Mouse(mouse::Event::CursorLeft)), None);
    }
}