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