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 = parse_ime_compostion_string(ctx)?;
759 with_input_handler(&state_ptr, |input_handler| {
760 input_handler.replace_and_mark_text_in_range(None, &comp_string, None);
761 })?;
762 ime_input = Some(comp_string);
763 }
764 if lparam.0 as u32 & GCS_CURSORPOS.0 > 0 {
765 let comp_string = &ime_input?;
766 let caret_pos = retrieve_composition_cursor_position(ctx);
767 with_input_handler(&state_ptr, |input_handler| {
768 input_handler.replace_and_mark_text_in_range(
769 None,
770 comp_string,
771 Some(caret_pos..caret_pos),
772 );
773 })?;
774 }
775 if lparam.0 as u32 & GCS_RESULTSTR.0 > 0 {
776 let comp_result = parse_ime_compostion_result(ctx)?;
777 with_input_handler(&state_ptr, |input_handler| {
778 input_handler.replace_text_in_range(None, &comp_result);
779 })?;
780 return Some(0);
781 }
782 // currently, we don't care other stuff
783 None
784}
785
786/// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
787fn handle_calc_client_size(
788 handle: HWND,
789 wparam: WPARAM,
790 lparam: LPARAM,
791 state_ptr: Rc<WindowsWindowStatePtr>,
792) -> Option<isize> {
793 if !state_ptr.hide_title_bar || state_ptr.state.borrow().is_fullscreen() || wparam.0 == 0 {
794 return None;
795 }
796
797 let is_maximized = state_ptr.state.borrow().is_maximized();
798 let insets = get_client_area_insets(handle, is_maximized, state_ptr.windows_version);
799 // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
800 let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
801 let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
802
803 requested_client_rect[0].left += insets.left;
804 requested_client_rect[0].top += insets.top;
805 requested_client_rect[0].right -= insets.right;
806 requested_client_rect[0].bottom -= insets.bottom;
807
808 // Fix auto hide taskbar not showing. This solution is based on the approach
809 // used by Chrome. However, it may result in one row of pixels being obscured
810 // in our client area. But as Chrome says, "there seems to be no better solution."
811 if is_maximized {
812 if let Some(ref taskbar_position) = state_ptr
813 .state
814 .borrow()
815 .system_settings
816 .auto_hide_taskbar_position
817 {
818 // Fot the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
819 // so the window isn't treated as a "fullscreen app", which would cause
820 // the taskbar to disappear.
821 match taskbar_position {
822 AutoHideTaskbarPosition::Left => {
823 requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
824 }
825 AutoHideTaskbarPosition::Top => {
826 requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
827 }
828 AutoHideTaskbarPosition::Right => {
829 requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
830 }
831 AutoHideTaskbarPosition::Bottom => {
832 requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
833 }
834 }
835 }
836 }
837
838 Some(0)
839}
840
841fn handle_activate_msg(
842 handle: HWND,
843 wparam: WPARAM,
844 state_ptr: Rc<WindowsWindowStatePtr>,
845) -> Option<isize> {
846 let activated = wparam.loword() > 0;
847 if state_ptr.hide_title_bar {
848 if let Some(titlebar_rect) = state_ptr.state.borrow().get_titlebar_rect().log_err() {
849 unsafe {
850 InvalidateRect(Some(handle), Some(&titlebar_rect), false)
851 .ok()
852 .log_err()
853 };
854 }
855 }
856 let this = state_ptr.clone();
857 state_ptr
858 .executor
859 .spawn(async move {
860 let mut lock = this.state.borrow_mut();
861 if let Some(mut cb) = lock.callbacks.active_status_change.take() {
862 drop(lock);
863 cb(activated);
864 this.state.borrow_mut().callbacks.active_status_change = Some(cb);
865 }
866 })
867 .detach();
868
869 None
870}
871
872fn handle_create_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
873 if state_ptr.hide_title_bar {
874 notify_frame_changed(handle);
875 Some(0)
876 } else {
877 None
878 }
879}
880
881fn handle_dpi_changed_msg(
882 handle: HWND,
883 wparam: WPARAM,
884 lparam: LPARAM,
885 state_ptr: Rc<WindowsWindowStatePtr>,
886) -> Option<isize> {
887 let new_dpi = wparam.loword() as f32;
888 let mut lock = state_ptr.state.borrow_mut();
889 lock.scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
890 lock.border_offset.update(handle).log_err();
891 drop(lock);
892
893 let rect = unsafe { &*(lparam.0 as *const RECT) };
894 let width = rect.right - rect.left;
895 let height = rect.bottom - rect.top;
896 // this will emit `WM_SIZE` and `WM_MOVE` right here
897 // even before this function returns
898 // the new size is handled in `WM_SIZE`
899 unsafe {
900 SetWindowPos(
901 handle,
902 None,
903 rect.left,
904 rect.top,
905 width,
906 height,
907 SWP_NOZORDER | SWP_NOACTIVATE,
908 )
909 .context("unable to set window position after dpi has changed")
910 .log_err();
911 }
912
913 Some(0)
914}
915
916/// The following conditions will trigger this event:
917/// 1. The monitor on which the window is located goes offline or changes resolution.
918/// 2. Another monitor goes offline, is plugged in, or changes resolution.
919///
920/// In either case, the window will only receive information from the monitor on which
921/// it is located.
922///
923/// For example, in the case of condition 2, where the monitor on which the window is
924/// located has actually changed nothing, it will still receive this event.
925fn handle_display_change_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
926 // NOTE:
927 // Even the `lParam` holds the resolution of the screen, we just ignore it.
928 // Because WM_DPICHANGED, WM_MOVE, WM_SIZE will come first, window reposition and resize
929 // are handled there.
930 // So we only care about if monitor is disconnected.
931 let previous_monitor = state_ptr.as_ref().state.borrow().display;
932 if WindowsDisplay::is_connected(previous_monitor.handle) {
933 // we are fine, other display changed
934 return None;
935 }
936 // display disconnected
937 // in this case, the OS will move our window to another monitor, and minimize it.
938 // we deminimize the window and query the monitor after moving
939 unsafe {
940 let _ = ShowWindow(handle, SW_SHOWNORMAL);
941 };
942 let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
943 // all monitors disconnected
944 if new_monitor.is_invalid() {
945 log::error!("No monitor detected!");
946 return None;
947 }
948 let new_display = WindowsDisplay::new_with_handle(new_monitor);
949 state_ptr.as_ref().state.borrow_mut().display = new_display;
950 Some(0)
951}
952
953fn handle_hit_test_msg(
954 handle: HWND,
955 msg: u32,
956 wparam: WPARAM,
957 lparam: LPARAM,
958 state_ptr: Rc<WindowsWindowStatePtr>,
959) -> Option<isize> {
960 if !state_ptr.is_movable {
961 return None;
962 }
963 if !state_ptr.hide_title_bar {
964 return None;
965 }
966
967 // default handler for resize areas
968 let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
969 if matches!(
970 hit.0 as u32,
971 HTNOWHERE
972 | HTRIGHT
973 | HTLEFT
974 | HTTOPLEFT
975 | HTTOP
976 | HTTOPRIGHT
977 | HTBOTTOMRIGHT
978 | HTBOTTOM
979 | HTBOTTOMLEFT
980 ) {
981 return Some(hit.0);
982 }
983
984 if state_ptr.state.borrow().is_fullscreen() {
985 return Some(HTCLIENT as _);
986 }
987
988 let dpi = unsafe { GetDpiForWindow(handle) };
989 let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
990
991 let mut cursor_point = POINT {
992 x: lparam.signed_loword().into(),
993 y: lparam.signed_hiword().into(),
994 };
995 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
996 if !state_ptr.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y
997 {
998 return Some(HTTOP as _);
999 }
1000
1001 let titlebar_rect = state_ptr.state.borrow().get_titlebar_rect();
1002 if let Ok(titlebar_rect) = titlebar_rect {
1003 if cursor_point.y < titlebar_rect.bottom {
1004 let caption_btn_width = (state_ptr.state.borrow().caption_button_width().0
1005 * state_ptr.state.borrow().scale_factor) as i32;
1006 if cursor_point.x >= titlebar_rect.right - caption_btn_width {
1007 return Some(HTCLOSE as _);
1008 } else if cursor_point.x >= titlebar_rect.right - caption_btn_width * 2 {
1009 return Some(HTMAXBUTTON as _);
1010 } else if cursor_point.x >= titlebar_rect.right - caption_btn_width * 3 {
1011 return Some(HTMINBUTTON as _);
1012 }
1013
1014 return Some(HTCAPTION as _);
1015 }
1016 }
1017
1018 Some(HTCLIENT as _)
1019}
1020
1021fn handle_nc_mouse_move_msg(
1022 handle: HWND,
1023 lparam: LPARAM,
1024 state_ptr: Rc<WindowsWindowStatePtr>,
1025) -> Option<isize> {
1026 if !state_ptr.hide_title_bar {
1027 return None;
1028 }
1029
1030 start_tracking_mouse(handle, &state_ptr, TME_LEAVE | TME_NONCLIENT);
1031
1032 let mut lock = state_ptr.state.borrow_mut();
1033 if let Some(mut callback) = lock.callbacks.input.take() {
1034 let scale_factor = lock.scale_factor;
1035 drop(lock);
1036 let mut cursor_point = POINT {
1037 x: lparam.signed_loword().into(),
1038 y: lparam.signed_hiword().into(),
1039 };
1040 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1041 let event = MouseMoveEvent {
1042 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1043 pressed_button: None,
1044 modifiers: current_modifiers(),
1045 };
1046 let result = if callback(PlatformInput::MouseMove(event)).default_prevented {
1047 Some(0)
1048 } else {
1049 Some(1)
1050 };
1051 state_ptr.state.borrow_mut().callbacks.input = Some(callback);
1052
1053 result
1054 } else {
1055 None
1056 }
1057}
1058
1059fn handle_nc_mouse_down_msg(
1060 handle: HWND,
1061 button: MouseButton,
1062 wparam: WPARAM,
1063 lparam: LPARAM,
1064 state_ptr: Rc<WindowsWindowStatePtr>,
1065) -> Option<isize> {
1066 if !state_ptr.hide_title_bar {
1067 return None;
1068 }
1069
1070 let mut lock = state_ptr.state.borrow_mut();
1071 if let Some(mut callback) = lock.callbacks.input.take() {
1072 let scale_factor = lock.scale_factor;
1073 let mut cursor_point = POINT {
1074 x: lparam.signed_loword().into(),
1075 y: lparam.signed_hiword().into(),
1076 };
1077 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1078 let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
1079 let click_count = lock.click_state.update(button, physical_point);
1080 drop(lock);
1081 let event = MouseDownEvent {
1082 button,
1083 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1084 modifiers: current_modifiers(),
1085 click_count,
1086 first_mouse: false,
1087 };
1088 let result = if callback(PlatformInput::MouseDown(event)).default_prevented {
1089 Some(0)
1090 } else {
1091 None
1092 };
1093 state_ptr.state.borrow_mut().callbacks.input = Some(callback);
1094
1095 if result.is_some() {
1096 return result;
1097 }
1098 } else {
1099 drop(lock);
1100 };
1101
1102 // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
1103 if button == MouseButton::Left {
1104 match wparam.0 as u32 {
1105 HTMINBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
1106 HTMAXBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
1107 HTCLOSE => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
1108 _ => return None,
1109 };
1110 Some(0)
1111 } else {
1112 None
1113 }
1114}
1115
1116fn handle_nc_mouse_up_msg(
1117 handle: HWND,
1118 button: MouseButton,
1119 wparam: WPARAM,
1120 lparam: LPARAM,
1121 state_ptr: Rc<WindowsWindowStatePtr>,
1122) -> Option<isize> {
1123 if !state_ptr.hide_title_bar {
1124 return None;
1125 }
1126
1127 let mut lock = state_ptr.state.borrow_mut();
1128 if let Some(mut callback) = lock.callbacks.input.take() {
1129 let scale_factor = lock.scale_factor;
1130 drop(lock);
1131 let mut cursor_point = POINT {
1132 x: lparam.signed_loword().into(),
1133 y: lparam.signed_hiword().into(),
1134 };
1135 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1136 let event = MouseUpEvent {
1137 button,
1138 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1139 modifiers: current_modifiers(),
1140 click_count: 1,
1141 };
1142 let result = if callback(PlatformInput::MouseUp(event)).default_prevented {
1143 Some(0)
1144 } else {
1145 None
1146 };
1147 state_ptr.state.borrow_mut().callbacks.input = Some(callback);
1148 if result.is_some() {
1149 return result;
1150 }
1151 } else {
1152 drop(lock);
1153 }
1154
1155 let last_pressed = state_ptr.state.borrow_mut().nc_button_pressed.take();
1156 if button == MouseButton::Left && last_pressed.is_some() {
1157 let last_button = last_pressed.unwrap();
1158 let mut handled = false;
1159 match wparam.0 as u32 {
1160 HTMINBUTTON => {
1161 if last_button == HTMINBUTTON {
1162 unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1163 handled = true;
1164 }
1165 }
1166 HTMAXBUTTON => {
1167 if last_button == HTMAXBUTTON {
1168 if state_ptr.state.borrow().is_maximized() {
1169 unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1170 } else {
1171 unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1172 }
1173 handled = true;
1174 }
1175 }
1176 HTCLOSE => {
1177 if last_button == HTCLOSE {
1178 unsafe {
1179 PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1180 .log_err()
1181 };
1182 handled = true;
1183 }
1184 }
1185 _ => {}
1186 };
1187 if handled {
1188 return Some(0);
1189 }
1190 }
1191
1192 None
1193}
1194
1195fn handle_cursor_changed(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1196 let mut state = state_ptr.state.borrow_mut();
1197 let had_cursor = state.current_cursor.is_some();
1198
1199 state.current_cursor = if lparam.0 == 0 {
1200 None
1201 } else {
1202 Some(HCURSOR(lparam.0 as _))
1203 };
1204
1205 if had_cursor != state.current_cursor.is_some() {
1206 unsafe { SetCursor(state.current_cursor) };
1207 }
1208
1209 Some(0)
1210}
1211
1212fn handle_set_cursor(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1213 if matches!(
1214 lparam.loword() as u32,
1215 HTLEFT | HTRIGHT | HTTOP | HTTOPLEFT | HTTOPRIGHT | HTBOTTOM | HTBOTTOMLEFT | HTBOTTOMRIGHT
1216 ) {
1217 return None;
1218 }
1219 unsafe {
1220 SetCursor(state_ptr.state.borrow().current_cursor);
1221 };
1222 Some(1)
1223}
1224
1225fn handle_system_settings_changed(
1226 handle: HWND,
1227 lparam: LPARAM,
1228 state_ptr: Rc<WindowsWindowStatePtr>,
1229) -> Option<isize> {
1230 let mut lock = state_ptr.state.borrow_mut();
1231 let display = lock.display;
1232 // system settings
1233 lock.system_settings.update(display);
1234 // mouse double click
1235 lock.click_state.system_update();
1236 // window border offset
1237 lock.border_offset.update(handle).log_err();
1238 drop(lock);
1239
1240 // lParam is a pointer to a string that indicates the area containing the system parameter
1241 // that was changed.
1242 let parameter = PCWSTR::from_raw(lparam.0 as _);
1243 if unsafe { !parameter.is_null() && !parameter.is_empty() } {
1244 if let Some(parameter_string) = unsafe { parameter.to_string() }.log_err() {
1245 log::info!("System settings changed: {}", parameter_string);
1246 match parameter_string.as_str() {
1247 "ImmersiveColorSet" => {
1248 handle_system_theme_changed(handle, state_ptr);
1249 }
1250 _ => {}
1251 }
1252 }
1253 }
1254
1255 // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1256 // taskbar correctly.
1257 notify_frame_changed(handle);
1258 Some(0)
1259}
1260
1261fn handle_system_command(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1262 if wparam.0 == SC_KEYMENU as usize {
1263 let mut lock = state_ptr.state.borrow_mut();
1264 if lock.system_key_handled {
1265 lock.system_key_handled = false;
1266 return Some(0);
1267 }
1268 }
1269 None
1270}
1271
1272fn handle_system_theme_changed(
1273 handle: HWND,
1274 state_ptr: Rc<WindowsWindowStatePtr>,
1275) -> Option<isize> {
1276 let mut callback = state_ptr
1277 .state
1278 .borrow_mut()
1279 .callbacks
1280 .appearance_changed
1281 .take()?;
1282 callback();
1283 state_ptr.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1284 configure_dwm_dark_mode(handle);
1285 Some(0)
1286}
1287
1288fn handle_input_language_changed(
1289 lparam: LPARAM,
1290 state_ptr: Rc<WindowsWindowStatePtr>,
1291) -> Option<isize> {
1292 let thread = state_ptr.main_thread_id_win32;
1293 let validation = state_ptr.validation_number;
1294 unsafe {
1295 PostThreadMessageW(thread, WM_INPUTLANGCHANGE, WPARAM(validation), lparam).log_err();
1296 }
1297 Some(0)
1298}
1299
1300fn parse_syskeydown_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1301 let modifiers = current_modifiers();
1302 let vk_code = wparam.loword();
1303
1304 // on Windows, F10 can trigger this event, not just the alt key,
1305 // so when F10 was pressed, handle only it
1306 if !modifiers.alt {
1307 if vk_code == VK_F10.0 {
1308 let offset = vk_code - VK_F1.0;
1309 return Some(Keystroke {
1310 modifiers,
1311 key: format!("f{}", offset + 1),
1312 key_char: None,
1313 });
1314 } else {
1315 return None;
1316 }
1317 }
1318
1319 let key = match VIRTUAL_KEY(vk_code) {
1320 VK_BACK => "backspace",
1321 VK_RETURN => "enter",
1322 VK_TAB => "tab",
1323 VK_UP => "up",
1324 VK_DOWN => "down",
1325 VK_RIGHT => "right",
1326 VK_LEFT => "left",
1327 VK_HOME => "home",
1328 VK_END => "end",
1329 VK_PRIOR => "pageup",
1330 VK_NEXT => "pagedown",
1331 VK_BROWSER_BACK => "back",
1332 VK_BROWSER_FORWARD => "forward",
1333 VK_ESCAPE => "escape",
1334 VK_INSERT => "insert",
1335 VK_DELETE => "delete",
1336 VK_APPS => "menu",
1337 _ => {
1338 let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1339 if basic_key.is_some() {
1340 return basic_key;
1341 } else {
1342 if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
1343 let offset = vk_code - VK_F1.0;
1344 return Some(Keystroke {
1345 modifiers,
1346 key: format!("f{}", offset + 1),
1347 key_char: None,
1348 });
1349 } else {
1350 return None;
1351 }
1352 }
1353 }
1354 }
1355 .to_owned();
1356
1357 Some(Keystroke {
1358 modifiers,
1359 key,
1360 key_char: None,
1361 })
1362}
1363
1364enum KeystrokeOrModifier {
1365 Keystroke(Keystroke),
1366 Modifier(Modifiers),
1367}
1368
1369fn parse_keystroke_from_vkey(wparam: WPARAM, is_keyup: bool) -> Option<KeystrokeOrModifier> {
1370 let vk_code = wparam.loword();
1371
1372 let modifiers = current_modifiers();
1373
1374 let key = match VIRTUAL_KEY(vk_code) {
1375 VK_BACK => "backspace",
1376 VK_RETURN => "enter",
1377 VK_TAB => "tab",
1378 VK_UP => "up",
1379 VK_DOWN => "down",
1380 VK_RIGHT => "right",
1381 VK_LEFT => "left",
1382 VK_HOME => "home",
1383 VK_END => "end",
1384 VK_PRIOR => "pageup",
1385 VK_NEXT => "pagedown",
1386 VK_BROWSER_BACK => "back",
1387 VK_BROWSER_FORWARD => "forward",
1388 VK_ESCAPE => "escape",
1389 VK_INSERT => "insert",
1390 VK_DELETE => "delete",
1391 VK_APPS => "menu",
1392 _ => {
1393 if is_modifier(VIRTUAL_KEY(vk_code)) {
1394 return Some(KeystrokeOrModifier::Modifier(modifiers));
1395 }
1396
1397 if modifiers.control || modifiers.alt || is_keyup {
1398 let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1399 if let Some(basic_key) = basic_key {
1400 return Some(KeystrokeOrModifier::Keystroke(basic_key));
1401 }
1402 }
1403
1404 if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
1405 let offset = vk_code - VK_F1.0;
1406 return Some(KeystrokeOrModifier::Keystroke(Keystroke {
1407 modifiers,
1408 key: format!("f{}", offset + 1),
1409 key_char: None,
1410 }));
1411 };
1412 return None;
1413 }
1414 }
1415 .to_owned();
1416
1417 Some(KeystrokeOrModifier::Keystroke(Keystroke {
1418 modifiers,
1419 key,
1420 key_char: None,
1421 }))
1422}
1423
1424fn parse_char_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1425 let first_char = char::from_u32((wparam.0 as u16).into())?;
1426 if first_char.is_control() {
1427 None
1428 } else {
1429 let mut modifiers = current_modifiers();
1430 // for characters that use 'shift' to type it is expected that the
1431 // shift is not reported if the uppercase/lowercase are the same and instead only the key is reported
1432 if first_char.to_ascii_uppercase() == first_char.to_ascii_lowercase() {
1433 modifiers.shift = false;
1434 }
1435 let key = match first_char {
1436 ' ' => "space".to_string(),
1437 first_char => first_char.to_lowercase().to_string(),
1438 };
1439 Some(Keystroke {
1440 modifiers,
1441 key,
1442 key_char: Some(first_char.to_string()),
1443 })
1444 }
1445}
1446
1447fn parse_ime_compostion_string(ctx: HIMC) -> Option<String> {
1448 unsafe {
1449 let string_len = ImmGetCompositionStringW(ctx, GCS_COMPSTR, None, 0);
1450 if string_len >= 0 {
1451 let mut buffer = vec![0u8; string_len as usize + 2];
1452 ImmGetCompositionStringW(
1453 ctx,
1454 GCS_COMPSTR,
1455 Some(buffer.as_mut_ptr() as _),
1456 string_len as _,
1457 );
1458 let wstring = std::slice::from_raw_parts::<u16>(
1459 buffer.as_mut_ptr().cast::<u16>(),
1460 string_len as usize / 2,
1461 );
1462 Some(String::from_utf16_lossy(wstring))
1463 } else {
1464 None
1465 }
1466 }
1467}
1468
1469#[inline]
1470fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1471 unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1472}
1473
1474fn parse_ime_compostion_result(ctx: HIMC) -> Option<String> {
1475 unsafe {
1476 let string_len = ImmGetCompositionStringW(ctx, GCS_RESULTSTR, None, 0);
1477 if string_len >= 0 {
1478 let mut buffer = vec![0u8; string_len as usize + 2];
1479 ImmGetCompositionStringW(
1480 ctx,
1481 GCS_RESULTSTR,
1482 Some(buffer.as_mut_ptr() as _),
1483 string_len as _,
1484 );
1485 let wstring = std::slice::from_raw_parts::<u16>(
1486 buffer.as_mut_ptr().cast::<u16>(),
1487 string_len as usize / 2,
1488 );
1489 let string = String::from_utf16_lossy(wstring);
1490 Some(string)
1491 } else {
1492 None
1493 }
1494 }
1495}
1496
1497fn basic_vkcode_to_string(code: u16, modifiers: Modifiers) -> Option<Keystroke> {
1498 let mapped_code = unsafe { MapVirtualKeyW(code as u32, MAPVK_VK_TO_CHAR) };
1499
1500 let key = match mapped_code {
1501 0 => None,
1502 raw_code => char::from_u32(raw_code),
1503 }?
1504 .to_ascii_lowercase();
1505
1506 let key = if matches!(code as u32, 112..=135) {
1507 format!("f{key}")
1508 } else {
1509 key.to_string()
1510 };
1511
1512 Some(Keystroke {
1513 modifiers,
1514 key,
1515 key_char: None,
1516 })
1517}
1518
1519#[inline]
1520fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1521 unsafe { GetKeyState(vkey.0 as i32) < 0 }
1522}
1523
1524fn is_modifier(virtual_key: VIRTUAL_KEY) -> bool {
1525 matches!(
1526 virtual_key,
1527 VK_CONTROL | VK_MENU | VK_SHIFT | VK_LWIN | VK_RWIN
1528 )
1529}
1530
1531#[inline]
1532pub(crate) fn current_modifiers() -> Modifiers {
1533 Modifiers {
1534 control: is_virtual_key_pressed(VK_CONTROL),
1535 alt: is_virtual_key_pressed(VK_MENU),
1536 shift: is_virtual_key_pressed(VK_SHIFT),
1537 platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1538 function: false,
1539 }
1540}
1541
1542fn get_client_area_insets(
1543 handle: HWND,
1544 is_maximized: bool,
1545 windows_version: WindowsVersion,
1546) -> RECT {
1547 // For maximized windows, Windows outdents the window rect from the screen's client rect
1548 // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1549 // on all sides (including the top) to avoid the client area extending onto adjacent
1550 // monitors.
1551 //
1552 // For non-maximized windows, things become complicated:
1553 //
1554 // - On Windows 10
1555 // The top inset must be zero, since if there is any nonclient area, Windows will draw
1556 // a full native titlebar outside the client area. (This doesn't occur in the maximized
1557 // case.)
1558 //
1559 // - On Windows 11
1560 // The top inset is calculated using an empirical formula that I derived through various
1561 // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1562 let dpi = unsafe { GetDpiForWindow(handle) };
1563 let frame_thickness = get_frame_thickness(dpi);
1564 let top_insets = if is_maximized {
1565 frame_thickness
1566 } else {
1567 match windows_version {
1568 WindowsVersion::Win10 => 0,
1569 WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1570 }
1571 };
1572 RECT {
1573 left: frame_thickness,
1574 top: top_insets,
1575 right: frame_thickness,
1576 bottom: frame_thickness,
1577 }
1578}
1579
1580// there is some additional non-visible space when talking about window
1581// borders on Windows:
1582// - SM_CXSIZEFRAME: The resize handle.
1583// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1584fn get_frame_thickness(dpi: u32) -> i32 {
1585 let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1586 let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1587 resize_frame_thickness + padding_thickness
1588}
1589
1590fn notify_frame_changed(handle: HWND) {
1591 unsafe {
1592 SetWindowPos(
1593 handle,
1594 None,
1595 0,
1596 0,
1597 0,
1598 0,
1599 SWP_FRAMECHANGED
1600 | SWP_NOACTIVATE
1601 | SWP_NOCOPYBITS
1602 | SWP_NOMOVE
1603 | SWP_NOOWNERZORDER
1604 | SWP_NOREPOSITION
1605 | SWP_NOSENDCHANGING
1606 | SWP_NOSIZE
1607 | SWP_NOZORDER,
1608 )
1609 .log_err();
1610 }
1611}
1612
1613fn start_tracking_mouse(
1614 handle: HWND,
1615 state_ptr: &Rc<WindowsWindowStatePtr>,
1616 flags: TRACKMOUSEEVENT_FLAGS,
1617) {
1618 let mut lock = state_ptr.state.borrow_mut();
1619 if !lock.hovered {
1620 lock.hovered = true;
1621 unsafe {
1622 TrackMouseEvent(&mut TRACKMOUSEEVENT {
1623 cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1624 dwFlags: flags,
1625 hwndTrack: handle,
1626 dwHoverTime: HOVER_DEFAULT,
1627 })
1628 .log_err()
1629 };
1630 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1631 drop(lock);
1632 callback(true);
1633 state_ptr.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1634 }
1635 }
1636}
1637
1638fn with_input_handler<F, R>(state_ptr: &Rc<WindowsWindowStatePtr>, f: F) -> Option<R>
1639where
1640 F: FnOnce(&mut PlatformInputHandler) -> R,
1641{
1642 let mut input_handler = state_ptr.state.borrow_mut().input_handler.take()?;
1643 let result = f(&mut input_handler);
1644 state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1645 Some(result)
1646}
1647
1648fn with_input_handler_and_scale_factor<F, R>(
1649 state_ptr: &Rc<WindowsWindowStatePtr>,
1650 f: F,
1651) -> Option<R>
1652where
1653 F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1654{
1655 let mut lock = state_ptr.state.borrow_mut();
1656 let mut input_handler = lock.input_handler.take()?;
1657 let scale_factor = lock.scale_factor;
1658 drop(lock);
1659 let result = f(&mut input_handler, scale_factor);
1660 state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1661 result
1662}