platform.rs

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