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
use std::cmp::Reverse;

use ordered_float::OrderedFloat;
use winit::monitor::{MonitorHandle as WinitMonitorHandle, VideoMode as WinitVideoMode};
use winit::window::Fullscreen as WinitFullscreen;

/// Object that represents a mode of a monitor.
///
/// ***Note:** this represents the current modes available at the time of querying and is not updated.*
#[derive(Clone, PartialEq, Eq)]
pub struct MonitorMode {
    pub(crate) resolution: [u32; 2],
    pub(crate) bit_depth: u16,
    pub(crate) refresh_rate: OrderedFloat<f32>,
    pub(crate) handle: WinitVideoMode,
    pub(crate) monitor_handle: WinitMonitorHandle,
}

impl MonitorMode {
    /// Returns the resolution of this mode.
    pub fn resolution(&self) -> [u32; 2] {
        self.resolution
    }

    /// Returns the bit depth of this mode.
    pub fn bit_depth(&self) -> u16 {
        self.bit_depth
    }

    /// Returns the refresh rate in Hz of this mode.
    pub fn refresh_rate(&self) -> f32 {
        self.refresh_rate.into_inner()
    }
}

impl std::fmt::Debug for MonitorMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MonitorMode")
            .field("resolution", &self.resolution)
            .field("bit_depth", &self.bit_depth)
            .field("refresh_rate", &self.refresh_rate.into_inner())
            .finish()
    }
}

/// Object that represents a monitor.
///
/// ***Note:** this represents the monitor at the time of querying and is not updated.*
#[derive(Clone, PartialEq, Eq)]
pub struct Monitor {
    pub(crate) name: String,
    pub(crate) resolution: [u32; 2],
    pub(crate) position: [i32; 2],
    pub(crate) refresh_rate: OrderedFloat<f32>,
    pub(crate) bit_depth: u16,
    pub(crate) is_current: bool,
    pub(crate) is_primary: bool,
    pub(crate) modes: Vec<MonitorMode>,
    pub(crate) handle: WinitMonitorHandle,
}

impl std::fmt::Debug for Monitor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Monitor")
            .field("name", &self.name)
            .field("resolution", &self.resolution)
            .field("bit_depth", &self.bit_depth)
            .field("refresh_rate", &self.refresh_rate.into_inner())
            .field("is_current", &self.is_current)
            .field("is_primary", &self.is_primary)
            .field("modes", &self.modes)
            .finish()
    }
}

impl Monitor {
    /// Returns a human-readable name of the monitor.
    pub fn name(&self) -> String {
        self.name.clone()
    }

    /// Returns the monitor’s resolution.
    pub fn resolution(&self) -> [u32; 2] {
        self.resolution
    }

    /// Returns the top-left corner position of the monitor relative to the larger full screen area.
    pub fn position(&self) -> [i32; 2] {
        self.position
    }

    /// Returns the bit depth of this monitor.
    pub fn bit_depth(&self) -> u16 {
        self.bit_depth
    }

    /// The monitor refresh rate used by the system.
    pub fn refresh_rate(&self) -> f32 {
        self.refresh_rate.into_inner()
    }

    /// Returns a list of `MonitorMode`'s supported by this monitor.
    pub fn modes(&self) -> Vec<MonitorMode> {
        self.modes.clone()
    }

    /// Returns `true` if it is the systems primary monitor.
    pub fn is_primary(&self) -> bool {
        self.is_primary
    }

    /// Returns `true` if it is the current monitor in use.
    pub fn is_current(&self) -> bool {
        self.is_current
    }

    /// Get the most optimal mode for this monitor.
    ///
    /// # Priority
    /// 1. Resolution (Higher than the monitor are less favorable)
    /// 2. Aspect Ratio
    /// 2. Refresh Rate
    /// 3. Bit Depth
    pub fn optimal_mode(&self) -> MonitorMode {
        assert!(!self.modes.is_empty());

        let mut modes: Vec<&MonitorMode> = {
            let same_resolution: Vec<_> = self
                .modes
                .iter()
                .filter(|mode| mode.resolution == self.resolution)
                .collect();

            if !same_resolution.is_empty() {
                same_resolution
            } else {
                // Same resolution isn't available, try lesser ones first.
                let mut modes_a: Vec<_> = self
                    .modes
                    .iter()
                    .filter(|mode| {
                        mode.resolution[0] <= self.resolution[0]
                            && mode.resolution[1] <= self.resolution[1]
                    })
                    .collect();

                // No lesser resolution modes, use them all.
                if modes_a.is_empty() {
                    modes_a = self.modes.iter().collect();
                }

                // Try to find one with the same aspect ratio
                let ideal_aspect = self.resolution[0] as f32 / self.resolution[1] as f32;
                let mut modes_b: Vec<_> = modes_a
                    .iter()
                    .filter(|mode| {
                        mode.resolution[0] as f32 / mode.resolution[1] as f32 == ideal_aspect
                    })
                    .collect();

                // No modes with same aspect ratio use modes_a.
                if modes_b.is_empty() {
                    // TODO: sort by closest aspect ratio?
                    modes_b = modes_a.iter().collect();
                }

                modes_b.sort_by_key(|mode| Reverse(mode.resolution[0] * mode.resolution[1]));
                modes_b.into_iter().copied().collect()
            }
        };

        let best_resolution = modes[0].resolution;
        modes.retain(|mode| mode.resolution == best_resolution);
        modes.sort_by_key(|mode| Reverse(mode.refresh_rate));
        let best_refresh_rate = modes[0].refresh_rate;
        modes.retain(|mode| mode.refresh_rate == best_refresh_rate);
        modes.sort_by_key(|mode| Reverse(mode.bit_depth));
        let best_bit_depth = modes[0].bit_depth;
        modes.retain(|mode| mode.bit_depth == best_bit_depth);
        modes[0].clone()
    }

    pub(crate) fn from_winit(winit_monitor: WinitMonitorHandle) -> Option<Self> {
        // Should always be some, "Returns None if the monitor doesn’t exist anymore."
        let name = match winit_monitor.name() {
            Some(some) => some,
            None => return None,
        };

        let physical_size = winit_monitor.size();
        let resolution = [physical_size.width, physical_size.height];
        let physical_position = winit_monitor.position();
        let position = [physical_position.x, physical_position.y];

        let refresh_rate_op = winit_monitor
            .refresh_rate_millihertz()
            .map(|mhz| OrderedFloat::from(mhz as f32 / 1000.0));

        let modes: Vec<MonitorMode> = winit_monitor
            .video_modes()
            .map(|winit_mode| {
                let physical_size = winit_mode.size();
                let resolution = [physical_size.width, physical_size.height];
                let bit_depth = winit_mode.bit_depth();

                let refresh_rate =
                    OrderedFloat::from(winit_mode.refresh_rate_millihertz() as f32 / 1000.0);

                MonitorMode {
                    resolution,
                    bit_depth,
                    refresh_rate,
                    handle: winit_mode,
                    monitor_handle: winit_monitor.clone(),
                }
            })
            .collect();

        if modes.is_empty() {
            return None;
        }

        let refresh_rate = refresh_rate_op.unwrap_or_else(|| {
            modes
                .iter()
                .max_by_key(|mode| mode.refresh_rate)
                .unwrap()
                .refresh_rate
        });

        let bit_depth = modes
            .iter()
            .max_by_key(|mode| mode.bit_depth)
            .unwrap()
            .bit_depth;

        Some(Monitor {
            name,
            resolution,
            position,
            refresh_rate,
            bit_depth,
            is_current: false,
            is_primary: false,
            modes,
            handle: winit_monitor,
        })
    }
}

/// Determines how the application should go into full screen.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub enum FullScreenBehavior {
    #[default]
    /// **Default**
    ///
    /// If fullscreen exclusive support is enabled this uses, `AutoExclusive` otherwise `AutoBorderless`.
    Auto,
    /// Enable borderless full screen on a monitor determined by this order:
    /// 1. Current Monitor
    /// 2. Primary Monitor
    /// 3. Implementation decides
    AutoBorderless,
    /// Enable borderless full screen on the primary monitor.
    AutoBorderlessPrimary,
    /// Enable borderless full screen on the current monitor.
    AutoBorderlessCurrent,
    /// Enable borderless full screen on the provided monitor.
    Borderless(Monitor),
    /// Enable exclusive full screen on a monitor determined by this order:
    /// 1. Current Monitor
    /// 2. Primary Monitor
    /// 3. First enumerated
    AutoExclusive,
    /// Enable exclusive full screen on the primary monitor
    ///
    /// See `Monitor::optimal_mode` for how the mode is determined.
    AutoExclusivePrimary,
    /// Enable exclusive full screen on the current monitor
    ///
    /// See `Monitor::optimal_mode` for how the mode is determined.
    AutoExclusiveCurrent,
    /// Enable exclusive full screen on the provided monitor and automatically select the mode.
    ///
    /// See `Monitor::optimal_mode` for how the mode is determined.
    ExclusiveAutoMode(Monitor),
    /// Enable exclusive full screen on the provided monitor and mode.
    Exclusive(Monitor, MonitorMode),
}

impl FullScreenBehavior {
    /// Returns false for `Auto`
    pub fn is_exclusive(&self) -> bool {
        match self {
            Self::Auto => false,
            Self::AutoBorderless => false,
            Self::AutoBorderlessPrimary => false,
            Self::AutoBorderlessCurrent => false,
            Self::Borderless(_) => false,
            Self::AutoExclusive => true,
            Self::AutoExclusivePrimary => true,
            Self::AutoExclusiveCurrent => true,
            Self::ExclusiveAutoMode(_) => true,
            Self::Exclusive(..) => true,
        }
    }

    pub(crate) fn determine_winit_fullscreen(
        &self,
        fallback_borderless: bool,
        exclusive_supported: bool,
        current_monitor: Option<Monitor>,
        primary_monitor: Option<Monitor>,
        monitors: Vec<Monitor>,
    ) -> Result<WinitFullscreen, FullScreenError> {
        if self.is_exclusive() && !exclusive_supported {
            if !fallback_borderless {
                return Err(FullScreenError::ExclusiveNotSupported);
            }

            return match self {
                Self::AutoExclusive => Self::AutoBorderless,
                Self::AutoExclusivePrimary => Self::AutoBorderlessPrimary,
                Self::AutoExclusiveCurrent => Self::AutoBorderlessCurrent,
                Self::ExclusiveAutoMode(monitor) | Self::Exclusive(monitor, _) => {
                    Self::Borderless(monitor.clone())
                },
                _ => unreachable!(),
            }
            .determine_winit_fullscreen(
                true,
                false,
                current_monitor,
                primary_monitor,
                monitors,
            );
        }

        if *self == Self::Auto {
            return match exclusive_supported {
                true => Self::AutoExclusive,
                false => Self::AutoBorderless,
            }
            .determine_winit_fullscreen(
                fallback_borderless,
                exclusive_supported,
                current_monitor,
                primary_monitor,
                monitors,
            );
        }

        if self.is_exclusive() {
            let (monitor, mode) = match self.clone() {
                FullScreenBehavior::AutoExclusive => {
                    let monitor = match current_monitor {
                        Some(some) => some,
                        None => {
                            match primary_monitor {
                                Some(some) => some,
                                None => {
                                    match monitors.first() {
                                        Some(some) => some.clone(),
                                        None => return Err(FullScreenError::NoAvailableMonitors),
                                    }
                                },
                            }
                        },
                    };

                    let mode = monitor.optimal_mode();
                    (monitor, mode)
                },
                FullScreenBehavior::AutoExclusivePrimary => {
                    let monitor = match primary_monitor {
                        Some(some) => some,
                        None => return Err(FullScreenError::UnableToDeterminePrimary),
                    };

                    let mode = monitor.optimal_mode();
                    (monitor, mode)
                },
                FullScreenBehavior::AutoExclusiveCurrent => {
                    let monitor = match current_monitor {
                        Some(some) => some,
                        None => return Err(FullScreenError::UnableToDetermineCurrent),
                    };

                    let mode = monitor.optimal_mode();
                    (monitor, mode)
                },
                FullScreenBehavior::ExclusiveAutoMode(monitor) => {
                    let mode = monitor.optimal_mode();
                    (monitor, mode)
                },
                FullScreenBehavior::Exclusive(monitor, mode) => (monitor, mode),
                _ => unreachable!(),
            };

            if mode.monitor_handle != monitor.handle {
                return Err(FullScreenError::IncompatibleMonitorMode);
            }

            Ok(WinitFullscreen::Exclusive(mode.handle))
        } else {
            let monitor_op = match self.clone() {
                FullScreenBehavior::AutoBorderless => {
                    match current_monitor {
                        Some(some) => Some(some),
                        None => primary_monitor,
                    }
                },
                FullScreenBehavior::AutoBorderlessPrimary => {
                    match primary_monitor {
                        Some(some) => Some(some),
                        None => return Err(FullScreenError::UnableToDeterminePrimary),
                    }
                },
                FullScreenBehavior::AutoBorderlessCurrent => {
                    match current_monitor {
                        Some(some) => Some(some),
                        None => return Err(FullScreenError::UnableToDetermineCurrent),
                    }
                },
                FullScreenBehavior::Borderless(monitor) => Some(monitor),
                _ => unreachable!(),
            };

            Ok(WinitFullscreen::Borderless(
                monitor_op.map(|monitor| monitor.handle),
            ))
        }
    }
}

/// An error that can be returned from attempting to go full screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FullScreenError {
    /// The window implmentation is unable to determine the primary monitor.
    UnableToDeterminePrimary,
    /// The window implmentation is unable to determine the current monitor.
    UnableToDetermineCurrent,
    /// Attempted to use exclusive fullscreen, when it wasn't enabled.
    ///
    /// See: `BstOptions::use_exclusive_fullscreen`
    ExclusiveNotSupported,
    /// The monitor no longer exists.
    MonitorDoesNotExist,
    /// No available monitors
    NoAvailableMonitors,
    /// The provided mode doesn't belong to the monitor.
    IncompatibleMonitorMode,
}