Trait kas_core::WidgetExt

source ·
pub trait WidgetExt: Widget {
    fn id(&self) -> WidgetId { ... }
    fn eq_id<T>(&self, rhs: T) -> bool
    where
        WidgetId: PartialEq<T>
, { ... } fn identify(&self) -> IdentifyWidget { ... } fn is_ancestor_of(&self, id: &WidgetId) -> bool { ... } fn is_strict_ancestor_of(&self, id: &WidgetId) -> bool { ... } fn find_widget(&self, id: &WidgetId) -> Option<&dyn Widget> { ... } fn find_widget_mut(&mut self, id: &WidgetId) -> Option<&mut dyn Widget> { ... } }
Expand description

Extension trait over widgets

Provided Methods§

Get the widget’s identifier

Note that the default-constructed WidgetId is invalid: any operations on this value will cause a panic. Valid identifiers are assigned by Widget::pre_configure.

Examples found in repository?
src/core/widget.rs (line 606)
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    fn identify(&self) -> IdentifyWidget {
        IdentifyWidget(self.widget_name(), self.id())
    }

    /// Check whether `id` is self or a descendant
    ///
    /// This function assumes that `id` is a valid widget.
    #[inline]
    fn is_ancestor_of(&self, id: &WidgetId) -> bool {
        self.id().is_ancestor_of(id)
    }

    /// Check whether `id` is not self and is a descendant
    ///
    /// This function assumes that `id` is a valid widget.
    #[inline]
    fn is_strict_ancestor_of(&self, id: &WidgetId) -> bool {
        !self.eq_id(id) && self.id().is_ancestor_of(id)
    }
More examples
Hide additional examples
src/theme/draw.rs (line 85)
84
85
86
    pub fn recurse(&mut self, child: &mut dyn Widget) {
        child.draw(self.re_id(child.id()));
    }
src/root.rs (line 56)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        fn find_id(&mut self, coord: Coord) -> Option<WidgetId> {
            if !self.core.rect.contains(coord) {
                return None;
            }
            for popup in self.popups.iter_mut().rev() {
                if let Some(id) = self
                    .w
                    .find_widget_mut(&popup.1.id)
                    .and_then(|w| w.find_id(coord))
                {
                    return Some(id);
                }
            }
            self.w.find_id(coord).or_else(|| Some(self.id()))
        }
src/event/manager/config_mgr.rs (line 190)
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
        fn nav(
            mgr: &mut ConfigMgr,
            widget: &mut dyn Widget,
            focus: Option<&WidgetId>,
            rev: bool,
        ) -> Option<WidgetId> {
            if mgr.ev_state().is_disabled(widget.id_ref()) {
                return None;
            }

            let mut child = focus.and_then(|id| widget.find_child_index(id));

            if !rev {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                } else if !widget.eq_id(focus) && widget.navigable() {
                    return Some(widget.id());
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return None;
                    }
                }
            } else {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return if !widget.eq_id(focus) && widget.navigable() {
                            Some(widget.id())
                        } else {
                            None
                        };
                    }
                }
            }
        }
src/event/manager.rs (line 455)
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
    fn start_key_event(&mut self, widget: &mut dyn Widget, vkey: VirtualKeyCode, scancode: u32) {
        log::trace!(
            "start_key_event: widget={}, vkey={vkey:?}, scancode={scancode}",
            widget.id()
        );

        use VirtualKeyCode as VK;

        let opt_command = self.config.shortcuts(|s| s.get(self.modifiers, vkey));

        if let Some(cmd) = opt_command {
            let mut targets = vec![];
            let mut send = |_self: &mut Self, id: WidgetId, cmd| -> bool {
                if !targets.contains(&id) {
                    let used = _self.send_event(widget, id.clone(), Event::Command(cmd));
                    if used {
                        _self.add_key_depress(scancode, id.clone());
                    }
                    targets.push(id);
                    used
                } else {
                    false
                }
            };

            if self.char_focus || cmd.suitable_for_sel_focus() {
                if let Some(id) = self.sel_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if !self.modifiers.alt() {
                if let Some(id) = self.nav_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if let Some(id) = self.popups.last().map(|popup| popup.1.parent.clone()) {
                if send(self, id, cmd) {
                    return;
                }
            }

            if let Some(id) = self.nav_fallback.clone() {
                if send(self, id, cmd) {
                    return;
                }
            }
        }

        // Next priority goes to accelerator keys when Alt is held or alt_bypass is true
        let mut target = None;
        let mut n = 0;
        for (i, id) in (self.popups.iter().rev())
            .map(|(_, popup, _)| popup.parent.clone())
            .chain(std::iter::once(widget.id()))
            .enumerate()
        {
            if let Some(layer) = self.accel_layers.get(&id) {
                // but only when Alt is held or alt-bypass is enabled:
                if self.modifiers == ModifiersState::ALT
                    || layer.0 && self.modifiers == ModifiersState::empty()
                {
                    if let Some(id) = layer.1.get(&vkey).cloned() {
                        target = Some(id);
                        n = i;
                        break;
                    }
                }
            }
        }

        // If we found a key binding below the top layer, we should close everything above
        if n > 0 {
            let len = self.popups.len();
            for i in ((len - n)..len).rev() {
                let id = self.popups[i].0;
                self.close_window(id, false);
            }
        }

        if let Some(id) = target {
            if widget
                .find_widget(&id)
                .map(|w| w.navigable())
                .unwrap_or(false)
            {
                self.set_nav_focus(id.clone(), true);
            }
            self.add_key_depress(scancode, id.clone());
            self.send_event(widget, id, Event::Command(Command::Activate));
        } else if self.config.nav_focus && vkey == VK::Tab {
            self.clear_char_focus();
            let shift = self.modifiers.shift();
            self.next_nav_focus(widget, shift, true);
        } else if vkey == VK::Escape {
            if let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
                self.close_window(id, true);
            }
        }
    }
src/event/manager/mgr_shell.rs (line 431)
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
    pub fn handle_winit(&mut self, widget: &mut dyn Widget, event: winit::event::WindowEvent) {
        use winit::event::{ElementState, MouseScrollDelta, TouchPhase, WindowEvent::*};

        match event {
            CloseRequested => self.send_action(TkAction::CLOSE),
            /* Not yet supported: see #98
            DroppedFile(path) => ,
            HoveredFile(path) => ,
            HoveredFileCancelled => ,
            */
            ReceivedCharacter(c) => {
                if let Some(id) = self.char_focus() {
                    // Filter out control codes (Unicode 5.11). These may be
                    // generated from combinations such as Ctrl+C by some other
                    // layer. We use our own shortcut system instead.
                    if c >= '\x20' && !('\x7f'..='\u{9f}').contains(&c) {
                        let event = Event::ReceivedCharacter(c);
                        self.send_event(widget, id, event);
                    }
                }
            }
            Focused(state) => {
                self.window_has_focus = state;
                if state {
                    // Required to restart theme animations
                    self.send_action(TkAction::REDRAW);
                } else {
                    // Window focus lost: close all popups
                    while let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
                        self.close_window(id, true);
                    }
                }
            }
            KeyboardInput {
                input,
                is_synthetic,
                ..
            } => {
                if input.state == ElementState::Pressed && !is_synthetic {
                    if let Some(vkey) = input.virtual_keycode {
                        self.start_key_event(widget, vkey, input.scancode);
                    }
                } else if input.state == ElementState::Released {
                    self.end_key_event(input.scancode);
                }
            }
            ModifiersChanged(state) => {
                if state.alt() != self.modifiers.alt() {
                    // This controls drawing of accelerator key indicators
                    self.send_action(TkAction::REDRAW);
                }
                self.modifiers = state;
            }
            CursorMoved { position, .. } => {
                self.last_click_button = FAKE_MOUSE_BUTTON;
                let coord = position.cast_approx();

                // Update hovered widget
                let cur_id = widget.find_id(coord);
                let delta = coord - self.last_mouse_coord;
                self.set_hover(cur_id.clone());

                if let Some(grab) = self.state.mouse_grab.as_mut() {
                    if grab.mode == GrabMode::Grab {
                        grab.cur_id = cur_id;
                        grab.coord = coord;
                        grab.delta += delta;
                    } else if let Some(pan) =
                        self.state.pan_grab.get_mut(usize::conv(grab.pan_grab.0))
                    {
                        pan.coords[usize::conv(grab.pan_grab.1)].1 = coord;
                    }
                } else if let Some(id) = self.popups.last().map(|(_, p, _)| p.parent.clone()) {
                    let source = PressSource::Mouse(FAKE_MOUSE_BUTTON, 0);
                    let event = Event::PressMove {
                        source,
                        cur_id,
                        coord,
                        delta,
                    };
                    self.send_event(widget, id, event);
                } else {
                    // We don't forward move events without a grab
                }

                self.last_mouse_coord = coord;
            }
            // CursorEntered { .. },
            CursorLeft { .. } => {
                self.last_click_button = FAKE_MOUSE_BUTTON;

                if self.mouse_grab().is_none() {
                    // If there's a mouse grab, we will continue to receive
                    // coordinates; if not, set a fake coordinate off the window
                    self.last_mouse_coord = Coord(-1, -1);
                    self.set_hover(None);
                }
            }
            MouseWheel { delta, .. } => {
                if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
                    self.send_event(widget, id, event);
                }

                self.last_click_button = FAKE_MOUSE_BUTTON;

                let event = Event::Scroll(match delta {
                    MouseScrollDelta::LineDelta(x, y) => ScrollDelta::LineDelta(x, y),
                    MouseScrollDelta::PixelDelta(pos) => {
                        // The delta is given as a PhysicalPosition, so we need
                        // to convert to our vector type (Offset) here.
                        let coord = Coord::conv_approx(pos);
                        ScrollDelta::PixelDelta(coord.cast())
                    }
                });
                if let Some(id) = self.hover.clone() {
                    self.send_event(widget, id, event);
                }
            }
            MouseInput { state, button, .. } => {
                if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
                    self.send_event(widget, id, event);
                }

                let coord = self.last_mouse_coord;

                if state == ElementState::Pressed {
                    let now = Instant::now();
                    if button != self.last_click_button || self.last_click_timeout < now {
                        self.last_click_button = button;
                        self.last_click_repetitions = 0;
                    }
                    self.last_click_repetitions += 1;
                    self.last_click_timeout = now + DOUBLE_CLICK_TIMEOUT;
                }

                if let Some(grab) = self.remove_mouse_grab() {
                    if grab.mode == GrabMode::Grab {
                        // Mouse grab active: send events there
                        // Note: any button release may end the grab (intended).
                        let event = Event::PressEnd {
                            source: PressSource::Mouse(grab.button, grab.repetitions),
                            end_id: self.hover.clone(),
                            coord,
                            success: state == ElementState::Released,
                        };
                        self.send_event(widget, grab.start_id, event);
                    }
                    // Pan events do not receive Start/End notifications
                }

                if state == ElementState::Pressed {
                    if let Some(start_id) = self.hover.clone() {
                        // No mouse grab but have a hover target
                        if self.config.mouse_nav_focus() {
                            if let Some(w) = widget.find_widget(&start_id) {
                                if w.navigable() {
                                    self.set_nav_focus(w.id(), false);
                                }
                            }
                        }
                    }

                    let source = PressSource::Mouse(button, self.last_click_repetitions);
                    let event = Event::PressStart {
                        source,
                        start_id: self.hover.clone(),
                        coord,
                    };
                    self.send_popup_first(widget, self.hover.clone(), event);
                }
            }
            // TouchpadPressure { pressure: f32, stage: i64, },
            // AxisMotion { axis: AxisId, value: f64, },
            Touch(touch) => {
                let source = PressSource::Touch(touch.id);
                let coord = touch.location.cast_approx();
                match touch.phase {
                    TouchPhase::Started => {
                        let start_id = widget.find_id(coord);
                        if let Some(id) = start_id.as_ref() {
                            if self.config.touch_nav_focus() {
                                if let Some(w) = widget.find_widget(id) {
                                    if w.navigable() {
                                        self.set_nav_focus(w.id(), false);
                                    }
                                }
                            }

                            let event = Event::PressStart {
                                source,
                                start_id: start_id.clone(),
                                coord,
                            };
                            self.send_popup_first(widget, start_id, event);
                        }
                    }
                    TouchPhase::Moved => {
                        let cur_id = widget.find_id(coord);

                        let mut redraw = false;
                        let mut pan_grab = None;
                        if let Some(grab) = self.get_touch(touch.id) {
                            if grab.mode == GrabMode::Grab {
                                // Only when 'depressed' status changes:
                                redraw = grab.cur_id != cur_id
                                    && (grab.start_id == grab.cur_id || grab.start_id == cur_id);

                                grab.cur_id = cur_id;
                                grab.coord = coord;
                            } else {
                                pan_grab = Some(grab.pan_grab);
                            }
                        }

                        if redraw {
                            self.send_action(TkAction::REDRAW);
                        } else if let Some(pan_grab) = pan_grab {
                            if usize::conv(pan_grab.1) < MAX_PAN_GRABS {
                                if let Some(pan) = self.pan_grab.get_mut(usize::conv(pan_grab.0)) {
                                    pan.coords[usize::conv(pan_grab.1)].1 = coord;
                                }
                            }
                        }
                    }
                    ev @ (TouchPhase::Ended | TouchPhase::Cancelled) => {
                        if let Some(mut grab) = self.remove_touch(touch.id) {
                            if let Some((id, event)) = grab.flush_move() {
                                self.send_event(widget, id, event);
                            }

                            if grab.mode == GrabMode::Grab {
                                let event = Event::PressEnd {
                                    source,
                                    end_id: grab.cur_id.clone(),
                                    coord,
                                    success: ev == TouchPhase::Ended,
                                };
                                self.send_event(widget, grab.start_id, event);
                            }
                        }
                    }
                }
            }
            _ => (),
        }
    }

Test widget identifier for equality

This method may be used to test against WidgetId, Option<WidgetId> and Option<&WidgetId>.

Examples found in repository?
src/core/widget.rs (line 622)
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
    fn is_strict_ancestor_of(&self, id: &WidgetId) -> bool {
        !self.eq_id(id) && self.id().is_ancestor_of(id)
    }

    /// Find the descendant with this `id`, if any
    fn find_widget(&self, id: &WidgetId) -> Option<&dyn Widget> {
        if let Some(index) = self.find_child_index(id) {
            self.get_child(index)
                .and_then(|child| child.find_widget(id))
        } else if self.eq_id(id) {
            return Some(self.as_widget());
        } else {
            None
        }
    }

    /// Find the descendant with this `id`, if any
    fn find_widget_mut(&mut self, id: &WidgetId) -> Option<&mut dyn Widget> {
        if let Some(index) = self.find_child_index(id) {
            self.get_child_mut(index)
                .and_then(|child| child.find_widget_mut(id))
        } else if self.eq_id(id) {
            return Some(self.as_widget_mut());
        } else {
            None
        }
    }
More examples
Hide additional examples
src/root.rs (line 126)
117
118
119
120
121
122
123
124
125
126
127
128
129
fn find_rect(widget: &dyn Widget, id: WidgetId) -> Option<Rect> {
    match widget.find_child_index(&id) {
        Some(i) => {
            if let Some(w) = widget.get_child(i) {
                find_rect(w, id).map(|rect| rect - widget.translation())
            } else {
                None
            }
        }
        None if widget.eq_id(&id) => Some(widget.rect()),
        _ => None,
    }
}
src/event/manager/config_mgr.rs (line 189)
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
        fn nav(
            mgr: &mut ConfigMgr,
            widget: &mut dyn Widget,
            focus: Option<&WidgetId>,
            rev: bool,
        ) -> Option<WidgetId> {
            if mgr.ev_state().is_disabled(widget.id_ref()) {
                return None;
            }

            let mut child = focus.and_then(|id| widget.find_child_index(id));

            if !rev {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                } else if !widget.eq_id(focus) && widget.navigable() {
                    return Some(widget.id());
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return None;
                    }
                }
            } else {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return if !widget.eq_id(focus) && widget.navigable() {
                            Some(widget.id())
                        } else {
                            None
                        };
                    }
                }
            }
        }

Display as “StructName#WidgetId”

Examples found in repository?
src/layout/sizer.rs (line 245)
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let len = 43 - 2 * self.1;
        let trail = "| ".repeat(self.1);
        // Note: pre-format some items to ensure correct alignment
        let identify = format!("{}", self.0.identify());
        let pos = format!("{:?}", self.0.rect().pos);
        let plen = 17usize.saturating_sub(identify.len().saturating_sub(len));
        let size = self.0.rect().size;
        write!(f, "\n{trail}{identify:<len$} {pos:<plen$} {size:?}")?;

        for i in 0..self.0.num_children() {
            WidgetHeirarchy(self.0.get_child(i).unwrap(), self.1 + 1).fmt(f)?;
        }
        Ok(())
    }
More examples
Hide additional examples
src/event/manager.rs (line 594)
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
    fn send_recurse(
        &mut self,
        widget: &mut dyn Widget,
        id: WidgetId,
        disabled: bool,
        event: Event,
    ) -> Response {
        let mut response = Response::Unused;
        if widget.steal_event(self, &id, &event) == Response::Used {
            response = Response::Used;
        } else if let Some(index) = widget.find_child_index(&id) {
            let translation = widget.translation();
            if let Some(w) = widget.get_child_mut(index) {
                response = self.send_recurse(w, id, disabled, event.clone() + translation);
                if self.scroll != Scroll::None {
                    widget.handle_scroll(self, self.scroll);
                }
            } else {
                log::warn!(
                    "send_recurse: {} found index {index} for {id} but not child",
                    widget.identify()
                );
            }

            if matches!(response, Response::Unused) {
                response = widget.handle_unused(self, index, event);
            } else if self.has_msg() {
                widget.handle_message(self, index);
            }
        } else if disabled {
            // event is unused
        } else if id == widget.id_ref() {
            if event == Event::NavFocus(true) {
                self.set_scroll(Scroll::Rect(widget.rect()));
                response = Response::Used;
            }

            response |= widget.pre_handle_event(self, event)
        } else {
            log::warn!(
                "send_recurse: Widget {} cannot find path to {id}",
                widget.identify()
            );
        }

        response
    }

Check whether id is self or a descendant

This function assumes that id is a valid widget.

Check whether id is not self and is a descendant

This function assumes that id is a valid widget.

Find the descendant with this id, if any

Examples found in repository?
src/core/widget.rs (line 629)
626
627
628
629
630
631
632
633
634
635
    fn find_widget(&self, id: &WidgetId) -> Option<&dyn Widget> {
        if let Some(index) = self.find_child_index(id) {
            self.get_child(index)
                .and_then(|child| child.find_widget(id))
        } else if self.eq_id(id) {
            return Some(self.as_widget());
        } else {
            None
        }
    }
More examples
Hide additional examples
src/event/manager/config_mgr.rs (line 294)
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
    pub fn next_nav_focus_from(
        &mut self,
        widget: &mut dyn Widget,
        id: WidgetId,
        key_focus: bool,
    ) -> bool {
        if id == self.nav_focus {
            return true;
        } else if !self.config.nav_focus {
            return false;
        }

        self.send_action(TkAction::REDRAW);
        if let Some(old_id) = self.nav_focus.take() {
            self.pending.push_back(Pending::LostNavFocus(old_id));
        }
        self.clear_char_focus();
        if widget
            .find_widget(&id)
            .map(|w| w.navigable())
            .unwrap_or(false)
        {
            log::trace!(target: "kas_core::event::manager", "set_nav_focus: {id}");
            self.nav_focus = Some(id.clone());
            self.pending.push_back(Pending::SetNavFocus(id, key_focus));
            true
        } else {
            self.nav_focus = Some(id);
            self.next_nav_focus(widget, false, key_focus)
        }
    }
src/event/manager/mgr_pub.rs (line 873)
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
    pub fn next_nav_focus_from(
        &mut self,
        widget: &mut dyn Widget,
        id: WidgetId,
        key_focus: bool,
    ) -> bool {
        if id == self.nav_focus {
            return true;
        } else if !self.config.nav_focus {
            return false;
        }

        self.send_action(TkAction::REDRAW);
        if let Some(old_id) = self.nav_focus.take() {
            self.pending.push_back(Pending::LostNavFocus(old_id));
        }
        self.clear_char_focus();
        if widget
            .find_widget(&id)
            .map(|w| w.navigable())
            .unwrap_or(false)
        {
            log::trace!(target: "kas_core::event::manager", "set_nav_focus: {id}");
            self.nav_focus = Some(id.clone());
            self.pending.push_back(Pending::SetNavFocus(id, key_focus));
            true
        } else {
            self.nav_focus = Some(id);
            self.next_nav_focus(widget, false, key_focus)
        }
    }
src/event/manager.rs (line 539)
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
    fn start_key_event(&mut self, widget: &mut dyn Widget, vkey: VirtualKeyCode, scancode: u32) {
        log::trace!(
            "start_key_event: widget={}, vkey={vkey:?}, scancode={scancode}",
            widget.id()
        );

        use VirtualKeyCode as VK;

        let opt_command = self.config.shortcuts(|s| s.get(self.modifiers, vkey));

        if let Some(cmd) = opt_command {
            let mut targets = vec![];
            let mut send = |_self: &mut Self, id: WidgetId, cmd| -> bool {
                if !targets.contains(&id) {
                    let used = _self.send_event(widget, id.clone(), Event::Command(cmd));
                    if used {
                        _self.add_key_depress(scancode, id.clone());
                    }
                    targets.push(id);
                    used
                } else {
                    false
                }
            };

            if self.char_focus || cmd.suitable_for_sel_focus() {
                if let Some(id) = self.sel_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if !self.modifiers.alt() {
                if let Some(id) = self.nav_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if let Some(id) = self.popups.last().map(|popup| popup.1.parent.clone()) {
                if send(self, id, cmd) {
                    return;
                }
            }

            if let Some(id) = self.nav_fallback.clone() {
                if send(self, id, cmd) {
                    return;
                }
            }
        }

        // Next priority goes to accelerator keys when Alt is held or alt_bypass is true
        let mut target = None;
        let mut n = 0;
        for (i, id) in (self.popups.iter().rev())
            .map(|(_, popup, _)| popup.parent.clone())
            .chain(std::iter::once(widget.id()))
            .enumerate()
        {
            if let Some(layer) = self.accel_layers.get(&id) {
                // but only when Alt is held or alt-bypass is enabled:
                if self.modifiers == ModifiersState::ALT
                    || layer.0 && self.modifiers == ModifiersState::empty()
                {
                    if let Some(id) = layer.1.get(&vkey).cloned() {
                        target = Some(id);
                        n = i;
                        break;
                    }
                }
            }
        }

        // If we found a key binding below the top layer, we should close everything above
        if n > 0 {
            let len = self.popups.len();
            for i in ((len - n)..len).rev() {
                let id = self.popups[i].0;
                self.close_window(id, false);
            }
        }

        if let Some(id) = target {
            if widget
                .find_widget(&id)
                .map(|w| w.navigable())
                .unwrap_or(false)
            {
                self.set_nav_focus(id.clone(), true);
            }
            self.add_key_depress(scancode, id.clone());
            self.send_event(widget, id, Event::Command(Command::Activate));
        } else if self.config.nav_focus && vkey == VK::Tab {
            self.clear_char_focus();
            let shift = self.modifiers.shift();
            self.next_nav_focus(widget, shift, true);
        } else if vkey == VK::Escape {
            if let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
                self.close_window(id, true);
            }
        }
    }
src/event/manager/mgr_shell.rs (line 429)
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
    pub fn handle_winit(&mut self, widget: &mut dyn Widget, event: winit::event::WindowEvent) {
        use winit::event::{ElementState, MouseScrollDelta, TouchPhase, WindowEvent::*};

        match event {
            CloseRequested => self.send_action(TkAction::CLOSE),
            /* Not yet supported: see #98
            DroppedFile(path) => ,
            HoveredFile(path) => ,
            HoveredFileCancelled => ,
            */
            ReceivedCharacter(c) => {
                if let Some(id) = self.char_focus() {
                    // Filter out control codes (Unicode 5.11). These may be
                    // generated from combinations such as Ctrl+C by some other
                    // layer. We use our own shortcut system instead.
                    if c >= '\x20' && !('\x7f'..='\u{9f}').contains(&c) {
                        let event = Event::ReceivedCharacter(c);
                        self.send_event(widget, id, event);
                    }
                }
            }
            Focused(state) => {
                self.window_has_focus = state;
                if state {
                    // Required to restart theme animations
                    self.send_action(TkAction::REDRAW);
                } else {
                    // Window focus lost: close all popups
                    while let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
                        self.close_window(id, true);
                    }
                }
            }
            KeyboardInput {
                input,
                is_synthetic,
                ..
            } => {
                if input.state == ElementState::Pressed && !is_synthetic {
                    if let Some(vkey) = input.virtual_keycode {
                        self.start_key_event(widget, vkey, input.scancode);
                    }
                } else if input.state == ElementState::Released {
                    self.end_key_event(input.scancode);
                }
            }
            ModifiersChanged(state) => {
                if state.alt() != self.modifiers.alt() {
                    // This controls drawing of accelerator key indicators
                    self.send_action(TkAction::REDRAW);
                }
                self.modifiers = state;
            }
            CursorMoved { position, .. } => {
                self.last_click_button = FAKE_MOUSE_BUTTON;
                let coord = position.cast_approx();

                // Update hovered widget
                let cur_id = widget.find_id(coord);
                let delta = coord - self.last_mouse_coord;
                self.set_hover(cur_id.clone());

                if let Some(grab) = self.state.mouse_grab.as_mut() {
                    if grab.mode == GrabMode::Grab {
                        grab.cur_id = cur_id;
                        grab.coord = coord;
                        grab.delta += delta;
                    } else if let Some(pan) =
                        self.state.pan_grab.get_mut(usize::conv(grab.pan_grab.0))
                    {
                        pan.coords[usize::conv(grab.pan_grab.1)].1 = coord;
                    }
                } else if let Some(id) = self.popups.last().map(|(_, p, _)| p.parent.clone()) {
                    let source = PressSource::Mouse(FAKE_MOUSE_BUTTON, 0);
                    let event = Event::PressMove {
                        source,
                        cur_id,
                        coord,
                        delta,
                    };
                    self.send_event(widget, id, event);
                } else {
                    // We don't forward move events without a grab
                }

                self.last_mouse_coord = coord;
            }
            // CursorEntered { .. },
            CursorLeft { .. } => {
                self.last_click_button = FAKE_MOUSE_BUTTON;

                if self.mouse_grab().is_none() {
                    // If there's a mouse grab, we will continue to receive
                    // coordinates; if not, set a fake coordinate off the window
                    self.last_mouse_coord = Coord(-1, -1);
                    self.set_hover(None);
                }
            }
            MouseWheel { delta, .. } => {
                if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
                    self.send_event(widget, id, event);
                }

                self.last_click_button = FAKE_MOUSE_BUTTON;

                let event = Event::Scroll(match delta {
                    MouseScrollDelta::LineDelta(x, y) => ScrollDelta::LineDelta(x, y),
                    MouseScrollDelta::PixelDelta(pos) => {
                        // The delta is given as a PhysicalPosition, so we need
                        // to convert to our vector type (Offset) here.
                        let coord = Coord::conv_approx(pos);
                        ScrollDelta::PixelDelta(coord.cast())
                    }
                });
                if let Some(id) = self.hover.clone() {
                    self.send_event(widget, id, event);
                }
            }
            MouseInput { state, button, .. } => {
                if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
                    self.send_event(widget, id, event);
                }

                let coord = self.last_mouse_coord;

                if state == ElementState::Pressed {
                    let now = Instant::now();
                    if button != self.last_click_button || self.last_click_timeout < now {
                        self.last_click_button = button;
                        self.last_click_repetitions = 0;
                    }
                    self.last_click_repetitions += 1;
                    self.last_click_timeout = now + DOUBLE_CLICK_TIMEOUT;
                }

                if let Some(grab) = self.remove_mouse_grab() {
                    if grab.mode == GrabMode::Grab {
                        // Mouse grab active: send events there
                        // Note: any button release may end the grab (intended).
                        let event = Event::PressEnd {
                            source: PressSource::Mouse(grab.button, grab.repetitions),
                            end_id: self.hover.clone(),
                            coord,
                            success: state == ElementState::Released,
                        };
                        self.send_event(widget, grab.start_id, event);
                    }
                    // Pan events do not receive Start/End notifications
                }

                if state == ElementState::Pressed {
                    if let Some(start_id) = self.hover.clone() {
                        // No mouse grab but have a hover target
                        if self.config.mouse_nav_focus() {
                            if let Some(w) = widget.find_widget(&start_id) {
                                if w.navigable() {
                                    self.set_nav_focus(w.id(), false);
                                }
                            }
                        }
                    }

                    let source = PressSource::Mouse(button, self.last_click_repetitions);
                    let event = Event::PressStart {
                        source,
                        start_id: self.hover.clone(),
                        coord,
                    };
                    self.send_popup_first(widget, self.hover.clone(), event);
                }
            }
            // TouchpadPressure { pressure: f32, stage: i64, },
            // AxisMotion { axis: AxisId, value: f64, },
            Touch(touch) => {
                let source = PressSource::Touch(touch.id);
                let coord = touch.location.cast_approx();
                match touch.phase {
                    TouchPhase::Started => {
                        let start_id = widget.find_id(coord);
                        if let Some(id) = start_id.as_ref() {
                            if self.config.touch_nav_focus() {
                                if let Some(w) = widget.find_widget(id) {
                                    if w.navigable() {
                                        self.set_nav_focus(w.id(), false);
                                    }
                                }
                            }

                            let event = Event::PressStart {
                                source,
                                start_id: start_id.clone(),
                                coord,
                            };
                            self.send_popup_first(widget, start_id, event);
                        }
                    }
                    TouchPhase::Moved => {
                        let cur_id = widget.find_id(coord);

                        let mut redraw = false;
                        let mut pan_grab = None;
                        if let Some(grab) = self.get_touch(touch.id) {
                            if grab.mode == GrabMode::Grab {
                                // Only when 'depressed' status changes:
                                redraw = grab.cur_id != cur_id
                                    && (grab.start_id == grab.cur_id || grab.start_id == cur_id);

                                grab.cur_id = cur_id;
                                grab.coord = coord;
                            } else {
                                pan_grab = Some(grab.pan_grab);
                            }
                        }

                        if redraw {
                            self.send_action(TkAction::REDRAW);
                        } else if let Some(pan_grab) = pan_grab {
                            if usize::conv(pan_grab.1) < MAX_PAN_GRABS {
                                if let Some(pan) = self.pan_grab.get_mut(usize::conv(pan_grab.0)) {
                                    pan.coords[usize::conv(pan_grab.1)].1 = coord;
                                }
                            }
                        }
                    }
                    ev @ (TouchPhase::Ended | TouchPhase::Cancelled) => {
                        if let Some(mut grab) = self.remove_touch(touch.id) {
                            if let Some((id, event)) = grab.flush_move() {
                                self.send_event(widget, id, event);
                            }

                            if grab.mode == GrabMode::Grab {
                                let event = Event::PressEnd {
                                    source,
                                    end_id: grab.cur_id.clone(),
                                    coord,
                                    success: ev == TouchPhase::Ended,
                                };
                                self.send_event(widget, grab.start_id, event);
                            }
                        }
                    }
                }
            }
            _ => (),
        }
    }

Find the descendant with this id, if any

Examples found in repository?
src/core/widget.rs (line 641)
638
639
640
641
642
643
644
645
646
647
    fn find_widget_mut(&mut self, id: &WidgetId) -> Option<&mut dyn Widget> {
        if let Some(index) = self.find_child_index(id) {
            self.get_child_mut(index)
                .and_then(|child| child.find_widget_mut(id))
        } else if self.eq_id(id) {
            return Some(self.as_widget_mut());
        } else {
            None
        }
    }
More examples
Hide additional examples
src/root.rs (line 50)
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
        fn find_id(&mut self, coord: Coord) -> Option<WidgetId> {
            if !self.core.rect.contains(coord) {
                return None;
            }
            for popup in self.popups.iter_mut().rev() {
                if let Some(id) = self
                    .w
                    .find_widget_mut(&popup.1.id)
                    .and_then(|w| w.find_id(coord))
                {
                    return Some(id);
                }
            }
            self.w.find_id(coord).or_else(|| Some(self.id()))
        }

        fn draw(&mut self, mut draw: DrawMgr) {
            draw.recurse(&mut self.w);
            for (_, popup) in &self.popups {
                if let Some(widget) = self.w.find_widget_mut(&popup.id) {
                    draw.with_overlay(widget.rect(), |mut draw| {
                        draw.recurse(widget);
                    });
                }
            }
        }
    }
}

impl RootWidget {
    /// Construct
    pub fn new(w: Box<dyn Window>) -> RootWidget {
        RootWidget {
            core: Default::default(),
            w,
            popups: Default::default(),
        }
    }

    /// Add a pop-up as a layer in the current window
    ///
    /// Each [`crate::Popup`] is assigned a [`WindowId`]; both are passed.
    pub fn add_popup(&mut self, mgr: &mut EventMgr, id: WindowId, popup: kas::Popup) {
        let index = self.popups.len();
        self.popups.push((id, popup));
        mgr.config_mgr(|mgr| self.resize_popup(mgr, index));
        mgr.send_action(TkAction::REDRAW);
    }

    /// Trigger closure of a pop-up
    ///
    /// If the given `id` refers to a pop-up, it should be closed.
    pub fn remove_popup(&mut self, mgr: &mut EventMgr, id: WindowId) {
        for i in 0..self.popups.len() {
            if id == self.popups[i].0 {
                self.popups.remove(i);
                mgr.send_action(TkAction::REGION_MOVED);
                return;
            }
        }
    }

    /// Resize popups
    ///
    /// This is called immediately after [`Layout::set_rect`] to resize
    /// existing pop-ups.
    pub fn resize_popups(&mut self, mgr: &mut ConfigMgr) {
        for i in 0..self.popups.len() {
            self.resize_popup(mgr, i);
        }
    }
}

// This is like WidgetChildren::find, but returns a translated Rect.
fn find_rect(widget: &dyn Widget, id: WidgetId) -> Option<Rect> {
    match widget.find_child_index(&id) {
        Some(i) => {
            if let Some(w) = widget.get_child(i) {
                find_rect(w, id).map(|rect| rect - widget.translation())
            } else {
                None
            }
        }
        None if widget.eq_id(&id) => Some(widget.rect()),
        _ => None,
    }
}

impl RootWidget {
    fn resize_popup(&mut self, mgr: &mut ConfigMgr, index: usize) {
        // Notation: p=point/coord, s=size, m=margin
        // r=window/root rect, c=anchor rect
        let r = self.core.rect;
        let popup = &mut self.popups[index].1;

        let c = find_rect(&self.w, popup.parent.clone()).unwrap();
        let widget = self.w.find_widget_mut(&popup.id).unwrap();
        let mut cache = layout::SolveCache::find_constraints(widget, mgr.size_mgr());
        let ideal = cache.ideal(false);
        let m = cache.margins();

        let is_reversed = popup.direction.is_reversed();
        let place_in = |rp, rs: i32, cp: i32, cs: i32, ideal, m: (u16, u16)| -> (i32, i32) {
            let m: (i32, i32) = (m.0.into(), m.1.into());
            let before: i32 = cp - (rp + m.1);
            let before = before.max(0);
            let after = (rs - (cs + before + m.0)).max(0);
            if after >= ideal {
                if is_reversed && before >= ideal {
                    (cp - ideal - m.1, ideal)
                } else {
                    (cp + cs + m.0, ideal)
                }
            } else if before >= ideal {
                (cp - ideal - m.1, ideal)
            } else if before > after {
                (rp, before)
            } else {
                (cp + cs + m.0, after)
            }
        };
        #[allow(clippy::manual_clamp)]
        let place_out = |rp, rs, cp: i32, cs, ideal: i32| -> (i32, i32) {
            let pos = cp.min(rp + rs - ideal).max(rp);
            let size = ideal.max(cs).min(rs);
            (pos, size)
        };
        let rect = if popup.direction.is_horizontal() {
            let (x, w) = place_in(r.pos.0, r.size.0, c.pos.0, c.size.0, ideal.0, m.horiz);
            let (y, h) = place_out(r.pos.1, r.size.1, c.pos.1, c.size.1, ideal.1);
            Rect::new(Coord(x, y), Size::new(w, h))
        } else {
            let (x, w) = place_out(r.pos.0, r.size.0, c.pos.0, c.size.0, ideal.0);
            let (y, h) = place_in(r.pos.1, r.size.1, c.pos.1, c.size.1, ideal.1, m.vert);
            Rect::new(Coord(x, y), Size::new(w, h))
        };

        cache.apply_rect(widget, mgr, rect, false, true);
    }
src/event/manager/config_mgr.rs (line 153)
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
    pub fn next_nav_focus(
        &mut self,
        mut widget: &mut dyn Widget,
        reverse: bool,
        key_focus: bool,
    ) -> bool {
        if !self.config.nav_focus {
            return false;
        }

        if let Some(id) = self.popups.last().map(|(_, p, _)| p.id.clone()) {
            if id.is_ancestor_of(widget.id_ref()) {
                // do nothing
            } else if let Some(w) = widget.find_widget_mut(&id) {
                widget = w;
            } else {
                log::warn!(
                    target: "kas_core::event::config_mgr",
                    "next_nav_focus: have open pop-up which is not a child of widget",
                );
                return false;
            }
        }

        // We redraw in all cases. Since this is not part of widget event
        // processing, we can push directly to self.action.
        self.send_action(TkAction::REDRAW);
        let old_nav_focus = self.nav_focus.take();

        fn nav(
            mgr: &mut ConfigMgr,
            widget: &mut dyn Widget,
            focus: Option<&WidgetId>,
            rev: bool,
        ) -> Option<WidgetId> {
            if mgr.ev_state().is_disabled(widget.id_ref()) {
                return None;
            }

            let mut child = focus.and_then(|id| widget.find_child_index(id));

            if !rev {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                } else if !widget.eq_id(focus) && widget.navigable() {
                    return Some(widget.id());
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return None;
                    }
                }
            } else {
                if let Some(index) = child {
                    if let Some(id) = widget
                        .get_child_mut(index)
                        .and_then(|w| nav(mgr, w, focus, rev))
                    {
                        return Some(id);
                    }
                }

                loop {
                    if let Some(index) = widget.nav_next(mgr, rev, child) {
                        if let Some(id) = widget
                            .get_child_mut(index)
                            .and_then(|w| nav(mgr, w, focus, rev))
                        {
                            return Some(id);
                        }
                        child = Some(index);
                    } else {
                        return if !widget.eq_id(focus) && widget.navigable() {
                            Some(widget.id())
                        } else {
                            None
                        };
                    }
                }
            }
        }

        // Whether to restart from the beginning on failure
        let restart = old_nav_focus.is_some();

        let mut opt_id = nav(self, widget, old_nav_focus.as_ref(), reverse);
        if restart && opt_id.is_none() {
            opt_id = nav(self, widget, None, reverse);
        }

        log::trace!(
            target: "kas_core::event::config_mgr",
            "next_nav_focus: nav_focus={opt_id:?}",
        );
        self.nav_focus = opt_id.clone();

        if opt_id == old_nav_focus {
            return opt_id.is_some();
        }

        if let Some(id) = old_nav_focus {
            self.pending.push_back(Pending::LostNavFocus(id));
        }

        if let Some(id) = opt_id {
            if id != self.sel_focus {
                self.clear_char_focus();
            }
            self.pending.push_back(Pending::SetNavFocus(id, key_focus));
            true
        } else {
            // Most likely an error occurred
            self.clear_char_focus();
            false
        }
    }

Implementors§