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