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