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 copypasta::{ClipboardContext, ClipboardProvider};
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 let mut ctx = ClipboardContext::new().unwrap();
506 ctx.set_contents(item.text().to_owned()).unwrap();
507 }
508 }
509
510 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
511 let mut ctx = ClipboardContext::new().unwrap();
512 let content = ctx.get_contents().ok()?;
513 Some(ClipboardItem {
514 text: content,
515 metadata: None,
516 })
517 }
518
519 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
520 let mut password = password.to_vec();
521 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
522 let mut target_name = windows_credentials_target_name(url)
523 .encode_utf16()
524 .chain(Some(0))
525 .collect_vec();
526 self.foreground_executor().spawn(async move {
527 let credentials = CREDENTIALW {
528 LastWritten: unsafe { GetSystemTimeAsFileTime() },
529 Flags: CRED_FLAGS(0),
530 Type: CRED_TYPE_GENERIC,
531 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
532 CredentialBlobSize: password.len() as u32,
533 CredentialBlob: password.as_ptr() as *mut _,
534 Persist: CRED_PERSIST_LOCAL_MACHINE,
535 UserName: PWSTR::from_raw(username.as_mut_ptr()),
536 ..CREDENTIALW::default()
537 };
538 unsafe { CredWriteW(&credentials, 0) }?;
539 Ok(())
540 })
541 }
542
543 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
544 let mut target_name = windows_credentials_target_name(url)
545 .encode_utf16()
546 .chain(Some(0))
547 .collect_vec();
548 self.foreground_executor().spawn(async move {
549 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
550 unsafe {
551 CredReadW(
552 PCWSTR::from_raw(target_name.as_ptr()),
553 CRED_TYPE_GENERIC,
554 0,
555 &mut credentials,
556 )?
557 };
558
559 if credentials.is_null() {
560 Ok(None)
561 } else {
562 let username: String = unsafe { (*credentials).UserName.to_string()? };
563 let credential_blob = unsafe {
564 std::slice::from_raw_parts(
565 (*credentials).CredentialBlob,
566 (*credentials).CredentialBlobSize as usize,
567 )
568 };
569 let password = credential_blob.to_vec();
570 unsafe { CredFree(credentials as *const c_void) };
571 Ok(Some((username, password)))
572 }
573 })
574 }
575
576 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
577 let mut target_name = windows_credentials_target_name(url)
578 .encode_utf16()
579 .chain(Some(0))
580 .collect_vec();
581 self.foreground_executor().spawn(async move {
582 unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
583 Ok(())
584 })
585 }
586
587 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
588 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
589 }
590}
591
592impl Drop for WindowsPlatform {
593 fn drop(&mut self) {
594 unsafe {
595 OleUninitialize();
596 }
597 }
598}
599
600fn open_target(target: &str) {
601 unsafe {
602 let ret = ShellExecuteW(
603 None,
604 windows::core::w!("open"),
605 &HSTRING::from(target),
606 None,
607 None,
608 SW_SHOWDEFAULT,
609 );
610 if ret.0 <= 32 {
611 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
612 }
613 }
614}
615
616fn open_target_in_explorer(target: &str) {
617 unsafe {
618 let ret = ShellExecuteW(
619 None,
620 windows::core::w!("open"),
621 windows::core::w!("explorer.exe"),
622 &HSTRING::from(format!("/select,{}", target).as_str()),
623 None,
624 SW_SHOWDEFAULT,
625 );
626 if ret.0 <= 32 {
627 log::error!(
628 "Unable to open target in explorer: {}",
629 std::io::Error::last_os_error()
630 );
631 }
632 }
633}
634
635unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
636 let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
637 let bind_context = CreateBindCtx(0)?;
638 let Ok(full_path) = directory.canonicalize() else {
639 return Ok(dialog);
640 };
641 let dir_str = full_path.into_os_string();
642 if dir_str.is_empty() {
643 return Ok(dialog);
644 }
645 let dir_vec = dir_str.encode_wide().collect_vec();
646 let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
647 .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
648 if ret.is_ok() {
649 let dir_shell_item: IShellItem = ret.unwrap();
650 let _ = dialog
651 .SetFolder(&dir_shell_item)
652 .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
653 }
654
655 Ok(dialog)
656}
657
658fn begin_vsync(vsync_evnet: HANDLE) {
659 std::thread::spawn(move || unsafe {
660 loop {
661 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
662 SetEvent(vsync_evnet).log_err();
663 }
664 });
665}
666
667fn load_icon() -> Result<HICON> {
668 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
669 let handle = unsafe {
670 LoadImageW(
671 module,
672 IDI_APPLICATION,
673 IMAGE_ICON,
674 0,
675 0,
676 LR_DEFAULTSIZE | LR_SHARED,
677 )
678 .context("unable to load icon file")?
679 };
680 Ok(HICON(handle.0))
681}
682
683// https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/apply-windows-themes
684#[inline]
685fn system_appearance() -> Result<WindowAppearance> {
686 let ui_settings = UISettings::new()?;
687 let foreground_color = ui_settings.GetColorValue(UIColorType::Foreground)?;
688 // If the foreground is light, then is_color_light will evaluate to true,
689 // meaning Dark mode is enabled.
690 if is_color_light(&foreground_color) {
691 Ok(WindowAppearance::Dark)
692 } else {
693 Ok(WindowAppearance::Light)
694 }
695}
696
697#[inline(always)]
698fn is_color_light(color: &Color) -> bool {
699 ((5 * color.G as u32) + (2 * color.R as u32) + color.B as u32) > (8 * 128)
700}
701
702#[inline]
703fn should_auto_hide_scrollbars() -> Result<bool> {
704 let ui_settings = UISettings::new()?;
705 Ok(ui_settings.AutoHideScrollBars()?)
706}