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