1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use core::fmt;
use std::sync::Arc;

use zng_app::event::{event, event_args, AnyEventArgs};
use zng_app::update::EventUpdate;
use zng_app::view_process::raw_events::{RawMonitorsChangedArgs, RAW_MONITORS_CHANGED_EVENT, RAW_SCALE_FACTOR_CHANGED_EVENT};
use zng_app::view_process::VIEW_PROCESS_INITED_EVENT;
use zng_app::window::{MonitorId, WindowId, WINDOW};
use zng_app_context::app_local;
use zng_layout::unit::{Dip, DipRect, DipSize, DipToPx, Factor, FactorUnits, Ppi, Px, PxPoint, PxRect, PxSize, PxToDip};
use zng_txt::{ToTxt, Txt};
use zng_unique_id::IdMap;
use zng_var::{impl_from_and_into_var, var, ArcVar, ReadOnlyArcVar, Var, VarValue};
use zng_view_api::window::VideoMode;

use crate::WINDOWS;

app_local! {
    pub(super) static MONITORS_SV: MonitorsService = const { MonitorsService { monitors: IdMap::new() } };
}

/// Monitors service.
///
/// List monitor screens and configure the PPI of a given monitor.
///
/// # Uses
///
/// Uses of this service:
///
/// #### Start Position
///
/// Windows are positioned on a virtual screen that overlaps all monitors, but all position configuration is done relative to
/// an specific parent monitor, it is important to track the parent monitor as it defines properties that affect the layout of the window.
/// This service is used to provide information to implement this feature.
///
/// #### Fullscreen
///
/// To set a window to fullscreen a monitor must be selected, by default it can be the one the window is at but
/// the users may want to select a monitor. To enter fullscreen exclusive the video mode must also be decided, all video
/// modes supported by the monitor are available in the [`MonitorInfo`] value.
///
/// #### Real-Size Preview
///
/// Some apps, like image editors, may implement a feature where the user can preview the *real* dimensions of
/// the content they are editing, to accurately implement this you must known the real dimensions of the monitor screen,
/// unfortunately this information is not provided by display drivers. You can ask the user to measure their screen and
/// set the **pixel-per-inch** ratio for the screen using the [`ppi`] variable, this value is then available in the [`LayoutMetrics`]
/// for the next layout. If not set, the default is `96.0ppi`.
///
/// # Provider
///
/// This service is provided by the [`WindowManager`].
///
/// [`ppi`]: MonitorInfo::ppi
/// [`scale_factor`]: MonitorInfo::scale_factor
/// [`LayoutMetrics`]: zng_layout::context::LayoutMetrics
/// [`WindowManager`]: crate::WindowManager
pub struct MONITORS;
impl MONITORS {
    /// Get monitor info.
    ///
    /// Returns `None` if the monitor was not found or the app is running in headless mode without renderer.
    pub fn monitor(&self, monitor_id: MonitorId) -> Option<MonitorInfo> {
        MONITORS_SV.read().monitors.get(&monitor_id).cloned()
    }

    /// Iterate over all available monitors.
    ///
    /// Is empty if no monitor was found or the app is running in headless mode without renderer.
    pub fn available_monitors(&self) -> Vec<MonitorInfo> {
        MONITORS_SV.read().monitors.values().cloned().collect()
    }

    /// Gets the monitor info marked as primary.
    pub fn primary_monitor(&self) -> Option<MonitorInfo> {
        MONITORS_SV.read().monitors.values().find(|m| m.is_primary().get()).cloned()
    }
}

pub(super) struct MonitorsService {
    monitors: IdMap<MonitorId, MonitorInfo>,
}
impl MonitorsService {
    fn on_monitors_changed(&mut self, args: &RawMonitorsChangedArgs) {
        let mut available_monitors: IdMap<_, _> = args.available_monitors.iter().cloned().collect();

        let mut removed = vec![];
        let mut changed = vec![];

        self.monitors.retain(|key, value| {
            if let Some(new) = available_monitors.remove(key) {
                if value.update(new) {
                    changed.push(*key);
                }
                true
            } else {
                removed.push(*key);
                false
            }
        });

        let mut added = Vec::with_capacity(available_monitors.len());

        for (id, info) in available_monitors {
            added.push(id);

            self.monitors.insert(id, MonitorInfo::from_gen(id, info));
        }

        if !removed.is_empty() || !added.is_empty() || !changed.is_empty() {
            let args = MonitorsChangedArgs::new(args.timestamp, args.propagation().clone(), removed, added, changed);
            MONITORS_CHANGED_EVENT.notify(args);
        }
    }

    pub(super) fn on_pre_event(update: &EventUpdate) {
        if let Some(args) = RAW_SCALE_FACTOR_CHANGED_EVENT.on(update) {
            if let Some(m) = MONITORS_SV.read().monitors.get(&args.monitor_id) {
                m.scale_factor.set(args.scale_factor);
            }
        } else if let Some(args) = RAW_MONITORS_CHANGED_EVENT.on(update) {
            MONITORS_SV.write().on_monitors_changed(args);
        } else if let Some(args) = VIEW_PROCESS_INITED_EVENT.on(update) {
            let args = RawMonitorsChangedArgs::new(args.timestamp, args.propagation().clone(), args.available_monitors.clone());
            MONITORS_SV.write().on_monitors_changed(&args);
        }
    }
}

/// "Monitor" configuration used by windows in [headless mode].
///
/// [headless mode]: zng_app::window::WindowMode::is_headless
#[derive(Clone, Copy, PartialEq)]
pub struct HeadlessMonitor {
    /// The scale factor used for the headless layout and rendering.
    ///
    /// If set to `None`, falls back to the [`parent`] scale-factor, or `1.0` if the headless window has not parent.
    ///
    /// `None` by default.
    ///
    /// [`parent`]: crate::WindowVars::parent
    pub scale_factor: Option<Factor>,

    /// Size of the imaginary monitor screen that contains the headless window.
    ///
    /// This is used to calculate relative lengths in the window size definition and is defined in
    /// layout pixels instead of device like in a real monitor info.
    ///
    /// `(11608, 8708)` by default.
    pub size: DipSize,

    /// Pixel-per-inches used for the headless layout and rendering.
    pub ppi: Ppi,
}
impl fmt::Debug for HeadlessMonitor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() || self.ppi != Ppi::default() {
            f.debug_struct("HeadlessMonitor")
                .field("scale_factor", &self.scale_factor)
                .field("screen_size", &self.size)
                .field("ppi", &self.ppi)
                .finish()
        } else {
            write!(f, "({:?}, ({}, {}))", self.scale_factor, self.size.width, self.size.height)
        }
    }
}
impl HeadlessMonitor {
    /// New with custom size at `None` scale.
    pub fn new(size: DipSize) -> Self {
        HeadlessMonitor {
            scale_factor: None,
            size,
            ppi: Ppi::default(),
        }
    }

    /// New with custom size and scale.
    pub fn new_scaled(size: DipSize, scale_factor: Factor) -> Self {
        HeadlessMonitor {
            scale_factor: Some(scale_factor),
            size,
            ppi: Ppi::default(),
        }
    }

    /// New with default size `(11608, 8708)` and custom scale.
    pub fn new_scale(scale_factor: Factor) -> Self {
        HeadlessMonitor {
            scale_factor: Some(scale_factor),
            ..Self::default()
        }
    }
}
impl Default for HeadlessMonitor {
    /// New `(11608, 8708)` at `None` scale.
    fn default() -> Self {
        (11608, 8708).into()
    }
}
impl_from_and_into_var! {
    fn from<W: Into<Dip>, H: Into<Dip>>((width, height): (W, H)) -> HeadlessMonitor {
        HeadlessMonitor::new(DipSize::new(width.into(), height.into()))
    }
    fn from<W: Into<Dip>, H: Into<Dip>, F: Into<Factor>>((width, height, scale): (W, H, F)) -> HeadlessMonitor {
        HeadlessMonitor::new_scaled(DipSize::new(width.into(), height.into()), scale.into())
    }
}

/// All information about a monitor that [`MONITORS`] can provide.
#[derive(Clone)]
pub struct MonitorInfo {
    id: MonitorId,
    is_primary: ArcVar<bool>,
    name: ArcVar<Txt>,
    position: ArcVar<PxPoint>,
    size: ArcVar<PxSize>,
    video_modes: ArcVar<Vec<VideoMode>>,
    scale_factor: ArcVar<Factor>,
    ppi: ArcVar<Ppi>,
}
impl fmt::Debug for MonitorInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MonitorFullInfo").field("id", &self.id).finish_non_exhaustive()
    }
}
impl MonitorInfo {
    /// New from a [`zng_view_api::MonitorInfo`].
    fn from_gen(id: MonitorId, info: zng_view_api::window::MonitorInfo) -> Self {
        MonitorInfo {
            id,
            is_primary: var(info.is_primary),
            name: var(info.name.to_txt()),
            position: var(info.position),
            size: var(info.size),
            scale_factor: var(info.scale_factor),
            video_modes: var(info.video_modes),
            ppi: var(Ppi::default()),
        }
    }

    /// Update variables from fresh [`zng_view_api::MonitorInfo`],
    /// returns if any value changed.
    fn update(&self, info: zng_view_api::window::MonitorInfo) -> bool {
        fn check_set<T: VarValue + PartialEq>(var: &impl Var<T>, value: T) -> bool {
            let ne = var.with(|v| v != &value);
            var.set(value).unwrap();
            ne
        }

        check_set(&self.is_primary, info.is_primary)
            | check_set(&self.name, info.name.to_txt())
            | check_set(&self.position, info.position)
            | check_set(&self.size, info.size)
            | check_set(&self.scale_factor, info.scale_factor)
            | check_set(&self.video_modes, info.video_modes)
    }

    /// Unique ID.
    pub fn id(&self) -> MonitorId {
        self.id
    }

    /// If this monitor is the primary screen.
    pub fn is_primary(&self) -> ReadOnlyArcVar<bool> {
        self.is_primary.read_only()
    }

    /// Name of the monitor.
    pub fn name(&self) -> ReadOnlyArcVar<Txt> {
        self.name.read_only()
    }
    /// Top-left offset of the monitor region in the virtual screen, in pixels.
    pub fn position(&self) -> ReadOnlyArcVar<PxPoint> {
        self.position.read_only()
    }
    /// Width/height of the monitor region in the virtual screen, in pixels.
    pub fn size(&self) -> ReadOnlyArcVar<PxSize> {
        self.size.read_only()
    }

    /// Exclusive fullscreen video modes.
    pub fn video_modes(&self) -> ReadOnlyArcVar<Vec<VideoMode>> {
        self.video_modes.read_only()
    }

    /// The monitor scale factor.
    ///
    /// Can update if the user changes system settings.
    pub fn scale_factor(&self) -> ReadOnlyArcVar<Factor> {
        self.scale_factor.read_only()
    }
    /// Pixel-per-inch config var.
    pub fn ppi(&self) -> ArcVar<Ppi> {
        self.ppi.clone()
    }

    /// Gets the monitor area in pixels.
    pub fn px_rect(&self) -> PxRect {
        let pos = self.position.get();
        let size = self.size.get();

        PxRect::new(pos, size)
    }

    /// Gets the monitor area in device independent pixels.
    pub fn dip_rect(&self) -> DipRect {
        let pos = self.position.get();
        let size = self.size.get();
        let factor = self.scale_factor.get();

        PxRect::new(pos, size).to_dip(factor)
    }

    /// Bogus metadata for the [`MonitorId::fallback`].
    ///
    /// [`MonitorId::fallback`]: crate::monitor::MonitorId::fallback
    pub fn fallback() -> Self {
        let defaults = HeadlessMonitor::default();
        let fct = 1.fct();

        Self {
            id: MonitorId::fallback(),
            is_primary: var(false),
            name: var("<fallback>".into()),
            position: var(PxPoint::zero()),
            size: var(defaults.size.to_px(fct)),
            video_modes: var(vec![]),
            scale_factor: var(fct),
            ppi: var(Ppi::default()),
        }
    }
}

/// A selector that returns a [`MonitorInfo`].
#[derive(Clone, Default)]
pub enum MonitorQuery {
    /// The parent window monitor, or `Primary` if the window has no parent.
    ///
    /// Note that the window is not moved automatically if the parent window is moved to another monitor, only
    /// after the query variable updates.
    ///
    /// This is the default value.
    #[default]
    ParentOrPrimary,

    /// The primary monitor, if there is any monitor.
    Primary,
    /// Custom query closure.
    ///
    /// If the closure returns `None` the `ParentOrPrimary` query is used, if there is any.
    ///
    /// You can use the [`MONITORS`] service in the query closure to select a monitor.
    Query(Arc<dyn Fn() -> Option<MonitorInfo> + Send + Sync>),
}
impl std::fmt::Debug for MonitorQuery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            write!(f, "MonitorQuery::")?;
        }
        match self {
            Self::ParentOrPrimary => write!(f, "ParentOrPrimary"),
            Self::Primary => write!(f, "Primary"),
            Self::Query(_) => write!(f, "Query(_)"),
        }
    }
}
impl MonitorQuery {
    /// New query.
    pub fn new(query: impl Fn() -> Option<MonitorInfo> + Send + Sync + 'static) -> Self {
        Self::Query(Arc::new(query))
    }

    /// Runs the query.
    pub fn select(&self) -> Option<MonitorInfo> {
        self.select_for(WINDOW.id())
    }
    fn select_for(&self, win_id: WindowId) -> Option<MonitorInfo> {
        match self {
            MonitorQuery::ParentOrPrimary => Self::parent_or_primary_query(win_id),
            MonitorQuery::Primary => Self::primary_query(),
            MonitorQuery::Query(q) => q(),
        }
    }

    /// Runs the query. Falls back to `Primary`, or the largest or [`MonitorInfo::fallback`].
    pub fn select_fallback(&self) -> MonitorInfo {
        match self {
            MonitorQuery::ParentOrPrimary => Self::parent_or_primary_query(WINDOW.id()),
            MonitorQuery::Primary => Self::primary_query(),
            MonitorQuery::Query(q) => q().or_else(Self::primary_query),
        }
        .unwrap_or_else(Self::fallback)
    }

    fn fallback() -> MonitorInfo {
        let mut best = MonitorInfo::fallback();
        let mut best_area = Px(0);
        for m in MONITORS.available_monitors() {
            let m_area = m.px_rect().area();
            if m_area > best_area {
                best = m;
                best_area = m_area;
            }
        }
        best
    }

    fn parent_or_primary_query(win_id: WindowId) -> Option<MonitorInfo> {
        if let Some(parent) = WINDOWS.vars(win_id).unwrap().parent().get() {
            if let Ok(w) = WINDOWS.vars(parent) {
                return if let Some(monitor) = w.actual_monitor().get() {
                    MONITORS.monitor(monitor)
                } else {
                    w.monitor().get().select_for(parent)
                };
            }
        }
        MONITORS.primary_monitor()
    }

    fn primary_query() -> Option<MonitorInfo> {
        MONITORS.primary_monitor()
    }
}
impl PartialEq for MonitorQuery {
    /// Returns `true` only if both are [`MonitorQuery::Primary`].
    fn eq(&self, other: &Self) -> bool {
        matches!((self, other), (Self::Primary, Self::Primary))
    }
}

event_args! {
    /// [`MONITORS_CHANGED_EVENT`] args.
    pub struct MonitorsChangedArgs {
        /// Removed monitors.
        pub removed: Vec<MonitorId>,

        /// Added monitors.
        ///
        /// Use the [`MONITORS`] service to get metadata about the added monitors.
        pub added: Vec<MonitorId>,

        /// Modified monitors.
        ///
        /// The monitor metadata is tracked using variables that are now flagged new.
        pub modified: Vec<MonitorId>,

        ..

        /// Broadcast to all widgets.
        fn delivery_list(&self, list: &mut UpdateDeliveryList) {
            list.search_all()
        }
    }
}

event! {
    /// Monitors added, removed or modified event.
    pub static MONITORS_CHANGED_EVENT: MonitorsChangedArgs;
}