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 => lock.system_settings.mouse_wheel_settings.wheel_scroll_chars,
534 false => lock.system_settings.mouse_wheel_settings.wheel_scroll_lines,
535 };
536 drop(lock);
537
538 let wheel_distance =
539 (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
540 let mut cursor_point = POINT {
541 x: lparam.signed_loword().into(),
542 y: lparam.signed_hiword().into(),
543 };
544 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
545 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
546 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
547 delta: ScrollDelta::Lines(match modifiers.shift {
548 true => Point {
549 x: wheel_distance,
550 y: 0.0,
551 },
552 false => Point {
553 y: wheel_distance,
554 x: 0.0,
555 },
556 }),
557 modifiers,
558 touch_phase: TouchPhase::Moved,
559 });
560 let handled = !func(input).propagate;
561 self.state.borrow_mut().callbacks.input = Some(func);
562
563 if handled { Some(0) } else { Some(1) }
564 }
565
566 fn handle_mouse_horizontal_wheel_msg(
567 &self,
568 handle: HWND,
569 wparam: WPARAM,
570 lparam: LPARAM,
571 ) -> Option<isize> {
572 let mut lock = self.state.borrow_mut();
573 let Some(mut func) = lock.callbacks.input.take() else {
574 return Some(1);
575 };
576 let scale_factor = lock.scale_factor;
577 let wheel_scroll_chars = lock.system_settings.mouse_wheel_settings.wheel_scroll_chars;
578 drop(lock);
579
580 let wheel_distance =
581 (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
582 let mut cursor_point = POINT {
583 x: lparam.signed_loword().into(),
584 y: lparam.signed_hiword().into(),
585 };
586 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
587 let event = PlatformInput::ScrollWheel(ScrollWheelEvent {
588 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
589 delta: ScrollDelta::Lines(Point {
590 x: wheel_distance,
591 y: 0.0,
592 }),
593 modifiers: current_modifiers(),
594 touch_phase: TouchPhase::Moved,
595 });
596 let handled = !func(event).propagate;
597 self.state.borrow_mut().callbacks.input = Some(func);
598
599 if handled { Some(0) } else { Some(1) }
600 }
601
602 fn retrieve_caret_position(&self) -> Option<POINT> {
603 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
604 let caret_range = input_handler.selected_text_range(false)?;
605 let caret_position = input_handler.bounds_for_range(caret_range.range)?;
606 Some(POINT {
607 // logical to physical
608 x: (caret_position.origin.x.0 * scale_factor) as i32,
609 y: (caret_position.origin.y.0 * scale_factor) as i32
610 + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
611 })
612 })
613 }
614
615 fn handle_ime_position(&self, handle: HWND) -> Option<isize> {
616 unsafe {
617 let ctx = ImmGetContext(handle);
618
619 let Some(caret_position) = self.retrieve_caret_position() else {
620 return Some(0);
621 };
622 {
623 let config = COMPOSITIONFORM {
624 dwStyle: CFS_POINT,
625 ptCurrentPos: caret_position,
626 ..Default::default()
627 };
628 ImmSetCompositionWindow(ctx, &config as _).ok().log_err();
629 }
630 {
631 let config = CANDIDATEFORM {
632 dwStyle: CFS_CANDIDATEPOS,
633 ptCurrentPos: caret_position,
634 ..Default::default()
635 };
636 ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
637 }
638 ImmReleaseContext(handle, ctx).ok().log_err();
639 Some(0)
640 }
641 }
642
643 fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
644 let ctx = unsafe { ImmGetContext(handle) };
645 let result = self.handle_ime_composition_inner(ctx, lparam);
646 unsafe { ImmReleaseContext(handle, ctx).ok().log_err() };
647 result
648 }
649
650 fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {
651 let lparam = lparam.0 as u32;
652 if lparam == 0 {
653 // Japanese IME may send this message with lparam = 0, which indicates that
654 // there is no composition string.
655 self.with_input_handler(|input_handler| {
656 input_handler.replace_text_in_range(None, "");
657 })?;
658 Some(0)
659 } else {
660 if lparam & GCS_COMPSTR.0 > 0 {
661 let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
662 let caret_pos =
663 (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
664 let pos = retrieve_composition_cursor_position(ctx);
665 pos..pos
666 });
667 self.with_input_handler(|input_handler| {
668 input_handler.replace_and_mark_text_in_range(None, &comp_string, caret_pos);
669 })?;
670 }
671 if lparam & GCS_RESULTSTR.0 > 0 {
672 let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
673 self.with_input_handler(|input_handler| {
674 input_handler.replace_text_in_range(None, &comp_result);
675 })?;
676 return Some(0);
677 }
678
679 // currently, we don't care other stuff
680 None
681 }
682 }
683
684 /// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
685 fn handle_calc_client_size(
686 &self,
687 handle: HWND,
688 wparam: WPARAM,
689 lparam: LPARAM,
690 ) -> Option<isize> {
691 if !self.hide_title_bar || self.state.borrow().is_fullscreen() || wparam.0 == 0 {
692 return None;
693 }
694
695 let is_maximized = self.state.borrow().is_maximized();
696 let insets = get_client_area_insets(handle, is_maximized, self.windows_version);
697 // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
698 let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
699 let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
700
701 requested_client_rect[0].left += insets.left;
702 requested_client_rect[0].top += insets.top;
703 requested_client_rect[0].right -= insets.right;
704 requested_client_rect[0].bottom -= insets.bottom;
705
706 // Fix auto hide taskbar not showing. This solution is based on the approach
707 // used by Chrome. However, it may result in one row of pixels being obscured
708 // in our client area. But as Chrome says, "there seems to be no better solution."
709 if is_maximized
710 && let Some(ref taskbar_position) = self
711 .state
712 .borrow()
713 .system_settings
714 .auto_hide_taskbar_position
715 {
716 // For the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
717 // so the window isn't treated as a "fullscreen app", which would cause
718 // the taskbar to disappear.
719 match taskbar_position {
720 AutoHideTaskbarPosition::Left => {
721 requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
722 }
723 AutoHideTaskbarPosition::Top => {
724 requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
725 }
726 AutoHideTaskbarPosition::Right => {
727 requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
728 }
729 AutoHideTaskbarPosition::Bottom => {
730 requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
731 }
732 }
733 }
734
735 Some(0)
736 }
737
738 fn handle_activate_msg(self: &Rc<Self>, wparam: WPARAM) -> Option<isize> {
739 let activated = wparam.loword() > 0;
740 let this = self.clone();
741 self.executor
742 .spawn(async move {
743 let mut lock = this.state.borrow_mut();
744 if let Some(mut func) = lock.callbacks.active_status_change.take() {
745 drop(lock);
746 func(activated);
747 this.state.borrow_mut().callbacks.active_status_change = Some(func);
748 }
749 })
750 .detach();
751
752 None
753 }
754
755 fn handle_create_msg(&self, handle: HWND) -> Option<isize> {
756 if self.hide_title_bar {
757 notify_frame_changed(handle);
758 Some(0)
759 } else {
760 None
761 }
762 }
763
764 fn handle_dpi_changed_msg(
765 &self,
766 handle: HWND,
767 wparam: WPARAM,
768 lparam: LPARAM,
769 ) -> Option<isize> {
770 let new_dpi = wparam.loword() as f32;
771 let mut lock = self.state.borrow_mut();
772 let is_maximized = lock.is_maximized();
773 let new_scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
774 lock.scale_factor = new_scale_factor;
775 lock.border_offset.update(handle).log_err();
776 drop(lock);
777
778 let rect = unsafe { &*(lparam.0 as *const RECT) };
779 let width = rect.right - rect.left;
780 let height = rect.bottom - rect.top;
781 // this will emit `WM_SIZE` and `WM_MOVE` right here
782 // even before this function returns
783 // the new size is handled in `WM_SIZE`
784 unsafe {
785 SetWindowPos(
786 handle,
787 None,
788 rect.left,
789 rect.top,
790 width,
791 height,
792 SWP_NOZORDER | SWP_NOACTIVATE,
793 )
794 .context("unable to set window position after dpi has changed")
795 .log_err();
796 }
797
798 // When maximized, SetWindowPos doesn't send WM_SIZE, so we need to manually
799 // update the size and call the resize callback
800 if is_maximized {
801 let device_size = size(DevicePixels(width), DevicePixels(height));
802 self.handle_size_change(device_size, new_scale_factor, true);
803 }
804
805 Some(0)
806 }
807
808 /// The following conditions will trigger this event:
809 /// 1. The monitor on which the window is located goes offline or changes resolution.
810 /// 2. Another monitor goes offline, is plugged in, or changes resolution.
811 ///
812 /// In either case, the window will only receive information from the monitor on which
813 /// it is located.
814 ///
815 /// For example, in the case of condition 2, where the monitor on which the window is
816 /// located has actually changed nothing, it will still receive this event.
817 fn handle_display_change_msg(&self, handle: HWND) -> Option<isize> {
818 // NOTE:
819 // Even the `lParam` holds the resolution of the screen, we just ignore it.
820 // Because WM_DPICHANGED, WM_MOVE, WM_SIZE will come first, window reposition and resize
821 // are handled there.
822 // So we only care about if monitor is disconnected.
823 let previous_monitor = self.state.borrow().display;
824 if WindowsDisplay::is_connected(previous_monitor.handle) {
825 // we are fine, other display changed
826 return None;
827 }
828 // display disconnected
829 // in this case, the OS will move our window to another monitor, and minimize it.
830 // we deminimize the window and query the monitor after moving
831 unsafe {
832 let _ = ShowWindow(handle, SW_SHOWNORMAL);
833 };
834 let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
835 // all monitors disconnected
836 if new_monitor.is_invalid() {
837 log::error!("No monitor detected!");
838 return None;
839 }
840 let new_display = WindowsDisplay::new_with_handle(new_monitor);
841 self.state.borrow_mut().display = new_display;
842 Some(0)
843 }
844
845 fn handle_hit_test_msg(
846 &self,
847 handle: HWND,
848 msg: u32,
849 wparam: WPARAM,
850 lparam: LPARAM,
851 ) -> Option<isize> {
852 if !self.is_movable || self.state.borrow().is_fullscreen() {
853 return None;
854 }
855
856 let mut lock = self.state.borrow_mut();
857 if let Some(mut callback) = lock.callbacks.hit_test_window_control.take() {
858 drop(lock);
859 let area = callback();
860 self.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
861 if let Some(area) = area {
862 return match area {
863 WindowControlArea::Drag => Some(HTCAPTION as _),
864 WindowControlArea::Close => Some(HTCLOSE as _),
865 WindowControlArea::Max => Some(HTMAXBUTTON as _),
866 WindowControlArea::Min => Some(HTMINBUTTON as _),
867 };
868 }
869 } else {
870 drop(lock);
871 }
872
873 if !self.hide_title_bar {
874 // If the OS draws the title bar, we don't need to handle hit test messages.
875 return None;
876 }
877
878 // default handler for resize areas
879 let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
880 if matches!(
881 hit.0 as u32,
882 HTNOWHERE
883 | HTRIGHT
884 | HTLEFT
885 | HTTOPLEFT
886 | HTTOP
887 | HTTOPRIGHT
888 | HTBOTTOMRIGHT
889 | HTBOTTOM
890 | HTBOTTOMLEFT
891 ) {
892 return Some(hit.0);
893 }
894
895 if self.state.borrow().is_fullscreen() {
896 return Some(HTCLIENT as _);
897 }
898
899 let dpi = unsafe { GetDpiForWindow(handle) };
900 let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
901
902 let mut cursor_point = POINT {
903 x: lparam.signed_loword().into(),
904 y: lparam.signed_hiword().into(),
905 };
906 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
907 if !self.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y {
908 return Some(HTTOP as _);
909 }
910
911 Some(HTCLIENT as _)
912 }
913
914 fn handle_nc_mouse_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
915 self.start_tracking_mouse(handle, TME_LEAVE | TME_NONCLIENT);
916
917 let mut lock = self.state.borrow_mut();
918 let mut func = lock.callbacks.input.take()?;
919 let scale_factor = lock.scale_factor;
920 drop(lock);
921
922 let mut cursor_point = POINT {
923 x: lparam.signed_loword().into(),
924 y: lparam.signed_hiword().into(),
925 };
926 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
927 let input = PlatformInput::MouseMove(MouseMoveEvent {
928 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
929 pressed_button: None,
930 modifiers: current_modifiers(),
931 });
932 let handled = !func(input).propagate;
933 self.state.borrow_mut().callbacks.input = Some(func);
934
935 if handled { Some(0) } else { None }
936 }
937
938 fn handle_nc_mouse_down_msg(
939 &self,
940 handle: HWND,
941 button: MouseButton,
942 wparam: WPARAM,
943 lparam: LPARAM,
944 ) -> Option<isize> {
945 let mut lock = self.state.borrow_mut();
946 if let Some(mut func) = lock.callbacks.input.take() {
947 let scale_factor = lock.scale_factor;
948 let mut cursor_point = POINT {
949 x: lparam.signed_loword().into(),
950 y: lparam.signed_hiword().into(),
951 };
952 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
953 let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
954 let click_count = lock.click_state.update(button, physical_point);
955 drop(lock);
956
957 let input = PlatformInput::MouseDown(MouseDownEvent {
958 button,
959 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
960 modifiers: current_modifiers(),
961 click_count,
962 first_mouse: false,
963 });
964 let result = func(input);
965 let handled = !result.propagate || result.default_prevented;
966 self.state.borrow_mut().callbacks.input = Some(func);
967
968 if handled {
969 return Some(0);
970 }
971 } else {
972 drop(lock);
973 };
974
975 // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
976 if button == MouseButton::Left {
977 match wparam.0 as u32 {
978 HTMINBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
979 HTMAXBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
980 HTCLOSE => self.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
981 _ => return None,
982 };
983 Some(0)
984 } else {
985 None
986 }
987 }
988
989 fn handle_nc_mouse_up_msg(
990 &self,
991 handle: HWND,
992 button: MouseButton,
993 wparam: WPARAM,
994 lparam: LPARAM,
995 ) -> Option<isize> {
996 let mut lock = self.state.borrow_mut();
997 if let Some(mut func) = lock.callbacks.input.take() {
998 let scale_factor = lock.scale_factor;
999 drop(lock);
1000
1001 let mut cursor_point = POINT {
1002 x: lparam.signed_loword().into(),
1003 y: lparam.signed_hiword().into(),
1004 };
1005 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1006 let input = PlatformInput::MouseUp(MouseUpEvent {
1007 button,
1008 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1009 modifiers: current_modifiers(),
1010 click_count: 1,
1011 });
1012 let handled = !func(input).propagate;
1013 self.state.borrow_mut().callbacks.input = Some(func);
1014
1015 if handled {
1016 return Some(0);
1017 }
1018 } else {
1019 drop(lock);
1020 }
1021
1022 let last_pressed = self.state.borrow_mut().nc_button_pressed.take();
1023 if button == MouseButton::Left
1024 && let Some(last_pressed) = last_pressed
1025 {
1026 let handled = match (wparam.0 as u32, last_pressed) {
1027 (HTMINBUTTON, HTMINBUTTON) => {
1028 unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1029 true
1030 }
1031 (HTMAXBUTTON, HTMAXBUTTON) => {
1032 if self.state.borrow().is_maximized() {
1033 unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1034 } else {
1035 unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1036 }
1037 true
1038 }
1039 (HTCLOSE, HTCLOSE) => {
1040 unsafe {
1041 PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1042 .log_err()
1043 };
1044 true
1045 }
1046 _ => false,
1047 };
1048 if handled {
1049 return Some(0);
1050 }
1051 }
1052
1053 None
1054 }
1055
1056 fn handle_cursor_changed(&self, lparam: LPARAM) -> Option<isize> {
1057 let mut state = self.state.borrow_mut();
1058 let had_cursor = state.current_cursor.is_some();
1059
1060 state.current_cursor = if lparam.0 == 0 {
1061 None
1062 } else {
1063 Some(HCURSOR(lparam.0 as _))
1064 };
1065
1066 if had_cursor != state.current_cursor.is_some() {
1067 unsafe { SetCursor(state.current_cursor) };
1068 }
1069
1070 Some(0)
1071 }
1072
1073 fn handle_set_cursor(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1074 if unsafe { !IsWindowEnabled(handle).as_bool() }
1075 || matches!(
1076 lparam.loword() as u32,
1077 HTLEFT
1078 | HTRIGHT
1079 | HTTOP
1080 | HTTOPLEFT
1081 | HTTOPRIGHT
1082 | HTBOTTOM
1083 | HTBOTTOMLEFT
1084 | HTBOTTOMRIGHT
1085 )
1086 {
1087 return None;
1088 }
1089 unsafe {
1090 SetCursor(self.state.borrow().current_cursor);
1091 };
1092 Some(1)
1093 }
1094
1095 fn handle_system_settings_changed(
1096 &self,
1097 handle: HWND,
1098 wparam: WPARAM,
1099 lparam: LPARAM,
1100 ) -> Option<isize> {
1101 if wparam.0 != 0 {
1102 let mut lock = self.state.borrow_mut();
1103 let display = lock.display;
1104 lock.system_settings.update(display, wparam.0);
1105 lock.click_state.system_update(wparam.0);
1106 lock.border_offset.update(handle).log_err();
1107 } else {
1108 self.handle_system_theme_changed(handle, lparam)?;
1109 };
1110 // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1111 // taskbar correctly.
1112 notify_frame_changed(handle);
1113
1114 Some(0)
1115 }
1116
1117 fn handle_system_command(&self, wparam: WPARAM) -> Option<isize> {
1118 if wparam.0 == SC_KEYMENU as usize {
1119 let mut lock = self.state.borrow_mut();
1120 if lock.system_key_handled {
1121 lock.system_key_handled = false;
1122 return Some(0);
1123 }
1124 }
1125 None
1126 }
1127
1128 fn handle_system_theme_changed(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1129 // lParam is a pointer to a string that indicates the area containing the system parameter
1130 // that was changed.
1131 let parameter = PCWSTR::from_raw(lparam.0 as _);
1132 if unsafe { !parameter.is_null() && !parameter.is_empty() }
1133 && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()
1134 {
1135 log::info!("System settings changed: {}", parameter_string);
1136 if parameter_string.as_str() == "ImmersiveColorSet" {
1137 let new_appearance = system_appearance()
1138 .context("unable to get system appearance when handling ImmersiveColorSet")
1139 .log_err()?;
1140 let mut lock = self.state.borrow_mut();
1141 if new_appearance != lock.appearance {
1142 lock.appearance = new_appearance;
1143 let mut callback = lock.callbacks.appearance_changed.take()?;
1144 drop(lock);
1145 callback();
1146 self.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1147 configure_dwm_dark_mode(handle, new_appearance);
1148 }
1149 }
1150 }
1151 Some(0)
1152 }
1153
1154 fn handle_input_language_changed(&self) -> Option<isize> {
1155 unsafe {
1156 PostMessageW(
1157 Some(self.platform_window_handle),
1158 WM_GPUI_KEYBOARD_LAYOUT_CHANGED,
1159 WPARAM(self.validation_number),
1160 LPARAM(0),
1161 )
1162 .log_err();
1163 }
1164 Some(0)
1165 }
1166
1167 fn handle_window_visibility_changed(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1168 if wparam.0 == 1 {
1169 self.draw_window(handle, false);
1170 }
1171 None
1172 }
1173
1174 fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1175 let mut lock = self.state.borrow_mut();
1176 let devices = lparam.0 as *const DirectXDevices;
1177 let devices = unsafe { &*devices };
1178 lock.renderer.handle_device_lost(&devices);
1179 Some(0)
1180 }
1181
1182 #[inline]
1183 fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1184 let mut request_frame = self.state.borrow_mut().callbacks.request_frame.take()?;
1185 request_frame(RequestFrameOptions {
1186 require_presentation: false,
1187 force_render,
1188 });
1189 self.state.borrow_mut().callbacks.request_frame = Some(request_frame);
1190 unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1191 Some(0)
1192 }
1193
1194 #[inline]
1195 fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {
1196 let code_point = wparam.loword();
1197 let mut lock = self.state.borrow_mut();
1198 // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630
1199 match code_point {
1200 0xD800..=0xDBFF => {
1201 // High surrogate, wait for low surrogate
1202 lock.pending_surrogate = Some(code_point);
1203 None
1204 }
1205 0xDC00..=0xDFFF => {
1206 if let Some(high_surrogate) = lock.pending_surrogate.take() {
1207 // Low surrogate, combine with pending high surrogate
1208 String::from_utf16(&[high_surrogate, code_point]).ok()
1209 } else {
1210 // Invalid low surrogate without a preceding high surrogate
1211 log::warn!(
1212 "Received low surrogate without a preceding high surrogate: {code_point:x}"
1213 );
1214 None
1215 }
1216 }
1217 _ => {
1218 lock.pending_surrogate = None;
1219 char::from_u32(code_point as u32)
1220 .filter(|c| !c.is_control())
1221 .map(|c| c.to_string())
1222 }
1223 }
1224 }
1225
1226 fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {
1227 let mut lock = self.state.borrow_mut();
1228 if !lock.hovered {
1229 lock.hovered = true;
1230 unsafe {
1231 TrackMouseEvent(&mut TRACKMOUSEEVENT {
1232 cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1233 dwFlags: flags,
1234 hwndTrack: handle,
1235 dwHoverTime: HOVER_DEFAULT,
1236 })
1237 .log_err()
1238 };
1239 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1240 drop(lock);
1241 callback(true);
1242 self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1243 }
1244 }
1245 }
1246
1247 fn with_input_handler<F, R>(&self, f: F) -> Option<R>
1248 where
1249 F: FnOnce(&mut PlatformInputHandler) -> R,
1250 {
1251 let mut input_handler = self.state.borrow_mut().input_handler.take()?;
1252 let result = f(&mut input_handler);
1253 self.state.borrow_mut().input_handler = Some(input_handler);
1254 Some(result)
1255 }
1256
1257 fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>
1258 where
1259 F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1260 {
1261 let mut lock = self.state.borrow_mut();
1262 let mut input_handler = lock.input_handler.take()?;
1263 let scale_factor = lock.scale_factor;
1264 drop(lock);
1265 let result = f(&mut input_handler, scale_factor);
1266 self.state.borrow_mut().input_handler = Some(input_handler);
1267 result
1268 }
1269}
1270
1271#[inline]
1272fn translate_message(handle: HWND, wparam: WPARAM, lparam: LPARAM) {
1273 let msg = MSG {
1274 hwnd: handle,
1275 message: WM_KEYDOWN,
1276 wParam: wparam,
1277 lParam: lparam,
1278 // It seems like leaving the following two parameters empty doesn't break key events, they still work as expected.
1279 // But if any bugs pop up after this PR, this is probably the place to look first.
1280 time: 0,
1281 pt: POINT::default(),
1282 };
1283 unsafe { TranslateMessage(&msg).ok().log_err() };
1284}
1285
1286fn handle_key_event<F>(
1287 handle: HWND,
1288 wparam: WPARAM,
1289 lparam: LPARAM,
1290 state: &mut WindowsWindowState,
1291 f: F,
1292) -> Option<PlatformInput>
1293where
1294 F: FnOnce(Keystroke) -> PlatformInput,
1295{
1296 let virtual_key = VIRTUAL_KEY(wparam.loword());
1297 let mut modifiers = current_modifiers();
1298
1299 match virtual_key {
1300 VK_SHIFT | VK_CONTROL | VK_MENU | VK_LWIN | VK_RWIN => {
1301 if state
1302 .last_reported_modifiers
1303 .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1304 {
1305 return None;
1306 }
1307 state.last_reported_modifiers = Some(modifiers);
1308 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1309 modifiers,
1310 capslock: current_capslock(),
1311 }))
1312 }
1313 VK_PACKET => {
1314 translate_message(handle, wparam, lparam);
1315 None
1316 }
1317 VK_CAPITAL => {
1318 let capslock = current_capslock();
1319 if state
1320 .last_reported_capslock
1321 .is_some_and(|prev_capslock| prev_capslock == capslock)
1322 {
1323 return None;
1324 }
1325 state.last_reported_capslock = Some(capslock);
1326 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1327 modifiers,
1328 capslock,
1329 }))
1330 }
1331 vkey => {
1332 let vkey = if vkey == VK_PROCESSKEY {
1333 VIRTUAL_KEY(unsafe { ImmGetVirtualKey(handle) } as u16)
1334 } else {
1335 vkey
1336 };
1337 let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1338 Some(f(keystroke))
1339 }
1340 }
1341}
1342
1343fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1344 Some(
1345 match vkey {
1346 VK_SPACE => "space",
1347 VK_BACK => "backspace",
1348 VK_RETURN => "enter",
1349 VK_TAB => "tab",
1350 VK_UP => "up",
1351 VK_DOWN => "down",
1352 VK_RIGHT => "right",
1353 VK_LEFT => "left",
1354 VK_HOME => "home",
1355 VK_END => "end",
1356 VK_PRIOR => "pageup",
1357 VK_NEXT => "pagedown",
1358 VK_BROWSER_BACK => "back",
1359 VK_BROWSER_FORWARD => "forward",
1360 VK_ESCAPE => "escape",
1361 VK_INSERT => "insert",
1362 VK_DELETE => "delete",
1363 VK_APPS => "menu",
1364 VK_F1 => "f1",
1365 VK_F2 => "f2",
1366 VK_F3 => "f3",
1367 VK_F4 => "f4",
1368 VK_F5 => "f5",
1369 VK_F6 => "f6",
1370 VK_F7 => "f7",
1371 VK_F8 => "f8",
1372 VK_F9 => "f9",
1373 VK_F10 => "f10",
1374 VK_F11 => "f11",
1375 VK_F12 => "f12",
1376 VK_F13 => "f13",
1377 VK_F14 => "f14",
1378 VK_F15 => "f15",
1379 VK_F16 => "f16",
1380 VK_F17 => "f17",
1381 VK_F18 => "f18",
1382 VK_F19 => "f19",
1383 VK_F20 => "f20",
1384 VK_F21 => "f21",
1385 VK_F22 => "f22",
1386 VK_F23 => "f23",
1387 VK_F24 => "f24",
1388 _ => return None,
1389 }
1390 .to_string(),
1391 )
1392}
1393
1394fn parse_normal_key(
1395 vkey: VIRTUAL_KEY,
1396 lparam: LPARAM,
1397 mut modifiers: Modifiers,
1398) -> Option<Keystroke> {
1399 let mut key_char = None;
1400 let key = parse_immutable(vkey).or_else(|| {
1401 let scan_code = lparam.hiword() & 0xFF;
1402 key_char = generate_key_char(
1403 vkey,
1404 scan_code as u32,
1405 modifiers.control,
1406 modifiers.shift,
1407 modifiers.alt,
1408 );
1409 get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1410 })?;
1411 Some(Keystroke {
1412 modifiers,
1413 key,
1414 key_char,
1415 })
1416}
1417
1418fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1419 unsafe {
1420 let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1421 if string_len >= 0 {
1422 let mut buffer = vec![0u8; string_len as usize + 2];
1423 ImmGetCompositionStringW(
1424 ctx,
1425 comp_type,
1426 Some(buffer.as_mut_ptr() as _),
1427 string_len as _,
1428 );
1429 let wstring = std::slice::from_raw_parts::<u16>(
1430 buffer.as_mut_ptr().cast::<u16>(),
1431 string_len as usize / 2,
1432 );
1433 Some(String::from_utf16_lossy(wstring))
1434 } else {
1435 None
1436 }
1437 }
1438}
1439
1440#[inline]
1441fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1442 unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1443}
1444
1445#[inline]
1446fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1447 unsafe { GetKeyState(vkey.0 as i32) < 0 }
1448}
1449
1450#[inline]
1451pub(crate) fn current_modifiers() -> Modifiers {
1452 let altgr = is_virtual_key_pressed(VK_RMENU) && is_virtual_key_pressed(VK_LCONTROL);
1453
1454 Modifiers {
1455 control: is_virtual_key_pressed(VK_CONTROL) && !altgr,
1456 alt: is_virtual_key_pressed(VK_MENU) && !altgr,
1457 shift: is_virtual_key_pressed(VK_SHIFT),
1458 platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1459 function: false,
1460 }
1461}
1462
1463#[inline]
1464pub(crate) fn current_capslock() -> Capslock {
1465 let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1466 Capslock { on }
1467}
1468
1469fn get_client_area_insets(
1470 handle: HWND,
1471 is_maximized: bool,
1472 windows_version: WindowsVersion,
1473) -> RECT {
1474 // For maximized windows, Windows outdents the window rect from the screen's client rect
1475 // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1476 // on all sides (including the top) to avoid the client area extending onto adjacent
1477 // monitors.
1478 //
1479 // For non-maximized windows, things become complicated:
1480 //
1481 // - On Windows 10
1482 // The top inset must be zero, since if there is any nonclient area, Windows will draw
1483 // a full native titlebar outside the client area. (This doesn't occur in the maximized
1484 // case.)
1485 //
1486 // - On Windows 11
1487 // The top inset is calculated using an empirical formula that I derived through various
1488 // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1489 let dpi = unsafe { GetDpiForWindow(handle) };
1490 let frame_thickness = get_frame_thickness(dpi);
1491 let top_insets = if is_maximized {
1492 frame_thickness
1493 } else {
1494 match windows_version {
1495 WindowsVersion::Win10 => 0,
1496 WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1497 }
1498 };
1499 RECT {
1500 left: frame_thickness,
1501 top: top_insets,
1502 right: frame_thickness,
1503 bottom: frame_thickness,
1504 }
1505}
1506
1507// there is some additional non-visible space when talking about window
1508// borders on Windows:
1509// - SM_CXSIZEFRAME: The resize handle.
1510// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1511fn get_frame_thickness(dpi: u32) -> i32 {
1512 let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1513 let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1514 resize_frame_thickness + padding_thickness
1515}
1516
1517fn notify_frame_changed(handle: HWND) {
1518 unsafe {
1519 SetWindowPos(
1520 handle,
1521 None,
1522 0,
1523 0,
1524 0,
1525 0,
1526 SWP_FRAMECHANGED
1527 | SWP_NOACTIVATE
1528 | SWP_NOCOPYBITS
1529 | SWP_NOMOVE
1530 | SWP_NOOWNERZORDER
1531 | SWP_NOREPOSITION
1532 | SWP_NOSENDCHANGING
1533 | SWP_NOSIZE
1534 | SWP_NOZORDER,
1535 )
1536 .log_err();
1537 }
1538}