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