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
use std::{
    error::Error,
    os::windows::prelude::AsRawHandle,
    thread::{self, JoinHandle},
};

use log::{info, trace, warn};
use windows::{
    Foundation::AsyncActionCompletedHandler,
    Win32::{
        Foundation::{HANDLE, LPARAM, WPARAM},
        System::{
            Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED, COINIT_SPEED_OVER_MEMORY},
            Threading::GetThreadId,
            WinRT::{
                CreateDispatcherQueueController, DispatcherQueueOptions, DQTAT_COM_NONE,
                DQTYPE_THREAD_CURRENT,
            },
        },
        UI::{
            HiDpi::{SetProcessDpiAwareness, PROCESS_PER_MONITOR_DPI_AWARE},
            WindowsAndMessaging::{
                DispatchMessageW, GetMessageW, PostQuitMessage, PostThreadMessageW,
                TranslateMessage, MSG, WM_QUIT,
            },
        },
    },
};

use crate::{
    frame::Frame,
    graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl, RESULT},
    settings::WindowsCaptureSettings,
};

/// Used To Handle Capture Control Errors
#[derive(thiserror::Error, Eq, PartialEq, Clone, Copy, Debug)]
pub enum CaptureControlError {
    #[error("Failed To Join Thread")]
    FailedToJoin,
}

/// Struct Used To Control Capture Thread
pub struct CaptureControl {
    thread_handle: Option<JoinHandle<Result<(), Box<dyn Error + Send + Sync>>>>,
}

impl CaptureControl {
    /// Create A New Capture Control Struct
    #[must_use]
    pub fn new(thread_handle: JoinHandle<Result<(), Box<dyn Error + Send + Sync>>>) -> Self {
        Self {
            thread_handle: Some(thread_handle),
        }
    }

    /// Wait Until The Thread Stops
    pub fn wait(mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
        if let Some(thread_handle) = self.thread_handle.take() {
            match thread_handle.join() {
                Ok(result) => result?,
                Err(_) => {
                    return Err(Box::new(CaptureControlError::FailedToJoin));
                }
            }
        }

        Ok(())
    }

    /// Gracefully Stop The Capture Thread
    pub fn stop(mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
        if let Some(thread_handle) = self.thread_handle.take() {
            let handle = thread_handle.as_raw_handle();
            let handle = HANDLE(handle as isize);
            let therad_id = unsafe { GetThreadId(handle) };

            loop {
                match unsafe {
                    PostThreadMessageW(therad_id, WM_QUIT, WPARAM::default(), LPARAM::default())
                } {
                    Ok(_) => break,
                    Err(e) => {
                        if thread_handle.is_finished() {
                            break;
                        }

                        if e.code().0 == -2147023452 {
                            warn!("Thread Is Not In Message Loop Yet");
                        } else {
                            Err(e)?;
                        }
                    }
                }
            }

            match thread_handle.join() {
                Ok(result) => result?,
                Err(_) => {
                    return Err(Box::new(CaptureControlError::FailedToJoin));
                }
            }
        }

        Ok(())
    }
}

/// Event Handler Trait
pub trait WindowsCaptureHandler: Sized {
    /// To Get The Message From The Settings
    type Flags;

    /// Starts The Capture And Takes Control Of The Current Thread
    fn start(
        settings: WindowsCaptureSettings<Self::Flags>,
    ) -> Result<(), Box<dyn Error + Send + Sync>>
    where
        Self: Send + 'static,
        <Self as WindowsCaptureHandler>::Flags: Send,
    {
        // Initialize COM
        trace!("Initializing COM");
        unsafe { CoInitializeEx(None, COINIT_MULTITHREADED | COINIT_SPEED_OVER_MEMORY)? };

        // Set DPI Awarness
        trace!("Setting DPI Awarness");
        unsafe { SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE)? };

        // Create A Dispatcher Queue For Current Thread
        trace!("Creating A Dispatcher Queue For Capture Thread");
        let options = DispatcherQueueOptions {
            dwSize: std::mem::size_of::<DispatcherQueueOptions>() as u32,
            threadType: DQTYPE_THREAD_CURRENT,
            apartmentType: DQTAT_COM_NONE,
        };
        let controller = unsafe { CreateDispatcherQueueController(options)? };

        // Start Capture
        info!("Starting Capture Thread");
        let trigger = Self::new(settings.flags)?;
        let mut capture = GraphicsCaptureApi::new(
            settings.item,
            trigger,
            settings.capture_cursor,
            settings.draw_border,
            settings.color_format,
        )?;
        capture.start_capture()?;

        // Message Loop
        trace!("Entering Message Loop");
        let mut message = MSG::default();
        unsafe {
            while GetMessageW(&mut message, None, 0, 0).as_bool() {
                TranslateMessage(&message);
                DispatchMessageW(&message);
            }
        }

        // Shutdown Dispatcher Queue
        trace!("Shutting Down Dispatcher Queue");
        let async_action = controller.ShutdownQueueAsync()?;
        async_action.SetCompleted(&AsyncActionCompletedHandler::new(
            move |_, _| -> Result<(), windows::core::Error> {
                unsafe { PostQuitMessage(0) };
                Ok(())
            },
        ))?;

        // Final Message Loop
        trace!("Entering Final Message Loop");
        let mut message = MSG::default();
        unsafe {
            while GetMessageW(&mut message, None, 0, 0).as_bool() {
                TranslateMessage(&message);
                DispatchMessageW(&message);
            }
        }

        // Stop Capturing
        info!("Stopping Capture Thread");
        capture.stop_capture();

        // Uninitialize COM
        trace!("Uninitializing COM");
        unsafe { CoUninitialize() };

        // Check RESULT
        trace!("Checking RESULT");
        let result = RESULT.take().expect("Failed To Take RESULT");

        result?;

        Ok(())
    }

    /// Starts The Capture Without Taking Control Of The Current Thread
    fn start_free_threaded(settings: WindowsCaptureSettings<Self::Flags>) -> CaptureControl
    where
        Self: Send + 'static,
        <Self as WindowsCaptureHandler>::Flags: Send,
    {
        let thread_handle = thread::spawn(move || Self::start(settings));

        CaptureControl::new(thread_handle)
    }

    /// Function That Will Be Called To Create The Struct The Flags Can Be
    /// Passed From Settings
    fn new(flags: Self::Flags) -> Result<Self, Box<dyn Error + Send + Sync>>;

    /// Called Every Time A New Frame Is Available
    fn on_frame_arrived(
        &mut self,
        frame: Frame,
        capture_control: InternalCaptureControl,
    ) -> Result<(), Box<dyn Error + Send + Sync>>;

    /// Called When The Capture Item Closes Usually When The Window Closes,
    /// Capture Session Will End After This Function Ends
    fn on_closed(&mut self) -> Result<(), Box<dyn Error + Send + Sync>>;

    /// Call To Stop The Capture Thread, You Might Receive A Few More Frames
    /// Before It Stops
    fn stop(&self) {
        unsafe { PostQuitMessage(0) };
    }
}