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