platform.rs

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