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