zng_ext_window/
vars.rs

1use core::fmt;
2use std::sync::{Arc, atomic::AtomicBool};
3
4use crate::{AutoSize, CursorSource, MonitorQuery, WindowIcon, WindowInstanceState};
5use zng_app::{
6    widget::{WidgetId, base::Parallel, info::access::AccessEnabled},
7    window::{MonitorId, WINDOW, WindowId},
8};
9use zng_color::LightDark;
10use zng_layout::unit::{
11    Dip, DipPoint, DipRect, DipSideOffsets, DipSize, DipToPx, Factor, FactorUnits, Frequency, FrequencyUnits as _, Length, LengthUnits,
12    Point, PxPoint, PxSize, Size,
13};
14use zng_state_map::{StateId, static_id};
15use zng_txt::Txt;
16use zng_unique_id::IdSet;
17use zng_var::{Var, VarValue, merge_var, var, var_from};
18use zng_view_api::{
19    config::{ColorScheme, ColorsConfig},
20    window::{CursorIcon, FocusIndicator, RenderMode, VideoMode, WindowButton, WindowState, WindowStateAll},
21};
22
23#[cfg(feature = "image")]
24use crate::FrameCaptureMode;
25#[cfg(feature = "image")]
26use zng_ext_image::ImageEntry;
27
28pub(crate) struct WindowVarsData {
29    pub(crate) instance_state: Var<WindowInstanceState>,
30
31    pub(crate) chrome: Var<bool>,
32    pub(crate) icon: Var<WindowIcon>,
33    #[cfg(feature = "image")]
34    pub(crate) actual_icon: Var<Option<ImageEntry>>,
35    pub(crate) cursor: Var<CursorSource>,
36    #[cfg(feature = "image")]
37    pub(crate) actual_cursor_img: Var<Option<(ImageEntry, PxPoint)>>,
38    pub(crate) title: Var<Txt>,
39
40    pub(crate) state: Var<WindowState>,
41    pub(crate) focus_indicator: Var<Option<FocusIndicator>>,
42
43    pub(crate) position: Var<Point>,
44    pub(crate) monitor: Var<MonitorQuery>,
45    pub(crate) video_mode: Var<VideoMode>,
46
47    pub(crate) size: Var<Size>,
48    pub(crate) auto_size: Var<AutoSize>,
49    pub(crate) auto_size_origin: Var<Point>,
50    pub(crate) min_size: Var<Size>,
51    pub(crate) max_size: Var<Size>,
52
53    pub(crate) font_size: Var<Length>,
54
55    pub(crate) actual_position: Var<DipPoint>,
56    pub(crate) global_position: Var<PxPoint>,
57    pub(crate) actual_monitor: Var<Option<MonitorId>>,
58    pub(crate) actual_size: Var<DipSize>,
59    pub(crate) actual_min_size: Var<DipSize>,
60    pub(crate) actual_max_size: Var<DipSize>,
61    pub(crate) safe_padding: Var<DipSideOffsets>,
62
63    pub(crate) scale_factor: Var<Factor>,
64    pub(crate) refresh_rate: Var<Frequency>,
65
66    pub(crate) restore_state: Var<WindowState>,
67    pub(crate) restore_rect: Var<DipRect>,
68
69    pub(crate) enabled_buttons: Var<WindowButton>,
70
71    pub(crate) resizable: Var<bool>,
72    pub(crate) movable: Var<bool>,
73
74    pub(crate) always_on_top: Var<bool>,
75
76    pub(crate) visible: Var<bool>,
77    pub(crate) taskbar_visible: Var<bool>,
78
79    pub(crate) parent: Var<Option<WindowId>>,
80    pub(crate) nest_parent: Var<Option<WidgetId>>,
81    modal: Var<bool>,
82    pub(crate) children: Var<IdSet<WindowId>>,
83
84    pub(crate) color_scheme: Var<Option<ColorScheme>>,
85    pub(crate) actual_color_scheme: Var<ColorScheme>,
86    pub(crate) accent_color: Var<Option<LightDark>>,
87    pub(crate) actual_accent_color: Var<LightDark>,
88
89    pub(crate) focused: Var<bool>,
90
91    #[cfg(feature = "image")]
92    pub(crate) frame_capture_mode: Var<FrameCaptureMode>,
93    pub(crate) render_mode: Var<RenderMode>,
94
95    pub(crate) access_enabled: Var<AccessEnabled>,
96    pub(crate) system_shutdown_warn: Var<Txt>,
97
98    parallel: Var<Parallel>,
99
100    pub(crate) pending_state_update: AtomicBool,
101}
102
103/// Variables that configure the opening or open window.
104///
105/// You can get the vars for any window using [`WINDOWS.vars`].
106///
107/// You can get the vars for the current context window using [`WINDOW.vars`].
108///
109/// [`WINDOWS.vars`]: crate::WINDOWS::vars
110/// [`WINDOW.vars`]: crate::WINDOW_Ext::vars
111#[derive(Clone)]
112pub struct WindowVars(pub(crate) Arc<WindowVarsData>);
113impl fmt::Debug for WindowVars {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_tuple("WindowVars").finish_non_exhaustive()
116    }
117}
118impl WindowVars {
119    pub(crate) fn new(default_render_mode: RenderMode, primary_scale_factor: Factor, system_colors: ColorsConfig) -> Self {
120        let vars = Arc::new(WindowVarsData {
121            instance_state: var(WindowInstanceState::Building),
122            chrome: var(true),
123            icon: var(WindowIcon::Default),
124            #[cfg(feature = "image")]
125            actual_icon: var(None),
126            cursor: var_from(CursorIcon::Default),
127            #[cfg(feature = "image")]
128            actual_cursor_img: var(None),
129            title: var(zng_env::about().app.clone()),
130
131            state: var(WindowState::Normal),
132            focus_indicator: var(None),
133
134            position: var(Point::default()),
135            monitor: var(MonitorQuery::default()),
136            video_mode: var(VideoMode::default()),
137            size: var(Size::default()),
138
139            font_size: var(11.pt()),
140
141            actual_position: var(DipPoint::zero()),
142            global_position: var(PxPoint::zero()),
143            actual_monitor: var(None),
144            actual_size: var(DipSize::zero()),
145            actual_min_size: var(DipSize::zero()),
146            actual_max_size: var(DipSize::splat(Dip::MAX)),
147            safe_padding: var(DipSideOffsets::zero()),
148
149            scale_factor: var(primary_scale_factor),
150            refresh_rate: var(60.hertz()),
151
152            restore_state: var(WindowState::Normal),
153            restore_rect: var(DipRect::new(
154                DipPoint::new(Dip::new(30), Dip::new(30)),
155                DipSize::new(Dip::new(800), Dip::new(600)),
156            )),
157
158            enabled_buttons: var(WindowButton::all()),
159
160            min_size: var(Size::new(192, 48)),
161            max_size: var(Size::new(100.pct(), 100.pct())),
162
163            auto_size: var(AutoSize::empty()),
164            auto_size_origin: var(Point::top_left()),
165
166            resizable: var(true),
167            movable: var(true),
168
169            always_on_top: var(false),
170
171            visible: var(true),
172            taskbar_visible: var(true),
173
174            parent: var(None),
175            nest_parent: var(None),
176            modal: var(false),
177            children: var(IdSet::default()),
178
179            color_scheme: var(None),
180            actual_color_scheme: var(system_colors.scheme),
181            accent_color: var(None),
182            actual_accent_color: var(system_colors.accent.into()),
183
184            focused: var(false),
185
186            #[cfg(feature = "image")]
187            frame_capture_mode: var(FrameCaptureMode::Sporadic),
188            render_mode: var(default_render_mode),
189
190            access_enabled: var(AccessEnabled::empty()),
191            system_shutdown_warn: var(Txt::from("")),
192
193            parallel: var(Parallel::default()),
194
195            pending_state_update: AtomicBool::new(false),
196        });
197        Self(vars)
198    }
199
200    /// Require the window vars from the window state.
201    ///
202    /// # Panics
203    ///
204    /// Panics if called in a custom window context that did not setup the variables.
205    pub(crate) fn req() -> Self {
206        WINDOW.req_state(*WINDOW_VARS_ID)
207    }
208
209    /// Window instance state.
210    pub fn instance_state(&self) -> Var<WindowInstanceState> {
211        self.0.instance_state.read_only()
212    }
213
214    /// Defines if the window chrome is visible.
215    ///
216    /// The window chrome is the non-client area of the window, usually a border with resize handles and a title bar.
217    ///
218    /// The default value is `true`.
219    ///
220    /// Note that if the [`WINDOWS.system_chrome`] reports the windowing system prefers a custom chrome **and** does not
221    /// provide one the system chrome is not requested, even if this is `true`. Window widget implementers can use that variable to
222    /// detect when a fallback chrome must be provided.
223    ///
224    /// [`WINDOWS.system_chrome`]: crate::WINDOWS::system_chrome
225    pub fn chrome(&self) -> Var<bool> {
226        self.0.chrome.clone()
227    }
228
229    /// Window icon.
230    ///
231    /// See [`WindowIcon`] for details.
232    ///
233    /// The default value is [`WindowIcon::Default`].
234    ///
235    /// You can retrieve the custom icon image using [`actual_icon`].
236    ///
237    /// [`actual_icon`]: Self::actual_icon
238    pub fn icon(&self) -> Var<WindowIcon> {
239        self.0.icon.clone()
240    }
241
242    /// Window icon image.
243    ///
244    /// This is `None` if [`icon`] is [`WindowIcon::Default`], otherwise it is an [`ImageEntry`]
245    /// reference clone.
246    ///
247    /// [`icon`]: Self::icon
248    /// [`ImageEntry`]: zng_ext_image::ImageEntry
249    #[cfg(feature = "image")]
250    pub fn actual_icon(&self) -> Var<Option<ImageEntry>> {
251        self.0.actual_icon.read_only()
252    }
253
254    /// Window cursor icon and visibility.
255    ///
256    /// See [`CursorSource`] for details.
257    ///
258    /// The default is [`CursorIcon::Default`].
259    ///
260    /// [`CursorIcon`]: zng_view_api::window::CursorIcon
261    /// [`CursorIcon::Default`]: zng_view_api::window::CursorIcon::Default
262    pub fn cursor(&self) -> Var<CursorSource> {
263        self.0.cursor.clone()
264    }
265
266    /// Window custom cursor image.
267    ///
268    /// This is `None` if [`cursor`] is not set to a custom image, otherwise it is an [`ImageEntry`]
269    /// reference clone with computed hotspot [`PxPoint`].
270    ///
271    /// [`cursor`]: Self::cursor
272    /// [`ImageEntry`]: zng_ext_image::ImageEntry
273    /// [`PxPoint`]: zng_layout::unit::PxPoint
274    #[cfg(feature = "image")]
275    pub fn actual_cursor_img(&self) -> Var<Option<(ImageEntry, PxPoint)>> {
276        self.0.actual_cursor_img.read_only()
277    }
278
279    /// Window title text.
280    ///
281    /// The default value is `""`.
282    pub fn title(&self) -> Var<Txt> {
283        self.0.title.clone()
284    }
285
286    /// Window screen state.
287    ///
288    /// Minimized, maximized or fullscreen. See [`WindowState`] for details.
289    ///
290    /// The default value is [`WindowState::Normal`].
291    pub fn state(&self) -> Var<WindowState> {
292        self.0.state.clone()
293    }
294
295    /// Window monitor.
296    ///
297    /// The query selects the monitor to which the [`position`] and [`size`] is relative to.
298    ///
299    /// It evaluate once when the window opens and then once every time the variable updates. You can track
300    /// what the current monitor is by using [`actual_monitor`].
301    ///
302    /// # Behavior After Open
303    ///
304    /// If this variable is changed after the window has opened, and the new query produces a different
305    /// monitor from the [`actual_monitor`] and the window is visible; then the window is moved to
306    /// the new monitor:
307    ///
308    /// * **Maximized**: The window is maximized in the new monitor.
309    /// * **Fullscreen**: The window is fullscreen in the new monitor.
310    /// * **Normal**: The window is centered in the new monitor, keeping the same size.
311    /// * **Minimized/Hidden**: The window remains hidden, the restore position and size are defined like **Normal**.
312    ///
313    /// [`position`]: WindowVars::position
314    /// [`actual_monitor`]: WindowVars::actual_monitor
315    /// [`size`]: WindowVars::size
316    pub fn monitor(&self) -> Var<MonitorQuery> {
317        self.0.monitor.clone()
318    }
319
320    /// Video mode for exclusive fullscreen.
321    pub fn video_mode(&self) -> Var<VideoMode> {
322        self.0.video_mode.clone()
323    }
324
325    /// Current monitor hosting the window.
326    ///
327    /// This is `None` if the window has not opened yet (before first render) or if
328    /// no monitors where found in the operating system or if the window is headless without renderer.
329    pub fn actual_monitor(&self) -> Var<Option<MonitorId>> {
330        self.0.actual_monitor.read_only()
331    }
332
333    /// Available video modes in the current monitor.
334    pub fn video_modes(&self) -> Var<Vec<VideoMode>> {
335        self.0.actual_monitor.flat_map(|&m| {
336            m.and_then(|m| super::MONITORS.monitor(m))
337                .unwrap_or_else(super::MonitorInfo::fallback)
338                .video_modes()
339        })
340    }
341
342    /// Current scale factor of the current monitor hosting the window.
343    ///
344    /// Note that this is only set after [`actual_monitor`] is set. During layout prefer [`LAYOUT.scale_factor`] as
345    /// it will already be set to the scale factor of the expected monitor when the window is still opening.
346    ///
347    /// [`actual_monitor`]: Self::actual_monitor
348    /// [`LAYOUT.scale_factor`]: zng_wgt::prelude::LAYOUT::scale_factor
349    pub fn scale_factor(&self) -> Var<Factor> {
350        self.0.scale_factor.read_only()
351    }
352
353    /// Window actual position on the [monitor].
354    ///
355    /// This is a read-only variable that tracks the computed position of the window, it updates every
356    /// time the window moves.
357    ///
358    /// The initial value is `(0, 0)`, it starts updating once the window opens. The point
359    /// is relative to the origin of the [monitor].
360    ///
361    /// [monitor]: Self::actual_monitor
362    pub fn actual_position(&self) -> Var<DipPoint> {
363        self.0.actual_position.read_only()
364    }
365
366    /// Window actual position on the virtual screen that encompasses all monitors.
367    ///
368    /// This is a read-only variable that tracks the computed position of the window, it updates every
369    /// time the window moves.
370    ///
371    /// The initial value is `(0, 0)`, it starts updating once the window opens.
372    pub fn global_position(&self) -> Var<PxPoint> {
373        self.0.global_position.read_only()
374    }
375
376    /// Window restore state.
377    ///
378    /// The restore state that the window must be set to be restored, if the [current state] is [`Maximized`], [`Fullscreen`] or [`Exclusive`]
379    /// the restore state is [`Normal`], if the [current state] is [`Minimized`] the restore state is the previous state.
380    ///
381    /// When the restore state is [`Normal`] the [`restore_rect`] defines the window position and size.
382    ///
383    /// [current state]: Self::state
384    /// [`Maximized`]: WindowState::Maximized
385    /// [`Fullscreen`]: WindowState::Fullscreen
386    /// [`Exclusive`]: WindowState::Exclusive
387    /// [`Normal`]: WindowState::Normal
388    /// [`Minimized`]: WindowState::Minimized
389    /// [`restore_rect`]: Self::restore_rect
390    pub fn restore_state(&self) -> Var<WindowState> {
391        self.0.restore_state.read_only()
392    }
393
394    /// Window restore position and size when restoring to [`Normal`].
395    ///
396    /// The restore rectangle is the window position and size when its state is [`Normal`], when the state is not [`Normal`]
397    /// this variable tracks the last normal position and size, it will be the window [`actual_position`] and [`actual_size`] again
398    /// when the state is set back to [`Normal`].
399    ///
400    /// This is a read-only variable, to programmatically set it assign the [`position`] and [`size`] variables. The initial
401    /// value is `(30, 30).at(800, 600)`, it starts updating when the window opens.
402    ///
403    /// Note that to restore the window you only need to set [`state`] to [`restore_state`], if the restore state is [`Normal`]
404    /// this position and size will be applied automatically.
405    ///
406    /// [`Normal`]: WindowState::Normal
407    /// [`actual_position`]: Self::actual_position
408    /// [`actual_size`]: Self::actual_size
409    /// [`position`]: Self::position
410    /// [`size`]: Self::size
411    /// [`monitor`]: Self::monitor
412    /// [`actual_monitor`]: Self::actual_monitor
413    /// [`state`]: Self::state
414    /// [`restore_state`]: Self::restore_state
415    pub fn restore_rect(&self) -> Var<DipRect> {
416        self.0.restore_rect.read_only()
417    }
418
419    /// Window top-left offset on the [`monitor`] when the window is [`Normal`].
420    ///
421    /// Relative values are computed in relation to the [`monitor`] size, updating every time the
422    /// position or monitor variable updates.
423    ///
424    /// When the user moves the window this value is considered stale, when it updates it overwrites the window position again,
425    /// note that the window is only moved if it is in the [`Normal`] state, otherwise only the [`restore_rect`] updates.
426    ///
427    /// When the window is moved by the user this variable does **not** update back, to track the current position of the window
428    /// use [`actual_position`], to track the restore position use [`restore_rect`].
429    ///
430    /// The [`Length::Default`] value causes the OS to select a value.
431    ///
432    /// [`restore_rect`]: WindowVars::restore_rect
433    /// [`actual_position`]: WindowVars::actual_position
434    /// [`monitor`]: WindowVars::monitor
435    /// [`Normal`]: WindowState::Normal
436    /// [`Length::Default`]: zng_layout::unit::Length::Default
437    pub fn position(&self) -> Var<Point> {
438        self.0.position.clone()
439    }
440
441    /// Window actual size on the screen.
442    ///
443    /// This is a read-only variable that tracks the computed size of the window, it updates every time
444    /// the window resizes.
445    ///
446    /// The initial value is `(0, 0)`, it starts updating when the window opens.
447    pub fn actual_size(&self) -> Var<DipSize> {
448        self.0.actual_size.read_only()
449    }
450
451    /// Window [`actual_size`], converted to pixels given the [`scale_factor`].
452    ///
453    /// [`actual_size`]: Self::actual_size
454    /// [`scale_factor`]: Self::scale_factor
455    pub fn actual_size_px(&self) -> Var<PxSize> {
456        merge_var!(self.0.actual_size.clone(), self.0.scale_factor.clone(), |size, factor| {
457            PxSize::new(size.width.to_px(*factor), size.height.to_px(*factor))
458        })
459    }
460
461    /// Window actual min size.
462    ///
463    /// This is a read-only variable that tracks the computed min size of the window.
464    pub fn actual_min_size(&self) -> Var<DipSize> {
465        self.0.actual_min_size.read_only()
466    }
467
468    /// Window actual max size.
469    ///
470    /// This is a read-only variable that tracks the computed min size of the window.
471    pub fn actual_max_size(&self) -> Var<DipSize> {
472        self.0.actual_max_size.read_only()
473    }
474
475    /// Padding that must be applied to the window content so that it stays clear of screen obstructions
476    /// such as a camera notch cutout.
477    ///
478    /// Note that the *unsafe* area must still be rendered as it may be partially visible, just don't place nay
479    /// interactive or important content outside of this padding.
480    pub fn safe_padding(&self) -> Var<DipSideOffsets> {
481        self.0.safe_padding.read_only()
482    }
483
484    /// Window width and height on the screen when the window is [`Normal`].
485    ///
486    /// Relative values are computed in relation to the [`monitor`] size, updating every time the
487    /// size or monitor variable updates.
488    ///
489    /// When the user resizes the window this value is considered stale, when it updates it overwrites the window size again,
490    /// note that the window is only resized if it is in the [`Normal`] state, otherwise only the [`restore_rect`] updates.
491    ///
492    /// When the window is resized this variable is **not** updated back, to track the current window size use [`actual_size`],
493    /// to track the restore size use [`restore_rect`].
494    ///
495    /// The default value is `(800, 600)`.
496    ///
497    /// [`actual_size`]: WindowVars::actual_size
498    /// [`monitor`]: WindowVars::monitor
499    /// [`restore_rect`]: WindowVars::restore_rect
500    /// [`Normal`]: WindowState::Normal
501    pub fn size(&self) -> Var<Size> {
502        self.0.size.clone()
503    }
504
505    /// Defines if and how the window size is controlled by the content layout.
506    ///
507    /// When enabled overwrites previously set window size, but is still coerced by [`min_size`]
508    /// and [`max_size`]. Auto-size is disabled if the user resizes the window or if [`size`]
509    /// is set.
510    ///
511    /// The default value is [`AutoSize::DISABLED`].
512    ///
513    /// [`size`]: Self::size
514    /// [`min_size`]: Self::min_size
515    /// [`max_size`]: Self::max_size
516    pub fn auto_size(&self) -> Var<AutoSize> {
517        self.0.auto_size.clone()
518    }
519
520    /// The point in the window content that does not move when the window is resized by [`auto_size`].
521    ///
522    /// When the window size increases it *grows* to the right-bottom, the top-left corner does not move because
523    /// the origin of windows it at the top-left and the position did not change, this variables overwrites this origin
524    /// for [`auto_size`] size changes, the window position is adjusted so that it is the center of the resize.
525    ///
526    /// Note this only applies to resizes, the initial auto-size when the window opens is positioned according to the [`StartPosition`] value.
527    ///
528    /// The default value is [`Point::top_left`].
529    ///
530    /// [`auto_size`]: Self::auto_size
531    /// [`monitor`]: WindowVars::monitor
532    /// [`StartPosition`]: crate::StartPosition
533    /// [`Point::top_left`]: zng_layout::unit::Point::top_left
534    pub fn auto_size_origin(&self) -> Var<Point> {
535        self.0.auto_size_origin.clone()
536    }
537
538    /// Minimal window width and height constraint on the [`size`].
539    ///
540    /// Relative values are computed in relation to the [`monitor`] size, updating every time the
541    /// size or monitor variable updates.
542    ///
543    /// Note that the OS can also define a minimum size that supersedes this variable.
544    ///
545    /// The default value is `(192, 48)`.
546    ///
547    /// [`monitor`]: WindowVars::monitor
548    /// [`size`]: Self::size
549    pub fn min_size(&self) -> Var<Size> {
550        self.0.min_size.clone()
551    }
552
553    /// Maximal window width and height constraint on the [`size`].
554    ///
555    /// Relative values are computed in relation to the [`monitor`] size, updating every time the
556    /// size or monitor variable updates.
557    ///
558    /// Note that the OS can also define a maximum size that supersedes this variable.
559    ///
560    /// The default value is `(100.pct(), 100.pct())`
561    ///
562    /// [`monitor`]: WindowVars::monitor
563    /// [`size`]: Self::size
564    pub fn max_size(&self) -> Var<Size> {
565        self.0.max_size.clone()
566    }
567
568    /// Root font size.
569    ///
570    /// This is the font size in all widget branches  that do not override the font size. The [`rem`] unit is relative to this value.
571    ///
572    /// [`rem`]: LengthUnits::rem
573    pub fn font_size(&self) -> Var<Length> {
574        self.0.font_size.clone()
575    }
576
577    /// Defines if the user can resize the window using the window frame.
578    ///
579    /// Note that even if disabled the window can still be resized from other sources.
580    ///
581    /// The default value is `true`.
582    pub fn resizable(&self) -> Var<bool> {
583        self.0.resizable.clone()
584    }
585
586    /// Defines if the user can move the window using the window frame.
587    ///
588    /// Note that even if disabled the window can still be moved from other sources.
589    ///
590    /// The default value is `true`.
591    pub fn movable(&self) -> Var<bool> {
592        self.0.movable.clone()
593    }
594
595    /// Defines the enabled state of the window chrome buttons.
596    pub fn enabled_buttons(&self) -> Var<WindowButton> {
597        self.0.enabled_buttons.clone()
598    }
599
600    /// Defines if the window should always stay on top of other windows.
601    ///
602    /// Note this only applies to other windows that are not also "always-on-top".
603    ///
604    /// The default value is `false`.
605    pub fn always_on_top(&self) -> Var<bool> {
606        self.0.always_on_top.clone()
607    }
608
609    /// Defines if the window is visible on the screen and in the task-bar.
610    ///
611    /// This variable is observed only after the first frame render, before that the window
612    /// is always not visible.
613    ///
614    /// The default value is `true`.
615    pub fn visible(&self) -> Var<bool> {
616        self.0.visible.clone()
617    }
618
619    /// Defines if the window is visible in the task-bar.
620    ///
621    /// The default value is `true`.
622    pub fn taskbar_visible(&self) -> Var<bool> {
623        self.0.taskbar_visible.clone()
624    }
625
626    /// Defines the parent window.
627    ///
628    /// If a parent is set this behavior applies:
629    ///
630    /// * If the parent is minimized, this window is also minimized.
631    /// * If the parent window is maximized, this window is restored.
632    /// * This window is always on-top of the parent window.
633    /// * If the parent window is closed, this window is also closed.
634    /// * If [`modal`] is set, the parent window cannot be focused while this window is open.
635    /// * If a [`color_scheme`] is not set, the fallback is the parent's actual scheme.
636    /// * If an [`accent_color`] is not set, the fallback is the parent's actual accent.
637    ///
638    /// The default value is `None`.
639    ///
640    /// # Validation
641    ///
642    /// The parent window cannot have a parent, if it has, that parent ID is used instead.
643    /// The parent window must exist. This window (child) cannot have children, it also can't set itself as the parent.
644    ///
645    /// If any of these conditions are not met, an error is logged and the parent var is restored to the previous value.
646    ///
647    /// [`modal`]: Self::modal
648    /// [`color_scheme`]: Self::color_scheme
649    /// [`accent_color`]: Self::accent_color
650    pub fn parent(&self) -> Var<Option<WindowId>> {
651        self.0.parent.clone()
652    }
653
654    /// Gets the widget in [`parent`] that hosts the window, if it is nesting.
655    ///
656    /// Nesting windows are presented as an widget, similar to an "iframe".
657    ///
658    /// [`parent`]: Self::parent
659    pub fn nest_parent(&self) -> Var<Option<WidgetId>> {
660        self.0.nest_parent.read_only()
661    }
662
663    /// Defines the [`parent`](Self::parent) connection.
664    ///
665    /// Value is ignored if `parent` is not set. When this is `true` the parent window cannot be focused while this window is open.
666    ///
667    /// The default value is `false`.
668    pub fn modal(&self) -> Var<bool> {
669        self.0.modal.clone()
670    }
671
672    /// Window children.
673    ///
674    /// This is a set of other windows that have this window as a [`parent`].
675    ///
676    /// [`parent`]: Self::parent
677    pub fn children(&self) -> Var<IdSet<WindowId>> {
678        self.0.children.read_only()
679    }
680
681    /// Override the preferred color scheme.
682    ///
683    /// If set to `None` the system preference is used, see [`actual_color_scheme`].
684    ///
685    /// [`actual_color_scheme`]: Self::actual_color_scheme
686    pub fn color_scheme(&self) -> Var<Option<ColorScheme>> {
687        self.0.color_scheme.clone()
688    }
689
690    /// Actual color scheme to use.
691    ///
692    /// This is the system preference, or [`color_scheme`] if it is set.
693    ///
694    /// [`color_scheme`]: Self::color_scheme
695    pub fn actual_color_scheme(&self) -> Var<ColorScheme> {
696        self.0.actual_color_scheme.read_only()
697    }
698
699    /// Override the preferred accent color.
700    ///
701    /// If set to `None` the system preference is used, see [`actual_accent_color`].
702    ///
703    /// [`actual_accent_color`]: Self::actual_accent_color
704    pub fn accent_color(&self) -> Var<Option<LightDark>> {
705        self.0.accent_color.clone()
706    }
707
708    /// Actual accent color to use.
709    ///
710    /// This is the system preference, or [`color_scheme`] if it is set.
711    ///
712    /// The window widget also sets [`ACCENT_COLOR_VAR`] to this variable.
713    ///
714    /// [`color_scheme`]: Self::color_scheme
715    /// [`ACCENT_COLOR_VAR`]: zng_color::colors::ACCENT_COLOR_VAR
716    pub fn actual_accent_color(&self) -> Var<LightDark> {
717        self.0.actual_accent_color.read_only()
718    }
719
720    /// Read-only variable that tracks if the window is focused in the system window manager.
721    ///
722    /// Note that most of the time its preferable to use the `FOCUS` service as it also tracks the widget focus.
723    pub fn is_focused(&self) -> Var<bool> {
724        self.0.focused.read_only()
725    }
726
727    /// Defines the active user attention required indicator.
728    ///
729    /// This is usually a visual indication on the taskbar icon that prompts the user to focus on the window, it is automatically
730    /// changed to `None` once the window receives focus or you can set it to `None` to cancel the indicator.
731    ///
732    /// Prefer using the `FOCUS` service and advanced `FocusRequest` configs instead of setting this variable directly.
733    pub fn focus_indicator(&self) -> Var<Option<FocusIndicator>> {
734        self.0.focus_indicator.clone()
735    }
736
737    /// Defines if and how the frame pixels are captured for the next rendered frames.
738    ///
739    /// If set to [`Next`] the value will change to [`Sporadic`] after the next frame is rendered.
740    ///
741    /// Note that setting this to [`Next`] does not cause a frame request. Use [`WIDGET.render_update`] for that.
742    ///
743    /// [`Next`]: FrameCaptureMode::Next
744    /// [`Sporadic`]: FrameCaptureMode::Sporadic
745    /// [`WIDGET.render_update`]: zng_app::widget::WIDGET::render_update
746    #[cfg(feature = "image")]
747    pub fn frame_capture_mode(&self) -> Var<FrameCaptureMode> {
748        self.0.frame_capture_mode.clone()
749    }
750
751    /// Window actual render mode.
752    ///
753    /// The initial value is the [`default_render_mode`], it can update after the window is created, when the view-process
754    /// actually creates the backend window and after a view-process respawn.
755    ///
756    /// [`default_render_mode`]: crate::WINDOWS::default_render_mode
757    pub fn render_mode(&self) -> Var<RenderMode> {
758        self.0.render_mode.read_only()
759    }
760
761    /// If an accessibility service has requested info from this window.
762    ///
763    /// You can enable this in the app-process using [`enable_access`], the
764    /// view-process can also enable it on the first request for accessibility info by an external tool.
765    ///
766    /// This variable does not update to fully disabled after first enable, but the VIEW bit can disable and re-enable.
767    ///
768    /// [`enable_access`]: crate::WINDOW_Ext::enable_access
769    pub fn access_enabled(&self) -> Var<AccessEnabled> {
770        self.0.access_enabled.read_only()
771    }
772
773    /// Attempt to set a system wide shutdown warning associated with the window.
774    ///
775    /// Operating systems that support this show the text in a warning for the user, it must be a short text
776    /// that identifies the critical operation that cannot be cancelled.
777    ///
778    /// Set to an empty text to remove the warning.
779    ///
780    /// Note that this does not stop the window from closing or the app from exiting normally, you must
781    /// handle window close requests and show some feedback to the user, the view-process will send a window close
782    /// request when a system shutdown attempt is detected.
783    ///
784    /// Note that there is no guarantee that the view-process or operating system will actually set a block, there
785    /// is no error result because operating systems can silently ignore block requests at any moment, even after
786    /// an initial successful block.
787    ///
788    /// ## Current Limitations
789    ///
790    /// The current `zng::view_process` or `zng-view` only implements this feature on Windows and it will only work properly
791    /// under these conditions:
792    ///
793    /// * It must be running in `run_same_process` mode. Windows kills all other processes, so in a run with `init` the app-process
794    ///   will be lost. Note that this also mean that the crash handler and worker processes are also killed.
795    /// * Must be built with `#![windows_subsystem = "windows"]` and must be running from the Windows Explorer (desktop).
796    pub fn system_shutdown_warn(&self) -> Var<Txt> {
797        self.0.system_shutdown_warn.clone()
798    }
799
800    /// Defines what node list methods can run in parallel in the window widgets.
801    ///
802    /// The window binds [`PARALLEL_VAR`] to this value at the root node ensuring all window nodes are
803    /// configured.
804    ///
805    /// See also [`WINDOWS.parallel`] to define parallelization between windows.
806    ///
807    /// [`PARALLEL_VAR`]: zng_app::widget::base::PARALLEL_VAR
808    /// [`WINDOWS.parallel`]: crate::WINDOWS::parallel
809    pub fn parallel(&self) -> Var<Parallel> {
810        self.0.parallel.clone()
811    }
812
813    #[cfg(feature = "image")]
814    pub(crate) fn take_frame_capture(&self) -> zng_view_api::window::FrameCapture {
815        use zng_view_api::window::FrameCapture;
816        match self.0.frame_capture_mode.get() {
817            FrameCaptureMode::Sporadic => FrameCapture::None,
818            FrameCaptureMode::Next => {
819                self.0.frame_capture_mode.set(FrameCaptureMode::Sporadic);
820                FrameCapture::Full
821            }
822            FrameCaptureMode::All => FrameCapture::Full,
823            FrameCaptureMode::NextMask(m) => {
824                self.0.frame_capture_mode.set(FrameCaptureMode::Sporadic);
825                FrameCapture::Mask(m)
826            }
827            FrameCaptureMode::AllMask(m) => FrameCapture::Mask(m),
828        }
829    }
830    #[cfg(not(feature = "image"))]
831    pub(crate) fn take_frame_capture(&self) -> zng_view_api::window::FrameCapture {
832        zng_view_api::window::FrameCapture::None
833    }
834
835    pub(crate) fn window_state_all(&self) -> WindowStateAll {
836        WindowStateAll::new(
837            self.0.state.get(),
838            self.0.global_position.get(),
839            self.0.restore_rect.get(),
840            self.0.restore_state.get(),
841            self.0.actual_min_size.get(),
842            self.0.actual_max_size.get(),
843            self.0.chrome.get(),
844        )
845    }
846
847    pub(crate) fn set_from_view<T: VarValue>(&self, var: impl FnOnce(&Self) -> &Var<T>, new_value: T) {
848        var(self).modify(move |a| {
849            if a.set(new_value) {
850                a.push_tag(SetFromViewTag);
851            }
852        });
853    }
854}
855impl PartialEq for WindowVars {
856    fn eq(&self, other: &Self) -> bool {
857        Arc::ptr_eq(&self.0, &other.0)
858    }
859}
860impl Eq for WindowVars {}
861
862static_id! {
863    pub(crate) static ref WINDOW_VARS_ID: StateId<WindowVars>;
864}
865
866/// Identifies a variable update set from the view-process.
867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
868pub struct SetFromViewTag;