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