platform.rs

  1use std::{
  2    cell::RefCell,
  3    mem::ManuallyDrop,
  4    path::{Path, PathBuf},
  5    rc::Rc,
  6    sync::Arc,
  7};
  8
  9use ::util::{ResultExt, paths::SanitizedPath};
 10use anyhow::{Context as _, Result, anyhow};
 11use async_task::Runnable;
 12use futures::channel::oneshot::{self, Receiver};
 13use itertools::Itertools;
 14use parking_lot::RwLock;
 15use smallvec::SmallVec;
 16use windows::{
 17    UI::ViewManagement::UISettings,
 18    Win32::{
 19        Foundation::*,
 20        Graphics::{
 21            Gdi::*,
 22            Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
 23        },
 24        Security::Credentials::*,
 25        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*},
 26        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 27    },
 28    core::*,
 29};
 30
 31use crate::{platform::blade::BladeContext, *};
 32
 33pub(crate) struct WindowsPlatform {
 34    state: RefCell<WindowsPlatformState>,
 35    raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 36    // The below members will never change throughout the entire lifecycle of the app.
 37    gpu_context: BladeContext,
 38    icon: HICON,
 39    main_receiver: flume::Receiver<Runnable>,
 40    background_executor: BackgroundExecutor,
 41    foreground_executor: ForegroundExecutor,
 42    text_system: Arc<DirectWriteTextSystem>,
 43    windows_version: WindowsVersion,
 44    bitmap_factory: ManuallyDrop<IWICImagingFactory>,
 45    validation_number: usize,
 46    main_thread_id_win32: u32,
 47}
 48
 49pub(crate) struct WindowsPlatformState {
 50    callbacks: PlatformCallbacks,
 51    menus: Vec<OwnedMenu>,
 52    jump_list: JumpList,
 53    // NOTE: standard cursor handles don't need to close.
 54    pub(crate) current_cursor: Option<HCURSOR>,
 55}
 56
 57#[derive(Default)]
 58struct PlatformCallbacks {
 59    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 60    quit: Option<Box<dyn FnMut()>>,
 61    reopen: Option<Box<dyn FnMut()>>,
 62    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 63    will_open_app_menu: Option<Box<dyn FnMut()>>,
 64    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 65    keyboard_layout_change: Option<Box<dyn FnMut()>>,
 66}
 67
 68impl WindowsPlatformState {
 69    fn new() -> Self {
 70        let callbacks = PlatformCallbacks::default();
 71        let jump_list = JumpList::new();
 72        let current_cursor = load_cursor(CursorStyle::Arrow);
 73
 74        Self {
 75            callbacks,
 76            jump_list,
 77            current_cursor,
 78            menus: Vec::new(),
 79        }
 80    }
 81}
 82
 83impl WindowsPlatform {
 84    pub(crate) fn new() -> Self {
 85        unsafe {
 86            OleInitialize(None).expect("unable to initialize Windows OLE");
 87        }
 88        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
 89        let main_thread_id_win32 = unsafe { GetCurrentThreadId() };
 90        let validation_number = rand::random::<usize>();
 91        let dispatcher = Arc::new(WindowsDispatcher::new(
 92            main_sender,
 93            main_thread_id_win32,
 94            validation_number,
 95        ));
 96        let background_executor = BackgroundExecutor::new(dispatcher.clone());
 97        let foreground_executor = ForegroundExecutor::new(dispatcher);
 98        let bitmap_factory = ManuallyDrop::new(unsafe {
 99            CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
100                .expect("Error creating bitmap factory.")
101        });
102        let text_system = Arc::new(
103            DirectWriteTextSystem::new(&bitmap_factory)
104                .expect("Error creating DirectWriteTextSystem"),
105        );
106        let icon = load_icon().unwrap_or_default();
107        let state = RefCell::new(WindowsPlatformState::new());
108        let raw_window_handles = RwLock::new(SmallVec::new());
109        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
110        let windows_version = WindowsVersion::new().expect("Error retrieve windows version");
111
112        Self {
113            state,
114            raw_window_handles,
115            gpu_context,
116            icon,
117            main_receiver,
118            background_executor,
119            foreground_executor,
120            text_system,
121            windows_version,
122            bitmap_factory,
123            validation_number,
124            main_thread_id_win32,
125        }
126    }
127
128    fn redraw_all(&self) {
129        for handle in self.raw_window_handles.read().iter() {
130            unsafe {
131                RedrawWindow(Some(*handle), None, None, RDW_INVALIDATE | RDW_UPDATENOW)
132                    .ok()
133                    .log_err();
134            }
135        }
136    }
137
138    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
139        self.raw_window_handles
140            .read()
141            .iter()
142            .find(|entry| *entry == &hwnd)
143            .and_then(|hwnd| try_get_window_inner(*hwnd))
144    }
145
146    #[inline]
147    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
148        self.raw_window_handles
149            .read()
150            .iter()
151            .for_each(|handle| unsafe {
152                PostMessageW(Some(*handle), message, wparam, lparam).log_err();
153            });
154    }
155
156    fn close_one_window(&self, target_window: HWND) -> bool {
157        let mut lock = self.raw_window_handles.write();
158        let index = lock
159            .iter()
160            .position(|handle| *handle == target_window)
161            .unwrap();
162        lock.remove(index);
163
164        lock.is_empty()
165    }
166
167    #[inline]
168    fn run_foreground_task(&self) {
169        for runnable in self.main_receiver.drain() {
170            runnable.run();
171        }
172    }
173
174    fn generate_creation_info(&self) -> WindowCreationInfo {
175        WindowCreationInfo {
176            icon: self.icon,
177            executor: self.foreground_executor.clone(),
178            current_cursor: self.state.borrow().current_cursor,
179            windows_version: self.windows_version,
180            validation_number: self.validation_number,
181            main_receiver: self.main_receiver.clone(),
182            main_thread_id_win32: self.main_thread_id_win32,
183        }
184    }
185
186    fn handle_dock_action_event(&self, action_idx: usize) {
187        let mut lock = self.state.borrow_mut();
188        if let Some(mut callback) = lock.callbacks.app_menu_action.take() {
189            let Some(action) = lock
190                .jump_list
191                .dock_menus
192                .get(action_idx)
193                .map(|dock_menu| dock_menu.action.boxed_clone())
194            else {
195                lock.callbacks.app_menu_action = Some(callback);
196                log::error!("Dock menu for index {action_idx} not found");
197                return;
198            };
199            drop(lock);
200            callback(&*action);
201            self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
202        }
203    }
204
205    fn handle_input_lang_change(&self) {
206        let mut lock = self.state.borrow_mut();
207        if let Some(mut callback) = lock.callbacks.keyboard_layout_change.take() {
208            drop(lock);
209            callback();
210            self.state
211                .borrow_mut()
212                .callbacks
213                .keyboard_layout_change
214                .get_or_insert(callback);
215        }
216    }
217
218    // Returns true if the app should quit.
219    fn handle_events(&self) -> bool {
220        let mut msg = MSG::default();
221        unsafe {
222            while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
223                match msg.message {
224                    WM_QUIT => return true,
225                    WM_INPUTLANGCHANGE
226                    | WM_GPUI_CLOSE_ONE_WINDOW
227                    | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
228                    | WM_GPUI_DOCK_MENU_ACTION => {
229                        if self.handle_gpui_evnets(msg.message, msg.wParam, msg.lParam, &msg) {
230                            return true;
231                        }
232                    }
233                    _ => {
234                        // todo(windows)
235                        // crate `windows 0.56` reports true as Err
236                        TranslateMessage(&msg).as_bool();
237                        DispatchMessageW(&msg);
238                    }
239                }
240            }
241        }
242        false
243    }
244
245    // Returns true if the app should quit.
246    fn handle_gpui_evnets(
247        &self,
248        message: u32,
249        wparam: WPARAM,
250        lparam: LPARAM,
251        msg: *const MSG,
252    ) -> bool {
253        if wparam.0 != self.validation_number {
254            unsafe { DispatchMessageW(msg) };
255            return false;
256        }
257        match message {
258            WM_GPUI_CLOSE_ONE_WINDOW => {
259                if self.close_one_window(HWND(lparam.0 as _)) {
260                    return true;
261                }
262            }
263            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
264            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
265            WM_INPUTLANGCHANGE => self.handle_input_lang_change(),
266            _ => unreachable!(),
267        }
268        false
269    }
270
271    fn set_dock_menus(&self, menus: Vec<MenuItem>) {
272        let mut actions = Vec::new();
273        menus.into_iter().for_each(|menu| {
274            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
275                actions.push(dock_menu);
276            }
277        });
278        let mut lock = self.state.borrow_mut();
279        lock.jump_list.dock_menus = actions;
280        update_jump_list(&lock.jump_list).log_err();
281    }
282
283    fn update_jump_list(
284        &self,
285        menus: Vec<MenuItem>,
286        entries: Vec<SmallVec<[PathBuf; 2]>>,
287    ) -> Vec<SmallVec<[PathBuf; 2]>> {
288        let mut actions = Vec::new();
289        menus.into_iter().for_each(|menu| {
290            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
291                actions.push(dock_menu);
292            }
293        });
294        let mut lock = self.state.borrow_mut();
295        lock.jump_list.dock_menus = actions;
296        lock.jump_list.recent_workspaces = entries;
297        update_jump_list(&lock.jump_list)
298            .log_err()
299            .unwrap_or_default()
300    }
301}
302
303impl Platform for WindowsPlatform {
304    fn background_executor(&self) -> BackgroundExecutor {
305        self.background_executor.clone()
306    }
307
308    fn foreground_executor(&self) -> ForegroundExecutor {
309        self.foreground_executor.clone()
310    }
311
312    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
313        self.text_system.clone()
314    }
315
316    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
317        Box::new(
318            WindowsKeyboardLayout::new()
319                .log_err()
320                .unwrap_or(WindowsKeyboardLayout::unknown()),
321        )
322    }
323
324    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
325        self.state.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
326    }
327
328    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
329        on_finish_launching();
330        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
331        begin_vsync(*vsync_event);
332        'a: loop {
333            let wait_result = unsafe {
334                MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
335            };
336
337            match wait_result {
338                // compositor clock ticked so we should draw a frame
339                WAIT_EVENT(0) => self.redraw_all(),
340                // Windows thread messages are posted
341                WAIT_EVENT(1) => {
342                    if self.handle_events() {
343                        break 'a;
344                    }
345                }
346                _ => {
347                    log::error!("Something went wrong while waiting {:?}", wait_result);
348                    break;
349                }
350            }
351        }
352
353        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
354            callback();
355        }
356    }
357
358    fn quit(&self) {
359        self.foreground_executor()
360            .spawn(async { unsafe { PostQuitMessage(0) } })
361            .detach();
362    }
363
364    fn restart(&self, _: Option<PathBuf>) {
365        let pid = std::process::id();
366        let Some(app_path) = self.app_path().log_err() else {
367            return;
368        };
369        let script = format!(
370            r#"
371            $pidToWaitFor = {}
372            $exePath = "{}"
373
374            while ($true) {{
375                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
376                if (-not $process) {{
377                    Start-Process -FilePath $exePath
378                    break
379                }}
380                Start-Sleep -Seconds 0.1
381            }}
382            "#,
383            pid,
384            app_path.display(),
385        );
386        let restart_process = util::command::new_std_command("powershell.exe")
387            .arg("-command")
388            .arg(script)
389            .spawn();
390
391        match restart_process {
392            Ok(_) => self.quit(),
393            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
394        }
395    }
396
397    fn activate(&self, _ignoring_other_apps: bool) {}
398
399    fn hide(&self) {}
400
401    // todo(windows)
402    fn hide_other_apps(&self) {
403        unimplemented!()
404    }
405
406    // todo(windows)
407    fn unhide_other_apps(&self) {
408        unimplemented!()
409    }
410
411    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
412        WindowsDisplay::displays()
413    }
414
415    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
416        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
417    }
418
419    fn is_screen_capture_supported(&self) -> bool {
420        false
421    }
422
423    fn screen_capture_sources(
424        &self,
425    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
426        let (mut tx, rx) = oneshot::channel();
427        tx.send(Err(anyhow!("screen capture not implemented"))).ok();
428        rx
429    }
430
431    fn active_window(&self) -> Option<AnyWindowHandle> {
432        let active_window_hwnd = unsafe { GetActiveWindow() };
433        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
434            .map(|inner| inner.handle)
435    }
436
437    fn open_window(
438        &self,
439        handle: AnyWindowHandle,
440        options: WindowParams,
441    ) -> Result<Box<dyn PlatformWindow>> {
442        let window = WindowsWindow::new(
443            handle,
444            options,
445            self.generate_creation_info(),
446            &self.gpu_context,
447        )?;
448        let handle = window.get_raw_handle();
449        self.raw_window_handles.write().push(handle);
450
451        Ok(Box::new(window))
452    }
453
454    fn window_appearance(&self) -> WindowAppearance {
455        system_appearance().log_err().unwrap_or_default()
456    }
457
458    fn open_url(&self, url: &str) {
459        let url_string = url.to_string();
460        self.background_executor()
461            .spawn(async move {
462                if url_string.is_empty() {
463                    return;
464                }
465                open_target(url_string.as_str());
466            })
467            .detach();
468    }
469
470    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
471        self.state.borrow_mut().callbacks.open_urls = Some(callback);
472    }
473
474    fn prompt_for_paths(
475        &self,
476        options: PathPromptOptions,
477    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
478        let (tx, rx) = oneshot::channel();
479        self.foreground_executor()
480            .spawn(async move {
481                let _ = tx.send(file_open_dialog(options));
482            })
483            .detach();
484
485        rx
486    }
487
488    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
489        let directory = directory.to_owned();
490        let (tx, rx) = oneshot::channel();
491        self.foreground_executor()
492            .spawn(async move {
493                let _ = tx.send(file_save_dialog(directory));
494            })
495            .detach();
496
497        rx
498    }
499
500    fn can_select_mixed_files_and_dirs(&self) -> bool {
501        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
502        false
503    }
504
505    fn reveal_path(&self, path: &Path) {
506        let Ok(file_full_path) = path.canonicalize() else {
507            log::error!("unable to parse file path");
508            return;
509        };
510        self.background_executor()
511            .spawn(async move {
512                let Some(path) = file_full_path.to_str() else {
513                    return;
514                };
515                if path.is_empty() {
516                    return;
517                }
518                open_target_in_explorer(path);
519            })
520            .detach();
521    }
522
523    fn open_with_system(&self, path: &Path) {
524        let Ok(full_path) = path.canonicalize() else {
525            log::error!("unable to parse file full path: {}", path.display());
526            return;
527        };
528        self.background_executor()
529            .spawn(async move {
530                let Some(full_path_str) = full_path.to_str() else {
531                    return;
532                };
533                if full_path_str.is_empty() {
534                    return;
535                };
536                open_target(full_path_str);
537            })
538            .detach();
539    }
540
541    fn on_quit(&self, callback: Box<dyn FnMut()>) {
542        self.state.borrow_mut().callbacks.quit = Some(callback);
543    }
544
545    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
546        self.state.borrow_mut().callbacks.reopen = Some(callback);
547    }
548
549    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
550        self.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
551    }
552
553    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
554        Some(self.state.borrow().menus.clone())
555    }
556
557    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
558        self.set_dock_menus(menus);
559    }
560
561    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
562        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
563    }
564
565    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
566        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
567    }
568
569    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
570        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
571    }
572
573    fn app_path(&self) -> Result<PathBuf> {
574        Ok(std::env::current_exe()?)
575    }
576
577    // todo(windows)
578    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
579        anyhow::bail!("not yet implemented");
580    }
581
582    fn set_cursor_style(&self, style: CursorStyle) {
583        let hcursor = load_cursor(style);
584        let mut lock = self.state.borrow_mut();
585        if lock.current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
586            self.post_message(
587                WM_GPUI_CURSOR_STYLE_CHANGED,
588                WPARAM(0),
589                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
590            );
591            lock.current_cursor = hcursor;
592        }
593    }
594
595    fn should_auto_hide_scrollbars(&self) -> bool {
596        should_auto_hide_scrollbars().log_err().unwrap_or(false)
597    }
598
599    fn write_to_clipboard(&self, item: ClipboardItem) {
600        write_to_clipboard(item);
601    }
602
603    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
604        read_from_clipboard()
605    }
606
607    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
608        let mut password = password.to_vec();
609        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
610        let mut target_name = windows_credentials_target_name(url)
611            .encode_utf16()
612            .chain(Some(0))
613            .collect_vec();
614        self.foreground_executor().spawn(async move {
615            let credentials = CREDENTIALW {
616                LastWritten: unsafe { GetSystemTimeAsFileTime() },
617                Flags: CRED_FLAGS(0),
618                Type: CRED_TYPE_GENERIC,
619                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
620                CredentialBlobSize: password.len() as u32,
621                CredentialBlob: password.as_ptr() as *mut _,
622                Persist: CRED_PERSIST_LOCAL_MACHINE,
623                UserName: PWSTR::from_raw(username.as_mut_ptr()),
624                ..CREDENTIALW::default()
625            };
626            unsafe { CredWriteW(&credentials, 0) }?;
627            Ok(())
628        })
629    }
630
631    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
632        let mut target_name = windows_credentials_target_name(url)
633            .encode_utf16()
634            .chain(Some(0))
635            .collect_vec();
636        self.foreground_executor().spawn(async move {
637            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
638            unsafe {
639                CredReadW(
640                    PCWSTR::from_raw(target_name.as_ptr()),
641                    CRED_TYPE_GENERIC,
642                    None,
643                    &mut credentials,
644                )?
645            };
646
647            if credentials.is_null() {
648                Ok(None)
649            } else {
650                let username: String = unsafe { (*credentials).UserName.to_string()? };
651                let credential_blob = unsafe {
652                    std::slice::from_raw_parts(
653                        (*credentials).CredentialBlob,
654                        (*credentials).CredentialBlobSize as usize,
655                    )
656                };
657                let password = credential_blob.to_vec();
658                unsafe { CredFree(credentials as *const _ as _) };
659                Ok(Some((username, password)))
660            }
661        })
662    }
663
664    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
665        let mut target_name = windows_credentials_target_name(url)
666            .encode_utf16()
667            .chain(Some(0))
668            .collect_vec();
669        self.foreground_executor().spawn(async move {
670            unsafe {
671                CredDeleteW(
672                    PCWSTR::from_raw(target_name.as_ptr()),
673                    CRED_TYPE_GENERIC,
674                    None,
675                )?
676            };
677            Ok(())
678        })
679    }
680
681    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
682        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
683    }
684
685    fn perform_dock_menu_action(&self, action: usize) {
686        unsafe {
687            PostThreadMessageW(
688                self.main_thread_id_win32,
689                WM_GPUI_DOCK_MENU_ACTION,
690                WPARAM(self.validation_number),
691                LPARAM(action as isize),
692            )
693            .log_err();
694        }
695    }
696
697    fn update_jump_list(
698        &self,
699        menus: Vec<MenuItem>,
700        entries: Vec<SmallVec<[PathBuf; 2]>>,
701    ) -> Vec<SmallVec<[PathBuf; 2]>> {
702        self.update_jump_list(menus, entries)
703    }
704}
705
706impl Drop for WindowsPlatform {
707    fn drop(&mut self) {
708        unsafe {
709            ManuallyDrop::drop(&mut self.bitmap_factory);
710            OleUninitialize();
711        }
712    }
713}
714
715pub(crate) struct WindowCreationInfo {
716    pub(crate) icon: HICON,
717    pub(crate) executor: ForegroundExecutor,
718    pub(crate) current_cursor: Option<HCURSOR>,
719    pub(crate) windows_version: WindowsVersion,
720    pub(crate) validation_number: usize,
721    pub(crate) main_receiver: flume::Receiver<Runnable>,
722    pub(crate) main_thread_id_win32: u32,
723}
724
725fn open_target(target: &str) {
726    unsafe {
727        let ret = ShellExecuteW(
728            None,
729            windows::core::w!("open"),
730            &HSTRING::from(target),
731            None,
732            None,
733            SW_SHOWDEFAULT,
734        );
735        if ret.0 as isize <= 32 {
736            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
737        }
738    }
739}
740
741fn open_target_in_explorer(target: &str) {
742    unsafe {
743        let ret = ShellExecuteW(
744            None,
745            windows::core::w!("open"),
746            windows::core::w!("explorer.exe"),
747            &HSTRING::from(format!("/select,{}", target).as_str()),
748            None,
749            SW_SHOWDEFAULT,
750        );
751        if ret.0 as isize <= 32 {
752            log::error!(
753                "Unable to open target in explorer: {}",
754                std::io::Error::last_os_error()
755            );
756        }
757    }
758}
759
760fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
761    let folder_dialog: IFileOpenDialog =
762        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
763
764    let mut dialog_options = FOS_FILEMUSTEXIST;
765    if options.multiple {
766        dialog_options |= FOS_ALLOWMULTISELECT;
767    }
768    if options.directories {
769        dialog_options |= FOS_PICKFOLDERS;
770    }
771
772    unsafe {
773        folder_dialog.SetOptions(dialog_options)?;
774        if folder_dialog.Show(None).is_err() {
775            // User cancelled
776            return Ok(None);
777        }
778    }
779
780    let results = unsafe { folder_dialog.GetResults()? };
781    let file_count = unsafe { results.GetCount()? };
782    if file_count == 0 {
783        return Ok(None);
784    }
785
786    let mut paths = Vec::new();
787    for i in 0..file_count {
788        let item = unsafe { results.GetItemAt(i)? };
789        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
790        paths.push(PathBuf::from(path));
791    }
792
793    Ok(Some(paths))
794}
795
796fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
797    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
798    if !directory.to_string_lossy().is_empty() {
799        if let Some(full_path) = directory.canonicalize().log_err() {
800            let full_path = SanitizedPath::from(full_path);
801            let full_path_string = full_path.to_string();
802            let path_item: IShellItem =
803                unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
804            unsafe { dialog.SetFolder(&path_item).log_err() };
805        }
806    }
807    unsafe {
808        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
809            pszName: windows::core::w!("All files"),
810            pszSpec: windows::core::w!("*.*"),
811        }])?;
812        if dialog.Show(None).is_err() {
813            // User cancelled
814            return Ok(None);
815        }
816    }
817    let shell_item = unsafe { dialog.GetResult()? };
818    let file_path_string = unsafe {
819        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
820        let string = pwstr.to_string()?;
821        CoTaskMemFree(Some(pwstr.0 as _));
822        string
823    };
824    Ok(Some(PathBuf::from(file_path_string)))
825}
826
827fn begin_vsync(vsync_event: HANDLE) {
828    let event: SafeHandle = vsync_event.into();
829    std::thread::spawn(move || unsafe {
830        loop {
831            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
832            SetEvent(*event).log_err();
833        }
834    });
835}
836
837fn load_icon() -> Result<HICON> {
838    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
839    let handle = unsafe {
840        LoadImageW(
841            Some(module.into()),
842            windows::core::PCWSTR(1 as _),
843            IMAGE_ICON,
844            0,
845            0,
846            LR_DEFAULTSIZE | LR_SHARED,
847        )
848        .context("unable to load icon file")?
849    };
850    Ok(HICON(handle.0))
851}
852
853#[inline]
854fn should_auto_hide_scrollbars() -> Result<bool> {
855    let ui_settings = UISettings::new()?;
856    Ok(ui_settings.AutoHideScrollBars()?)
857}
858
859#[cfg(test)]
860mod tests {
861    use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
862
863    #[test]
864    fn test_clipboard() {
865        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
866        write_to_clipboard(item.clone());
867        assert_eq!(read_from_clipboard(), Some(item));
868
869        let item = ClipboardItem::new_string("12345".to_string());
870        write_to_clipboard(item.clone());
871        assert_eq!(read_from_clipboard(), Some(item));
872
873        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
874        write_to_clipboard(item.clone());
875        assert_eq!(read_from_clipboard(), Some(item));
876    }
877}