teksilo-core 0.24.0

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! A key release goes to the widget that received its press, not to whatever
//! focus moved to while the key was down; a lone Enter or Space release is
//! dropped.

use std::cell::RefCell;
use std::rc::Rc;

use teksilo_canvas::SizeProposal;

use super::WidgetTree;
use crate::event::{EventResponse, Key, Modifiers, WidgetEvent};
use crate::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
use crate::test_widgets::{FillWidget, StackWidget};
use crate::widget_builder::WidgetBuilder;
use crate::widget_id::WidgetId;

type Log = Rc<RefCell<Vec<(&'static str, &'static str)>>>;

fn lay_out(tree: &mut WidgetTree) {
    tree.layout(SizeProposal::exact(400.0, 300.0));
}

/// A focusable field named `name` logging the key events it receives. On an
/// Enter press, it hands focus to `next` when one is set.
fn field(
    tree: &mut WidgetTree,
    parent: WidgetId,
    name: &'static str,
    log: &Log,
    next: Rc<RefCell<Option<WidgetId>>>,
) -> WidgetId {
    let log = log.clone();
    tree.add_child(
        parent,
        FillWidget::new().focusable().on_key(move |event, ctx| {
            match event {
                WidgetEvent::KeyDown { key, .. } => {
                    log.borrow_mut().push((name, "down"));
                    if *key == Key::Enter
                        && let Some(next) = *next.borrow()
                    {
                        ctx.request_focus(next);
                    }
                }
                WidgetEvent::KeyUp { .. } => log.borrow_mut().push((name, "up")),
                _ => return EventResponse::Ignored,
            }
            EventResponse::Handled
        }),
    )
}

/// Fields A and B; A's Enter press moves focus to B.
fn a_hands_focus_to_b() -> (WidgetTree, WidgetId, WidgetId, Log) {
    let log = Log::default();
    let mut tree = WidgetTree::new();
    let root = tree.add(StackWidget::new());
    let next = Rc::new(RefCell::new(None));
    let a = field(&mut tree, root, "A", &log, next.clone());
    let b = field(&mut tree, root, "B", &log, Rc::new(RefCell::new(None)));
    *next.borrow_mut() = Some(b);
    lay_out(&mut tree);
    tree.focus(a);
    (tree, a, b, log)
}

fn down(tree: &mut WidgetTree, key: Key) {
    tree.dispatch_event(WidgetEvent::KeyDown {
        key,
        modifiers: Modifiers::NONE,
        text: None,
    });
}

fn up(tree: &mut WidgetTree, key: Key) {
    tree.dispatch_event(WidgetEvent::KeyUp {
        key,
        modifiers: Modifiers::NONE,
    });
}

fn with_window(tree: &mut WidgetTree) -> crate::window::WindowState {
    use crate::window::state::WindowStateInit;
    use crate::window::{TeksiloWindowId, WindowPlacement, WindowState};
    let state = WindowState::new(WindowStateInit {
        id: TeksiloWindowId::new(1),
        string_id: None,
        placement: WindowPlacement::Floating,
        title: "Test".to_string(),
        size: (400, 300),
        position: (0, 0),
        focused: true,
        resizable: true,
        always_on_top: false,
    });
    tree.set_window_state(state.clone());
    state
}

#[test]
fn a_release_goes_to_the_widget_that_got_the_press() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    down(&mut tree, Key::Enter);
    assert_eq!(tree.focused(), Some(b), "the press moved focus on");
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("A", "down"), ("A", "up")]);
}

#[test]
fn a_press_and_release_on_one_widget_is_delivered_once() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    tree.focus(b);
    down(&mut tree, Key::Enter);
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("B", "down"), ("B", "up")]);
}

#[test]
fn auto_repeated_presses_end_in_one_release() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    tree.focus(b);
    for _ in 0..3 {
        down(&mut tree, Key::ArrowDown);
    }
    up(&mut tree, Key::ArrowDown);
    up(&mut tree, Key::ArrowDown);
    let ups = log
        .borrow()
        .iter()
        .filter(|(_, what)| *what == "up")
        .count();
    assert_eq!(ups, 2, "the second release, lone, still reaches focus");
}

/// A lone Enter or Space release (its press was never delivered here) is
/// dropped; any other lone release still reaches focus.
#[test]
fn a_lone_activation_release_is_dropped() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    tree.focus(b);
    up(&mut tree, Key::Enter);
    up(&mut tree, Key::Space);
    assert!(log.borrow().is_empty());
    up(&mut tree, Key::Character('x'));
    assert_eq!(*log.borrow(), [("B", "up")]);
}

/// Shift released before the letter: pressed as "A", released as "a", one
/// key.
#[test]
fn a_shifted_character_pairs_with_its_unshifted_release() {
    let (mut tree, a, b, log) = a_hands_focus_to_b();
    down(&mut tree, Key::Character('A'));
    tree.focus(b);
    up(&mut tree, Key::Character('a'));
    assert_eq!(*log.borrow(), [("A", "down"), ("A", "up")]);
    assert_ne!(tree.focused(), Some(a));
}

/// With the physical key noted by the window manager, a release whose
/// logical key differs from its press still pairs: Option+Shift+2 pressed as
/// "€", released as "2" after Shift.
#[test]
fn the_physical_key_pairs_a_release_whose_logical_key_changed() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    let window = with_window(&mut tree);
    window.note_key_identity_from_os(42, false);
    down(&mut tree, Key::Character('€'));
    tree.focus(b);
    window.note_key_identity_from_os(42, false);
    up(&mut tree, Key::Character('2'));
    assert_eq!(*log.borrow(), [("A", "down"), ("A", "up")]);
}

/// A record whose release was lost does not take the release of the next
/// fresh press of that key, made on another widget; an auto-repeat keeps it.
#[test]
fn a_fresh_press_replaces_a_stale_record() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    let window = with_window(&mut tree);
    window.note_key_identity_from_os(7, false);
    down(&mut tree, Key::Character('q'));
    tree.focus(b);
    window.note_key_identity_from_os(7, true);
    down(&mut tree, Key::Character('q'));
    window.note_key_identity_from_os(7, false);
    down(&mut tree, Key::Character('q'));
    window.note_key_identity_from_os(7, false);
    up(&mut tree, Key::Character('q'));
    assert_eq!(log.borrow().last(), Some(&("B", "up")));
}

/// A press made before the window lost the focus is forgotten when it gets
/// the focus back; a release synthesised as it loses the focus still reaches
/// the widget that had the press.
#[test]
fn window_focus_bounds_a_press_record() {
    let (mut tree, a, b, log) = a_hands_focus_to_b();
    down(&mut tree, Key::Character('z'));
    tree.set_window_active(false);
    up(&mut tree, Key::Character('z'));
    assert_eq!(log.borrow().last(), Some(&("A", "up")), "the blur release");

    tree.focus(a);
    log.borrow_mut().clear();
    down(&mut tree, Key::Character('z'));
    tree.set_window_active(false);
    tree.set_window_active(true);
    tree.focus(b);
    up(&mut tree, Key::Character('z'));
    assert_eq!(
        *log.borrow(),
        [("A", "down"), ("B", "up")],
        "the record is gone"
    );
}

/// A press that opened a modal over its widget: the release is not sent
/// behind the modal, nor to the modal's field.
#[test]
fn a_release_is_not_sent_behind_a_modal_opened_by_its_press() {
    let log = Log::default();
    let mut tree = WidgetTree::new();
    let root = tree.add(StackWidget::new());
    let opener = field(&mut tree, root, "opener", &log, Rc::new(RefCell::new(None)));
    let content = tree.add(StackWidget::new());
    let inside = field(
        &mut tree,
        content,
        "inside",
        &log,
        Rc::new(RefCell::new(None)),
    );
    lay_out(&mut tree);
    tree.focus(opener);
    down(&mut tree, Key::Enter);
    tree.activate(content);
    tree.show_overlay(OverlayRequest::new(
        content,
        opener,
        OverlayPlacement::Centered,
        DismissBehavior::EscapeKey,
    ));
    lay_out(&mut tree);
    tree.focus(inside);
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("opener", "down")]);
}

/// A widget that captures the keyboard still gets the release of a press
/// that opened a modal over it.
#[test]
fn a_keyboard_capture_surface_gets_its_release_behind_a_modal() {
    let log = Log::default();
    let mut tree = WidgetTree::new();
    let root = tree.add(StackWidget::new());
    let surface = {
        let log = log.clone();
        tree.add_child(
            root,
            FillWidget::new()
                .focusable()
                .keyboard_capture(true)
                .on_key(move |event, _ctx| {
                    match event {
                        WidgetEvent::KeyDown { .. } => log.borrow_mut().push(("surface", "down")),
                        WidgetEvent::KeyUp { .. } => log.borrow_mut().push(("surface", "up")),
                        _ => return EventResponse::Ignored,
                    }
                    EventResponse::Handled
                }),
        )
    };
    let content = tree.add(StackWidget::new());
    let inside = field(
        &mut tree,
        content,
        "inside",
        &log,
        Rc::new(RefCell::new(None)),
    );
    lay_out(&mut tree);
    tree.focus(surface);
    down(&mut tree, Key::Enter);
    tree.activate(content);
    tree.show_overlay(OverlayRequest::new(
        content,
        surface,
        OverlayPlacement::Centered,
        DismissBehavior::EscapeKey,
    ));
    lay_out(&mut tree);
    tree.focus(inside);
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("surface", "down"), ("surface", "up")]);
}

/// Two keys held at once, the second moving focus: each release goes to the
/// widget that had its press.
#[test]
fn two_held_keys_each_release_where_they_were_pressed() {
    let (mut tree, _a, b, log) = a_hands_focus_to_b();
    down(&mut tree, Key::Character('x'));
    down(&mut tree, Key::Enter);
    assert_eq!(tree.focused(), Some(b));
    down(&mut tree, Key::Character('y'));
    up(&mut tree, Key::Character('x'));
    up(&mut tree, Key::Enter);
    up(&mut tree, Key::Character('y'));
    let ups: Vec<_> = log
        .borrow()
        .iter()
        .filter(|(_, what)| *what == "up")
        .map(|(who, _)| *who)
        .collect();
    assert_eq!(ups, ["A", "A", "B"]);
}

/// A redirected release bubbles from the press target, so an ancestor that
/// tracks held keys hears it.
#[test]
fn a_redirected_release_bubbles_to_the_press_targets_ancestors() {
    let log = Log::default();
    let mut tree = WidgetTree::new();
    let parent_log = log.clone();
    let parent = tree.add(StackWidget::new().on_key(move |event, _ctx| {
        if matches!(event, WidgetEvent::KeyUp { .. }) {
            parent_log.borrow_mut().push(("parent", "up"));
        }
        EventResponse::Ignored
    }));
    let next = Rc::new(RefCell::new(None));
    let a = {
        let next = next.clone();
        tree.add_child(
            parent,
            FillWidget::new()
                .focusable()
                .on_key(move |event, ctx| match event {
                    WidgetEvent::KeyDown {
                        key: Key::Enter, ..
                    } => {
                        if let Some(next) = *next.borrow() {
                            ctx.request_focus(next);
                        }
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                }),
        )
    };
    let other_root = tree.add(StackWidget::new());
    let b = field(
        &mut tree,
        other_root,
        "B",
        &log,
        Rc::new(RefCell::new(None)),
    );
    *next.borrow_mut() = Some(b);
    lay_out(&mut tree);
    tree.focus(a);
    down(&mut tree, Key::Enter);
    assert_eq!(tree.focused(), Some(b));
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("parent", "up")]);
}

/// A widget that asked for every release gets it behind a modal, alone: the
/// release does not bubble on to its ancestors, which are behind the modal
/// too.
#[test]
fn a_release_behind_a_modal_does_not_bubble_past_its_target() {
    #[derive(Debug)]
    struct Forwarder;
    impl crate::widget::Widget for Forwarder {
        fn build(&mut self, ctx: &mut crate::BuildContext) -> Vec<WidgetId> {
            ctx.receive_every_key_release();
            vec![]
        }
        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(10.0, 10.0).into()
        }
    }
    let log = Log::default();
    let mut tree = WidgetTree::new();
    let parent_log = log.clone();
    let parent = tree.add(StackWidget::new().on_key(move |event, _ctx| {
        if matches!(event, WidgetEvent::KeyUp { .. }) {
            parent_log.borrow_mut().push(("parent", "up"));
        }
        EventResponse::Ignored
    }));
    let child_log = log.clone();
    let forwarder = tree.add_child(
        parent,
        Forwarder.focusable(true).on_key(move |event, _ctx| {
            if matches!(event, WidgetEvent::KeyUp { .. }) {
                child_log.borrow_mut().push(("forwarder", "up"));
            }
            EventResponse::Ignored
        }),
    );
    let content = tree.add(StackWidget::new());
    let inside = field(
        &mut tree,
        content,
        "inside",
        &log,
        Rc::new(RefCell::new(None)),
    );
    lay_out(&mut tree);
    tree.focus(forwarder);
    down(&mut tree, Key::Enter);
    tree.activate(content);
    tree.show_overlay(OverlayRequest::new(
        content,
        forwarder,
        OverlayPlacement::Centered,
        DismissBehavior::EscapeKey,
    ));
    lay_out(&mut tree);
    tree.focus(inside);
    up(&mut tree, Key::Enter);
    assert_eq!(*log.borrow(), [("forwarder", "up")]);
}