platform.rs

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