1// todo!("windows"): remove
2#![allow(unused_variables)]
3
4use std::{
5 cell::RefCell,
6 collections::HashSet,
7 ffi::{c_uint, c_void},
8 path::{Path, PathBuf},
9 rc::Rc,
10 sync::Arc,
11 time::Duration,
12};
13
14use anyhow::{anyhow, Result};
15use async_task::Runnable;
16use futures::channel::oneshot::Receiver;
17use parking_lot::Mutex;
18use time::UtcOffset;
19use util::{ResultExt, SemanticVersion};
20use windows::Win32::{
21 Foundation::{CloseHandle, BOOL, HANDLE, HWND, LPARAM, TRUE},
22 Graphics::DirectComposition::DCompositionWaitForCompositorClock,
23 System::Threading::{CreateEventW, GetCurrentThreadId, INFINITE},
24 UI::WindowsAndMessaging::{
25 DispatchMessageW, EnumThreadWindows, PeekMessageW, PostQuitMessage, SystemParametersInfoW,
26 TranslateMessage, MSG, PM_REMOVE, SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES,
27 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WM_QUIT, WM_SETTINGCHANGE,
28 },
29};
30
31use crate::{
32 try_get_window_inner, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
33 ForegroundExecutor, Keymap, Menu, PathPromptOptions, Platform, PlatformDisplay, PlatformInput,
34 PlatformTextSystem, PlatformWindow, Task, WindowAppearance, WindowOptions, WindowsDispatcher,
35 WindowsDisplay, WindowsTextSystem, WindowsWindow,
36};
37
38pub(crate) struct WindowsPlatform {
39 inner: Rc<WindowsPlatformInner>,
40}
41
42/// Windows settings pulled from SystemParametersInfo
43/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
44#[derive(Default, Debug)]
45pub(crate) struct WindowsPlatformSystemSettings {
46 /// SEE: SPI_GETWHEELSCROLLCHARS
47 pub(crate) wheel_scroll_chars: u32,
48
49 /// SEE: SPI_GETWHEELSCROLLLINES
50 pub(crate) wheel_scroll_lines: u32,
51}
52
53pub(crate) struct WindowsPlatformInner {
54 background_executor: BackgroundExecutor,
55 pub(crate) foreground_executor: ForegroundExecutor,
56 main_receiver: flume::Receiver<Runnable>,
57 text_system: Arc<WindowsTextSystem>,
58 callbacks: Mutex<Callbacks>,
59 pub(crate) window_handles: RefCell<HashSet<AnyWindowHandle>>,
60 pub(crate) event: HANDLE,
61 pub(crate) settings: RefCell<WindowsPlatformSystemSettings>,
62}
63
64impl Drop for WindowsPlatformInner {
65 fn drop(&mut self) {
66 unsafe { CloseHandle(self.event) }.ok();
67 }
68}
69
70#[derive(Default)]
71struct Callbacks {
72 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
73 become_active: Option<Box<dyn FnMut()>>,
74 resign_active: Option<Box<dyn FnMut()>>,
75 quit: Option<Box<dyn FnMut()>>,
76 reopen: Option<Box<dyn FnMut()>>,
77 event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
78 app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
79 will_open_app_menu: Option<Box<dyn FnMut()>>,
80 validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
81}
82
83enum WindowsMessageWaitResult {
84 ForegroundExecution,
85 WindowsMessage(MSG),
86 Error,
87}
88
89impl WindowsPlatformSystemSettings {
90 fn new() -> Self {
91 let mut settings = Self::default();
92 settings.update_all();
93 settings
94 }
95
96 pub(crate) fn update_all(&mut self) {
97 self.update_wheel_scroll_lines();
98 self.update_wheel_scroll_chars();
99 }
100
101 pub(crate) fn update_wheel_scroll_lines(&mut self) {
102 let mut value = c_uint::default();
103 let result = unsafe {
104 SystemParametersInfoW(
105 SPI_GETWHEELSCROLLLINES,
106 0,
107 Some((&mut value) as *mut c_uint as *mut c_void),
108 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
109 )
110 };
111
112 if result.log_err() != None {
113 self.wheel_scroll_lines = value;
114 }
115 }
116
117 pub(crate) fn update_wheel_scroll_chars(&mut self) {
118 let mut value = c_uint::default();
119 let result = unsafe {
120 SystemParametersInfoW(
121 SPI_GETWHEELSCROLLCHARS,
122 0,
123 Some((&mut value) as *mut c_uint as *mut c_void),
124 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
125 )
126 };
127
128 if result.log_err() != None {
129 self.wheel_scroll_chars = value;
130 }
131 }
132}
133
134impl WindowsPlatform {
135 pub(crate) fn new() -> Self {
136 let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
137 let event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
138 let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, event));
139 let background_executor = BackgroundExecutor::new(dispatcher.clone());
140 let foreground_executor = ForegroundExecutor::new(dispatcher);
141 let text_system = Arc::new(WindowsTextSystem::new());
142 let callbacks = Mutex::new(Callbacks::default());
143 let window_handles = RefCell::new(HashSet::new());
144 let settings = RefCell::new(WindowsPlatformSystemSettings::new());
145 let inner = Rc::new(WindowsPlatformInner {
146 background_executor,
147 foreground_executor,
148 main_receiver,
149 text_system,
150 callbacks,
151 window_handles,
152 event,
153 settings,
154 });
155 Self { inner }
156 }
157
158 /// runs message handlers that should be processed before dispatching to prevent translating unnecessary messages
159 /// returns true if message is handled and should not dispatch
160 fn run_immediate_msg_handlers(&self, msg: &MSG) -> bool {
161 if msg.message == WM_SETTINGCHANGE {
162 self.inner.settings.borrow_mut().update_all();
163 return true;
164 }
165
166 if let Some(inner) = try_get_window_inner(msg.hwnd) {
167 inner.handle_immediate_msg(msg.message, msg.wParam, msg.lParam)
168 } else {
169 false
170 }
171 }
172
173 fn run_foreground_tasks(&self) {
174 for runnable in self.inner.main_receiver.drain() {
175 runnable.run();
176 }
177 }
178}
179
180unsafe extern "system" fn invalidate_window_callback(hwnd: HWND, _: LPARAM) -> BOOL {
181 if let Some(inner) = try_get_window_inner(hwnd) {
182 inner.invalidate_client_area();
183 }
184 TRUE
185}
186
187/// invalidates all windows belonging to a thread causing a paint message to be scheduled
188fn invalidate_thread_windows(win32_thread_id: u32) {
189 unsafe {
190 EnumThreadWindows(
191 win32_thread_id,
192 Some(invalidate_window_callback),
193 LPARAM::default(),
194 )
195 };
196}
197
198impl Platform for WindowsPlatform {
199 fn background_executor(&self) -> BackgroundExecutor {
200 self.inner.background_executor.clone()
201 }
202
203 fn foreground_executor(&self) -> ForegroundExecutor {
204 self.inner.foreground_executor.clone()
205 }
206
207 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
208 self.inner.text_system.clone()
209 }
210
211 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
212 on_finish_launching();
213 'a: loop {
214 let mut msg = MSG::default();
215 // will be 0 if woken up by self.inner.event or 1 if the compositor clock ticked
216 // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
217 let wait_result =
218 unsafe { DCompositionWaitForCompositorClock(Some(&[self.inner.event]), INFINITE) };
219
220 // compositor clock ticked so we should draw a frame
221 if wait_result == 1 {
222 unsafe { invalidate_thread_windows(GetCurrentThreadId()) };
223
224 while unsafe { PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE) }.as_bool()
225 {
226 if msg.message == WM_QUIT {
227 break 'a;
228 }
229
230 if !self.run_immediate_msg_handlers(&msg) {
231 unsafe { TranslateMessage(&msg) };
232 unsafe { DispatchMessageW(&msg) };
233 }
234 }
235 }
236
237 self.run_foreground_tasks();
238 }
239
240 let mut callbacks = self.inner.callbacks.lock();
241 if let Some(callback) = callbacks.quit.as_mut() {
242 callback()
243 }
244 }
245
246 fn quit(&self) {
247 self.foreground_executor()
248 .spawn(async { unsafe { PostQuitMessage(0) } })
249 .detach();
250 }
251
252 // todo!("windows")
253 fn restart(&self) {
254 unimplemented!()
255 }
256
257 // todo!("windows")
258 fn activate(&self, ignoring_other_apps: bool) {}
259
260 // todo!("windows")
261 fn hide(&self) {
262 unimplemented!()
263 }
264
265 // todo!("windows")
266 fn hide_other_apps(&self) {
267 unimplemented!()
268 }
269
270 // todo!("windows")
271 fn unhide_other_apps(&self) {
272 unimplemented!()
273 }
274
275 // todo!("windows")
276 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
277 vec![Rc::new(WindowsDisplay::new())]
278 }
279
280 // todo!("windows")
281 fn display(&self, id: crate::DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
282 Some(Rc::new(WindowsDisplay::new()))
283 }
284
285 // todo!("windows")
286 fn active_window(&self) -> Option<AnyWindowHandle> {
287 unimplemented!()
288 }
289
290 fn open_window(
291 &self,
292 handle: AnyWindowHandle,
293 options: WindowOptions,
294 ) -> Box<dyn PlatformWindow> {
295 Box::new(WindowsWindow::new(self.inner.clone(), handle, options))
296 }
297
298 // todo!("windows")
299 fn window_appearance(&self) -> WindowAppearance {
300 WindowAppearance::Dark
301 }
302
303 // todo!("windows")
304 fn open_url(&self, url: &str) {
305 // todo!("windows")
306 }
307
308 // todo!("windows")
309 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
310 self.inner.callbacks.lock().open_urls = Some(callback);
311 }
312
313 // todo!("windows")
314 fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
315 unimplemented!()
316 }
317
318 // todo!("windows")
319 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
320 unimplemented!()
321 }
322
323 // todo!("windows")
324 fn reveal_path(&self, path: &Path) {
325 unimplemented!()
326 }
327
328 fn on_become_active(&self, callback: Box<dyn FnMut()>) {
329 self.inner.callbacks.lock().become_active = Some(callback);
330 }
331
332 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
333 self.inner.callbacks.lock().resign_active = Some(callback);
334 }
335
336 fn on_quit(&self, callback: Box<dyn FnMut()>) {
337 self.inner.callbacks.lock().quit = Some(callback);
338 }
339
340 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
341 self.inner.callbacks.lock().reopen = Some(callback);
342 }
343
344 fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
345 self.inner.callbacks.lock().event = Some(callback);
346 }
347
348 // todo!("windows")
349 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
350
351 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
352 self.inner.callbacks.lock().app_menu_action = Some(callback);
353 }
354
355 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
356 self.inner.callbacks.lock().will_open_app_menu = Some(callback);
357 }
358
359 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
360 self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
361 }
362
363 fn os_name(&self) -> &'static str {
364 "Windows"
365 }
366
367 fn os_version(&self) -> Result<SemanticVersion> {
368 Ok(SemanticVersion {
369 major: 1,
370 minor: 0,
371 patch: 0,
372 })
373 }
374
375 fn app_version(&self) -> Result<SemanticVersion> {
376 Ok(SemanticVersion {
377 major: 1,
378 minor: 0,
379 patch: 0,
380 })
381 }
382
383 // todo!("windows")
384 fn app_path(&self) -> Result<PathBuf> {
385 Err(anyhow!("not yet implemented"))
386 }
387
388 // todo!("windows")
389 fn local_timezone(&self) -> UtcOffset {
390 UtcOffset::from_hms(9, 0, 0).unwrap()
391 }
392
393 // todo!("windows")
394 fn double_click_interval(&self) -> Duration {
395 Duration::from_millis(100)
396 }
397
398 // todo!("windows")
399 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
400 Err(anyhow!("not yet implemented"))
401 }
402
403 // todo!("windows")
404 fn set_cursor_style(&self, style: CursorStyle) {}
405
406 // todo!("windows")
407 fn should_auto_hide_scrollbars(&self) -> bool {
408 false
409 }
410
411 // todo!("windows")
412 fn write_to_clipboard(&self, item: ClipboardItem) {
413 unimplemented!()
414 }
415
416 // todo!("windows")
417 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
418 unimplemented!()
419 }
420
421 // todo!("windows")
422 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
423 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
424 }
425
426 // todo!("windows")
427 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
428 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
429 }
430
431 // todo!("windows")
432 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
433 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
434 }
435
436 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
437 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
438 }
439}