1use std::rc::Rc;
2
3use ::util::ResultExt;
4use anyhow::Context as _;
5use windows::{
6 Win32::{
7 Foundation::*,
8 Graphics::Gdi::*,
9 System::SystemServices::*,
10 UI::{
11 Controls::*,
12 HiDpi::*,
13 Input::{Ime::*, KeyboardAndMouse::*},
14 WindowsAndMessaging::*,
15 },
16 },
17 core::PCWSTR,
18};
19
20use crate::*;
21
22pub(crate) const WM_GPUI_CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;
23pub(crate) const WM_GPUI_CLOSE_ONE_WINDOW: u32 = WM_USER + 2;
24pub(crate) const WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD: u32 = WM_USER + 3;
25pub(crate) const WM_GPUI_DOCK_MENU_ACTION: u32 = WM_USER + 4;
26
27const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
28const AUTO_HIDE_TASKBAR_THICKNESS_PX: i32 = 1;
29
30pub(crate) fn handle_msg(
31 handle: HWND,
32 msg: u32,
33 wparam: WPARAM,
34 lparam: LPARAM,
35 state_ptr: Rc<WindowsWindowStatePtr>,
36) -> LRESULT {
37 let handled = match msg {
38 WM_ACTIVATE => handle_activate_msg(wparam, state_ptr),
39 WM_CREATE => handle_create_msg(handle, state_ptr),
40 WM_MOVE => handle_move_msg(handle, lparam, state_ptr),
41 WM_SIZE => handle_size_msg(wparam, lparam, state_ptr),
42 WM_GETMINMAXINFO => handle_get_min_max_info_msg(lparam, state_ptr),
43 WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => handle_size_move_loop(handle),
44 WM_EXITSIZEMOVE | WM_EXITMENULOOP => handle_size_move_loop_exit(handle),
45 WM_TIMER => handle_timer_msg(handle, wparam, state_ptr),
46 WM_NCCALCSIZE => handle_calc_client_size(handle, wparam, lparam, state_ptr),
47 WM_DPICHANGED => handle_dpi_changed_msg(handle, wparam, lparam, state_ptr),
48 WM_DISPLAYCHANGE => handle_display_change_msg(handle, state_ptr),
49 WM_NCHITTEST => handle_hit_test_msg(handle, msg, wparam, lparam, state_ptr),
50 WM_PAINT => handle_paint_msg(handle, state_ptr),
51 WM_CLOSE => handle_close_msg(handle, state_ptr),
52 WM_DESTROY => handle_destroy_msg(handle, state_ptr),
53 WM_MOUSEMOVE => handle_mouse_move_msg(handle, lparam, wparam, state_ptr),
54 WM_MOUSELEAVE | WM_NCMOUSELEAVE => handle_mouse_leave_msg(state_ptr),
55 WM_NCMOUSEMOVE => handle_nc_mouse_move_msg(handle, lparam, state_ptr),
56 WM_NCLBUTTONDOWN => {
57 handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam, state_ptr)
58 }
59 WM_NCRBUTTONDOWN => {
60 handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam, state_ptr)
61 }
62 WM_NCMBUTTONDOWN => {
63 handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam, state_ptr)
64 }
65 WM_NCLBUTTONUP => {
66 handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam, state_ptr)
67 }
68 WM_NCRBUTTONUP => {
69 handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam, state_ptr)
70 }
71 WM_NCMBUTTONUP => {
72 handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam, state_ptr)
73 }
74 WM_LBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Left, lparam, state_ptr),
75 WM_RBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Right, lparam, state_ptr),
76 WM_MBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Middle, lparam, state_ptr),
77 WM_XBUTTONDOWN => {
78 handle_xbutton_msg(handle, wparam, lparam, handle_mouse_down_msg, state_ptr)
79 }
80 WM_LBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Left, lparam, state_ptr),
81 WM_RBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Right, lparam, state_ptr),
82 WM_MBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Middle, lparam, state_ptr),
83 WM_XBUTTONUP => handle_xbutton_msg(handle, wparam, lparam, handle_mouse_up_msg, state_ptr),
84 WM_MOUSEWHEEL => handle_mouse_wheel_msg(handle, wparam, lparam, state_ptr),
85 WM_MOUSEHWHEEL => handle_mouse_horizontal_wheel_msg(handle, wparam, lparam, state_ptr),
86 WM_SYSKEYDOWN => handle_syskeydown_msg(handle, wparam, lparam, state_ptr),
87 WM_SYSKEYUP => handle_syskeyup_msg(handle, wparam, lparam, state_ptr),
88 WM_SYSCOMMAND => handle_system_command(wparam, state_ptr),
89 WM_KEYDOWN => handle_keydown_msg(handle, wparam, lparam, state_ptr),
90 WM_KEYUP => handle_keyup_msg(handle, wparam, lparam, state_ptr),
91 WM_CHAR => handle_char_msg(wparam, state_ptr),
92 WM_DEADCHAR => handle_dead_char_msg(wparam, state_ptr),
93 WM_IME_STARTCOMPOSITION => handle_ime_position(handle, state_ptr),
94 WM_IME_COMPOSITION => handle_ime_composition(handle, lparam, state_ptr),
95 WM_SETCURSOR => handle_set_cursor(handle, lparam, state_ptr),
96 WM_SETTINGCHANGE => handle_system_settings_changed(handle, lparam, state_ptr),
97 WM_INPUTLANGCHANGE => handle_input_language_changed(lparam, state_ptr),
98 WM_GPUI_CURSOR_STYLE_CHANGED => handle_cursor_changed(lparam, state_ptr),
99 _ => None,
100 };
101 if let Some(n) = handled {
102 LRESULT(n)
103 } else {
104 unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
105 }
106}
107
108fn handle_move_msg(
109 handle: HWND,
110 lparam: LPARAM,
111 state_ptr: Rc<WindowsWindowStatePtr>,
112) -> Option<isize> {
113 let mut lock = state_ptr.state.borrow_mut();
114 let origin = logical_point(
115 lparam.signed_loword() as f32,
116 lparam.signed_hiword() as f32,
117 lock.scale_factor,
118 );
119 lock.origin = origin;
120 let size = lock.logical_size;
121 let center_x = origin.x.0 + size.width.0 / 2.;
122 let center_y = origin.y.0 + size.height.0 / 2.;
123 let monitor_bounds = lock.display.bounds();
124 if center_x < monitor_bounds.left().0
125 || center_x > monitor_bounds.right().0
126 || center_y < monitor_bounds.top().0
127 || center_y > monitor_bounds.bottom().0
128 {
129 // center of the window may have moved to another monitor
130 let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
131 // minimize the window can trigger this event too, in this case,
132 // monitor is invalid, we do nothing.
133 if !monitor.is_invalid() && lock.display.handle != monitor {
134 // we will get the same monitor if we only have one
135 lock.display = WindowsDisplay::new_with_handle(monitor);
136 }
137 }
138 if let Some(mut callback) = lock.callbacks.moved.take() {
139 drop(lock);
140 callback();
141 state_ptr.state.borrow_mut().callbacks.moved = Some(callback);
142 }
143 Some(0)
144}
145
146fn handle_get_min_max_info_msg(
147 lparam: LPARAM,
148 state_ptr: Rc<WindowsWindowStatePtr>,
149) -> Option<isize> {
150 let lock = state_ptr.state.borrow();
151 let min_size = lock.min_size?;
152 let scale_factor = lock.scale_factor;
153 let boarder_offset = lock.border_offset;
154 drop(lock);
155 unsafe {
156 let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);
157 minmax_info.ptMinTrackSize.x =
158 min_size.width.scale(scale_factor).0 as i32 + boarder_offset.width_offset;
159 minmax_info.ptMinTrackSize.y =
160 min_size.height.scale(scale_factor).0 as i32 + boarder_offset.height_offset;
161 }
162 Some(0)
163}
164
165fn handle_size_msg(
166 wparam: WPARAM,
167 lparam: LPARAM,
168 state_ptr: Rc<WindowsWindowStatePtr>,
169) -> Option<isize> {
170 let mut lock = state_ptr.state.borrow_mut();
171
172 // Don't resize the renderer when the window is minimized, but record that it was minimized so
173 // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.
174 if wparam.0 == SIZE_MINIMIZED as usize {
175 lock.restore_from_minimized = lock.callbacks.request_frame.take();
176 return Some(0);
177 }
178
179 let width = lparam.loword().max(1) as i32;
180 let height = lparam.hiword().max(1) as i32;
181 let new_size = size(DevicePixels(width), DevicePixels(height));
182 let scale_factor = lock.scale_factor;
183 if lock.restore_from_minimized.is_some() {
184 lock.renderer
185 .update_drawable_size_even_if_unchanged(new_size);
186 lock.callbacks.request_frame = lock.restore_from_minimized.take();
187 } else {
188 lock.renderer.update_drawable_size(new_size);
189 }
190 let new_size = new_size.to_pixels(scale_factor);
191 lock.logical_size = new_size;
192 if let Some(mut callback) = lock.callbacks.resize.take() {
193 drop(lock);
194 callback(new_size, scale_factor);
195 state_ptr.state.borrow_mut().callbacks.resize = Some(callback);
196 }
197 Some(0)
198}
199
200fn handle_size_move_loop(handle: HWND) -> Option<isize> {
201 unsafe {
202 let ret = SetTimer(
203 Some(handle),
204 SIZE_MOVE_LOOP_TIMER_ID,
205 USER_TIMER_MINIMUM,
206 None,
207 );
208 if ret == 0 {
209 log::error!(
210 "unable to create timer: {}",
211 std::io::Error::last_os_error()
212 );
213 }
214 }
215 None
216}
217
218fn handle_size_move_loop_exit(handle: HWND) -> Option<isize> {
219 unsafe {
220 KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();
221 }
222 None
223}
224
225fn handle_timer_msg(
226 handle: HWND,
227 wparam: WPARAM,
228 state_ptr: Rc<WindowsWindowStatePtr>,
229) -> Option<isize> {
230 if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
231 for runnable in state_ptr.main_receiver.drain() {
232 runnable.run();
233 }
234 handle_paint_msg(handle, state_ptr)
235 } else {
236 None
237 }
238}
239
240fn handle_paint_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
241 let mut lock = state_ptr.state.borrow_mut();
242 if let Some(mut request_frame) = lock.callbacks.request_frame.take() {
243 drop(lock);
244 request_frame(Default::default());
245 state_ptr.state.borrow_mut().callbacks.request_frame = Some(request_frame);
246 }
247 unsafe { ValidateRect(Some(handle), None).ok().log_err() };
248 Some(0)
249}
250
251fn handle_close_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
252 let mut lock = state_ptr.state.borrow_mut();
253 let output = if let Some(mut callback) = lock.callbacks.should_close.take() {
254 drop(lock);
255 let should_close = callback();
256 state_ptr.state.borrow_mut().callbacks.should_close = Some(callback);
257 if should_close { None } else { Some(0) }
258 } else {
259 None
260 };
261
262 // Workaround as window close animation is not played with `WS_EX_LAYERED` enabled.
263 if output.is_none() {
264 unsafe {
265 let current_style = get_window_long(handle, GWL_EXSTYLE);
266 set_window_long(
267 handle,
268 GWL_EXSTYLE,
269 current_style & !WS_EX_LAYERED.0 as isize,
270 );
271 }
272 }
273
274 output
275}
276
277fn handle_destroy_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
278 let callback = {
279 let mut lock = state_ptr.state.borrow_mut();
280 lock.callbacks.close.take()
281 };
282 if let Some(callback) = callback {
283 callback();
284 }
285 unsafe {
286 PostThreadMessageW(
287 state_ptr.main_thread_id_win32,
288 WM_GPUI_CLOSE_ONE_WINDOW,
289 WPARAM(state_ptr.validation_number),
290 LPARAM(handle.0 as isize),
291 )
292 .log_err();
293 }
294 Some(0)
295}
296
297fn handle_mouse_move_msg(
298 handle: HWND,
299 lparam: LPARAM,
300 wparam: WPARAM,
301 state_ptr: Rc<WindowsWindowStatePtr>,
302) -> Option<isize> {
303 start_tracking_mouse(handle, &state_ptr, TME_LEAVE);
304
305 let mut lock = state_ptr.state.borrow_mut();
306 let Some(mut func) = lock.callbacks.input.take() else {
307 return Some(1);
308 };
309 let scale_factor = lock.scale_factor;
310 drop(lock);
311
312 let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
313 flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
314 flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
315 flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
316 flags if flags.contains(MK_XBUTTON1) => {
317 Some(MouseButton::Navigate(NavigationDirection::Back))
318 }
319 flags if flags.contains(MK_XBUTTON2) => {
320 Some(MouseButton::Navigate(NavigationDirection::Forward))
321 }
322 _ => None,
323 };
324 let x = lparam.signed_loword() as f32;
325 let y = lparam.signed_hiword() as f32;
326 let input = PlatformInput::MouseMove(MouseMoveEvent {
327 position: logical_point(x, y, scale_factor),
328 pressed_button,
329 modifiers: current_modifiers(),
330 });
331 let handled = !func(input).propagate;
332 state_ptr.state.borrow_mut().callbacks.input = Some(func);
333
334 if handled { Some(0) } else { Some(1) }
335}
336
337fn handle_mouse_leave_msg(state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
338 let mut lock = state_ptr.state.borrow_mut();
339 lock.hovered = false;
340 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
341 drop(lock);
342 callback(false);
343 state_ptr.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
344 }
345
346 Some(0)
347}
348
349fn handle_syskeydown_msg(
350 handle: HWND,
351 wparam: WPARAM,
352 lparam: LPARAM,
353 state_ptr: Rc<WindowsWindowStatePtr>,
354) -> Option<isize> {
355 let mut lock = state_ptr.state.borrow_mut();
356 let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
357 PlatformInput::KeyDown(KeyDownEvent {
358 keystroke,
359 is_held: lparam.0 & (0x1 << 30) > 0,
360 })
361 })?;
362 let mut func = lock.callbacks.input.take()?;
363 drop(lock);
364
365 let handled = !func(input).propagate;
366
367 let mut lock = state_ptr.state.borrow_mut();
368 lock.callbacks.input = Some(func);
369
370 if handled {
371 lock.system_key_handled = true;
372 Some(0)
373 } else {
374 // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
375 // shortcuts.
376 None
377 }
378}
379
380fn handle_syskeyup_msg(
381 handle: HWND,
382 wparam: WPARAM,
383 lparam: LPARAM,
384 state_ptr: Rc<WindowsWindowStatePtr>,
385) -> Option<isize> {
386 let mut lock = state_ptr.state.borrow_mut();
387 let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
388 PlatformInput::KeyUp(KeyUpEvent { keystroke })
389 })?;
390 let mut func = lock.callbacks.input.take()?;
391 drop(lock);
392 func(input);
393 state_ptr.state.borrow_mut().callbacks.input = Some(func);
394
395 // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.
396 Some(0)
397}
398
399// It's a known bug that you can't trigger `ctrl-shift-0`. See:
400// https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers
401fn handle_keydown_msg(
402 handle: HWND,
403 wparam: WPARAM,
404 lparam: LPARAM,
405 state_ptr: Rc<WindowsWindowStatePtr>,
406) -> Option<isize> {
407 let mut lock = state_ptr.state.borrow_mut();
408 let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
409 PlatformInput::KeyDown(KeyDownEvent {
410 keystroke,
411 is_held: lparam.0 & (0x1 << 30) > 0,
412 })
413 }) else {
414 return Some(1);
415 };
416 drop(lock);
417
418 let is_composing = with_input_handler(&state_ptr, |input_handler| {
419 input_handler.marked_text_range()
420 })
421 .flatten()
422 .is_some();
423 if is_composing {
424 translate_message(handle, wparam, lparam);
425 return Some(0);
426 }
427
428 let Some(mut func) = state_ptr.state.borrow_mut().callbacks.input.take() else {
429 return Some(1);
430 };
431
432 let handled = !func(input).propagate;
433
434 state_ptr.state.borrow_mut().callbacks.input = Some(func);
435
436 if handled {
437 Some(0)
438 } else {
439 translate_message(handle, wparam, lparam);
440 Some(1)
441 }
442}
443
444fn handle_keyup_msg(
445 handle: HWND,
446 wparam: WPARAM,
447 lparam: LPARAM,
448 state_ptr: Rc<WindowsWindowStatePtr>,
449) -> Option<isize> {
450 let mut lock = state_ptr.state.borrow_mut();
451 let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
452 PlatformInput::KeyUp(KeyUpEvent { keystroke })
453 }) else {
454 return Some(1);
455 };
456
457 let Some(mut func) = lock.callbacks.input.take() else {
458 return Some(1);
459 };
460 drop(lock);
461
462 let handled = !func(input).propagate;
463 state_ptr.state.borrow_mut().callbacks.input = Some(func);
464
465 if handled { Some(0) } else { Some(1) }
466}
467
468fn handle_char_msg(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
469 let Some(input) = char::from_u32(wparam.0 as u32)
470 .filter(|c| !c.is_control())
471 .map(String::from)
472 else {
473 return Some(1);
474 };
475 with_input_handler(&state_ptr, |input_handler| {
476 input_handler.replace_text_in_range(None, &input);
477 });
478
479 Some(0)
480}
481
482fn handle_dead_char_msg(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
483 let ch = char::from_u32(wparam.0 as u32)?.to_string();
484 with_input_handler(&state_ptr, |input_handler| {
485 input_handler.replace_and_mark_text_in_range(None, &ch, None);
486 });
487 None
488}
489
490fn handle_mouse_down_msg(
491 handle: HWND,
492 button: MouseButton,
493 lparam: LPARAM,
494 state_ptr: Rc<WindowsWindowStatePtr>,
495) -> Option<isize> {
496 unsafe { SetCapture(handle) };
497 let mut lock = state_ptr.state.borrow_mut();
498 let Some(mut func) = lock.callbacks.input.take() else {
499 return Some(1);
500 };
501 let x = lparam.signed_loword();
502 let y = lparam.signed_hiword();
503 let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
504 let click_count = lock.click_state.update(button, physical_point);
505 let scale_factor = lock.scale_factor;
506 drop(lock);
507
508 let input = PlatformInput::MouseDown(MouseDownEvent {
509 button,
510 position: logical_point(x as f32, y as f32, scale_factor),
511 modifiers: current_modifiers(),
512 click_count,
513 first_mouse: false,
514 });
515 let handled = !func(input).propagate;
516 state_ptr.state.borrow_mut().callbacks.input = Some(func);
517
518 if handled { Some(0) } else { Some(1) }
519}
520
521fn handle_mouse_up_msg(
522 _handle: HWND,
523 button: MouseButton,
524 lparam: LPARAM,
525 state_ptr: Rc<WindowsWindowStatePtr>,
526) -> Option<isize> {
527 unsafe { ReleaseCapture().log_err() };
528 let mut lock = state_ptr.state.borrow_mut();
529 let Some(mut func) = lock.callbacks.input.take() else {
530 return Some(1);
531 };
532 let x = lparam.signed_loword() as f32;
533 let y = lparam.signed_hiword() as f32;
534 let click_count = lock.click_state.current_count;
535 let scale_factor = lock.scale_factor;
536 drop(lock);
537
538 let input = PlatformInput::MouseUp(MouseUpEvent {
539 button,
540 position: logical_point(x, y, scale_factor),
541 modifiers: current_modifiers(),
542 click_count,
543 });
544 let handled = !func(input).propagate;
545 state_ptr.state.borrow_mut().callbacks.input = Some(func);
546
547 if handled { Some(0) } else { Some(1) }
548}
549
550fn handle_xbutton_msg(
551 handle: HWND,
552 wparam: WPARAM,
553 lparam: LPARAM,
554 handler: impl Fn(HWND, MouseButton, LPARAM, Rc<WindowsWindowStatePtr>) -> Option<isize>,
555 state_ptr: Rc<WindowsWindowStatePtr>,
556) -> Option<isize> {
557 let nav_dir = match wparam.hiword() {
558 XBUTTON1 => NavigationDirection::Back,
559 XBUTTON2 => NavigationDirection::Forward,
560 _ => return Some(1),
561 };
562 handler(handle, MouseButton::Navigate(nav_dir), lparam, state_ptr)
563}
564
565fn handle_mouse_wheel_msg(
566 handle: HWND,
567 wparam: WPARAM,
568 lparam: LPARAM,
569 state_ptr: Rc<WindowsWindowStatePtr>,
570) -> Option<isize> {
571 let modifiers = current_modifiers();
572 let mut lock = state_ptr.state.borrow_mut();
573 let Some(mut func) = lock.callbacks.input.take() else {
574 return Some(1);
575 };
576 let scale_factor = lock.scale_factor;
577 let wheel_scroll_amount = match modifiers.shift {
578 true => lock.system_settings.mouse_wheel_settings.wheel_scroll_chars,
579 false => lock.system_settings.mouse_wheel_settings.wheel_scroll_lines,
580 };
581 drop(lock);
582
583 let wheel_distance =
584 (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
585 let mut cursor_point = POINT {
586 x: lparam.signed_loword().into(),
587 y: lparam.signed_hiword().into(),
588 };
589 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
590 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
591 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
592 delta: ScrollDelta::Lines(match modifiers.shift {
593 true => Point {
594 x: wheel_distance,
595 y: 0.0,
596 },
597 false => Point {
598 y: wheel_distance,
599 x: 0.0,
600 },
601 }),
602 modifiers,
603 touch_phase: TouchPhase::Moved,
604 });
605 let handled = !func(input).propagate;
606 state_ptr.state.borrow_mut().callbacks.input = Some(func);
607
608 if handled { Some(0) } else { Some(1) }
609}
610
611fn handle_mouse_horizontal_wheel_msg(
612 handle: HWND,
613 wparam: WPARAM,
614 lparam: LPARAM,
615 state_ptr: Rc<WindowsWindowStatePtr>,
616) -> Option<isize> {
617 let mut lock = state_ptr.state.borrow_mut();
618 let Some(mut func) = lock.callbacks.input.take() else {
619 return Some(1);
620 };
621 let scale_factor = lock.scale_factor;
622 let wheel_scroll_chars = lock.system_settings.mouse_wheel_settings.wheel_scroll_chars;
623 drop(lock);
624
625 let wheel_distance =
626 (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
627 let mut cursor_point = POINT {
628 x: lparam.signed_loword().into(),
629 y: lparam.signed_hiword().into(),
630 };
631 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
632 let event = PlatformInput::ScrollWheel(ScrollWheelEvent {
633 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
634 delta: ScrollDelta::Lines(Point {
635 x: wheel_distance,
636 y: 0.0,
637 }),
638 modifiers: current_modifiers(),
639 touch_phase: TouchPhase::Moved,
640 });
641 let handled = !func(event).propagate;
642 state_ptr.state.borrow_mut().callbacks.input = Some(func);
643
644 if handled { Some(0) } else { Some(1) }
645}
646
647fn retrieve_caret_position(state_ptr: &Rc<WindowsWindowStatePtr>) -> Option<POINT> {
648 with_input_handler_and_scale_factor(state_ptr, |input_handler, scale_factor| {
649 let caret_range = input_handler.selected_text_range(false)?;
650 let caret_position = input_handler.bounds_for_range(caret_range.range)?;
651 Some(POINT {
652 // logical to physical
653 x: (caret_position.origin.x.0 * scale_factor) as i32,
654 y: (caret_position.origin.y.0 * scale_factor) as i32
655 + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
656 })
657 })
658}
659
660fn handle_ime_position(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
661 unsafe {
662 let ctx = ImmGetContext(handle);
663
664 let Some(caret_position) = retrieve_caret_position(&state_ptr) else {
665 return Some(0);
666 };
667 {
668 let config = COMPOSITIONFORM {
669 dwStyle: CFS_POINT,
670 ptCurrentPos: caret_position,
671 ..Default::default()
672 };
673 ImmSetCompositionWindow(ctx, &config as _).ok().log_err();
674 }
675 {
676 let config = CANDIDATEFORM {
677 dwStyle: CFS_CANDIDATEPOS,
678 ptCurrentPos: caret_position,
679 ..Default::default()
680 };
681 ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
682 }
683 ImmReleaseContext(handle, ctx).ok().log_err();
684 Some(0)
685 }
686}
687
688fn handle_ime_composition(
689 handle: HWND,
690 lparam: LPARAM,
691 state_ptr: Rc<WindowsWindowStatePtr>,
692) -> Option<isize> {
693 let ctx = unsafe { ImmGetContext(handle) };
694 let result = handle_ime_composition_inner(ctx, lparam, state_ptr);
695 unsafe { ImmReleaseContext(handle, ctx).ok().log_err() };
696 result
697}
698
699fn handle_ime_composition_inner(
700 ctx: HIMC,
701 lparam: LPARAM,
702 state_ptr: Rc<WindowsWindowStatePtr>,
703) -> Option<isize> {
704 let lparam = lparam.0 as u32;
705 if lparam == 0 {
706 // Japanese IME may send this message with lparam = 0, which indicates that
707 // there is no composition string.
708 with_input_handler(&state_ptr, |input_handler| {
709 input_handler.replace_text_in_range(None, "");
710 })?;
711 Some(0)
712 } else {
713 if lparam & GCS_COMPSTR.0 > 0 {
714 let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
715 let caret_pos = (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
716 let pos = retrieve_composition_cursor_position(ctx);
717 pos..pos
718 });
719 with_input_handler(&state_ptr, |input_handler| {
720 input_handler.replace_and_mark_text_in_range(None, &comp_string, caret_pos);
721 })?;
722 }
723 if lparam & GCS_RESULTSTR.0 > 0 {
724 let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
725 with_input_handler(&state_ptr, |input_handler| {
726 input_handler.replace_text_in_range(None, &comp_result);
727 })?;
728 return Some(0);
729 }
730
731 // currently, we don't care other stuff
732 None
733 }
734}
735
736/// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
737fn handle_calc_client_size(
738 handle: HWND,
739 wparam: WPARAM,
740 lparam: LPARAM,
741 state_ptr: Rc<WindowsWindowStatePtr>,
742) -> Option<isize> {
743 if !state_ptr.hide_title_bar || state_ptr.state.borrow().is_fullscreen() || wparam.0 == 0 {
744 return None;
745 }
746
747 let is_maximized = state_ptr.state.borrow().is_maximized();
748 let insets = get_client_area_insets(handle, is_maximized, state_ptr.windows_version);
749 // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
750 let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
751 let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
752
753 requested_client_rect[0].left += insets.left;
754 requested_client_rect[0].top += insets.top;
755 requested_client_rect[0].right -= insets.right;
756 requested_client_rect[0].bottom -= insets.bottom;
757
758 // Fix auto hide taskbar not showing. This solution is based on the approach
759 // used by Chrome. However, it may result in one row of pixels being obscured
760 // in our client area. But as Chrome says, "there seems to be no better solution."
761 if is_maximized {
762 if let Some(ref taskbar_position) = state_ptr
763 .state
764 .borrow()
765 .system_settings
766 .auto_hide_taskbar_position
767 {
768 // Fot the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
769 // so the window isn't treated as a "fullscreen app", which would cause
770 // the taskbar to disappear.
771 match taskbar_position {
772 AutoHideTaskbarPosition::Left => {
773 requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
774 }
775 AutoHideTaskbarPosition::Top => {
776 requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
777 }
778 AutoHideTaskbarPosition::Right => {
779 requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
780 }
781 AutoHideTaskbarPosition::Bottom => {
782 requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
783 }
784 }
785 }
786 }
787
788 Some(0)
789}
790
791fn handle_activate_msg(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
792 let activated = wparam.loword() > 0;
793 let this = state_ptr.clone();
794 state_ptr
795 .executor
796 .spawn(async move {
797 let mut lock = this.state.borrow_mut();
798 if let Some(mut func) = lock.callbacks.active_status_change.take() {
799 drop(lock);
800 func(activated);
801 this.state.borrow_mut().callbacks.active_status_change = Some(func);
802 }
803 })
804 .detach();
805
806 None
807}
808
809fn handle_create_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
810 if state_ptr.hide_title_bar {
811 notify_frame_changed(handle);
812 Some(0)
813 } else {
814 None
815 }
816}
817
818fn handle_dpi_changed_msg(
819 handle: HWND,
820 wparam: WPARAM,
821 lparam: LPARAM,
822 state_ptr: Rc<WindowsWindowStatePtr>,
823) -> Option<isize> {
824 let new_dpi = wparam.loword() as f32;
825 let mut lock = state_ptr.state.borrow_mut();
826 lock.scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
827 lock.border_offset.update(handle).log_err();
828 drop(lock);
829
830 let rect = unsafe { &*(lparam.0 as *const RECT) };
831 let width = rect.right - rect.left;
832 let height = rect.bottom - rect.top;
833 // this will emit `WM_SIZE` and `WM_MOVE` right here
834 // even before this function returns
835 // the new size is handled in `WM_SIZE`
836 unsafe {
837 SetWindowPos(
838 handle,
839 None,
840 rect.left,
841 rect.top,
842 width,
843 height,
844 SWP_NOZORDER | SWP_NOACTIVATE,
845 )
846 .context("unable to set window position after dpi has changed")
847 .log_err();
848 }
849
850 Some(0)
851}
852
853/// The following conditions will trigger this event:
854/// 1. The monitor on which the window is located goes offline or changes resolution.
855/// 2. Another monitor goes offline, is plugged in, or changes resolution.
856///
857/// In either case, the window will only receive information from the monitor on which
858/// it is located.
859///
860/// For example, in the case of condition 2, where the monitor on which the window is
861/// located has actually changed nothing, it will still receive this event.
862fn handle_display_change_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
863 // NOTE:
864 // Even the `lParam` holds the resolution of the screen, we just ignore it.
865 // Because WM_DPICHANGED, WM_MOVE, WM_SIZE will come first, window reposition and resize
866 // are handled there.
867 // So we only care about if monitor is disconnected.
868 let previous_monitor = state_ptr.state.borrow().display;
869 if WindowsDisplay::is_connected(previous_monitor.handle) {
870 // we are fine, other display changed
871 return None;
872 }
873 // display disconnected
874 // in this case, the OS will move our window to another monitor, and minimize it.
875 // we deminimize the window and query the monitor after moving
876 unsafe {
877 let _ = ShowWindow(handle, SW_SHOWNORMAL);
878 };
879 let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
880 // all monitors disconnected
881 if new_monitor.is_invalid() {
882 log::error!("No monitor detected!");
883 return None;
884 }
885 let new_display = WindowsDisplay::new_with_handle(new_monitor);
886 state_ptr.state.borrow_mut().display = new_display;
887 Some(0)
888}
889
890fn handle_hit_test_msg(
891 handle: HWND,
892 msg: u32,
893 wparam: WPARAM,
894 lparam: LPARAM,
895 state_ptr: Rc<WindowsWindowStatePtr>,
896) -> Option<isize> {
897 if !state_ptr.is_movable || state_ptr.state.borrow().is_fullscreen() {
898 return None;
899 }
900
901 let mut lock = state_ptr.state.borrow_mut();
902 if let Some(mut callback) = lock.callbacks.hit_test_window_control.take() {
903 drop(lock);
904 let area = callback();
905 state_ptr
906 .state
907 .borrow_mut()
908 .callbacks
909 .hit_test_window_control = Some(callback);
910 if let Some(area) = area {
911 return match area {
912 WindowControlArea::Drag => Some(HTCAPTION as _),
913 WindowControlArea::Close => Some(HTCLOSE as _),
914 WindowControlArea::Max => Some(HTMAXBUTTON as _),
915 WindowControlArea::Min => Some(HTMINBUTTON as _),
916 };
917 }
918 } else {
919 drop(lock);
920 }
921
922 if !state_ptr.hide_title_bar {
923 // If the OS draws the title bar, we don't need to handle hit test messages.
924 return None;
925 }
926
927 // default handler for resize areas
928 let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
929 if matches!(
930 hit.0 as u32,
931 HTNOWHERE
932 | HTRIGHT
933 | HTLEFT
934 | HTTOPLEFT
935 | HTTOP
936 | HTTOPRIGHT
937 | HTBOTTOMRIGHT
938 | HTBOTTOM
939 | HTBOTTOMLEFT
940 ) {
941 return Some(hit.0);
942 }
943
944 if state_ptr.state.borrow().is_fullscreen() {
945 return Some(HTCLIENT as _);
946 }
947
948 let dpi = unsafe { GetDpiForWindow(handle) };
949 let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
950
951 let mut cursor_point = POINT {
952 x: lparam.signed_loword().into(),
953 y: lparam.signed_hiword().into(),
954 };
955 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
956 if !state_ptr.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y
957 {
958 return Some(HTTOP as _);
959 }
960
961 Some(HTCLIENT as _)
962}
963
964fn handle_nc_mouse_move_msg(
965 handle: HWND,
966 lparam: LPARAM,
967 state_ptr: Rc<WindowsWindowStatePtr>,
968) -> Option<isize> {
969 start_tracking_mouse(handle, &state_ptr, TME_LEAVE | TME_NONCLIENT);
970
971 let mut lock = state_ptr.state.borrow_mut();
972 let mut func = lock.callbacks.input.take()?;
973 let scale_factor = lock.scale_factor;
974 drop(lock);
975
976 let mut cursor_point = POINT {
977 x: lparam.signed_loword().into(),
978 y: lparam.signed_hiword().into(),
979 };
980 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
981 let input = PlatformInput::MouseMove(MouseMoveEvent {
982 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
983 pressed_button: None,
984 modifiers: current_modifiers(),
985 });
986 let handled = !func(input).propagate;
987 state_ptr.state.borrow_mut().callbacks.input = Some(func);
988
989 if handled { Some(0) } else { None }
990}
991
992fn handle_nc_mouse_down_msg(
993 handle: HWND,
994 button: MouseButton,
995 wparam: WPARAM,
996 lparam: LPARAM,
997 state_ptr: Rc<WindowsWindowStatePtr>,
998) -> Option<isize> {
999 let mut lock = state_ptr.state.borrow_mut();
1000 if let Some(mut func) = lock.callbacks.input.take() {
1001 let scale_factor = lock.scale_factor;
1002 let mut cursor_point = POINT {
1003 x: lparam.signed_loword().into(),
1004 y: lparam.signed_hiword().into(),
1005 };
1006 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1007 let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
1008 let click_count = lock.click_state.update(button, physical_point);
1009 drop(lock);
1010
1011 let input = PlatformInput::MouseDown(MouseDownEvent {
1012 button,
1013 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1014 modifiers: current_modifiers(),
1015 click_count,
1016 first_mouse: false,
1017 });
1018 let result = func(input.clone());
1019 let handled = !result.propagate || result.default_prevented;
1020 state_ptr.state.borrow_mut().callbacks.input = Some(func);
1021
1022 if handled {
1023 return Some(0);
1024 }
1025 } else {
1026 drop(lock);
1027 };
1028
1029 // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
1030 if button == MouseButton::Left {
1031 match wparam.0 as u32 {
1032 HTMINBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
1033 HTMAXBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
1034 HTCLOSE => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
1035 _ => return None,
1036 };
1037 Some(0)
1038 } else {
1039 None
1040 }
1041}
1042
1043fn handle_nc_mouse_up_msg(
1044 handle: HWND,
1045 button: MouseButton,
1046 wparam: WPARAM,
1047 lparam: LPARAM,
1048 state_ptr: Rc<WindowsWindowStatePtr>,
1049) -> Option<isize> {
1050 let mut lock = state_ptr.state.borrow_mut();
1051 if let Some(mut func) = lock.callbacks.input.take() {
1052 let scale_factor = lock.scale_factor;
1053 drop(lock);
1054
1055 let mut cursor_point = POINT {
1056 x: lparam.signed_loword().into(),
1057 y: lparam.signed_hiword().into(),
1058 };
1059 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1060 let input = PlatformInput::MouseUp(MouseUpEvent {
1061 button,
1062 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1063 modifiers: current_modifiers(),
1064 click_count: 1,
1065 });
1066 let handled = !func(input).propagate;
1067 state_ptr.state.borrow_mut().callbacks.input = Some(func);
1068
1069 if handled {
1070 return Some(0);
1071 }
1072 } else {
1073 drop(lock);
1074 }
1075
1076 let last_pressed = state_ptr.state.borrow_mut().nc_button_pressed.take();
1077 if button == MouseButton::Left && last_pressed.is_some() {
1078 let handled = match (wparam.0 as u32, last_pressed.unwrap()) {
1079 (HTMINBUTTON, HTMINBUTTON) => {
1080 unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1081 true
1082 }
1083 (HTMAXBUTTON, HTMAXBUTTON) => {
1084 if state_ptr.state.borrow().is_maximized() {
1085 unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1086 } else {
1087 unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1088 }
1089 true
1090 }
1091 (HTCLOSE, HTCLOSE) => {
1092 unsafe {
1093 PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1094 .log_err()
1095 };
1096 true
1097 }
1098 _ => false,
1099 };
1100 if handled {
1101 return Some(0);
1102 }
1103 }
1104
1105 None
1106}
1107
1108fn handle_cursor_changed(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1109 let mut state = state_ptr.state.borrow_mut();
1110 let had_cursor = state.current_cursor.is_some();
1111
1112 state.current_cursor = if lparam.0 == 0 {
1113 None
1114 } else {
1115 Some(HCURSOR(lparam.0 as _))
1116 };
1117
1118 if had_cursor != state.current_cursor.is_some() {
1119 unsafe { SetCursor(state.current_cursor) };
1120 }
1121
1122 Some(0)
1123}
1124
1125fn handle_set_cursor(
1126 handle: HWND,
1127 lparam: LPARAM,
1128 state_ptr: Rc<WindowsWindowStatePtr>,
1129) -> Option<isize> {
1130 if unsafe { !IsWindowEnabled(handle).as_bool() }
1131 || matches!(
1132 lparam.loword() as u32,
1133 HTLEFT
1134 | HTRIGHT
1135 | HTTOP
1136 | HTTOPLEFT
1137 | HTTOPRIGHT
1138 | HTBOTTOM
1139 | HTBOTTOMLEFT
1140 | HTBOTTOMRIGHT
1141 )
1142 {
1143 return None;
1144 }
1145 unsafe {
1146 SetCursor(state_ptr.state.borrow().current_cursor);
1147 };
1148 Some(1)
1149}
1150
1151fn handle_system_settings_changed(
1152 handle: HWND,
1153 lparam: LPARAM,
1154 state_ptr: Rc<WindowsWindowStatePtr>,
1155) -> Option<isize> {
1156 let mut lock = state_ptr.state.borrow_mut();
1157 let display = lock.display;
1158 // system settings
1159 lock.system_settings.update(display);
1160 // mouse double click
1161 lock.click_state.system_update();
1162 // window border offset
1163 lock.border_offset.update(handle).log_err();
1164 drop(lock);
1165
1166 // lParam is a pointer to a string that indicates the area containing the system parameter
1167 // that was changed.
1168 let parameter = PCWSTR::from_raw(lparam.0 as _);
1169 if unsafe { !parameter.is_null() && !parameter.is_empty() } {
1170 if let Some(parameter_string) = unsafe { parameter.to_string() }.log_err() {
1171 log::info!("System settings changed: {}", parameter_string);
1172 match parameter_string.as_str() {
1173 "ImmersiveColorSet" => {
1174 handle_system_theme_changed(handle, state_ptr);
1175 }
1176 _ => {}
1177 }
1178 }
1179 }
1180
1181 // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1182 // taskbar correctly.
1183 notify_frame_changed(handle);
1184 Some(0)
1185}
1186
1187fn handle_system_command(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1188 if wparam.0 == SC_KEYMENU as usize {
1189 let mut lock = state_ptr.state.borrow_mut();
1190 if lock.system_key_handled {
1191 lock.system_key_handled = false;
1192 return Some(0);
1193 }
1194 }
1195 None
1196}
1197
1198fn handle_system_theme_changed(
1199 handle: HWND,
1200 state_ptr: Rc<WindowsWindowStatePtr>,
1201) -> Option<isize> {
1202 let mut callback = state_ptr
1203 .state
1204 .borrow_mut()
1205 .callbacks
1206 .appearance_changed
1207 .take()?;
1208 callback();
1209 state_ptr.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1210 configure_dwm_dark_mode(handle);
1211 Some(0)
1212}
1213
1214fn handle_input_language_changed(
1215 lparam: LPARAM,
1216 state_ptr: Rc<WindowsWindowStatePtr>,
1217) -> Option<isize> {
1218 let thread = state_ptr.main_thread_id_win32;
1219 let validation = state_ptr.validation_number;
1220 unsafe {
1221 PostThreadMessageW(thread, WM_INPUTLANGCHANGE, WPARAM(validation), lparam).log_err();
1222 }
1223 Some(0)
1224}
1225
1226#[inline]
1227fn translate_message(handle: HWND, wparam: WPARAM, lparam: LPARAM) {
1228 let msg = MSG {
1229 hwnd: handle,
1230 message: WM_KEYDOWN,
1231 wParam: wparam,
1232 lParam: lparam,
1233 // It seems like leaving the following two parameters empty doesn't break key events, they still work as expected.
1234 // But if any bugs pop up after this PR, this is probably the place to look first.
1235 time: 0,
1236 pt: POINT::default(),
1237 };
1238 unsafe { TranslateMessage(&msg).ok().log_err() };
1239}
1240
1241fn handle_key_event<F>(
1242 handle: HWND,
1243 wparam: WPARAM,
1244 lparam: LPARAM,
1245 state: &mut WindowsWindowState,
1246 f: F,
1247) -> Option<PlatformInput>
1248where
1249 F: FnOnce(Keystroke) -> PlatformInput,
1250{
1251 let virtual_key = VIRTUAL_KEY(wparam.loword());
1252 let mut modifiers = current_modifiers();
1253
1254 match virtual_key {
1255 VK_SHIFT | VK_CONTROL | VK_MENU | VK_LWIN | VK_RWIN => {
1256 if state
1257 .last_reported_modifiers
1258 .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1259 {
1260 return None;
1261 }
1262 state.last_reported_modifiers = Some(modifiers);
1263 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1264 modifiers,
1265 capslock: current_capslock(),
1266 }))
1267 }
1268 VK_CAPITAL => {
1269 let capslock = current_capslock();
1270 if state
1271 .last_reported_capslock
1272 .is_some_and(|prev_capslock| prev_capslock == capslock)
1273 {
1274 return None;
1275 }
1276 state.last_reported_capslock = Some(capslock);
1277 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1278 modifiers,
1279 capslock,
1280 }))
1281 }
1282 vkey => {
1283 let vkey = if vkey == VK_PROCESSKEY {
1284 VIRTUAL_KEY(unsafe { ImmGetVirtualKey(handle) } as u16)
1285 } else {
1286 vkey
1287 };
1288 let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1289 Some(f(keystroke))
1290 }
1291 }
1292}
1293
1294fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1295 Some(
1296 match vkey {
1297 VK_SPACE => "space",
1298 VK_BACK => "backspace",
1299 VK_RETURN => "enter",
1300 VK_TAB => "tab",
1301 VK_UP => "up",
1302 VK_DOWN => "down",
1303 VK_RIGHT => "right",
1304 VK_LEFT => "left",
1305 VK_HOME => "home",
1306 VK_END => "end",
1307 VK_PRIOR => "pageup",
1308 VK_NEXT => "pagedown",
1309 VK_BROWSER_BACK => "back",
1310 VK_BROWSER_FORWARD => "forward",
1311 VK_ESCAPE => "escape",
1312 VK_INSERT => "insert",
1313 VK_DELETE => "delete",
1314 VK_APPS => "menu",
1315 VK_F1 => "f1",
1316 VK_F2 => "f2",
1317 VK_F3 => "f3",
1318 VK_F4 => "f4",
1319 VK_F5 => "f5",
1320 VK_F6 => "f6",
1321 VK_F7 => "f7",
1322 VK_F8 => "f8",
1323 VK_F9 => "f9",
1324 VK_F10 => "f10",
1325 VK_F11 => "f11",
1326 VK_F12 => "f12",
1327 VK_F13 => "f13",
1328 VK_F14 => "f14",
1329 VK_F15 => "f15",
1330 VK_F16 => "f16",
1331 VK_F17 => "f17",
1332 VK_F18 => "f18",
1333 VK_F19 => "f19",
1334 VK_F20 => "f20",
1335 VK_F21 => "f21",
1336 VK_F22 => "f22",
1337 VK_F23 => "f23",
1338 VK_F24 => "f24",
1339 _ => return None,
1340 }
1341 .to_string(),
1342 )
1343}
1344
1345fn parse_normal_key(
1346 vkey: VIRTUAL_KEY,
1347 lparam: LPARAM,
1348 mut modifiers: Modifiers,
1349) -> Option<Keystroke> {
1350 let mut key_char = None;
1351 let key = parse_immutable(vkey).or_else(|| {
1352 let scan_code = lparam.hiword() & 0xFF;
1353 key_char = generate_key_char(
1354 vkey,
1355 scan_code as u32,
1356 modifiers.control,
1357 modifiers.shift,
1358 modifiers.alt,
1359 );
1360 get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1361 })?;
1362 Some(Keystroke {
1363 modifiers,
1364 key,
1365 key_char,
1366 })
1367}
1368
1369fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1370 unsafe {
1371 let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1372 if string_len >= 0 {
1373 let mut buffer = vec![0u8; string_len as usize + 2];
1374 ImmGetCompositionStringW(
1375 ctx,
1376 comp_type,
1377 Some(buffer.as_mut_ptr() as _),
1378 string_len as _,
1379 );
1380 let wstring = std::slice::from_raw_parts::<u16>(
1381 buffer.as_mut_ptr().cast::<u16>(),
1382 string_len as usize / 2,
1383 );
1384 Some(String::from_utf16_lossy(wstring))
1385 } else {
1386 None
1387 }
1388 }
1389}
1390
1391#[inline]
1392fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1393 unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1394}
1395
1396#[inline]
1397fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1398 unsafe { GetKeyState(vkey.0 as i32) < 0 }
1399}
1400
1401#[inline]
1402pub(crate) fn current_modifiers() -> Modifiers {
1403 Modifiers {
1404 control: is_virtual_key_pressed(VK_CONTROL),
1405 alt: is_virtual_key_pressed(VK_MENU),
1406 shift: is_virtual_key_pressed(VK_SHIFT),
1407 platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1408 function: false,
1409 }
1410}
1411
1412#[inline]
1413pub(crate) fn current_capslock() -> Capslock {
1414 let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1415 Capslock { on: on }
1416}
1417
1418fn get_client_area_insets(
1419 handle: HWND,
1420 is_maximized: bool,
1421 windows_version: WindowsVersion,
1422) -> RECT {
1423 // For maximized windows, Windows outdents the window rect from the screen's client rect
1424 // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1425 // on all sides (including the top) to avoid the client area extending onto adjacent
1426 // monitors.
1427 //
1428 // For non-maximized windows, things become complicated:
1429 //
1430 // - On Windows 10
1431 // The top inset must be zero, since if there is any nonclient area, Windows will draw
1432 // a full native titlebar outside the client area. (This doesn't occur in the maximized
1433 // case.)
1434 //
1435 // - On Windows 11
1436 // The top inset is calculated using an empirical formula that I derived through various
1437 // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1438 let dpi = unsafe { GetDpiForWindow(handle) };
1439 let frame_thickness = get_frame_thickness(dpi);
1440 let top_insets = if is_maximized {
1441 frame_thickness
1442 } else {
1443 match windows_version {
1444 WindowsVersion::Win10 => 0,
1445 WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1446 }
1447 };
1448 RECT {
1449 left: frame_thickness,
1450 top: top_insets,
1451 right: frame_thickness,
1452 bottom: frame_thickness,
1453 }
1454}
1455
1456// there is some additional non-visible space when talking about window
1457// borders on Windows:
1458// - SM_CXSIZEFRAME: The resize handle.
1459// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1460fn get_frame_thickness(dpi: u32) -> i32 {
1461 let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1462 let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1463 resize_frame_thickness + padding_thickness
1464}
1465
1466fn notify_frame_changed(handle: HWND) {
1467 unsafe {
1468 SetWindowPos(
1469 handle,
1470 None,
1471 0,
1472 0,
1473 0,
1474 0,
1475 SWP_FRAMECHANGED
1476 | SWP_NOACTIVATE
1477 | SWP_NOCOPYBITS
1478 | SWP_NOMOVE
1479 | SWP_NOOWNERZORDER
1480 | SWP_NOREPOSITION
1481 | SWP_NOSENDCHANGING
1482 | SWP_NOSIZE
1483 | SWP_NOZORDER,
1484 )
1485 .log_err();
1486 }
1487}
1488
1489fn start_tracking_mouse(
1490 handle: HWND,
1491 state_ptr: &Rc<WindowsWindowStatePtr>,
1492 flags: TRACKMOUSEEVENT_FLAGS,
1493) {
1494 let mut lock = state_ptr.state.borrow_mut();
1495 if !lock.hovered {
1496 lock.hovered = true;
1497 unsafe {
1498 TrackMouseEvent(&mut TRACKMOUSEEVENT {
1499 cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1500 dwFlags: flags,
1501 hwndTrack: handle,
1502 dwHoverTime: HOVER_DEFAULT,
1503 })
1504 .log_err()
1505 };
1506 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1507 drop(lock);
1508 callback(true);
1509 state_ptr.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1510 }
1511 }
1512}
1513
1514fn with_input_handler<F, R>(state_ptr: &Rc<WindowsWindowStatePtr>, f: F) -> Option<R>
1515where
1516 F: FnOnce(&mut PlatformInputHandler) -> R,
1517{
1518 let mut input_handler = state_ptr.state.borrow_mut().input_handler.take()?;
1519 let result = f(&mut input_handler);
1520 state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1521 Some(result)
1522}
1523
1524fn with_input_handler_and_scale_factor<F, R>(
1525 state_ptr: &Rc<WindowsWindowStatePtr>,
1526 f: F,
1527) -> Option<R>
1528where
1529 F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1530{
1531 let mut lock = state_ptr.state.borrow_mut();
1532 let mut input_handler = lock.input_handler.take()?;
1533 let scale_factor = lock.scale_factor;
1534 drop(lock);
1535 let result = f(&mut input_handler, scale_factor);
1536 state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1537 result
1538}