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

pub type Result<T> = result::Result<T, String>;

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

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
  }

  /// Return needed buffer size, in bytes.
  fn calc_buffer_size(&self) -> usize {
    (self.width() * self.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
  }

  fn mouse_updated(&self) -> bool {
    self.LastMouseUpdateTime == 0
  }
}

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

  use crate::utils::{FrameInfoExt, 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);
    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());
  }
}