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