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