platform.rs

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