Skip to main content

crabshell_ui/
floating.rs

1//! [`FloatingWindow`], an ordinary window that the compositor places and
2//! the user can move, and what a widget in one can ask of it.
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use crabshell_reactive::{Signal, untrack};
8
9use crate::access::AccessEvent;
10use crate::cx::{Anchor, Cx};
11use crate::input::{Handler, run_isolated};
12use crate::prop::{IntoProp, Prop};
13use crate::region::Region;
14use crate::style::Style;
15use crate::tree::{Tree, borrow};
16use crate::widgets::Widget;
17use crate::window::{Anchors, Hints, Output, Window};
18
19pub(crate) type CloseHandler = Rc<Handler<dyn Fn(&Cx)>>;
20
21/// A window like an application's, which the compositor places, tiles or
22/// floats: a launcher, a settings panel, a picture viewer. Show one with
23/// `cx.floating` from the `crabshell` crate. Every property takes a value
24/// or a closure.
25///
26/// ```
27/// use crabshell_ui::{FloatingWindow, Text};
28///
29/// let about = FloatingWindow::new()
30///     .title("About")
31///     .width(320)
32///     .height(200)
33///     .child(Text::new("hello"));
34/// ```
35pub struct FloatingWindow {
36  pub(crate) title: Option<Prop<String>>,
37  pub(crate) width: Option<Prop<u32>>,
38  pub(crate) height: Option<Prop<u32>>,
39  pub(crate) min_size: Option<Prop<(u32, u32)>>,
40  pub(crate) max_size: Option<Prop<(u32, u32)>>,
41  pub(crate) maximized: Option<Prop<bool>>,
42  pub(crate) fullscreen: Option<Prop<bool>>,
43  pub(crate) visible: Option<Prop<bool>>,
44  pub(crate) hints: Hints,
45  pub(crate) on_close: Option<CloseHandler>,
46  pub(crate) style: Option<Prop<Style>>,
47  pub(crate) child: Option<Box<dyn Widget>>,
48}
49
50impl Default for FloatingWindow {
51  fn default() -> FloatingWindow {
52    FloatingWindow::new()
53  }
54}
55
56impl FloatingWindow {
57  /// The default width and height in logical pixels.
58  pub const DEFAULT_SIZE: (u32, u32) = (400, 300);
59
60  /// A visible, empty window of the default size.
61  pub fn new() -> FloatingWindow {
62    FloatingWindow {
63      title: None,
64      width: None,
65      height: None,
66      min_size: None,
67      max_size: None,
68      maximized: None,
69      fullscreen: None,
70      visible: None,
71      hints: Hints::default(),
72      on_close: None,
73      style: None,
74      child: None,
75    }
76  }
77
78  /// Sets the title the compositor shows, as in a title bar or task list.
79  pub fn title(mut self, title: impl IntoProp<String>) -> FloatingWindow {
80    self.title = Some(title.into_prop());
81    self
82  }
83
84  /// Sets the width it asks for, in logical pixels. The compositor may
85  /// give it another, as when tiling it.
86  pub fn width(mut self, width: impl IntoProp<u32>) -> FloatingWindow {
87    self.width = Some(width.into_prop());
88    self
89  }
90
91  /// Sets the height it asks for, in logical pixels.
92  pub fn height(mut self, height: impl IntoProp<u32>) -> FloatingWindow {
93    self.height = Some(height.into_prop());
94    self
95  }
96
97  /// Sets the smallest size the user may make it, as `(width, height)`;
98  /// 0 leaves a side free.
99  pub fn min_size(mut self, size: impl IntoProp<(u32, u32)>) -> FloatingWindow {
100    self.min_size = Some(size.into_prop());
101    self
102  }
103
104  /// Sets the largest size the user may make it, as `(width, height)`;
105  /// 0 leaves a side free.
106  pub fn max_size(mut self, size: impl IntoProp<(u32, u32)>) -> FloatingWindow {
107    self.max_size = Some(size.into_prop());
108    self
109  }
110
111  /// Sets whether it asks to fill the screen but for panels.
112  pub fn maximized(mut self, maximized: impl IntoProp<bool>) -> FloatingWindow {
113    self.maximized = Some(maximized.into_prop());
114    self
115  }
116
117  /// Sets whether it asks to cover the whole screen.
118  pub fn fullscreen(mut self, fullscreen: impl IntoProp<bool>) -> FloatingWindow {
119    self.fullscreen = Some(fullscreen.into_prop());
120    self
121  }
122
123  /// Sets whether it is shown. Hidden, it has no surface at all; shown
124  /// again, it is a new window to the compositor.
125  pub fn visible(mut self, visible: impl IntoProp<bool>) -> FloatingWindow {
126    self.visible = Some(visible.into_prop());
127    self
128  }
129
130  /// Sets the part of the window that takes pointer input, as
131  /// [`PanelWindow::mask`](crate::PanelWindow::mask) does: clicks outside
132  /// it reach whatever is below, and `None`, the default, is the whole
133  /// window.
134  pub fn mask(mut self, mask: impl IntoProp<Option<Region>>) -> FloatingWindow {
135    self.hints.mask = Some(mask.into_prop());
136    self
137  }
138
139  /// Asks the compositor to blur what is behind this part of the window,
140  /// as [`PanelWindow::blur`](crate::PanelWindow::blur) does.
141  pub fn blur(mut self, region: impl IntoProp<Option<Region>>) -> FloatingWindow {
142    self.hints.blur = Some(region.into_prop());
143    self
144  }
145
146  /// Keeps the screen from idling while `true` and the window is shown,
147  /// as [`PanelWindow::inhibit_idle`](crate::PanelWindow::inhibit_idle)
148  /// does.
149  pub fn inhibit_idle(mut self, inhibit: impl IntoProp<bool>) -> FloatingWindow {
150    self.hints.inhibit_idle = Some(inhibit.into_prop());
151    self
152  }
153
154  /// Takes the compositor's shortcuts while `true` and the window has the
155  /// keyboard, as
156  /// [`PanelWindow::inhibit_shortcuts`](crate::PanelWindow::inhibit_shortcuts)
157  /// does.
158  pub fn inhibit_shortcuts(mut self, inhibit: impl IntoProp<bool>) -> FloatingWindow {
159    self.hints.inhibit_shortcuts = Some(inhibit.into_prop());
160    self
161  }
162
163  /// Has the compositor write whether it honors `inhibit_shortcuts`, as
164  /// [`PanelWindow::shortcuts_inhibited`](crate::PanelWindow::shortcuts_inhibited)
165  /// does.
166  pub fn shortcuts_inhibited(mut self, signal: Signal<bool>) -> FloatingWindow {
167    self.hints.shortcuts_inhibited = Some(signal);
168    self
169  }
170
171  /// Holds the focus while `signal` is `true`, with the other windows
172  /// given it, as [`PanelWindow::focus_grab`](crate::PanelWindow::focus_grab)
173  /// does.
174  pub fn focus_grab(mut self, signal: Signal<bool>) -> FloatingWindow {
175    self.hints.focus_grab = Some(signal);
176    self
177  }
178
179  /// Sets the opacity the compositor shows the whole window at, blur
180  /// included, as
181  /// [`PanelWindow::compositor_opacity`](crate::PanelWindow::compositor_opacity)
182  /// does.
183  pub fn compositor_opacity(mut self, opacity: impl IntoProp<f32>) -> FloatingWindow {
184    self.hints.compositor_opacity = Some(opacity.into_prop());
185    self
186  }
187
188  /// Tells the compositor which part of the window holds anything to
189  /// see, as [`PanelWindow::visible_mask`](crate::PanelWindow::visible_mask)
190  /// does.
191  pub fn visible_mask(mut self, region: impl IntoProp<Option<Region>>) -> FloatingWindow {
192    self.hints.visible_mask = Some(region.into_prop());
193    self
194  }
195
196  /// Runs `handler` when the user or compositor asks the window to close,
197  /// as with a title bar's close button. Without one, the window hides
198  /// until `visible` turns false and true again.
199  pub fn on_close(mut self, handler: impl Fn(&Cx) + 'static) -> FloatingWindow {
200    self.on_close = Some(Rc::new(Handler::new(handler)));
201    self
202  }
203
204  /// Sets the window's style. Its color and font are inherited by every
205  /// [`Text`](crate::Text) in it that doesn't set its own.
206  pub fn style(mut self, style: impl IntoProp<Style>) -> FloatingWindow {
207    self.style = Some(style.into_prop());
208    self
209  }
210
211  /// Sets the window's one child, which fills the window.
212  pub fn child(mut self, child: impl Widget) -> FloatingWindow {
213    self.child = Some(Box::new(child));
214    self
215  }
216}
217
218/// What the platform needs to show a floating window.
219#[derive(Clone, Debug, PartialEq, Eq)]
220pub struct FloatingConfig {
221  /// The title.
222  pub title: String,
223  /// The size asked for, in logical pixels.
224  pub width: u32,
225  /// The size asked for, in logical pixels.
226  pub height: u32,
227  /// The smallest size; 0 leaves a side free.
228  pub min_size: (u32, u32),
229  /// The largest size; 0 leaves a side free.
230  pub max_size: (u32, u32),
231  /// Whether it asks to be maximized.
232  pub maximized: bool,
233  /// Whether it asks to be fullscreen.
234  pub fullscreen: bool,
235  /// Whether it should have a surface: visible, and not closed since.
236  pub shown: bool,
237}
238
239/// What a widget asked of the floating window it is in. Moving and
240/// resizing need a pointer button held, so ask from a button's
241/// `on_press`; asked otherwise, they are ignored.
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
243pub enum WindowRequest {
244  /// Let the user drag the window, as by its title bar.
245  Move,
246  /// Let the user resize the window from these edges.
247  Resize(Anchors),
248  /// Minimize it; the compositor may do nothing.
249  Minimize,
250}
251
252/// A floating window's settings in its tree.
253pub(crate) struct FloatingState {
254  title: String,
255  width: u32,
256  height: u32,
257  min_size: (u32, u32),
258  max_size: (u32, u32),
259  maximized: bool,
260  fullscreen: bool,
261  visible: bool,
262  /// Closed with no `on_close`: hidden until `visible` turns false.
263  dismissed: bool,
264  /// Kept in the reactive runtime, which drops the user's closure when the
265  /// window's owner goes.
266  on_close: Signal<Option<CloseHandler>>,
267  pub(crate) requests: Vec<WindowRequest>,
268}
269
270impl FloatingState {
271  /// Shown now: `visible`, and not closed by the compositor since.
272  pub(crate) fn shown(&self) -> bool {
273    self.visible && !self.dismissed
274  }
275
276  pub(crate) fn title(&self) -> &str {
277    &self.title
278  }
279}
280
281impl Window {
282  /// Builds `window` under a new child owner of `cx`, as
283  /// [`Window::new`] does for a panel.
284  pub fn floating(cx: &Cx, mut window: FloatingWindow) -> Window {
285    let child = untrack(|| window.child.take().map(|child| child.into_element()));
286    let path: Rc<str> = "FloatingWindow".into();
287    let cx = cx
288      .child()
289      .named(path.to_string())
290      .at(Rc::new(Anchor::default()));
291    let owner = cx.owner();
292    let on_close = cx.signal(window.on_close.take());
293    let tree = Rc::new_cyclic(|this| {
294      RefCell::new(Tree::new(
295        this.clone(),
296        "FloatingWindow",
297        Output::new(""),
298        cx,
299        path,
300      ))
301    });
302    borrow(&tree).mount_floating(window, child, on_close);
303    Window { tree, owner }
304  }
305
306  /// A floating window's settings; `None` for a panel or popup. Read
307  /// them only after the first flush, as [`surface`](Self::surface).
308  pub fn floating_config(&self) -> Option<FloatingConfig> {
309    let tree = self.tree.borrow();
310    let floating = tree.floating.as_ref()?;
311    let (width, height) = FloatingWindow::DEFAULT_SIZE;
312    Some(FloatingConfig {
313      title: floating.title.clone(),
314      width: if floating.width == 0 {
315        width
316      } else {
317        floating.width
318      },
319      height: if floating.height == 0 {
320        height
321      } else {
322        floating.height
323      },
324      min_size: floating.min_size,
325      max_size: floating.max_size,
326      maximized: floating.maximized,
327      fullscreen: floating.fullscreen,
328      shown: floating.visible && !floating.dismissed,
329    })
330  }
331
332  /// The user or compositor asked this floating window to close: its
333  /// `on_close` runs, or without one it hides.
334  pub fn request_close(&self) {
335    let call = {
336      let mut tree = borrow(&self.tree);
337      let root = tree.root;
338      let Some(floating) = tree.floating.as_mut() else {
339        return;
340      };
341      let handler = untrack(|| floating.on_close.try_with(Option::clone)).flatten();
342      let Some(handler) = handler else {
343        floating.dismissed = true;
344        tree.surface.changed = true;
345        tree.access_event(|_| AccessEvent::WindowsChanged);
346        return;
347      };
348      let Some(node) = tree.node(root) else {
349        return;
350      };
351      (node.cx.clone(), Rc::clone(&node.path), handler)
352    };
353    let (cx, path, handler) = call;
354    run_isolated(&path, "on_close", handler, |f| f(&cx));
355  }
356
357  /// Takes what the window's widgets asked of it since the last call.
358  pub fn take_requests(&self) -> Vec<WindowRequest> {
359    let mut tree = borrow(&self.tree);
360    tree
361      .floating
362      .as_mut()
363      .map(|floating| std::mem::take(&mut floating.requests))
364      .unwrap_or_default()
365  }
366}
367
368impl Cx {
369  /// Lets the user drag the floating window this widget is in, as by a
370  /// title bar. Call it from a button's `on_press`, while the pointer
371  /// button is held.
372  pub fn start_move(&self) {
373    self.request(WindowRequest::Move);
374  }
375
376  /// Lets the user resize the floating window this widget is in from
377  /// `edges`, such as `Edge::Bottom | Edge::Right`. Call it from a
378  /// button's `on_press`.
379  pub fn start_resize(&self, edges: impl Into<Anchors>) {
380    self.request(WindowRequest::Resize(edges.into()));
381  }
382
383  /// Asks to minimize the floating window this widget is in.
384  pub fn minimize(&self) {
385    self.request(WindowRequest::Minimize);
386  }
387
388  fn request(&self, request: WindowRequest) {
389    let Some((tree, _)) = self.anchor.as_ref().and_then(|anchor| anchor.get()) else {
390      return tracing::warn!("{request:?} needs a widget's context in a floating window");
391    };
392    let mut tree = borrow(&tree);
393    match tree.floating.as_mut() {
394      Some(floating) => floating.requests.push(request),
395      None => tracing::warn!("{request:?} works only in a floating window"),
396    }
397  }
398}
399
400impl Tree {
401  /// Applies a floating window's own properties and adds its child.
402  fn mount_floating(
403    &mut self,
404    window: FloatingWindow,
405    child: Option<crate::widgets::Element>,
406    on_close: Signal<Option<CloseHandler>>,
407  ) {
408    let (width, height) = FloatingWindow::DEFAULT_SIZE;
409    self.floating = Some(FloatingState {
410      title: String::new(),
411      width,
412      height,
413      min_size: (0, 0),
414      max_size: (0, 0),
415      maximized: false,
416      fullscreen: false,
417      visible: true,
418      dismissed: false,
419      on_close,
420      requests: Vec::new(),
421    });
422    let root = self.root;
423    let FloatingWindow {
424      title,
425      width,
426      height,
427      min_size,
428      max_size,
429      maximized,
430      fullscreen,
431      visible,
432      hints,
433      on_close: _,
434      style,
435      child: _,
436    } = window;
437    self.bind_opt(root, title, "title", |tree, root, value| {
438      if tree.set_floating(|f| &mut f.title, value) {
439        tree.node_event(root, AccessEvent::NameChanged);
440      }
441    });
442    self.bind_opt(root, width, "width", |tree, _, value| {
443      tree.set_floating(|f| &mut f.width, value);
444    });
445    self.bind_opt(root, height, "height", |tree, _, value| {
446      tree.set_floating(|f| &mut f.height, value);
447    });
448    self.bind_opt(root, min_size, "min_size", |tree, _, value| {
449      tree.set_floating(|f| &mut f.min_size, value);
450    });
451    self.bind_opt(root, max_size, "max_size", |tree, _, value| {
452      tree.set_floating(|f| &mut f.max_size, value);
453    });
454    self.bind_opt(root, maximized, "maximized", |tree, _, value| {
455      tree.set_floating(|f| &mut f.maximized, value);
456    });
457    self.bind_opt(root, fullscreen, "fullscreen", |tree, _, value| {
458      tree.set_floating(|f| &mut f.fullscreen, value);
459    });
460    self.bind_opt(root, visible, "visible", |tree, _, value| {
461      // Hiding forgets a close, so showing again shows.
462      let mut changed = !value && tree.set_floating(|f| &mut f.dismissed, false);
463      changed |= tree.set_floating(|f| &mut f.visible, value);
464      if changed {
465        tree.access_event(|_| AccessEvent::WindowsChanged);
466      }
467    });
468    self.bind_compositor_hints(hints);
469    self.mount_root(style, child);
470    self.surface.changed = true;
471  }
472
473  /// Sets one floating setting and remembers that the settings changed,
474  /// and says whether it did.
475  fn set_floating<T: PartialEq>(
476    &mut self,
477    field: impl FnOnce(&mut FloatingState) -> &mut T,
478    value: T,
479  ) -> bool {
480    let Some(floating) = self.floating.as_mut() else {
481      return false;
482    };
483    let slot = field(floating);
484    if *slot == value {
485      return false;
486    }
487    *slot = value;
488    self.surface.changed = true;
489    true
490  }
491}