-
-
Notifications
You must be signed in to change notification settings - Fork 188
/
window.rs
1426 lines (1237 loc) · 44.4 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
// Copyright 2014-2021 The winit contributors
// Copyright 2021-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
#![cfg(target_os = "windows")]
use mem::MaybeUninit;
use parking_lot::Mutex;
use std::{
cell::{Cell, RefCell},
ffi::OsStr,
io, mem,
os::windows::ffi::OsStrExt,
sync::Arc,
};
use crossbeam_channel as channel;
use windows::{
core::PCWSTR,
Win32::{
Foundation::{
self as win32f, HINSTANCE, HMODULE, HWND, LPARAM, LRESULT, POINT, POINTS, RECT, WPARAM,
},
Graphics::{
Dwm::{DwmEnableBlurBehindWindow, DWM_BB_BLURREGION, DWM_BB_ENABLE, DWM_BLURBEHIND},
Gdi::*,
},
System::{Com::*, LibraryLoader::*, Ole::*},
UI::{
Input::{Ime::*, KeyboardAndMouse::*, Touch::*},
Shell::{ITaskbarList4 as ITaskbarList, TaskbarList, *},
WindowsAndMessaging::{self as win32wm, *},
},
},
};
use crate::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
error::{ExternalError, NotSupportedError, OsError as RootOsError},
icon::Icon,
monitor::MonitorHandle as RootMonitorHandle,
platform_impl::platform::{
dark_mode::try_window_theme,
dpi::{dpi_to_scale_factor, hwnd_dpi},
drop_handler::FileDropHandler,
event_loop::{self, EventLoopWindowTarget, DESTROY_MSG_ID},
icon::{self, IconType},
monitor, util,
window_state::{CursorFlags, SavedWindow, WindowFlags, WindowState},
OsError, Parent, PlatformSpecificWindowBuilderAttributes, WindowId,
},
window::{
CursorIcon, Fullscreen, ProgressBarState, ProgressState, ResizeDirection, Theme,
UserAttentionType, WindowAttributes, WindowSizeConstraints,
},
};
use super::{
event_loop::CHANGE_THEME_MSG_ID,
keyboard::{KeyEventBuilder, KEY_EVENT_BUILDERS},
};
/// A simple non-owning wrapper around a window.
#[derive(Clone, Copy)]
pub struct WindowWrapper(pub HWND);
// Send and Sync are not implemented for HWND and HDC, we have to wrap it and implement them manually.
// For more info see:
// https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Sync for WindowWrapper {}
unsafe impl Send for WindowWrapper {}
/// The Win32 implementation of the main `Window` object.
pub struct Window {
/// Main handle for the window.
window: WindowWrapper,
/// The current window state.
window_state: Arc<Mutex<WindowState>>,
// The events loop proxy.
thread_executor: event_loop::EventLoopThreadExecutor,
}
impl Window {
pub fn new<T: 'static>(
event_loop: &EventLoopWindowTarget<T>,
w_attr: WindowAttributes,
pl_attr: PlatformSpecificWindowBuilderAttributes,
) -> Result<Window, RootOsError> {
// 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 {
let drag_and_drop = pl_attr.drag_and_drop;
init(w_attr, pl_attr, event_loop).map(|win| {
let file_drop_handler = if drag_and_drop {
// It is ok if the initialize result is `S_FALSE` because it might happen that
// multiple windows are created on the same thread.
if let Err(error) = OleInitialize(None) {
match error.code() {
win32f::OLE_E_WRONGCOMPOBJ => {
panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`")
}
win32f::RPC_E_CHANGED_MODE => panic!(
"OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`. \
Make sure other crates are not using multithreaded COM library \
on the same thread or disable drag and drop support."
),
_ => (),
};
}
let file_drop_runner = event_loop.runner_shared.clone();
let file_drop_handler: IDropTarget = FileDropHandler::new(
win.window.0,
Box::new(move |event| {
if let Ok(e) = event.map_nonuser_event() {
file_drop_runner.send_event(e)
}
}),
)
.into();
assert!(RegisterDragDrop(win.window.0, &file_drop_handler).is_ok());
Some(file_drop_handler)
} else {
None
};
let subclass_input = event_loop::SubclassInput {
window_state: win.window_state.clone(),
event_loop_runner: event_loop.runner_shared.clone(),
_file_drop_handler: file_drop_handler,
subclass_removed: Cell::new(false),
recurse_depth: Cell::new(0),
event_loop_preferred_theme: event_loop.preferred_theme.clone(),
};
event_loop::subclass_window(win.window.0, subclass_input);
win
})
}
}
pub fn set_title(&self, text: &str) {
let text = util::encode_wide(text);
unsafe {
let _ = SetWindowTextW(self.window.0, PCWSTR::from_raw(text.as_ptr()));
}
}
pub fn title(&self) -> String {
let len = unsafe { GetWindowTextLengthW(self.window.0) };
let mut buf = vec![0; (len + 1) as usize];
unsafe { GetWindowTextW(self.window.0, &mut buf) };
String::from_utf16_lossy(&buf[..len as _])
}
#[inline]
pub fn set_visible(&self, visible: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::VISIBLE, visible)
});
});
}
#[inline]
pub fn set_focus(&self) {
let window = self.window.clone();
let window_flags = self.window_state.lock().window_flags();
let is_visible = window_flags.contains(WindowFlags::VISIBLE);
let is_minimized = window_flags.contains(WindowFlags::MINIMIZED);
let is_foreground = window.0 == unsafe { GetForegroundWindow() };
if is_visible && !is_minimized && !is_foreground {
unsafe { force_window_active(window.0) };
}
}
#[inline]
pub fn is_focused(&self) -> bool {
let window_state = self.window_state.lock();
window_state.has_active_focus()
}
#[inline]
pub fn request_redraw(&self) {
unsafe {
let _ = RedrawWindow(self.window.0, None, HRGN::default(), RDW_INTERNALPAINT);
}
}
#[inline]
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
unsafe { util::get_window_rect(self.window.0) }
.map(|rect| Ok(PhysicalPosition::new(rect.left, rect.top)))
.expect("Unexpected GetWindowRect failure")
}
#[inline]
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
let mut position = POINT::default();
if !unsafe { ClientToScreen(self.window.0, &mut position) }.as_bool() {
panic!("Unexpected ClientToScreen failure")
}
Ok(PhysicalPosition::new(position.x, position.y))
}
#[inline]
pub 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.0 .0 as isize;
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MAXIMIZED, false)
});
});
unsafe {
let _ = SetWindowPos(
self.window.0,
HWND::default(),
x,
y,
0,
0,
SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE,
);
let _ = InvalidateRgn(self.window.0, HRGN::default(), false);
}
}
#[inline]
pub fn inner_size(&self) -> PhysicalSize<u32> {
let mut rect = RECT::default();
if unsafe { GetClientRect(self.window.0, &mut rect) }.is_err() {
panic!("Unexpected GetClientRect failure")
}
PhysicalSize::new(
(rect.right - rect.left) as u32,
(rect.bottom - rect.top) as u32,
)
}
#[inline]
pub fn outer_size(&self) -> PhysicalSize<u32> {
unsafe { util::get_window_rect(self.window.0) }
.map(|rect| {
PhysicalSize::new(
(rect.right - rect.left) as u32,
(rect.bottom - rect.top) as u32,
)
})
.unwrap()
}
#[inline]
pub fn set_inner_size(&self, size: Size) {
let scale_factor = self.scale_factor();
let (width, height) = size.to_physical::<u32>(scale_factor).into();
let window_state = Arc::clone(&self.window_state);
let is_decorated = window_state
.lock()
.window_flags
.contains(WindowFlags::MARKER_DECORATIONS);
let window = self.window.0 .0 as isize;
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MAXIMIZED, false)
});
});
util::set_inner_size_physical(self.window.0, width, height, is_decorated);
}
#[inline]
pub fn set_min_inner_size(&self, size: Option<Size>) {
let (width, height) = size.map(crate::extract_width_height).unzip();
{
let mut window_state = self.window_state.lock();
window_state.size_constraints.min_width = width;
window_state.size_constraints.min_height = height;
}
// Make windows re-check the window size bounds.
let size = self.inner_size();
self.set_inner_size(size.into());
}
#[inline]
pub fn set_max_inner_size(&self, size: Option<Size>) {
let (width, height) = size.map(crate::extract_width_height).unzip();
{
let mut window_state = self.window_state.lock();
window_state.size_constraints.max_width = width;
window_state.size_constraints.max_height = height;
}
// Make windows re-check the window size bounds.
let size = self.inner_size();
self.set_inner_size(size.into());
}
#[inline]
pub fn set_inner_size_constraints(&self, constraints: WindowSizeConstraints) {
self.window_state.lock().size_constraints = constraints;
// Make windows re-check the window size bounds.
let size = self.inner_size();
self.set_inner_size(size.into());
}
#[inline]
pub fn set_resizable(&self, resizable: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::RESIZABLE, resizable)
});
});
}
#[inline]
pub fn set_minimizable(&self, minimizable: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MINIMIZABLE, minimizable)
});
});
}
#[inline]
pub fn set_maximizable(&self, maximizable: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MAXIMIZABLE, maximizable)
});
});
}
#[inline]
pub fn set_closable(&self, closable: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::CLOSABLE, closable)
});
});
}
/// Returns the `hwnd` of this window.
#[inline]
pub fn hwnd(&self) -> HWND {
self.window.0
}
#[inline]
pub fn hinstance(&self) -> HMODULE {
util::get_instance_handle()
}
#[cfg(feature = "rwh_04")]
#[inline]
pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
let mut window_handle = rwh_04::Win32Handle::empty();
window_handle.hwnd = self.window.0 .0 as *mut _;
let hinstance = util::GetWindowLongPtrW(self.hwnd(), GWLP_HINSTANCE);
window_handle.hinstance = hinstance as *mut _;
rwh_04::RawWindowHandle::Win32(window_handle)
}
#[cfg(feature = "rwh_05")]
#[inline]
pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
let mut window_handle = rwh_05::Win32WindowHandle::empty();
window_handle.hwnd = self.window.0 .0 as *mut _;
let hinstance = util::GetWindowLongPtrW(self.hwnd(), GWLP_HINSTANCE);
window_handle.hinstance = hinstance as *mut _;
rwh_05::RawWindowHandle::Win32(window_handle)
}
#[cfg(feature = "rwh_05")]
#[inline]
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
rwh_05::RawDisplayHandle::Windows(rwh_05::WindowsDisplayHandle::empty())
}
#[cfg(feature = "rwh_06")]
#[inline]
pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
let mut window_handle = rwh_06::Win32WindowHandle::new(unsafe {
// SAFETY: Handle will never be zero.
let window = self.window.0 .0;
std::num::NonZeroIsize::new_unchecked(window as _)
});
let hinstance = util::GetWindowLongPtrW(self.hwnd(), GWLP_HINSTANCE);
window_handle.hinstance = std::num::NonZeroIsize::new(hinstance);
Ok(rwh_06::RawWindowHandle::Win32(window_handle))
}
#[cfg(feature = "rwh_06")]
#[inline]
pub fn raw_display_handle_rwh_06(&self) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
Ok(rwh_06::RawDisplayHandle::Windows(
rwh_06::WindowsDisplayHandle::new(),
))
}
#[inline]
pub fn set_cursor_icon(&self, cursor: CursorIcon) {
self.window_state.lock().mouse.cursor = cursor;
self.thread_executor.execute_in_thread(move || unsafe {
let cursor = LoadCursorW(HMODULE::default(), cursor.to_windows_cursor()).unwrap_or_default();
SetCursor(cursor);
});
}
#[inline]
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
let (tx, rx) = channel::unbounded();
self.thread_executor.execute_in_thread(move || {
let result = window_state
.lock()
.mouse
.set_cursor_flags(HWND(window as _), |f| f.set(CursorFlags::GRABBED, grab))
.map_err(|e| ExternalError::Os(os_error!(OsError::IoError(e))));
let _ = tx.send(result);
});
rx.recv().unwrap()
}
#[inline]
pub fn set_cursor_visible(&self, visible: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
let (tx, rx) = channel::unbounded();
self.thread_executor.execute_in_thread(move || {
let result = window_state
.lock()
.mouse
.set_cursor_flags(HWND(window as _), |f| f.set(CursorFlags::HIDDEN, !visible))
.map_err(|e| e.to_string());
let _ = tx.send(result);
});
rx.recv().unwrap().ok();
}
#[inline]
pub fn cursor_position(&self) -> Result<PhysicalPosition<f64>, ExternalError> {
util::cursor_position().map_err(Into::into)
}
#[inline]
pub fn scale_factor(&self) -> f64 {
self.window_state.lock().scale_factor
}
#[inline]
pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
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.window.0, &mut point).as_bool() {
return Err(ExternalError::Os(os_error!(OsError::IoError(
io::Error::last_os_error()
))));
}
SetCursorPos(point.x, point.y)
.map_err(|e| ExternalError::Os(os_error!(OsError::IoError(e.into()))))
}
}
fn handle_os_dragging(&self, wparam: WPARAM) -> Result<(), ExternalError> {
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,
};
unsafe { ReleaseCapture()? };
self.window_state.lock().dragging = true;
unsafe {
PostMessageW(
self.hwnd(),
WM_NCLBUTTONDOWN,
wparam,
LPARAM(&points as *const _ as _),
)?
};
Ok(())
}
#[inline]
pub fn drag_window(&self) -> Result<(), ExternalError> {
self.handle_os_dragging(WPARAM(HTCAPTION as _))
}
#[inline]
pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
self.handle_os_dragging(WPARAM(direction.to_win32() as _))
}
#[inline]
pub fn set_ignore_cursor_events(&self, ignore: bool) -> Result<(), ExternalError> {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::IGNORE_CURSOR_EVENT, ignore)
});
});
Ok(())
}
#[inline]
pub fn id(&self) -> WindowId {
WindowId(self.window.0 .0 as _)
}
#[inline]
pub fn set_minimized(&self, minimized: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
let is_minimized = self.is_minimized();
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags_in_place(&mut window_state.lock(), |f| {
f.set(WindowFlags::MINIMIZED, is_minimized)
});
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MINIMIZED, minimized)
});
});
}
#[inline]
pub fn set_maximized(&self, maximized: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MAXIMIZED, maximized)
});
});
}
#[inline]
pub fn is_maximized(&self) -> bool {
let window_state = self.window_state.lock();
window_state.window_flags.contains(WindowFlags::MAXIMIZED)
}
#[inline]
pub fn is_always_on_top(&self) -> bool {
let window_state = self.window_state.lock();
window_state
.window_flags
.contains(WindowFlags::ALWAYS_ON_TOP)
}
#[inline]
pub fn is_minimized(&self) -> bool {
unsafe { IsIconic(self.hwnd()) }.as_bool()
}
#[inline]
pub fn is_resizable(&self) -> bool {
let window_state = self.window_state.lock();
window_state.window_flags.contains(WindowFlags::RESIZABLE)
}
#[inline]
pub fn is_minimizable(&self) -> bool {
let window_state = self.window_state.lock();
window_state.window_flags.contains(WindowFlags::MINIMIZABLE)
}
#[inline]
pub fn is_maximizable(&self) -> bool {
let window_state = self.window_state.lock();
window_state.window_flags.contains(WindowFlags::MAXIMIZABLE)
}
#[inline]
pub fn is_closable(&self) -> bool {
let window_state = self.window_state.lock();
window_state.window_flags.contains(WindowFlags::CLOSABLE)
}
#[inline]
pub fn is_decorated(&self) -> bool {
let window_state = self.window_state.lock();
window_state
.window_flags
.contains(WindowFlags::MARKER_DECORATIONS)
}
#[inline]
pub fn is_visible(&self) -> bool {
util::is_visible(self.window.0)
}
#[inline]
pub fn fullscreen(&self) -> Option<Fullscreen> {
let window_state = self.window_state.lock();
window_state.fullscreen.clone()
}
#[inline]
pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
let window = self.window.clone();
let window_state = Arc::clone(&self.window_state);
let mut window_state_lock = window_state.lock();
let old_fullscreen = window_state_lock.fullscreen.clone();
match (&old_fullscreen, &fullscreen) {
// Return if we already 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.inner == monitor::current_monitor(window.0) =>
{
return
}
_ => {}
}
window_state_lock.fullscreen = fullscreen.clone();
drop(window_state_lock);
let window_isize = window.0 .0 as isize;
self.thread_executor.execute_in_thread(move || {
let hwnd = HWND(window_isize as _);
// Change video mode if we're transitioning to or from exclusive
// fullscreen
match (&old_fullscreen, &fullscreen) {
(&None, &Some(Fullscreen::Exclusive(ref video_mode)))
| (&Some(Fullscreen::Borderless(_)), &Some(Fullscreen::Exclusive(ref video_mode)))
| (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Exclusive(ref video_mode))) => {
let monitor = video_mode.monitor();
let mut display_name = OsStr::new(&monitor.inner.native_identifier())
.encode_wide()
.collect::<Vec<_>>();
// `encode_wide` does not add a null-terminator but
// `ChangeDisplaySettingsExW` requires a null-terminated
// string, so add it
display_name.push(0);
let native_video_mode = video_mode.video_mode.native_video_mode;
let res = unsafe {
ChangeDisplaySettingsExW(
PCWSTR::from_raw(display_name.as_ptr()),
Some(&native_video_mode),
HWND::default(),
CDS_FULLSCREEN,
None,
)
};
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(_)), &None)
| (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Borderless(_))) => {
let res = unsafe {
ChangeDisplaySettingsExW(PCWSTR::null(), None, HWND::default(), CDS_FULLSCREEN, None)
};
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 = MSG::default();
let _ = PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_NOREMOVE);
}
// Update window style
WindowState::set_window_flags(window_state.lock(), HWND(window_isize as _), |f| {
f.set(
WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN,
matches!(fullscreen, Some(Fullscreen::Exclusive(_))),
);
f.set(
WindowFlags::MARKER_BORDERLESS_FULLSCREEN,
matches!(fullscreen, Some(Fullscreen::Borderless(_))),
);
});
// Update window bounds
match &fullscreen {
Some(fullscreen) => {
// Save window bounds before entering fullscreen
let placement = unsafe {
let mut placement = WINDOWPLACEMENT::default();
let _ = GetWindowPlacement(hwnd, &mut placement);
placement
};
window_state.lock().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) => RootMonitorHandle {
inner: monitor::current_monitor(hwnd),
},
};
let position: (i32, i32) = monitor.position().into();
let size: (u32, u32) = monitor.size().into();
unsafe {
let _ = SetWindowPos(
hwnd,
HWND::default(),
position.0,
position.1,
size.0 as i32,
size.1 as i32,
SWP_ASYNCWINDOWPOS | SWP_NOZORDER,
);
let _ = InvalidateRgn(hwnd, HRGN::default(), false);
}
}
None => {
let mut window_state_lock = window_state.lock();
if let Some(SavedWindow { placement }) = window_state_lock.saved_window.take() {
drop(window_state_lock);
unsafe {
let _ = SetWindowPlacement(hwnd, &placement);
let _ = InvalidateRgn(hwnd, HRGN::default(), false);
}
}
}
}
unsafe {
taskbar_mark_fullscreen(hwnd, fullscreen.is_some());
}
});
}
#[inline]
pub fn set_decorations(&self, decorations: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::MARKER_DECORATIONS, decorations)
});
});
}
#[inline]
pub fn set_always_on_bottom(&self, always_on_bottom: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::ALWAYS_ON_BOTTOM, always_on_bottom)
});
});
}
#[inline]
pub fn set_always_on_top(&self, always_on_top: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::ALWAYS_ON_TOP, always_on_top)
});
});
}
pub fn set_rtl(&self, rtl: bool) {
let window = self.window.0 .0 as isize;
let window_state = Arc::clone(&self.window_state);
self.thread_executor.execute_in_thread(move || {
WindowState::set_window_flags(window_state.lock(), HWND(window as _), |f| {
f.set(WindowFlags::RIGHT_TO_LEFT_LAYOUT, rtl)
});
});
}
#[inline]
pub fn current_monitor(&self) -> Option<RootMonitorHandle> {
Some(RootMonitorHandle {
inner: monitor::current_monitor(self.window.0),
})
}
#[inline]
pub fn set_window_icon(&self, window_icon: Option<Icon>) {
if let Some(ref window_icon) = window_icon {
window_icon
.inner
.set_for_window(self.window.0, IconType::Small);
} else {
icon::unset_for_window(self.window.0, IconType::Small);
}
self.window_state.lock().window_icon = window_icon;
}
#[inline]
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.window.0, IconType::Big);
} else {
icon::unset_for_window(self.window.0, IconType::Big);
}
self.window_state.lock().taskbar_icon = taskbar_icon;
}
pub(crate) fn set_ime_position_physical(&self, x: i32, y: i32) {
if unsafe { GetSystemMetrics(SM_IMMENABLED) } != 0 {
let composition_form = COMPOSITIONFORM {
dwStyle: CFS_POINT,
ptCurrentPos: POINT { x, y },
rcArea: RECT::default(),
};
unsafe {
let himc = ImmGetContext(self.window.0);
let _ = ImmSetCompositionWindow(himc, &composition_form);
let _ = ImmReleaseContext(self.window.0, himc);
}
}
}
#[inline]
pub fn set_ime_position(&self, spot: Position) {
let (x, y) = spot.to_physical::<i32>(self.scale_factor()).into();
self.set_ime_position_physical(x, y);
}
#[inline]
pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
let window = self.window.clone();
let active_window_handle = unsafe { GetActiveWindow() };
if window.0 == active_window_handle {
// active window could be minimized, so we skip requesting attention
// if it is not minimized
let window_flags = self.window_state.lock().window_flags();
let is_minimized = window_flags.contains(WindowFlags::MINIMIZED);
if !is_minimized {
return;
}
}
let window_isize = window.0 .0 as isize;
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, 4),
})
.unwrap_or((FLASHW_STOP, 0));
let flash_info = FLASHWINFO {
cbSize: mem::size_of::<FLASHWINFO>() as u32,
hwnd: HWND(window_isize as _),
dwFlags: flags,
uCount: count,
dwTimeout: 0,
};
let _ = FlashWindowEx(&flash_info);
});
}
#[inline]
pub fn theme(&self) -> Theme {
self.window_state.lock().current_theme
}
pub fn set_theme(&self, theme: Option<Theme>) {
{
let mut window_state = self.window_state.lock();
if window_state.preferred_theme == theme {
return;
}
window_state.preferred_theme = theme;
}
unsafe { SendMessageW(self.hwnd(), *CHANGE_THEME_MSG_ID, WPARAM(0), LPARAM(0)) };
}
#[inline]
pub fn reset_dead_keys(&self) {
// `ToUnicode` consumes the dead-key by default, so we are constructing a fake (but valid)
// key input which we can call `ToUnicode` with.
unsafe {
let vk = u32::from(VK_SPACE.0);
let scancode = MapVirtualKeyW(vk, MAPVK_VK_TO_VSC);
let kbd_state = [0; 256];
let mut char_buff: [MaybeUninit<u16>; 8] = [MaybeUninit::uninit(); 8];
ToUnicode(
vk,
scancode,
Some(&kbd_state),
mem::transmute(char_buff.as_mut()),
0,
);
}
}
#[inline]
pub fn begin_resize_drag(&self, edge: isize, button: u32, x: i32, y: i32) {
unsafe {
let w_param = WPARAM(edge as _);
let l_param = util::MAKELPARAM(x as i16, y as i16);
let _ = ReleaseCapture();
let _ = PostMessageW(self.hwnd(), button, w_param, l_param);
}
}
#[inline]
pub(crate) fn set_skip_taskbar(&self, skip: bool) -> Result<(), ExternalError> {
self.window_state.lock().skip_taskbar = skip;
unsafe { set_skip_taskbar(self.hwnd(), skip) }
}
#[inline]
pub fn set_progress_bar(&self, progress: ProgressBarState) {
unsafe {
let taskbar_list: ITaskbarList = CoCreateInstance(&TaskbarList, None, CLSCTX_SERVER).unwrap();
let handle = self.window.0;
if let Some(state) = progress.state {
let taskbar_state = {
match state {
ProgressState::None => TBPF_NOPROGRESS,
ProgressState::Indeterminate => TBPF_INDETERMINATE,
ProgressState::Normal => TBPF_NORMAL,
ProgressState::Error => TBPF_ERROR,
ProgressState::Paused => TBPF_PAUSED,
}
};