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