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(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
320        let (tx, rx) = oneshot::channel();
321
322        self.foreground_executor()
323            .spawn(async move {
324                let tx = Cell::new(Some(tx));
325
326                // create file open dialog
327                let folder_dialog: IFileOpenDialog = unsafe {
328                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
329                        &FileOpenDialog,
330                        None,
331                        CLSCTX_ALL,
332                    )
333                    .unwrap()
334                };
335
336                // dialog options
337                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
338                if options.multiple {
339                    dialog_options |= FOS_ALLOWMULTISELECT;
340                }
341                if options.directories {
342                    dialog_options |= FOS_PICKFOLDERS;
343                }
344
345                unsafe {
346                    folder_dialog.SetOptions(dialog_options).unwrap();
347                    folder_dialog
348                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
349                        .unwrap();
350                }
351
352                let hr = unsafe { folder_dialog.Show(None) };
353
354                if hr.is_err() {
355                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
356                        // user canceled error
357                        if let Some(tx) = tx.take() {
358                            tx.send(None).unwrap();
359                        }
360                        return;
361                    }
362                }
363
364                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
365
366                let mut paths: Vec<PathBuf> = Vec::new();
367                for i in 0..unsafe { results.GetCount().unwrap() } {
368                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
369                    let mut path: PWSTR =
370                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
371                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
372
373                    paths.push(PathBuf::from(path_os_string));
374                }
375
376                if let Some(tx) = tx.take() {
377                    if paths.len() == 0 {
378                        tx.send(None).unwrap();
379                    } else {
380                        tx.send(Some(paths)).unwrap();
381                    }
382                }
383            })
384            .detach();
385
386        rx
387    }
388
389    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
390        let directory = directory.to_owned();
391        let (tx, rx) = oneshot::channel();
392        self.foreground_executor()
393            .spawn(async move {
394                unsafe {
395                    let Ok(dialog) = show_savefile_dialog(directory) else {
396                        let _ = tx.send(None);
397                        return;
398                    };
399                    let Ok(_) = dialog.Show(None) else {
400                        let _ = tx.send(None); // user cancel
401                        return;
402                    };
403                    if let Ok(shell_item) = dialog.GetResult() {
404                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
405                            let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
406                            return;
407                        }
408                    }
409                    let _ = tx.send(None);
410                }
411            })
412            .detach();
413
414        rx
415    }
416
417    fn reveal_path(&self, path: &Path) {
418        let Ok(file_full_path) = path.canonicalize() else {
419            log::error!("unable to parse file path");
420            return;
421        };
422        self.background_executor()
423            .spawn(async move {
424                let Some(path) = file_full_path.to_str() else {
425                    return;
426                };
427                if path.is_empty() {
428                    return;
429                }
430                open_target_in_explorer(path);
431            })
432            .detach();
433    }
434
435    fn on_quit(&self, callback: Box<dyn FnMut()>) {
436        self.state.borrow_mut().callbacks.quit = Some(callback);
437    }
438
439    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
440        self.state.borrow_mut().callbacks.reopen = Some(callback);
441    }
442
443    // todo(windows)
444    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
445    fn set_dock_menu(&self, menus: Vec<MenuItem>, keymap: &Keymap) {}
446
447    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
448        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
449    }
450
451    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
452        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
453    }
454
455    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
456        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
457    }
458
459    fn app_path(&self) -> Result<PathBuf> {
460        Ok(std::env::current_exe()?)
461    }
462
463    fn local_timezone(&self) -> UtcOffset {
464        let mut info = unsafe { std::mem::zeroed() };
465        let ret = unsafe { GetTimeZoneInformation(&mut info) };
466        if ret == TIME_ZONE_ID_INVALID {
467            log::error!(
468                "Unable to get local timezone: {}",
469                std::io::Error::last_os_error()
470            );
471            return UtcOffset::UTC;
472        }
473        // Windows treat offset as:
474        // UTC = localtime + offset
475        // so we add a minus here
476        let hours = -info.Bias / 60;
477        let minutes = -info.Bias % 60;
478
479        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
480    }
481
482    // todo(windows)
483    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
484        Err(anyhow!("not yet implemented"))
485    }
486
487    fn set_cursor_style(&self, style: CursorStyle) {
488        let hcursor = load_cursor(style);
489        let mut lock = self.state.borrow_mut();
490        if lock.current_cursor.0 != hcursor.0 {
491            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
492            lock.current_cursor = hcursor;
493        }
494    }
495
496    fn should_auto_hide_scrollbars(&self) -> bool {
497        should_auto_hide_scrollbars().log_err().unwrap_or(false)
498    }
499
500    fn write_to_clipboard(&self, item: ClipboardItem) {
501        if item.text.len() > 0 {
502            set_clipboard_string(item.text()).unwrap();
503        }
504    }
505
506    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
507        let text = get_clipboard_string().ok()?;
508        Some(ClipboardItem {
509            text,
510            metadata: None,
511        })
512    }
513
514    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
515        let mut password = password.to_vec();
516        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
517        let mut target_name = windows_credentials_target_name(url)
518            .encode_utf16()
519            .chain(Some(0))
520            .collect_vec();
521        self.foreground_executor().spawn(async move {
522            let credentials = CREDENTIALW {
523                LastWritten: unsafe { GetSystemTimeAsFileTime() },
524                Flags: CRED_FLAGS(0),
525                Type: CRED_TYPE_GENERIC,
526                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
527                CredentialBlobSize: password.len() as u32,
528                CredentialBlob: password.as_ptr() as *mut _,
529                Persist: CRED_PERSIST_LOCAL_MACHINE,
530                UserName: PWSTR::from_raw(username.as_mut_ptr()),
531                ..CREDENTIALW::default()
532            };
533            unsafe { CredWriteW(&credentials, 0) }?;
534            Ok(())
535        })
536    }
537
538    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
539        let mut target_name = windows_credentials_target_name(url)
540            .encode_utf16()
541            .chain(Some(0))
542            .collect_vec();
543        self.foreground_executor().spawn(async move {
544            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
545            unsafe {
546                CredReadW(
547                    PCWSTR::from_raw(target_name.as_ptr()),
548                    CRED_TYPE_GENERIC,
549                    0,
550                    &mut credentials,
551                )?
552            };
553
554            if credentials.is_null() {
555                Ok(None)
556            } else {
557                let username: String = unsafe { (*credentials).UserName.to_string()? };
558                let credential_blob = unsafe {
559                    std::slice::from_raw_parts(
560                        (*credentials).CredentialBlob,
561                        (*credentials).CredentialBlobSize as usize,
562                    )
563                };
564                let password = credential_blob.to_vec();
565                unsafe { CredFree(credentials as *const c_void) };
566                Ok(Some((username, password)))
567            }
568        })
569    }
570
571    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
572        let mut target_name = windows_credentials_target_name(url)
573            .encode_utf16()
574            .chain(Some(0))
575            .collect_vec();
576        self.foreground_executor().spawn(async move {
577            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
578            Ok(())
579        })
580    }
581
582    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
583        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
584    }
585}
586
587impl Drop for WindowsPlatform {
588    fn drop(&mut self) {
589        unsafe {
590            OleUninitialize();
591        }
592    }
593}
594
595fn open_target(target: &str) {
596    unsafe {
597        let ret = ShellExecuteW(
598            None,
599            windows::core::w!("open"),
600            &HSTRING::from(target),
601            None,
602            None,
603            SW_SHOWDEFAULT,
604        );
605        if ret.0 <= 32 {
606            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
607        }
608    }
609}
610
611fn open_target_in_explorer(target: &str) {
612    unsafe {
613        let ret = ShellExecuteW(
614            None,
615            windows::core::w!("open"),
616            windows::core::w!("explorer.exe"),
617            &HSTRING::from(format!("/select,{}", target).as_str()),
618            None,
619            SW_SHOWDEFAULT,
620        );
621        if ret.0 <= 32 {
622            log::error!(
623                "Unable to open target in explorer: {}",
624                std::io::Error::last_os_error()
625            );
626        }
627    }
628}
629
630unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
631    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
632    let bind_context = CreateBindCtx(0)?;
633    let Ok(full_path) = directory.canonicalize() else {
634        return Ok(dialog);
635    };
636    let dir_str = full_path.into_os_string();
637    if dir_str.is_empty() {
638        return Ok(dialog);
639    }
640    let dir_vec = dir_str.encode_wide().collect_vec();
641    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
642        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
643    if ret.is_ok() {
644        let dir_shell_item: IShellItem = ret.unwrap();
645        let _ = dialog
646            .SetFolder(&dir_shell_item)
647            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
648    }
649
650    Ok(dialog)
651}
652
653fn begin_vsync(vsync_evnet: HANDLE) {
654    std::thread::spawn(move || unsafe {
655        loop {
656            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
657            SetEvent(vsync_evnet).log_err();
658        }
659    });
660}
661
662fn load_icon() -> Result<HICON> {
663    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
664    let handle = unsafe {
665        LoadImageW(
666            module,
667            IDI_APPLICATION,
668            IMAGE_ICON,
669            0,
670            0,
671            LR_DEFAULTSIZE | LR_SHARED,
672        )
673        .context("unable to load icon file")?
674    };
675    Ok(HICON(handle.0))
676}
677
678#[inline]
679fn should_auto_hide_scrollbars() -> Result<bool> {
680    let ui_settings = UISettings::new()?;
681    Ok(ui_settings.AutoHideScrollBars()?)
682}