platform.rs

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