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::{
21 core::{HSTRING, PCWSTR},
22 Wdk::System::SystemServices::RtlGetVersion,
23 Win32::{
24 Foundation::{CloseHandle, BOOL, HANDLE, HWND, LPARAM, TRUE},
25 Graphics::DirectComposition::DCompositionWaitForCompositorClock,
26 System::{
27 Threading::{CreateEventW, GetCurrentThreadId, INFINITE},
28 Time::{GetTimeZoneInformation, TIME_ZONE_ID_INVALID},
29 },
30 UI::{
31 Input::KeyboardAndMouse::GetDoubleClickTime,
32 Shell::ShellExecuteW,
33 WindowsAndMessaging::{
34 DispatchMessageW, EnumThreadWindows, LoadImageW, MsgWaitForMultipleObjects,
35 PeekMessageW, PostQuitMessage, SetCursor, SystemParametersInfoW, TranslateMessage,
36 HCURSOR, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_IBEAM, IDC_NO, IDC_SIZENS, IDC_SIZEWE,
37 IMAGE_CURSOR, LR_DEFAULTSIZE, LR_SHARED, MSG, PM_REMOVE, QS_ALLINPUT,
38 SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES, SW_SHOWDEFAULT,
39 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WM_QUIT, WM_SETTINGCHANGE,
40 },
41 },
42 },
43};
44
45use crate::{
46 try_get_window_inner, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
47 ForegroundExecutor, Keymap, Menu, PathPromptOptions, Platform, PlatformDisplay, PlatformInput,
48 PlatformTextSystem, PlatformWindow, Task, WindowAppearance, WindowOptions, WindowsDispatcher,
49 WindowsDisplay, WindowsTextSystem, WindowsWindow,
50};
51
52pub(crate) struct WindowsPlatform {
53 inner: Rc<WindowsPlatformInner>,
54}
55
56/// Windows settings pulled from SystemParametersInfo
57/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
58#[derive(Default, Debug)]
59pub(crate) struct WindowsPlatformSystemSettings {
60 /// SEE: SPI_GETWHEELSCROLLCHARS
61 pub(crate) wheel_scroll_chars: u32,
62
63 /// SEE: SPI_GETWHEELSCROLLLINES
64 pub(crate) wheel_scroll_lines: u32,
65}
66
67pub(crate) struct WindowsPlatformInner {
68 background_executor: BackgroundExecutor,
69 pub(crate) foreground_executor: ForegroundExecutor,
70 main_receiver: flume::Receiver<Runnable>,
71 text_system: Arc<WindowsTextSystem>,
72 callbacks: Mutex<Callbacks>,
73 pub(crate) window_handles: RefCell<HashSet<AnyWindowHandle>>,
74 pub(crate) event: HANDLE,
75 pub(crate) settings: RefCell<WindowsPlatformSystemSettings>,
76}
77
78impl Drop for WindowsPlatformInner {
79 fn drop(&mut self) {
80 unsafe { CloseHandle(self.event) }.ok();
81 }
82}
83
84#[derive(Default)]
85struct Callbacks {
86 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
87 become_active: Option<Box<dyn FnMut()>>,
88 resign_active: Option<Box<dyn FnMut()>>,
89 quit: Option<Box<dyn FnMut()>>,
90 reopen: Option<Box<dyn FnMut()>>,
91 event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
92 app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
93 will_open_app_menu: Option<Box<dyn FnMut()>>,
94 validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
95}
96
97enum WindowsMessageWaitResult {
98 ForegroundExecution,
99 WindowsMessage(MSG),
100 Error,
101}
102
103impl WindowsPlatformSystemSettings {
104 fn new() -> Self {
105 let mut settings = Self::default();
106 settings.update_all();
107 settings
108 }
109
110 pub(crate) fn update_all(&mut self) {
111 self.update_wheel_scroll_lines();
112 self.update_wheel_scroll_chars();
113 }
114
115 pub(crate) fn update_wheel_scroll_lines(&mut self) {
116 let mut value = c_uint::default();
117 let result = unsafe {
118 SystemParametersInfoW(
119 SPI_GETWHEELSCROLLLINES,
120 0,
121 Some((&mut value) as *mut c_uint as *mut c_void),
122 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
123 )
124 };
125
126 if result.log_err() != None {
127 self.wheel_scroll_lines = value;
128 }
129 }
130
131 pub(crate) fn update_wheel_scroll_chars(&mut self) {
132 let mut value = c_uint::default();
133 let result = unsafe {
134 SystemParametersInfoW(
135 SPI_GETWHEELSCROLLCHARS,
136 0,
137 Some((&mut value) as *mut c_uint as *mut c_void),
138 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
139 )
140 };
141
142 if result.log_err() != None {
143 self.wheel_scroll_chars = value;
144 }
145 }
146}
147
148impl WindowsPlatform {
149 pub(crate) fn new() -> Self {
150 let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
151 let event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
152 let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, event));
153 let background_executor = BackgroundExecutor::new(dispatcher.clone());
154 let foreground_executor = ForegroundExecutor::new(dispatcher);
155 let text_system = Arc::new(WindowsTextSystem::new());
156 let callbacks = Mutex::new(Callbacks::default());
157 let window_handles = RefCell::new(HashSet::new());
158 let settings = RefCell::new(WindowsPlatformSystemSettings::new());
159 let inner = Rc::new(WindowsPlatformInner {
160 background_executor,
161 foreground_executor,
162 main_receiver,
163 text_system,
164 callbacks,
165 window_handles,
166 event,
167 settings,
168 });
169 Self { inner }
170 }
171
172 /// runs message handlers that should be processed before dispatching to prevent translating unnecessary messages
173 /// returns true if message is handled and should not dispatch
174 fn run_immediate_msg_handlers(&self, msg: &MSG) -> bool {
175 if msg.message == WM_SETTINGCHANGE {
176 self.inner.settings.borrow_mut().update_all();
177 return true;
178 }
179
180 if let Some(inner) = try_get_window_inner(msg.hwnd) {
181 inner.handle_immediate_msg(msg.message, msg.wParam, msg.lParam)
182 } else {
183 false
184 }
185 }
186
187 fn run_foreground_tasks(&self) {
188 for runnable in self.inner.main_receiver.drain() {
189 runnable.run();
190 }
191 }
192}
193
194unsafe extern "system" fn invalidate_window_callback(hwnd: HWND, _: LPARAM) -> BOOL {
195 if let Some(inner) = try_get_window_inner(hwnd) {
196 inner.invalidate_client_area();
197 }
198 TRUE
199}
200
201/// invalidates all windows belonging to a thread causing a paint message to be scheduled
202fn invalidate_thread_windows(win32_thread_id: u32) {
203 unsafe {
204 EnumThreadWindows(
205 win32_thread_id,
206 Some(invalidate_window_callback),
207 LPARAM::default(),
208 )
209 };
210}
211
212impl Platform for WindowsPlatform {
213 fn background_executor(&self) -> BackgroundExecutor {
214 self.inner.background_executor.clone()
215 }
216
217 fn foreground_executor(&self) -> ForegroundExecutor {
218 self.inner.foreground_executor.clone()
219 }
220
221 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
222 self.inner.text_system.clone()
223 }
224
225 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
226 on_finish_launching();
227 'a: loop {
228 let mut msg = MSG::default();
229 // will be 0 if woken up by self.inner.event or 1 if the compositor clock ticked
230 // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
231 let wait_result =
232 unsafe { DCompositionWaitForCompositorClock(Some(&[self.inner.event]), INFINITE) };
233
234 // compositor clock ticked so we should draw a frame
235 if wait_result == 1 {
236 unsafe { invalidate_thread_windows(GetCurrentThreadId()) };
237
238 while unsafe { PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE) }.as_bool()
239 {
240 if msg.message == WM_QUIT {
241 break 'a;
242 }
243
244 if !self.run_immediate_msg_handlers(&msg) {
245 unsafe { TranslateMessage(&msg) };
246 unsafe { DispatchMessageW(&msg) };
247 }
248 }
249 }
250
251 self.run_foreground_tasks();
252 }
253
254 let mut callbacks = self.inner.callbacks.lock();
255 if let Some(callback) = callbacks.quit.as_mut() {
256 callback()
257 }
258 }
259
260 fn quit(&self) {
261 self.foreground_executor()
262 .spawn(async { unsafe { PostQuitMessage(0) } })
263 .detach();
264 }
265
266 // todo(windows)
267 fn restart(&self) {
268 unimplemented!()
269 }
270
271 // todo(windows)
272 fn activate(&self, ignoring_other_apps: bool) {}
273
274 // todo(windows)
275 fn hide(&self) {
276 unimplemented!()
277 }
278
279 // todo(windows)
280 fn hide_other_apps(&self) {
281 unimplemented!()
282 }
283
284 // todo(windows)
285 fn unhide_other_apps(&self) {
286 unimplemented!()
287 }
288
289 // todo(windows)
290 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
291 vec![Rc::new(WindowsDisplay::new())]
292 }
293
294 // todo(windows)
295 fn display(&self, id: crate::DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
296 Some(Rc::new(WindowsDisplay::new()))
297 }
298
299 // todo(windows)
300 fn active_window(&self) -> Option<AnyWindowHandle> {
301 unimplemented!()
302 }
303
304 fn open_window(
305 &self,
306 handle: AnyWindowHandle,
307 options: WindowOptions,
308 ) -> Box<dyn PlatformWindow> {
309 Box::new(WindowsWindow::new(self.inner.clone(), handle, options))
310 }
311
312 // todo(windows)
313 fn window_appearance(&self) -> WindowAppearance {
314 WindowAppearance::Dark
315 }
316
317 fn open_url(&self, url: &str) {
318 let url_string = url.to_string();
319 self.background_executor()
320 .spawn(async move {
321 if url_string.is_empty() {
322 return;
323 }
324 open_target(url_string.as_str());
325 })
326 .detach();
327 }
328
329 // todo(windows)
330 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
331 self.inner.callbacks.lock().open_urls = Some(callback);
332 }
333
334 // todo(windows)
335 fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
336 unimplemented!()
337 }
338
339 // todo(windows)
340 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
341 unimplemented!()
342 }
343
344 fn reveal_path(&self, path: &Path) {
345 let Ok(file_full_path) = path.canonicalize() else {
346 log::error!("unable to parse file path");
347 return;
348 };
349 self.background_executor()
350 .spawn(async move {
351 let Some(path) = file_full_path.to_str() else {
352 return;
353 };
354 if path.is_empty() {
355 return;
356 }
357 open_target(path);
358 })
359 .detach();
360 }
361
362 fn on_become_active(&self, callback: Box<dyn FnMut()>) {
363 self.inner.callbacks.lock().become_active = Some(callback);
364 }
365
366 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
367 self.inner.callbacks.lock().resign_active = Some(callback);
368 }
369
370 fn on_quit(&self, callback: Box<dyn FnMut()>) {
371 self.inner.callbacks.lock().quit = Some(callback);
372 }
373
374 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
375 self.inner.callbacks.lock().reopen = Some(callback);
376 }
377
378 fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
379 self.inner.callbacks.lock().event = Some(callback);
380 }
381
382 // todo(windows)
383 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
384
385 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
386 self.inner.callbacks.lock().app_menu_action = Some(callback);
387 }
388
389 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
390 self.inner.callbacks.lock().will_open_app_menu = Some(callback);
391 }
392
393 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
394 self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
395 }
396
397 fn os_name(&self) -> &'static str {
398 "Windows"
399 }
400
401 fn os_version(&self) -> Result<SemanticVersion> {
402 let mut info = unsafe { std::mem::zeroed() };
403 let status = unsafe { RtlGetVersion(&mut info) };
404 if status.is_ok() {
405 Ok(SemanticVersion {
406 major: info.dwMajorVersion as _,
407 minor: info.dwMinorVersion as _,
408 patch: info.dwBuildNumber as _,
409 })
410 } else {
411 Err(anyhow::anyhow!(
412 "unable to get Windows version: {}",
413 std::io::Error::last_os_error()
414 ))
415 }
416 }
417
418 fn app_version(&self) -> Result<SemanticVersion> {
419 Ok(SemanticVersion {
420 major: 1,
421 minor: 0,
422 patch: 0,
423 })
424 }
425
426 // todo(windows)
427 fn app_path(&self) -> Result<PathBuf> {
428 Err(anyhow!("not yet implemented"))
429 }
430
431 fn local_timezone(&self) -> UtcOffset {
432 let mut info = unsafe { std::mem::zeroed() };
433 let ret = unsafe { GetTimeZoneInformation(&mut info) };
434 if ret == TIME_ZONE_ID_INVALID {
435 log::error!(
436 "Unable to get local timezone: {}",
437 std::io::Error::last_os_error()
438 );
439 return UtcOffset::UTC;
440 }
441 // Windows treat offset as:
442 // UTC = localtime + offset
443 // so we add a minus here
444 let hours = -info.Bias / 60;
445 let minutes = -info.Bias % 60;
446
447 UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
448 }
449
450 fn double_click_interval(&self) -> Duration {
451 let millis = unsafe { GetDoubleClickTime() };
452 Duration::from_millis(millis as _)
453 }
454
455 // todo(windows)
456 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
457 Err(anyhow!("not yet implemented"))
458 }
459
460 fn set_cursor_style(&self, style: CursorStyle) {
461 let handle = match style {
462 CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => unsafe {
463 load_cursor(IDC_IBEAM)
464 },
465 CursorStyle::Crosshair => unsafe { load_cursor(IDC_CROSS) },
466 CursorStyle::PointingHand | CursorStyle::DragLink => unsafe { load_cursor(IDC_HAND) },
467 CursorStyle::ResizeLeft | CursorStyle::ResizeRight | CursorStyle::ResizeLeftRight => unsafe {
468 load_cursor(IDC_SIZEWE)
469 },
470 CursorStyle::ResizeUp | CursorStyle::ResizeDown | CursorStyle::ResizeUpDown => unsafe {
471 load_cursor(IDC_SIZENS)
472 },
473 CursorStyle::OperationNotAllowed => unsafe { load_cursor(IDC_NO) },
474 _ => unsafe { load_cursor(IDC_ARROW) },
475 };
476 if handle.is_err() {
477 log::error!(
478 "Error loading cursor image: {}",
479 std::io::Error::last_os_error()
480 );
481 return;
482 }
483 let _ = unsafe { SetCursor(HCURSOR(handle.unwrap().0)) };
484 }
485
486 // todo(windows)
487 fn should_auto_hide_scrollbars(&self) -> bool {
488 false
489 }
490
491 // todo(windows)
492 fn write_to_clipboard(&self, item: ClipboardItem) {
493 unimplemented!()
494 }
495
496 // todo(windows)
497 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
498 unimplemented!()
499 }
500
501 // todo(windows)
502 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
503 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
504 }
505
506 // todo(windows)
507 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
508 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
509 }
510
511 // todo(windows)
512 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
513 Task::Ready(Some(Err(anyhow!("not implemented yet."))))
514 }
515
516 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
517 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
518 }
519}
520
521unsafe fn load_cursor(name: PCWSTR) -> Result<HANDLE> {
522 LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED).map_err(|e| anyhow!(e))
523}
524
525fn open_target(target: &str) {
526 unsafe {
527 let ret = ShellExecuteW(
528 None,
529 windows::core::w!("open"),
530 &HSTRING::from(target),
531 None,
532 None,
533 SW_SHOWDEFAULT,
534 );
535 if ret.0 <= 32 {
536 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
537 }
538 }
539}