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