-
Notifications
You must be signed in to change notification settings - Fork 941
/
Copy pathwindow.rs
1522 lines (1324 loc) · 56 KB
/
window.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg(windows_platform)]
use std::cell::Cell;
use std::ffi::c_void;
use std::mem::{self, MaybeUninit};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex, MutexGuard};
use std::{io, panic, ptr};
use tracing::warn;
use windows_sys::Win32::Foundation::{
HWND, LPARAM, OLE_E_WRONGCOMPOBJ, POINT, POINTS, RECT, RPC_E_CHANGED_MODE, S_OK, WPARAM,
};
use windows_sys::Win32::Graphics::Dwm::{
DwmEnableBlurBehindWindow, DwmSetWindowAttribute, DWMWA_BORDER_COLOR, DWMWA_CAPTION_COLOR,
DWMWA_SYSTEMBACKDROP_TYPE, DWMWA_TEXT_COLOR, DWMWA_WINDOW_CORNER_PREFERENCE, DWM_BB_BLURREGION,
DWM_BB_ENABLE, DWM_BLURBEHIND, DWM_SYSTEMBACKDROP_TYPE, DWM_WINDOW_CORNER_PREFERENCE,
};
use windows_sys::Win32::Graphics::Gdi::{
ChangeDisplaySettingsExW, ClientToScreen, CreateRectRgn, DeleteObject, InvalidateRgn,
RedrawWindow, CDS_FULLSCREEN, DISP_CHANGE_BADFLAGS, DISP_CHANGE_BADMODE, DISP_CHANGE_BADPARAM,
DISP_CHANGE_FAILED, DISP_CHANGE_SUCCESSFUL, RDW_INTERNALPAINT,
};
use windows_sys::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
};
use windows_sys::Win32::System::Ole::{OleInitialize, RegisterDragDrop};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
EnableWindow, GetActiveWindow, MapVirtualKeyW, ReleaseCapture, SendInput, ToUnicode, INPUT,
INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC,
VIRTUAL_KEY, VK_LMENU, VK_MENU, VK_SPACE,
};
use windows_sys::Win32::UI::Input::Touch::{RegisterTouchWindow, TWF_WANTPALM};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, EnableMenuItem, FlashWindowEx, GetClientRect, GetCursorPos,
GetForegroundWindow, GetSystemMenu, GetSystemMetrics, GetWindowPlacement, GetWindowTextLengthW,
GetWindowTextW, IsWindowVisible, LoadCursorW, PeekMessageW, PostMessageW, RegisterClassExW,
SetCursor, SetCursorPos, SetForegroundWindow, SetMenuDefaultItem, SetWindowDisplayAffinity,
SetWindowPlacement, SetWindowPos, SetWindowTextW, TrackPopupMenu, CS_HREDRAW, CS_VREDRAW,
CW_USEDEFAULT, FLASHWINFO, FLASHW_ALL, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY,
GWLP_HINSTANCE, HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTLEFT, HTRIGHT, HTTOP,
HTTOPLEFT, HTTOPRIGHT, MENU_ITEM_STATE, MFS_DISABLED, MFS_ENABLED, MF_BYCOMMAND, NID_READY,
PM_NOREMOVE, SC_CLOSE, SC_MAXIMIZE, SC_MINIMIZE, SC_MOVE, SC_RESTORE, SC_SIZE, SM_DIGITIZER,
SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, TPM_LEFTALIGN, TPM_RETURNCMD,
WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_NCLBUTTONDOWN, WM_SYSCOMMAND, WNDCLASSEXW,
};
use crate::cursor::Cursor;
use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size};
use crate::error::{NotSupportedError, RequestError};
use crate::icon::Icon;
use crate::monitor::MonitorHandle as CoreMonitorHandle;
use crate::platform::windows::{BackdropType, Color, CornerPreference};
use crate::platform_impl::platform::dark_mode::try_theme;
use crate::platform_impl::platform::definitions::{
CLSID_TaskbarList, IID_ITaskbarList, IID_ITaskbarList2, ITaskbarList, ITaskbarList2,
};
use crate::platform_impl::platform::dpi::{
dpi_to_scale_factor, enable_non_client_dpi_scaling, hwnd_dpi,
};
use crate::platform_impl::platform::drop_handler::FileDropHandler;
use crate::platform_impl::platform::event_loop::{self, ActiveEventLoop, DESTROY_MSG_ID};
use crate::platform_impl::platform::icon::{self, IconType};
use crate::platform_impl::platform::ime::ImeContext;
use crate::platform_impl::platform::keyboard::KeyEventBuilder;
use crate::platform_impl::platform::window_state::{
CursorFlags, SavedWindow, WindowFlags, WindowState,
};
use crate::platform_impl::platform::{monitor, util, Fullscreen, SelectedCursor, WindowId};
use crate::window::{
CursorGrabMode, Fullscreen as CoreFullscreen, ImePurpose, ResizeDirection, Theme,
UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons,
WindowId as CoreWindowId, WindowLevel,
};
/// The Win32 implementation of the main `Window` object.
pub(crate) struct Window {
/// Main handle for the window.
window: HWND,
/// The current window state.
window_state: Arc<Mutex<WindowState>>,
// The events loop proxy.
thread_executor: event_loop::EventLoopThreadExecutor,
}
impl Window {
pub(crate) fn new(
event_loop: &ActiveEventLoop,
w_attr: WindowAttributes,
) -> Result<Window, RequestError> {
// We dispatch an `init` function because of code style.
// First person to remove the need for cloning here gets a cookie!
//
// done. you owe me -- ossi
unsafe { init(w_attr, event_loop) }
}
fn window_state_lock(&self) -> MutexGuard<'_, WindowState> {
self.window_state.lock().unwrap()
}
/// Returns the `hwnd` of this window.
pub fn hwnd(&self) -> HWND {
self.window
}
#[cfg(feature = "rwh_06")]
pub unsafe fn rwh_06_no_thread_check(
&self,
) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
let mut window_handle = rwh_06::Win32WindowHandle::new(unsafe {
// SAFETY: Handle will never be zero.
std::num::NonZeroIsize::new_unchecked(self.window)
});
let hinstance = unsafe { super::get_window_long(self.hwnd(), GWLP_HINSTANCE) };
window_handle.hinstance = std::num::NonZeroIsize::new(hinstance);
Ok(rwh_06::RawWindowHandle::Win32(window_handle))
}
#[cfg(feature = "rwh_06")]
pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
// TODO: Write a test once integration framework is ready to ensure that it holds.
// If we aren't in the GUI thread, we can't return the window.
if !self.thread_executor.in_event_loop_thread() {
tracing::error!("tried to access window handle outside of the main thread");
return Err(rwh_06::HandleError::Unavailable);
}
// SAFETY: We are on the correct thread.
unsafe { self.rwh_06_no_thread_check() }
}
#[cfg(feature = "rwh_06")]
pub fn raw_display_handle_rwh_06(
&self,
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
Ok(rwh_06::RawDisplayHandle::Windows(rwh_06::WindowsDisplayHandle::new()))
}
pub fn set_enable(&self, enabled: bool) {
unsafe { EnableWindow(self.hwnd(), enabled.into()) };
}
pub fn set_skip_taskbar(&self, skip: bool) {
self.window_state_lock().skip_taskbar = skip;
unsafe { set_skip_taskbar(self.hwnd(), skip) };
}
pub fn set_undecorated_shadow(&self, shadow: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MARKER_UNDECORATED_SHADOW, shadow)
});
});
}
pub fn set_system_backdrop(&self, backdrop_type: BackdropType) {
unsafe {
DwmSetWindowAttribute(
self.hwnd(),
DWMWA_SYSTEMBACKDROP_TYPE as u32,
&(backdrop_type as i32) as *const _ as _,
mem::size_of::<DWM_SYSTEMBACKDROP_TYPE>() as _,
);
}
}
pub fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
if let Some(ref taskbar_icon) = taskbar_icon {
taskbar_icon.inner.set_for_window(self.hwnd(), IconType::Big);
} else {
icon::unset_for_window(self.hwnd(), IconType::Big);
}
self.window_state_lock().taskbar_icon = taskbar_icon;
}
unsafe fn handle_os_dragging(&self, wparam: WPARAM) {
let window = self.window;
let window_state = self.window_state.clone();
self.thread_executor.execute_in_thread(move || {
{
let mut guard = window_state.lock().unwrap();
if !guard.dragging {
guard.dragging = true;
} else {
return;
}
}
let points = {
let mut pos = unsafe { mem::zeroed() };
unsafe { GetCursorPos(&mut pos) };
pos
};
let points = POINTS { x: points.x as i16, y: points.y as i16 };
// ReleaseCapture needs to execute on the main thread
unsafe { ReleaseCapture() };
unsafe {
PostMessageW(window, WM_NCLBUTTONDOWN, wparam, &points as *const _ as LPARAM)
};
});
}
unsafe fn handle_showing_window_menu(&self, position: Position) {
unsafe {
let point = {
let mut point = POINT { x: 0, y: 0 };
let scale_factor = self.scale_factor();
let (x, y) = position.to_physical::<i32>(scale_factor).into();
point.x = x;
point.y = y;
if ClientToScreen(self.hwnd(), &mut point) == false.into() {
warn!(
"Can't convert client-area coordinates to screen coordinates when showing \
window menu."
);
return;
}
point
};
// get the current system menu
let h_menu = GetSystemMenu(self.hwnd(), 0);
if h_menu == 0 {
warn!("The corresponding window doesn't have a system menu");
// This situation should not be treated as an error so just return without showing
// menu.
return;
}
fn enable(b: bool) -> MENU_ITEM_STATE {
if b {
MFS_ENABLED
} else {
MFS_DISABLED
}
}
// Change the menu items according to the current window status.
let restore_btn = enable(self.is_maximized() && self.is_resizable());
let size_btn = enable(!self.is_maximized() && self.is_resizable());
let maximize_btn = enable(!self.is_maximized() && self.is_resizable());
EnableMenuItem(h_menu, SC_RESTORE, MF_BYCOMMAND | restore_btn);
EnableMenuItem(h_menu, SC_MOVE, MF_BYCOMMAND | enable(!self.is_maximized()));
EnableMenuItem(h_menu, SC_SIZE, MF_BYCOMMAND | size_btn);
EnableMenuItem(h_menu, SC_MINIMIZE, MF_BYCOMMAND | MFS_ENABLED);
EnableMenuItem(h_menu, SC_MAXIMIZE, MF_BYCOMMAND | maximize_btn);
EnableMenuItem(h_menu, SC_CLOSE, MF_BYCOMMAND | MFS_ENABLED);
// Set the default menu item.
SetMenuDefaultItem(h_menu, SC_CLOSE, 0);
// Popup the system menu at the position.
let result = TrackPopupMenu(
h_menu,
TPM_RETURNCMD | TPM_LEFTALIGN, /* for now im using LTR, but we have to use user
* layout direction */
point.x,
point.y,
0,
self.hwnd(),
std::ptr::null_mut(),
);
if result == 0 {
// User canceled the menu, no need to continue.
return;
}
// Send the command that the user select to the corresponding window.
if PostMessageW(self.hwnd(), WM_SYSCOMMAND, result as _, 0) == 0 {
warn!("Can't post the system menu message to the window.");
}
}
}
#[inline]
pub fn set_border_color(&self, color: Color) {
unsafe {
DwmSetWindowAttribute(
self.hwnd(),
DWMWA_BORDER_COLOR as u32,
&color as *const _ as _,
mem::size_of::<Color>() as _,
);
}
}
#[inline]
pub fn set_title_background_color(&self, color: Color) {
unsafe {
DwmSetWindowAttribute(
self.hwnd(),
DWMWA_CAPTION_COLOR as u32,
&color as *const _ as _,
mem::size_of::<Color>() as _,
);
}
}
#[inline]
pub fn set_title_text_color(&self, color: Color) {
unsafe {
DwmSetWindowAttribute(
self.hwnd(),
DWMWA_TEXT_COLOR as u32,
&color as *const _ as _,
mem::size_of::<Color>() as _,
);
}
}
#[inline]
pub fn set_corner_preference(&self, preference: CornerPreference) {
unsafe {
DwmSetWindowAttribute(
self.hwnd(),
DWMWA_WINDOW_CORNER_PREFERENCE as u32,
&(preference as DWM_WINDOW_CORNER_PREFERENCE) as *const _ as _,
mem::size_of::<DWM_WINDOW_CORNER_PREFERENCE>() as _,
);
}
}
}
impl Drop for Window {
fn drop(&mut self) {
// Restore fullscreen video mode on exit.
if matches!(self.fullscreen(), Some(CoreFullscreen::Exclusive(_))) {
self.set_fullscreen(None);
}
unsafe {
// The window must be destroyed from the same thread that created it, so we send a
// custom message to be handled by our callback to do the actual work.
PostMessageW(self.hwnd(), DESTROY_MSG_ID.get(), 0, 0);
}
}
}
#[cfg(feature = "rwh_06")]
impl rwh_06::HasDisplayHandle for Window {
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
let raw = self.raw_display_handle_rwh_06()?;
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
}
}
#[cfg(feature = "rwh_06")]
impl rwh_06::HasWindowHandle for Window {
fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
let raw = self.raw_window_handle_rwh_06()?;
unsafe { Ok(rwh_06::WindowHandle::borrow_raw(raw)) }
}
}
impl CoreWindow for Window {
fn set_title(&self, text: &str) {
let wide_text = util::encode_wide(text);
unsafe {
SetWindowTextW(self.hwnd(), wide_text.as_ptr());
}
}
fn set_transparent(&self, transparent: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::TRANSPARENT, transparent)
});
});
}
fn set_blur(&self, _blur: bool) {}
fn set_visible(&self, visible: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::VISIBLE, visible)
});
});
}
fn is_visible(&self) -> Option<bool> {
Some(unsafe { IsWindowVisible(self.window) == 1 })
}
fn request_redraw(&self) {
// NOTE: mark that we requested a redraw to handle requests during `WM_PAINT` handling.
self.window_state.lock().unwrap().redraw_requested = true;
unsafe {
RedrawWindow(self.hwnd(), ptr::null(), 0, RDW_INTERNALPAINT);
}
}
fn pre_present_notify(&self) {}
fn outer_position(&self) -> Result<PhysicalPosition<i32>, RequestError> {
util::WindowArea::Outer
.get_rect(self.hwnd())
.map(|rect| Ok(PhysicalPosition::new(rect.left, rect.top)))
.expect(
"Unexpected GetWindowRect failure; please report this error to \
rust-windowing/winit",
)
}
fn inner_position(&self) -> Result<PhysicalPosition<i32>, RequestError> {
let mut position: POINT = unsafe { mem::zeroed() };
if unsafe { ClientToScreen(self.hwnd(), &mut position) } == false.into() {
panic!(
"Unexpected ClientToScreen failure: please report this error to \
rust-windowing/winit"
)
}
Ok(PhysicalPosition::new(position.x, position.y))
}
fn set_outer_position(&self, position: Position) {
let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into();
let window_state = Arc::clone(&self.window_state);
let window = self.window;
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MAXIMIZED, false)
});
});
unsafe {
SetWindowPos(
self.hwnd(),
0,
x,
y,
0,
0,
SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE,
);
InvalidateRgn(self.hwnd(), 0, false.into());
}
}
fn surface_size(&self) -> PhysicalSize<u32> {
let mut rect: RECT = unsafe { mem::zeroed() };
if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() {
panic!(
"Unexpected GetClientRect failure: please report this error to \
rust-windowing/winit"
)
}
PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32)
}
fn outer_size(&self) -> PhysicalSize<u32> {
util::WindowArea::Outer
.get_rect(self.hwnd())
.map(|rect| {
PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32)
})
.unwrap()
}
fn request_surface_size(&self, size: Size) -> Option<PhysicalSize<u32>> {
let scale_factor = self.scale_factor();
let physical_size = size.to_physical::<u32>(scale_factor);
let window_flags = self.window_state_lock().window_flags;
window_flags.set_size(self.hwnd(), physical_size);
if physical_size != self.surface_size() {
let window_state = Arc::clone(&self.window_state);
let window = self.window;
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MAXIMIZED, false)
});
});
}
None
}
fn set_min_surface_size(&self, size: Option<Size>) {
self.window_state_lock().min_size = size;
// Make windows re-check the window size bounds.
let size = self.surface_size();
let _ = self.request_surface_size(size.into());
}
fn set_max_surface_size(&self, size: Option<Size>) {
self.window_state_lock().max_size = size;
// Make windows re-check the window size bounds.
let size = self.surface_size();
let _ = self.request_surface_size(size.into());
}
fn surface_resize_increments(&self) -> Option<PhysicalSize<u32>> {
let w = self.window_state_lock();
let scale_factor = w.scale_factor;
w.surface_resize_increments.map(|size| size.to_physical(scale_factor))
}
fn set_surface_resize_increments(&self, increments: Option<Size>) {
self.window_state_lock().surface_resize_increments = increments;
}
fn set_resizable(&self, resizable: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::RESIZABLE, resizable)
});
});
}
fn is_resizable(&self) -> bool {
let window_state = self.window_state_lock();
window_state.window_flags.contains(WindowFlags::RESIZABLE)
}
fn set_enabled_buttons(&self, buttons: WindowButtons) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MINIMIZABLE, buttons.contains(WindowButtons::MINIMIZE));
f.set(WindowFlags::MAXIMIZABLE, buttons.contains(WindowButtons::MAXIMIZE));
f.set(WindowFlags::CLOSABLE, buttons.contains(WindowButtons::CLOSE))
});
});
}
fn enabled_buttons(&self) -> WindowButtons {
let mut buttons = WindowButtons::empty();
let window_state = self.window_state_lock();
if window_state.window_flags.contains(WindowFlags::MINIMIZABLE) {
buttons |= WindowButtons::MINIMIZE;
}
if window_state.window_flags.contains(WindowFlags::MAXIMIZABLE) {
buttons |= WindowButtons::MAXIMIZE;
}
if window_state.window_flags.contains(WindowFlags::CLOSABLE) {
buttons |= WindowButtons::CLOSE;
}
buttons
}
fn set_cursor(&self, cursor: Cursor) {
match cursor {
Cursor::Icon(icon) => {
self.window_state_lock().mouse.selected_cursor = SelectedCursor::Named(icon);
self.thread_executor.execute_in_thread(move || unsafe {
let cursor = LoadCursorW(0, util::to_windows_cursor(icon));
SetCursor(cursor);
});
},
Cursor::Custom(cursor) => {
self.window_state_lock().mouse.selected_cursor =
SelectedCursor::Custom(cursor.inner.0.clone());
self.thread_executor.execute_in_thread(move || unsafe {
SetCursor(cursor.inner.0.as_raw_handle());
});
},
}
}
fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> {
let confine = match mode {
CursorGrabMode::None => false,
CursorGrabMode::Confined => true,
CursorGrabMode::Locked => {
return Err(NotSupportedError::new("locked cursor is not supported").into())
},
};
let window = self.window;
let window_state = Arc::clone(&self.window_state);
let (tx, rx) = channel();
self.thread_executor.execute_in_thread(move || {
let _ = &window;
let result = window_state
.lock()
.unwrap()
.mouse
.set_cursor_flags(window, |f| f.set(CursorFlags::GRABBED, confine))
.map_err(|err| os_error!(err).into());
let _ = tx.send(result);
});
rx.recv().unwrap()
}
fn set_cursor_visible(&self, visible: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
let (tx, rx) = channel();
self.thread_executor.execute_in_thread(move || {
let _ = &window;
let result = window_state
.lock()
.unwrap()
.mouse
.set_cursor_flags(window, |f| f.set(CursorFlags::HIDDEN, !visible))
.map_err(|e| e.to_string());
let _ = tx.send(result);
});
rx.recv().unwrap().ok();
}
fn scale_factor(&self) -> f64 {
self.window_state_lock().scale_factor
}
fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> {
let scale_factor = self.scale_factor();
let (x, y) = position.to_physical::<i32>(scale_factor).into();
let mut point = POINT { x, y };
unsafe {
if ClientToScreen(self.hwnd(), &mut point) == false.into() {
return Err(os_error!(io::Error::last_os_error()).into());
}
if SetCursorPos(point.x, point.y) == false.into() {
return Err(os_error!(io::Error::last_os_error()).into());
}
}
Ok(())
}
fn drag_window(&self) -> Result<(), RequestError> {
unsafe {
self.handle_os_dragging(HTCAPTION as WPARAM);
}
Ok(())
}
fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), RequestError> {
unsafe {
self.handle_os_dragging(match direction {
ResizeDirection::East => HTRIGHT,
ResizeDirection::North => HTTOP,
ResizeDirection::NorthEast => HTTOPRIGHT,
ResizeDirection::NorthWest => HTTOPLEFT,
ResizeDirection::South => HTBOTTOM,
ResizeDirection::SouthEast => HTBOTTOMRIGHT,
ResizeDirection::SouthWest => HTBOTTOMLEFT,
ResizeDirection::West => HTLEFT,
} as WPARAM);
}
Ok(())
}
fn show_window_menu(&self, position: Position) {
unsafe {
self.handle_showing_window_menu(position);
}
}
fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::IGNORE_CURSOR_EVENT, !hittest)
});
});
Ok(())
}
fn id(&self) -> CoreWindowId {
CoreWindowId(WindowId(self.hwnd()))
}
fn set_minimized(&self, minimized: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
let is_minimized = util::is_minimized(self.hwnd());
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags_in_place(&mut window_state.lock().unwrap(), |f| {
f.set(WindowFlags::MINIMIZED, is_minimized)
});
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MINIMIZED, minimized)
});
});
}
fn is_minimized(&self) -> Option<bool> {
Some(util::is_minimized(self.hwnd()))
}
fn set_maximized(&self, maximized: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MAXIMIZED, maximized)
});
});
}
fn is_maximized(&self) -> bool {
let window_state = self.window_state_lock();
window_state.window_flags.contains(WindowFlags::MAXIMIZED)
}
fn fullscreen(&self) -> Option<CoreFullscreen> {
let window_state = self.window_state_lock();
window_state.fullscreen.clone().map(Into::into)
}
fn set_fullscreen(&self, fullscreen: Option<CoreFullscreen>) {
let fullscreen = fullscreen.map(Into::into);
let window = self.window;
let window_state = Arc::clone(&self.window_state);
let mut window_state_lock = window_state.lock().unwrap();
let old_fullscreen = window_state_lock.fullscreen.clone();
match (&old_fullscreen, &fullscreen) {
// Return if we already are in the same fullscreen mode
_ if old_fullscreen == fullscreen => return,
// Return if saved Borderless(monitor) is the same as current monitor when requested
// fullscreen is Borderless(None)
(Some(Fullscreen::Borderless(Some(monitor))), Some(Fullscreen::Borderless(None)))
if *monitor == monitor::current_monitor(window) =>
{
return
},
_ => {},
}
window_state_lock.fullscreen.clone_from(&fullscreen);
drop(window_state_lock);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
// Change video mode if we're transitioning to or from exclusive
// fullscreen
match (&old_fullscreen, &fullscreen) {
(_, Some(Fullscreen::Exclusive(video_mode))) => {
let monitor = video_mode.monitor();
let monitor_info = monitor::get_monitor_info(monitor.hmonitor()).unwrap();
let res = unsafe {
ChangeDisplaySettingsExW(
monitor_info.szDevice.as_ptr(),
&*video_mode.native_video_mode,
0,
CDS_FULLSCREEN,
ptr::null(),
)
};
debug_assert!(res != DISP_CHANGE_BADFLAGS);
debug_assert!(res != DISP_CHANGE_BADMODE);
debug_assert!(res != DISP_CHANGE_BADPARAM);
debug_assert!(res != DISP_CHANGE_FAILED);
assert_eq!(res, DISP_CHANGE_SUCCESSFUL);
},
(Some(Fullscreen::Exclusive(_)), _) => {
let res = unsafe {
ChangeDisplaySettingsExW(
ptr::null(),
ptr::null(),
0,
CDS_FULLSCREEN,
ptr::null(),
)
};
debug_assert!(res != DISP_CHANGE_BADFLAGS);
debug_assert!(res != DISP_CHANGE_BADMODE);
debug_assert!(res != DISP_CHANGE_BADPARAM);
debug_assert!(res != DISP_CHANGE_FAILED);
assert_eq!(res, DISP_CHANGE_SUCCESSFUL);
},
_ => (),
}
unsafe {
// There are some scenarios where calling `ChangeDisplaySettingsExW` takes long
// enough to execute that the DWM thinks our program has frozen and takes over
// our program's window. When that happens, the `SetWindowPos` call below gets
// eaten and the window doesn't get set to the proper fullscreen position.
//
// Calling `PeekMessageW` here notifies Windows that our process is still running
// fine, taking control back from the DWM and ensuring that the `SetWindowPos` call
// below goes through.
let mut msg = mem::zeroed();
PeekMessageW(&mut msg, 0, 0, 0, PM_NOREMOVE);
}
// Update window style
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(
WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN,
matches!(fullscreen, Some(Fullscreen::Exclusive(_))),
);
f.set(
WindowFlags::MARKER_BORDERLESS_FULLSCREEN,
matches!(fullscreen, Some(Fullscreen::Borderless(_))),
);
});
// Mark as fullscreen window wrt to z-order
//
// this needs to be called before the below fullscreen SetWindowPos as this itself
// will generate WM_SIZE messages of the old window size that can race with what we set
// below
unsafe {
taskbar_mark_fullscreen(window, fullscreen.is_some());
}
// Update window bounds
match &fullscreen {
Some(fullscreen) => {
// Save window bounds before entering fullscreen
let placement = unsafe {
let mut placement = mem::zeroed();
GetWindowPlacement(window, &mut placement);
placement
};
window_state.lock().unwrap().saved_window = Some(SavedWindow { placement });
let monitor = match &fullscreen {
Fullscreen::Exclusive(video_mode) => video_mode.monitor(),
Fullscreen::Borderless(Some(monitor)) => monitor.clone(),
Fullscreen::Borderless(None) => monitor::current_monitor(window),
};
let position: (i32, i32) = monitor.position().unwrap_or_default().into();
let size: (u32, u32) = monitor.size().into();
unsafe {
SetWindowPos(
window,
0,
position.0,
position.1,
size.0 as i32,
size.1 as i32,
SWP_ASYNCWINDOWPOS | SWP_NOZORDER,
);
InvalidateRgn(window, 0, false.into());
}
},
None => {
let mut window_state_lock = window_state.lock().unwrap();
if let Some(SavedWindow { placement }) = window_state_lock.saved_window.take() {
drop(window_state_lock);
unsafe {
SetWindowPlacement(window, &placement);
InvalidateRgn(window, 0, false.into());
}
}
},
}
});
}
fn set_decorations(&self, decorations: bool) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::MARKER_DECORATIONS, decorations)
});
});
}
fn is_decorated(&self) -> bool {
let window_state = self.window_state_lock();
window_state.window_flags.contains(WindowFlags::MARKER_DECORATIONS)
}
fn set_window_level(&self, level: WindowLevel) {
let window = self.window;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
let _ = &window;
WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| {
f.set(WindowFlags::ALWAYS_ON_TOP, level == WindowLevel::AlwaysOnTop);
f.set(WindowFlags::ALWAYS_ON_BOTTOM, level == WindowLevel::AlwaysOnBottom);
});
});
}
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
Some(CoreMonitorHandle { inner: monitor::current_monitor(self.hwnd()) })
}
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
Box::new(monitor::available_monitors().into_iter().map(|inner| CoreMonitorHandle { inner }))
}
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
Some(CoreMonitorHandle { inner: monitor::primary_monitor() })
}
fn set_window_icon(&self, window_icon: Option<Icon>) {
if let Some(ref window_icon) = window_icon {
window_icon.inner.set_for_window(self.hwnd(), IconType::Small);
} else {
icon::unset_for_window(self.hwnd(), IconType::Small);
}
self.window_state_lock().window_icon = window_icon;
}
fn set_ime_cursor_area(&self, spot: Position, size: Size) {
let window = self.window;
let state = self.window_state.clone();
self.thread_executor.execute_in_thread(move || unsafe {
let scale_factor = state.lock().unwrap().scale_factor;
ImeContext::current(window).set_ime_cursor_area(spot, size, scale_factor);
});
}
fn set_ime_allowed(&self, allowed: bool) {
let window = self.window;
let state = self.window_state.clone();
self.thread_executor.execute_in_thread(move || unsafe {
state.lock().unwrap().ime_allowed = allowed;
ImeContext::set_ime_allowed(window, allowed);
})
}
fn set_ime_purpose(&self, _purpose: ImePurpose) {}
fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
let window = self.window;
let active_window_handle = unsafe { GetActiveWindow() };
if window == active_window_handle {
return;
}
self.thread_executor.execute_in_thread(move || unsafe {
let (flags, count) = request_type
.map(|ty| match ty {
UserAttentionType::Critical => (FLASHW_ALL | FLASHW_TIMERNOFG, u32::MAX),
UserAttentionType::Informational => (FLASHW_TRAY | FLASHW_TIMERNOFG, 0),
})
.unwrap_or((FLASHW_STOP, 0));
let flash_info = FLASHWINFO {
cbSize: mem::size_of::<FLASHWINFO>() as u32,
hwnd: window,
dwFlags: flags,
uCount: count,
dwTimeout: 0,
};
FlashWindowEx(&flash_info);
});
}
fn set_theme(&self, theme: Option<Theme>) {
try_theme(self.window, theme);
}
fn theme(&self) -> Option<Theme> {
Some(self.window_state_lock().current_theme)
}