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