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