-
Notifications
You must be signed in to change notification settings - Fork 933
/
Copy pathevent_loop.rs
2152 lines (1895 loc) · 82.2 KB
/
event_loop.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
#![allow(non_snake_case)]
mod runner;
use parking_lot::Mutex;
use std::{
collections::VecDeque,
marker::PhantomData,
mem, panic, ptr,
rc::Rc,
sync::{
mpsc::{self, Receiver, Sender},
Arc,
},
thread,
time::{Duration, Instant},
};
use winapi::shared::basetsd::{DWORD_PTR, UINT_PTR};
use winapi::{
shared::{
minwindef::{BOOL, DWORD, HIWORD, INT, LOWORD, LPARAM, LRESULT, UINT, WPARAM},
windef::{HWND, POINT, RECT},
windowsx, winerror,
},
um::{
commctrl, libloaderapi, ole2, processthreadsapi, winbase,
winnt::{HANDLE, LONG, LPCSTR, SHORT},
winuser,
},
};
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
event::{DeviceEvent, Event, Force, KeyboardInput, Touch, TouchPhase, WindowEvent},
event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW},
monitor::MonitorHandle as RootMonitorHandle,
platform_impl::platform::{
dark_mode::try_theme,
dpi::{become_dpi_aware, dpi_to_scale_factor, enable_non_client_dpi_scaling},
drop_handler::FileDropHandler,
event::{self, handle_extended_keys, process_key_params, vkey_to_winit_vkey},
monitor::{self, MonitorHandle},
raw_input, util,
window_state::{CursorFlags, WindowFlags, WindowState},
wrap_device_id, WindowId, DEVICE_ID,
},
window::{Fullscreen, WindowId as RootWindowId},
};
use runner::{EventLoopRunner, EventLoopRunnerShared};
type GetPointerFrameInfoHistory = unsafe extern "system" fn(
pointerId: UINT,
entriesCount: *mut UINT,
pointerCount: *mut UINT,
pointerInfo: *mut winuser::POINTER_INFO,
) -> BOOL;
type SkipPointerFrameMessages = unsafe extern "system" fn(pointerId: UINT) -> BOOL;
type GetPointerDeviceRects = unsafe extern "system" fn(
device: HANDLE,
pointerDeviceRect: *mut RECT,
displayRect: *mut RECT,
) -> BOOL;
type GetPointerTouchInfo =
unsafe extern "system" fn(pointerId: UINT, touchInfo: *mut winuser::POINTER_TOUCH_INFO) -> BOOL;
type GetPointerPenInfo =
unsafe extern "system" fn(pointId: UINT, penInfo: *mut winuser::POINTER_PEN_INFO) -> BOOL;
lazy_static! {
static ref GET_POINTER_FRAME_INFO_HISTORY: Option<GetPointerFrameInfoHistory> =
get_function!("user32.dll", GetPointerFrameInfoHistory);
static ref SKIP_POINTER_FRAME_MESSAGES: Option<SkipPointerFrameMessages> =
get_function!("user32.dll", SkipPointerFrameMessages);
static ref GET_POINTER_DEVICE_RECTS: Option<GetPointerDeviceRects> =
get_function!("user32.dll", GetPointerDeviceRects);
static ref GET_POINTER_TOUCH_INFO: Option<GetPointerTouchInfo> =
get_function!("user32.dll", GetPointerTouchInfo);
static ref GET_POINTER_PEN_INFO: Option<GetPointerPenInfo> =
get_function!("user32.dll", GetPointerPenInfo);
}
pub(crate) struct SubclassInput<T: 'static> {
pub window_state: Arc<Mutex<WindowState>>,
pub event_loop_runner: EventLoopRunnerShared<T>,
pub file_drop_handler: Option<FileDropHandler>,
}
impl<T> SubclassInput<T> {
unsafe fn send_event(&self, event: Event<'_, T>) {
self.event_loop_runner.send_event(event);
}
}
struct ThreadMsgTargetSubclassInput<T: 'static> {
event_loop_runner: EventLoopRunnerShared<T>,
user_event_receiver: Receiver<T>,
}
impl<T> ThreadMsgTargetSubclassInput<T> {
unsafe fn send_event(&self, event: Event<'_, T>) {
self.event_loop_runner.send_event(event);
}
}
pub struct EventLoop<T: 'static> {
thread_msg_sender: Sender<T>,
window_target: RootELW<T>,
}
pub struct EventLoopWindowTarget<T: 'static> {
thread_id: DWORD,
thread_msg_target: HWND,
pub(crate) runner_shared: EventLoopRunnerShared<T>,
}
macro_rules! main_thread_check {
($fn_name:literal) => {{
let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
if thread_id != main_thread_id() {
panic!(concat!(
"Initializing the event loop outside of the main thread is a significant \
cross-platform compatibility hazard. If you really, absolutely need to create an \
EventLoop on a different thread, please use the `EventLoopExtWindows::",
$fn_name,
"` function."
));
}
}};
}
impl<T: 'static> EventLoop<T> {
pub fn new() -> EventLoop<T> {
main_thread_check!("new_any_thread");
Self::new_any_thread()
}
pub fn new_any_thread() -> EventLoop<T> {
become_dpi_aware();
Self::new_dpi_unaware_any_thread()
}
pub fn new_dpi_unaware() -> EventLoop<T> {
main_thread_check!("new_dpi_unaware_any_thread");
Self::new_dpi_unaware_any_thread()
}
pub fn new_dpi_unaware_any_thread() -> EventLoop<T> {
let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
let thread_msg_target = create_event_target_window();
let send_thread_msg_target = thread_msg_target as usize;
thread::spawn(move || wait_thread(thread_id, send_thread_msg_target as HWND));
let wait_thread_id = get_wait_thread_id();
let runner_shared = Rc::new(EventLoopRunner::new(thread_msg_target, wait_thread_id));
let thread_msg_sender =
subclass_event_target_window(thread_msg_target, runner_shared.clone());
raw_input::register_all_mice_and_keyboards_for_raw_input(thread_msg_target);
EventLoop {
thread_msg_sender,
window_target: RootELW {
p: EventLoopWindowTarget {
thread_id,
thread_msg_target,
runner_shared,
},
_marker: PhantomData,
},
}
}
pub fn window_target(&self) -> &RootELW<T> {
&self.window_target
}
pub fn run<F>(mut self, event_handler: F) -> !
where
F: 'static + FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow),
{
self.run_return(event_handler);
::std::process::exit(0);
}
pub fn run_return<F>(&mut self, mut event_handler: F)
where
F: FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow),
{
let event_loop_windows_ref = &self.window_target;
unsafe {
self.window_target
.p
.runner_shared
.set_event_handler(move |event, control_flow| {
event_handler(event, event_loop_windows_ref, control_flow)
});
}
let runner = &self.window_target.p.runner_shared;
unsafe {
let mut msg = mem::zeroed();
runner.poll();
'main: loop {
if 0 == winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
break 'main;
}
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
if let Err(payload) = runner.take_panic_error() {
runner.reset_runner();
panic::resume_unwind(payload);
}
if runner.control_flow() == ControlFlow::Exit && !runner.handling_events() {
break 'main;
}
}
}
unsafe {
runner.loop_destroyed();
}
runner.reset_runner();
}
pub fn create_proxy(&self) -> EventLoopProxy<T> {
EventLoopProxy {
target_window: self.window_target.p.thread_msg_target,
event_send: self.thread_msg_sender.clone(),
}
}
}
impl<T> EventLoopWindowTarget<T> {
#[inline(always)]
pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor {
EventLoopThreadExecutor {
thread_id: self.thread_id,
target_window: self.thread_msg_target,
}
}
// TODO: Investigate opportunities for caching
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
monitor::available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = monitor::primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
fn main_thread_id() -> DWORD {
static mut MAIN_THREAD_ID: DWORD = 0;
#[used]
#[allow(non_upper_case_globals)]
#[link_section = ".CRT$XCU"]
static INIT_MAIN_THREAD_ID: unsafe fn() = {
unsafe fn initer() {
MAIN_THREAD_ID = processthreadsapi::GetCurrentThreadId();
}
initer
};
unsafe { MAIN_THREAD_ID }
}
fn get_wait_thread_id() -> DWORD {
unsafe {
let mut msg = mem::zeroed();
let result = winuser::GetMessageW(
&mut msg,
-1 as _,
*SEND_WAIT_THREAD_ID_MSG_ID,
*SEND_WAIT_THREAD_ID_MSG_ID,
);
assert_eq!(
msg.message, *SEND_WAIT_THREAD_ID_MSG_ID,
"this shouldn't be possible. please open an issue with Winit. error code: {}",
result
);
msg.lParam as DWORD
}
}
fn wait_thread(parent_thread_id: DWORD, msg_window_id: HWND) {
unsafe {
let mut msg: winuser::MSG;
let cur_thread_id = processthreadsapi::GetCurrentThreadId();
winuser::PostThreadMessageW(
parent_thread_id,
*SEND_WAIT_THREAD_ID_MSG_ID,
0,
cur_thread_id as LPARAM,
);
let mut wait_until_opt = None;
'main: loop {
// Zeroing out the message ensures that the `WaitUntilInstantBox` doesn't get
// double-freed if `MsgWaitForMultipleObjectsEx` returns early and there aren't
// additional messages to process.
msg = mem::zeroed();
if wait_until_opt.is_some() {
if 0 != winuser::PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, winuser::PM_REMOVE) {
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
}
} else {
if 0 == winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
break 'main;
} else {
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
}
}
if msg.message == *WAIT_UNTIL_MSG_ID {
wait_until_opt = Some(*WaitUntilInstantBox::from_raw(msg.lParam as *mut _));
} else if msg.message == *CANCEL_WAIT_UNTIL_MSG_ID {
wait_until_opt = None;
}
if let Some(wait_until) = wait_until_opt {
let now = Instant::now();
if now < wait_until {
// MsgWaitForMultipleObjects tends to overshoot just a little bit. We subtract
// 1 millisecond from the requested time and spinlock for the remainder to
// compensate for that.
let resume_reason = winuser::MsgWaitForMultipleObjectsEx(
0,
ptr::null(),
dur2timeout(wait_until - now).saturating_sub(1),
winuser::QS_ALLEVENTS,
winuser::MWMO_INPUTAVAILABLE,
);
if resume_reason == winerror::WAIT_TIMEOUT {
winuser::PostMessageW(msg_window_id, *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
wait_until_opt = None;
}
} else {
winuser::PostMessageW(msg_window_id, *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
wait_until_opt = None;
}
}
}
}
}
// Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs
fn dur2timeout(dur: Duration) -> DWORD {
// Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
// timeouts in windows APIs are typically u32 milliseconds. To translate, we
// have two pieces to take care of:
//
// * Nanosecond precision is rounded up
// * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
// (never time out).
dur.as_secs()
.checked_mul(1000)
.and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
.and_then(|ms| {
ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {
1
} else {
0
})
})
.map(|ms| {
if ms > DWORD::max_value() as u64 {
winbase::INFINITE
} else {
ms as DWORD
}
})
.unwrap_or(winbase::INFINITE)
}
impl<T> Drop for EventLoop<T> {
fn drop(&mut self) {
unsafe {
winuser::DestroyWindow(self.window_target.p.thread_msg_target);
}
}
}
pub(crate) struct EventLoopThreadExecutor {
thread_id: DWORD,
target_window: HWND,
}
unsafe impl Send for EventLoopThreadExecutor {}
unsafe impl Sync for EventLoopThreadExecutor {}
impl EventLoopThreadExecutor {
/// Check to see if we're in the parent event loop's thread.
pub(super) fn in_event_loop_thread(&self) -> bool {
let cur_thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
self.thread_id == cur_thread_id
}
/// Executes a function in the event loop thread. If we're already in the event loop thread,
/// we just call the function directly.
///
/// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is
/// removed automatically if the callback receives a `WM_CLOSE` message for the window.
///
/// Note that if you are using this to change some property of a window and updating
/// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the
/// events may be sent to the other thread in different order to the one in which you set
/// `WindowState`, leaving them out of sync.
///
/// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent
/// to the unstable FnBox.
pub(super) fn execute_in_thread<F>(&self, mut function: F)
where
F: FnMut() + Send + 'static,
{
unsafe {
if self.in_event_loop_thread() {
function();
} else {
// We double-box because the first box is a fat pointer.
let boxed = Box::new(function) as Box<dyn FnMut()>;
let boxed2: ThreadExecFn = Box::new(boxed);
let raw = Box::into_raw(boxed2);
let res = winuser::PostMessageW(
self.target_window,
*EXEC_MSG_ID,
raw as *mut () as usize as WPARAM,
0,
);
assert!(res != 0, "PostMessage failed ; is the messages queue full?");
}
}
}
}
type ThreadExecFn = Box<Box<dyn FnMut()>>;
pub struct EventLoopProxy<T: 'static> {
target_window: HWND,
event_send: Sender<T>,
}
unsafe impl<T: Send + 'static> Send for EventLoopProxy<T> {}
impl<T: 'static> Clone for EventLoopProxy<T> {
fn clone(&self) -> Self {
Self {
target_window: self.target_window,
event_send: self.event_send.clone(),
}
}
}
impl<T: 'static> EventLoopProxy<T> {
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
unsafe {
if winuser::PostMessageW(self.target_window, *USER_EVENT_MSG_ID, 0, 0) != 0 {
self.event_send.send(event).ok();
Ok(())
} else {
Err(EventLoopClosed(event))
}
}
}
}
type WaitUntilInstantBox = Box<Instant>;
lazy_static! {
// Message sent by the `EventLoopProxy` when we want to wake up the thread.
// WPARAM and LPARAM are unused.
static ref USER_EVENT_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as LPCSTR)
}
};
// Message sent when we want to execute a closure in the thread.
// WPARAM contains a Box<Box<dyn FnMut()>> that must be retrieved with `Box::from_raw`,
// and LPARAM is unused.
static ref EXEC_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8)
}
};
static ref PROCESS_NEW_EVENTS_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::ProcessNewEvents\0".as_ptr() as *const i8)
}
};
/// lparam is the wait thread's message id.
static ref SEND_WAIT_THREAD_ID_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::SendWaitThreadId\0".as_ptr() as *const i8)
}
};
/// lparam points to a `Box<Instant>` signifying the time `PROCESS_NEW_EVENTS_MSG_ID` should
/// be sent.
static ref WAIT_UNTIL_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::WaitUntil\0".as_ptr() as *const i8)
}
};
static ref CANCEL_WAIT_UNTIL_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::CancelWaitUntil\0".as_ptr() as *const i8)
}
};
// Message sent by a `Window` when it wants to be destroyed by the main thread.
// WPARAM and LPARAM are unused.
pub static ref DESTROY_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as LPCSTR)
}
};
// WPARAM is a bool specifying the `WindowFlags::MARKER_RETAIN_STATE_ON_SIZE` flag. See the
// documentation in the `window_state` module for more information.
pub static ref SET_RETAIN_STATE_ON_SIZE_MSG_ID: u32 = unsafe {
winuser::RegisterWindowMessageA("Winit::SetRetainMaximized\0".as_ptr() as LPCSTR)
};
static ref THREAD_EVENT_TARGET_WINDOW_CLASS: Vec<u16> = unsafe {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
let class_name: Vec<_> = OsStr::new("Winit Thread Event Target")
.encode_wide()
.chain(Some(0).into_iter())
.collect();
let class = winuser::WNDCLASSEXW {
cbSize: mem::size_of::<winuser::WNDCLASSEXW>() as UINT,
style: 0,
lpfnWndProc: Some(winuser::DefWindowProcW),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: libloaderapi::GetModuleHandleW(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
winuser::RegisterClassExW(&class);
class_name
};
}
fn create_event_target_window() -> HWND {
unsafe {
let window = winuser::CreateWindowExW(
winuser::WS_EX_NOACTIVATE | winuser::WS_EX_TRANSPARENT | winuser::WS_EX_LAYERED,
THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(),
ptr::null_mut(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
libloaderapi::GetModuleHandleW(ptr::null()),
ptr::null_mut(),
);
winuser::SetWindowLongPtrW(
window,
winuser::GWL_STYLE,
// The window technically has to be visible to receive WM_PAINT messages (which are used
// for delivering events during resizes), but it isn't displayed to the user because of
// the LAYERED style.
(winuser::WS_VISIBLE | winuser::WS_POPUP) as _,
);
window
}
}
fn subclass_event_target_window<T>(
window: HWND,
event_loop_runner: EventLoopRunnerShared<T>,
) -> Sender<T> {
unsafe {
let (tx, rx) = mpsc::channel();
let subclass_input = ThreadMsgTargetSubclassInput {
event_loop_runner,
user_event_receiver: rx,
};
let input_ptr = Box::into_raw(Box::new(subclass_input));
let subclass_result = commctrl::SetWindowSubclass(
window,
Some(thread_event_target_callback::<T>),
THREAD_EVENT_TARGET_SUBCLASS_ID,
input_ptr as DWORD_PTR,
);
assert_eq!(subclass_result, 1);
tx
}
}
/// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of
/// the window.
unsafe fn capture_mouse(window: HWND, window_state: &mut WindowState) {
window_state.mouse.buttons_down += 1;
winuser::SetCapture(window);
}
/// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor
/// is outside the window.
unsafe fn release_mouse(window_state: &mut WindowState) {
window_state.mouse.buttons_down = window_state.mouse.buttons_down.saturating_sub(1);
if window_state.mouse.buttons_down == 0 {
winuser::ReleaseCapture();
}
}
const WINDOW_SUBCLASS_ID: UINT_PTR = 0;
const THREAD_EVENT_TARGET_SUBCLASS_ID: UINT_PTR = 1;
pub(crate) fn subclass_window<T>(window: HWND, subclass_input: SubclassInput<T>) {
subclass_input.event_loop_runner.register_window(window);
let input_ptr = Box::into_raw(Box::new(subclass_input));
let subclass_result = unsafe {
commctrl::SetWindowSubclass(
window,
Some(public_window_callback::<T>),
WINDOW_SUBCLASS_ID,
input_ptr as DWORD_PTR,
)
};
assert_eq!(subclass_result, 1);
}
fn normalize_pointer_pressure(pressure: u32) -> Option<Force> {
match pressure {
1..=1024 => Some(Force::Normalized(pressure as f64 / 1024.0)),
_ => None,
}
}
/// Flush redraw events for Winit's windows.
///
/// Winit's API guarantees that all redraw events will be clustered together and dispatched all at
/// once, but the standard Windows message loop doesn't always exhibit that behavior. If multiple
/// windows have had redraws scheduled, but an input event is pushed to the message queue between
/// the `WM_PAINT` call for the first window and the `WM_PAINT` call for the second window, Windows
/// will dispatch the input event immediately instead of flushing all the redraw events. This
/// function explicitly pulls all of Winit's redraw events out of the event queue so that they
/// always all get processed in one fell swoop.
///
/// Returns `true` if this invocation flushed all the redraw events. If this function is re-entrant,
/// it won't flush the redraw events and will return `false`.
#[must_use]
unsafe fn flush_paint_messages<T: 'static>(
except: Option<HWND>,
runner: &EventLoopRunner<T>,
) -> bool {
if !runner.redrawing() {
runner.main_events_cleared();
let mut msg = mem::zeroed();
runner.owned_windows(|redraw_window| {
if Some(redraw_window) == except {
return;
}
if 0 == winuser::PeekMessageW(
&mut msg,
redraw_window,
winuser::WM_PAINT,
winuser::WM_PAINT,
winuser::PM_REMOVE | winuser::PM_QS_PAINT,
) {
return;
}
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
});
true
} else {
false
}
}
unsafe fn process_control_flow<T: 'static>(runner: &EventLoopRunner<T>) {
match runner.control_flow() {
ControlFlow::Poll => {
winuser::PostMessageW(runner.thread_msg_target(), *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
}
ControlFlow::Wait => (),
ControlFlow::WaitUntil(until) => {
winuser::PostThreadMessageW(
runner.wait_thread_id(),
*WAIT_UNTIL_MSG_ID,
0,
Box::into_raw(WaitUntilInstantBox::new(until)) as LPARAM,
);
}
ControlFlow::Exit => (),
}
}
/// Emit a `ModifiersChanged` event whenever modifiers have changed.
fn update_modifiers<T>(window: HWND, subclass_input: &SubclassInput<T>) {
use crate::event::WindowEvent::ModifiersChanged;
let modifiers = event::get_key_mods();
let mut window_state = subclass_input.window_state.lock();
if window_state.modifiers_state != modifiers {
window_state.modifiers_state = modifiers;
// Drop lock
drop(window_state);
unsafe {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ModifiersChanged(modifiers),
});
}
}
}
/// Any window whose callback is configured to this function will have its events propagated
/// through the events loop of the thread the window was created in.
//
// This is the callback that is called by `DispatchMessage` in the events loop.
//
// Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
unsafe extern "system" fn public_window_callback<T: 'static>(
window: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
_: UINT_PTR,
subclass_input_ptr: DWORD_PTR,
) -> LRESULT {
let subclass_input = &*(subclass_input_ptr as *const SubclassInput<T>);
winuser::RedrawWindow(
subclass_input.event_loop_runner.thread_msg_target(),
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
// I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing
// the closure to catch_unwind directly so that the match body indendation wouldn't change and
// the git blame and history would be preserved.
let callback = || match msg {
winuser::WM_ENTERSIZEMOVE => {
subclass_input
.window_state
.lock()
.set_window_flags_in_place(|f| f.insert(WindowFlags::MARKER_IN_SIZE_MOVE));
0
}
winuser::WM_EXITSIZEMOVE => {
subclass_input
.window_state
.lock()
.set_window_flags_in_place(|f| f.remove(WindowFlags::MARKER_IN_SIZE_MOVE));
0
}
winuser::WM_NCCREATE => {
enable_non_client_dpi_scaling(window);
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_NCLBUTTONDOWN => {
if wparam == winuser::HTCAPTION as _ {
winuser::PostMessageW(window, winuser::WM_MOUSEMOVE, 0, 0);
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_CLOSE => {
use crate::event::WindowEvent::CloseRequested;
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: CloseRequested,
});
0
}
winuser::WM_DESTROY => {
use crate::event::WindowEvent::Destroyed;
ole2::RevokeDragDrop(window);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Destroyed,
});
subclass_input.event_loop_runner.remove_window(window);
0
}
winuser::WM_NCDESTROY => {
drop(subclass_input);
Box::from_raw(subclass_input_ptr as *mut SubclassInput<T>);
0
}
winuser::WM_PAINT => {
if subclass_input.event_loop_runner.should_buffer() {
// this branch can happen in response to `UpdateWindow`, if win32 decides to
// redraw the window outside the normal flow of the event loop.
winuser::RedrawWindow(
window,
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
} else {
let managing_redraw =
flush_paint_messages(Some(window), &subclass_input.event_loop_runner);
subclass_input.send_event(Event::RedrawRequested(RootWindowId(WindowId(window))));
if managing_redraw {
subclass_input.event_loop_runner.redraw_events_cleared();
process_control_flow(&subclass_input.event_loop_runner);
}
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_WINDOWPOSCHANGING => {
let mut window_state = subclass_input.window_state.lock();
if let Some(ref mut fullscreen) = window_state.fullscreen {
let window_pos = &mut *(lparam as *mut winuser::WINDOWPOS);
let new_rect = RECT {
left: window_pos.x,
top: window_pos.y,
right: window_pos.x + window_pos.cx,
bottom: window_pos.y + window_pos.cy,
};
let new_monitor =
winuser::MonitorFromRect(&new_rect, winuser::MONITOR_DEFAULTTONULL);
match fullscreen {
Fullscreen::Borderless(ref mut fullscreen_monitor) => {
if new_monitor != ptr::null_mut()
&& fullscreen_monitor
.as_ref()
.map(|monitor| new_monitor != monitor.inner.hmonitor())
.unwrap_or(true)
{
if let Ok(new_monitor_info) = monitor::get_monitor_info(new_monitor) {
let new_monitor_rect = new_monitor_info.rcMonitor;
window_pos.x = new_monitor_rect.left;
window_pos.y = new_monitor_rect.top;
window_pos.cx = new_monitor_rect.right - new_monitor_rect.left;
window_pos.cy = new_monitor_rect.bottom - new_monitor_rect.top;
}
*fullscreen_monitor = Some(crate::monitor::MonitorHandle {
inner: MonitorHandle::new(new_monitor),
});
}
}
Fullscreen::Exclusive(ref video_mode) => {
let old_monitor = video_mode.video_mode.monitor.hmonitor();
if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) {
let old_monitor_rect = old_monitor_info.rcMonitor;
window_pos.x = old_monitor_rect.left;
window_pos.y = old_monitor_rect.top;
window_pos.cx = old_monitor_rect.right - old_monitor_rect.left;
window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top;
}
}
}
}
0
}
// WM_MOVE supplies client area positions, so we send Moved here instead.
winuser::WM_WINDOWPOSCHANGED => {
use crate::event::WindowEvent::Moved;
let windowpos = lparam as *const winuser::WINDOWPOS;
if (*windowpos).flags & winuser::SWP_NOMOVE != winuser::SWP_NOMOVE {
let physical_position =
PhysicalPosition::new((*windowpos).x as i32, (*windowpos).y as i32);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Moved(physical_position),
});
}
// This is necessary for us to still get sent WM_SIZE.
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_SIZE => {
use crate::event::WindowEvent::Resized;
let w = LOWORD(lparam as DWORD) as u32;
let h = HIWORD(lparam as DWORD) as u32;
let physical_size = PhysicalSize::new(w, h);
let event = Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Resized(physical_size),
};
{
let mut w = subclass_input.window_state.lock();
// See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check exists.
if !w
.window_flags()
.contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE)
{
let maximized = wparam == winuser::SIZE_MAXIMIZED;
w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized));
}
}
subclass_input.send_event(event);
0
}
winuser::WM_CHAR | winuser::WM_SYSCHAR => {
use crate::event::WindowEvent::ReceivedCharacter;
use std::char;
let is_high_surrogate = 0xD800 <= wparam && wparam <= 0xDBFF;
let is_low_surrogate = 0xDC00 <= wparam && wparam <= 0xDFFF;
if is_high_surrogate {
subclass_input.window_state.lock().high_surrogate = Some(wparam as u16);
} else if is_low_surrogate {
let high_surrogate = subclass_input.window_state.lock().high_surrogate.take();
if let Some(high_surrogate) = high_surrogate {
let pair = [high_surrogate, wparam as u16];
if let Some(Ok(chr)) = char::decode_utf16(pair.iter().copied()).next() {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ReceivedCharacter(chr),
});
}
}
} else {
subclass_input.window_state.lock().high_surrogate = None;
if let Some(chr) = char::from_u32(wparam as u32) {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ReceivedCharacter(chr),
});
}
}
0
}
// this is necessary for us to maintain minimize/restore state
winuser::WM_SYSCOMMAND => {
if wparam == winuser::SC_RESTORE {
let mut w = subclass_input.window_state.lock();
w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, false));
}
if wparam == winuser::SC_MINIMIZE {
let mut w = subclass_input.window_state.lock();
w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, true));
}
// Send `WindowEvent::Minimized` here if we decide to implement one
if wparam == winuser::SC_SCREENSAVE {
let window_state = subclass_input.window_state.lock();
if window_state.fullscreen.is_some() {
return 0;
}
}
winuser::DefWindowProcW(window, msg, wparam, lparam)
}
winuser::WM_MOUSEMOVE => {
use crate::event::WindowEvent::{CursorEntered, CursorMoved};
let mouse_was_outside_window = {
let mut w = subclass_input.window_state.lock();
let was_outside_window = !w.mouse.cursor_flags().contains(CursorFlags::IN_WINDOW);
w.mouse
.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, true))