platform.rs

  1// todo(windows): remove
  2#![allow(unused_variables)]
  3
  4use std::{
  5    cell::{Cell, RefCell},
  6    ffi::{c_uint, c_void, OsString},
  7    iter::once,
  8    mem::transmute,
  9    os::windows::ffi::{OsStrExt, OsStringExt},
 10    path::{Path, PathBuf},
 11    rc::Rc,
 12    sync::{Arc, OnceLock},
 13};
 14
 15use ::util::ResultExt;
 16use anyhow::{anyhow, Context, Result};
 17use async_task::Runnable;
 18use copypasta::{ClipboardContext, ClipboardProvider};
 19use futures::channel::oneshot::{self, Receiver};
 20use itertools::Itertools;
 21use parking_lot::{Mutex, RwLock};
 22use semantic_version::SemanticVersion;
 23use smallvec::SmallVec;
 24use time::UtcOffset;
 25use windows::{
 26    core::*,
 27    Wdk::System::SystemServices::*,
 28    Win32::{
 29        Foundation::*,
 30        Graphics::Gdi::*,
 31        Media::*,
 32        Security::Credentials::*,
 33        Storage::FileSystem::*,
 34        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*, Time::*},
 35        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 36    },
 37};
 38
 39use crate::*;
 40
 41pub(crate) struct WindowsPlatform {
 42    inner: Rc<WindowsPlatformInner>,
 43}
 44
 45/// Windows settings pulled from SystemParametersInfo
 46/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
 47#[derive(Default, Debug)]
 48pub(crate) struct WindowsPlatformSystemSettings {
 49    /// SEE: SPI_GETWHEELSCROLLCHARS
 50    pub(crate) wheel_scroll_chars: u32,
 51
 52    /// SEE: SPI_GETWHEELSCROLLLINES
 53    pub(crate) wheel_scroll_lines: u32,
 54}
 55
 56pub(crate) struct WindowsPlatformInner {
 57    background_executor: BackgroundExecutor,
 58    pub(crate) foreground_executor: ForegroundExecutor,
 59    main_receiver: flume::Receiver<Runnable>,
 60    text_system: Arc<dyn PlatformTextSystem>,
 61    callbacks: Mutex<Callbacks>,
 62    pub raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 63    pub(crate) dispatch_event: OwnedHandle,
 64    pub(crate) settings: RefCell<WindowsPlatformSystemSettings>,
 65    pub icon: HICON,
 66    // NOTE: standard cursor handles don't need to close.
 67    pub(crate) current_cursor: Cell<HCURSOR>,
 68}
 69
 70impl WindowsPlatformInner {
 71    pub(crate) fn try_get_windows_inner_from_hwnd(
 72        &self,
 73        hwnd: HWND,
 74    ) -> Option<Rc<WindowsWindowInner>> {
 75        self.raw_window_handles
 76            .read()
 77            .iter()
 78            .find(|entry| *entry == &hwnd)
 79            .and_then(|hwnd| try_get_window_inner(*hwnd))
 80    }
 81
 82    #[inline]
 83    pub fn run_foreground_tasks(&self) {
 84        for runnable in self.main_receiver.drain() {
 85            runnable.run();
 86        }
 87    }
 88}
 89
 90#[derive(Default)]
 91struct Callbacks {
 92    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 93    quit: Option<Box<dyn FnMut()>>,
 94    reopen: Option<Box<dyn FnMut()>>,
 95    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 96    will_open_app_menu: Option<Box<dyn FnMut()>>,
 97    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 98}
 99
100enum WindowsMessageWaitResult {
101    ForegroundExecution,
102    WindowsMessage(MSG),
103    Error,
104}
105
106impl WindowsPlatformSystemSettings {
107    fn new() -> Self {
108        let mut settings = Self::default();
109        settings.update_all();
110        settings
111    }
112
113    pub(crate) fn update_all(&mut self) {
114        self.update_wheel_scroll_lines();
115        self.update_wheel_scroll_chars();
116    }
117
118    pub(crate) fn update_wheel_scroll_lines(&mut self) {
119        let mut value = c_uint::default();
120        let result = unsafe {
121            SystemParametersInfoW(
122                SPI_GETWHEELSCROLLLINES,
123                0,
124                Some((&mut value) as *mut c_uint as *mut c_void),
125                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
126            )
127        };
128
129        if result.log_err() != None {
130            self.wheel_scroll_lines = value;
131        }
132    }
133
134    pub(crate) fn update_wheel_scroll_chars(&mut self) {
135        let mut value = c_uint::default();
136        let result = unsafe {
137            SystemParametersInfoW(
138                SPI_GETWHEELSCROLLCHARS,
139                0,
140                Some((&mut value) as *mut c_uint as *mut c_void),
141                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
142            )
143        };
144
145        if result.log_err() != None {
146            self.wheel_scroll_chars = value;
147        }
148    }
149}
150
151impl WindowsPlatform {
152    pub(crate) fn new() -> Self {
153        unsafe {
154            OleInitialize(None).expect("unable to initialize Windows OLE");
155        }
156        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
157        let dispatch_event =
158            OwnedHandle::new(unsafe { CreateEventW(None, false, false, None) }.unwrap());
159        let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, dispatch_event.to_raw()));
160        let background_executor = BackgroundExecutor::new(dispatcher.clone());
161        let foreground_executor = ForegroundExecutor::new(dispatcher);
162        let text_system = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
163            log::info!("Using direct write text system.");
164            Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
165        } else {
166            log::info!("Using cosmic text system.");
167            Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
168        };
169        let callbacks = Mutex::new(Callbacks::default());
170        let raw_window_handles = RwLock::new(SmallVec::new());
171        let settings = RefCell::new(WindowsPlatformSystemSettings::new());
172        let icon = load_icon().unwrap_or_default();
173        let current_cursor = Cell::new(load_cursor(CursorStyle::Arrow));
174        let inner = Rc::new(WindowsPlatformInner {
175            background_executor,
176            foreground_executor,
177            main_receiver,
178            text_system,
179            callbacks,
180            raw_window_handles,
181            dispatch_event,
182            settings,
183            icon,
184            current_cursor,
185        });
186        Self { inner }
187    }
188
189    #[inline]
190    fn run_foreground_tasks(&self) {
191        self.inner.run_foreground_tasks();
192    }
193
194    fn redraw_all(&self) {
195        for handle in self.inner.raw_window_handles.read().iter() {
196            unsafe {
197                RedrawWindow(
198                    *handle,
199                    None,
200                    HRGN::default(),
201                    RDW_INVALIDATE | RDW_UPDATENOW,
202                );
203            }
204        }
205    }
206}
207
208impl Platform for WindowsPlatform {
209    fn background_executor(&self) -> BackgroundExecutor {
210        self.inner.background_executor.clone()
211    }
212
213    fn foreground_executor(&self) -> ForegroundExecutor {
214        self.inner.foreground_executor.clone()
215    }
216
217    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
218        self.inner.text_system.clone()
219    }
220
221    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
222        on_finish_launching();
223        let dispatch_event = self.inner.dispatch_event.to_raw();
224        let vsync_event = create_event().unwrap();
225        let timer_stop_event = create_event().unwrap();
226        let raw_timer_stop_event = timer_stop_event.to_raw();
227        begin_vsync_timer(vsync_event.to_raw(), timer_stop_event);
228        'a: loop {
229            let wait_result = unsafe {
230                MsgWaitForMultipleObjects(
231                    Some(&[vsync_event.to_raw(), dispatch_event]),
232                    false,
233                    INFINITE,
234                    QS_ALLINPUT,
235                )
236            };
237
238            match wait_result {
239                // compositor clock ticked so we should draw a frame
240                WAIT_EVENT(0) => {
241                    self.redraw_all();
242                }
243                // foreground tasks are dispatched
244                WAIT_EVENT(1) => {
245                    self.run_foreground_tasks();
246                }
247                // Windows thread messages are posted
248                WAIT_EVENT(2) => {
249                    let mut msg = MSG::default();
250                    unsafe {
251                        while PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE).as_bool() {
252                            if msg.message == WM_QUIT {
253                                break 'a;
254                            }
255                            if msg.message == WM_SETTINGCHANGE {
256                                self.inner.settings.borrow_mut().update_all();
257                                continue;
258                            }
259                            TranslateMessage(&msg);
260                            DispatchMessageW(&msg);
261                        }
262                    }
263
264                    // foreground tasks may have been queued in the message handlers
265                    self.run_foreground_tasks();
266                }
267                _ => {
268                    log::error!("Something went wrong while waiting {:?}", wait_result);
269                    break;
270                }
271            }
272        }
273        end_vsync_timer(raw_timer_stop_event);
274
275        let mut callbacks = self.inner.callbacks.lock();
276        if let Some(callback) = callbacks.quit.as_mut() {
277            callback()
278        }
279    }
280
281    fn quit(&self) {
282        self.foreground_executor()
283            .spawn(async { unsafe { PostQuitMessage(0) } })
284            .detach();
285    }
286
287    fn restart(&self) {
288        let pid = std::process::id();
289        let Some(app_path) = self.app_path().log_err() else {
290            return;
291        };
292        let script = format!(
293            r#"
294            $pidToWaitFor = {}
295            $exePath = "{}"
296
297            while ($true) {{
298                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
299                if (-not $process) {{
300                    Start-Process -FilePath $exePath
301                    break
302                }}
303                Start-Sleep -Seconds 0.1
304            }}
305            "#,
306            pid,
307            app_path.display(),
308        );
309        let restart_process = std::process::Command::new("powershell.exe")
310            .arg("-command")
311            .arg(script)
312            .spawn();
313
314        match restart_process {
315            Ok(_) => self.quit(),
316            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
317        }
318    }
319
320    // todo(windows)
321    fn activate(&self, ignoring_other_apps: bool) {}
322
323    // todo(windows)
324    fn hide(&self) {
325        unimplemented!()
326    }
327
328    // todo(windows)
329    fn hide_other_apps(&self) {
330        unimplemented!()
331    }
332
333    // todo(windows)
334    fn unhide_other_apps(&self) {
335        unimplemented!()
336    }
337
338    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
339        WindowsDisplay::displays()
340    }
341
342    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
343        if let Some(display) = WindowsDisplay::primary_monitor() {
344            Some(Rc::new(display) as Rc<dyn PlatformDisplay>)
345        } else {
346            None
347        }
348    }
349
350    fn active_window(&self) -> Option<AnyWindowHandle> {
351        let active_window_hwnd = unsafe { GetActiveWindow() };
352        self.inner
353            .try_get_windows_inner_from_hwnd(active_window_hwnd)
354            .map(|inner| inner.handle)
355    }
356
357    fn open_window(
358        &self,
359        handle: AnyWindowHandle,
360        options: WindowParams,
361    ) -> Box<dyn PlatformWindow> {
362        Box::new(WindowsWindow::new(self.inner.clone(), handle, options))
363    }
364
365    // todo(windows)
366    fn window_appearance(&self) -> WindowAppearance {
367        WindowAppearance::Dark
368    }
369
370    fn open_url(&self, url: &str) {
371        let url_string = url.to_string();
372        self.background_executor()
373            .spawn(async move {
374                if url_string.is_empty() {
375                    return;
376                }
377                open_target(url_string.as_str());
378            })
379            .detach();
380    }
381
382    // todo(windows)
383    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
384        self.inner.callbacks.lock().open_urls = Some(callback);
385    }
386
387    fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
388        let (tx, rx) = oneshot::channel();
389
390        self.foreground_executor()
391            .spawn(async move {
392                let tx = Cell::new(Some(tx));
393
394                // create file open dialog
395                let folder_dialog: IFileOpenDialog = unsafe {
396                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
397                        &FileOpenDialog,
398                        None,
399                        CLSCTX_ALL,
400                    )
401                    .unwrap()
402                };
403
404                // dialog options
405                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
406                if options.multiple {
407                    dialog_options |= FOS_ALLOWMULTISELECT;
408                }
409                if options.directories {
410                    dialog_options |= FOS_PICKFOLDERS;
411                }
412
413                unsafe {
414                    folder_dialog.SetOptions(dialog_options).unwrap();
415                    folder_dialog
416                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
417                        .unwrap();
418                }
419
420                let hr = unsafe { folder_dialog.Show(None) };
421
422                if hr.is_err() {
423                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
424                        // user canceled error
425                        if let Some(tx) = tx.take() {
426                            tx.send(None).unwrap();
427                        }
428                        return;
429                    }
430                }
431
432                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
433
434                let mut paths: Vec<PathBuf> = Vec::new();
435                for i in 0..unsafe { results.GetCount().unwrap() } {
436                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
437                    let mut path: PWSTR =
438                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
439                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
440
441                    paths.push(PathBuf::from(path_os_string));
442                }
443
444                if let Some(tx) = tx.take() {
445                    if paths.len() == 0 {
446                        tx.send(None).unwrap();
447                    } else {
448                        tx.send(Some(paths)).unwrap();
449                    }
450                }
451            })
452            .detach();
453
454        rx
455    }
456
457    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
458        let directory = directory.to_owned();
459        let (tx, rx) = oneshot::channel();
460        self.foreground_executor()
461            .spawn(async move {
462                unsafe {
463                    let Ok(dialog) = show_savefile_dialog(directory) else {
464                        let _ = tx.send(None);
465                        return;
466                    };
467                    let Ok(_) = dialog.Show(None) else {
468                        let _ = tx.send(None); // user cancel
469                        return;
470                    };
471                    if let Ok(shell_item) = dialog.GetResult() {
472                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
473                            let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
474                            return;
475                        }
476                    }
477                    let _ = tx.send(None);
478                }
479            })
480            .detach();
481
482        rx
483    }
484
485    fn reveal_path(&self, path: &Path) {
486        let Ok(file_full_path) = path.canonicalize() else {
487            log::error!("unable to parse file path");
488            return;
489        };
490        self.background_executor()
491            .spawn(async move {
492                let Some(path) = file_full_path.to_str() else {
493                    return;
494                };
495                if path.is_empty() {
496                    return;
497                }
498                open_target(path);
499            })
500            .detach();
501    }
502
503    fn on_quit(&self, callback: Box<dyn FnMut()>) {
504        self.inner.callbacks.lock().quit = Some(callback);
505    }
506
507    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
508        self.inner.callbacks.lock().reopen = Some(callback);
509    }
510
511    // todo(windows)
512    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
513
514    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
515        self.inner.callbacks.lock().app_menu_action = Some(callback);
516    }
517
518    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
519        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
520    }
521
522    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
523        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
524    }
525
526    fn os_name(&self) -> &'static str {
527        "Windows"
528    }
529
530    fn os_version(&self) -> Result<SemanticVersion> {
531        let mut info = unsafe { std::mem::zeroed() };
532        let status = unsafe { RtlGetVersion(&mut info) };
533        if status.is_ok() {
534            Ok(SemanticVersion::new(
535                info.dwMajorVersion as _,
536                info.dwMinorVersion as _,
537                info.dwBuildNumber as _,
538            ))
539        } else {
540            Err(anyhow::anyhow!(
541                "unable to get Windows version: {}",
542                std::io::Error::last_os_error()
543            ))
544        }
545    }
546
547    fn app_version(&self) -> Result<SemanticVersion> {
548        let mut file_name_buffer = vec![0u16; MAX_PATH as usize];
549        let file_name = {
550            let mut file_name_buffer_capacity = MAX_PATH as usize;
551            let mut file_name_length;
552            loop {
553                file_name_length =
554                    unsafe { GetModuleFileNameW(None, &mut file_name_buffer) } as usize;
555                if file_name_length < file_name_buffer_capacity {
556                    break;
557                }
558                // buffer too small
559                file_name_buffer_capacity *= 2;
560                file_name_buffer = vec![0u16; file_name_buffer_capacity];
561            }
562            PCWSTR::from_raw(file_name_buffer[0..(file_name_length + 1)].as_ptr())
563        };
564
565        let version_info_block = {
566            let mut version_handle = 0;
567            let version_info_size =
568                unsafe { GetFileVersionInfoSizeW(file_name, Some(&mut version_handle)) } as usize;
569            if version_info_size == 0 {
570                log::error!(
571                    "unable to get version info size: {}",
572                    std::io::Error::last_os_error()
573                );
574                return Err(anyhow!("unable to get version info size"));
575            }
576            let mut version_data = vec![0u8; version_info_size + 2];
577            unsafe {
578                GetFileVersionInfoW(
579                    file_name,
580                    version_handle,
581                    version_info_size as u32,
582                    version_data.as_mut_ptr() as _,
583                )
584            }
585            .inspect_err(|_| {
586                log::error!(
587                    "unable to retrieve version info: {}",
588                    std::io::Error::last_os_error()
589                )
590            })?;
591            version_data
592        };
593
594        let version_info_raw = {
595            let mut buffer = unsafe { std::mem::zeroed() };
596            let mut size = 0;
597            let entry = "\\".encode_utf16().chain(Some(0)).collect_vec();
598            if !unsafe {
599                VerQueryValueW(
600                    version_info_block.as_ptr() as _,
601                    PCWSTR::from_raw(entry.as_ptr()),
602                    &mut buffer,
603                    &mut size,
604                )
605            }
606            .as_bool()
607            {
608                log::error!(
609                    "unable to query version info data: {}",
610                    std::io::Error::last_os_error()
611                );
612                return Err(anyhow!("the specified resource is not valid"));
613            }
614            if size == 0 {
615                log::error!(
616                    "unable to query version info data: {}",
617                    std::io::Error::last_os_error()
618                );
619                return Err(anyhow!("no value is available for the specified name"));
620            }
621            buffer
622        };
623
624        let version_info = unsafe { &*(version_info_raw as *mut VS_FIXEDFILEINFO) };
625        // https://learn.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo
626        if version_info.dwSignature == 0xFEEF04BD {
627            return Ok(SemanticVersion::new(
628                ((version_info.dwProductVersionMS >> 16) & 0xFFFF) as usize,
629                (version_info.dwProductVersionMS & 0xFFFF) as usize,
630                ((version_info.dwProductVersionLS >> 16) & 0xFFFF) as usize,
631            ));
632        } else {
633            log::error!(
634                "no version info present: {}",
635                std::io::Error::last_os_error()
636            );
637            return Err(anyhow!("no version info present"));
638        }
639    }
640
641    fn app_path(&self) -> Result<PathBuf> {
642        Ok(std::env::current_exe()?)
643    }
644
645    fn local_timezone(&self) -> UtcOffset {
646        let mut info = unsafe { std::mem::zeroed() };
647        let ret = unsafe { GetTimeZoneInformation(&mut info) };
648        if ret == TIME_ZONE_ID_INVALID {
649            log::error!(
650                "Unable to get local timezone: {}",
651                std::io::Error::last_os_error()
652            );
653            return UtcOffset::UTC;
654        }
655        // Windows treat offset as:
656        // UTC = localtime + offset
657        // so we add a minus here
658        let hours = -info.Bias / 60;
659        let minutes = -info.Bias % 60;
660
661        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
662    }
663
664    // todo(windows)
665    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
666        Err(anyhow!("not yet implemented"))
667    }
668
669    fn set_cursor_style(&self, style: CursorStyle) {
670        self.inner.current_cursor.set(load_cursor(style));
671    }
672
673    // todo(windows)
674    fn should_auto_hide_scrollbars(&self) -> bool {
675        false
676    }
677
678    fn write_to_primary(&self, _item: ClipboardItem) {}
679
680    fn write_to_clipboard(&self, item: ClipboardItem) {
681        if item.text.len() > 0 {
682            let mut ctx = ClipboardContext::new().unwrap();
683            ctx.set_contents(item.text().to_owned()).unwrap();
684        }
685    }
686
687    fn read_from_primary(&self) -> Option<ClipboardItem> {
688        None
689    }
690
691    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
692        let mut ctx = ClipboardContext::new().unwrap();
693        let content = ctx.get_contents().unwrap();
694        Some(ClipboardItem {
695            text: content,
696            metadata: None,
697        })
698    }
699
700    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
701        let mut password = password.to_vec();
702        let mut username = username.encode_utf16().chain(once(0)).collect_vec();
703        let mut target_name = windows_credentials_target_name(url)
704            .encode_utf16()
705            .chain(once(0))
706            .collect_vec();
707        self.foreground_executor().spawn(async move {
708            let credentials = CREDENTIALW {
709                LastWritten: unsafe { GetSystemTimeAsFileTime() },
710                Flags: CRED_FLAGS(0),
711                Type: CRED_TYPE_GENERIC,
712                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
713                CredentialBlobSize: password.len() as u32,
714                CredentialBlob: password.as_ptr() as *mut _,
715                Persist: CRED_PERSIST_LOCAL_MACHINE,
716                UserName: PWSTR::from_raw(username.as_mut_ptr()),
717                ..CREDENTIALW::default()
718            };
719            unsafe { CredWriteW(&credentials, 0) }?;
720            Ok(())
721        })
722    }
723
724    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
725        let mut target_name = windows_credentials_target_name(url)
726            .encode_utf16()
727            .chain(once(0))
728            .collect_vec();
729        self.foreground_executor().spawn(async move {
730            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
731            unsafe {
732                CredReadW(
733                    PCWSTR::from_raw(target_name.as_ptr()),
734                    CRED_TYPE_GENERIC,
735                    0,
736                    &mut credentials,
737                )?
738            };
739
740            if credentials.is_null() {
741                Ok(None)
742            } else {
743                let username: String = unsafe { (*credentials).UserName.to_string()? };
744                let credential_blob = unsafe {
745                    std::slice::from_raw_parts(
746                        (*credentials).CredentialBlob,
747                        (*credentials).CredentialBlobSize as usize,
748                    )
749                };
750                let password = credential_blob.to_vec();
751                unsafe { CredFree(credentials as *const c_void) };
752                Ok(Some((username, password)))
753            }
754        })
755    }
756
757    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
758        let mut target_name = windows_credentials_target_name(url)
759            .encode_utf16()
760            .chain(once(0))
761            .collect_vec();
762        self.foreground_executor().spawn(async move {
763            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
764            Ok(())
765        })
766    }
767
768    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
769        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
770    }
771}
772
773impl Drop for WindowsPlatform {
774    fn drop(&mut self) {
775        unsafe {
776            OleUninitialize();
777        }
778    }
779}
780
781fn open_target(target: &str) {
782    unsafe {
783        let ret = ShellExecuteW(
784            None,
785            windows::core::w!("open"),
786            &HSTRING::from(target),
787            None,
788            None,
789            SW_SHOWDEFAULT,
790        );
791        if ret.0 <= 32 {
792            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
793        }
794    }
795}
796
797unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
798    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
799    let bind_context = CreateBindCtx(0)?;
800    let Ok(full_path) = directory.canonicalize() else {
801        return Ok(dialog);
802    };
803    let dir_str = full_path.into_os_string();
804    if dir_str.is_empty() {
805        return Ok(dialog);
806    }
807    let dir_vec = dir_str.encode_wide().collect_vec();
808    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
809        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
810    if ret.is_ok() {
811        let dir_shell_item: IShellItem = ret.unwrap();
812        let _ = dialog
813            .SetFolder(&dir_shell_item)
814            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
815    }
816
817    Ok(dialog)
818}
819
820fn begin_vsync_timer(vsync_event: HANDLE, timer_stop_event: OwnedHandle) {
821    let vsync_fn = select_vsync_fn();
822    std::thread::spawn(move || {
823        while vsync_fn(timer_stop_event.to_raw()) {
824            if unsafe { SetEvent(vsync_event) }.log_err().is_none() {
825                break;
826            }
827        }
828    });
829}
830
831fn end_vsync_timer(timer_stop_event: HANDLE) {
832    unsafe { SetEvent(timer_stop_event) }.log_err();
833}
834
835fn select_vsync_fn() -> Box<dyn Fn(HANDLE) -> bool + Send> {
836    if let Some(dcomp_fn) = load_dcomp_vsync_fn() {
837        log::info!("use DCompositionWaitForCompositorClock for vsync");
838        return Box::new(move |timer_stop_event| {
839            // will be 0 if woken up by timer_stop_event or 1 if the compositor clock ticked
840            // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
841            (unsafe { dcomp_fn(1, &timer_stop_event, INFINITE) }) == 1
842        });
843    }
844    log::info!("use fallback vsync function");
845    Box::new(fallback_vsync_fn())
846}
847
848fn load_dcomp_vsync_fn() -> Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32> {
849    static FN: OnceLock<Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32>> =
850        OnceLock::new();
851    *FN.get_or_init(|| {
852        let hmodule = unsafe { LoadLibraryW(windows::core::w!("dcomp.dll")) }.ok()?;
853        let address = unsafe {
854            GetProcAddress(
855                hmodule,
856                windows::core::s!("DCompositionWaitForCompositorClock"),
857            )
858        }?;
859        Some(unsafe { transmute(address) })
860    })
861}
862
863fn fallback_vsync_fn() -> impl Fn(HANDLE) -> bool + Send {
864    let freq = WindowsDisplay::primary_monitor()
865        .and_then(|monitor| monitor.frequency())
866        .unwrap_or(60);
867    log::info!("primaly refresh rate is {freq}Hz");
868
869    let interval = (1000 / freq).max(1);
870    log::info!("expected interval is {interval}ms");
871
872    unsafe { timeBeginPeriod(1) };
873
874    struct TimePeriod;
875    impl Drop for TimePeriod {
876        fn drop(&mut self) {
877            unsafe { timeEndPeriod(1) };
878        }
879    }
880    let period = TimePeriod;
881
882    move |timer_stop_event| {
883        let _ = (&period,);
884        (unsafe { WaitForSingleObject(timer_stop_event, interval) }) == WAIT_TIMEOUT
885    }
886}
887
888fn load_icon() -> Result<HICON> {
889    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
890    let handle = unsafe {
891        LoadImageW(
892            module,
893            IDI_APPLICATION,
894            IMAGE_ICON,
895            0,
896            0,
897            LR_DEFAULTSIZE | LR_SHARED,
898        )
899        .context("unable to load icon file")?
900    };
901    Ok(HICON(handle.0))
902}