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
use std::{error::Error, fmt::{Debug, Display}};

use crate::{platform::platform_impl::{ImplCapturableApplication, ImplCapturableContent, ImplCapturableContentFilter, ImplCapturableDisplay, ImplCapturableWindow}, util::Rect};

/// Represents an error that occurred when enumerating capturable content
#[derive(Debug, Clone)]
pub enum CapturableContentError {
    Other(String)
}

impl Display for CapturableContentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Other(message) => f.write_fmt(format_args!("CapturableContentError::Other(\"{}\")", message))
        }
    }
}

impl Error for CapturableContentError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }

    fn description(&self) -> &str {
        "description() is deprecated; use Display"
    }

    fn cause(&self) -> Option<&dyn Error> {
        self.source()
    }
}

#[derive(Clone)]
/// Selects the kind of windows to enumerate for capture
pub struct CapturableWindowFilter {
    /// Desktop windows are elements of the desktop environment, E.G. the dock on MacOS or the start bar on Windows.
    pub desktop_windows: bool,
    /// Whether to restrict to onscreen windows
    pub onscreen_only: bool,
}

impl Default for CapturableWindowFilter {
    fn default() -> Self {
        Self { desktop_windows: false, onscreen_only: true }
    }
}

#[derive(Clone)]
/// Selects the kind of capturable content to enumerate
pub struct CapturableContentFilter {
    /// What kind of capturable windows, if Some, to enumerate
    pub(crate) windows: Option<CapturableWindowFilter>,
    /// Whether to enumerate capturable displays
    pub(crate) displays: bool,
    /// Platform-specific filtering options
    pub(crate) impl_capturable_content_filter: ImplCapturableContentFilter,
}

impl CapturableContentFilter {
    /// Create a new content filter with the given filtering options
    pub fn new(displays: bool, windows: Option<CapturableWindowFilter>) -> Self {
        Self {
            displays,
            windows,
            impl_capturable_content_filter: ImplCapturableContentFilter::default()
        }
    }

    /// Whether this filter allows any capturable content
    pub fn is_empty(&self) -> bool {
        !(
            self.windows.is_some() ||
            self.displays
        )
    }

    /// All capturable displays, but no windows
    pub const DISPLAYS: Self = CapturableContentFilter {
        windows: None,
        displays: true,
        impl_capturable_content_filter: ImplCapturableContentFilter::DEFAULT,
    };

    /// All capturable windows, but no displays
    pub const ALL_WINDOWS: Self = CapturableContentFilter {
        windows: Some(CapturableWindowFilter {
            desktop_windows: true,
            onscreen_only: false,
        }),
        displays: false,
        impl_capturable_content_filter: ImplCapturableContentFilter::DEFAULT,
    };

    /// Everything that can be captured
    pub const EVERYTHING: Self = CapturableContentFilter {
        windows: Some(CapturableWindowFilter {
            desktop_windows: true,
            onscreen_only: false,
        }),
        displays: true,
        impl_capturable_content_filter: ImplCapturableContentFilter::DEFAULT,
    };

    /// Only normal windows - no modal panels, not the dock on macos, etc.
    pub const NORMAL_WINDOWS: Self = CapturableContentFilter {
        windows: Some(CapturableWindowFilter {
            desktop_windows: false,
            onscreen_only: true
        }),
        displays: false,
        impl_capturable_content_filter: ImplCapturableContentFilter::NORMAL_WINDOWS,
    };

    /// Only normal windows and displays
    pub const EVERYTHING_NORMAL: Self = CapturableContentFilter {
        windows: Some(CapturableWindowFilter {
            desktop_windows: false,
            onscreen_only: true,
        }),
        displays: true,
        impl_capturable_content_filter: ImplCapturableContentFilter::NORMAL_WINDOWS,
    };
}

/// A collection of capturable content (windows, screens)
pub struct CapturableContent {
    impl_capturable_content: ImplCapturableContent
}

unsafe impl Send for CapturableContent {}
unsafe impl Sync for CapturableContent {}

/// An iterator over capturable windows
pub struct CapturableWindowIterator<'content> {
    content: &'content CapturableContent,
    i: usize
}

impl Iterator for CapturableWindowIterator<'_> {
    type Item = CapturableWindow;

    fn next(&mut self) -> Option<Self::Item> {
        if self.i < self.content.impl_capturable_content.windows.len() {
            let i = self.i;
            self.i += 1;
            Some(CapturableWindow { impl_capturable_window: ImplCapturableWindow::from_impl(self.content.impl_capturable_content.windows[i].clone()) })
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.i, Some(self.content.impl_capturable_content.windows.len()))
    }
}

impl ExactSizeIterator for CapturableWindowIterator<'_> {
}

/// An iterator over capturable displays
pub struct CapturableDisplayIterator<'content> {
    content: &'content CapturableContent,
    i: usize
}

impl Iterator for CapturableDisplayIterator<'_> {
    type Item = CapturableDisplay;

    fn next(&mut self) -> Option<Self::Item> {
        if self.i < self.content.impl_capturable_content.displays.len() {
            let i = self.i;
            self.i += 1;
            Some(CapturableDisplay { impl_capturable_display: ImplCapturableDisplay::from_impl(self.content.impl_capturable_content.displays[i].clone()) })
        } else {
            None
        }
    }
    
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.i, Some(self.content.impl_capturable_content.displays.len()))
    }
}

impl ExactSizeIterator for CapturableDisplayIterator<'_> {
    fn len(&self) -> usize {
        self.content.impl_capturable_content.displays.len()
    }
}

impl CapturableContent {
    /// Requests capturable content from the OS
    /// 
    /// Note that the returned capturable content may be stale - for example, a window enumerated in this capturable content
    /// may have been closed before it is used to open a stream, and creating a stream for that window will result in an error.
    pub async fn new(filter: CapturableContentFilter) -> Result<Self, CapturableContentError> {
        Ok(Self {
            impl_capturable_content: ImplCapturableContent::new(filter).await?
        })
    }

    /// Get an iterator over the capturable windows
    pub fn windows<'a>(&'a self) -> CapturableWindowIterator<'a> {
        CapturableWindowIterator { content: self, i: 0 }
    }

    /// Get an iterator over the capturable displays
    pub fn displays<'a>(&'a self) -> CapturableDisplayIterator<'a> {
        CapturableDisplayIterator { content: self, i: 0 }
    }
}

#[derive(Clone, Debug)]
pub(crate) enum Capturable {
    Window(CapturableWindow),
    Display(CapturableDisplay),
}

/// Represents a capturable application window
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct CapturableWindow {
    pub(crate) impl_capturable_window: ImplCapturableWindow
}

unsafe impl Send for CapturableWindow {}
unsafe impl Sync for CapturableWindow {}

impl CapturableWindow {
    /// Gets the title of the window
    pub fn title(&self) -> String {
        self.impl_capturable_window.title()
    }

    /// Gets the virtual screen rectangle of the window
    pub fn rect(&self) -> Rect {
        self.impl_capturable_window.rect()
    }

    /// Gets the application that owns this window
    pub fn application(&self) -> CapturableApplication {
        CapturableApplication {
            impl_capturable_application: self.impl_capturable_window.application()
        }
    }

    /// Checks whether an application is visible (on-screen, not minimized)
    pub fn is_visible(&self) -> bool {
        self.impl_capturable_window.is_visible()
    }
}

/// Represents a capturable display
#[derive(Debug, Clone)]
pub struct CapturableDisplay {
    pub(crate) impl_capturable_display: ImplCapturableDisplay
}

impl CapturableDisplay {
    /// Gets the virtual screen rectangle of this display
    /// 
    /// Note: Currently on windows, this is only evaluated at the time of display enumeration
    pub fn rect(&self) -> Rect {
        self.impl_capturable_display.rect()
    }
}

unsafe impl Send for CapturableDisplay {}
unsafe impl Sync for CapturableDisplay {}

/// Represents an application with capturable windows
pub struct CapturableApplication {
    impl_capturable_application: ImplCapturableApplication
}

impl CapturableApplication {
    /// Gets the "identifier" of the application
    /// 
    /// On MacOS, this is the application bundle, and on windows, this is the application file name
    pub fn identifier(&self) -> String {
        self.impl_capturable_application.identifier()
    }

    /// Gets the friendly name of the application
    pub fn name(&self) -> String {
        self.impl_capturable_application.name()
    }

    /// Gets the process id of the application
    pub fn pid(&self) -> i32 {
        self.impl_capturable_application.pid()
    }
}