1// todo(windows): remove
2#![allow(unused_variables)]
3
4use std::{
5 cell::{Cell, RefCell},
6 ffi::{c_void, OsString},
7 os::windows::ffi::{OsStrExt, OsStringExt},
8 path::{Path, PathBuf},
9 rc::Rc,
10 sync::Arc,
11};
12
13use ::util::ResultExt;
14use anyhow::{anyhow, Context, Result};
15use clipboard_win::{get_clipboard_string, set_clipboard_string};
16use futures::channel::oneshot::{self, Receiver};
17use itertools::Itertools;
18use parking_lot::RwLock;
19use smallvec::SmallVec;
20use time::UtcOffset;
21use windows::{
22 core::*,
23 Win32::{
24 Foundation::*,
25 Graphics::Gdi::*,
26 Security::Credentials::*,
27 System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*, Time::*},
28 UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
29 },
30 UI::{
31 Color,
32 ViewManagement::{UIColorType, UISettings},
33 },
34};
35
36use crate::*;
37
38pub(crate) struct WindowsPlatform {
39 state: RefCell<WindowsPlatformState>,
40 raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
41 // The below members will never change throughout the entire lifecycle of the app.
42 icon: HICON,
43 background_executor: BackgroundExecutor,
44 foreground_executor: ForegroundExecutor,
45 text_system: Arc<dyn PlatformTextSystem>,
46}
47
48pub(crate) struct WindowsPlatformState {
49 callbacks: PlatformCallbacks,
50 // NOTE: standard cursor handles don't need to close.
51 pub(crate) current_cursor: HCURSOR,
52}
53
54#[derive(Default)]
55struct PlatformCallbacks {
56 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
57 quit: Option<Box<dyn FnMut()>>,
58 reopen: Option<Box<dyn FnMut()>>,
59 app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
60 will_open_app_menu: Option<Box<dyn FnMut()>>,
61 validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
62}
63
64impl WindowsPlatformState {
65 fn new() -> Self {
66 let callbacks = PlatformCallbacks::default();
67 let current_cursor = load_cursor(CursorStyle::Arrow);
68
69 Self {
70 callbacks,
71 current_cursor,
72 }
73 }
74}
75
76impl WindowsPlatform {
77 pub(crate) fn new() -> Self {
78 unsafe {
79 OleInitialize(None).expect("unable to initialize Windows OLE");
80 }
81 let dispatcher = Arc::new(WindowsDispatcher::new());
82 let background_executor = BackgroundExecutor::new(dispatcher.clone());
83 let foreground_executor = ForegroundExecutor::new(dispatcher);
84 let text_system = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
85 log::info!("Using direct write text system.");
86 Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
87 } else {
88 log::info!("Using cosmic text system.");
89 Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
90 };
91 let icon = load_icon().unwrap_or_default();
92 let state = RefCell::new(WindowsPlatformState::new());
93 let raw_window_handles = RwLock::new(SmallVec::new());
94
95 Self {
96 state,
97 raw_window_handles,
98 icon,
99 background_executor,
100 foreground_executor,
101 text_system,
102 }
103 }
104
105 fn redraw_all(&self) {
106 for handle in self.raw_window_handles.read().iter() {
107 unsafe {
108 RedrawWindow(
109 *handle,
110 None,
111 HRGN::default(),
112 RDW_INVALIDATE | RDW_UPDATENOW,
113 )
114 .ok()
115 .log_err();
116 }
117 }
118 }
119
120 pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
121 self.raw_window_handles
122 .read()
123 .iter()
124 .find(|entry| *entry == &hwnd)
125 .and_then(|hwnd| try_get_window_inner(*hwnd))
126 }
127
128 #[inline]
129 fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
130 self.raw_window_handles
131 .read()
132 .iter()
133 .for_each(|handle| unsafe {
134 PostMessageW(*handle, message, wparam, lparam).log_err();
135 });
136 }
137
138 fn close_one_window(&self, target_window: HWND) -> bool {
139 let mut lock = self.raw_window_handles.write();
140 let index = lock
141 .iter()
142 .position(|handle| *handle == target_window)
143 .unwrap();
144 lock.remove(index);
145
146 lock.is_empty()
147 }
148}
149
150impl Platform for WindowsPlatform {
151 fn background_executor(&self) -> BackgroundExecutor {
152 self.background_executor.clone()
153 }
154
155 fn foreground_executor(&self) -> ForegroundExecutor {
156 self.foreground_executor.clone()
157 }
158
159 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
160 self.text_system.clone()
161 }
162
163 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
164 on_finish_launching();
165 let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
166 begin_vsync(*vsync_event);
167 'a: loop {
168 let wait_result = unsafe {
169 MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
170 };
171
172 match wait_result {
173 // compositor clock ticked so we should draw a frame
174 WAIT_EVENT(0) => {
175 self.redraw_all();
176 }
177 // Windows thread messages are posted
178 WAIT_EVENT(1) => {
179 let mut msg = MSG::default();
180 unsafe {
181 while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
182 match msg.message {
183 WM_QUIT => break 'a,
184 CLOSE_ONE_WINDOW => {
185 if self.close_one_window(HWND(msg.lParam.0)) {
186 break 'a;
187 }
188 }
189 _ => {
190 // todo(windows)
191 // crate `windows 0.56` reports true as Err
192 TranslateMessage(&msg).as_bool();
193 DispatchMessageW(&msg);
194 }
195 }
196 }
197 }
198 }
199 _ => {
200 log::error!("Something went wrong while waiting {:?}", wait_result);
201 break;
202 }
203 }
204 }
205
206 if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
207 callback();
208 }
209 }
210
211 fn quit(&self) {
212 self.foreground_executor()
213 .spawn(async { unsafe { PostQuitMessage(0) } })
214 .detach();
215 }
216
217 fn restart(&self, _: Option<PathBuf>) {
218 let pid = std::process::id();
219 let Some(app_path) = self.app_path().log_err() else {
220 return;
221 };
222 let script = format!(
223 r#"
224 $pidToWaitFor = {}
225 $exePath = "{}"
226
227 while ($true) {{
228 $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
229 if (-not $process) {{
230 Start-Process -FilePath $exePath
231 break
232 }}
233 Start-Sleep -Seconds 0.1
234 }}
235 "#,
236 pid,
237 app_path.display(),
238 );
239 let restart_process = std::process::Command::new("powershell.exe")
240 .arg("-command")
241 .arg(script)
242 .spawn();
243
244 match restart_process {
245 Ok(_) => self.quit(),
246 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
247 }
248 }
249
250 // todo(windows)
251 fn activate(&self, ignoring_other_apps: bool) {}
252
253 // todo(windows)
254 fn hide(&self) {
255 unimplemented!()
256 }
257
258 // todo(windows)
259 fn hide_other_apps(&self) {
260 unimplemented!()
261 }
262
263 // todo(windows)
264 fn unhide_other_apps(&self) {
265 unimplemented!()
266 }
267
268 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
269 WindowsDisplay::displays()
270 }
271
272 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
273 WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
274 }
275
276 fn active_window(&self) -> Option<AnyWindowHandle> {
277 let active_window_hwnd = unsafe { GetActiveWindow() };
278 self.try_get_windows_inner_from_hwnd(active_window_hwnd)
279 .map(|inner| inner.handle)
280 }
281
282 fn open_window(
283 &self,
284 handle: AnyWindowHandle,
285 options: WindowParams,
286 ) -> Result<Box<dyn PlatformWindow>> {
287 let lock = self.state.borrow();
288 let window = WindowsWindow::new(
289 handle,
290 options,
291 self.icon,
292 self.foreground_executor.clone(),
293 lock.current_cursor,
294 );
295 drop(lock);
296 let handle = window.get_raw_handle();
297 self.raw_window_handles.write().push(handle);
298
299 Ok(Box::new(window))
300 }
301
302 fn window_appearance(&self) -> WindowAppearance {
303 system_appearance().log_err().unwrap_or_default()
304 }
305
306 fn open_url(&self, url: &str) {
307 let url_string = url.to_string();
308 self.background_executor()
309 .spawn(async move {
310 if url_string.is_empty() {
311 return;
312 }
313 open_target(url_string.as_str());
314 })
315 .detach();
316 }
317
318 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
319 self.state.borrow_mut().callbacks.open_urls = Some(callback);
320 }
321
322 fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
323 let (tx, rx) = oneshot::channel();
324
325 self.foreground_executor()
326 .spawn(async move {
327 let tx = Cell::new(Some(tx));
328
329 // create file open dialog
330 let folder_dialog: IFileOpenDialog = unsafe {
331 CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
332 &FileOpenDialog,
333 None,
334 CLSCTX_ALL,
335 )
336 .unwrap()
337 };
338
339 // dialog options
340 let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
341 if options.multiple {
342 dialog_options |= FOS_ALLOWMULTISELECT;
343 }
344 if options.directories {
345 dialog_options |= FOS_PICKFOLDERS;
346 }
347
348 unsafe {
349 folder_dialog.SetOptions(dialog_options).unwrap();
350 folder_dialog
351 .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
352 .unwrap();
353 }
354
355 let hr = unsafe { folder_dialog.Show(None) };
356
357 if hr.is_err() {
358 if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
359 // user canceled error
360 if let Some(tx) = tx.take() {
361 tx.send(None).unwrap();
362 }
363 return;
364 }
365 }
366
367 let mut results = unsafe { folder_dialog.GetResults().unwrap() };
368
369 let mut paths: Vec<PathBuf> = Vec::new();
370 for i in 0..unsafe { results.GetCount().unwrap() } {
371 let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
372 let mut path: PWSTR =
373 unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
374 let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
375
376 paths.push(PathBuf::from(path_os_string));
377 }
378
379 if let Some(tx) = tx.take() {
380 if paths.len() == 0 {
381 tx.send(None).unwrap();
382 } else {
383 tx.send(Some(paths)).unwrap();
384 }
385 }
386 })
387 .detach();
388
389 rx
390 }
391
392 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
393 let directory = directory.to_owned();
394 let (tx, rx) = oneshot::channel();
395 self.foreground_executor()
396 .spawn(async move {
397 unsafe {
398 let Ok(dialog) = show_savefile_dialog(directory) else {
399 let _ = tx.send(None);
400 return;
401 };
402 let Ok(_) = dialog.Show(None) else {
403 let _ = tx.send(None); // user cancel
404 return;
405 };
406 if let Ok(shell_item) = dialog.GetResult() {
407 if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
408 let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
409 return;
410 }
411 }
412 let _ = tx.send(None);
413 }
414 })
415 .detach();
416
417 rx
418 }
419
420 fn reveal_path(&self, path: &Path) {
421 let Ok(file_full_path) = path.canonicalize() else {
422 log::error!("unable to parse file path");
423 return;
424 };
425 self.background_executor()
426 .spawn(async move {
427 let Some(path) = file_full_path.to_str() else {
428 return;
429 };
430 if path.is_empty() {
431 return;
432 }
433 open_target_in_explorer(path);
434 })
435 .detach();
436 }
437
438 fn on_quit(&self, callback: Box<dyn FnMut()>) {
439 self.state.borrow_mut().callbacks.quit = Some(callback);
440 }
441
442 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
443 self.state.borrow_mut().callbacks.reopen = Some(callback);
444 }
445
446 // todo(windows)
447 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
448 fn set_dock_menu(&self, menus: Vec<MenuItem>, keymap: &Keymap) {}
449
450 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
451 self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
452 }
453
454 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
455 self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
456 }
457
458 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
459 self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
460 }
461
462 fn app_path(&self) -> Result<PathBuf> {
463 Ok(std::env::current_exe()?)
464 }
465
466 fn local_timezone(&self) -> UtcOffset {
467 let mut info = unsafe { std::mem::zeroed() };
468 let ret = unsafe { GetTimeZoneInformation(&mut info) };
469 if ret == TIME_ZONE_ID_INVALID {
470 log::error!(
471 "Unable to get local timezone: {}",
472 std::io::Error::last_os_error()
473 );
474 return UtcOffset::UTC;
475 }
476 // Windows treat offset as:
477 // UTC = localtime + offset
478 // so we add a minus here
479 let hours = -info.Bias / 60;
480 let minutes = -info.Bias % 60;
481
482 UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
483 }
484
485 // todo(windows)
486 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
487 Err(anyhow!("not yet implemented"))
488 }
489
490 fn set_cursor_style(&self, style: CursorStyle) {
491 let hcursor = load_cursor(style);
492 let mut lock = self.state.borrow_mut();
493 if lock.current_cursor.0 != hcursor.0 {
494 self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
495 lock.current_cursor = hcursor;
496 }
497 }
498
499 fn should_auto_hide_scrollbars(&self) -> bool {
500 should_auto_hide_scrollbars().log_err().unwrap_or(false)
501 }
502
503 fn write_to_clipboard(&self, item: ClipboardItem) {
504 if item.text.len() > 0 {
505 set_clipboard_string(item.text()).unwrap();
506 }
507 }
508
509 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
510 let text = get_clipboard_string().ok()?;
511 Some(ClipboardItem {
512 text,
513 metadata: None,
514 })
515 }
516
517 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
518 let mut password = password.to_vec();
519 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
520 let mut target_name = windows_credentials_target_name(url)
521 .encode_utf16()
522 .chain(Some(0))
523 .collect_vec();
524 self.foreground_executor().spawn(async move {
525 let credentials = CREDENTIALW {
526 LastWritten: unsafe { GetSystemTimeAsFileTime() },
527 Flags: CRED_FLAGS(0),
528 Type: CRED_TYPE_GENERIC,
529 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
530 CredentialBlobSize: password.len() as u32,
531 CredentialBlob: password.as_ptr() as *mut _,
532 Persist: CRED_PERSIST_LOCAL_MACHINE,
533 UserName: PWSTR::from_raw(username.as_mut_ptr()),
534 ..CREDENTIALW::default()
535 };
536 unsafe { CredWriteW(&credentials, 0) }?;
537 Ok(())
538 })
539 }
540
541 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
542 let mut target_name = windows_credentials_target_name(url)
543 .encode_utf16()
544 .chain(Some(0))
545 .collect_vec();
546 self.foreground_executor().spawn(async move {
547 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
548 unsafe {
549 CredReadW(
550 PCWSTR::from_raw(target_name.as_ptr()),
551 CRED_TYPE_GENERIC,
552 0,
553 &mut credentials,
554 )?
555 };
556
557 if credentials.is_null() {
558 Ok(None)
559 } else {
560 let username: String = unsafe { (*credentials).UserName.to_string()? };
561 let credential_blob = unsafe {
562 std::slice::from_raw_parts(
563 (*credentials).CredentialBlob,
564 (*credentials).CredentialBlobSize as usize,
565 )
566 };
567 let password = credential_blob.to_vec();
568 unsafe { CredFree(credentials as *const c_void) };
569 Ok(Some((username, password)))
570 }
571 })
572 }
573
574 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
575 let mut target_name = windows_credentials_target_name(url)
576 .encode_utf16()
577 .chain(Some(0))
578 .collect_vec();
579 self.foreground_executor().spawn(async move {
580 unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
581 Ok(())
582 })
583 }
584
585 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
586 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
587 }
588}
589
590impl Drop for WindowsPlatform {
591 fn drop(&mut self) {
592 unsafe {
593 OleUninitialize();
594 }
595 }
596}
597
598fn open_target(target: &str) {
599 unsafe {
600 let ret = ShellExecuteW(
601 None,
602 windows::core::w!("open"),
603 &HSTRING::from(target),
604 None,
605 None,
606 SW_SHOWDEFAULT,
607 );
608 if ret.0 <= 32 {
609 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
610 }
611 }
612}
613
614fn open_target_in_explorer(target: &str) {
615 unsafe {
616 let ret = ShellExecuteW(
617 None,
618 windows::core::w!("open"),
619 windows::core::w!("explorer.exe"),
620 &HSTRING::from(format!("/select,{}", target).as_str()),
621 None,
622 SW_SHOWDEFAULT,
623 );
624 if ret.0 <= 32 {
625 log::error!(
626 "Unable to open target in explorer: {}",
627 std::io::Error::last_os_error()
628 );
629 }
630 }
631}
632
633unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
634 let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
635 let bind_context = CreateBindCtx(0)?;
636 let Ok(full_path) = directory.canonicalize() else {
637 return Ok(dialog);
638 };
639 let dir_str = full_path.into_os_string();
640 if dir_str.is_empty() {
641 return Ok(dialog);
642 }
643 let dir_vec = dir_str.encode_wide().collect_vec();
644 let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
645 .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
646 if ret.is_ok() {
647 let dir_shell_item: IShellItem = ret.unwrap();
648 let _ = dialog
649 .SetFolder(&dir_shell_item)
650 .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
651 }
652
653 Ok(dialog)
654}
655
656fn begin_vsync(vsync_evnet: HANDLE) {
657 std::thread::spawn(move || unsafe {
658 loop {
659 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
660 SetEvent(vsync_evnet).log_err();
661 }
662 });
663}
664
665fn load_icon() -> Result<HICON> {
666 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
667 let handle = unsafe {
668 LoadImageW(
669 module,
670 IDI_APPLICATION,
671 IMAGE_ICON,
672 0,
673 0,
674 LR_DEFAULTSIZE | LR_SHARED,
675 )
676 .context("unable to load icon file")?
677 };
678 Ok(HICON(handle.0))
679}
680
681// https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/apply-windows-themes
682#[inline]
683fn system_appearance() -> Result<WindowAppearance> {
684 let ui_settings = UISettings::new()?;
685 let foreground_color = ui_settings.GetColorValue(UIColorType::Foreground)?;
686 // If the foreground is light, then is_color_light will evaluate to true,
687 // meaning Dark mode is enabled.
688 if is_color_light(&foreground_color) {
689 Ok(WindowAppearance::Dark)
690 } else {
691 Ok(WindowAppearance::Light)
692 }
693}
694
695#[inline(always)]
696fn is_color_light(color: &Color) -> bool {
697 ((5 * color.G as u32) + (2 * color.R as u32) + color.B as u32) > (8 * 128)
698}
699
700#[inline]
701fn should_auto_hide_scrollbars() -> Result<bool> {
702 let ui_settings = UISettings::new()?;
703 Ok(ui_settings.AutoHideScrollBars()?)
704}