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