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