platform.rs

  1// todo(windows): remove
  2#![allow(unused_variables)]
  3
  4use std::{
  5    cell::{Cell, RefCell},
  6    ffi::{c_void, OsString},
  7    os::windows::ffi::{OsStrExt, OsStringExt},
  8    path::{Path, PathBuf},
  9    rc::Rc,
 10    sync::Arc,
 11};
 12
 13use ::util::ResultExt;
 14use anyhow::{anyhow, Context, Result};
 15use clipboard_win::{get_clipboard_string, set_clipboard_string};
 16use futures::channel::oneshot::{self, Receiver};
 17use itertools::Itertools;
 18use parking_lot::RwLock;
 19use smallvec::SmallVec;
 20use time::UtcOffset;
 21use windows::{
 22    core::*,
 23    Win32::{
 24        Foundation::*,
 25        Graphics::Gdi::*,
 26        Security::Credentials::*,
 27        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*, Time::*},
 28        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 29    },
 30    UI::ViewManagement::UISettings,
 31};
 32
 33use crate::*;
 34
 35pub(crate) struct WindowsPlatform {
 36    state: RefCell<WindowsPlatformState>,
 37    raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 38    // The below members will never change throughout the entire lifecycle of the app.
 39    icon: HICON,
 40    background_executor: BackgroundExecutor,
 41    foreground_executor: ForegroundExecutor,
 42    text_system: Arc<dyn PlatformTextSystem>,
 43}
 44
 45pub(crate) struct WindowsPlatformState {
 46    callbacks: PlatformCallbacks,
 47    // NOTE: standard cursor handles don't need to close.
 48    pub(crate) current_cursor: HCURSOR,
 49}
 50
 51#[derive(Default)]
 52struct PlatformCallbacks {
 53    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 54    quit: Option<Box<dyn FnMut()>>,
 55    reopen: Option<Box<dyn FnMut()>>,
 56    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 57    will_open_app_menu: Option<Box<dyn FnMut()>>,
 58    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 59}
 60
 61impl WindowsPlatformState {
 62    fn new() -> Self {
 63        let callbacks = PlatformCallbacks::default();
 64        let current_cursor = load_cursor(CursorStyle::Arrow);
 65
 66        Self {
 67            callbacks,
 68            current_cursor,
 69        }
 70    }
 71}
 72
 73impl WindowsPlatform {
 74    pub(crate) fn new() -> Self {
 75        unsafe {
 76            OleInitialize(None).expect("unable to initialize Windows OLE");
 77        }
 78        let dispatcher = Arc::new(WindowsDispatcher::new());
 79        let background_executor = BackgroundExecutor::new(dispatcher.clone());
 80        let foreground_executor = ForegroundExecutor::new(dispatcher);
 81        let text_system = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
 82            log::info!("Using direct write text system.");
 83            Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
 84        } else {
 85            log::info!("Using cosmic text system.");
 86            Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
 87        };
 88        let icon = load_icon().unwrap_or_default();
 89        let state = RefCell::new(WindowsPlatformState::new());
 90        let raw_window_handles = RwLock::new(SmallVec::new());
 91
 92        Self {
 93            state,
 94            raw_window_handles,
 95            icon,
 96            background_executor,
 97            foreground_executor,
 98            text_system,
 99        }
100    }
101
102    fn redraw_all(&self) {
103        for handle in self.raw_window_handles.read().iter() {
104            unsafe {
105                RedrawWindow(
106                    *handle,
107                    None,
108                    HRGN::default(),
109                    RDW_INVALIDATE | RDW_UPDATENOW,
110                )
111                .ok()
112                .log_err();
113            }
114        }
115    }
116
117    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
118        self.raw_window_handles
119            .read()
120            .iter()
121            .find(|entry| *entry == &hwnd)
122            .and_then(|hwnd| try_get_window_inner(*hwnd))
123    }
124
125    #[inline]
126    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
127        self.raw_window_handles
128            .read()
129            .iter()
130            .for_each(|handle| unsafe {
131                PostMessageW(*handle, message, wparam, lparam).log_err();
132            });
133    }
134
135    fn close_one_window(&self, target_window: HWND) -> bool {
136        let mut lock = self.raw_window_handles.write();
137        let index = lock
138            .iter()
139            .position(|handle| *handle == target_window)
140            .unwrap();
141        lock.remove(index);
142
143        lock.is_empty()
144    }
145}
146
147impl Platform for WindowsPlatform {
148    fn background_executor(&self) -> BackgroundExecutor {
149        self.background_executor.clone()
150    }
151
152    fn foreground_executor(&self) -> ForegroundExecutor {
153        self.foreground_executor.clone()
154    }
155
156    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
157        self.text_system.clone()
158    }
159
160    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
161        on_finish_launching();
162        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
163        begin_vsync(*vsync_event);
164        'a: loop {
165            let wait_result = unsafe {
166                MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
167            };
168
169            match wait_result {
170                // compositor clock ticked so we should draw a frame
171                WAIT_EVENT(0) => {
172                    self.redraw_all();
173                }
174                // Windows thread messages are posted
175                WAIT_EVENT(1) => {
176                    let mut msg = MSG::default();
177                    unsafe {
178                        while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
179                            match msg.message {
180                                WM_QUIT => break 'a,
181                                CLOSE_ONE_WINDOW => {
182                                    if self.close_one_window(HWND(msg.lParam.0)) {
183                                        break 'a;
184                                    }
185                                }
186                                _ => {
187                                    // todo(windows)
188                                    // crate `windows 0.56` reports true as Err
189                                    TranslateMessage(&msg).as_bool();
190                                    DispatchMessageW(&msg);
191                                }
192                            }
193                        }
194                    }
195                }
196                _ => {
197                    log::error!("Something went wrong while waiting {:?}", wait_result);
198                    break;
199                }
200            }
201        }
202
203        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
204            callback();
205        }
206    }
207
208    fn quit(&self) {
209        self.foreground_executor()
210            .spawn(async { unsafe { PostQuitMessage(0) } })
211            .detach();
212    }
213
214    fn restart(&self, _: Option<PathBuf>) {
215        let pid = std::process::id();
216        let Some(app_path) = self.app_path().log_err() else {
217            return;
218        };
219        let script = format!(
220            r#"
221            $pidToWaitFor = {}
222            $exePath = "{}"
223
224            while ($true) {{
225                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
226                if (-not $process) {{
227                    Start-Process -FilePath $exePath
228                    break
229                }}
230                Start-Sleep -Seconds 0.1
231            }}
232            "#,
233            pid,
234            app_path.display(),
235        );
236        let restart_process = std::process::Command::new("powershell.exe")
237            .arg("-command")
238            .arg(script)
239            .spawn();
240
241        match restart_process {
242            Ok(_) => self.quit(),
243            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
244        }
245    }
246
247    // todo(windows)
248    fn activate(&self, ignoring_other_apps: bool) {}
249
250    // todo(windows)
251    fn hide(&self) {
252        unimplemented!()
253    }
254
255    // todo(windows)
256    fn hide_other_apps(&self) {
257        unimplemented!()
258    }
259
260    // todo(windows)
261    fn unhide_other_apps(&self) {
262        unimplemented!()
263    }
264
265    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
266        WindowsDisplay::displays()
267    }
268
269    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
270        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
271    }
272
273    fn active_window(&self) -> Option<AnyWindowHandle> {
274        let active_window_hwnd = unsafe { GetActiveWindow() };
275        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
276            .map(|inner| inner.handle)
277    }
278
279    fn open_window(
280        &self,
281        handle: AnyWindowHandle,
282        options: WindowParams,
283    ) -> Result<Box<dyn PlatformWindow>> {
284        let lock = self.state.borrow();
285        let window = WindowsWindow::new(
286            handle,
287            options,
288            self.icon,
289            self.foreground_executor.clone(),
290            lock.current_cursor,
291        );
292        drop(lock);
293        let handle = window.get_raw_handle();
294        self.raw_window_handles.write().push(handle);
295
296        Ok(Box::new(window))
297    }
298
299    fn window_appearance(&self) -> WindowAppearance {
300        system_appearance().log_err().unwrap_or_default()
301    }
302
303    fn open_url(&self, url: &str) {
304        let url_string = url.to_string();
305        self.background_executor()
306            .spawn(async move {
307                if url_string.is_empty() {
308                    return;
309                }
310                open_target(url_string.as_str());
311            })
312            .detach();
313    }
314
315    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
316        self.state.borrow_mut().callbacks.open_urls = Some(callback);
317    }
318
319    fn prompt_for_paths(
320        &self,
321        options: PathPromptOptions,
322    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
323        let (tx, rx) = oneshot::channel();
324
325        self.foreground_executor()
326            .spawn(async move {
327                let tx = Cell::new(Some(tx));
328
329                // create file open dialog
330                let folder_dialog: IFileOpenDialog = unsafe {
331                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
332                        &FileOpenDialog,
333                        None,
334                        CLSCTX_ALL,
335                    )
336                    .unwrap()
337                };
338
339                // dialog options
340                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
341                if options.multiple {
342                    dialog_options |= FOS_ALLOWMULTISELECT;
343                }
344                if options.directories {
345                    dialog_options |= FOS_PICKFOLDERS;
346                }
347
348                unsafe {
349                    folder_dialog.SetOptions(dialog_options).unwrap();
350                    folder_dialog
351                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
352                        .unwrap();
353                }
354
355                let hr = unsafe { folder_dialog.Show(None) };
356
357                if hr.is_err() {
358                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
359                        // user canceled error
360                        if let Some(tx) = tx.take() {
361                            tx.send(Ok(None)).unwrap();
362                        }
363                        return;
364                    }
365                }
366
367                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
368
369                let mut paths: Vec<PathBuf> = Vec::new();
370                for i in 0..unsafe { results.GetCount().unwrap() } {
371                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
372                    let mut path: PWSTR =
373                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
374                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
375
376                    paths.push(PathBuf::from(path_os_string));
377                }
378
379                if let Some(tx) = tx.take() {
380                    if paths.is_empty() {
381                        tx.send(Ok(None)).unwrap();
382                    } else {
383                        tx.send(Ok(Some(paths))).unwrap();
384                    }
385                }
386            })
387            .detach();
388
389        rx
390    }
391
392    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
393        let directory = directory.to_owned();
394        let (tx, rx) = oneshot::channel();
395        self.foreground_executor()
396            .spawn(async move {
397                unsafe {
398                    let Ok(dialog) = show_savefile_dialog(directory) else {
399                        let _ = tx.send(Ok(None));
400                        return;
401                    };
402                    let Ok(_) = dialog.Show(None) else {
403                        let _ = tx.send(Ok(None)); // user cancel
404                        return;
405                    };
406                    if let Ok(shell_item) = dialog.GetResult() {
407                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
408                            let _ = tx.send(Ok(Some(PathBuf::from(file.to_string().unwrap()))));
409                            return;
410                        }
411                    }
412                    let _ = tx.send(Ok(None));
413                }
414            })
415            .detach();
416
417        rx
418    }
419
420    fn reveal_path(&self, path: &Path) {
421        let Ok(file_full_path) = path.canonicalize() else {
422            log::error!("unable to parse file path");
423            return;
424        };
425        self.background_executor()
426            .spawn(async move {
427                let Some(path) = file_full_path.to_str() else {
428                    return;
429                };
430                if path.is_empty() {
431                    return;
432                }
433                open_target_in_explorer(path);
434            })
435            .detach();
436    }
437
438    fn on_quit(&self, callback: Box<dyn FnMut()>) {
439        self.state.borrow_mut().callbacks.quit = Some(callback);
440    }
441
442    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
443        self.state.borrow_mut().callbacks.reopen = Some(callback);
444    }
445
446    // todo(windows)
447    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
448    fn set_dock_menu(&self, menus: Vec<MenuItem>, keymap: &Keymap) {}
449
450    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
451        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
452    }
453
454    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
455        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
456    }
457
458    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
459        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
460    }
461
462    fn app_path(&self) -> Result<PathBuf> {
463        Ok(std::env::current_exe()?)
464    }
465
466    fn local_timezone(&self) -> UtcOffset {
467        let mut info = unsafe { std::mem::zeroed() };
468        let ret = unsafe { GetTimeZoneInformation(&mut info) };
469        if ret == TIME_ZONE_ID_INVALID {
470            log::error!(
471                "Unable to get local timezone: {}",
472                std::io::Error::last_os_error()
473            );
474            return UtcOffset::UTC;
475        }
476        // Windows treat offset as:
477        // UTC = localtime + offset
478        // so we add a minus here
479        let hours = -info.Bias / 60;
480        let minutes = -info.Bias % 60;
481
482        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
483    }
484
485    // todo(windows)
486    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
487        Err(anyhow!("not yet implemented"))
488    }
489
490    fn set_cursor_style(&self, style: CursorStyle) {
491        let hcursor = load_cursor(style);
492        let mut lock = self.state.borrow_mut();
493        if lock.current_cursor.0 != hcursor.0 {
494            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
495            lock.current_cursor = hcursor;
496        }
497    }
498
499    fn should_auto_hide_scrollbars(&self) -> bool {
500        should_auto_hide_scrollbars().log_err().unwrap_or(false)
501    }
502
503    fn write_to_clipboard(&self, item: ClipboardItem) {
504        if item.text.len() > 0 {
505            set_clipboard_string(item.text()).unwrap();
506        }
507    }
508
509    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
510        let text = get_clipboard_string().ok()?;
511        Some(ClipboardItem {
512            text,
513            metadata: None,
514        })
515    }
516
517    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
518        let mut password = password.to_vec();
519        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
520        let mut target_name = windows_credentials_target_name(url)
521            .encode_utf16()
522            .chain(Some(0))
523            .collect_vec();
524        self.foreground_executor().spawn(async move {
525            let credentials = CREDENTIALW {
526                LastWritten: unsafe { GetSystemTimeAsFileTime() },
527                Flags: CRED_FLAGS(0),
528                Type: CRED_TYPE_GENERIC,
529                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
530                CredentialBlobSize: password.len() as u32,
531                CredentialBlob: password.as_ptr() as *mut _,
532                Persist: CRED_PERSIST_LOCAL_MACHINE,
533                UserName: PWSTR::from_raw(username.as_mut_ptr()),
534                ..CREDENTIALW::default()
535            };
536            unsafe { CredWriteW(&credentials, 0) }?;
537            Ok(())
538        })
539    }
540
541    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
542        let mut target_name = windows_credentials_target_name(url)
543            .encode_utf16()
544            .chain(Some(0))
545            .collect_vec();
546        self.foreground_executor().spawn(async move {
547            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
548            unsafe {
549                CredReadW(
550                    PCWSTR::from_raw(target_name.as_ptr()),
551                    CRED_TYPE_GENERIC,
552                    0,
553                    &mut credentials,
554                )?
555            };
556
557            if credentials.is_null() {
558                Ok(None)
559            } else {
560                let username: String = unsafe { (*credentials).UserName.to_string()? };
561                let credential_blob = unsafe {
562                    std::slice::from_raw_parts(
563                        (*credentials).CredentialBlob,
564                        (*credentials).CredentialBlobSize as usize,
565                    )
566                };
567                let password = credential_blob.to_vec();
568                unsafe { CredFree(credentials as *const c_void) };
569                Ok(Some((username, password)))
570            }
571        })
572    }
573
574    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
575        let mut target_name = windows_credentials_target_name(url)
576            .encode_utf16()
577            .chain(Some(0))
578            .collect_vec();
579        self.foreground_executor().spawn(async move {
580            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
581            Ok(())
582        })
583    }
584
585    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
586        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
587    }
588}
589
590impl Drop for WindowsPlatform {
591    fn drop(&mut self) {
592        unsafe {
593            OleUninitialize();
594        }
595    }
596}
597
598fn open_target(target: &str) {
599    unsafe {
600        let ret = ShellExecuteW(
601            None,
602            windows::core::w!("open"),
603            &HSTRING::from(target),
604            None,
605            None,
606            SW_SHOWDEFAULT,
607        );
608        if ret.0 <= 32 {
609            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
610        }
611    }
612}
613
614fn open_target_in_explorer(target: &str) {
615    unsafe {
616        let ret = ShellExecuteW(
617            None,
618            windows::core::w!("open"),
619            windows::core::w!("explorer.exe"),
620            &HSTRING::from(format!("/select,{}", target).as_str()),
621            None,
622            SW_SHOWDEFAULT,
623        );
624        if ret.0 <= 32 {
625            log::error!(
626                "Unable to open target in explorer: {}",
627                std::io::Error::last_os_error()
628            );
629        }
630    }
631}
632
633unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
634    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
635    let bind_context = CreateBindCtx(0)?;
636    let Ok(full_path) = directory.canonicalize() else {
637        return Ok(dialog);
638    };
639    let dir_str = full_path.into_os_string();
640    if dir_str.is_empty() {
641        return Ok(dialog);
642    }
643    let dir_vec = dir_str.encode_wide().collect_vec();
644    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
645        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
646    if ret.is_ok() {
647        let dir_shell_item: IShellItem = ret.unwrap();
648        let _ = dialog
649            .SetFolder(&dir_shell_item)
650            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
651    }
652
653    Ok(dialog)
654}
655
656fn begin_vsync(vsync_evnet: HANDLE) {
657    std::thread::spawn(move || unsafe {
658        loop {
659            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
660            SetEvent(vsync_evnet).log_err();
661        }
662    });
663}
664
665fn load_icon() -> Result<HICON> {
666    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
667    let handle = unsafe {
668        LoadImageW(
669            module,
670            IDI_APPLICATION,
671            IMAGE_ICON,
672            0,
673            0,
674            LR_DEFAULTSIZE | LR_SHARED,
675        )
676        .context("unable to load icon file")?
677    };
678    Ok(HICON(handle.0))
679}
680
681#[inline]
682fn should_auto_hide_scrollbars() -> Result<bool> {
683    let ui_settings = UISettings::new()?;
684    Ok(ui_settings.AutoHideScrollBars()?)
685}