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