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
use windows::Win32::Graphics::{
  Dxgi::{DXGI_OUTDUPL_DESC, DXGI_OUTDUPL_FRAME_INFO, DXGI_OUTPUT_DESC},
  Gdi::MONITORINFO,
};

pub trait OutputDescExt {
  fn width(&self) -> u32;
  fn height(&self) -> u32;
}

impl OutputDescExt for DXGI_OUTPUT_DESC {
  fn width(&self) -> u32 {
    (self.DesktopCoordinates.right - self.DesktopCoordinates.left) as u32
  }
  fn height(&self) -> u32 {
    (self.DesktopCoordinates.bottom - self.DesktopCoordinates.top) as u32
  }
}

pub trait OutDuplDescExt {
  fn calc_buffer_size(&self) -> usize;
}

impl OutDuplDescExt for DXGI_OUTDUPL_DESC {
  /// Return needed buffer size, in bytes.
  fn calc_buffer_size(&self) -> usize {
    (self.ModeDesc.Width * self.ModeDesc.Height * 4) as usize // 4 for BGRA32
  }
}

pub trait FrameInfoExt {
  fn desktop_updated(&self) -> bool;
  fn mouse_updated(&self) -> bool;
}

impl FrameInfoExt for DXGI_OUTDUPL_FRAME_INFO {
  fn desktop_updated(&self) -> bool {
    self.LastPresentTime > 0
  }

  /// Return true if mouse's shape or/and position is updated.
  fn mouse_updated(&self) -> bool {
    self.LastMouseUpdateTime > 0
  }
}

pub trait MonitorInfoExt {
  fn is_primary(&self) -> bool;
}

impl MonitorInfoExt for MONITORINFO {
  fn is_primary(&self) -> bool {
    self.dwFlags == 0x01 // MONITORINFOF_PRIMARY
  }
}

#[cfg(test)]
mod tests {
  use windows::Win32::Graphics::{
    Dxgi::{DXGI_OUTDUPL_DESC, DXGI_OUTDUPL_FRAME_INFO, DXGI_OUTPUT_DESC},
    Gdi::MONITORINFO,
  };

  use crate::utils::{FrameInfoExt, MonitorInfoExt, OutDuplDescExt, OutputDescExt};

  #[test]
  fn output_desc_ext() {
    let mut desc = DXGI_OUTPUT_DESC::default();
    desc.DesktopCoordinates.left = 0;
    desc.DesktopCoordinates.top = 0;
    desc.DesktopCoordinates.right = 1920;
    desc.DesktopCoordinates.bottom = 1080;
    assert_eq!(desc.width(), 1920);
    assert_eq!(desc.height(), 1080);
  }

  #[test]
  fn out_dupl_desc_ext() {
    let mut desc = DXGI_OUTDUPL_DESC::default();
    desc.ModeDesc.Width = 1920;
    desc.ModeDesc.Height = 1080;
    assert_eq!(desc.calc_buffer_size(), 1920 * 1080 * 4);
  }

  #[test]
  fn frame_info_ext() {
    let mut desc = DXGI_OUTDUPL_FRAME_INFO::default();
    assert!(!desc.desktop_updated());
    desc.LastPresentTime = 1;
    assert!(desc.desktop_updated());
    assert!(!desc.mouse_updated());
    desc.LastMouseUpdateTime = 1;
    assert!(desc.mouse_updated());
  }

  #[test]
  fn monitor_info_ext() {
    let mut info = MONITORINFO::default();
    assert!(!info.is_primary());
    info.dwFlags = 0x01;
    assert!(info.is_primary());
  }
}