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