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