platform.rs

  1use std::{
  2    cell::RefCell,
  3    mem::ManuallyDrop,
  4    path::{Path, PathBuf},
  5    rc::Rc,
  6    sync::Arc,
  7};
  8
  9use ::util::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 run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
201        on_finish_launching();
202        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
203        begin_vsync(*vsync_event);
204        'a: loop {
205            let wait_result = unsafe {
206                MsgWaitForMultipleObjects(
207                    Some(&[*vsync_event, self.dispatch_event]),
208                    false,
209                    INFINITE,
210                    QS_ALLINPUT,
211                )
212            };
213
214            match wait_result {
215                // compositor clock ticked so we should draw a frame
216                WAIT_EVENT(0) => self.redraw_all(),
217                // foreground tasks are dispatched
218                WAIT_EVENT(1) => self.run_foreground_tasks(),
219                // Windows thread messages are posted
220                WAIT_EVENT(2) => {
221                    let mut msg = MSG::default();
222                    unsafe {
223                        while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
224                            match msg.message {
225                                WM_QUIT => break 'a,
226                                CLOSE_ONE_WINDOW => {
227                                    if self.close_one_window(
228                                        HWND(msg.lParam.0 as _),
229                                        msg.wParam.0,
230                                        &msg,
231                                    ) {
232                                        break 'a;
233                                    }
234                                }
235                                _ => {
236                                    // todo(windows)
237                                    // crate `windows 0.56` reports true as Err
238                                    TranslateMessage(&msg).as_bool();
239                                    DispatchMessageW(&msg);
240                                }
241                            }
242                        }
243                    }
244                    // foreground tasks may have been queued in the message handlers
245                    self.run_foreground_tasks();
246                }
247                _ => {
248                    log::error!("Something went wrong while waiting {:?}", wait_result);
249                    break;
250                }
251            }
252        }
253
254        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
255            callback();
256        }
257    }
258
259    fn quit(&self) {
260        self.foreground_executor()
261            .spawn(async { unsafe { PostQuitMessage(0) } })
262            .detach();
263    }
264
265    fn restart(&self, _: Option<PathBuf>) {
266        let pid = std::process::id();
267        let Some(app_path) = self.app_path().log_err() else {
268            return;
269        };
270        let script = format!(
271            r#"
272            $pidToWaitFor = {}
273            $exePath = "{}"
274
275            while ($true) {{
276                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
277                if (-not $process) {{
278                    Start-Process -FilePath $exePath
279                    break
280                }}
281                Start-Sleep -Seconds 0.1
282            }}
283            "#,
284            pid,
285            app_path.display(),
286        );
287        let restart_process = std::process::Command::new("powershell.exe")
288            .arg("-command")
289            .arg(script)
290            .spawn();
291
292        match restart_process {
293            Ok(_) => self.quit(),
294            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
295        }
296    }
297
298    fn activate(&self, _ignoring_other_apps: bool) {}
299
300    fn hide(&self) {}
301
302    // todo(windows)
303    fn hide_other_apps(&self) {
304        unimplemented!()
305    }
306
307    // todo(windows)
308    fn unhide_other_apps(&self) {
309        unimplemented!()
310    }
311
312    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
313        WindowsDisplay::displays()
314    }
315
316    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
317        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
318    }
319
320    fn active_window(&self) -> Option<AnyWindowHandle> {
321        let active_window_hwnd = unsafe { GetActiveWindow() };
322        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
323            .map(|inner| inner.handle)
324    }
325
326    fn open_window(
327        &self,
328        handle: AnyWindowHandle,
329        options: WindowParams,
330    ) -> Result<Box<dyn PlatformWindow>> {
331        let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
332        let handle = window.get_raw_handle();
333        self.raw_window_handles.write().push(handle);
334
335        Ok(Box::new(window))
336    }
337
338    fn window_appearance(&self) -> WindowAppearance {
339        system_appearance().log_err().unwrap_or_default()
340    }
341
342    fn open_url(&self, url: &str) {
343        let url_string = url.to_string();
344        self.background_executor()
345            .spawn(async move {
346                if url_string.is_empty() {
347                    return;
348                }
349                open_target(url_string.as_str());
350            })
351            .detach();
352    }
353
354    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
355        self.state.borrow_mut().callbacks.open_urls = Some(callback);
356    }
357
358    fn prompt_for_paths(
359        &self,
360        options: PathPromptOptions,
361    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
362        let (tx, rx) = oneshot::channel();
363        self.foreground_executor()
364            .spawn(async move {
365                let _ = tx.send(file_open_dialog(options));
366            })
367            .detach();
368
369        rx
370    }
371
372    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
373        let directory = directory.to_owned();
374        let (tx, rx) = oneshot::channel();
375        self.foreground_executor()
376            .spawn(async move {
377                let _ = tx.send(file_save_dialog(directory));
378            })
379            .detach();
380
381        rx
382    }
383
384    fn reveal_path(&self, path: &Path) {
385        let Ok(file_full_path) = path.canonicalize() else {
386            log::error!("unable to parse file path");
387            return;
388        };
389        self.background_executor()
390            .spawn(async move {
391                let Some(path) = file_full_path.to_str() else {
392                    return;
393                };
394                if path.is_empty() {
395                    return;
396                }
397                open_target_in_explorer(path);
398            })
399            .detach();
400    }
401
402    fn open_with_system(&self, path: &Path) {
403        let Ok(full_path) = path.canonicalize() else {
404            log::error!("unable to parse file full path: {}", path.display());
405            return;
406        };
407        self.background_executor()
408            .spawn(async move {
409                let Some(full_path_str) = full_path.to_str() else {
410                    return;
411                };
412                if full_path_str.is_empty() {
413                    return;
414                };
415                open_target(full_path_str);
416            })
417            .detach();
418    }
419
420    fn on_quit(&self, callback: Box<dyn FnMut()>) {
421        self.state.borrow_mut().callbacks.quit = Some(callback);
422    }
423
424    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
425        self.state.borrow_mut().callbacks.reopen = Some(callback);
426    }
427
428    // todo(windows)
429    fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
430    fn set_dock_menu(&self, _menus: Vec<MenuItem>, _keymap: &Keymap) {}
431
432    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
433        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
434    }
435
436    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
437        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
438    }
439
440    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
441        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
442    }
443
444    fn app_path(&self) -> Result<PathBuf> {
445        Ok(std::env::current_exe()?)
446    }
447
448    // todo(windows)
449    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
450        Err(anyhow!("not yet implemented"))
451    }
452
453    fn set_cursor_style(&self, style: CursorStyle) {
454        let hcursor = load_cursor(style);
455        let mut lock = self.state.borrow_mut();
456        if lock.current_cursor.0 != hcursor.0 {
457            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0 as isize));
458            lock.current_cursor = hcursor;
459        }
460    }
461
462    fn should_auto_hide_scrollbars(&self) -> bool {
463        should_auto_hide_scrollbars().log_err().unwrap_or(false)
464    }
465
466    fn write_to_clipboard(&self, item: ClipboardItem) {
467        write_to_clipboard(item);
468    }
469
470    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
471        read_from_clipboard()
472    }
473
474    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
475        let mut password = password.to_vec();
476        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
477        let mut target_name = windows_credentials_target_name(url)
478            .encode_utf16()
479            .chain(Some(0))
480            .collect_vec();
481        self.foreground_executor().spawn(async move {
482            let credentials = CREDENTIALW {
483                LastWritten: unsafe { GetSystemTimeAsFileTime() },
484                Flags: CRED_FLAGS(0),
485                Type: CRED_TYPE_GENERIC,
486                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
487                CredentialBlobSize: password.len() as u32,
488                CredentialBlob: password.as_ptr() as *mut _,
489                Persist: CRED_PERSIST_LOCAL_MACHINE,
490                UserName: PWSTR::from_raw(username.as_mut_ptr()),
491                ..CREDENTIALW::default()
492            };
493            unsafe { CredWriteW(&credentials, 0) }?;
494            Ok(())
495        })
496    }
497
498    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
499        let mut target_name = windows_credentials_target_name(url)
500            .encode_utf16()
501            .chain(Some(0))
502            .collect_vec();
503        self.foreground_executor().spawn(async move {
504            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
505            unsafe {
506                CredReadW(
507                    PCWSTR::from_raw(target_name.as_ptr()),
508                    CRED_TYPE_GENERIC,
509                    0,
510                    &mut credentials,
511                )?
512            };
513
514            if credentials.is_null() {
515                Ok(None)
516            } else {
517                let username: String = unsafe { (*credentials).UserName.to_string()? };
518                let credential_blob = unsafe {
519                    std::slice::from_raw_parts(
520                        (*credentials).CredentialBlob,
521                        (*credentials).CredentialBlobSize as usize,
522                    )
523                };
524                let password = credential_blob.to_vec();
525                unsafe { CredFree(credentials as *const _ as _) };
526                Ok(Some((username, password)))
527            }
528        })
529    }
530
531    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
532        let mut target_name = windows_credentials_target_name(url)
533            .encode_utf16()
534            .chain(Some(0))
535            .collect_vec();
536        self.foreground_executor().spawn(async move {
537            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
538            Ok(())
539        })
540    }
541
542    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
543        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
544    }
545}
546
547impl Drop for WindowsPlatform {
548    fn drop(&mut self) {
549        unsafe {
550            ManuallyDrop::drop(&mut self.bitmap_factory);
551            OleUninitialize();
552        }
553    }
554}
555
556pub(crate) struct WindowCreationInfo {
557    pub(crate) icon: HICON,
558    pub(crate) executor: ForegroundExecutor,
559    pub(crate) current_cursor: HCURSOR,
560    pub(crate) windows_version: WindowsVersion,
561    pub(crate) validation_number: usize,
562    pub(crate) main_receiver: flume::Receiver<Runnable>,
563}
564
565fn open_target(target: &str) {
566    unsafe {
567        let ret = ShellExecuteW(
568            None,
569            windows::core::w!("open"),
570            &HSTRING::from(target),
571            None,
572            None,
573            SW_SHOWDEFAULT,
574        );
575        if ret.0 as isize <= 32 {
576            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
577        }
578    }
579}
580
581fn open_target_in_explorer(target: &str) {
582    unsafe {
583        let ret = ShellExecuteW(
584            None,
585            windows::core::w!("open"),
586            windows::core::w!("explorer.exe"),
587            &HSTRING::from(format!("/select,{}", target).as_str()),
588            None,
589            SW_SHOWDEFAULT,
590        );
591        if ret.0 as isize <= 32 {
592            log::error!(
593                "Unable to open target in explorer: {}",
594                std::io::Error::last_os_error()
595            );
596        }
597    }
598}
599
600fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
601    let folder_dialog: IFileOpenDialog =
602        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
603
604    let mut dialog_options = FOS_FILEMUSTEXIST;
605    if options.multiple {
606        dialog_options |= FOS_ALLOWMULTISELECT;
607    }
608    if options.directories {
609        dialog_options |= FOS_PICKFOLDERS;
610    }
611
612    unsafe {
613        folder_dialog.SetOptions(dialog_options)?;
614        if folder_dialog.Show(None).is_err() {
615            // User cancelled
616            return Ok(None);
617        }
618    }
619
620    let results = unsafe { folder_dialog.GetResults()? };
621    let file_count = unsafe { results.GetCount()? };
622    if file_count == 0 {
623        return Ok(None);
624    }
625
626    let mut paths = Vec::new();
627    for i in 0..file_count {
628        let item = unsafe { results.GetItemAt(i)? };
629        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
630        paths.push(PathBuf::from(path));
631    }
632
633    Ok(Some(paths))
634}
635
636fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
637    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
638    if !directory.to_string_lossy().is_empty() {
639        if let Some(full_path) = directory.canonicalize().log_err() {
640            let full_path = full_path.to_string_lossy();
641            let full_path_str = full_path.trim_start_matches("\\\\?\\");
642            if !full_path_str.is_empty() {
643                let path_item: IShellItem =
644                    unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_str), None)? };
645                unsafe { dialog.SetFolder(&path_item).log_err() };
646            }
647        }
648    }
649    unsafe {
650        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
651            pszName: windows::core::w!("All files"),
652            pszSpec: windows::core::w!("*.*"),
653        }])?;
654        if dialog.Show(None).is_err() {
655            // User cancelled
656            return Ok(None);
657        }
658    }
659    let shell_item = unsafe { dialog.GetResult()? };
660    let file_path_string = unsafe {
661        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
662        let string = pwstr.to_string()?;
663        CoTaskMemFree(Some(pwstr.0 as _));
664        string
665    };
666    Ok(Some(PathBuf::from(file_path_string)))
667}
668
669fn begin_vsync(vsync_event: HANDLE) {
670    let event: SafeHandle = vsync_event.into();
671    std::thread::spawn(move || unsafe {
672        loop {
673            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
674            SetEvent(*event).log_err();
675        }
676    });
677}
678
679fn load_icon() -> Result<HICON> {
680    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
681    let handle = unsafe {
682        LoadImageW(
683            module,
684            IDI_APPLICATION,
685            IMAGE_ICON,
686            0,
687            0,
688            LR_DEFAULTSIZE | LR_SHARED,
689        )
690        .context("unable to load icon file")?
691    };
692    Ok(HICON(handle.0))
693}
694
695#[inline]
696fn should_auto_hide_scrollbars() -> Result<bool> {
697    let ui_settings = UISettings::new()?;
698    Ok(ui_settings.AutoHideScrollBars()?)
699}
700
701#[cfg(test)]
702mod tests {
703    use crate::{ClipboardItem, Platform, WindowsPlatform};
704
705    #[test]
706    fn test_clipboard() {
707        let platform = WindowsPlatform::new();
708        let item = ClipboardItem::new_string("你好".to_string());
709        platform.write_to_clipboard(item.clone());
710        assert_eq!(platform.read_from_clipboard(), Some(item));
711
712        let item = ClipboardItem::new_string("12345".to_string());
713        platform.write_to_clipboard(item.clone());
714        assert_eq!(platform.read_from_clipboard(), Some(item));
715
716        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
717        platform.write_to_clipboard(item.clone());
718        assert_eq!(platform.read_from_clipboard(), Some(item));
719    }
720}