Skip to main content

prism_linux/
imp.rs

1//! GTK widgets for Prism nodes, the window and the event loop.
2
3use std::cell::{Cell, RefCell};
4use std::collections::{HashMap, HashSet};
5use std::rc::Rc;
6use std::sync::OnceLock;
7
8use gtk::prelude::*;
9use gtk::{gdk, gio, glib};
10use prism_core::{
11    Accessibility, AppConfig, AppInit, Appearance, Backend, Color, NodeId, NodeKind, Runtime,
12    Style, TextAlign, UiEvent,
13};
14use prism_native::{Insets, NativeRenderer, Viewport, Widgets};
15
16use crate::controls;
17use crate::layout;
18use crate::text;
19
20const HEADER: f32 = 44.;
21const TAB_BAR: f32 = 52.;
22
23static APP: OnceLock<(AppConfig, AppInit)> = OnceLock::new();
24
25// ---------------------------------------------------------------------------
26// Views
27// ---------------------------------------------------------------------------
28
29pub struct NavStack {
30    root: gtk::Box,
31    header: gtk::Box,
32    back: gtk::Button,
33    title: gtk::Label,
34    screens: RefCell<Vec<View>>,
35    /// Inside a modal: the first screen offers "Close".
36    in_sheet: Cell<bool>,
37    // --- Hidden header (#8) ---
38    /// No header bar at all (`Router::header(false)`).
39    no_header: Cell<bool>,
40}
41
42pub struct TabBar {
43    root: gtk::Box,
44    bar: gtk::Box,
45    tabs: RefCell<Vec<View>>,
46    selected: Cell<usize>,
47}
48
49pub struct Sheet {
50    window: gtk::Window,
51    content: gtk::Box,
52    children: RefCell<Vec<View>>,
53}
54
55#[derive(Clone)]
56pub enum View {
57    /// view, screen, tab: a Prism-laid-out container.
58    Container(NodeId, NodeKind, gtk::Box),
59    Text(NodeId, gtk::Label),
60    Button(NodeId, gtk::Button),
61    Input(NodeId, gtk::Entry),
62    Toggle(NodeId, gtk::Switch),
63    Progress(NodeId, gtk::ProgressBar),
64    /// SF Symbol names drawn as glyphs (see prism_core::glyphs).
65    Image(NodeId, gtk::Label),
66    Picture(NodeId, gtk::Picture),
67    Timer(NodeId, gtk::Label),
68    Scroll(NodeId, gtk::ScrolledWindow, gtk::Box),
69    Stack(NodeId, Rc<NavStack>),
70    Tabs(NodeId, Rc<TabBar>),
71    Sheet(NodeId, Rc<Sheet>),
72    /// Vector drawing (cairo), with its paths in points.
73    Shape(NodeId, gtk::DrawingArea, Rc<RefCell<Vec<prism_core::Path>>>),
74    /// 3D scene (OpenGL).
75    Scene(NodeId, Rc<crate::scene3d::SceneView>),
76    Slider(
77        NodeId,
78        gtk::Scale,
79        Rc<Cell<prism_core::controls::SliderConfig>>,
80    ),
81    Picker(NodeId, Rc<controls::Picker>),
82    DatePicker(NodeId, Rc<controls::DatePicker>),
83    TextArea(NodeId, Rc<controls::TextArea>),
84    Spinner(NodeId, gtk::Spinner),
85    // Choice controls and overlays (#18, #19).
86    Check(NodeId, gtk::CheckButton),
87    Radio(NodeId, Rc<controls::RadioGroup>),
88    Overlay(NodeId, Rc<OverlayView>),
89    /// A video (#207): GTK's player (GStreamer) with its own controls.
90    Video(NodeId, gtk::Video),
91}
92
93thread_local! {
94    /// Whether shapes and 3D scenes draw the dark variants of their colors.
95    static SHAPE_DARK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
96}
97
98/// Whether the dark appearance is on (for drawings: shapes, 3D scenes).
99pub(crate) fn dark() -> bool {
100    SHAPE_DARK.with(Cell::get)
101}
102
103/// Fills, then strokes, each path with cairo.
104fn draw_paths(cr: &gtk::cairo::Context, paths: &[prism_core::Path]) {
105    use prism_core::Segment as S;
106    let dark = SHAPE_DARK.with(|d| d.get());
107    let source = |c: Color| {
108        let c = if dark {
109            c.dark_variant()
110        } else {
111            c.light_variant()
112        };
113        cr.set_source_rgba(c.r as f64, c.g as f64, c.b as f64, c.a as f64);
114    };
115    for p in paths {
116        cr.new_path();
117        for s in &p.segments {
118            match *s {
119                S::Move(x, y) => cr.move_to(x as f64, y as f64),
120                S::Line(x, y) => cr.line_to(x as f64, y as f64),
121                S::Cubic(a, b, c, d, e, f) => {
122                    cr.curve_to(a as f64, b as f64, c as f64, d as f64, e as f64, f as f64)
123                }
124                S::Close => cr.close_path(),
125                S::Arc { .. } => {}
126            }
127        }
128        if let Some(c) = p.fill {
129            source(c);
130            cr.set_fill_rule(if p.even_odd {
131                gtk::cairo::FillRule::EvenOdd
132            } else {
133                gtk::cairo::FillRule::Winding
134            });
135            let _ = cr.fill_preserve();
136        }
137        if let Some(c) = p.stroke {
138            source(c);
139            cr.set_line_width(p.width as f64);
140            let (cap, join) = if p.round {
141                (gtk::cairo::LineCap::Round, gtk::cairo::LineJoin::Round)
142            } else {
143                (gtk::cairo::LineCap::Butt, gtk::cairo::LineJoin::Miter)
144            };
145            cr.set_line_cap(cap);
146            cr.set_line_join(join);
147            match p.dash {
148                Some((d, g)) => cr.set_dash(&[d as f64, g as f64], 0.),
149                None => cr.set_dash(&[], 0.),
150            }
151            let _ = cr.stroke_preserve();
152        }
153        cr.new_path();
154    }
155}
156
157impl View {
158    fn id(&self) -> NodeId {
159        match self {
160            View::Container(id, ..)
161            | View::Text(id, _)
162            | View::Button(id, _)
163            | View::Input(id, _)
164            | View::Toggle(id, _)
165            | View::Progress(id, _)
166            | View::Image(id, _)
167            | View::Picture(id, _)
168            | View::Timer(id, _)
169            | View::Scroll(id, ..)
170            | View::Stack(id, _)
171            | View::Tabs(id, _)
172            | View::Sheet(id, _)
173            | View::Shape(id, ..)
174            | View::Scene(id, _)
175            | View::Slider(id, ..)
176            | View::Picker(id, _)
177            | View::DatePicker(id, _)
178            | View::TextArea(id, _)
179            | View::Spinner(id, _)
180            | View::Check(id, _)
181            | View::Radio(id, _)
182            | View::Overlay(id, _)
183            | View::Video(id, _) => *id,
184        }
185    }
186
187    /// The widget placed in the parent.
188    fn widget(&self) -> gtk::Widget {
189        match self {
190            View::Container(_, _, w) => w.clone().upcast(),
191            View::Text(_, w) | View::Image(_, w) | View::Timer(_, w) => w.clone().upcast(),
192            View::Button(_, w) => w.clone().upcast(),
193            View::Input(_, w) => w.clone().upcast(),
194            View::Toggle(_, w) => w.clone().upcast(),
195            View::Progress(_, w) => w.clone().upcast(),
196            View::Picture(_, w) => w.clone().upcast(),
197            View::Scroll(_, w, _) => w.clone().upcast(),
198            View::Stack(_, s) => s.root.clone().upcast(),
199            View::Tabs(_, t) => t.root.clone().upcast(),
200            View::Sheet(_, s) => s.content.clone().upcast(),
201            View::Shape(_, w, _) => w.clone().upcast(),
202            View::Scene(_, s) => s.area.clone().upcast(),
203            View::Slider(_, w, _) => w.clone().upcast(),
204            View::Picker(_, p) => p.dropdown.clone().upcast(),
205            View::DatePicker(_, p) => p.button.clone().upcast(),
206            View::TextArea(_, t) => t.root.clone().upcast(),
207            View::Spinner(_, w) => w.clone().upcast(),
208            View::Check(_, b) => b.clone().upcast(),
209            View::Radio(_, r) => r.root.clone().upcast(),
210            View::Overlay(_, o) => o.anchor.clone().upcast(),
211            View::Video(_, v) => v.clone().upcast(),
212        }
213    }
214}
215
216/// How a container's children change (`set_children`): the old ones to
217/// unparent, then the order of what is left. What `stays` (popovers,
218/// pictures of removed views) comes first, then `new`. A child in both is
219/// moved in place, never unparented: unparented, a focused field would lose
220/// the focus and its selection when a sibling comes or goes.
221fn arrange_children<T: Clone + Eq + std::hash::Hash>(
222    old: &[T],
223    new: &[T],
224    stays: impl Fn(&T) -> bool,
225) -> (Vec<T>, Vec<T>) {
226    // A set: long lists have thousands of children on each side.
227    let in_new: HashSet<&T> = new.iter().collect();
228    let (kept, gone): (Vec<T>, Vec<T>) = old
229        .iter()
230        .filter(|c| !in_new.contains(c))
231        .cloned()
232        .partition(|c| stays(c));
233    (gone, kept.into_iter().chain(new.iter().cloned()).collect())
234}
235
236// ---------------------------------------------------------------------------
237// Overlays (#19): a popover anchored to the overlay's parent, or a modal
238// window for sheets and dialogs
239// ---------------------------------------------------------------------------
240
241/// Marks a popover a press around closes while it leaves the focus to its
242/// anchor (#182).
243const LIGHT_BESIDE_FOCUS: &str = "prism-light-beside-focus";
244
245/// Autohide (close on a click outside, which also grabs the keyboard focus)
246/// unless the popover is fixed, manual, or leaves the focus to its anchor;
247/// one that leaves the focus never takes it, and a press around it closes
248/// it through `OverlayView::watch_outside` instead (#182).
249fn set_popover_mode(p: &gtk::Popover, config: prism_core::controls::OverlayConfig) {
250    p.set_autohide(!(config.fixed || config.manual || config.keep_focus));
251    p.set_can_focus(!config.keep_focus);
252    if config.light_dismiss_beside_focus() {
253        p.add_css_class(LIGHT_BESIDE_FOCUS);
254    } else {
255        p.remove_css_class(LIGHT_BESIDE_FOCUS);
256    }
257    p.set_has_arrow(!config.bare);
258    set_bare(p, config.bare);
259}
260
261/// A bare dialog (#166): no box of its own (the `prism-bare` rules take
262/// GTK's background, border, padding and shadow away).
263fn set_bare(w: &impl IsA<gtk::Widget>, bare: bool) {
264    if bare {
265        w.add_css_class("prism-bare");
266    } else {
267        w.remove_css_class("prism-bare");
268    }
269}
270
271/// On its side of `parent` (GTK takes the opposite side without room
272/// there), pointing at the part of `parent` it lines up with: GTK centers
273/// the popover on that part (#113).
274fn place_popover(
275    p: &gtk::Popover,
276    parent: &gtk::Widget,
277    config: prism_core::controls::OverlayConfig,
278    size: (i32, i32),
279) {
280    use prism_core::PopoverSide as S;
281    let rtl = parent.direction() == gtk::TextDirection::Rtl;
282    // GTK's left and right are the screen's.
283    p.set_position(match config.side {
284        S::Bottom => gtk::PositionType::Bottom,
285        S::Top => gtk::PositionType::Top,
286        S::Trailing if rtl => gtk::PositionType::Left,
287        S::Trailing => gtk::PositionType::Right,
288        S::Leading if rtl => gtk::PositionType::Right,
289        S::Leading => gtk::PositionType::Left,
290    });
291    let (w, h) = (parent.width(), parent.height());
292    let rect = if config.side.beside() {
293        // Start is the top (GTK's y goes down).
294        let (o, l) = config.align.arrow_span(h as f64, size.1 as f64, true);
295        gdk::Rectangle::new(0, o.round() as i32, w, (l.round() as i32).max(1))
296    } else {
297        let (o, l) = config.align.arrow_span(w as f64, size.0 as f64, !rtl);
298        gdk::Rectangle::new(o.round() as i32, 0, (l.round() as i32).max(1), h)
299    };
300    p.set_pointing_to(Some(&rect));
301}
302
303/// Shown in a `GtkPopover`: popovers, and dialogs placed beside their
304/// anchor (#79). An autohiding popover keeps the focus inside and closes
305/// on Escape or a click outside, like the dialog.
306fn popover_kind(config: prism_core::controls::OverlayConfig) -> bool {
307    config.anchored_side().is_some()
308}
309
310pub struct OverlayView {
311    id: NodeId,
312    /// Zero-size placeholder in the parent (the popover's anchor is the
313    /// parent).
314    anchor: gtk::Box,
315    /// Holds the content node, at its Prism frame.
316    content: gtk::Box,
317    popover: RefCell<Option<gtk::Popover>>,
318    window: RefCell<Option<gtk::Window>>,
319    config: Cell<prism_core::controls::OverlayConfig>,
320    open: Cell<bool>,
321    /// Content size from the last layout.
322    size: Cell<(i32, i32)>,
323    /// The press watcher on the anchor's window of a popover that leaves
324    /// the focus to its anchor (#182).
325    outside: RefCell<Option<(gtk::Window, gtk::GestureClick)>>,
326}
327
328impl OverlayView {
329    /// Builds the popover or window `config` asks for.
330    fn configure(
331        self: &Rc<Self>,
332        config: prism_core::controls::OverlayConfig,
333        main: &gtk::ApplicationWindow,
334        keys: &Rc<KeyState>,
335    ) {
336        use prism_core::OverlayKind;
337        let old = self.config.replace(config);
338        let built = self.popover.borrow().is_some() || self.window.borrow().is_some();
339        let as_popover = popover_kind(config);
340        if built && popover_kind(old) == as_popover {
341            if let Some(p) = self.popover.borrow().as_ref() {
342                set_popover_mode(p, config);
343                if let Some(parent) = p.parent() {
344                    place_popover(p, &parent, config, self.size.get());
345                }
346            }
347            if let Some(w) = self.window.borrow().as_ref() {
348                w.set_deletable(!config.fixed);
349                w.set_decorated(!config.bare);
350                set_bare(w, config.bare);
351            }
352            return;
353        }
354        self.teardown();
355        let id = self.id;
356        if as_popover {
357            let p = gtk::Popover::new();
358            set_popover_mode(&p, config);
359            p.set_child(Some(&self.content));
360            // An Escape just before it closes is its reason (#156); GTK's
361            // autohide does not say.
362            let keys = gtk::EventControllerKey::new();
363            keys.set_propagation_phase(gtk::PropagationPhase::Capture);
364            keys.connect_key_pressed(|_, key, _, _| {
365                if key == gdk::Key::Escape {
366                    ESCAPE_AT.set(Some(std::time::Instant::now()));
367                }
368                glib::Propagation::Proceed
369            });
370            p.add_controller(keys);
371            let weak = Rc::downgrade(self);
372            p.connect_closed(move |p| {
373                let Some(o) = weak.upgrade() else { return };
374                if !o.open.get() {
375                    return;
376                }
377                if o.config.get().fixed {
378                    // Escape closed a fixed popover: it stays.
379                    let p = p.clone();
380                    glib::idle_add_local_once(move || p.popup());
381                } else {
382                    o.open.set(false);
383                    let escape = ESCAPE_AT
384                        .take()
385                        .is_some_and(|at| at.elapsed() < std::time::Duration::from_millis(500));
386                    let reason = if escape {
387                        prism_core::DismissReason::Escape
388                    } else {
389                        prism_core::DismissReason::Outside
390                    };
391                    dispatch(UiEvent::Dismiss(id, reason));
392                }
393            });
394            *self.popover.borrow_mut() = Some(p);
395        } else {
396            let w = gtk::Window::builder()
397                .transient_for(main)
398                .modal(true)
399                .destroy_with_parent(true)
400                .resizable(config.kind == OverlayKind::Sheet)
401                .deletable(!config.fixed)
402                .decorated(!config.bare)
403                .accessible_role(gtk::AccessibleRole::Dialog)
404                .child(&self.content)
405                .build();
406            let weak = Rc::downgrade(self);
407            w.connect_close_request(move |_| {
408                if let Some(o) = weak.upgrade() {
409                    o.user_closed(prism_core::DismissReason::Back);
410                }
411                glib::Propagation::Stop
412            });
413            // Escape closes it; the app's key handlers see the dialog's keys.
414            let esc = gtk::EventControllerKey::new();
415            let weak = Rc::downgrade(self);
416            esc.connect_key_pressed(move |_, key, _, _| {
417                if key == gdk::Key::Escape
418                    && let Some(o) = weak.upgrade()
419                    && !o.config.get().fixed
420                {
421                    o.user_closed(prism_core::DismissReason::Escape);
422                    return glib::Propagation::Stop;
423                }
424                glib::Propagation::Proceed
425            });
426            w.add_controller(esc);
427            attach_keys(&w, keys.clone());
428            set_bare(&w, config.bare);
429            *self.window.borrow_mut() = Some(w);
430        }
431        if self.open.get() {
432            self.show();
433        }
434    }
435
436    /// Escape or the close button: closes at once (unless fixed) and tells
437    /// the app, which keeps it closed or opens it again.
438    fn user_closed(&self, reason: prism_core::DismissReason) {
439        if self.config.get().fixed || !self.open.get() {
440            return;
441        }
442        self.open.set(false);
443        if let Some(w) = self.window.borrow().as_ref() {
444            w.set_visible(false);
445        }
446        dispatch(UiEvent::Dismiss(self.id, reason));
447    }
448
449    fn teardown(&self) {
450        self.unwatch_outside();
451        if let Some(p) = self.popover.borrow_mut().take() {
452            p.set_child(None::<&gtk::Widget>);
453            if p.parent().is_some() {
454                p.unparent();
455            }
456        }
457        if let Some(w) = self.window.borrow_mut().take() {
458            w.set_child(None::<&gtk::Widget>);
459            w.destroy();
460        }
461    }
462
463    fn set_open(&self, open: bool) {
464        if self.open.replace(open) == open {
465            return;
466        }
467        if open {
468            self.show();
469        } else {
470            if let Some(p) = self.popover.borrow().as_ref() {
471                p.popdown();
472            }
473            if let Some(w) = self.window.borrow().as_ref() {
474                w.set_visible(false);
475            }
476        }
477    }
478
479    fn show(&self) {
480        if let Some(p) = self.popover.borrow().as_ref() {
481            // Anchored to the element that contains the overlay.
482            if let Some(parent) = self.anchor.parent()
483                && p.parent().as_ref() != Some(&parent)
484            {
485                if p.parent().is_some() {
486                    p.unparent();
487                }
488                p.set_parent(&parent);
489            }
490            if let Some(parent) = p.parent() {
491                place_popover(p, &parent, self.config.get(), self.size.get());
492                p.popup();
493                self.watch_outside(p, &parent);
494            }
495        }
496        if let Some(w) = self.window.borrow().as_ref() {
497            let (cw, ch) = self.size.get();
498            if cw > 0 && ch > 0 {
499                w.set_default_size(cw, ch);
500            }
501            w.present();
502        }
503    }
504
505    /// A popover that leaves the focus to its anchor has no autohide (it
506    /// would take the focus and swallow the press): a press anywhere in the
507    /// anchor's window closes it and goes on to what it landed on (#182).
508    /// Presses in the popover are its own surface's, not the window's.
509    fn watch_outside(&self, p: &gtk::Popover, parent: &gtk::Widget) {
510        let Some(window) = parent.root().and_downcast::<gtk::Window>() else {
511            return;
512        };
513        if self
514            .outside
515            .borrow()
516            .as_ref()
517            .is_some_and(|(w, _)| *w == window)
518        {
519            return;
520        }
521        self.unwatch_outside();
522        let click = gtk::GestureClick::new();
523        click.set_button(0);
524        click.set_propagation_phase(gtk::PropagationPhase::Capture);
525        let p = p.clone();
526        click.connect_pressed(move |_, _, _, _| {
527            // Not claimed: the press goes on to what it landed on.
528            if p.has_css_class(LIGHT_BESIDE_FOCUS) && p.is_visible() {
529                // `connect_closed` tells the app, with `Outside`.
530                p.popdown();
531            }
532        });
533        window.add_controller(click.clone());
534        *self.outside.borrow_mut() = Some((window, click));
535    }
536
537    fn unwatch_outside(&self) {
538        if let Some((w, c)) = self.outside.borrow_mut().take() {
539            w.remove_controller(&c);
540        }
541    }
542
543    /// Shows a popover the app opened before its anchor had a parent
544    /// (inserted open with it, #70): called after each layout.
545    fn show_if_pending(&self) {
546        let pending = self
547            .popover
548            .borrow()
549            .as_ref()
550            .is_some_and(|p| !p.is_visible());
551        if self.open.get() && pending {
552            self.show();
553        }
554    }
555
556    fn set_size(&self, w: i32, h: i32) {
557        if self.size.replace((w, h)) == (w, h) {
558            return;
559        }
560        self.content.set_size_request(w, h);
561        // Its edges line up with the anchor's at its new size.
562        if let Some(p) = self.popover.borrow().as_ref()
563            && let Some(parent) = p.parent()
564        {
565            place_popover(p, &parent, self.config.get(), (w, h));
566        }
567        if let Some(win) = self.window.borrow().as_ref() {
568            win.set_default_size(w, h);
569        }
570    }
571}
572
573// ---------------------------------------------------------------------------
574// Keys (#17): one controller per window, in the capture phase
575// ---------------------------------------------------------------------------
576
577/// Nodes that listen to keys, the keys held down (to flag repeats), and
578/// those whose press was reported: hardware keycode, name and target, for
579/// their release (#159).
580#[derive(Default)]
581pub struct KeyState {
582    local: RefCell<HashSet<NodeId>>,
583    global: RefCell<HashSet<NodeId>>,
584    down: RefCell<HashSet<u32>>,
585    held: RefCell<Vec<(u32, String, Option<NodeId>)>>,
586}
587
588/// A click with its count (GTK's `n_press`, the system's double-click
589/// time and distance) and keys (#159).
590fn click_event(
591    id: NodeId,
592    position: Option<prism_core::Point>,
593    n_press: i32,
594    g: &gtk::GestureClick,
595) -> UiEvent {
596    let count = n_press.max(1) as u32;
597    let modifiers = modifiers(g.current_event_state());
598    match position {
599        _ if count > 1 || modifiers != prism_core::Modifiers::default() => UiEvent::ClickWith(
600            id,
601            prism_core::ClickEvent {
602                position,
603                modifiers,
604                count,
605                button: prism_core::PointerButton::Primary,
606                text_offset: None,
607            },
608        ),
609        Some(p) => UiEvent::ClickAt(id, p),
610        None => UiEvent::Click(id),
611    }
612}
613
614/// Releases every key whose press was reported (the window lost the focus:
615/// GTK sends no release for them, #159).
616fn release_keys(keys: &KeyState) {
617    keys.down.borrow_mut().clear();
618    let held = std::mem::take(&mut *keys.held.borrow_mut());
619    for (_, name, target) in held {
620        dispatch(UiEvent::KeyUp(target, prism_core::KeyEvent::new(name)));
621    }
622}
623
624/// The Prism node a widget belongs to (its `p{id}` class), if any.
625fn node_of(w: &gtk::Widget) -> Option<NodeId> {
626    w.css_classes()
627        .iter()
628        .find_map(|c| c.strip_prefix('p').and_then(|n| n.parse::<NodeId>().ok()))
629}
630
631/// Reports key presses in `window` (`UiEvent::Key`): to the focused node's
632/// nearest ancestor with `on_key_down`, and to global listeners. Typing in
633/// a text field only reaches local listeners.
634fn attach_keys(window: &gtk::Window, keys: Rc<KeyState>) {
635    use gtk::glib::translate::IntoGlib;
636    let controller = gtk::EventControllerKey::new();
637    controller.set_propagation_phase(gtk::PropagationPhase::Capture);
638    let up = keys.clone();
639    controller.connect_key_released(move |_, key, code, mods| {
640        up.down.borrow_mut().remove(&key.into_glib());
641        // A release goes where its press went (#159), by hardware key: Shift
642        // may have changed the key's name meanwhile.
643        let pressed = {
644            let mut held = up.held.borrow_mut();
645            held.iter()
646                .position(|(c, ..)| *c == code)
647                .map(|i| held.remove(i))
648        };
649        if let Some((_, name, target)) = pressed {
650            dispatch(UiEvent::KeyUp(
651                target,
652                prism_core::KeyEvent {
653                    key: name,
654                    modifiers: modifiers(mods),
655                    repeat: false,
656                    selection: None,
657                    edges: None,
658                },
659            ));
660        }
661    });
662    let gone = keys.clone();
663    window.connect_is_active_notify(move |w| {
664        if !w.is_active() {
665            release_keys(&gone);
666        }
667    });
668    controller.connect_key_pressed(move |c, key, code, mods| {
669        if keys.local.borrow().is_empty() && keys.global.borrow().is_empty() {
670            return glib::Propagation::Proceed;
671        }
672        let name = key.name().map(|n| n.to_string()).unwrap_or_default();
673        let Some(name) = crate::input::key_name(&name, key.to_unicode()) else {
674            return glib::Propagation::Proceed;
675        };
676        let repeat = !keys.down.borrow_mut().insert(key.into_glib());
677        let modifiers = modifiers(mods);
678        let focus = c
679            .widget()
680            .and_downcast::<gtk::Window>()
681            .and_then(|w| GtkWindowExt::focus(&w));
682        let editing = focus
683            .as_ref()
684            .is_some_and(|f| f.is::<gtk::Text>() || f.is::<gtk::TextView>());
685        // In a text field: its selection before the key (#86).
686        // And where its caret is (#211).
687        let (selection, edges) = match focus.as_ref() {
688            Some(f) if f.is::<gtk::Text>() => {
689                let t = f.downcast_ref::<gtk::Text>().expect("a text");
690                (Some(editable_selection(t)), Some(editable_edges(t)))
691            }
692            Some(f) if f.is::<gtk::TextView>() => {
693                let v = f.downcast_ref::<gtk::TextView>().expect("a text view");
694                (Some(buffer_selection(&v.buffer())), Some(view_edges(v)))
695            }
696            _ => (None, None),
697        };
698        // The nearest focused node with `on_key_down`.
699        let mut target = None;
700        let mut next = focus.clone();
701        while let Some(w) = next {
702            if let Some(id) = node_of(&w)
703                && keys.local.borrow().contains(&id)
704            {
705                target = Some((id, w.clone()));
706                break;
707            }
708            next = w.parent();
709        }
710        let typing = editing
711            && crate::input::types_text(&name, modifiers.control, modifiers.alt, modifiers.meta);
712        if target.is_none() && (typing || keys.global.borrow().is_empty()) {
713            return glib::Propagation::Proceed;
714        }
715        let claimed = target
716            .as_ref()
717            .is_some_and(|(_, w)| Some(w) == focus.as_ref() && crate::input::claims(&name));
718        let target = target.map(|(id, _)| id);
719        {
720            let mut held = keys.held.borrow_mut();
721            if !held.iter().any(|(c, ..)| *c == code) {
722                held.push((code, name.clone(), target));
723            }
724        }
725        // The app's alone (`consume_keys`, #181): the focused field does not
726        // also act on it. Asked from the focused node, wherever its handler is.
727        let focused_node = {
728            let mut next = focus.clone();
729            let mut found = None;
730            while let Some(w) = next {
731                if let Some(id) = node_of(&w) {
732                    found = Some(id);
733                    break;
734                }
735                next = w.parent();
736            }
737            found
738        };
739        // A selection group's keys too (#231), from the key as dispatched.
740        let key = prism_core::KeyEvent {
741            key: name,
742            modifiers,
743            repeat,
744            selection,
745            edges,
746        };
747        let mut consumed = false;
748        with_state(|s| consumed = s.runtime.consumes_key_event(focused_node, &key));
749        let claimed = claimed || consumed;
750        dispatch(UiEvent::Key(target, key));
751        if claimed {
752            glib::Propagation::Stop
753        } else {
754            glib::Propagation::Proceed
755        }
756    });
757    window.add_controller(controller);
758}
759
760// ---------------------------------------------------------------------------
761// Pointer (#17): moves are coalesced to one dispatch per main-loop turn
762// ---------------------------------------------------------------------------
763
764thread_local! {
765    static COALESCED: RefCell<HashMap<(NodeId, u8), UiEvent>> = RefCell::new(HashMap::new());
766}
767
768/// Dispatches `event`, replacing a not yet delivered one of the same kind
769/// for the same node (pointer and drag moves).
770fn dispatch_latest(id: NodeId, channel: u8, event: UiEvent) {
771    if UPDATING.get() {
772        return;
773    }
774    let first = COALESCED.with(|c| c.borrow_mut().insert((id, channel), event).is_none());
775    if first {
776        glib::idle_add_local_once(move || {
777            if let Some(e) = COALESCED.with(|c| c.borrow_mut().remove(&(id, channel))) {
778                with_state(|s| deliver(s, e));
779            }
780        });
781    }
782}
783
784/// Where a drag's pointer went down, with which button and keys, and
785/// whether it moved past the slop.
786#[derive(Clone, Copy)]
787struct DragStart {
788    at: (f64, f64),
789    button: prism_core::PointerButton,
790    mods: prism_core::Modifiers,
791    started: bool,
792    /// A touch waiting for its long press (#243).
793    holding: bool,
794}
795
796/// GTK's button number as Prism's (touches are the primary button).
797fn drag_button(button: u32) -> prism_core::PointerButton {
798    use prism_core::PointerButton as B;
799    match button {
800        0 | gdk::BUTTON_PRIMARY => B::Primary,
801        gdk::BUTTON_MIDDLE => B::Middle,
802        gdk::BUTTON_SECONDARY => B::Secondary,
803        n => B::Other(n.min(255) as u8),
804    }
805}
806
807/// GDK's modifier state as Prism's.
808pub(crate) fn modifiers(mods: gdk::ModifierType) -> prism_core::Modifiers {
809    prism_core::Modifiers {
810        shift: mods.contains(gdk::ModifierType::SHIFT_MASK),
811        control: mods.contains(gdk::ModifierType::CONTROL_MASK),
812        alt: mods.contains(gdk::ModifierType::ALT_MASK),
813        meta: mods.intersects(gdk::ModifierType::SUPER_MASK | gdk::ModifierType::META_MASK),
814    }
815}
816
817/// A wheel or touchpad scroll of `dx`, `dy` (#133) as Prism's `WheelEvent`:
818/// points, positive `y` toward the end (GTK's sign, after the user's
819/// natural scrolling), at the pointer in the element.
820fn wheel_event(
821    id: NodeId,
822    c: &gtk::EventControllerScroll,
823    dx: f64,
824    dy: f64,
825    phase: prism_core::GesturePhase,
826) -> UiEvent {
827    // A wheel counts notches: 16 points a line, three lines a notch, like
828    // browsers. A touchpad counts surface pixels.
829    let precise = c.unit() == gdk::ScrollUnit::Surface;
830    let k = if precise { 1. } else { 48. };
831    UiEvent::Wheel(
832        id,
833        prism_core::WheelEvent {
834            delta: point(dx * k, dy * k),
835            position: event_point(c),
836            modifiers: modifiers(c.current_event_state()),
837            phase,
838            precise,
839        },
840    )
841}
842
843/// Where the controller's current event is, in its widget.
844fn event_point(c: &impl IsA<gtk::EventController>) -> prism_core::Point {
845    let at = (|| {
846        let w = c.widget()?;
847        let (x, y) = c.current_event()?.position()?;
848        let native = w.native()?;
849        let (nx, ny) = native.surface_transform();
850        let p = native.compute_point(
851            &w,
852            &gtk::graphene::Point::new((x - nx) as f32, (y - ny) as f32),
853        )?;
854        Some(point(p.x() as f64, p.y() as f64))
855    })();
856    at.unwrap_or_default()
857}
858
859fn point(x: f64, y: f64) -> prism_core::Point {
860    prism_core::Point::new(x as f32, y as f32)
861}
862
863// ---------------------------------------------------------------------------
864// Main-thread state
865// ---------------------------------------------------------------------------
866
867struct State {
868    runtime: Runtime,
869    renderer: NativeRenderer<Gtk>,
870    services: crate::services::LinuxServices,
871}
872
873thread_local! {
874    static STATE: RefCell<Option<State>> = const { RefCell::new(None) };
875    /// Set while Prism changes widgets, so their signals are not reported back.
876    static UPDATING: Cell<bool> = const { Cell::new(false) };
877    /// What each text field sent and the app has not rendered back yet (#73).
878    static TYPED: RefCell<HashMap<NodeId, prism_native::fields::Typed>> = RefCell::new(HashMap::new());
879}
880
881// ---------------------------------------------------------------------------
882// Text field selections (#86): GTK counts characters, like Prism
883// ---------------------------------------------------------------------------
884
885thread_local! {
886    /// Fields reporting their selection (`on_select`).
887    static SELECT_EVENTS: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
888    /// The selection last reported, and the one waiting to be, by field.
889    static REPORTED: RefCell<HashMap<NodeId, prism_core::SelectionEvent>> = RefCell::new(HashMap::new());
890    static PENDING_SELECTION: RefCell<HashMap<NodeId, prism_core::SelectionEvent>> = RefCell::new(HashMap::new());
891    /// Entries the app set a selection on: `cx.focus` keeps it (instead of
892    /// selecting everything).
893    static APP_SELECTED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
894}
895
896/// The selection of an editable (an entry, its inner `GtkText`), in characters.
897pub(crate) fn editable_selection(e: &impl IsA<gtk::Editable>) -> prism_core::SelectionEvent {
898    match e.selection_bounds() {
899        Some((a, b)) => prism_core::SelectionEvent::new(a.max(0) as usize, b.max(0) as usize),
900        None => prism_core::SelectionEvent::caret(e.position().max(0) as usize),
901    }
902}
903
904/// Where the caret of a single-line field is (#211).
905fn editable_edges(e: &impl IsA<gtk::Editable>) -> prism_core::CaretEdges {
906    if e.selection_bounds().is_some_and(|(a, b)| a != b) {
907        return prism_core::CaretEdges::default();
908    }
909    let len = e.text().chars().count();
910    prism_core::CaretEdges::caret(e.position().max(0) as usize, len, 0, 1)
911}
912
913/// Where a text view's caret is (#211): its location against those of the
914/// buffer's start and end, so wrapped lines count.
915fn view_edges(v: &gtk::TextView) -> prism_core::CaretEdges {
916    let b = v.buffer();
917    if b.has_selection() {
918        return prism_core::CaretEdges::default();
919    }
920    let caret = b.iter_at_mark(&b.get_insert());
921    let mid = |i: &gtk::TextIter| {
922        let r = v.iter_location(i);
923        (
924            r.y() as f32 + r.height() as f32 / 2.,
925            r.height().max(1) as f32,
926        )
927    };
928    let (at, h) = mid(&caret);
929    let same_line = |i: &gtk::TextIter| (mid(i).0 - at).abs() < h / 2.;
930    prism_core::CaretEdges {
931        start: caret.is_start(),
932        end: caret.is_end(),
933        first_line: same_line(&b.start_iter()),
934        last_line: same_line(&b.end_iter()),
935    }
936}
937
938/// The selection of a text buffer, in characters.
939pub(crate) fn buffer_selection(b: &gtk::TextBuffer) -> prism_core::SelectionEvent {
940    match b.selection_bounds() {
941        Some((s, e)) => {
942            prism_core::SelectionEvent::new(s.offset().max(0) as usize, e.offset().max(0) as usize)
943        }
944        None => prism_core::SelectionEvent::caret(
945            b.iter_at_mark(&b.get_insert()).offset().max(0) as usize
946        ),
947    }
948}
949
950/// Field `id`'s selection may have moved to `sel` (typing, the pointer,
951/// keys): reported once per main-loop turn, after the `Input` of the same
952/// edit (a lower priority than `dispatch`), only when it moved, and never
953/// for Prism's own changes.
954pub(crate) fn report_selection(id: NodeId, sel: prism_core::SelectionEvent) {
955    if UPDATING.get() || !SELECT_EVENTS.with(|s| s.borrow().contains(&id)) {
956        return;
957    }
958    let first = PENDING_SELECTION.with(|p| p.borrow_mut().insert(id, sel).is_none());
959    if !first {
960        return;
961    }
962    glib::idle_add_local_full(glib::Priority::LOW, move || {
963        let sel = PENDING_SELECTION.with(|p| p.borrow_mut().remove(&id));
964        if let Some(sel) = sel
965            && SELECT_EVENTS.with(|s| s.borrow().contains(&id))
966            && REPORTED.with(|r| r.borrow_mut().insert(id, sel)) != Some(sel)
967        {
968            with_state(|s| {
969                let patches = s.runtime.dispatch(UiEvent::Select(id, sel.start, sel.end));
970                commit(s, patches);
971            });
972        }
973        glib::ControlFlow::Break
974    });
975}
976
977fn forget_selection(id: NodeId) {
978    APP_SELECTED.with(|s| s.borrow_mut().remove(&id));
979    SELECT_EVENTS.with(|s| s.borrow_mut().remove(&id));
980    REPORTED.with(|r| r.borrow_mut().remove(&id));
981    PENDING_SELECTION.with(|p| p.borrow_mut().remove(&id));
982}
983
984/// The user typed `text` in field `id`: remembered until the app renders it
985/// back (events run on a later turn, the user may type further meanwhile),
986/// then dispatched.
987pub(crate) fn dispatch_typed(id: NodeId, text: String) {
988    if UPDATING.get() {
989        return;
990    }
991    TYPED.with(|t| t.borrow_mut().entry(id).or_default().sent(&text));
992    dispatch(UiEvent::Input(id, text));
993}
994
995/// Whether the app's `text` for field `id`, showing `current`, is written
996/// into it: not an echo of the user's typing, and different (#73).
997fn field_takes(id: NodeId, text: &str, current: &str) -> bool {
998    TYPED.with(|t| {
999        t.borrow_mut()
1000            .entry(id)
1001            .or_default()
1002            .should_apply(text, current)
1003    })
1004}
1005
1006/// The selection group text field `id` is in (#231).
1007pub(crate) fn selection_group_of(id: NodeId) -> Option<NodeId> {
1008    let mut out = None;
1009    with_state(|s| out = s.runtime.selection_group(id));
1010    out
1011}
1012
1013/// The field of the selection group of field `id` under `p` (in `root`'s
1014/// coordinates) and the character there (#231).
1015pub(crate) fn group_field_at(
1016    id: NodeId,
1017    root: &gtk::Widget,
1018    p: &gtk::graphene::Point,
1019) -> Option<(NodeId, usize)> {
1020    let mut out = None;
1021    with_state(|s| {
1022        let Some(group) = s.runtime.selection_group(id) else {
1023            return;
1024        };
1025        for f in s.runtime.selection_group_fields(group) {
1026            let (frame, hit): (gtk::Widget, _) = match s.renderer.view(f) {
1027                Some(View::TextArea(_, t)) => (t.root.clone().upcast(), Some(t.view.clone())),
1028                Some(View::Input(_, e)) => (e.clone().upcast(), None),
1029                _ => continue,
1030            };
1031            let inside = frame.is_mapped()
1032                && frame
1033                    .compute_bounds(root)
1034                    .is_some_and(|b| b.contains_point(p));
1035            if !inside {
1036                continue;
1037            }
1038            let Some(local) = root.compute_point(&frame, p) else {
1039                continue;
1040            };
1041            out = Some(match (hit, s.renderer.view(f)) {
1042                (Some(view), _) => {
1043                    let l = root.compute_point(&view, p).unwrap_or(local);
1044                    (
1045                        f,
1046                        crate::across::offset_in_view(&view, l.x() as f64, l.y() as f64),
1047                    )
1048                }
1049                (None, Some(View::Input(_, e))) => {
1050                    (f, crate::across::offset_in_entry(e, local.x() as f64))
1051                }
1052                _ => continue,
1053            });
1054            break;
1055        }
1056    });
1057    out
1058}
1059
1060fn with_state(f: impl FnOnce(&mut State)) {
1061    STATE.with(|cell| {
1062        if let Ok(mut guard) = cell.try_borrow_mut()
1063            && let Some(state) = guard.as_mut()
1064        {
1065            f(state)
1066        }
1067    });
1068}
1069
1070/// A UI event from GTK, handled on the next turn (GTK may be mid-update).
1071pub(crate) fn dispatch(event: UiEvent) {
1072    if UPDATING.get() {
1073        return;
1074    }
1075    glib::idle_add_local_once(move || with_state(|s| deliver(s, event)));
1076}
1077
1078/// Dispatches `event` now; a draggable's drag goes with the drop target
1079/// under the pointer (#251).
1080fn deliver(s: &mut State, event: UiEvent) {
1081    let (event, restyled) = s.renderer.locate_drag(event);
1082    if restyled {
1083        s.renderer.widgets.flush_css();
1084        relayout(s);
1085    }
1086    let patches = s.runtime.dispatch(event);
1087    commit(s, patches);
1088    if s.renderer.autoscroll_due() {
1089        schedule_autoscroll();
1090    }
1091}
1092
1093thread_local! {
1094    /// An autoscroll step is scheduled (#251).
1095    static AUTOSCROLL: Cell<bool> = const { Cell::new(false) };
1096}
1097
1098/// While a dragged payload stays near a scroll view's edge (#251): a step
1099/// every frame, the drag reported again over what moved under it.
1100fn schedule_autoscroll() {
1101    if AUTOSCROLL.replace(true) {
1102        return;
1103    }
1104    glib::timeout_add_local_once(prism_native::dnd::AUTOSCROLL_INTERVAL, || {
1105        AUTOSCROLL.set(false);
1106        with_state(|s| {
1107            if let Some((event, restyled)) = s.renderer.autoscroll() {
1108                if restyled {
1109                    s.renderer.widgets.flush_css();
1110                    relayout(s);
1111                }
1112                deliver(s, event);
1113            }
1114        });
1115    });
1116}
1117
1118fn commit(s: &mut State, patches: Vec<prism_core::Patch>) {
1119    UPDATING.set(true);
1120    if !patches.is_empty() {
1121        s.renderer.apply(&patches);
1122    }
1123    s.renderer.widgets.flush_css();
1124    relayout(s);
1125    UPDATING.set(false);
1126    for request in s.runtime.take_requests() {
1127        if let prism_core::PlatformRequest::LoadFont(face) = request {
1128            load_font(s, face);
1129            continue;
1130        }
1131        // `cx.set_title` (#154): the window's title, else the app's name.
1132        // Unsaved changes (#158): closing the window asks first.
1133        if let prism_core::PlatformRequest::SetUnsavedChanges(on) = &request {
1134            UNSAVED.set(*on);
1135        }
1136        if let prism_core::PlatformRequest::SetTitle(title) = &request {
1137            let w = &s.renderer.widgets;
1138            w.window
1139                .set_title(Some(title.as_deref().unwrap_or(&w.app_title)));
1140        }
1141        prism_core::PlatformServices::handle(&mut s.services, request);
1142    }
1143    if let Some(at) = s.runtime.next_timer() {
1144        let delay = at.saturating_duration_since(std::time::Instant::now());
1145        glib::timeout_add_local_once(delay, poll);
1146    }
1147}
1148
1149/// A video player (#207): reports the end of the playback, and lays out
1150/// again once the stream knows its size.
1151fn video_widget(id: NodeId) -> gtk::Video {
1152    let v = gtk::Video::new();
1153    v.set_autoplay(false);
1154    v.connect_media_stream_notify(move |v| {
1155        let Some(stream) = v.media_stream() else {
1156            return;
1157        };
1158        // SAFETY: set by `set_config` as a bool.
1159        let muted = unsafe { v.data::<bool>("prism-muted").map(|m| *m.as_ref()) };
1160        stream.set_muted(muted.unwrap_or(false));
1161        let looping = v.is_loop();
1162        stream.connect_ended_notify(move |s| {
1163            if s.is_ended() && !looping {
1164                dispatch(UiEvent::Ended(id));
1165            }
1166        });
1167        stream.connect_invalidate_size(|_| {
1168            glib::idle_add_local_once(|| {
1169                with_state(|s| {
1170                    s.renderer.mark_all_dirty();
1171                    relayout(s);
1172                })
1173            });
1174        });
1175    });
1176    v
1177}
1178
1179/// Registers a run-time font (`cx.load_font`) with fontconfig (from a file in
1180/// the user's cache) and draws the texts again. A URL comes back here
1181/// with its bytes once loaded.
1182fn load_font(s: &mut State, face: prism_core::FontFace) {
1183    let w = &s.renderer.widgets;
1184    let sources = prism_native::images::ImageSources {
1185        embedded: w.embedded.clone(),
1186        asset_dirs: w.assets.iter().cloned().collect(),
1187        ..Default::default()
1188    };
1189    let Some(font) = prism_native::fonts::prepare(&mut s.runtime.app, face, &sources) else {
1190        return;
1191    };
1192    // Next to the embedded fonts (fontconfig only reads files).
1193    let dir = glib::user_cache_dir().join("prism-fonts").join("runtime");
1194    if let Some(path) = prism_native::fonts::save(&font, &dir)
1195        && text::add_runtime_font(&path)
1196    {
1197        s.renderer.restyle_all();
1198        s.renderer.widgets.flush_css();
1199        relayout(s);
1200    }
1201}
1202
1203fn relayout(s: &mut State) {
1204    // GTK before 4.12: names from content, no type names (`names.rs`).
1205    crate::names::schedule();
1206    let (w, h) = s.renderer.widgets.size;
1207    if w <= 0. {
1208        return;
1209    }
1210    if (w, h) != s.runtime.app.viewport() {
1211        let patches = s.runtime.set_viewport(w, h);
1212        if !patches.is_empty() {
1213            s.renderer.apply(&patches);
1214            s.renderer.widgets.flush_css();
1215        }
1216    }
1217    let insets = s.renderer.widgets.chrome_insets();
1218    s.renderer.layout(w, h, insets);
1219    // Elements that report their frame and moved (#192).
1220    let more = prism_native::report_layout(&mut s.runtime, &mut s.renderer);
1221    if !more.is_empty() {
1222        commit(s, more);
1223    }
1224}
1225
1226pub(crate) fn device_reply(
1227    id: u64,
1228    result: Result<prism_core::DeviceValue, prism_core::DeviceError>,
1229) {
1230    with_state(|s| {
1231        let patches = s.runtime.device_reply(id, result);
1232        commit(s, patches);
1233    });
1234}
1235
1236pub(crate) fn push_registered(
1237    result: Result<prism_core::PushSubscription, prism_core::DeviceError>,
1238) {
1239    with_state(|s| {
1240        let patches = s.runtime.push_registered(result);
1241        commit(s, patches);
1242    });
1243}
1244
1245/// A UnifiedPush message: shown as a notification unless the window is
1246/// active; silent ones run `on_background_push`.
1247pub(crate) fn push_received(message: prism_core::PushMessage) {
1248    with_state(|s| {
1249        let patches = if message.event == prism_core::PushEvent::Background {
1250            s.runtime.run_background_push(message);
1251            s.runtime.poll()
1252        } else {
1253            s.runtime.push_received(message, true)
1254        };
1255        commit(s, patches);
1256    });
1257}
1258
1259pub(crate) fn device_event(id: u64, event: prism_core::DeviceEvent) {
1260    with_state(|s| {
1261        let patches = s.runtime.device_event(id, event);
1262        commit(s, patches);
1263    });
1264}
1265
1266/// `PRISM_BACKGROUND_INTERVAL=<seconds>` shortens background intervals (development).
1267pub(crate) fn background_interval(every: std::time::Duration) -> std::time::Duration {
1268    std::env::var("PRISM_BACKGROUND_INTERVAL")
1269        .ok()
1270        .and_then(|s| s.parse::<f64>().ok())
1271        .map_or(every, std::time::Duration::from_secs_f64)
1272}
1273
1274fn poll() {
1275    with_state(|s| {
1276        let patches = s.runtime.poll();
1277        commit(s, patches);
1278    });
1279}
1280
1281// ---------------------------------------------------------------------------
1282// Widgets
1283// ---------------------------------------------------------------------------
1284
1285pub struct Gtk {
1286    root: gtk::Box,
1287    window: gtk::ApplicationWindow,
1288    /// The window's own title (the app's name), for `cx.clear_title`.
1289    app_title: String,
1290    app: gtk::Application,
1291    /// Context menus by node (right-click / press and hold).
1292    menus: Rc<RefCell<HashMap<NodeId, gtk::PopoverMenu>>>,
1293    swipes: Rc<RefCell<HashMap<NodeId, (bool, bool)>>>,
1294    scroll_events: Rc<RefCell<HashSet<NodeId>>>,
1295    /// Refreshable scroll views (F5 / Ctrl+R).
1296    refreshable: Rc<RefCell<HashMap<NodeId, gtk::ScrolledWindow>>>,
1297    /// Each node's size from the last layout (GTK's own lags behind).
1298    sizes: HashMap<NodeId, (f32, f32)>,
1299    css: gtk::CssProvider,
1300    /// The nodes' CSS rules, one per distinct style (`sheet.rs`), loaded
1301    /// again only when a new one appears.
1302    sheet: crate::sheet::Sheet,
1303    css_dirty: bool,
1304    clickable: Rc<RefCell<HashSet<NodeId>>>,
1305    timers: HashMap<NodeId, (gtk::Label, f64)>,
1306    /// What each countdown shows once ended (`timer(..).after`, #281).
1307    timer_after: HashMap<NodeId, String>,
1308    assets: Option<std::path::PathBuf>,
1309    /// Assets compiled into the binary, found before the directory's.
1310    embedded: prism_core::EmbeddedAssets,
1311    dark: bool,
1312    /// Titles of screens and tabs, icons of tabs.
1313    titles: HashMap<NodeId, String>,
1314    icons: HashMap<NodeId, String>,
1315    stacks: Vec<Rc<NavStack>>,
1316    tab_bars: Vec<Rc<TabBar>>,
1317    /// Shapes, redrawn when the appearance changes.
1318    shapes: HashMap<NodeId, gtk::DrawingArea>,
1319    /// 3D scenes, redrawn when the appearance changes.
1320    scenes: HashMap<NodeId, gtk::GLArea>,
1321    /// Window content size.
1322    size: (f32, f32),
1323    /// Right-to-left layout and the app's locale (form controls follow them).
1324    rtl: bool,
1325    locale: prism_core::Locale,
1326    /// Form controls, mirrored in right-to-left.
1327    controls: HashMap<NodeId, gtk::Widget>,
1328    date_pickers: HashMap<NodeId, Rc<controls::DatePicker>>,
1329    /// "Clear" in the app's language (optional date pickers, #89).
1330    clear_label: String,
1331    /// Status regions and what they last announced.
1332    statuses: HashMap<NodeId, String>,
1333    /// Text labels: their text, runs and style (rebuilt when one changes).
1334    labels: HashMap<NodeId, text::LabelState>,
1335    // --- Hidden header (#8) ---
1336    /// Screens that hide their stack's header while on top (`.bare()`).
1337    bare: HashSet<NodeId>,
1338    /// Sticky views of each scroll view, moved as it scrolls.
1339    stickies: Stickies,
1340    /// Interaction states each widget reports to prism-native (refinements
1341    /// CSS cannot draw, groups, the focus of text fields), and the widgets
1342    /// that have the controllers reporting them.
1343    reports: Rc<RefCell<HashMap<NodeId, prism_core::Interactions>>>,
1344    watched: HashSet<NodeId>,
1345    /// Cursors set by `Style::cursor` (they win over the clickable default).
1346    cursors: HashMap<NodeId, prism_core::Cursor>,
1347    // Pointer, keys, layers, overlays (#17, #19, #25).
1348    /// Pointer events each node reports (`pointer_mask` bits).
1349    pointer: Rc<RefCell<HashMap<NodeId, u8>>>,
1350    /// Nodes whose motion / drag controllers are attached.
1351    pointer_attached: HashSet<(NodeId, u8)>,
1352    /// Touch holds before each node's drag, in ms (#243).
1353    drag_delays: Rc<RefCell<HashMap<NodeId, u32>>>,
1354    /// Drop targets' controllers (#111).
1355    drop_targets: HashMap<NodeId, gtk::DropTarget>,
1356    keys: Rc<KeyState>,
1357    /// Runtime layers, above the root in the window.
1358    layers: Vec<gtk::Widget>,
1359    /// Nodes made inert (hidden from assistive technologies).
1360    inert: HashSet<NodeId>,
1361    /// Nodes the app hid from assistive technologies (`accessibility_hidden`).
1362    a11y_hidden: HashSet<NodeId>,
1363    /// Containers with an interactive role (a drawn button, link, tab,
1364    /// checkbox, radio or switch): they take the keyboard focus, as on the
1365    /// web (`tabindex="0"`).
1366    pressable: HashSet<NodeId>,
1367    // --- Adaptive colors (#36) ---
1368    /// Styles with an adaptive color: their CSS rule picks the light or the
1369    /// dark variant, so it is rebuilt when the appearance changes.
1370    adaptive: HashMap<NodeId, (View, Style)>,
1371    /// The snapshot following a dragged payload (#251).
1372    drag_preview: Option<gtk::Picture>,
1373}
1374
1375/// Scroll view → its sticky views (node, widget, range).
1376type Stickies = Rc<RefCell<HashMap<NodeId, HashMap<NodeId, (gtk::Widget, prism_native::Sticky)>>>>;
1377
1378/// Pushes the sticky views of a scroll view scrolled to `value`.
1379fn place_sticky(stickies: &Stickies, scroll: NodeId, value: f64) {
1380    if let Some(views) = stickies.borrow().get(&scroll) {
1381        for (w, st) in views.values() {
1382            layout::set_sticky_offset(w, Some(st.offset(value as f32)));
1383        }
1384    }
1385}
1386
1387fn css_color(c: Color, dark: bool) -> String {
1388    crate::decor::color(c, dark)
1389}
1390
1391fn rect(x: f32, y: f32, w: f32, h: f32) -> (i32, i32, i32, i32) {
1392    (
1393        x.round() as i32,
1394        y.round() as i32,
1395        w.round().max(0.) as i32,
1396        h.round().max(0.) as i32,
1397    )
1398}
1399
1400impl Gtk {
1401    /// What the window's own chrome covers: a root tab bar at the bottom.
1402    /// Roots that are stacks or tab bars lay their bars out themselves, so
1403    /// only the layers (toasts) keep clear of it.
1404    fn chrome_insets(&self) -> Insets {
1405        let root = self.root.first_child();
1406        let tabs = self
1407            .tab_bars
1408            .iter()
1409            .any(|t| root.as_ref() == Some(t.root.upcast_ref::<gtk::Widget>()));
1410        Insets {
1411            bottom: if tabs { TAB_BAR } else { 0. },
1412            ..Insets::default()
1413        }
1414    }
1415
1416    /// Puts the layers back on top of the root's children.
1417    fn raise_layers(&self) {
1418        for l in &self.layers {
1419            if l.parent().is_some() {
1420                l.unparent();
1421            }
1422            l.set_parent(&self.root);
1423        }
1424    }
1425
1426    fn flush_css(&mut self) {
1427        if !self.css_dirty {
1428            return;
1429        }
1430        self.css_dirty = false;
1431        #[allow(deprecated)]
1432        self.css.load_from_data(&self.sheet.css());
1433    }
1434
1435    /// Whether `stack` shows no header bar: none at all, or a bare screen on top.
1436    fn header_hidden(&self, stack: &NavStack) -> bool {
1437        stack.no_header.get()
1438            || stack
1439                .screens
1440                .borrow()
1441                .last()
1442                .is_some_and(|top| self.bare.contains(&top.id()))
1443    }
1444
1445    fn header_back(&self, stack: &Rc<NavStack>) {
1446        stack.header.set_visible(!self.header_hidden(stack));
1447        let depth = stack.screens.borrow().len();
1448        let closable = stack.in_sheet.get() && depth <= 1;
1449        stack.back.set_visible(depth > 1 || closable);
1450        stack
1451            .back
1452            .set_label(if closable { "Close" } else { "‹ Back" });
1453        // Only the top screen shows; its title is the header's.
1454        for (i, s) in stack.screens.borrow().iter().enumerate() {
1455            s.widget().set_visible(i + 1 == depth);
1456        }
1457        let title = stack
1458            .screens
1459            .borrow()
1460            .last()
1461            .and_then(|s| self.titles.get(&s.id()).cloned())
1462            .unwrap_or_default();
1463        stack.title.set_text(&title);
1464        // The top screen's bar buttons (#30).
1465        let top = stack.screens.borrow().last().map(View::id);
1466        crate::navbar::refresh(&stack.header, &stack.back, &stack.title, top);
1467    }
1468
1469    fn refresh_tabs(&self, tabs: &Rc<TabBar>) {
1470        while let Some(c) = tabs.bar.first_child() {
1471            tabs.bar.remove(&c);
1472        }
1473        let selected = tabs.selected.get();
1474        for (i, tab) in tabs.tabs.borrow().iter().enumerate() {
1475            tab.widget().set_visible(i == selected);
1476            let title = self.titles.get(&tab.id()).cloned().unwrap_or_default();
1477            let spoken = title.clone();
1478            let label = match self.icons.get(&tab.id()) {
1479                Some(icon) => format!("{}  {title}", prism_core::glyphs::glyph(icon)),
1480                None => title,
1481            };
1482            let text = gtk::Label::new(Some(&label));
1483            text.set_ellipsize(gtk::pango::EllipsizeMode::End);
1484            let button = gtk::ToggleButton::new();
1485            // A tab of the tab list, named by its title (not the icon's
1486            // glyph, nor "GtkToggleButton" on GTK 4.8), selected or not.
1487            button.set_property("accessible-role", gtk::AccessibleRole::Tab);
1488            button.set_child(Some(&text));
1489            button.set_tooltip_text(Some(&label));
1490            button.set_active(i == selected);
1491            button.set_hexpand(true);
1492            set_accessible_string(&button, a11y_property::LABEL, &spoken);
1493            // The tooltip repeats the name; the selection is the state.
1494            reset_accessible_property(&button, a11y_property::DESCRIPTION);
1495            reset_accessible_state(&button, a11y_state::PRESSED);
1496            set_accessible_selected(&button, i == selected);
1497            // The panel is named by its tab, unless the app named it.
1498            let panel = tab.widget();
1499            if !crate::names::has_label(&panel) {
1500                crate::table::set_relation(
1501                    &panel,
1502                    crate::table::LABELLED_BY,
1503                    Some(button.upcast_ref()),
1504                );
1505            }
1506            let id = tabs_id(tabs);
1507            button.connect_clicked(move |_| dispatch(UiEvent::Change(id, i as f64)));
1508            tabs.bar.append(&button);
1509        }
1510    }
1511}
1512
1513impl Gtk {
1514    /// Right-click and press-and-hold open the node's context menu; a
1515    /// horizontal swipe (touchpad, touch screen) reports `Swipe`.
1516    fn attach_gestures(&self, id: NodeId, w: &gtk::Widget) {
1517        let menus = self.menus.clone();
1518        let open = move |x: f64, y: f64| {
1519            if let Some(p) = menus.borrow().get(&id) {
1520                p.set_pointing_to(Some(&gdk::Rectangle::new(x as i32, y as i32, 1, 1)));
1521                p.popup();
1522                return true;
1523            }
1524            false
1525        };
1526        let right = gtk::GestureClick::new();
1527        right.set_button(gdk::BUTTON_SECONDARY);
1528        // An element dragged with the secondary button (#136) opens its menu
1529        // on a release that did not move (a drag claims the press first).
1530        let masks = self.pointer.clone();
1531        let drags_secondary = move || {
1532            masks
1533                .borrow()
1534                .get(&id)
1535                .is_some_and(|m| m & prism_core::events::pointer_mask::DRAG_SECONDARY != 0)
1536        };
1537        let (open_right, drags) = (open.clone(), drags_secondary.clone());
1538        right.connect_pressed(move |g, _, x, y| {
1539            if !drags() && open_right(x, y) {
1540                g.set_state(gtk::EventSequenceState::Claimed);
1541            }
1542        });
1543        let open_right = open.clone();
1544        right.connect_released(move |g, _, x, y| {
1545            if drags_secondary() && open_right(x, y) {
1546                g.set_state(gtk::EventSequenceState::Claimed);
1547            }
1548        });
1549        w.add_controller(right);
1550        let hold = gtk::GestureLongPress::new();
1551        hold.connect_pressed(move |g, x, y| {
1552            if open(x, y) {
1553                g.set_state(gtk::EventSequenceState::Claimed);
1554            }
1555        });
1556        w.add_controller(hold);
1557        let swipes = self.swipes.clone();
1558        let swipe = gtk::GestureSwipe::new();
1559        swipe.connect_swipe(move |_, vx, vy| {
1560            let (left, right) = swipes.borrow().get(&id).copied().unwrap_or_default();
1561            if vx.abs() < 300. || vx.abs() < vy.abs() * 2. {
1562                return;
1563            }
1564            if vx < 0. && left {
1565                dispatch(UiEvent::Swipe(id, prism_core::SwipeDirection::Left));
1566            } else if vx > 0. && right {
1567                dispatch(UiEvent::Swipe(id, prism_core::SwipeDirection::Right));
1568            }
1569        });
1570        w.add_controller(swipe);
1571    }
1572}
1573
1574// Interaction states prism-native resolves (refinements CSS cannot draw:
1575// sizes, visibility, opacity, transforms; group states; focus-within).
1576impl Gtk {
1577    /// Decides which states `id` reports to prism-native and adds the event
1578    /// controllers reporting them (once): pointer motion (hover), raw
1579    /// presses (also setting GTK's `:active`, which plain boxes don't get),
1580    /// and keyboard focus.
1581    fn watch_states(&mut self, id: NodeId, w: &gtk::Widget, s: &Style, text_field: bool) {
1582        use prism_core::Interaction as I;
1583        let used = s.states.used();
1584        let mut report = prism_core::Interactions::NONE;
1585        if crate::decor::needs_engine(s) {
1586            for i in [I::Hover, I::Active, I::Focus] {
1587                report = report.with(i, used.contains(i));
1588            }
1589        }
1590        if s.is_group() {
1591            report = report.with(I::Hover, true).with(I::Active, true);
1592        }
1593        // Text fields always report their focus: ancestors' focus-within
1594        // and group refinements follow it.
1595        if text_field {
1596            report = report.with(I::Focus, true);
1597        }
1598        // GTK only sets `:active` on widgets that handle presses themselves.
1599        let pressable = used.contains(I::Active) || s.is_group();
1600        if report.is_empty() && !pressable {
1601            self.reports.borrow_mut().remove(&id);
1602            return;
1603        }
1604        self.reports.borrow_mut().insert(id, report);
1605        if !self.watched.insert(id) {
1606            return;
1607        }
1608        let reports = self.reports.clone();
1609        let reports_on = move |i: I| reports.borrow().get(&id).is_some_and(|r| r.contains(i));
1610        let motion = gtk::EventControllerMotion::new();
1611        let on = reports_on.clone();
1612        motion.connect_enter(move |_, _, _| {
1613            if on(I::Hover) {
1614                report_state(id, I::Hover, true)
1615            }
1616        });
1617        let on = reports_on.clone();
1618        motion.connect_leave(move |_| {
1619            if on(I::Hover) {
1620                report_state(id, I::Hover, false)
1621            }
1622        });
1623        w.add_controller(motion);
1624        // Raw presses and releases, seen before children (buttons still get
1625        // them): a click gesture would stop tracking at the double-click
1626        // timeout while the button is still down.
1627        let press = gtk::EventControllerLegacy::new();
1628        press.set_propagation_phase(gtk::PropagationPhase::Capture);
1629        let on = reports_on.clone();
1630        press.connect_event(move |c, event| {
1631            let down = match event.event_type() {
1632                gdk::EventType::ButtonPress | gdk::EventType::TouchBegin => true,
1633                gdk::EventType::ButtonRelease
1634                | gdk::EventType::TouchEnd
1635                | gdk::EventType::TouchCancel => false,
1636                _ => return glib::Propagation::Proceed,
1637            };
1638            if let Some(w) = c.widget() {
1639                if down {
1640                    w.set_state_flags(gtk::StateFlags::ACTIVE, false);
1641                } else {
1642                    w.unset_state_flags(gtk::StateFlags::ACTIVE);
1643                }
1644            }
1645            if on(I::Active) {
1646                report_state(id, I::Active, down)
1647            }
1648            glib::Propagation::Proceed
1649        });
1650        w.add_controller(press);
1651        let focus = gtk::EventControllerFocus::new();
1652        let on = reports_on.clone();
1653        focus.connect_enter(move |_| {
1654            if on(I::Focus) {
1655                report_state(id, I::Focus, true)
1656            }
1657        });
1658        focus.connect_leave(move |_| {
1659            if reports_on(I::Focus) {
1660                report_state(id, I::Focus, false)
1661            }
1662        });
1663        w.add_controller(focus);
1664    }
1665}
1666
1667thread_local! {
1668    /// The app has unsaved changes (`cx.set_unsaved_changes`, #158).
1669    static UNSAVED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1670}
1671
1672/// « Leave without saving? » over `window` (#158): discarding closes it.
1673fn confirm_leave(window: &gtk::ApplicationWindow) {
1674    let mut texts = None;
1675    with_state(|s| {
1676        texts = Some(
1677            ["unsaved_title", "unsaved_message", "discard", "cancel"]
1678                .map(|k| s.runtime.app.chrome_text(k)),
1679        )
1680    });
1681    let [title, message, discard, cancel] = texts.unwrap_or_else(|| {
1682        [
1683            "Leave without saving?",
1684            "Your changes will be lost.",
1685            "Discard Changes",
1686            "Cancel",
1687        ]
1688        .map(String::from)
1689    });
1690    let dialog = gtk::Window::builder()
1691        .transient_for(window)
1692        .modal(true)
1693        .resizable(false)
1694        .default_width(360)
1695        .accessible_role(gtk::AccessibleRole::AlertDialog)
1696        .build();
1697    let body = gtk::Box::new(gtk::Orientation::Vertical, 12);
1698    body.set_margin_top(20);
1699    body.set_margin_bottom(20);
1700    body.set_margin_start(20);
1701    body.set_margin_end(20);
1702    let heading = gtk::Label::new(Some(&title));
1703    heading.add_css_class("title-3");
1704    heading.set_wrap(true);
1705    body.append(&heading);
1706    let text = gtk::Label::new(Some(&message));
1707    text.set_wrap(true);
1708    body.append(&text);
1709    let buttons = gtk::Box::new(gtk::Orientation::Horizontal, 8);
1710    buttons.set_halign(gtk::Align::End);
1711    let keep = gtk::Button::with_label(&cancel);
1712    let leave = gtk::Button::with_label(&discard);
1713    leave.add_css_class("destructive-action");
1714    let d = dialog.clone();
1715    keep.connect_clicked(move |_| d.close());
1716    let (d, w) = (dialog.clone(), window.clone());
1717    leave.connect_clicked(move |_| {
1718        UNSAVED.set(false);
1719        d.close();
1720        w.close();
1721    });
1722    buttons.append(&keep);
1723    buttons.append(&leave);
1724    body.append(&buttons);
1725    dialog.set_child(Some(&body));
1726    dialog.set_default_widget(Some(&keep));
1727    dialog.present();
1728}
1729
1730thread_local! {
1731    /// When Escape was last pressed in a popover (#156).
1732    static ESCAPE_AT: std::cell::Cell<Option<std::time::Instant>> =
1733        const { std::cell::Cell::new(None) };
1734}
1735
1736/// A widget entered or left an interaction state: prism-native restyles it
1737/// (and its group's descendants, its ancestors for focus-within), then the
1738/// window is laid out again. On the next turn: GTK may be mid-update.
1739fn report_state(id: NodeId, state: prism_core::Interaction, on: bool) {
1740    glib::idle_add_local_once(move || {
1741        with_state(|s| {
1742            if s.renderer.set_interaction(id, state, on) {
1743                UPDATING.set(true);
1744                s.renderer.widgets.flush_css();
1745                relayout(s);
1746                UPDATING.set(false);
1747            }
1748            // The app hears focus changes (#224).
1749            for e in s.renderer.take_focus_changes() {
1750                let patches = s.runtime.dispatch(e);
1751                commit(s, patches);
1752            }
1753        })
1754    });
1755}
1756
1757fn tabs_id(tabs: &Rc<TabBar>) -> NodeId {
1758    tabs.root
1759        .widget_name()
1760        .trim_start_matches('n')
1761        .parse()
1762        .unwrap_or(0)
1763}
1764
1765impl Widgets for Gtk {
1766    type View = View;
1767
1768    fn create(&mut self, id: NodeId, kind: NodeKind) -> View {
1769        let view = match kind {
1770            NodeKind::View
1771            | NodeKind::Screen
1772            | NodeKind::Tab
1773            | NodeKind::Table
1774            | NodeKind::TableRow
1775            | NodeKind::ColumnHeader
1776            | NodeKind::TableCell => {
1777                let c = layout::container();
1778                // Tables (#284): their roles, see `table.rs`.
1779                if let Some(role) = crate::table::role(kind) {
1780                    c.set_property("accessible-role", role);
1781                }
1782                let gesture = gtk::GestureClick::new();
1783                let clickable = self.clickable.clone();
1784                gesture.connect_released(move |g, n, x, y| {
1785                    if clickable.borrow().contains(&id) {
1786                        g.set_state(gtk::EventSequenceState::Claimed);
1787                        dispatch(click_event(id, Some(point(x, y)), n, g));
1788                    }
1789                });
1790                c.add_controller(gesture);
1791                // A drawn button (focusable, see `set_accessibility`): Enter
1792                // or Space when it has the focus itself, as on the web.
1793                let keys = gtk::EventControllerKey::new();
1794                let clickable = self.clickable.clone();
1795                keys.connect_key_pressed(move |k, key, _, _| {
1796                    let focused = k.widget().is_some_and(|w| w.has_focus());
1797                    let activate =
1798                        matches!(key, gdk::Key::Return | gdk::Key::KP_Enter | gdk::Key::space);
1799                    if activate && focused && clickable.borrow().contains(&id) {
1800                        dispatch(UiEvent::Click(id));
1801                        glib::Propagation::Stop
1802                    } else {
1803                        glib::Propagation::Proceed
1804                    }
1805                });
1806                c.add_controller(keys);
1807                View::Container(id, kind, c)
1808            }
1809            NodeKind::Text => {
1810                let l = gtk::Label::new(None);
1811                l.set_wrap(true);
1812                l.set_wrap_mode(gtk::pango::WrapMode::WordChar);
1813                l.set_xalign(0.);
1814                l.set_yalign(0.);
1815                // Inline links (rich text): reported like menu items.
1816                l.connect_activate_link(|_, uri| match text::link_id(uri) {
1817                    Some(item) => {
1818                        dispatch(UiEvent::MenuSelect(item));
1819                        glib::Propagation::Stop
1820                    }
1821                    None => glib::Propagation::Proceed,
1822                });
1823                // A clickable text: click, or Enter / Space when focused
1824                // (not on one of its links, which handle themselves).
1825                let gesture = gtk::GestureClick::new();
1826                let clickable = self.clickable.clone();
1827                gesture.connect_released(move |g, n, _, _| {
1828                    let on_link = g
1829                        .widget()
1830                        .and_then(|w| w.downcast::<gtk::Label>().ok())
1831                        .is_some_and(|l| l.current_uri().is_some());
1832                    if clickable.borrow().contains(&id) && !on_link {
1833                        dispatch(click_event(id, None, n, g));
1834                    }
1835                });
1836                l.add_controller(gesture);
1837                let keys = gtk::EventControllerKey::new();
1838                let clickable = self.clickable.clone();
1839                keys.connect_key_pressed(move |k, key, _, _| {
1840                    let on_link = k
1841                        .widget()
1842                        .and_then(|w| w.downcast::<gtk::Label>().ok())
1843                        .is_some_and(|l| l.current_uri().is_some());
1844                    let activate =
1845                        matches!(key, gdk::Key::Return | gdk::Key::KP_Enter | gdk::Key::space);
1846                    if activate && !on_link && clickable.borrow().contains(&id) {
1847                        dispatch(UiEvent::Click(id));
1848                        glib::Propagation::Stop
1849                    } else {
1850                        glib::Propagation::Proceed
1851                    }
1852                });
1853                l.add_controller(keys);
1854                View::Text(id, l)
1855            }
1856            NodeKind::Button => {
1857                let b = gtk::Button::new();
1858                b.set_cursor_from_name(Some("pointer"));
1859                b.connect_clicked(move |_| dispatch(UiEvent::Click(id)));
1860                View::Button(id, b)
1861            }
1862            NodeKind::TextInput => {
1863                let e = gtk::Entry::new();
1864                e.connect_changed(move |e| dispatch_typed(id, e.text().to_string()));
1865                // The caret and the selection's other end (#86).
1866                for prop in ["cursor-position", "selection-bound"] {
1867                    e.connect_notify_local(Some(prop), move |e, _| {
1868                        report_selection(id, editable_selection(e))
1869                    });
1870                }
1871                // Enter.
1872                e.connect_activate(move |_| dispatch(UiEvent::Submit(id)));
1873                View::Input(id, e)
1874            }
1875            NodeKind::Slider => {
1876                let (scale, config) = controls::slider(id);
1877                View::Slider(id, scale, config)
1878            }
1879            NodeKind::Picker => View::Picker(id, controls::picker(id)),
1880            NodeKind::DatePicker => {
1881                let p = controls::date_picker(id, self.locale.clone());
1882                if !self.clear_label.is_empty() {
1883                    p.set_clear_label(&self.clear_label);
1884                }
1885                self.date_pickers.insert(id, p.clone());
1886                View::DatePicker(id, p)
1887            }
1888            NodeKind::TextArea => View::TextArea(id, controls::text_area(id)),
1889            // A text area showing runs as tags, chips at anchors (#115).
1890            NodeKind::RichInput => {
1891                let t = controls::text_area(id);
1892                crate::rich::setup(id, &t.view);
1893                View::TextArea(id, t)
1894            }
1895            NodeKind::Spinner => {
1896                let s = gtk::Spinner::new();
1897                s.set_spinning(true);
1898                controls::spinner_size(&s, false);
1899                View::Spinner(id, s)
1900            }
1901            NodeKind::Toggle => {
1902                let t = gtk::Switch::new();
1903                t.set_valign(gtk::Align::Center);
1904                t.connect_active_notify(move |t| {
1905                    dispatch(UiEvent::Change(id, if t.is_active() { 1. } else { 0. }))
1906                });
1907                View::Toggle(id, t)
1908            }
1909            NodeKind::Progress => View::Progress(id, gtk::ProgressBar::new()),
1910            NodeKind::Image => View::Image(id, gtk::Label::new(None)),
1911            NodeKind::Picture => {
1912                let p = gtk::Picture::new();
1913                p.set_content_fit(gtk::ContentFit::Cover);
1914                // New content (a load, a file): cropped around its focal
1915                // point (#218).
1916                p.connect_paintable_notify(move |p| {
1917                    if !p
1918                        .paintable()
1919                        .is_some_and(|c| c.is::<crate::focal::FocalPaintable>())
1920                    {
1921                        crate::focal::apply(id, p);
1922                    }
1923                });
1924                View::Picture(id, p)
1925            }
1926            NodeKind::Timer => View::Timer(id, gtk::Label::new(None)),
1927            NodeKind::Shape => {
1928                let area = gtk::DrawingArea::new();
1929                let paths: Rc<RefCell<Vec<prism_core::Path>>> = Rc::default();
1930                let drawn = paths.clone();
1931                area.set_draw_func(move |_, cr, _, _| draw_paths(cr, &drawn.borrow()));
1932                self.shapes.insert(id, area.clone());
1933                View::Shape(id, area, paths)
1934            }
1935            NodeKind::Scene3d => {
1936                let scene =
1937                    crate::scene3d::SceneView::new(id, self.assets.clone(), self.embedded.clone());
1938                self.scenes.insert(id, scene.area.clone());
1939                View::Scene(id, scene)
1940            }
1941            NodeKind::Scroll => {
1942                let content = layout::container();
1943                let s = gtk::ScrolledWindow::new();
1944                s.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
1945                s.set_child(Some(&content));
1946                let events = self.scroll_events.clone();
1947                let adj = s.vadjustment();
1948                let stickies = self.stickies.clone();
1949                adj.connect_value_changed(move |a| {
1950                    place_sticky(&stickies, id, a.value());
1951                    if events.borrow().contains(&id) {
1952                        // Also when the app moved it (`scroll_by`, #204)
1953                        // while Prism applied patches: reported right after.
1954                        let event = UiEvent::Scroll(id, a.value() as f32, a.page_size() as f32);
1955                        glib::idle_add_local_once(move || {
1956                            with_state(|s| {
1957                                let patches = s.runtime.dispatch(event);
1958                                commit(s, patches);
1959                            })
1960                        });
1961                    }
1962                });
1963                View::Scroll(id, s, content)
1964            }
1965            NodeKind::Stack => {
1966                let root = layout::container();
1967                let header = gtk::Box::new(gtk::Orientation::Horizontal, 8);
1968                header.add_css_class("prism-header");
1969                let back = gtk::Button::with_label("‹ Back");
1970                back.set_has_frame(false);
1971                let title = gtk::Label::new(None);
1972                title.set_hexpand(true);
1973                title.add_css_class("heading");
1974                header.append(&back);
1975                header.append(&title);
1976                header.set_parent(&root);
1977                let stack = Rc::new(NavStack {
1978                    root,
1979                    header,
1980                    back: back.clone(),
1981                    title,
1982                    screens: RefCell::new(Vec::new()),
1983                    in_sheet: Cell::new(false),
1984                    no_header: Cell::new(false),
1985                });
1986                self.stacks.push(stack.clone());
1987                let weak = Rc::downgrade(&stack);
1988                back.connect_clicked(move |_| {
1989                    if let Some(st) = weak.upgrade() {
1990                        let depth = st.screens.borrow().len();
1991                        dispatch(UiEvent::Back(id, depth.saturating_sub(1)));
1992                    }
1993                });
1994                View::Stack(id, stack)
1995            }
1996            NodeKind::Tabs => {
1997                let root = layout::container();
1998                root.set_widget_name(&format!("n{id}"));
1999                let bar = gtk::Box::new(gtk::Orientation::Horizontal, 4);
2000                bar.set_homogeneous(true);
2001                bar.add_css_class("prism-tabbar");
2002                bar.set_property("accessible-role", gtk::AccessibleRole::TabList);
2003                bar.set_parent(&root);
2004                let tabs = Rc::new(TabBar {
2005                    root,
2006                    bar,
2007                    tabs: RefCell::new(Vec::new()),
2008                    selected: Cell::new(0),
2009                });
2010                self.tab_bars.push(tabs.clone());
2011                View::Tabs(id, tabs)
2012            }
2013            NodeKind::Modal => {
2014                let content = layout::container();
2015                let window = gtk::Window::builder()
2016                    .transient_for(&self.window)
2017                    .modal(true)
2018                    .default_width(520)
2019                    .default_height(620)
2020                    .child(&content)
2021                    .build();
2022                let sheet = Rc::new(Sheet {
2023                    window: window.clone(),
2024                    content,
2025                    children: RefCell::new(Vec::new()),
2026                });
2027                let weak = Rc::downgrade(&sheet);
2028                // Closing the window dismisses the modal's stack.
2029                window.connect_close_request(move |_| {
2030                    if let Some(s) = weak.upgrade()
2031                        && let Some(stack) = s.children.borrow().first()
2032                    {
2033                        dispatch(UiEvent::Dismiss(
2034                            stack.id(),
2035                            prism_core::DismissReason::Back,
2036                        ));
2037                    }
2038                    glib::Propagation::Stop
2039                });
2040                View::Sheet(id, sheet)
2041            }
2042            // No web view on Linux yet (#62): an empty box sized by its
2043            // style (`capabilities().web_view` is false).
2044            NodeKind::WebView => View::Container(id, kind, layout::container()),
2045            NodeKind::Video => View::Video(id, video_widget(id)),
2046            NodeKind::Checkbox => View::Check(id, controls::checkbox(id)),
2047            NodeKind::RadioGroup => View::Radio(id, controls::radio_group(id)),
2048            NodeKind::Overlay => {
2049                let anchor = gtk::Box::new(gtk::Orientation::Vertical, 0);
2050                anchor.set_can_target(false);
2051                View::Overlay(
2052                    id,
2053                    Rc::new(OverlayView {
2054                        id,
2055                        anchor,
2056                        content: layout::container(),
2057                        popover: RefCell::new(None),
2058                        window: RefCell::new(None),
2059                        config: Cell::new(Default::default()),
2060                        open: Cell::new(false),
2061                        size: Cell::new((0, 0)),
2062                        outside: RefCell::new(None),
2063                    }),
2064                )
2065            }
2066        };
2067        let w = view.widget();
2068        w.add_css_class(&format!("p{id}"));
2069        self.attach_gestures(id, &w);
2070        if matches!(
2071            view,
2072            View::Input(..)
2073                | View::Slider(..)
2074                | View::Picker(..)
2075                | View::DatePicker(..)
2076                | View::TextArea(..)
2077                | View::Check(..)
2078                | View::Radio(..)
2079        ) {
2080            controls::set_direction_deep(&w, self.rtl);
2081            self.controls.insert(id, w);
2082        }
2083        view
2084    }
2085
2086    fn set_style(&mut self, view: &View, s: &Style) {
2087        let id = view.id();
2088        if let View::Scroll(_, sw, _) = view {
2089            // `scroll_x()`: sideways only.
2090            // Hidden bars (#132): `External` still scrolls, without a bar.
2091            let on = if s.scrollbar == prism_core::Scrollbar::Hidden {
2092                gtk::PolicyType::External
2093            } else {
2094                gtk::PolicyType::Automatic
2095            };
2096            let (h, v) = if s.scroll_axis == prism_core::ScrollAxis::Horizontal {
2097                (on, gtk::PolicyType::Never)
2098            } else {
2099                (gtk::PolicyType::Never, on)
2100            };
2101            sw.set_policy(h, v);
2102            // Overlay bars, whatever the desktop's setting for others.
2103            sw.set_overlay_scrolling(true);
2104        }
2105        if crate::decor::adapts(s) {
2106            self.adaptive.insert(id, (view.clone(), s.clone()));
2107        } else {
2108            self.adaptive.remove(&id);
2109        }
2110        // Background, gradient, corners, borders (per side, dashed, dotted)
2111        // and shadows.
2112        let mut css = crate::decor::declarations(&crate::decor::paint(s, self.dark, false));
2113        // The theme paints buttons with an image over their color.
2114        if s.background.is_some() && s.gradient.is_none() && matches!(view, View::Button(..)) {
2115            css += "background-image:none;";
2116        }
2117        if let Some(t) = s.transition {
2118            // Colors animate in GTK's CSS; opacity and transforms in `layout`.
2119            let (x1, y1, x2, y2) = t.bezier();
2120            css += &format!(
2121                "transition:all {}s cubic-bezier({x1},{y1},{x2},{y2}) {}s;",
2122                t.duration, t.delay
2123            );
2124        }
2125        // Tint of form controls: the slider's fill, the picker's and the
2126        // date picker's text (not their popovers').
2127        let mut extra = String::new();
2128        if let Some(c) = s.text_color {
2129            let c = css_color(c, self.dark);
2130            match view {
2131                View::Slider(..) => {
2132                    extra += &format!(
2133                        ".p{id} trough highlight{{background-color:{c};border-color:{c};}}\n"
2134                    )
2135                }
2136                View::Picker(..) | View::DatePicker(..) => {
2137                    extra += &format!(".p{id} > button{{color:{c};}}\n")
2138                }
2139                _ => css += &format!("color:{c};"),
2140            }
2141        }
2142        if let View::TextArea(_, t) = view {
2143            // Prism draws the field: the text view is transparent inside.
2144            let drawn =
2145                s.background.is_some() || s.borders().iter().any(|b| b.width > 0.) || s.border_none;
2146            t.scroll.set_has_frame(!drawn);
2147            if drawn {
2148                extra += &format!(
2149                    ".p{id} textview, .p{id} textview text{{background-color:transparent;}}\n"
2150                );
2151            }
2152        }
2153        css += &format!(
2154            "font-size:{}px;font-weight:{};",
2155            s.font_size,
2156            s.font_weight.css()
2157        );
2158        if let View::Text(..) = view {
2159            extra += &text::link_css(id);
2160        }
2161        // Padding (#14): drawn by GTK in place of the theme's, or the text
2162        // view's margins; `.border(0.)`: not even the theme's frame.
2163        crate::padding::remember(id, s);
2164        match view {
2165            View::Text(..) | View::Timer(..) | View::Button(..) => css += &crate::padding::css(s),
2166            View::Input(..) => {
2167                css += &crate::padding::css(s);
2168                css += crate::padding::entry_css(s);
2169            }
2170            View::TextArea(id, t) => {
2171                t.set_padding(s.has_padding().then_some(s.padding));
2172                crate::rich::set_style(*id, s);
2173            }
2174            _ => {}
2175        }
2176        if s.border_none && !s.borders().iter().any(|b| b.width > 0.) {
2177            match view {
2178                View::Input(..) | View::Button(..) => css += crate::padding::NO_BORDER,
2179                View::Picker(..) | View::DatePicker(..) => {
2180                    extra += &format!(".p{id} > button{{{}}}\n", crate::padding::NO_BORDER)
2181                }
2182                _ => {}
2183            }
2184        }
2185        // A field with its own look: no theme focus ring (#274), the caret
2186        // or the app's focus style shows the focus.
2187        if matches!(view, View::Input(..) | View::TextArea(..)) && s.own_field_look() {
2188            css += "outline:none;";
2189        }
2190        // Hover, press and focus refinements: GTK's own pseudo-classes.
2191        let text_on_self = !matches!(
2192            view,
2193            View::Slider(..) | View::Picker(..) | View::DatePicker(..)
2194        );
2195        let inner_focus = matches!(view, View::Input(..) | View::TextArea(..));
2196        extra += &crate::decor::state_rules(id, s, self.dark, text_on_self, inner_focus);
2197        // Bar tint (#30).
2198        if matches!(view, View::Tabs(..) | View::Stack(..)) {
2199            let tabs = matches!(view, View::Tabs(..));
2200            extra += &crate::navbar::tint_rules(id, tabs, s.tint, self.dark);
2201        }
2202        // Nodes with the same rule share its class; reloading the sheet
2203        // restyles every widget, so only a new rule does.
2204        let change = self.sheet.set(id, &format!(".p{id}{{{css}}}\n{extra}"));
2205        self.css_dirty |= change.added;
2206        let w = view.widget();
2207        if change.old != Some(change.new) {
2208            if let Some(old) = change.old {
2209                w.remove_css_class(&format!("s{old}"));
2210            }
2211            w.add_css_class(&format!("s{}", change.new));
2212        }
2213        if s.group {
2214            w.add_css_class("prism-group");
2215        } else {
2216            w.remove_css_class("prism-group");
2217        }
2218        // A named group (#212): its own class.
2219        let named = s.group_name.as_deref().map(crate::decor::group_class);
2220        for c in w.css_classes() {
2221            if c.starts_with("prism-gn-") && Some(c.as_str()) != named.as_deref() {
2222                w.remove_css_class(&c);
2223            }
2224        }
2225        if let Some(c) = &named {
2226            w.add_css_class(c);
2227        }
2228        self.watch_states(id, &w, s, inner_focus);
2229        match s.cursor {
2230            Some(c) => {
2231                self.cursors.insert(id, c);
2232                w.set_cursor_from_name(Some(c.css()));
2233            }
2234            None => {
2235                if self.cursors.remove(&id).is_some() {
2236                    let pointer =
2237                        self.clickable.borrow().contains(&id) || matches!(view, View::Button(..));
2238                    w.set_cursor_from_name(pointer.then_some("pointer"));
2239                }
2240            }
2241        }
2242        // `hit_test(false)`: GTK skips the widget and its children when
2243        // picking; `inert`: no pointer, no focus, hidden from screen readers.
2244        w.set_can_target(s.hit_test && !s.inert);
2245        w.set_can_focus(!s.inert);
2246        if s.inert != self.inert.contains(&id) {
2247            if s.inert {
2248                self.inert.insert(id);
2249            } else {
2250                self.inert.remove(&id);
2251            }
2252            set_accessible_hidden(&w, s.inert || self.a11y_hidden.contains(&id));
2253        }
2254        layout::stop(&w, layout::Channel::Visual);
2255        layout::set_visual(
2256            &w,
2257            layout::Visual {
2258                opacity: s.opacity,
2259                transform: s.transform,
2260            },
2261        );
2262        let xalign = match s.text_align {
2263            TextAlign::Left => 0.,
2264            TextAlign::Center => 0.5,
2265            TextAlign::Right => 1.,
2266        };
2267        if let View::Text(id, l) = view {
2268            let state = self.labels.entry(*id).or_default();
2269            state.label = Some(l.clone());
2270            state.style = s.clone();
2271            text::apply(l, state, self.dark);
2272        }
2273        match view {
2274            View::Text(_, l) | View::Timer(_, l) => {
2275                l.set_xalign(xalign);
2276                l.set_justify(match s.text_align {
2277                    TextAlign::Left => gtk::Justification::Left,
2278                    TextAlign::Center => gtk::Justification::Center,
2279                    TextAlign::Right => gtk::Justification::Right,
2280                });
2281            }
2282            View::Container(..) | View::TextArea(..) => {
2283                // `clip()`: children clipped to the (rounded) box.
2284                view.widget()
2285                    .set_overflow(if s.corner_radius > 0. || s.clip {
2286                        gtk::Overflow::Hidden
2287                    } else {
2288                        gtk::Overflow::Visible
2289                    })
2290            }
2291            _ => {}
2292        }
2293    }
2294
2295    fn set_text(&mut self, view: &View, text: &str) {
2296        match view {
2297            View::Text(id, l) => {
2298                let state = self.labels.entry(*id).or_default();
2299                state.label = Some(l.clone());
2300                state.text = text.to_string();
2301                text::apply(l, state, self.dark);
2302            }
2303            View::Button(_, b) => b.set_label(text),
2304            // A value from the app reaches a focused field too; echoes of
2305            // the typing leave it (and its caret) alone (#73).
2306            View::Input(id, e) => {
2307                let current = e.text();
2308                if field_takes(*id, text, &current) {
2309                    let caret = prism_native::fields::caret_from_end(
2310                        current.chars().count(),
2311                        e.position().max(0) as usize,
2312                        text.chars().count(),
2313                    );
2314                    e.set_text(text);
2315                    e.set_position(caret as i32);
2316                }
2317            }
2318            View::TextArea(id, t) => {
2319                let takes = field_takes(*id, text, &t.text());
2320                t.set_text(text, takes);
2321            }
2322            // Bytes in memory (`picture_data`): decoded by GdkTexture
2323            // (PNG, JPEG, TIFF; others through gdk-pixbuf's loaders).
2324            View::Picture(_, p) if text.starts_with("data:") => {
2325                let texture = prism_native::images::data_url(text).and_then(|b| {
2326                    gtk::gdk::Texture::from_bytes(&gtk::glib::Bytes::from_owned(b)).ok()
2327                });
2328                match texture {
2329                    Some(t) => p.set_paintable(Some(&t)),
2330                    None => eprintln!("prism-linux: could not decode a data: picture"),
2331                }
2332            }
2333            View::Check(_, b) => b.set_label((!text.is_empty()).then_some(text)),
2334            // A video's source (#207): a URL, a file or an asset. GTK's
2335            // player sends no headers: the first line is the URL.
2336            View::Video(_, v) => {
2337                let sources = prism_native::images::ImageSources {
2338                    embedded: self.embedded.clone(),
2339                    asset_dirs: self.assets.iter().cloned().collect(),
2340                    cache_dir: gtk::glib::user_cache_dir().join("prism").into(),
2341                };
2342                if let Some(url) = prism_native::images::media_url(text, &sources) {
2343                    let url = prism_core::picture_source(&url).0.to_string();
2344                    v.set_file(Some(&gtk::gio::File::for_uri(&url)));
2345                }
2346            }
2347            // A remote image (with its headers, `Picture::header`): loaded
2348            // on a background thread.
2349            View::Picture(_, p) if prism_native::images::is_remote(text) => {
2350                load_remote_picture(p, text);
2351            }
2352            View::Picture(_, p) => {
2353                // Compiled into the binary first, then the assets directory.
2354                if let Some(bytes) = self.embedded.get(text) {
2355                    match gtk::gdk::Texture::from_bytes(&gtk::glib::Bytes::from(bytes)) {
2356                        Ok(t) => p.set_paintable(Some(&t)),
2357                        Err(_) => eprintln!("prism-linux: could not decode the picture {text}"),
2358                    }
2359                } else {
2360                    let path = if text.starts_with('/') {
2361                        Some(std::path::PathBuf::from(text))
2362                    } else {
2363                        self.assets.as_ref().map(|a| a.join(text))
2364                    };
2365                    if let Some(path) = path.filter(|p| p.exists()) {
2366                        p.set_filename(Some(&path));
2367                    }
2368                }
2369            }
2370            // Screens and tabs: titles (the stack header / tab bar shows them).
2371            View::Container(id, NodeKind::Screen | NodeKind::Tab, _) => {
2372                self.titles.insert(*id, text.to_string());
2373                for st in self.stacks.clone() {
2374                    if st.screens.borrow().iter().any(|s| s.id() == *id) {
2375                        self.header_back(&st);
2376                    }
2377                }
2378                for t in self.tab_bars.clone() {
2379                    if t.tabs.borrow().iter().any(|s| s.id() == *id) {
2380                        self.refresh_tabs(&t);
2381                    }
2382                }
2383            }
2384            _ => {}
2385        }
2386    }
2387
2388    fn set_placeholder(&mut self, view: &View, text: &str) {
2389        match view {
2390            View::Input(_, e) => {
2391                e.set_placeholder_text(Some(text));
2392                // GtkText creates its placeholder label now: mirror it too.
2393                controls::set_direction_deep(e.upcast_ref(), self.rtl);
2394            }
2395            View::TextArea(_, t) => {
2396                t.set_placeholder(text);
2397                set_accessible_string(&t.view, a11y_property::PLACEHOLDER, text);
2398            }
2399            View::Picker(_, p) => p.set_placeholder(text),
2400            View::DatePicker(_, p) => p.set_placeholder(text),
2401            View::Timer(id, l) => {
2402                self.timer_after.insert(*id, text.to_string());
2403                if let Some((_, end)) = self.timers.get(id) {
2404                    l.set_text(&prism_core::timer_text(*end, text));
2405                }
2406            }
2407            _ => {}
2408        }
2409    }
2410
2411    fn set_clickable(&mut self, view: &View, clickable: bool) {
2412        // A "clickable" scroll view refreshes (F5 / Ctrl+R on desktops).
2413        if let View::Scroll(id, sw, _) = view {
2414            if clickable {
2415                self.refreshable.borrow_mut().insert(*id, sw.clone());
2416            } else {
2417                self.refreshable.borrow_mut().remove(id);
2418            }
2419            return;
2420        }
2421        if let View::Container(id, _, c) = view {
2422            if clickable {
2423                self.clickable.borrow_mut().insert(*id);
2424            } else {
2425                self.clickable.borrow_mut().remove(id);
2426            }
2427            // A pointing hand, unless the style chose a cursor.
2428            if !self.cursors.contains_key(id) {
2429                c.set_cursor_from_name(clickable.then_some("pointer"));
2430            }
2431        }
2432        if let View::Text(id, l) = view {
2433            if clickable {
2434                self.clickable.borrow_mut().insert(*id);
2435                if !self.cursors.contains_key(id) {
2436                    l.set_cursor_from_name(Some("pointer"));
2437                }
2438                // A button for assistive technologies (the role can only
2439                // change before the widget is realized).
2440                if !l.is_realized() {
2441                    l.set_property("accessible-role", gtk::AccessibleRole::Button);
2442                }
2443            } else {
2444                self.clickable.borrow_mut().remove(id);
2445                if !self.cursors.contains_key(id) {
2446                    l.set_cursor_from_name(None);
2447                }
2448            }
2449            self.update_text_focus(*id, l);
2450        }
2451    }
2452
2453    fn set_children(&mut self, parent: &View, children: &[View]) {
2454        let (sheets, children): (Vec<View>, Vec<View>) = children
2455            .iter()
2456            .cloned()
2457            .partition(|c| matches!(c, View::Sheet(..)));
2458        for sheet in &sheets {
2459            if let View::Sheet(_, s) = sheet {
2460                s.window.present();
2461            }
2462        }
2463        let host: gtk::Widget = match parent {
2464            View::Container(_, _, c) => c.clone().upcast(),
2465            View::Scroll(_, _, content) => content.clone().upcast(),
2466            View::Stack(_, st) => st.root.clone().upcast(),
2467            View::Tabs(_, t) => t.root.clone().upcast(),
2468            View::Sheet(_, s) => {
2469                *s.children.borrow_mut() = children.clone();
2470                if let Some(View::Stack(_, st)) = children.first() {
2471                    st.in_sheet.set(true);
2472                    self.header_back(st);
2473                }
2474                s.content.clone().upcast()
2475            }
2476            View::Overlay(_, o) => o.content.clone().upcast(),
2477            _ => return,
2478        };
2479        // Remove the old children (keeping a stack's header and a tab bar).
2480        let keep: Vec<gtk::Widget> = match parent {
2481            View::Stack(_, st) => vec![st.header.clone().upcast()],
2482            View::Tabs(_, t) => vec![t.bar.clone().upcast()],
2483            _ => vec![],
2484        };
2485        let mut old = Vec::new();
2486        let mut child = host.first_child();
2487        while let Some(c) = child {
2488            child = c.next_sibling();
2489            if !keep.contains(&c) {
2490                old.push(c);
2491            }
2492        }
2493        let new: Vec<gtk::Widget> = children.iter().map(View::widget).collect();
2494        // Context-menu popovers are children too: they stay, like pictures
2495        // of removed views animating out.
2496        let (gone, order) = arrange_children(&old, &new, |c| {
2497            c.is::<gtk::Popover>() || c.has_css_class("prism-ghost")
2498        });
2499        for c in gone {
2500            c.unparent();
2501        }
2502        let mut prev: Option<gtk::Widget> = None;
2503        for w in &order {
2504            if w.parent().is_some_and(|p| p != host) {
2505                w.unparent();
2506            }
2507            w.insert_after(&host, prev.as_ref());
2508            prev = Some(w.clone());
2509        }
2510        // Sticky views draw over the content that scrolls under them.
2511        for c in &children {
2512            let w = c.widget();
2513            if layout::is_sticky(&w) {
2514                layout::raise(&w);
2515            }
2516        }
2517        // The header and the tab bar draw over the screens.
2518        for bar in &keep {
2519            bar.insert_before(&host, None::<&gtk::Widget>);
2520        }
2521        match parent {
2522            View::Stack(_, st) => {
2523                *st.screens.borrow_mut() = children;
2524                self.header_back(st);
2525            }
2526            View::Tabs(_, t) => {
2527                *t.tabs.borrow_mut() = children;
2528                self.refresh_tabs(t);
2529            }
2530            _ => {}
2531        }
2532    }
2533
2534    fn set_root(&mut self, view: &View) {
2535        let mut child = self.root.first_child();
2536        while let Some(c) = child {
2537            child = c.next_sibling();
2538            if !self.layers.contains(&c) {
2539                c.unparent();
2540            }
2541        }
2542        view.widget().set_parent(&self.root);
2543        self.raise_layers();
2544    }
2545
2546    fn set_drawing(&mut self, view: &View, paths: &[prism_core::Path]) {
2547        if let View::Shape(_, area, p) = view {
2548            *p.borrow_mut() = paths.to_vec();
2549            area.queue_draw();
2550        }
2551    }
2552
2553    fn set_scene(&mut self, view: &View, update: &prism_core::scene3d::SceneUpdate, _json: &str) {
2554        if let View::Scene(_, s) = view {
2555            s.set_scene(update);
2556        }
2557    }
2558
2559    fn destroy(&mut self, view: &View) {
2560        if let View::Picture(id, _) = view {
2561            crate::focal::forget(*id);
2562        }
2563        let id = view.id();
2564        TYPED.with(|t| t.borrow_mut().remove(&id));
2565        crate::edit::forget(id);
2566        crate::rich::forget(id);
2567        forget_selection(id);
2568        crate::carets::forget(id);
2569        crate::navbar::forget(id);
2570        self.shapes.remove(&id);
2571        self.scenes.remove(&id);
2572        self.controls.remove(&id);
2573        self.date_pickers.remove(&id);
2574        self.statuses.remove(&id);
2575        self.labels.remove(&id);
2576        // No reload just for it (see `Sheet::remove`).
2577        self.sheet.remove(id);
2578        self.adaptive.remove(&id);
2579        self.clickable.borrow_mut().remove(&id);
2580        self.reports.borrow_mut().remove(&id);
2581        self.watched.remove(&id);
2582        self.cursors.remove(&id);
2583        self.timers.remove(&id);
2584        self.timer_after.remove(&id);
2585        if let Some(p) = self.menus.borrow_mut().remove(&id) {
2586            p.unparent();
2587        }
2588        self.swipes.borrow_mut().remove(&id);
2589        self.scroll_events.borrow_mut().remove(&id);
2590        self.refreshable.borrow_mut().remove(&id);
2591        self.titles.remove(&id);
2592        self.icons.remove(&id);
2593        self.sizes.remove(&id);
2594        {
2595            let mut stickies = self.stickies.borrow_mut();
2596            stickies.remove(&id);
2597            for views in stickies.values_mut() {
2598                views.remove(&id);
2599            }
2600        }
2601        if let View::Stack(_, st) = view {
2602            self.stacks.retain(|s| !Rc::ptr_eq(s, st));
2603        }
2604        if let View::Tabs(_, t) = view {
2605            self.tab_bars.retain(|b| !Rc::ptr_eq(b, t));
2606        }
2607        if let View::Sheet(_, s) = view {
2608            s.window.destroy();
2609            return;
2610        }
2611        if let View::Overlay(_, o) = view {
2612            o.open.set(false);
2613            o.teardown();
2614        }
2615        self.pointer.borrow_mut().remove(&id);
2616        self.drag_delays.borrow_mut().remove(&id);
2617        self.pointer_attached.retain(|(n, _)| *n != id);
2618        self.drop_targets.remove(&id);
2619        self.keys.local.borrow_mut().remove(&id);
2620        self.keys.global.borrow_mut().remove(&id);
2621        self.inert.remove(&id);
2622        self.a11y_hidden.remove(&id);
2623        self.pressable.remove(&id);
2624        self.layers.retain(|l| *l != view.widget());
2625        let w = view.widget();
2626        layout::forget(&w);
2627        if w.parent().is_some() {
2628            w.unparent();
2629        }
2630    }
2631
2632    fn measure(&mut self, view: &View, max_width: Option<f32>) -> (f32, f32) {
2633        // A countdown with an `after` text is as large as the larger of the
2634        // two, so the text fits once it ends (#281).
2635        if let View::Timer(id, l) = view
2636            && let Some(after) = self.timer_after.remove(id)
2637        {
2638            let shown = l.text();
2639            l.set_text(&after);
2640            let ended = self.measure(view, max_width);
2641            l.set_text(&shown);
2642            let counting = self.measure(view, max_width);
2643            self.timer_after.insert(*id, after);
2644            return (ended.0.max(counting.0), ended.1.max(counting.1));
2645        }
2646        let w = view.widget();
2647        // GTK measures with the CSS padding: the content is without it
2648        // (the layout adds it, #14).
2649        let p = crate::padding::of(view.id());
2650        let (px, py) = (p.left + p.right, p.top + p.bottom);
2651        let (_, nat_w, _, _) = w.measure(gtk::Orientation::Horizontal, -1);
2652        let nat_w = (nat_w as f32 - px).max(0.);
2653        // A video (#207): the stream's size once known, else 16:9.
2654        if let View::Video(_, v) = view {
2655            let natural = v
2656                .media_stream()
2657                .map(|m| (m.intrinsic_width(), m.intrinsic_height()));
2658            return match natural {
2659                Some((w, h)) if w > 0 && h > 0 => {
2660                    let (w, h) = (w as f32, h as f32);
2661                    let shown = max_width.map_or(w, |m| m.min(w));
2662                    (shown, shown * h / w)
2663                }
2664                _ => {
2665                    let w = max_width.unwrap_or(320.);
2666                    (w, w * 9. / 16.)
2667                }
2668            };
2669        }
2670        let width = match (view, max_width) {
2671            (View::Text(..), Some(m)) => nat_w.min(m),
2672            (View::Input(..) | View::Progress(..), Some(m)) => m,
2673            // GtkScale's natural width is its knob: sliders take 200 px.
2674            (View::Slider(..), m) => m.map_or(200., |m| m.min(200.)),
2675            // As wide as offered; as tall as its text, at least 3 lines.
2676            (View::TextArea(id, t), m) => {
2677                let w = m.unwrap_or(240.).ceil();
2678                let h = t.measure_height(w + px, crate::rich::attributes(*id));
2679                return (w, (h - py).max(0.).ceil());
2680            }
2681            _ => nat_w,
2682        };
2683        let (_, nat_h, _, _) = w.measure(gtk::Orientation::Vertical, (width + px).ceil() as i32);
2684        (width.ceil(), (nat_h as f32 - py).max(0.))
2685    }
2686
2687    /// A wrapping label's longest word. Labels fall back to breaking
2688    /// between characters when a word doesn't fit (`WordChar`), so GTK's
2689    /// own minimum is one character: the label's layout is measured with
2690    /// word wrapping alone, which keeps `09:35` and `Line` whole.
2691    fn measure_min_content(&mut self, view: &View) -> f32 {
2692        if let View::Text(_, l) = view {
2693            let layout = l.layout().copy();
2694            layout.set_wrap(gtk::pango::WrapMode::Word);
2695            layout.set_ellipsize(gtk::pango::EllipsizeMode::None);
2696            layout.set_height(-1);
2697            // As narrow as it gets (as GtkLabel measures its minimum).
2698            layout.set_width(0);
2699            return layout.pixel_extents().1.width() as f32;
2700        }
2701        view.widget().measure(gtk::Orientation::Horizontal, -1).1 as f32
2702    }
2703
2704    fn set_frame(&mut self, view: &View, x: f32, y: f32, w: f32, h: f32) {
2705        self.sizes.insert(view.id(), (w, h));
2706        match view {
2707            View::Sheet(..) => {}
2708            View::Stack(_, st) => {
2709                layout::set_frame(&st.root, rect(x, y, w, h));
2710                layout::set_frame(&st.header, rect(0., 0., w, HEADER));
2711            }
2712            View::Tabs(_, t) => {
2713                layout::set_frame(&t.root, rect(x, y, w, h));
2714                layout::set_frame(&t.bar, rect(0., h - TAB_BAR, w, TAB_BAR));
2715            }
2716            _ => layout::set_frame(&view.widget(), rect(x, y, w, h)),
2717        }
2718    }
2719
2720    fn set_frame_animated(
2721        &mut self,
2722        view: &View,
2723        x: f32,
2724        y: f32,
2725        w: f32,
2726        h: f32,
2727        t: prism_core::Transition,
2728    ) {
2729        match view {
2730            View::Container(..)
2731            | View::Text(..)
2732            | View::Image(..)
2733            | View::Button(..)
2734            | View::Picture(..)
2735            | View::Toggle(..)
2736            | View::Progress(..)
2737            | View::Timer(..) => {
2738                self.sizes.insert(view.id(), (w, h));
2739                layout::animate_frame(&view.widget(), rect(x, y, w, h), t);
2740            }
2741            _ => self.set_frame(view, x, y, w, h),
2742        }
2743    }
2744
2745    fn set_style_animated(&mut self, view: &View, style: &Style, t: prism_core::Transition) {
2746        let w = view.widget();
2747        let from = layout::visual(&w);
2748        self.set_style(view, style);
2749        let to = layout::visual(&w);
2750        if from != to {
2751            layout::set_visual(&w, from);
2752            layout::animate_visual(&w, to, t, || {});
2753        }
2754    }
2755
2756    /// A still picture of the view stays in its place and animates out.
2757    fn animate_exit(&mut self, parent: &View, view: &View, to: &Style, t: prism_core::Transition) {
2758        let host: gtk::Widget = match parent {
2759            View::Container(_, _, c) => c.clone().upcast(),
2760            View::Scroll(_, _, content) => content.clone().upcast(),
2761            _ => return,
2762        };
2763        let w = view.widget();
2764        let Some(frame) = layout::frame_of(&w) else {
2765            return;
2766        };
2767        if w.parent().as_ref() != Some(&host) || frame.2 <= 0 || frame.3 <= 0 {
2768            return;
2769        }
2770        let image = gtk::WidgetPaintable::new(Some(&w)).current_image();
2771        let picture = gtk::Picture::for_paintable(&image);
2772        picture.set_can_shrink(true);
2773        picture.set_can_target(false);
2774        picture.add_css_class("prism-ghost");
2775        picture.set_parent(&host);
2776        layout::set_frame(&picture, frame);
2777        layout::set_visual(&picture, layout::visual(&w));
2778        let ghost = picture.clone();
2779        layout::animate_visual(
2780            &picture,
2781            layout::Visual {
2782                opacity: to.opacity,
2783                transform: to.transform,
2784            },
2785            t,
2786            move || {
2787                layout::forget(&ghost);
2788                ghost.unparent();
2789            },
2790        );
2791    }
2792
2793    fn set_repeat(
2794        &mut self,
2795        view: &View,
2796        style: &Style,
2797        repeat: Option<(prism_core::Pose, prism_core::Transition)>,
2798    ) {
2799        let w = view.widget();
2800        let rest = layout::Visual {
2801            opacity: style.opacity,
2802            transform: style.transform,
2803        };
2804        match repeat {
2805            None => {
2806                layout::stop(&w, layout::Channel::Loop);
2807                layout::set_visual(&w, rest);
2808            }
2809            Some((pose, t)) => {
2810                let (opacity, transform) = pose.apply(style.opacity, style.transform);
2811                let to = layout::Visual { opacity, transform };
2812                if style.animations.restart {
2813                    layout::repeat_from_start(&w, rest, to, t);
2814                } else {
2815                    layout::repeat(&w, rest, to, t);
2816                }
2817            }
2818        }
2819    }
2820
2821    fn screen_viewport(&mut self, container: &View, child: &View) -> Viewport {
2822        if let View::Sheet(_, s) = child {
2823            let (w, h) = (s.window.width().max(520), s.window.height().max(620));
2824            return Viewport {
2825                x: 0.,
2826                y: 0.,
2827                width: w as f32,
2828                height: h as f32,
2829                insets: Insets::default(),
2830            };
2831        }
2832        let (w, h) = self
2833            .sizes
2834            .get(&container.id())
2835            .copied()
2836            .unwrap_or(self.size);
2837        match container {
2838            View::Tabs(..) => Viewport {
2839                x: 0.,
2840                y: 0.,
2841                width: w,
2842                height: (h - TAB_BAR).max(0.),
2843                insets: Insets::default(),
2844            },
2845            // No header bar: the screen gets the whole stack.
2846            View::Stack(_, st) if self.header_hidden(st) => Viewport {
2847                x: 0.,
2848                y: 0.,
2849                width: w,
2850                height: h,
2851                insets: Insets::default(),
2852            },
2853            _ => Viewport {
2854                x: 0.,
2855                y: HEADER,
2856                width: w,
2857                height: (h - HEADER).max(0.),
2858                insets: Insets::default(),
2859            },
2860        }
2861    }
2862
2863    fn set_table(&mut self, table: &View, rows: &[prism_native::table::TableRow<'_, View>]) {
2864        let rows: Vec<(gtk::Widget, bool, Vec<gtk::Widget>)> = rows
2865            .iter()
2866            .map(|r| {
2867                (
2868                    r.view.widget(),
2869                    r.header,
2870                    r.cells.iter().map(|c| c.widget()).collect(),
2871                )
2872            })
2873            .collect();
2874        crate::table::set(&table.widget(), &rows);
2875    }
2876
2877    fn set_accessibility(&mut self, view: &View, a11y: &Accessibility) {
2878        let w = view.widget();
2879        let id = view.id();
2880        // The focusable part reads the label.
2881        let target: gtk::Widget = match view {
2882            View::Picker(_, p) => p.dropdown.clone().upcast(),
2883            View::TextArea(_, t) => t.view.clone().upcast(),
2884            _ => w.clone(),
2885        };
2886        match &a11y.label {
2887            Some(label) => {
2888                set_accessible_label(&target, label);
2889                // A tab panel named by the app, not by its tab
2890                // (`refresh_tabs`).
2891                if let View::Container(_, NodeKind::Tab, _) = view {
2892                    crate::table::set_relation(&w, crate::table::LABELLED_BY, None);
2893                }
2894            }
2895            // A label removed: the widget's own name again.
2896            None if crate::names::take_label(&target) => {
2897                reset_accessible_property(&target, a11y_property::LABEL)
2898            }
2899            None => {}
2900        }
2901        // Out of the tree: decorations, duplicates (an inner text the
2902        // element's label already says).
2903        if a11y.hidden != self.a11y_hidden.contains(&id) {
2904            if a11y.hidden {
2905                self.a11y_hidden.insert(id);
2906            } else {
2907                self.a11y_hidden.remove(&id);
2908            }
2909            set_accessible_hidden(&w, a11y.hidden || self.inert.contains(&id));
2910        }
2911        // A selected item or the current page of a navigation (GTK has no
2912        // « current » state). Only what can be selected says it is not: a
2913        // SELECTED state makes AT-SPI call any element selectable.
2914        if a11y.selected.is_some()
2915            || a11y.is_selected()
2916            || matches!(a11y.role, Some(prism_core::Role::Tab))
2917        {
2918            set_accessible_selected(&w, a11y.is_selected());
2919        } else {
2920            reset_accessible_state(&w, a11y_state::SELECTED);
2921        }
2922        // A drawn control that is disabled: unavailable for screen readers
2923        // (GTK's own controls are made insensitive below).
2924        if matches!(
2925            view,
2926            View::Container(..) | View::Text(..) | View::Image(..) | View::Shape(..)
2927        ) {
2928            if a11y.disabled {
2929                set_accessible_disabled(&w);
2930            } else {
2931                reset_accessible_state(&w, a11y_state::DISABLED);
2932            }
2933        }
2934        // Tooltips (#216): GTK's, or a label's full text while it is
2935        // ellipsized (asked as the pointer rests).
2936        match (&a11y.tooltip, view) {
2937            (Some(prism_core::Tooltip::Text(t)), _) => {
2938                w.remove_css_class("prism-tip-cut");
2939                w.set_tooltip_text(Some(t));
2940            }
2941            (Some(prism_core::Tooltip::WhenTruncated), View::Text(_, l)) => {
2942                w.set_tooltip_text(None);
2943                l.add_css_class("prism-tip-cut");
2944                l.set_has_tooltip(true);
2945                if !l.has_css_class("prism-tip-bound") {
2946                    l.add_css_class("prism-tip-bound");
2947                    l.connect_query_tooltip(|l, _, _, _, tip| {
2948                        let cut = l.has_css_class("prism-tip-cut") && l.layout().is_ellipsized();
2949                        if cut {
2950                            tip.set_text(Some(&l.text()));
2951                        }
2952                        cut
2953                    });
2954                }
2955            }
2956            _ => {
2957                w.remove_css_class("prism-tip-cut");
2958                w.set_tooltip_text(None);
2959            }
2960        }
2961        // The hint, after the tooltip: GTK before 4.12 makes a tooltip the
2962        // description, and no tooltip an empty one (gtkwidget.c,
2963        // `gtk_widget_set_tooltip_text`), which erased the hint.
2964        match &a11y.hint {
2965            Some(hint) => set_accessible_string(&w, a11y_property::DESCRIPTION, hint),
2966            None if !matches!(a11y.tooltip, Some(prism_core::Tooltip::Text(_))) => {
2967                reset_accessible_property(&w, a11y_property::DESCRIPTION)
2968            }
2969            None => {}
2970        }
2971        match view {
2972            // GtkScale exposes its own range and value (VALUE_MIN/MAX/NOW,
2973            // gtkrange.c); a formatted value ("40 %") is read instead.
2974            View::Slider(_, s, _) => {
2975                if let Some(v) = &a11y.value {
2976                    set_accessible_string(s, a11y_property::VALUE_TEXT, v);
2977                }
2978                s.set_sensitive(!a11y.disabled);
2979            }
2980            View::Picker(_, p) => {
2981                if let Some(v) = &a11y.value {
2982                    set_accessible_string(&p.dropdown, a11y_property::VALUE_TEXT, v);
2983                }
2984                p.dropdown.set_sensitive(!a11y.disabled);
2985            }
2986            View::DatePicker(_, p) => p.button.set_sensitive(!a11y.disabled),
2987            View::Check(_, b) => b.set_sensitive(!a11y.disabled),
2988            View::Radio(_, r) => r.set_sensitive(!a11y.disabled),
2989            View::TextArea(_, t) => t.view.set_sensitive(!a11y.disabled),
2990            View::Container(id, ..) if a11y.role == Some(prism_core::Role::Status) => {
2991                // A live region: GTK 4.8 has ROLE_STATUS (gtkenums.h); the
2992                // role can only change before the widget is realized.
2993                if !w.is_realized()
2994                    && w.property::<gtk::AccessibleRole>("accessible-role")
2995                        != gtk::AccessibleRole::Status
2996                {
2997                    w.set_property("accessible-role", gtk::AccessibleRole::Status);
2998                }
2999                let value = a11y.value.clone().unwrap_or_default();
3000                if self.statuses.get(id) != Some(&value) {
3001                    if !value.is_empty() {
3002                        controls::announce(&w, &value);
3003                    }
3004                    self.statuses.insert(*id, value);
3005                }
3006            }
3007            // A container takes the role the app or the core gave it: a
3008            // drawn button or link, a list, a landmark, drawn choices (#84:
3009            // option cards that are radios, custom checkboxes and switches,
3010            // with their checked state). Table parts keep the roles they were
3011            // created with (`table.rs`); a plain layout box keeps GTK's.
3012            View::Container(id, kind, c) => {
3013                if let Some(role) = a11y.role.and_then(container_role)
3014                    && crate::table::role(*kind).is_none()
3015                    // As above: the role can only change before it is
3016                    // realized.
3017                    && !w.is_realized()
3018                    && w.property::<gtk::AccessibleRole>("accessible-role") != role
3019                {
3020                    w.set_property("accessible-role", role);
3021                }
3022                match a11y.role {
3023                    Some(
3024                        prism_core::Role::Radio
3025                        | prism_core::Role::Checkbox
3026                        | prism_core::Role::Switch,
3027                    ) => set_accessible_checked(&w, a11y.checked.unwrap_or(false)),
3028                    Some(prism_core::Role::Heading(level)) => {
3029                        set_accessible_int(&w, a11y_property::LEVEL, level.into())
3030                    }
3031                    _ => {}
3032                }
3033                // A drawn control takes the keyboard focus (Tab), shows it,
3034                // and Enter or Space presses it.
3035                let pressable = a11y.role.is_some_and(prism_core::Role::is_interactive)
3036                    && !a11y.hidden
3037                    && !a11y.disabled;
3038                let was = if pressable {
3039                    !self.pressable.insert(*id)
3040                } else {
3041                    self.pressable.remove(id)
3042                };
3043                if pressable != was {
3044                    let keys = self.keys.local.borrow().contains(id);
3045                    c.set_focusable(pressable || keys);
3046                    if pressable || keys {
3047                        c.add_css_class(layout::FOCUSABLE);
3048                    } else {
3049                        c.remove_css_class(layout::FOCUSABLE);
3050                    }
3051                }
3052            }
3053            // A drawing (a QR code, an SVG, a chart) or a 3D scene is an
3054            // image (a "filler" otherwise), or what the app made it; an icon
3055            // with a label too.
3056            View::Shape(..) | View::Scene(..) | View::Image(..) => {
3057                let icon = matches!(view, View::Image(..));
3058                if let Some(role) = a11y.role.and_then(container_role)
3059                    && (!icon || a11y.label.is_some())
3060                    && !w.is_realized()
3061                    && w.property::<gtk::AccessibleRole>("accessible-role") != role
3062                {
3063                    w.set_property("accessible-role", role);
3064                }
3065            }
3066            // A heading's level (GTK 4.16 and later give it to AT-SPI).
3067            View::Text(_, l) => {
3068                if let Some(prism_core::Role::Heading(level)) = a11y.role {
3069                    if !l.is_realized()
3070                        && l.property::<gtk::AccessibleRole>("accessible-role")
3071                            != gtk::AccessibleRole::Heading
3072                    {
3073                        l.set_property("accessible-role", gtk::AccessibleRole::Heading);
3074                    }
3075                    set_accessible_int(l, a11y_property::LEVEL, level.into());
3076                }
3077            }
3078            _ => {}
3079        }
3080    }
3081
3082    fn set_value(&mut self, view: &View, value: f64) {
3083        match view {
3084            View::Toggle(_, t) => t.set_active(value != 0.),
3085            View::Progress(_, p) => p.set_fraction(value.clamp(0., 1.)),
3086            View::Picture(id, p) => crate::focal::set_fit(*id, p, value == 1.),
3087            View::Timer(id, l) => {
3088                let after = self.timer_after.get(id).map_or("", String::as_str);
3089                l.set_text(&prism_core::timer_text(value, after));
3090                self.timers.insert(*id, (l.clone(), value));
3091            }
3092            View::Tabs(_, t) => {
3093                t.selected.set(value.max(0.) as usize);
3094                self.refresh_tabs(t);
3095            }
3096            View::Stack(_, st) => {
3097                st.no_header
3098                    .set((value as u32) & prism_core::STACK_NO_HEADER != 0);
3099                self.header_back(st);
3100            }
3101            View::Container(id, NodeKind::Screen, _) => {
3102                let changed = if value == 1. {
3103                    self.bare.insert(*id)
3104                } else {
3105                    self.bare.remove(id)
3106                };
3107                if changed {
3108                    for st in self.stacks.clone() {
3109                        self.header_back(&st);
3110                    }
3111                }
3112            }
3113            View::Slider(_, s, c) => s.set_value(c.get().snap(value)),
3114            View::Picker(_, p) => p.select(value),
3115            View::DatePicker(_, p) => p.set_value(value),
3116            View::Spinner(_, s) => controls::spinner_size(s, value >= 1.),
3117            View::Check(_, b) => b.set_active(value != 0.),
3118            View::Radio(_, r) => r.select(value),
3119            View::Overlay(_, o) => o.set_open(value != 0.),
3120            _ => {}
3121        }
3122    }
3123
3124    fn set_config(&mut self, view: &View, _kind: NodeKind, config: &str) {
3125        match view {
3126            // A filled picture's focal point (#218).
3127            View::Picture(id, p) => crate::focal::set_focus(*id, p, config),
3128            // How a video plays (#207). GTK's player always offers its
3129            // controls on hover.
3130            View::Video(_, v) => {
3131                let c = prism_core::VideoConfig::decode(config);
3132                v.set_autoplay(c.autoplay);
3133                v.set_loop(c.looping);
3134                if let Some(stream) = v.media_stream() {
3135                    stream.set_muted(c.muted);
3136                }
3137                // SAFETY: a plain bool kept on the widget for new streams.
3138                unsafe { v.set_data("prism-muted", c.muted) };
3139            }
3140            // Bar buttons (#30): the stack showing the screen puts them up.
3141            View::Container(id, NodeKind::Screen, _) => {
3142                if crate::navbar::set_config(*id, config) {
3143                    for st in self.stacks.clone() {
3144                        self.header_back(&st);
3145                    }
3146                }
3147            }
3148            View::Slider(_, s, c) => {
3149                let cfg = prism_core::controls::SliderConfig::decode(config);
3150                c.set(cfg);
3151                controls::configure_slider(s, cfg);
3152            }
3153            View::Picker(_, p) => p.set_options(config),
3154            View::DatePicker(_, p) => p.set_config(config),
3155            View::Input(_, e) => controls::configure_entry(e, config),
3156            View::TextArea(_, t) => {
3157                controls::configure_text_view(&t.view, config);
3158                // Its minimum lines (#235).
3159                t.rows
3160                    .set(prism_core::controls::InputConfig::decode(config).min_rows());
3161            }
3162            // A rich text's runs.
3163            View::Text(id, l) => {
3164                let state = self.labels.entry(*id).or_default();
3165                state.label = Some(l.clone());
3166                state.config = config.to_string();
3167                text::apply(l, state, self.dark);
3168                self.update_text_focus(*id, l);
3169            }
3170            View::Radio(id, r) => r.set_options(*id, config),
3171            View::Overlay(_, o) => o.configure(
3172                prism_core::controls::OverlayConfig::decode(config),
3173                &self.window,
3174                &self.keys,
3175            ),
3176            _ => {}
3177        }
3178    }
3179
3180    fn set_environment(&mut self, env: &prism_core::RenderEnvironment) {
3181        let rtl = env.direction == prism_core::Direction::Rtl;
3182        let locale = prism_core::Locale::new(&env.lang);
3183        if rtl != self.rtl {
3184            self.rtl = rtl;
3185            for w in self.controls.values() {
3186                controls::set_direction_deep(w, rtl);
3187            }
3188        }
3189        if locale != self.locale {
3190            self.locale = locale.clone();
3191            for p in self.date_pickers.values() {
3192                p.set_locale(locale.clone());
3193            }
3194        }
3195        if env.clear != self.clear_label {
3196            self.clear_label = env.clear.clone();
3197            for p in self.date_pickers.values() {
3198                p.set_clear_label(&env.clear);
3199            }
3200        }
3201    }
3202
3203    fn set_icon(&mut self, view: &View, icon: &str) {
3204        match view {
3205            View::Image(_, l) => l.set_text(prism_core::glyphs::glyph(icon)),
3206            // A leading icon in the field (a themed icon; unknown symbols
3207            // show none).
3208            View::Input(_, e) => e.set_icon_from_icon_name(
3209                gtk::EntryIconPosition::Primary,
3210                crate::input::freedesktop_icon(icon),
3211            ),
3212            View::Container(id, NodeKind::Tab, _) => {
3213                self.icons.insert(*id, icon.to_string());
3214                for t in self.tab_bars.clone() {
3215                    if t.tabs.borrow().iter().any(|s| s.id() == *id) {
3216                        self.refresh_tabs(&t);
3217                    }
3218                }
3219            }
3220            _ => {}
3221        }
3222    }
3223
3224    fn set_menu(&mut self, view: &View, menu: Option<&prism_core::menu::MenuSpec>) {
3225        let id = view.id();
3226        if let Some(old) = self.menus.borrow_mut().remove(&id) {
3227            old.unparent();
3228        }
3229        if let Some(spec) = menu {
3230            let model = crate::services::menu_model(&self.app, spec);
3231            let popover = gtk::PopoverMenu::from_model(Some(&model));
3232            popover.set_has_arrow(false);
3233            popover.set_parent(&view.widget());
3234            self.menus.borrow_mut().insert(id, popover);
3235        }
3236    }
3237
3238    /// A pop-up `GtkPopoverMenu` (#247) over the view (the window's
3239    /// content), pointing at `at` or at the whole view (below it), removed
3240    /// once closed.
3241    fn show_menu(
3242        &mut self,
3243        view: Option<&View>,
3244        menu: &prism_core::menu::MenuSpec,
3245        at: Option<(f32, f32)>,
3246    ) {
3247        let parent = match view {
3248            Some(v) => v.widget(),
3249            None => self.root.clone().upcast(),
3250        };
3251        let model = crate::services::menu_model(&self.app, menu);
3252        let popover = gtk::PopoverMenu::from_model(Some(&model));
3253        popover.set_has_arrow(false);
3254        popover.set_parent(&parent);
3255        let rect = match at {
3256            Some((x, y)) => gdk::Rectangle::new(x as i32, y as i32, 1, 1),
3257            None => gdk::Rectangle::new(0, 0, parent.width(), parent.height()),
3258        };
3259        popover.set_pointing_to(Some(&rect));
3260        popover.set_position(gtk::PositionType::Bottom);
3261        popover.connect_closed(|p| {
3262            let p = p.clone();
3263            // After the chosen item's action.
3264            glib::idle_add_local_once(move || p.unparent());
3265        });
3266        glib::idle_add_local_once(move || popover.popup());
3267    }
3268
3269    fn set_swipe(&mut self, view: &View, left: bool, right: bool) {
3270        self.swipes.borrow_mut().insert(view.id(), (left, right));
3271    }
3272
3273    fn set_scroll_events(&mut self, view: &View, on: bool) {
3274        if on {
3275            self.scroll_events.borrow_mut().insert(view.id());
3276        } else {
3277            self.scroll_events.borrow_mut().remove(&view.id());
3278        }
3279    }
3280
3281    fn set_hidden(&mut self, view: &View, hidden: bool) {
3282        view.widget().set_visible(!hidden);
3283    }
3284
3285    /// Labels, buttons and fields report their first baseline from GTK's
3286    /// measure at the width they were given.
3287    fn baseline(&mut self, view: &View, width: f32, _height: f32) -> Option<f32> {
3288        let w = match view {
3289            View::Text(..)
3290            | View::Timer(..)
3291            | View::Image(..)
3292            | View::Button(..)
3293            | View::Input(..)
3294            | View::Picker(..)
3295            | View::DatePicker(..) => view.widget(),
3296            _ => return None,
3297        };
3298        let (_, _, _, natural) = w.measure(gtk::Orientation::Vertical, width.ceil() as i32);
3299        (natural >= 0).then_some(natural as f32)
3300    }
3301
3302    fn set_sticky(&mut self, view: &View, sticky: Option<(&View, prism_native::Sticky)>) {
3303        let id = view.id();
3304        let w = view.widget();
3305        let mut stickies = self.stickies.borrow_mut();
3306        for views in stickies.values_mut() {
3307            views.remove(&id);
3308        }
3309        match sticky {
3310            Some((View::Scroll(sid, sw, _), st)) => {
3311                stickies
3312                    .entry(*sid)
3313                    .or_default()
3314                    .insert(id, (w.clone(), st));
3315                drop(stickies);
3316                layout::set_sticky_offset(&w, Some(st.offset(sw.vadjustment().value() as f32)));
3317            }
3318            _ => {
3319                drop(stickies);
3320                layout::set_sticky_offset(&w, None);
3321            }
3322        }
3323    }
3324
3325    fn set_content_size(&mut self, view: &View, width: f32, height: f32) {
3326        match view {
3327            View::Scroll(_, _, content) => {
3328                content.set_size_request(width.ceil() as i32, height.ceil() as i32)
3329            }
3330            View::Overlay(_, o) => {
3331                o.set_size(width.ceil() as i32, height.ceil() as i32);
3332                o.show_if_pending();
3333            }
3334            _ => {}
3335        }
3336    }
3337
3338    // --- Pointer, keys, focus, layers, overlays (#17, #19, #25) ---------------
3339
3340    // --- Drag and drop between elements (#251) ---
3341
3342    fn window_origin(&mut self, view: &View) -> Option<(f32, f32)> {
3343        let p = view
3344            .widget()
3345            .compute_point(&self.root, &gtk::graphene::Point::new(0., 0.))?;
3346        Some((p.x(), p.y()))
3347    }
3348
3349    fn node_at(&mut self, x: f32, y: f32) -> Option<NodeId> {
3350        // The preview cannot be targeted: picking goes through it.
3351        let mut w = self.root.pick(x as f64, y as f64, gtk::PickFlags::DEFAULT);
3352        while let Some(widget) = w {
3353            if let Some(id) = node_of(&widget) {
3354                return Some(id);
3355            }
3356            w = widget.parent();
3357        }
3358        None
3359    }
3360
3361    fn scroll_offset(&mut self, view: &View) -> (f32, f32) {
3362        match view {
3363            View::Scroll(_, sw, _) => (
3364                sw.hadjustment().value() as f32,
3365                sw.vadjustment().value() as f32,
3366            ),
3367            _ => (0., 0.),
3368        }
3369    }
3370
3371    fn set_drag_preview(&mut self, view: &View, at: Option<(f32, f32)>) {
3372        let Some((x, y)) = at else {
3373            if let Some(p) = self.drag_preview.take() {
3374                layout::forget(&p);
3375                p.unparent();
3376            }
3377            return;
3378        };
3379        let (w, h) = self.sizes.get(&view.id()).copied().unwrap_or_default();
3380        let preview = self.drag_preview.get_or_insert_with(|| {
3381            let paintable = gtk::WidgetPaintable::new(Some(&view.widget()));
3382            let p = gtk::Picture::for_paintable(&paintable);
3383            p.set_can_target(false);
3384            p.set_opacity(0.85);
3385            p.add_css_class("prism-drag-preview");
3386            p
3387        });
3388        if preview.parent().is_none() {
3389            preview.set_parent(&self.root);
3390        }
3391        layout::set_frame(preview, rect(x, y, w, h));
3392    }
3393
3394    fn set_drop_hover(&mut self, view: &View, on: bool) {
3395        // GTK styles `drop_hover` as `:drop(active)`.
3396        let w = view.widget();
3397        if on {
3398            w.set_state_flags(gtk::StateFlags::DROP_ACTIVE, false);
3399        } else {
3400            w.unset_state_flags(gtk::StateFlags::DROP_ACTIVE);
3401        }
3402    }
3403
3404    fn set_drop_target(&mut self, view: &View, types: Option<&[String]>) {
3405        use prism_core::Interaction::DropHover;
3406        let id = view.id();
3407        let w = view.widget();
3408        if let Some(old) = self.drop_targets.remove(&id) {
3409            w.remove_controller(&old);
3410        }
3411        let Some(types) = types else { return };
3412        let accept = prism_core::PickFiles::new().types(types.to_vec());
3413        // Files from the file manager or another app (#111); GTK sets
3414        // `:drop(active)` while they are over it.
3415        let target = gtk::DropTarget::new(gdk::FileList::static_type(), gdk::DragAction::COPY);
3416        target.connect_enter(move |_, _, _| {
3417            report_state(id, DropHover, true);
3418            gdk::DragAction::COPY
3419        });
3420        target.connect_leave(move |_| report_state(id, DropHover, false));
3421        target.connect_drop(move |_, value, _, _| {
3422            report_state(id, DropHover, false);
3423            let Ok(list) = value.get::<gdk::FileList>() else {
3424                return false;
3425            };
3426            let paths: Vec<_> = list.files().iter().filter_map(|f| f.path()).collect();
3427            let accept = accept.clone();
3428            // Copying large files takes a while: off the main loop.
3429            glib::MainContext::default().spawn_local(async move {
3430                let copied = gio::spawn_blocking(move || {
3431                    paths
3432                        .into_iter()
3433                        .filter_map(crate::services::copy_picked_path)
3434                        .collect::<Vec<_>>()
3435                })
3436                .await
3437                .unwrap_or_default();
3438                let files: Vec<_> = copied
3439                    .into_iter()
3440                    .filter(|f| accept.accepts(&f.name, &f.mime))
3441                    .collect();
3442                if !files.is_empty() {
3443                    dispatch(UiEvent::DropFiles(id, files));
3444                }
3445            });
3446            true
3447        });
3448        w.add_controller(target.clone());
3449        self.drop_targets.insert(id, target);
3450    }
3451
3452    fn set_drag_delay(&mut self, view: &View, ms: u32) {
3453        // Read by the drag gesture when a touch goes down (#243).
3454        let mut delays = self.drag_delays.borrow_mut();
3455        if ms == 0 {
3456            delays.remove(&view.id());
3457        } else {
3458            delays.insert(view.id(), ms);
3459        }
3460    }
3461
3462    fn set_pointer_events(&mut self, view: &View, mask: u8) {
3463        use prism_core::events::pointer_mask::{DRAG_ANY, HOVER, MAGNIFY, MOVE, WHEEL};
3464        let id = view.id();
3465        self.pointer.borrow_mut().insert(id, mask);
3466        let w = view.widget();
3467        if mask & (HOVER | MOVE) != 0 && self.pointer_attached.insert((id, HOVER)) {
3468            let motion = gtk::EventControllerMotion::new();
3469            let masks = self.pointer.clone();
3470            let has = move |bits: u8| masks.borrow().get(&id).is_some_and(|m| m & bits != 0);
3471            let pointer = move |phase, x, y| {
3472                UiEvent::Pointer(
3473                    id,
3474                    prism_core::PointerEvent {
3475                        phase,
3476                        position: point(x, y),
3477                    },
3478                )
3479            };
3480            let h = has.clone();
3481            motion.connect_enter(move |_, x, y| {
3482                if h(HOVER | MOVE) {
3483                    dispatch(pointer(prism_core::PointerPhase::Enter, x, y));
3484                }
3485            });
3486            let h = has.clone();
3487            motion.connect_motion(move |_, x, y| {
3488                if h(MOVE) {
3489                    dispatch_latest(id, 0, pointer(prism_core::PointerPhase::Move, x, y));
3490                }
3491            });
3492            motion.connect_leave(move |_| {
3493                if has(HOVER | MOVE) {
3494                    dispatch(pointer(prism_core::PointerPhase::Leave, 0., 0.));
3495                }
3496            });
3497            w.add_controller(motion);
3498        }
3499        if mask & DRAG_ANY != 0 && self.pointer_attached.insert((id, DRAG_ANY)) {
3500            let drag = gtk::GestureDrag::new();
3501            // Any button; the element's `drag_buttons` pick (#136).
3502            drag.set_button(0);
3503            let masks = self.pointer.clone();
3504            // Where the pointer went down, with which button, and whether
3505            // the drag started.
3506            let state: Rc<Cell<Option<DragStart>>> = Rc::default();
3507            let threshold = gtk::Settings::default()
3508                .map_or(8, |s| s.gtk_dnd_drag_threshold())
3509                .max(1) as f64;
3510            let event = move |phase, d: DragStart, dx: f64, dy: f64| {
3511                UiEvent::Drag(
3512                    id,
3513                    prism_core::DragEvent {
3514                        phase,
3515                        start: point(d.at.0, d.at.1),
3516                        translation: point(dx, dy),
3517                        button: d.button,
3518                        modifiers: d.mods,
3519                    },
3520                )
3521            };
3522            // A touch on a node that drags after a long press (#243): the
3523            // lift waits for it, and the drag's offset while it waits.
3524            let lift: Rc<RefCell<Option<glib::SourceId>>> = Rc::default();
3525            let held_at: Rc<Cell<(f64, f64)>> = Rc::default();
3526            let unhold = {
3527                let lift = lift.clone();
3528                move || {
3529                    if let Some(source) = lift.borrow_mut().take() {
3530                        source.remove();
3531                    }
3532                }
3533            };
3534            let st = state.clone();
3535            let delays = self.drag_delays.clone();
3536            let (lf, held) = (lift.clone(), held_at.clone());
3537            let un = unhold.clone();
3538            drag.connect_drag_begin(move |g, x, y| {
3539                un();
3540                let button = drag_button(g.current_button());
3541                let on = masks
3542                    .borrow()
3543                    .get(&id)
3544                    .is_some_and(|m| m & button.drag_bit() != 0);
3545                // Fingers and pens hold first; a mouse drags on movement.
3546                let touch = g.device().is_some_and(|d| {
3547                    matches!(
3548                        d.source(),
3549                        gdk::InputSource::Touchscreen | gdk::InputSource::Pen
3550                    )
3551                });
3552                let delay = delays.borrow().get(&id).copied().filter(|_| touch);
3553                let d = DragStart {
3554                    at: (x, y),
3555                    button,
3556                    mods: modifiers(g.current_event_state()),
3557                    started: false,
3558                    holding: delay.is_some(),
3559                };
3560                st.set(on.then_some(d));
3561                let (Some(ms), true) = (delay, on) else {
3562                    return;
3563                };
3564                held.set((0., 0.));
3565                let (st, g, lift, held) = (st.clone(), g.downgrade(), lf.clone(), held.clone());
3566                let source = glib::timeout_add_local_once(
3567                    std::time::Duration::from_millis(ms.into()),
3568                    move || {
3569                        lift.borrow_mut().take();
3570                        let (Some(g), Some(d)) = (g.upgrade(), st.get()) else {
3571                            return;
3572                        };
3573                        if !d.holding {
3574                            return;
3575                        }
3576                        // Lifted: the scrolled window around it lets go.
3577                        g.set_state(gtk::EventSequenceState::Claimed);
3578                        let d = DragStart {
3579                            started: true,
3580                            holding: false,
3581                            ..d
3582                        };
3583                        st.set(Some(d));
3584                        let (dx, dy) = held.get();
3585                        dispatch(event(prism_core::DragPhase::Start, d, dx, dy));
3586                    },
3587                );
3588                *lf.borrow_mut() = Some(source);
3589            });
3590            let st = state.clone();
3591            let un = unhold.clone();
3592            drag.connect_drag_update(move |g, dx, dy| {
3593                let Some(mut d) = st.get() else {
3594                    return;
3595                };
3596                // The keys held now (#223), not only at the press.
3597                d.mods = modifiers(g.current_event_state());
3598                st.set(Some(d));
3599                if d.holding {
3600                    held_at.set((dx, dy));
3601                    if dx.hypot(dy) >= threshold {
3602                        // Moved before the long press: a scroll.
3603                        un();
3604                        st.set(None);
3605                        g.set_state(gtk::EventSequenceState::Denied);
3606                    }
3607                    return;
3608                }
3609                if !d.started {
3610                    if dx.hypot(dy) < threshold {
3611                        return;
3612                    }
3613                    // A drag, not a click: the click gestures (and the
3614                    // middle button's paste, the secondary's menu) stop here.
3615                    g.set_state(gtk::EventSequenceState::Claimed);
3616                    let d = DragStart { started: true, ..d };
3617                    st.set(Some(d));
3618                    dispatch(event(prism_core::DragPhase::Start, d, dx, dy));
3619                    return;
3620                }
3621                dispatch_latest(id, 1, event(prism_core::DragPhase::Move, d, dx, dy));
3622            });
3623            let st = state.clone();
3624            let un = unhold.clone();
3625            drag.connect_drag_end(move |_, dx, dy| {
3626                un();
3627                if let Some(d) = st.take().filter(|d| d.started) {
3628                    dispatch(event(prism_core::DragPhase::End, d, dx, dy));
3629                }
3630            });
3631            drag.connect_cancel(move |_, _| {
3632                unhold();
3633                if let Some(d) = state.take().filter(|d| d.started) {
3634                    dispatch(event(prism_core::DragPhase::Cancel, d, 0., 0.));
3635                }
3636            });
3637            w.add_controller(drag);
3638        }
3639        // Middle, back and forward clicks (#215).
3640        let aux = prism_core::events::pointer_mask::AUX_CLICK;
3641        if mask & aux != 0 && self.pointer_attached.insert((id, aux)) {
3642            let click = gtk::GestureClick::new();
3643            click.set_button(0);
3644            let masks = self.pointer.clone();
3645            click.connect_released(move |g, n, x, y| {
3646                let button = match g.current_button() {
3647                    2 => prism_core::PointerButton::Middle,
3648                    8 => prism_core::PointerButton::BACK,
3649                    9 => prism_core::PointerButton::FORWARD,
3650                    _ => return,
3651                };
3652                if !masks.borrow().get(&id).is_some_and(|m| m & aux != 0) {
3653                    return;
3654                }
3655                g.set_state(gtk::EventSequenceState::Claimed);
3656                dispatch(UiEvent::AuxClick(
3657                    id,
3658                    prism_core::ClickEvent {
3659                        position: Some(point(x, y)),
3660                        modifiers: modifiers(g.current_event_state()),
3661                        count: n.max(1) as u32,
3662                        button,
3663                        text_offset: None,
3664                    },
3665                ));
3666            });
3667            w.add_controller(click);
3668        }
3669        if mask & WHEEL != 0 && self.pointer_attached.insert((id, WHEEL)) {
3670            // Wheels and touchpads (#133): the element takes the scrolling.
3671            let scroll =
3672                gtk::EventControllerScroll::new(gtk::EventControllerScrollFlags::BOTH_AXES);
3673            let masks = self.pointer.clone();
3674            let on = move || masks.borrow().get(&id).is_some_and(|m| m & WHEEL != 0);
3675            // A touchpad's gesture: between `scroll-begin` and `scroll-end`.
3676            let gesture: Rc<Cell<Option<bool>>> = Rc::default();
3677            let g = gesture.clone();
3678            scroll.connect_scroll_begin(move |_| g.set(Some(false)));
3679            let (g, on2) = (gesture.clone(), on.clone());
3680            scroll.connect_scroll_end(move |c| {
3681                if g.take() == Some(true) && on2() {
3682                    dispatch(wheel_event(id, c, 0., 0., prism_core::GesturePhase::End));
3683                }
3684            });
3685            scroll.connect_scroll(move |c, dx, dy| {
3686                if !on() {
3687                    return glib::Propagation::Proceed;
3688                }
3689                let phase = match gesture.get() {
3690                    None => prism_core::GesturePhase::None,
3691                    Some(false) => {
3692                        gesture.set(Some(true));
3693                        prism_core::GesturePhase::Start
3694                    }
3695                    Some(true) => prism_core::GesturePhase::Move,
3696                };
3697                dispatch(wheel_event(id, c, dx, dy, phase));
3698                glib::Propagation::Stop
3699            });
3700            w.add_controller(scroll);
3701        }
3702        if mask & MAGNIFY != 0 && self.pointer_attached.insert((id, MAGNIFY)) {
3703            // Pinches (#133): touchscreens and touchpads. GTK gives the scale
3704            // since the gesture began; Prism the change since the last event.
3705            let zoom = gtk::GestureZoom::new();
3706            let masks = self.pointer.clone();
3707            let last = Rc::new(Cell::new(1.));
3708            let event = move |g: &gtk::GestureZoom, scale: f64, phase| {
3709                let (x, y) = g.bounding_box_center().unwrap_or_default();
3710                UiEvent::Magnify(
3711                    id,
3712                    prism_core::MagnifyEvent {
3713                        scale: scale.max(0.01) as f32,
3714                        position: point(x, y),
3715                        phase,
3716                    },
3717                )
3718            };
3719            let l = last.clone();
3720            zoom.connect_begin(move |g, _| {
3721                if !masks.borrow().get(&id).is_some_and(|m| m & MAGNIFY != 0) {
3722                    g.set_state(gtk::EventSequenceState::Denied);
3723                    return;
3724                }
3725                l.set(1.);
3726                dispatch(event(g, 1., prism_core::GesturePhase::Start));
3727            });
3728            let l = last.clone();
3729            zoom.connect_scale_changed(move |g, now| {
3730                let ratio = now / l.replace(now).max(0.01);
3731                dispatch(event(g, ratio, prism_core::GesturePhase::Move));
3732            });
3733            zoom.connect_end(move |g, _| {
3734                dispatch(event(g, 1., prism_core::GesturePhase::End));
3735            });
3736            w.add_controller(zoom);
3737        }
3738    }
3739
3740    /// Text field selections (#86), in characters like GTK.
3741    fn set_selection(&mut self, view: &View, start: usize, end: usize) {
3742        match view {
3743            View::Input(id, e) => {
3744                let len = e.text().chars().count();
3745                e.select_region(start.min(len) as i32, end.min(len) as i32);
3746                APP_SELECTED.with(|s| s.borrow_mut().insert(*id));
3747            }
3748            View::TextArea(_, t) => t.select(start, end),
3749            _ => {}
3750        }
3751    }
3752
3753    /// Other people's carets (#240): text areas and rich inputs (a GTK
3754    /// entry has no layout to draw them with).
3755    fn set_remote_carets(&mut self, view: &View, carets: &[prism_core::RemoteCaret]) {
3756        if let View::TextArea(id, t) = view {
3757            crate::carets::set(*id, t, carets);
3758        }
3759    }
3760
3761    fn set_selection_highlight(&mut self, view: &View, start: usize, end: usize) {
3762        // Text areas and rich inputs with a text tag, an entry with a
3763        // background attribute (#231).
3764        match view {
3765            View::TextArea(_, t) => t.highlight(start, end),
3766            View::Input(_, e) => crate::across::highlight_entry(e, start, end),
3767            _ => {}
3768        }
3769    }
3770
3771    fn set_select_events(&mut self, view: &View, on: bool) {
3772        let id = view.id();
3773        if on {
3774            SELECT_EVENTS.with(|s| s.borrow_mut().insert(id));
3775        } else {
3776            forget_selection(id);
3777        }
3778    }
3779
3780    /// Rich inputs edit their runs as tags and chips (#115, `crate::rich`).
3781    fn rich_input(&self) -> bool {
3782        true
3783    }
3784
3785    fn set_rich_value(&mut self, view: &View, runs: &str) {
3786        if let View::TextArea(id, _) = view {
3787            crate::rich::set_runs(*id, runs);
3788        }
3789    }
3790
3791    /// A rich input's editing hooks (#217, `crate::edit`): its text area.
3792    fn set_edit_events(&mut self, view: &View, mask: u8) {
3793        if let View::TextArea(id, t) = view {
3794            crate::edit::set_mask(*id, t, mask);
3795        }
3796    }
3797
3798    fn write_clipboard(&mut self, view: &View, content: &prism_core::ClipboardContent) {
3799        if let View::TextArea(_, t) = view {
3800            crate::edit::write_clipboard(&t.view, content);
3801        }
3802    }
3803
3804    fn insert_text(&mut self, view: &View, text: &str) {
3805        if let View::TextArea(_, t) = view {
3806            crate::edit::insert_text(&t.view, text);
3807        }
3808    }
3809
3810    fn set_key_events(&mut self, view: &View, local: bool, global: bool) {
3811        let id = view.id();
3812        let set = |s: &RefCell<HashSet<NodeId>>, on: bool| {
3813            if on {
3814                s.borrow_mut().insert(id);
3815            } else {
3816                s.borrow_mut().remove(&id);
3817            }
3818        };
3819        set(&self.keys.local, local);
3820        set(&self.keys.global, global);
3821        // A view listening to keys can take the focus (Tab, a click), as
3822        // can a drawn control.
3823        if let View::Container(_, _, c) = view {
3824            c.set_focusable(local || self.pressable.contains(&id));
3825            if local {
3826                c.add_css_class(layout::FOCUSABLE);
3827                let focus = gtk::GestureClick::new();
3828                let weak = c.downgrade();
3829                focus.connect_pressed(move |_, _, _, _| {
3830                    if let Some(c) = weak.upgrade()
3831                        && c.is_focusable()
3832                    {
3833                        c.grab_focus();
3834                    }
3835                });
3836                if self.pointer_attached.insert((id, 8)) {
3837                    c.add_controller(focus);
3838                }
3839            } else if !self.pressable.contains(&id) {
3840                c.remove_css_class(layout::FOCUSABLE);
3841            }
3842        }
3843    }
3844
3845    fn focus(&mut self, view: &View) {
3846        let target: gtk::Widget = match view {
3847            View::Input(_, e) => e.clone().upcast(),
3848            View::TextArea(_, t) => t.view.clone().upcast(),
3849            View::Picker(_, p) => p.dropdown.clone().upcast(),
3850            View::DatePicker(_, p) => p.button.clone().upcast(),
3851            View::Radio(_, r) => r
3852                .root
3853                .first_child()
3854                .unwrap_or_else(|| r.root.clone().upcast()),
3855            other => other.widget(),
3856        };
3857        if target.is::<gtk::Box>() && !target.is_focusable() {
3858            target.set_focusable(true);
3859        }
3860        // An entry keeps the selection the app gave it (#86).
3861        let keep = match view {
3862            View::Input(id, _) => APP_SELECTED.with(|s| s.borrow().contains(id)),
3863            _ => false,
3864        };
3865        // After the layout pass: a new widget is not mapped yet.
3866        glib::idle_add_local_once(move || match target.downcast_ref::<gtk::Entry>() {
3867            Some(e) if keep => {
3868                e.grab_focus_without_selecting();
3869            }
3870            _ => {
3871                target.grab_focus();
3872            }
3873        });
3874    }
3875
3876    /// The window keeps the focus but no widget has it (an on-screen
3877    /// keyboard hides); sheets are their own windows.
3878    fn dismiss_keyboard(&mut self) {
3879        let windows: Vec<gtk::Window> = gtk::Window::list_toplevels()
3880            .into_iter()
3881            .filter_map(|w| w.downcast::<gtk::Window>().ok())
3882            .filter(|w| w.is_active())
3883            .chain(std::iter::once(self.window.clone().upcast()))
3884            .collect();
3885        glib::idle_add_local_once(move || {
3886            for w in windows {
3887                GtkWindowExt::set_focus(&w, None::<&gtk::Widget>);
3888            }
3889        });
3890    }
3891
3892    /// Scrolls every scroll view around the widget so its frame is visible.
3893    /// `cx.scroll_by` / `cx.scroll_to` (#193): the scrolled window's
3894    /// adjustments, kept within the content.
3895    fn scroll_to(&mut self, view: &View, x: f32, y: f32, relative: bool, _animated: bool) {
3896        let View::Scroll(_, sw, _) = view else {
3897            return;
3898        };
3899        for (adj, v) in [(sw.hadjustment(), x as f64), (sw.vadjustment(), y as f64)] {
3900            let target = if relative { adj.value() + v } else { v };
3901            let max = (adj.upper() - adj.page_size()).max(adj.lower());
3902            let target = if target.is_nan() {
3903                adj.lower()
3904            } else {
3905                target.clamp(adj.lower(), max)
3906            };
3907            adj.set_value(target);
3908        }
3909    }
3910
3911    fn scroll_into_view(&mut self, view: &View) {
3912        let mut w = view.widget();
3913        loop {
3914            // Offset of `w` inside the scroll view's content, from the
3915            // frames Prism gave each widget on the way up.
3916            let (mut y, h) = layout::frame_of(&w).map_or((0, 0), |f| (f.1, f.3));
3917            let mut up = w.parent();
3918            let sw = loop {
3919                let Some(p) = up else { return };
3920                if let Some(sw) = p.downcast_ref::<gtk::ScrolledWindow>() {
3921                    break sw.clone();
3922                }
3923                if !p.is::<gtk::Viewport>() {
3924                    y += layout::frame_of(&p).map_or(0, |f| f.1);
3925                }
3926                up = p.parent();
3927            };
3928            let adj = sw.vadjustment();
3929            let (top, bottom) = (f64::from(y) - 12., f64::from(y + h) + 12.);
3930            let (value, page) = (adj.value(), adj.page_size());
3931            // The adjustment clamps to its range.
3932            if top < value || bottom - top > page {
3933                adj.set_value(top);
3934            } else if bottom > value + page {
3935                adj.set_value(bottom - page);
3936            }
3937            w = sw.upcast();
3938        }
3939    }
3940
3941    /// Layers are the last children of the window's root container (drawn
3942    /// above it); they let input through where they have no child.
3943    fn set_layers(&mut self, layers: &[View]) {
3944        let next: Vec<gtk::Widget> = layers.iter().map(View::widget).collect();
3945        for old in &self.layers {
3946            if !next.contains(old)
3947                && old.parent().as_ref() == Some(self.root.upcast_ref::<gtk::Widget>())
3948            {
3949                old.remove_css_class(layout::PASS_THROUGH);
3950                old.unparent();
3951            }
3952        }
3953        self.layers = next;
3954        for l in &self.layers {
3955            l.add_css_class(layout::PASS_THROUGH);
3956        }
3957        self.raise_layers();
3958    }
3959
3960    /// A popover gets a phone-like width; dialogs and sheets fit the
3961    /// window (a sheet fills its height, or half of it).
3962    fn overlay_viewport(&mut self, overlay: &View, _content: &View) -> Viewport {
3963        use prism_core::OverlayKind;
3964        let (w, h) = self.size;
3965        let config = match overlay {
3966            View::Overlay(_, o) => o.config.get(),
3967            _ => Default::default(),
3968        };
3969        let (width, height) = match config.kind {
3970            OverlayKind::Popover => ((w - 32.).clamp(120., 360.), (h * 0.8).max(120.)),
3971            OverlayKind::Dialog => ((w - 48.).clamp(200., 480.), (h - 80.).max(160.)),
3972            OverlayKind::Sheet if config.medium => (w.min(560.), (h * 0.5).max(200.)),
3973            OverlayKind::Sheet => (w.min(560.), (h - 48.).max(200.)),
3974            // No on-screen keyboard: left out of Linux trees (#242).
3975            OverlayKind::Keyboard => (w, 0.),
3976        };
3977        Viewport {
3978            x: 0.,
3979            y: 0.,
3980            width,
3981            height,
3982            insets: Insets::default(),
3983        }
3984    }
3985
3986    fn set_appearance(&mut self, appearance: Appearance) {
3987        let dark = match appearance {
3988            Appearance::Dark => true,
3989            Appearance::Light => false,
3990            Appearance::System => self.dark,
3991        };
3992        if let Some(settings) = gtk::Settings::default() {
3993            settings.set_gtk_application_prefer_dark_theme(dark);
3994        }
3995        let changed = self.dark != dark;
3996        self.dark = dark;
3997        SHAPE_DARK.with(|d| d.set(dark));
3998        // Backgrounds, borders, shadows, gradients: CSS rules of the
3999        // light or the dark variant.
4000        if changed {
4001            let adaptive: Vec<(View, Style)> = self.adaptive.values().cloned().collect();
4002            for (view, style) in adaptive {
4003                self.set_style(&view, &style);
4004            }
4005        }
4006        // Run colors are Pango attributes: the light or the dark variant.
4007        for state in self.labels.values() {
4008            if let Some(l) = &state.label {
4009                text::apply(l, state, dark);
4010            }
4011        }
4012        crate::rich::restyle_all();
4013        for area in self.shapes.values() {
4014            area.queue_draw();
4015        }
4016        for area in self.scenes.values() {
4017            area.queue_render();
4018        }
4019    }
4020}
4021
4022/// The GTK role of a container that has Prism role `role` (`None`: GTK's
4023/// own, a plain layout box). A role GTK 4.8 lacks maps to the closest one.
4024fn container_role(role: prism_core::Role) -> Option<gtk::AccessibleRole> {
4025    use gtk::AccessibleRole as G;
4026    use prism_core::Role as P;
4027    Some(match role {
4028        P::Button => G::Button,
4029        P::Link => G::Link,
4030        P::Heading(_) => G::Heading,
4031        P::Image => G::Img,
4032        P::Group => G::Group,
4033        P::List => G::List,
4034        P::ListItem => G::ListItem,
4035        P::Switch => G::Switch,
4036        P::Checkbox => G::Checkbox,
4037        P::Tab => G::Tab,
4038        P::TabList => G::TabList,
4039        P::TabPanel => G::TabPanel,
4040        P::Navigation => G::Navigation,
4041        P::Main => G::Main,
4042        P::Alert => G::Alert,
4043        P::ProgressBar => G::ProgressBar,
4044        P::Slider => G::Slider,
4045        P::ComboBox => G::ComboBox,
4046        P::Status => G::Status,
4047        P::Radio => G::Radio,
4048        P::RadioGroup => G::RadioGroup,
4049        P::Dialog => G::Dialog,
4050        P::Table => G::Table,
4051        P::Row => G::Row,
4052        P::ColumnHeader => G::ColumnHeader,
4053        P::Cell => G::Cell,
4054        P::Text => return None,
4055    })
4056}
4057
4058/// `GtkAccessibleProperty` values (gtkenums.h, counted from 0).
4059pub(crate) mod a11y_property {
4060    pub const DESCRIPTION: i32 = 1;
4061    pub const LABEL: i32 = 4;
4062    pub const LEVEL: i32 = 5;
4063    pub const PLACEHOLDER: i32 = 10;
4064    pub const VALUE_TEXT: i32 = 18;
4065}
4066
4067unsafe extern "C" {
4068    /// gtkaccessible.h, `GDK_AVAILABLE_IN_ALL` (gtk-rs only binds it from 4.10).
4069    fn gtk_accessible_update_property_value(
4070        accessible: *mut std::ffi::c_void,
4071        n_properties: std::ffi::c_int,
4072        properties: *const i32,
4073        values: *const gtk::glib::gobject_ffi::GValue,
4074    );
4075}
4076
4077/// Sets a string accessible property of `w` (see [`a11y_property`]). A
4078/// label is Prism's: GTK before 4.12 reads it in its parents' names
4079/// (`names.rs`).
4080pub(crate) fn set_accessible_string(w: &impl IsA<gtk::Widget>, property: i32, text: &str) {
4081    if property == a11y_property::LABEL {
4082        crate::names::set_label(w.as_ref(), text);
4083    }
4084    update_string(w.as_ref(), property, text);
4085}
4086
4087/// Sets a string accessible property of any accessible: a widget, a stack
4088/// page (both implement GtkAccessible; gtk-rs's `Accessible` needs 4.10).
4089pub(crate) fn update_string(acc: &impl IsA<glib::Object>, property: i32, text: &str) {
4090    use gtk::glib::translate::{ToGlibPtr, ToGlibPtrMut};
4091    debug_assert!(acc.is::<gtk::Widget>() || acc.is::<gtk::StackPage>());
4092    let mut value = text.to_value();
4093    let accessible: *mut glib::gobject_ffi::GObject = acc.as_ref().to_glib_none().0;
4094    // SAFETY: a live GtkAccessible (above); one string property.
4095    unsafe {
4096        gtk_accessible_update_property_value(
4097            accessible.cast(),
4098            1,
4099            &property,
4100            value.to_glib_none_mut().0,
4101        );
4102    }
4103}
4104
4105/// Sets an integer accessible property of `w` (a heading's level).
4106fn set_accessible_int(w: &impl IsA<gtk::Widget>, property: i32, n: i32) {
4107    use gtk::glib::translate::{ToGlibPtr, ToGlibPtrMut};
4108    let mut value = n.to_value();
4109    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4110    // SAFETY: every GtkWidget implements GtkAccessible; one integer property.
4111    unsafe {
4112        gtk_accessible_update_property_value(
4113            widget.cast(),
4114            1,
4115            &property,
4116            value.to_glib_none_mut().0,
4117        );
4118    }
4119}
4120
4121/// `GtkAccessibleState` values (gtkenums.h, counted from 0).
4122pub(crate) mod a11y_state {
4123    pub const DISABLED: i32 = 2;
4124    pub const PRESSED: i32 = 6;
4125    pub const SELECTED: i32 = 7;
4126}
4127
4128/// `GTK_ACCESSIBLE_STATE_DISABLED`: `w` is unavailable (not "sensitive").
4129fn set_accessible_disabled(w: &impl IsA<gtk::Widget>) {
4130    use gtk::glib::translate::{ToGlibPtr, ToGlibPtrMut};
4131    let mut value = true.to_value();
4132    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4133    // SAFETY: every GtkWidget implements GtkAccessible; one boolean state.
4134    unsafe {
4135        gtk_accessible_update_state_value(
4136            widget.cast(),
4137            1,
4138            &a11y_state::DISABLED,
4139            value.to_glib_none_mut().0,
4140        );
4141    }
4142}
4143
4144/// Removes an accessible state of `w`.
4145fn reset_accessible_state(w: &impl IsA<gtk::Widget>, state: i32) {
4146    use gtk::glib::translate::ToGlibPtr;
4147    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4148    // SAFETY: every GtkWidget implements GtkAccessible.
4149    unsafe { gtk_accessible_reset_state(widget.cast(), state) };
4150}
4151
4152/// Removes an accessible property of `w` (GTK's own value again).
4153pub(crate) fn reset_accessible_property(w: &impl IsA<gtk::Widget>, property: i32) {
4154    use gtk::glib::translate::ToGlibPtr;
4155    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4156    // SAFETY: every GtkWidget implements GtkAccessible.
4157    unsafe { gtk_accessible_reset_property(widget.cast(), property) };
4158}
4159
4160unsafe extern "C" {
4161    /// gtkaccessible.h, `GDK_AVAILABLE_IN_ALL` (gtk-rs binds it from 4.10).
4162    fn gtk_accessible_reset_property(accessible: *mut std::ffi::c_void, property: i32);
4163    fn gtk_accessible_reset_state(accessible: *mut std::ffi::c_void, state: i32);
4164}
4165
4166unsafe extern "C" {
4167    /// gtkaccessible.h, `GDK_AVAILABLE_IN_ALL` (gtk-rs binds it from 4.10).
4168    fn gtk_accessible_update_state_value(
4169        accessible: *mut std::ffi::c_void,
4170        n_states: std::ffi::c_int,
4171        states: *const i32,
4172        values: *const gtk::glib::gobject_ffi::GValue,
4173    );
4174}
4175
4176/// `GTK_ACCESSIBLE_STATE_HIDDEN` (gtkenums.h): out of the accessibility
4177/// tree (inert subtrees).
4178pub(crate) fn set_accessible_hidden(w: &impl IsA<gtk::Widget>, hidden: bool) {
4179    use gtk::glib::translate::{ToGlibPtr, ToGlibPtrMut};
4180    const HIDDEN: i32 = 4;
4181    crate::names::set_hidden(w.as_ref(), hidden);
4182    let mut value = hidden.to_value();
4183    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4184    // SAFETY: every GtkWidget implements GtkAccessible; one boolean state.
4185    unsafe {
4186        gtk_accessible_update_state_value(widget.cast(), 1, &HIDDEN, value.to_glib_none_mut().0);
4187    }
4188}
4189
4190/// `GTK_ACCESSIBLE_STATE_CHECKED` (gtkenums.h): a radio, checkbox or switch
4191/// drawn by the app is on (a `GtkAccessibleTristate`).
4192fn set_accessible_checked(w: &impl IsA<gtk::Widget>, checked: bool) {
4193    use gtk::glib::translate::{IntoGlib, ToGlibPtr, ToGlibPtrMut};
4194    const CHECKED: i32 = 1;
4195    let state = if checked {
4196        gtk::AccessibleTristate::True
4197    } else {
4198        gtk::AccessibleTristate::False
4199    };
4200    // GTK reads the tristate as an int: an enum value makes it log a
4201    // critical.
4202    let mut value = state.into_glib().to_value();
4203    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4204    // SAFETY: every GtkWidget implements GtkAccessible; one tristate state.
4205    unsafe {
4206        gtk_accessible_update_state_value(widget.cast(), 1, &CHECKED, value.to_glib_none_mut().0);
4207    }
4208}
4209
4210/// `GTK_ACCESSIBLE_STATE_SELECTED` (gtkenums.h): a selected item.
4211pub(crate) fn set_accessible_selected(w: &impl IsA<gtk::Widget>, selected: bool) {
4212    use gtk::glib::translate::{ToGlibPtr, ToGlibPtrMut};
4213    const SELECTED: i32 = 7;
4214    // A « boolean or undefined » state is read as an int (-1 being
4215    // undefined): a boolean value makes GTK log a critical.
4216    let mut value = i32::from(selected).to_value();
4217    let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4218    // SAFETY: every GtkWidget implements GtkAccessible; one int state.
4219    unsafe {
4220        gtk_accessible_update_state_value(widget.cast(), 1, &SELECTED, value.to_glib_none_mut().0);
4221    }
4222}
4223
4224/// What screen readers say for `w`.
4225fn set_accessible_label(w: &gtk::Widget, label: &str) {
4226    set_accessible_string(w, a11y_property::LABEL, label);
4227}
4228
4229// ---------------------------------------------------------------------------
4230// Entry point
4231// ---------------------------------------------------------------------------
4232
4233fn data_dir(title: &str) -> std::path::PathBuf {
4234    let base = std::env::var_os("XDG_DATA_HOME")
4235        .map(std::path::PathBuf::from)
4236        .or_else(|| std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".local/share")))
4237        .unwrap_or_else(|| ".".into());
4238    base.join(title.replace('/', "-"))
4239}
4240
4241/// Active, inactive (another window focused) or background (minimized).
4242fn report_lifecycle(window: &gtk::ApplicationWindow) {
4243    let minimized = window
4244        .surface()
4245        .and_downcast::<gdk::Toplevel>()
4246        .is_some_and(|t| t.state().contains(gdk::ToplevelState::MINIMIZED));
4247    let phase = if minimized {
4248        prism_core::Lifecycle::Background
4249    } else if window.is_active() {
4250        prism_core::Lifecycle::Active
4251    } else {
4252        prism_core::Lifecycle::Inactive
4253    };
4254    with_state(|s| {
4255        let patches = s.runtime.set_lifecycle(phase);
4256        commit(s, patches);
4257    });
4258}
4259
4260/// Locale, text size (GNOME's text scaling factor, else the font DPI over
4261/// the 96 default) and reduced motion (animations off).
4262fn environment() -> prism_core::Environment {
4263    let settings = gtk::Settings::default();
4264    let gnome = gio::SettingsSchemaSource::default()
4265        .and_then(|src| src.lookup("org.gnome.desktop.interface", true))
4266        .filter(|schema| schema.has_key("text-scaling-factor"))
4267        .map(|_| gio::Settings::new("org.gnome.desktop.interface"));
4268    let text_scale = gnome
4269        .map(|g| g.double("text-scaling-factor"))
4270        .filter(|f| *f > 0.)
4271        .or_else(|| {
4272            settings
4273                .as_ref()
4274                .map(|s| s.gtk_xft_dpi())
4275                .filter(|dpi| *dpi > 0)
4276                .map(|dpi| dpi as f64 / 1024. / 96.)
4277        })
4278        .unwrap_or(1.);
4279    let text_scale = std::env::var("PRISM_TEXT_SCALE")
4280        .ok()
4281        .and_then(|s| s.parse().ok())
4282        .unwrap_or(text_scale as f32);
4283    prism_core::Environment {
4284        locale: locale(),
4285        text_scale,
4286        reduce_motion: settings.is_some_and(|s| !s.is_gtk_enable_animations()),
4287        ..Default::default()
4288    }
4289}
4290
4291fn environment_changed() {
4292    with_state(|s| {
4293        s.runtime.app.set_environment(environment());
4294        let patches = s.runtime.poll();
4295        commit(s, patches);
4296    });
4297}
4298
4299fn locale() -> prism_core::Locale {
4300    let lang = std::env::var("PRISM_LOCALE")
4301        .or_else(|_| std::env::var("LC_ALL"))
4302        .or_else(|_| std::env::var("LANG"))
4303        .unwrap_or_default();
4304    let tag = lang
4305        .split(['.', '@'])
4306        .next()
4307        .unwrap_or("")
4308        .replace('_', "-");
4309    prism_core::Locale::new(if tag.is_empty() || tag == "C" || tag == "POSIX" {
4310        "en"
4311    } else {
4312        &tag
4313    })
4314}
4315
4316/// `VERSION_ID` from /etc/os-release.
4317fn os_version() -> prism_core::Version {
4318    std::fs::read_to_string("/etc/os-release")
4319        .ok()
4320        .and_then(|s| {
4321            s.lines()
4322                .find_map(|l| l.strip_prefix("VERSION_ID="))
4323                .map(|v| prism_core::Version::parse(v.trim_matches('"')))
4324        })
4325        .unwrap_or_default()
4326}
4327
4328fn device_info(window: &gtk::ApplicationWindow) -> prism_core::DeviceInfo {
4329    let mut info = prism_core::DeviceInfo::guess(prism_core::Platform::Linux, (0., 0.));
4330    info.os.version = os_version();
4331    if let Some(display) = gdk::Display::default()
4332        && let Some(monitor) = window
4333            .surface()
4334            .and_then(|s| display.monitor_at_surface(&s))
4335            .or_else(|| display.monitors().item(0).and_downcast::<gdk::Monitor>())
4336    {
4337        let g = monitor.geometry();
4338        let (w, h) = (g.width() as f32, g.height() as f32);
4339        let (mm_w, mm_h) = (monitor.width_mm() as f32, monitor.height_mm() as f32);
4340        let diagonal = ((mm_w * mm_w + mm_h * mm_h).sqrt() / 25.4 * 10.).round() / 10.;
4341        info.orientation = prism_core::Orientation::of(w, h);
4342        info.screen = prism_core::ScreenInfo {
4343            width: w,
4344            height: h,
4345            scale: monitor.scale_factor() as f32,
4346            diagonal: (diagonal > 1.).then_some(diagonal),
4347            refresh_rate: (monitor.refresh_rate() > 0)
4348                .then(|| monitor.refresh_rate() as f32 / 1000.),
4349            ..Default::default()
4350        };
4351    }
4352    info
4353}
4354
4355/// Opens a window and runs the GTK main loop.
4356pub fn run(config: AppConfig, init: AppInit) {
4357    // App fonts, before GTK creates Pango's font map.
4358    let assets: Option<std::path::PathBuf> = std::env::var("PRISM_ASSETS_DIR")
4359        .ok()
4360        .or_else(|| config.assets.clone())
4361        .map(Into::into);
4362    text::register_fonts(assets.as_deref(), &config.embedded_assets);
4363    let _ = APP.set((config, init));
4364    // Installed packages set PRISM_APP_ID (the .desktop file's name), so
4365    // desktops match the window to its launcher and icon.
4366    let id = std::env::var("PRISM_APP_ID")
4367        .ok()
4368        .filter(|id| gtk::gio::Application::id_is_valid(id))
4369        .unwrap_or_else(|| "dev.prism.app".into());
4370    let app = gtk::Application::builder()
4371        .application_id(id)
4372        .flags(gtk::gio::ApplicationFlags::NON_UNIQUE)
4373        .build();
4374    app.connect_activate(activate);
4375    app.run_with_args::<&str>(&[]);
4376}
4377
4378fn activate(app: &gtk::Application) {
4379    let (config, init) = APP.get().expect("prism-linux: run() was not called");
4380    let (width, height) = std::env::var("PRISM_WINDOW")
4381        .ok()
4382        .and_then(|s| {
4383            let (w, h) = s.split_once('x')?;
4384            Some((w.parse().ok()?, h.parse().ok()?))
4385        })
4386        .unwrap_or((config.width as i32, config.height as i32));
4387    let window = gtk::ApplicationWindow::builder()
4388        .application(app)
4389        .title(&config.title)
4390        .default_width(width)
4391        .default_height(height)
4392        .build();
4393    let root = layout::container();
4394    window.set_child(Some(&root));
4395    // With unsaved changes, closing asks first (#158).
4396    window.connect_close_request(|w| {
4397        if !UNSAVED.get() {
4398            return glib::Propagation::Proceed;
4399        }
4400        confirm_leave(w);
4401        glib::Propagation::Stop
4402    });
4403
4404    // Clickable texts take the keyboard focus (GTK's labels only do with
4405    // links or a selection).
4406    layout::focusable_labels();
4407    let css = gtk::CssProvider::new();
4408    let base = gtk::CssProvider::new();
4409    #[allow(deprecated)]
4410    base.load_from_data(
4411        ".prism-header{padding:0 8px;border-bottom:1px solid alpha(currentColor,0.15);}\
4412         .prism-tabbar{padding:6px;border-top:1px solid alpha(currentColor,0.15);}\
4413         .prism-keys:focus-visible{outline:2px solid alpha(currentColor,0.55);outline-offset:2px;}\
4414         popover.prism-bare,popover.prism-bare>contents,window.prism-bare{background:none;border:none;border-radius:0;box-shadow:none;padding:0;}",
4415    );
4416    if let Some(display) = gdk::Display::default() {
4417        gtk::style_context_add_provider_for_display(
4418            &display,
4419            &base,
4420            gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
4421        );
4422        gtk::style_context_add_provider_for_display(
4423            &display,
4424            &css,
4425            gtk::STYLE_PROVIDER_PRIORITY_APPLICATION + 1,
4426        );
4427    }
4428    let dark = gtk::Settings::default().is_some_and(|s| s.is_gtk_application_prefer_dark_theme());
4429    SHAPE_DARK.with(|d| d.set(dark));
4430
4431    let data = data_dir(&config.title);
4432    let services = crate::services::LinuxServices::new(app.clone(), window.clone(), data.clone());
4433    // Notification clicks and buttons: (id, action, link).
4434    let respond = gio::SimpleAction::new(
4435        "prism-notification",
4436        Some(glib::VariantTy::new("(sss)").expect("type")),
4437    );
4438    respond.connect_activate(|_, param| {
4439        let Some((id, action, link)) = param.and_then(|p| p.get::<(String, String, String)>())
4440        else {
4441            return;
4442        };
4443        let response = prism_core::NotificationResponse {
4444            id,
4445            action: (!action.is_empty()).then_some(action),
4446            text: None,
4447        };
4448        let link = (!link.is_empty()).then_some(link);
4449        glib::idle_add_local_once(move || {
4450            with_state(|s| {
4451                let patches = s.runtime.notification_response(response, link);
4452                commit(s, patches);
4453            })
4454        });
4455    });
4456    app.add_action(&respond);
4457    let runtime = Runtime::with_options(
4458        init,
4459        prism_core::RuntimeOptions {
4460            path: std::env::var("PRISM_PATH").unwrap_or_else(|_| "/".into()),
4461            storage: Some(Box::new(prism_core::FileStorage::new(data.clone()))),
4462            // Queued, not `invoke`d: on the UI thread `invoke` would run
4463            // `poll` right away, nested in the update that woke it (#57).
4464            wake_ui: Some(std::sync::Arc::new(|| {
4465                glib::idle_add_once(poll);
4466            })),
4467            capabilities: prism_core::PlatformServices::capabilities(&services),
4468            environment: environment(),
4469            data_dir: Some(data),
4470            viewport: Some((width as f32, height as f32)),
4471            device_info: Some(device_info(&window)),
4472            ..Default::default()
4473        },
4474    );
4475    let keys = Rc::new(KeyState::default());
4476    attach_keys(window.upcast_ref(), keys.clone());
4477    let renderer = NativeRenderer::new(Gtk {
4478        root: root.clone(),
4479        window: window.clone(),
4480        app_title: config.title.clone(),
4481        app: app.clone(),
4482        menus: Rc::new(RefCell::new(HashMap::new())),
4483        swipes: Rc::new(RefCell::new(HashMap::new())),
4484        scroll_events: Rc::new(RefCell::new(HashSet::new())),
4485        refreshable: Rc::new(RefCell::new(HashMap::new())),
4486        sizes: HashMap::new(),
4487        css,
4488        sheet: Default::default(),
4489        css_dirty: false,
4490        clickable: Rc::new(RefCell::new(HashSet::new())),
4491        timers: HashMap::new(),
4492        timer_after: HashMap::new(),
4493        assets: std::env::var("PRISM_ASSETS_DIR")
4494            .ok()
4495            .or_else(|| config.assets.clone())
4496            .map(Into::into),
4497        embedded: config.embedded_assets.clone(),
4498        dark,
4499        titles: HashMap::new(),
4500        icons: HashMap::new(),
4501        stacks: Vec::new(),
4502        tab_bars: Vec::new(),
4503        shapes: HashMap::new(),
4504        scenes: HashMap::new(),
4505        size: (width as f32, height as f32),
4506        rtl: false,
4507        locale: locale(),
4508        controls: HashMap::new(),
4509        date_pickers: HashMap::new(),
4510        clear_label: String::new(),
4511        statuses: HashMap::new(),
4512        bare: HashSet::new(),
4513        stickies: Rc::new(RefCell::new(HashMap::new())),
4514        labels: HashMap::new(),
4515        reports: Rc::default(),
4516        watched: HashSet::new(),
4517        cursors: HashMap::new(),
4518        pointer: Rc::new(RefCell::new(HashMap::new())),
4519        pointer_attached: HashSet::new(),
4520        drag_delays: Rc::default(),
4521        drop_targets: HashMap::new(),
4522        keys: keys.clone(),
4523        layers: Vec::new(),
4524        inert: HashSet::new(),
4525        a11y_hidden: HashSet::new(),
4526        pressable: HashSet::new(),
4527        adaptive: HashMap::new(),
4528        drag_preview: None,
4529    });
4530    STATE.with(|s| {
4531        *s.borrow_mut() = Some(State {
4532            runtime,
4533            renderer,
4534            services,
4535        })
4536    });
4537    layout::watch_root(&root, |w, h| {
4538        with_state(|s| {
4539            s.renderer.widgets.size = (w as f32, h as f32);
4540            UPDATING.set(true);
4541            relayout(s);
4542            UPDATING.set(false);
4543        })
4544    });
4545    with_state(|s| {
4546        let first = s.runtime.render();
4547        commit(s, first);
4548    });
4549    // Timers count down every second; background tasks run while the app
4550    // is open.
4551    glib::timeout_add_seconds_local(1, || {
4552        with_state(|s| {
4553            let w = &s.renderer.widgets;
4554            for (id, (l, end)) in &w.timers {
4555                let after = w.timer_after.get(id).map_or("", String::as_str);
4556                l.set_text(&prism_core::timer_text(*end, after));
4557            }
4558            let due = s.services.due_background();
4559            for id in &due {
4560                s.runtime.run_background_task(id);
4561            }
4562            if !due.is_empty() {
4563                let patches = s.runtime.poll();
4564                commit(s, patches);
4565            }
4566        });
4567        glib::ControlFlow::Continue
4568    });
4569    // Lifecycle: focused, unfocused, minimized.
4570    window.connect_is_active_notify(report_lifecycle);
4571    window.connect_realize(|w| {
4572        if let Some(surface) = w.surface() {
4573            let window = w.clone();
4574            surface.connect_notify_local(Some("state"), move |_, _| report_lifecycle(&window));
4575        }
4576    });
4577    // Refresh (pull to refresh elsewhere): F5 or Ctrl+R, for the
4578    // refreshable scroll views shown (not a hidden tab's or screen's); the
4579    // key stays the app's when there is none.
4580    let keys = gtk::EventControllerKey::new();
4581    keys.connect_key_pressed(|_, key, _, modifiers| {
4582        let refresh = key == gdk::Key::F5
4583            || (modifiers.contains(gdk::ModifierType::CONTROL_MASK) && key == gdk::Key::r);
4584        if !refresh {
4585            return glib::Propagation::Proceed;
4586        }
4587        let mut ids = Vec::new();
4588        with_state(|s| {
4589            let w = &s.renderer.widgets;
4590            ids = w
4591                .refreshable
4592                .borrow()
4593                .iter()
4594                .filter(|(_, sw)| sw.is_mapped())
4595                .map(|(id, _)| *id)
4596                .collect();
4597        });
4598        if ids.is_empty() {
4599            return glib::Propagation::Proceed;
4600        }
4601        for id in ids {
4602            dispatch(UiEvent::Click(id));
4603        }
4604        glib::Propagation::Stop
4605    });
4606    window.add_controller(keys);
4607    // The system's text size and animation settings.
4608    if let Some(settings) = gtk::Settings::default() {
4609        settings.connect_gtk_enable_animations_notify(|_| environment_changed());
4610        settings.connect_gtk_xft_dpi_notify(|_| environment_changed());
4611    }
4612    window.present();
4613    automation(window);
4614}
4615
4616// ---------------------------------------------------------------------------
4617// Development hooks (like the macOS backend's)
4618// ---------------------------------------------------------------------------
4619
4620/// `PRISM_CLICK="+1|Save"` presses buttons by label (or clickable views
4621/// containing that text, or opens the picker / date picker showing it);
4622/// `fill:Placeholder=text` types into the text input or text area with that
4623/// placeholder (or picks option `text` of the picker showing it;
4624/// `fill:@slider=40` drags the first slider), `submit:Placeholder` presses
4625/// Enter in it, `type:Placeholder=text` types at the end of the text area
4626/// with that placeholder (its other text and chips kept).
4627/// `PRISM_SCROLL=600` scrolls the visible scroll views.
4628/// `PRISM_SNAPSHOT=out.png` then saves the window (and open popovers) and
4629/// quits. `PRISM_DELAY` (seconds, default 1) before.
4630fn automation(window: gtk::ApplicationWindow) {
4631    let snapshot = std::env::var("PRISM_SNAPSHOT").ok();
4632    let clicks = std::env::var("PRISM_CLICK").ok();
4633    if snapshot.is_none() && clicks.is_none() {
4634        return;
4635    }
4636    let delay: f64 = std::env::var("PRISM_DELAY")
4637        .ok()
4638        .and_then(|d| d.parse().ok())
4639        .unwrap_or(1.);
4640    glib::timeout_add_local_once(std::time::Duration::from_secs_f64(delay), move || {
4641        for title in clicks
4642            .iter()
4643            .flat_map(|c| c.split('|'))
4644            .filter(|t| !t.is_empty())
4645        {
4646            // `menu:Title` opens the context menu of the view showing Title.
4647            let root: gtk::Widget = window.clone().upcast();
4648            let found = if let Some(t) = title.strip_prefix("menu:") {
4649                open_menu(&root, t)
4650            } else if let Some((placeholder, text)) =
4651                title.strip_prefix("fill:").and_then(|t| t.split_once('='))
4652            {
4653                fill(&root, placeholder, Some(&text.replace("\\n", "\n")))
4654            } else if let Some(placeholder) = title.strip_prefix("submit:") {
4655                fill(&root, placeholder, None)
4656            } else if let Some((placeholder, text)) =
4657                title.strip_prefix("type:").and_then(|t| t.split_once('='))
4658            {
4659                type_at_end(&root, placeholder, text)
4660            } else {
4661                press(&root, title)
4662            };
4663            if !found {
4664                eprintln!("prism-linux: PRISM_CLICK: nothing labelled {title:?}");
4665            }
4666        }
4667        // `PRISM_SCROLL=<y>` scrolls the visible vertical scroll views.
4668        if let Some(y) = std::env::var("PRISM_SCROLL")
4669            .ok()
4670            .and_then(|y| y.parse::<f64>().ok())
4671        {
4672            fn scroll_all(w: &gtk::Widget, y: f64) {
4673                if let Some(sw) = w.downcast_ref::<gtk::ScrolledWindow>()
4674                    && w.is_mapped()
4675                {
4676                    let adj = sw.vadjustment();
4677                    adj.set_value(y.min(adj.upper() - adj.page_size()));
4678                }
4679                let mut child = w.first_child();
4680                while let Some(c) = child {
4681                    scroll_all(&c, y);
4682                    child = c.next_sibling();
4683                }
4684            }
4685            scroll_all(&window.clone().upcast(), y);
4686        }
4687        let Some(path) = snapshot else { return };
4688        // `PRISM_AFTER` (seconds, default 0.7): time for async work first.
4689        let after: f64 = std::env::var("PRISM_AFTER")
4690            .ok()
4691            .and_then(|d| d.parse().ok())
4692            .unwrap_or(0.7);
4693        glib::timeout_add_local_once(std::time::Duration::from_secs_f64(after), move || {
4694            save_png(&window.clone().upcast(), &path);
4695            // Dialogs (alerts, modals) and open menus: out-2.png, out-3.png…
4696            let mut n = 2;
4697            let mut extra = |w: &gtk::Widget| {
4698                save_png(w, &path.replace(".png", &format!("-{n}.png")));
4699                n += 1;
4700            };
4701            for w in gtk::Window::list_toplevels() {
4702                if w != window.clone().upcast::<gtk::Widget>() && w.is_visible() {
4703                    extra(&w);
4704                }
4705            }
4706            // Context menus, pickers' and date pickers' popovers.
4707            fn popovers(w: &gtk::Widget, out: &mut Vec<gtk::Widget>) {
4708                if w.is::<gtk::Popover>() && w.is_visible() {
4709                    out.push(w.clone());
4710                }
4711                let mut child = w.first_child();
4712                while let Some(c) = child {
4713                    popovers(&c, out);
4714                    child = c.next_sibling();
4715                }
4716            }
4717            let mut open = Vec::new();
4718            popovers(&window.clone().upcast(), &mut open);
4719            for p in &open {
4720                extra(p);
4721            }
4722            if let Some(app) = window.application() {
4723                app.quit();
4724            }
4725        });
4726    });
4727}
4728
4729impl Gtk {
4730    /// A text is focusable when it is clickable or has links.
4731    fn update_text_focus(&self, id: NodeId, l: &gtk::Label) {
4732        let links = self.labels.get(&id).is_some_and(|s| {
4733            prism_core::decode_runs(&s.config)
4734                .iter()
4735                .any(|r| r.is_link())
4736        });
4737        let clickable = self.clickable.borrow().contains(&id);
4738        l.set_focusable(links || clickable);
4739        // A clickable text takes the focus (Tab), links or not, and shows it.
4740        if clickable {
4741            l.add_css_class(layout::FOCUSABLE);
4742        } else {
4743            l.remove_css_class(layout::FOCUSABLE);
4744        }
4745    }
4746}
4747
4748fn label_of(w: &gtk::Widget) -> Option<String> {
4749    w.downcast_ref::<gtk::Label>()
4750        .map(|l| l.text().to_string())
4751        .or_else(|| {
4752            w.downcast_ref::<gtk::Button>()
4753                .and_then(|b| b.label())
4754                .map(|l| l.to_string())
4755        })
4756}
4757
4758fn press(w: &gtk::Widget, title: &str) -> bool {
4759    if !w.is_visible() {
4760        return false;
4761    }
4762    if let Some(b) = w.downcast_ref::<gtk::Button>()
4763        && b.label().is_some_and(|l| l == title)
4764    {
4765        b.emit_clicked();
4766        return true;
4767    }
4768    // A date picker or a picker showing `title`: open it.
4769    if let Some(m) = w.downcast_ref::<gtk::MenuButton>()
4770        && shows(w, title)
4771    {
4772        m.popup();
4773        return true;
4774    }
4775    if w.is::<gtk::DropDown>() && shows(w, title) {
4776        w.activate();
4777        return true;
4778    }
4779    // A clickable container showing `title` somewhere inside.
4780    fn shows(w: &gtk::Widget, title: &str) -> bool {
4781        let mut child = w.first_child();
4782        while let Some(c) = child {
4783            if (label_of(&c).is_some_and(|l| l == title) && !c.is::<gtk::Button>())
4784                || shows(&c, title)
4785            {
4786                return true;
4787            }
4788            child = c.next_sibling();
4789        }
4790        false
4791    }
4792    // An inline link reading `title` (rich text): activated like a click on it.
4793    if let Some(l) = w.downcast_ref::<gtk::Label>()
4794        && let Some(id) = w
4795            .css_classes()
4796            .iter()
4797            .find_map(|c| c.strip_prefix('p').and_then(|n| n.parse::<NodeId>().ok()))
4798        && let Some(item) = STATE.with(|s| {
4799            s.borrow().as_ref().and_then(|s| {
4800                let state = s.renderer.widgets.labels.get(&id)?;
4801                prism_core::decode_runs(&state.config)
4802                    .into_iter()
4803                    .find(|r| r.text == title)
4804                    .and_then(|r| r.link)
4805            })
4806        })
4807    {
4808        let uri = format!("{}{item}", text::LINK_SCHEME);
4809        l.emit_by_name::<bool>("activate-link", &[&uri]);
4810        return true;
4811    }
4812    // A clickable container showing `title`, or a clickable text reading it.
4813    let has_label =
4814        shows(w, title) || (w.is::<gtk::Label>() && label_of(w).is_some_and(|l| l == title));
4815    if has_label
4816        && let Some(id) = w
4817            .css_classes()
4818            .iter()
4819            .find_map(|c| c.strip_prefix('p').and_then(|n| n.parse::<NodeId>().ok()))
4820        && STATE.with(|s| {
4821            s.borrow()
4822                .as_ref()
4823                .is_some_and(|s| s.renderer.widgets.clickable.borrow().contains(&id))
4824        })
4825    {
4826        dispatch(UiEvent::Click(id));
4827        return true;
4828    }
4829    let mut child = w.first_child();
4830    while let Some(c) = child {
4831        if press(&c, title) {
4832            return true;
4833        }
4834        child = c.next_sibling();
4835    }
4836    false
4837}
4838
4839/// Types `text` into the entry or text area whose placeholder is
4840/// `placeholder` (`None`: presses Enter in the entry).
4841fn fill(w: &gtk::Widget, placeholder: &str, text: Option<&str>) -> bool {
4842    if let Some(e) = w.downcast_ref::<gtk::Entry>()
4843        && e.placeholder_text().is_some_and(|p| p == placeholder)
4844    {
4845        match text {
4846            Some(t) => e.set_text(t),
4847            None => e.emit_by_name::<()>("activate", &[]),
4848        }
4849        return true;
4850    }
4851    // `@slider`: drags the first slider to `text`.
4852    if placeholder == "@slider"
4853        && let Some(scale) = w.downcast_ref::<gtk::Scale>()
4854        && let Some(v) = text.and_then(|t| t.parse::<f64>().ok())
4855    {
4856        scale.emit_by_name::<bool>("change-value", &[&gtk::ScrollType::Jump, &v]);
4857        return true;
4858    }
4859    // A picker showing `placeholder` (or an option): selects option `text`.
4860    if let Some(d) = w.downcast_ref::<gtk::DropDown>()
4861        && let Some(i) = text.and_then(|t| t.parse::<u32>().ok())
4862        && label_shown(w, placeholder)
4863    {
4864        d.set_selected(i);
4865        return true;
4866    }
4867    // A text area: an overlay with the text view and its placeholder label.
4868    if let Some(o) = w.downcast_ref::<gtk::Overlay>()
4869        && let Some(view) = o
4870            .child()
4871            .and_then(|s| s.downcast::<gtk::ScrolledWindow>().ok())
4872            .and_then(|s| s.child())
4873            .and_then(|v| v.downcast::<gtk::TextView>().ok())
4874        && o.last_child()
4875            .and_then(|l| l.downcast::<gtk::Label>().ok())
4876            .is_some_and(|l| l.text() == placeholder)
4877    {
4878        if let Some(t) = text {
4879            view.buffer().set_text(t);
4880        }
4881        return true;
4882    }
4883    let mut child = w.first_child();
4884    while let Some(c) = child {
4885        if fill(&c, placeholder, text) {
4886            return true;
4887        }
4888        child = c.next_sibling();
4889    }
4890    false
4891}
4892
4893/// Types `text` at the end of the text area with `placeholder`, like the
4894/// keyboard (one undoable edit, its text and chips kept).
4895fn type_at_end(w: &gtk::Widget, placeholder: &str, text: &str) -> bool {
4896    if let Some(o) = w.downcast_ref::<gtk::Overlay>()
4897        && let Some(view) = o
4898            .child()
4899            .and_then(|s| s.downcast::<gtk::ScrolledWindow>().ok())
4900            .and_then(|s| s.child())
4901            .and_then(|v| v.downcast::<gtk::TextView>().ok())
4902        && o.last_child()
4903            .and_then(|l| l.downcast::<gtk::Label>().ok())
4904            .is_some_and(|l| l.text() == placeholder)
4905    {
4906        let b = view.buffer();
4907        b.place_cursor(&b.end_iter());
4908        b.begin_user_action();
4909        b.insert_interactive_at_cursor(text, true);
4910        b.end_user_action();
4911        return true;
4912    }
4913    let mut child = w.first_child();
4914    while let Some(c) = child {
4915        if type_at_end(&c, placeholder, text) {
4916            return true;
4917        }
4918        child = c.next_sibling();
4919    }
4920    false
4921}
4922
4923/// Whether a visible label inside `w` reads `text`.
4924fn label_shown(w: &gtk::Widget, text: &str) -> bool {
4925    if !w.is_visible() {
4926        return false;
4927    }
4928    if w.downcast_ref::<gtk::Label>()
4929        .is_some_and(|l| l.text() == text)
4930    {
4931        return true;
4932    }
4933    let mut child = w.first_child();
4934    while let Some(c) = child {
4935        if label_shown(&c, text) {
4936            return true;
4937        }
4938        child = c.next_sibling();
4939    }
4940    false
4941}
4942
4943/// Opens the context menu of the view showing `title`.
4944fn open_menu(w: &gtk::Widget, title: &str) -> bool {
4945    let mut child = w.first_child();
4946    while let Some(c) = child {
4947        if open_menu(&c, title) {
4948            return true;
4949        }
4950        child = c.next_sibling();
4951    }
4952    let Some(id) = w
4953        .css_classes()
4954        .iter()
4955        .find_map(|c| c.strip_prefix('p').and_then(|n| n.parse::<NodeId>().ok()))
4956    else {
4957        return false;
4958    };
4959    fn shows(w: &gtk::Widget, title: &str) -> bool {
4960        if label_of(w).is_some_and(|l| l == title) {
4961            return true;
4962        }
4963        let mut child = w.first_child();
4964        while let Some(c) = child {
4965            if shows(&c, title) {
4966                return true;
4967            }
4968            child = c.next_sibling();
4969        }
4970        false
4971    }
4972    if !shows(w, title) {
4973        return false;
4974    }
4975    let mut opened = false;
4976    with_state(|s| {
4977        if let Some(p) = s.renderer.widgets.menus.borrow().get(&id) {
4978            p.popup();
4979            opened = true;
4980        }
4981    });
4982    opened
4983}
4984
4985fn save_png(window: &gtk::Widget, path: &str) {
4986    let (w, h) = (window.width() as f64, window.height() as f64);
4987    let paintable = gtk::WidgetPaintable::new(Some(window));
4988    let snapshot = gtk::Snapshot::new();
4989    paintable.snapshot(&snapshot, w, h);
4990    let Some(node) = snapshot.to_node() else {
4991        eprintln!("prism-linux: snapshot: nothing drawn");
4992        return;
4993    };
4994    let Some(renderer) = window.native().and_then(|n| n.renderer()) else {
4995        eprintln!("prism-linux: snapshot: no renderer");
4996        return;
4997    };
4998    let texture = renderer.render_texture(&node, None);
4999    match texture.save_to_png(path) {
5000        Ok(()) => eprintln!("prism-linux: snapshot written to {path}"),
5001        Err(e) => eprintln!("prism-linux: snapshot failed: {e}"),
5002    }
5003}
5004
5005// --- Remote pictures (#32) ----------------------------------------------------------------
5006
5007/// Downloads `src` (a URL, maybe with header lines) off the main thread and
5008/// shows it in `p`, unless `p` was given another source meanwhile.
5009fn load_remote_picture(p: &gtk::Picture, src: &str) {
5010    p.set_paintable(None::<&gdk::Paintable>);
5011    // SAFETY: the key only ever holds a `String`.
5012    unsafe { p.set_data("prism-src", src.to_string()) };
5013    let (picture, src) = (p.clone(), src.to_string());
5014    glib::spawn_future_local(async move {
5015        let source = src.clone();
5016        let bytes =
5017            gio::spawn_blocking(move || prism_native::images::load(&source, &Default::default()))
5018                .await
5019                .ok()
5020                .flatten();
5021        // SAFETY: as above, a `String`.
5022        let current = unsafe {
5023            picture
5024                .data::<String>("prism-src")
5025                .map(|s| s.as_ref().clone())
5026        };
5027        if current.as_deref() != Some(src.as_str()) {
5028            return;
5029        }
5030        let texture =
5031            bytes.and_then(|b| gdk::Texture::from_bytes(&glib::Bytes::from_owned(b)).ok());
5032        match texture {
5033            Some(t) => picture.set_paintable(Some(&t)),
5034            None => eprintln!(
5035                "prism-linux: could not load image {:?}",
5036                prism_core::picture_source(&src).0
5037            ),
5038        }
5039    });
5040}
5041
5042#[cfg(test)]
5043mod arrange_tests {
5044    use super::arrange_children;
5045
5046    #[test]
5047    fn a_child_that_stays_is_moved_not_removed() {
5048        // A toolbar comes beside a focused field, then a ghost stays.
5049        let (gone, order) =
5050            arrange_children(&["field", "ghost", "old"], &["field", "toolbar"], |c| {
5051                *c == "ghost"
5052            });
5053        assert_eq!(gone, ["old"]);
5054        assert_eq!(order, ["ghost", "field", "toolbar"]);
5055        let (gone, order) = arrange_children(&["a", "b"], &["b", "a"], |_| false);
5056        assert!(gone.is_empty());
5057        assert_eq!(order, ["b", "a"]);
5058    }
5059}