1use 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
25pub struct NavStack {
30 root: gtk::Box,
31 header: gtk::Box,
32 back: gtk::Button,
33 title: gtk::Label,
34 screens: RefCell<Vec<View>>,
35 in_sheet: Cell<bool>,
37 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 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 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 Shape(NodeId, gtk::DrawingArea, Rc<RefCell<Vec<prism_core::Path>>>),
74 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 Check(NodeId, gtk::CheckButton),
87 Radio(NodeId, Rc<controls::RadioGroup>),
88 Overlay(NodeId, Rc<OverlayView>),
89 Video(NodeId, gtk::Video),
91}
92
93thread_local! {
94 static SHAPE_DARK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
96}
97
98pub(crate) fn dark() -> bool {
100 SHAPE_DARK.with(Cell::get)
101}
102
103fn draw_paths(cr: >k::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 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
216fn 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 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
236const LIGHT_BESIDE_FOCUS: &str = "prism-light-beside-focus";
244
245fn set_popover_mode(p: >k::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
261fn 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
271fn place_popover(
275 p: >k::Popover,
276 parent: >k::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 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 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
303fn popover_kind(config: prism_core::controls::OverlayConfig) -> bool {
307 config.anchored_side().is_some()
308}
309
310pub struct OverlayView {
311 id: NodeId,
312 anchor: gtk::Box,
315 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 size: Cell<(i32, i32)>,
323 outside: RefCell<Option<(gtk::Window, gtk::GestureClick)>>,
326}
327
328impl OverlayView {
329 fn configure(
331 self: &Rc<Self>,
332 config: prism_core::controls::OverlayConfig,
333 main: >k::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 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 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 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 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::<>k::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::<>k::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 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 fn watch_outside(&self, p: >k::Popover, parent: >k::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 if p.has_css_class(LIGHT_BESIDE_FOCUS) && p.is_visible() {
529 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 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 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#[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
588fn click_event(
591 id: NodeId,
592 position: Option<prism_core::Point>,
593 n_press: i32,
594 g: >k::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
614fn 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
624fn node_of(w: >k::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
631fn attach_keys(window: >k::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 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 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 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 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 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
760thread_local! {
765 static COALESCED: RefCell<HashMap<(NodeId, u8), UiEvent>> = RefCell::new(HashMap::new());
766}
767
768fn 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#[derive(Clone, Copy)]
787struct DragStart {
788 at: (f64, f64),
789 button: prism_core::PointerButton,
790 mods: prism_core::Modifiers,
791 started: bool,
792 holding: bool,
794}
795
796fn 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
807pub(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
817fn wheel_event(
821 id: NodeId,
822 c: >k::EventControllerScroll,
823 dx: f64,
824 dy: f64,
825 phase: prism_core::GesturePhase,
826) -> UiEvent {
827 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
843fn 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 >k::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
863struct 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 static UPDATING: Cell<bool> = const { Cell::new(false) };
877 static TYPED: RefCell<HashMap<NodeId, prism_native::fields::Typed>> = RefCell::new(HashMap::new());
879}
880
881thread_local! {
886 static SELECT_EVENTS: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
888 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 static APP_SELECTED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
894}
895
896pub(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
904fn 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
913fn view_edges(v: >k::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: >k::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: >k::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
938pub(crate) fn buffer_selection(b: >k::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
950pub(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
984pub(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
995fn 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
1006pub(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
1013pub(crate) fn group_field_at(
1016 id: NodeId,
1017 root: >k::Widget,
1018 p: >k::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
1070pub(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
1078fn 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 static AUTOSCROLL: Cell<bool> = const { Cell::new(false) };
1096}
1097
1098fn 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 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
1149fn 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 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
1179fn 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 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 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 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
1245pub(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
1266pub(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
1281pub struct Gtk {
1286 root: gtk::Box,
1287 window: gtk::ApplicationWindow,
1288 app_title: String,
1290 app: gtk::Application,
1291 menus: Rc<RefCell<HashMap<NodeId, gtk::PopoverMenu>>>,
1293 swipes: Rc<RefCell<HashMap<NodeId, (bool, bool)>>>,
1294 scroll_events: Rc<RefCell<HashSet<NodeId>>>,
1295 refreshable: Rc<RefCell<HashMap<NodeId, gtk::ScrolledWindow>>>,
1297 sizes: HashMap<NodeId, (f32, f32)>,
1299 css: gtk::CssProvider,
1300 sheet: crate::sheet::Sheet,
1303 css_dirty: bool,
1304 clickable: Rc<RefCell<HashSet<NodeId>>>,
1305 timers: HashMap<NodeId, (gtk::Label, f64)>,
1306 timer_after: HashMap<NodeId, String>,
1308 assets: Option<std::path::PathBuf>,
1309 embedded: prism_core::EmbeddedAssets,
1311 dark: bool,
1312 titles: HashMap<NodeId, String>,
1314 icons: HashMap<NodeId, String>,
1315 stacks: Vec<Rc<NavStack>>,
1316 tab_bars: Vec<Rc<TabBar>>,
1317 shapes: HashMap<NodeId, gtk::DrawingArea>,
1319 scenes: HashMap<NodeId, gtk::GLArea>,
1321 size: (f32, f32),
1323 rtl: bool,
1325 locale: prism_core::Locale,
1326 controls: HashMap<NodeId, gtk::Widget>,
1328 date_pickers: HashMap<NodeId, Rc<controls::DatePicker>>,
1329 clear_label: String,
1331 statuses: HashMap<NodeId, String>,
1333 labels: HashMap<NodeId, text::LabelState>,
1335 bare: HashSet<NodeId>,
1338 stickies: Stickies,
1340 reports: Rc<RefCell<HashMap<NodeId, prism_core::Interactions>>>,
1344 watched: HashSet<NodeId>,
1345 cursors: HashMap<NodeId, prism_core::Cursor>,
1347 pointer: Rc<RefCell<HashMap<NodeId, u8>>>,
1350 pointer_attached: HashSet<(NodeId, u8)>,
1352 drag_delays: Rc<RefCell<HashMap<NodeId, u32>>>,
1354 drop_targets: HashMap<NodeId, gtk::DropTarget>,
1356 keys: Rc<KeyState>,
1357 layers: Vec<gtk::Widget>,
1359 inert: HashSet<NodeId>,
1361 a11y_hidden: HashSet<NodeId>,
1363 pressable: HashSet<NodeId>,
1367 adaptive: HashMap<NodeId, (View, Style)>,
1371 drag_preview: Option<gtk::Picture>,
1373}
1374
1375type Stickies = Rc<RefCell<HashMap<NodeId, HashMap<NodeId, (gtk::Widget, prism_native::Sticky)>>>>;
1377
1378fn 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 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 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 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 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 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 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 reset_accessible_property(&button, a11y_property::DESCRIPTION);
1495 reset_accessible_state(&button, a11y_state::PRESSED);
1496 set_accessible_selected(&button, i == selected);
1497 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 fn attach_gestures(&self, id: NodeId, w: >k::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 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
1574impl Gtk {
1577 fn watch_states(&mut self, id: NodeId, w: >k::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 if text_field {
1596 report = report.with(I::Focus, true);
1597 }
1598 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 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 static UNSAVED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1670}
1671
1672fn confirm_leave(window: >k::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 static ESCAPE_AT: std::cell::Cell<Option<std::time::Instant>> =
1733 const { std::cell::Cell::new(None) };
1734}
1735
1736fn 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let mut css = crate::decor::declarations(&crate::decor::paint(s, self.dark, false));
2113 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 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 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 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 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 if matches!(view, View::Input(..) | View::TextArea(..)) && s.own_field_look() {
2188 css += "outline:none;";
2189 }
2190 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 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 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 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 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 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 View::Input(id, e) => {
2307 let current = e.text();
2308 if field_takes(*id, text, ¤t) {
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 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(>k::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 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(>k::gio::File::for_uri(&url)));
2345 }
2346 }
2347 View::Picture(_, p) if prism_native::images::is_remote(text) => {
2350 load_remote_picture(p, text);
2351 }
2352 View::Picture(_, p) => {
2353 if let Some(bytes) = self.embedded.get(text) {
2355 match gtk::gdk::Texture::from_bytes(>k::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 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 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 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 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 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 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 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 for c in &children {
2512 let w = c.widget();
2513 if layout::is_sticky(&w) {
2514 layout::raise(&w);
2515 }
2516 }
2517 for bar in &keep {
2519 bar.insert_before(&host, None::<>k::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 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 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 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 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 (View::Slider(..), m) => m.map_or(200., |m| m.min(200.)),
2675 (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 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 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 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 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 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 if let View::Container(_, NodeKind::Tab, _) = view {
2892 crate::table::set_relation(&w, crate::table::LABELLED_BY, None);
2893 }
2894 }
2895 None if crate::names::take_label(&target) => {
2897 reset_accessible_property(&target, a11y_property::LABEL)
2898 }
2899 None => {}
2900 }
2901 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 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 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 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 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 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 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 View::Container(id, kind, c) => {
3013 if let Some(role) = a11y.role.and_then(container_role)
3014 && crate::table::role(*kind).is_none()
3015 && !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 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 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 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 View::Picture(id, p) => crate::focal::set_focus(*id, p, config),
3128 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 unsafe { v.set_data("prism-muted", c.muted) };
3139 }
3140 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 t.rows
3160 .set(prism_core::controls::InputConfig::decode(config).min_rows());
3161 }
3162 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 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 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 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 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 fn window_origin(&mut self, view: &View) -> Option<(f32, f32)> {
3343 let p = view
3344 .widget()
3345 .compute_point(&self.root, >k::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 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 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 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 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 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 drag.set_button(0);
3503 let masks = self.pointer.clone();
3504 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 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 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 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 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 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 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 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 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 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 let zoom = gtk::GestureZoom::new();
3706 let masks = self.pointer.clone();
3707 let last = Rc::new(Cell::new(1.));
3708 let event = move |g: >k::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 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 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 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 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 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 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 let keep = match view {
3862 View::Input(id, _) => APP_SELECTED.with(|s| s.borrow().contains(id)),
3863 _ => false,
3864 };
3865 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 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::<>k::Widget>);
3888 }
3889 });
3890 }
3891
3892 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 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 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 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 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 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 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 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
4022fn 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
4058pub(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 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
4077pub(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
4087pub(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 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
4105fn 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 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
4121pub(crate) mod a11y_state {
4123 pub const DISABLED: i32 = 2;
4124 pub const PRESSED: i32 = 6;
4125 pub const SELECTED: i32 = 7;
4126}
4127
4128fn 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 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
4144fn 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 unsafe { gtk_accessible_reset_state(widget.cast(), state) };
4150}
4151
4152pub(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 unsafe { gtk_accessible_reset_property(widget.cast(), property) };
4158}
4159
4160unsafe extern "C" {
4161 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 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
4176pub(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 unsafe {
4186 gtk_accessible_update_state_value(widget.cast(), 1, &HIDDEN, value.to_glib_none_mut().0);
4187 }
4188}
4189
4190fn 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 let mut value = state.into_glib().to_value();
4203 let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4204 unsafe {
4206 gtk_accessible_update_state_value(widget.cast(), 1, &CHECKED, value.to_glib_none_mut().0);
4207 }
4208}
4209
4210pub(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 let mut value = i32::from(selected).to_value();
4217 let widget: *mut gtk::ffi::GtkWidget = w.as_ref().to_glib_none().0;
4218 unsafe {
4220 gtk_accessible_update_state_value(widget.cast(), 1, &SELECTED, value.to_glib_none_mut().0);
4221 }
4222}
4223
4224fn set_accessible_label(w: >k::Widget, label: &str) {
4226 set_accessible_string(w, a11y_property::LABEL, label);
4227}
4228
4229fn 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
4241fn report_lifecycle(window: >k::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
4260fn 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
4316fn 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: >k::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
4355pub fn run(config: AppConfig, init: AppInit) {
4357 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 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: >k::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 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 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 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 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 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 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 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 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
4616fn 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 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 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: >k::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 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 let mut n = 2;
4697 let mut extra = |w: >k::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 fn popovers(w: >k::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 fn update_text_focus(&self, id: NodeId, l: >k::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 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: >k::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: >k::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 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 fn shows(w: >k::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 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 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
4839fn fill(w: >k::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 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", &[>k::ScrollType::Jump, &v]);
4857 return true;
4858 }
4859 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 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
4893fn type_at_end(w: >k::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
4923fn label_shown(w: >k::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
4943fn open_menu(w: >k::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: >k::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: >k::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
5005fn load_remote_picture(p: >k::Picture, src: &str) {
5010 p.set_paintable(None::<&gdk::Paintable>);
5011 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 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 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}