1use std::rc::Rc;
2
3use ::util::ResultExt;
4use anyhow::Context as _;
5use windows::{
6 Win32::{
7 Foundation::*,
8 Graphics::Gdi::*,
9 System::SystemServices::*,
10 UI::{
11 Controls::*,
12 HiDpi::*,
13 Input::{Ime::*, KeyboardAndMouse::*},
14 WindowsAndMessaging::*,
15 },
16 },
17 core::PCWSTR,
18};
19
20use crate::*;
21
22pub(crate) const WM_GPUI_CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;
23pub(crate) const WM_GPUI_CLOSE_ONE_WINDOW: u32 = WM_USER + 2;
24pub(crate) const WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD: u32 = WM_USER + 3;
25pub(crate) const WM_GPUI_DOCK_MENU_ACTION: u32 = WM_USER + 4;
26pub(crate) const WM_GPUI_FORCE_UPDATE_WINDOW: u32 = WM_USER + 5;
27pub(crate) const WM_GPUI_KEYBOARD_LAYOUT_CHANGED: u32 = WM_USER + 6;
28
29const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
30const AUTO_HIDE_TASKBAR_THICKNESS_PX: i32 = 1;
31
32impl WindowsWindowInner {
33 pub(crate) fn handle_msg(
34 self: &Rc<Self>,
35 handle: HWND,
36 msg: u32,
37 wparam: WPARAM,
38 lparam: LPARAM,
39 ) -> LRESULT {
40 let handled = match msg {
41 WM_ACTIVATE => self.handle_activate_msg(wparam),
42 WM_CREATE => self.handle_create_msg(handle),
43 WM_DEVICECHANGE => self.handle_device_change_msg(handle, wparam),
44 WM_MOVE => self.handle_move_msg(handle, lparam),
45 WM_SIZE => self.handle_size_msg(wparam, lparam),
46 WM_GETMINMAXINFO => self.handle_get_min_max_info_msg(lparam),
47 WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => self.handle_size_move_loop(handle),
48 WM_EXITSIZEMOVE | WM_EXITMENULOOP => self.handle_size_move_loop_exit(handle),
49 WM_TIMER => self.handle_timer_msg(handle, wparam),
50 WM_NCCALCSIZE => self.handle_calc_client_size(handle, wparam, lparam),
51 WM_DPICHANGED => self.handle_dpi_changed_msg(handle, wparam, lparam),
52 WM_DISPLAYCHANGE => self.handle_display_change_msg(handle),
53 WM_NCHITTEST => self.handle_hit_test_msg(handle, msg, wparam, lparam),
54 WM_PAINT => self.handle_paint_msg(handle),
55 WM_CLOSE => self.handle_close_msg(),
56 WM_DESTROY => self.handle_destroy_msg(handle),
57 WM_MOUSEMOVE => self.handle_mouse_move_msg(handle, lparam, wparam),
58 WM_MOUSELEAVE | WM_NCMOUSELEAVE => self.handle_mouse_leave_msg(),
59 WM_NCMOUSEMOVE => self.handle_nc_mouse_move_msg(handle, lparam),
60 WM_NCLBUTTONDOWN => {
61 self.handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam)
62 }
63 WM_NCRBUTTONDOWN => {
64 self.handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam)
65 }
66 WM_NCMBUTTONDOWN => {
67 self.handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam)
68 }
69 WM_NCLBUTTONUP => {
70 self.handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam)
71 }
72 WM_NCRBUTTONUP => {
73 self.handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam)
74 }
75 WM_NCMBUTTONUP => {
76 self.handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam)
77 }
78 WM_LBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Left, lparam),
79 WM_RBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Right, lparam),
80 WM_MBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Middle, lparam),
81 WM_XBUTTONDOWN => {
82 self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_down_msg)
83 }
84 WM_LBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Left, lparam),
85 WM_RBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Right, lparam),
86 WM_MBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Middle, lparam),
87 WM_XBUTTONUP => {
88 self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_up_msg)
89 }
90 WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
91 WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
92 WM_SYSKEYDOWN => self.handle_syskeydown_msg(handle, wparam, lparam),
93 WM_SYSKEYUP => self.handle_syskeyup_msg(handle, wparam, lparam),
94 WM_SYSCOMMAND => self.handle_system_command(wparam),
95 WM_KEYDOWN => self.handle_keydown_msg(handle, wparam, lparam),
96 WM_KEYUP => self.handle_keyup_msg(handle, wparam, lparam),
97 WM_CHAR => self.handle_char_msg(wparam),
98 WM_DEADCHAR => self.handle_dead_char_msg(wparam),
99 WM_IME_STARTCOMPOSITION => self.handle_ime_position(handle),
100 WM_IME_COMPOSITION => self.handle_ime_composition(handle, lparam),
101 WM_SETCURSOR => self.handle_set_cursor(handle, lparam),
102 WM_SETTINGCHANGE => self.handle_system_settings_changed(handle, wparam, lparam),
103 WM_INPUTLANGCHANGE => self.handle_input_language_changed(),
104 WM_SHOWWINDOW => self.handle_window_visibility_changed(handle, wparam),
105 WM_GPUI_CURSOR_STYLE_CHANGED => self.handle_cursor_changed(lparam),
106 WM_GPUI_FORCE_UPDATE_WINDOW => self.draw_window(handle, true),
107 _ => None,
108 };
109 if let Some(n) = handled {
110 LRESULT(n)
111 } else {
112 unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
113 }
114 }
115
116 fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
117 let mut lock = self.state.borrow_mut();
118 let origin = logical_point(
119 lparam.signed_loword() as f32,
120 lparam.signed_hiword() as f32,
121 lock.scale_factor,
122 );
123 lock.origin = origin;
124 let size = lock.logical_size;
125 let center_x = origin.x.0 + size.width.0 / 2.;
126 let center_y = origin.y.0 + size.height.0 / 2.;
127 let monitor_bounds = lock.display.bounds();
128 if center_x < monitor_bounds.left().0
129 || center_x > monitor_bounds.right().0
130 || center_y < monitor_bounds.top().0
131 || center_y > monitor_bounds.bottom().0
132 {
133 // center of the window may have moved to another monitor
134 let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
135 // minimize the window can trigger this event too, in this case,
136 // monitor is invalid, we do nothing.
137 if !monitor.is_invalid() && lock.display.handle != monitor {
138 // we will get the same monitor if we only have one
139 lock.display = WindowsDisplay::new_with_handle(monitor);
140 }
141 }
142 if let Some(mut callback) = lock.callbacks.moved.take() {
143 drop(lock);
144 callback();
145 self.state.borrow_mut().callbacks.moved = Some(callback);
146 }
147 Some(0)
148 }
149
150 fn handle_get_min_max_info_msg(&self, lparam: LPARAM) -> Option<isize> {
151 let lock = self.state.borrow();
152 let min_size = lock.min_size?;
153 let scale_factor = lock.scale_factor;
154 let boarder_offset = lock.border_offset;
155 drop(lock);
156 unsafe {
157 let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);
158 minmax_info.ptMinTrackSize.x =
159 min_size.width.scale(scale_factor).0 as i32 + boarder_offset.width_offset;
160 minmax_info.ptMinTrackSize.y =
161 min_size.height.scale(scale_factor).0 as i32 + boarder_offset.height_offset;
162 }
163 Some(0)
164 }
165
166 fn handle_size_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
167 let mut lock = self.state.borrow_mut();
168
169 // Don't resize the renderer when the window is minimized, but record that it was minimized so
170 // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.
171 if wparam.0 == SIZE_MINIMIZED as usize {
172 lock.restore_from_minimized = lock.callbacks.request_frame.take();
173 return Some(0);
174 }
175
176 let width = lparam.loword().max(1) as i32;
177 let height = lparam.hiword().max(1) as i32;
178 let new_size = size(DevicePixels(width), DevicePixels(height));
179
180 let scale_factor = lock.scale_factor;
181 let mut should_resize_renderer = false;
182 if lock.restore_from_minimized.is_some() {
183 lock.callbacks.request_frame = lock.restore_from_minimized.take();
184 } else {
185 should_resize_renderer = true;
186 }
187 drop(lock);
188
189 self.handle_size_change(new_size, scale_factor, should_resize_renderer);
190 Some(0)
191 }
192
193 fn handle_size_change(
194 &self,
195 device_size: Size<DevicePixels>,
196 scale_factor: f32,
197 should_resize_renderer: bool,
198 ) {
199 let new_logical_size = device_size.to_pixels(scale_factor);
200 let mut lock = self.state.borrow_mut();
201 lock.logical_size = new_logical_size;
202 if should_resize_renderer {
203 lock.renderer.resize(device_size).log_err();
204 }
205 if let Some(mut callback) = lock.callbacks.resize.take() {
206 drop(lock);
207 callback(new_logical_size, scale_factor);
208 self.state.borrow_mut().callbacks.resize = Some(callback);
209 }
210 }
211
212 fn handle_size_move_loop(&self, handle: HWND) -> Option<isize> {
213 unsafe {
214 let ret = SetTimer(
215 Some(handle),
216 SIZE_MOVE_LOOP_TIMER_ID,
217 USER_TIMER_MINIMUM,
218 None,
219 );
220 if ret == 0 {
221 log::error!(
222 "unable to create timer: {}",
223 std::io::Error::last_os_error()
224 );
225 }
226 }
227 None
228 }
229
230 fn handle_size_move_loop_exit(&self, handle: HWND) -> Option<isize> {
231 unsafe {
232 KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();
233 }
234 None
235 }
236
237 fn handle_timer_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
238 if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
239 for runnable in self.main_receiver.drain() {
240 runnable.run();
241 }
242 self.handle_paint_msg(handle)
243 } else {
244 None
245 }
246 }
247
248 fn handle_paint_msg(&self, handle: HWND) -> Option<isize> {
249 self.draw_window(handle, false)
250 }
251
252 fn handle_close_msg(&self) -> Option<isize> {
253 let mut callback = self.state.borrow_mut().callbacks.should_close.take()?;
254 let should_close = callback();
255 self.state.borrow_mut().callbacks.should_close = Some(callback);
256 if should_close { None } else { Some(0) }
257 }
258
259 fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {
260 let callback = {
261 let mut lock = self.state.borrow_mut();
262 lock.callbacks.close.take()
263 };
264 if let Some(callback) = callback {
265 callback();
266 }
267 unsafe {
268 PostMessageW(
269 Some(self.platform_window_handle),
270 WM_GPUI_CLOSE_ONE_WINDOW,
271 WPARAM(self.validation_number),
272 LPARAM(handle.0 as isize),
273 )
274 .log_err();
275 }
276 Some(0)
277 }
278
279 fn handle_mouse_move_msg(&self, handle: HWND, lparam: LPARAM, wparam: WPARAM) -> Option<isize> {
280 self.start_tracking_mouse(handle, TME_LEAVE);
281
282 let mut lock = self.state.borrow_mut();
283 let Some(mut func) = lock.callbacks.input.take() else {
284 return Some(1);
285 };
286 let scale_factor = lock.scale_factor;
287 drop(lock);
288
289 let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
290 flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
291 flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
292 flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
293 flags if flags.contains(MK_XBUTTON1) => {
294 Some(MouseButton::Navigate(NavigationDirection::Back))
295 }
296 flags if flags.contains(MK_XBUTTON2) => {
297 Some(MouseButton::Navigate(NavigationDirection::Forward))
298 }
299 _ => None,
300 };
301 let x = lparam.signed_loword() as f32;
302 let y = lparam.signed_hiword() as f32;
303 let input = PlatformInput::MouseMove(MouseMoveEvent {
304 position: logical_point(x, y, scale_factor),
305 pressed_button,
306 modifiers: current_modifiers(),
307 });
308 let handled = !func(input).propagate;
309 self.state.borrow_mut().callbacks.input = Some(func);
310
311 if handled { Some(0) } else { Some(1) }
312 }
313
314 fn handle_mouse_leave_msg(&self) -> Option<isize> {
315 let mut lock = self.state.borrow_mut();
316 lock.hovered = false;
317 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
318 drop(lock);
319 callback(false);
320 self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
321 }
322
323 Some(0)
324 }
325
326 fn handle_syskeydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
327 let mut lock = self.state.borrow_mut();
328 let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
329 PlatformInput::KeyDown(KeyDownEvent {
330 keystroke,
331 is_held: lparam.0 & (0x1 << 30) > 0,
332 })
333 })?;
334 let mut func = lock.callbacks.input.take()?;
335 drop(lock);
336
337 let handled = !func(input).propagate;
338
339 let mut lock = self.state.borrow_mut();
340 lock.callbacks.input = Some(func);
341
342 if handled {
343 lock.system_key_handled = true;
344 Some(0)
345 } else {
346 // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
347 // shortcuts.
348 None
349 }
350 }
351
352 fn handle_syskeyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
353 let mut lock = self.state.borrow_mut();
354 let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
355 PlatformInput::KeyUp(KeyUpEvent { keystroke })
356 })?;
357 let mut func = lock.callbacks.input.take()?;
358 drop(lock);
359 func(input);
360 self.state.borrow_mut().callbacks.input = Some(func);
361
362 // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.
363 Some(0)
364 }
365
366 // It's a known bug that you can't trigger `ctrl-shift-0`. See:
367 // https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers
368 fn handle_keydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
369 let mut lock = self.state.borrow_mut();
370 let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
371 PlatformInput::KeyDown(KeyDownEvent {
372 keystroke,
373 is_held: lparam.0 & (0x1 << 30) > 0,
374 })
375 }) else {
376 return Some(1);
377 };
378 drop(lock);
379
380 let is_composing = self
381 .with_input_handler(|input_handler| input_handler.marked_text_range())
382 .flatten()
383 .is_some();
384 if is_composing {
385 translate_message(handle, wparam, lparam);
386 return Some(0);
387 }
388
389 let Some(mut func) = self.state.borrow_mut().callbacks.input.take() else {
390 return Some(1);
391 };
392
393 let handled = !func(input).propagate;
394
395 self.state.borrow_mut().callbacks.input = Some(func);
396
397 if handled {
398 Some(0)
399 } else {
400 translate_message(handle, wparam, lparam);
401 Some(1)
402 }
403 }
404
405 fn handle_keyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
406 let mut lock = self.state.borrow_mut();
407 let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
408 PlatformInput::KeyUp(KeyUpEvent { keystroke })
409 }) else {
410 return Some(1);
411 };
412
413 let Some(mut func) = lock.callbacks.input.take() else {
414 return Some(1);
415 };
416 drop(lock);
417
418 let handled = !func(input).propagate;
419 self.state.borrow_mut().callbacks.input = Some(func);
420
421 if handled { Some(0) } else { Some(1) }
422 }
423
424 fn handle_char_msg(&self, wparam: WPARAM) -> Option<isize> {
425 let input = self.parse_char_message(wparam)?;
426 self.with_input_handler(|input_handler| {
427 input_handler.replace_text_in_range(None, &input);
428 });
429
430 Some(0)
431 }
432
433 fn handle_dead_char_msg(&self, wparam: WPARAM) -> Option<isize> {
434 let ch = char::from_u32(wparam.0 as u32)?.to_string();
435 self.with_input_handler(|input_handler| {
436 input_handler.replace_and_mark_text_in_range(None, &ch, None);
437 });
438 None
439 }
440
441 fn handle_mouse_down_msg(
442 &self,
443 handle: HWND,
444 button: MouseButton,
445 lparam: LPARAM,
446 ) -> Option<isize> {
447 unsafe { SetCapture(handle) };
448 let mut lock = self.state.borrow_mut();
449 let Some(mut func) = lock.callbacks.input.take() else {
450 return Some(1);
451 };
452 let x = lparam.signed_loword();
453 let y = lparam.signed_hiword();
454 let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
455 let click_count = lock.click_state.update(button, physical_point);
456 let scale_factor = lock.scale_factor;
457 drop(lock);
458
459 let input = PlatformInput::MouseDown(MouseDownEvent {
460 button,
461 position: logical_point(x as f32, y as f32, scale_factor),
462 modifiers: current_modifiers(),
463 click_count,
464 first_mouse: false,
465 });
466 let handled = !func(input).propagate;
467 self.state.borrow_mut().callbacks.input = Some(func);
468
469 if handled { Some(0) } else { Some(1) }
470 }
471
472 fn handle_mouse_up_msg(
473 &self,
474 _handle: HWND,
475 button: MouseButton,
476 lparam: LPARAM,
477 ) -> Option<isize> {
478 unsafe { ReleaseCapture().log_err() };
479 let mut lock = self.state.borrow_mut();
480 let Some(mut func) = lock.callbacks.input.take() else {
481 return Some(1);
482 };
483 let x = lparam.signed_loword() as f32;
484 let y = lparam.signed_hiword() as f32;
485 let click_count = lock.click_state.current_count;
486 let scale_factor = lock.scale_factor;
487 drop(lock);
488
489 let input = PlatformInput::MouseUp(MouseUpEvent {
490 button,
491 position: logical_point(x, y, scale_factor),
492 modifiers: current_modifiers(),
493 click_count,
494 });
495 let handled = !func(input).propagate;
496 self.state.borrow_mut().callbacks.input = Some(func);
497
498 if handled { Some(0) } else { Some(1) }
499 }
500
501 fn handle_xbutton_msg(
502 &self,
503 handle: HWND,
504 wparam: WPARAM,
505 lparam: LPARAM,
506 handler: impl Fn(&Self, HWND, MouseButton, LPARAM) -> Option<isize>,
507 ) -> Option<isize> {
508 let nav_dir = match wparam.hiword() {
509 XBUTTON1 => NavigationDirection::Back,
510 XBUTTON2 => NavigationDirection::Forward,
511 _ => return Some(1),
512 };
513 handler(self, handle, MouseButton::Navigate(nav_dir), lparam)
514 }
515
516 fn handle_mouse_wheel_msg(
517 &self,
518 handle: HWND,
519 wparam: WPARAM,
520 lparam: LPARAM,
521 ) -> Option<isize> {
522 let modifiers = current_modifiers();
523 let mut lock = self.state.borrow_mut();
524 let Some(mut func) = lock.callbacks.input.take() else {
525 return Some(1);
526 };
527 let scale_factor = lock.scale_factor;
528 let wheel_scroll_amount = match modifiers.shift {
529 true => lock.system_settings.mouse_wheel_settings.wheel_scroll_chars,
530 false => lock.system_settings.mouse_wheel_settings.wheel_scroll_lines,
531 };
532 drop(lock);
533
534 let wheel_distance =
535 (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
536 let mut cursor_point = POINT {
537 x: lparam.signed_loword().into(),
538 y: lparam.signed_hiword().into(),
539 };
540 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
541 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
542 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
543 delta: ScrollDelta::Lines(match modifiers.shift {
544 true => Point {
545 x: wheel_distance,
546 y: 0.0,
547 },
548 false => Point {
549 y: wheel_distance,
550 x: 0.0,
551 },
552 }),
553 modifiers,
554 touch_phase: TouchPhase::Moved,
555 });
556 let handled = !func(input).propagate;
557 self.state.borrow_mut().callbacks.input = Some(func);
558
559 if handled { Some(0) } else { Some(1) }
560 }
561
562 fn handle_mouse_horizontal_wheel_msg(
563 &self,
564 handle: HWND,
565 wparam: WPARAM,
566 lparam: LPARAM,
567 ) -> Option<isize> {
568 let mut lock = self.state.borrow_mut();
569 let Some(mut func) = lock.callbacks.input.take() else {
570 return Some(1);
571 };
572 let scale_factor = lock.scale_factor;
573 let wheel_scroll_chars = lock.system_settings.mouse_wheel_settings.wheel_scroll_chars;
574 drop(lock);
575
576 let wheel_distance =
577 (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
578 let mut cursor_point = POINT {
579 x: lparam.signed_loword().into(),
580 y: lparam.signed_hiword().into(),
581 };
582 unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
583 let event = PlatformInput::ScrollWheel(ScrollWheelEvent {
584 position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
585 delta: ScrollDelta::Lines(Point {
586 x: wheel_distance,
587 y: 0.0,
588 }),
589 modifiers: current_modifiers(),
590 touch_phase: TouchPhase::Moved,
591 });
592 let handled = !func(event).propagate;
593 self.state.borrow_mut().callbacks.input = Some(func);
594
595 if handled { Some(0) } else { Some(1) }
596 }
597
598 fn retrieve_caret_position(&self) -> Option<POINT> {
599 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
600 let caret_range = input_handler.selected_text_range(false)?;
601 let caret_position = input_handler.bounds_for_range(caret_range.range)?;
602 Some(POINT {
603 // logical to physical
604 x: (caret_position.origin.x.0 * scale_factor) as i32,
605 y: (caret_position.origin.y.0 * scale_factor) as i32
606 + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
607 })
608 })
609 }
610
611 fn handle_ime_position(&self, handle: HWND) -> Option<isize> {
612 unsafe {
613 let ctx = ImmGetContext(handle);
614
615 let Some(caret_position) = self.retrieve_caret_position() else {
616 return Some(0);
617 };
618 {
619 let config = COMPOSITIONFORM {
620 dwStyle: CFS_POINT,
621 ptCurrentPos: caret_position,
622 ..Default::default()
623 };
624 ImmSetCompositionWindow(ctx, &config as _).ok().log_err();
625 }
626 {
627 let config = CANDIDATEFORM {
628 dwStyle: CFS_CANDIDATEPOS,
629 ptCurrentPos: caret_position,
630 ..Default::default()
631 };
632 ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
633 }
634 ImmReleaseContext(handle, ctx).ok().log_err();
635 Some(0)
636 }
637 }
638
639 fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
640 let ctx = unsafe { ImmGetContext(handle) };
641 let result = self.handle_ime_composition_inner(ctx, lparam);
642 unsafe { ImmReleaseContext(handle, ctx).ok().log_err() };
643 result
644 }
645
646 fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {
647 let lparam = lparam.0 as u32;
648 if lparam == 0 {
649 // Japanese IME may send this message with lparam = 0, which indicates that
650 // there is no composition string.
651 self.with_input_handler(|input_handler| {
652 input_handler.replace_text_in_range(None, "");
653 })?;
654 Some(0)
655 } else {
656 if lparam & GCS_COMPSTR.0 > 0 {
657 let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
658 let caret_pos =
659 (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
660 let pos = retrieve_composition_cursor_position(ctx);
661 pos..pos
662 });
663 self.with_input_handler(|input_handler| {
664 input_handler.replace_and_mark_text_in_range(None, &comp_string, caret_pos);
665 })?;
666 }
667 if lparam & GCS_RESULTSTR.0 > 0 {
668 let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
669 self.with_input_handler(|input_handler| {
670 input_handler.replace_text_in_range(None, &comp_result);
671 })?;
672 return Some(0);
673 }
674
675 // currently, we don't care other stuff
676 None
677 }
678 }
679
680 /// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
681 fn handle_calc_client_size(
682 &self,
683 handle: HWND,
684 wparam: WPARAM,
685 lparam: LPARAM,
686 ) -> Option<isize> {
687 if !self.hide_title_bar || self.state.borrow().is_fullscreen() || wparam.0 == 0 {
688 return None;
689 }
690
691 let is_maximized = self.state.borrow().is_maximized();
692 let insets = get_client_area_insets(handle, is_maximized, self.windows_version);
693 // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
694 let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
695 let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
696
697 requested_client_rect[0].left += insets.left;
698 requested_client_rect[0].top += insets.top;
699 requested_client_rect[0].right -= insets.right;
700 requested_client_rect[0].bottom -= insets.bottom;
701
702 // Fix auto hide taskbar not showing. This solution is based on the approach
703 // used by Chrome. However, it may result in one row of pixels being obscured
704 // in our client area. But as Chrome says, "there seems to be no better solution."
705 if is_maximized
706 && let Some(ref taskbar_position) = self
707 .state
708 .borrow()
709 .system_settings
710 .auto_hide_taskbar_position
711 {
712 // For the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
713 // so the window isn't treated as a "fullscreen app", which would cause
714 // the taskbar to disappear.
715 match taskbar_position {
716 AutoHideTaskbarPosition::Left => {
717 requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
718 }
719 AutoHideTaskbarPosition::Top => {
720 requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
721 }
722 AutoHideTaskbarPosition::Right => {
723 requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
724 }
725 AutoHideTaskbarPosition::Bottom => {
726 requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
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);
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 && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()
1130 {
1131 log::info!("System settings changed: {}", parameter_string);
1132 if parameter_string.as_str() == "ImmersiveColorSet" {
1133 let new_appearance = system_appearance()
1134 .context("unable to get system appearance when handling ImmersiveColorSet")
1135 .log_err()?;
1136 let mut lock = self.state.borrow_mut();
1137 if new_appearance != lock.appearance {
1138 lock.appearance = new_appearance;
1139 let mut callback = lock.callbacks.appearance_changed.take()?;
1140 drop(lock);
1141 callback();
1142 self.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1143 configure_dwm_dark_mode(handle, new_appearance);
1144 }
1145 }
1146 }
1147 Some(0)
1148 }
1149
1150 fn handle_input_language_changed(&self) -> Option<isize> {
1151 unsafe {
1152 PostMessageW(
1153 Some(self.platform_window_handle),
1154 WM_GPUI_KEYBOARD_LAYOUT_CHANGED,
1155 WPARAM(self.validation_number),
1156 LPARAM(0),
1157 )
1158 .log_err();
1159 }
1160 Some(0)
1161 }
1162
1163 fn handle_window_visibility_changed(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1164 if wparam.0 == 1 {
1165 self.draw_window(handle, false);
1166 }
1167 None
1168 }
1169
1170 fn handle_device_change_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1171 if wparam.0 == DBT_DEVNODES_CHANGED as usize {
1172 // The reason for sending this message is to actually trigger a redraw of the window.
1173 unsafe {
1174 PostMessageW(
1175 Some(handle),
1176 WM_GPUI_FORCE_UPDATE_WINDOW,
1177 WPARAM(0),
1178 LPARAM(0),
1179 )
1180 .log_err();
1181 }
1182 // If the GPU device is lost, this redraw will take care of recreating the device context.
1183 // The WM_GPUI_FORCE_UPDATE_WINDOW message will take care of redrawing the window, after
1184 // the device context has been recreated.
1185 self.draw_window(handle, true)
1186 } else {
1187 // Other device change messages are not handled.
1188 None
1189 }
1190 }
1191
1192 #[inline]
1193 fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1194 let mut request_frame = self.state.borrow_mut().callbacks.request_frame.take()?;
1195 request_frame(RequestFrameOptions {
1196 require_presentation: false,
1197 force_render,
1198 });
1199 self.state.borrow_mut().callbacks.request_frame = Some(request_frame);
1200 unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1201 Some(0)
1202 }
1203
1204 #[inline]
1205 fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {
1206 let code_point = wparam.loword();
1207 let mut lock = self.state.borrow_mut();
1208 // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630
1209 match code_point {
1210 0xD800..=0xDBFF => {
1211 // High surrogate, wait for low surrogate
1212 lock.pending_surrogate = Some(code_point);
1213 None
1214 }
1215 0xDC00..=0xDFFF => {
1216 if let Some(high_surrogate) = lock.pending_surrogate.take() {
1217 // Low surrogate, combine with pending high surrogate
1218 String::from_utf16(&[high_surrogate, code_point]).ok()
1219 } else {
1220 // Invalid low surrogate without a preceding high surrogate
1221 log::warn!(
1222 "Received low surrogate without a preceding high surrogate: {code_point:x}"
1223 );
1224 None
1225 }
1226 }
1227 _ => {
1228 lock.pending_surrogate = None;
1229 char::from_u32(code_point as u32)
1230 .filter(|c| !c.is_control())
1231 .map(|c| c.to_string())
1232 }
1233 }
1234 }
1235
1236 fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {
1237 let mut lock = self.state.borrow_mut();
1238 if !lock.hovered {
1239 lock.hovered = true;
1240 unsafe {
1241 TrackMouseEvent(&mut TRACKMOUSEEVENT {
1242 cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1243 dwFlags: flags,
1244 hwndTrack: handle,
1245 dwHoverTime: HOVER_DEFAULT,
1246 })
1247 .log_err()
1248 };
1249 if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1250 drop(lock);
1251 callback(true);
1252 self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1253 }
1254 }
1255 }
1256
1257 fn with_input_handler<F, R>(&self, f: F) -> Option<R>
1258 where
1259 F: FnOnce(&mut PlatformInputHandler) -> R,
1260 {
1261 let mut input_handler = self.state.borrow_mut().input_handler.take()?;
1262 let result = f(&mut input_handler);
1263 self.state.borrow_mut().input_handler = Some(input_handler);
1264 Some(result)
1265 }
1266
1267 fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>
1268 where
1269 F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1270 {
1271 let mut lock = self.state.borrow_mut();
1272 let mut input_handler = lock.input_handler.take()?;
1273 let scale_factor = lock.scale_factor;
1274 drop(lock);
1275 let result = f(&mut input_handler, scale_factor);
1276 self.state.borrow_mut().input_handler = Some(input_handler);
1277 result
1278 }
1279}
1280
1281#[inline]
1282fn translate_message(handle: HWND, wparam: WPARAM, lparam: LPARAM) {
1283 let msg = MSG {
1284 hwnd: handle,
1285 message: WM_KEYDOWN,
1286 wParam: wparam,
1287 lParam: lparam,
1288 // It seems like leaving the following two parameters empty doesn't break key events, they still work as expected.
1289 // But if any bugs pop up after this PR, this is probably the place to look first.
1290 time: 0,
1291 pt: POINT::default(),
1292 };
1293 unsafe { TranslateMessage(&msg).ok().log_err() };
1294}
1295
1296fn handle_key_event<F>(
1297 handle: HWND,
1298 wparam: WPARAM,
1299 lparam: LPARAM,
1300 state: &mut WindowsWindowState,
1301 f: F,
1302) -> Option<PlatformInput>
1303where
1304 F: FnOnce(Keystroke) -> PlatformInput,
1305{
1306 let virtual_key = VIRTUAL_KEY(wparam.loword());
1307 let mut modifiers = current_modifiers();
1308
1309 match virtual_key {
1310 VK_SHIFT | VK_CONTROL | VK_MENU | VK_LWIN | VK_RWIN => {
1311 if state
1312 .last_reported_modifiers
1313 .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1314 {
1315 return None;
1316 }
1317 state.last_reported_modifiers = Some(modifiers);
1318 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1319 modifiers,
1320 capslock: current_capslock(),
1321 }))
1322 }
1323 VK_PACKET => {
1324 translate_message(handle, wparam, lparam);
1325 None
1326 }
1327 VK_CAPITAL => {
1328 let capslock = current_capslock();
1329 if state
1330 .last_reported_capslock
1331 .is_some_and(|prev_capslock| prev_capslock == capslock)
1332 {
1333 return None;
1334 }
1335 state.last_reported_capslock = Some(capslock);
1336 Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1337 modifiers,
1338 capslock,
1339 }))
1340 }
1341 vkey => {
1342 let vkey = if vkey == VK_PROCESSKEY {
1343 VIRTUAL_KEY(unsafe { ImmGetVirtualKey(handle) } as u16)
1344 } else {
1345 vkey
1346 };
1347 let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1348 Some(f(keystroke))
1349 }
1350 }
1351}
1352
1353fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1354 Some(
1355 match vkey {
1356 VK_SPACE => "space",
1357 VK_BACK => "backspace",
1358 VK_RETURN => "enter",
1359 VK_TAB => "tab",
1360 VK_UP => "up",
1361 VK_DOWN => "down",
1362 VK_RIGHT => "right",
1363 VK_LEFT => "left",
1364 VK_HOME => "home",
1365 VK_END => "end",
1366 VK_PRIOR => "pageup",
1367 VK_NEXT => "pagedown",
1368 VK_BROWSER_BACK => "back",
1369 VK_BROWSER_FORWARD => "forward",
1370 VK_ESCAPE => "escape",
1371 VK_INSERT => "insert",
1372 VK_DELETE => "delete",
1373 VK_APPS => "menu",
1374 VK_F1 => "f1",
1375 VK_F2 => "f2",
1376 VK_F3 => "f3",
1377 VK_F4 => "f4",
1378 VK_F5 => "f5",
1379 VK_F6 => "f6",
1380 VK_F7 => "f7",
1381 VK_F8 => "f8",
1382 VK_F9 => "f9",
1383 VK_F10 => "f10",
1384 VK_F11 => "f11",
1385 VK_F12 => "f12",
1386 VK_F13 => "f13",
1387 VK_F14 => "f14",
1388 VK_F15 => "f15",
1389 VK_F16 => "f16",
1390 VK_F17 => "f17",
1391 VK_F18 => "f18",
1392 VK_F19 => "f19",
1393 VK_F20 => "f20",
1394 VK_F21 => "f21",
1395 VK_F22 => "f22",
1396 VK_F23 => "f23",
1397 VK_F24 => "f24",
1398 _ => return None,
1399 }
1400 .to_string(),
1401 )
1402}
1403
1404fn parse_normal_key(
1405 vkey: VIRTUAL_KEY,
1406 lparam: LPARAM,
1407 mut modifiers: Modifiers,
1408) -> Option<Keystroke> {
1409 let mut key_char = None;
1410 let key = parse_immutable(vkey).or_else(|| {
1411 let scan_code = lparam.hiword() & 0xFF;
1412 key_char = generate_key_char(
1413 vkey,
1414 scan_code as u32,
1415 modifiers.control,
1416 modifiers.shift,
1417 modifiers.alt,
1418 );
1419 get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1420 })?;
1421 Some(Keystroke {
1422 modifiers,
1423 key,
1424 key_char,
1425 })
1426}
1427
1428fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1429 unsafe {
1430 let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1431 if string_len >= 0 {
1432 let mut buffer = vec![0u8; string_len as usize + 2];
1433 ImmGetCompositionStringW(
1434 ctx,
1435 comp_type,
1436 Some(buffer.as_mut_ptr() as _),
1437 string_len as _,
1438 );
1439 let wstring = std::slice::from_raw_parts::<u16>(
1440 buffer.as_mut_ptr().cast::<u16>(),
1441 string_len as usize / 2,
1442 );
1443 Some(String::from_utf16_lossy(wstring))
1444 } else {
1445 None
1446 }
1447 }
1448}
1449
1450#[inline]
1451fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1452 unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1453}
1454
1455#[inline]
1456fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1457 unsafe { GetKeyState(vkey.0 as i32) < 0 }
1458}
1459
1460#[inline]
1461pub(crate) fn current_modifiers() -> Modifiers {
1462 Modifiers {
1463 control: is_virtual_key_pressed(VK_CONTROL),
1464 alt: is_virtual_key_pressed(VK_MENU),
1465 shift: is_virtual_key_pressed(VK_SHIFT),
1466 platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1467 function: false,
1468 }
1469}
1470
1471#[inline]
1472pub(crate) fn current_capslock() -> Capslock {
1473 let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1474 Capslock { on }
1475}
1476
1477fn get_client_area_insets(
1478 handle: HWND,
1479 is_maximized: bool,
1480 windows_version: WindowsVersion,
1481) -> RECT {
1482 // For maximized windows, Windows outdents the window rect from the screen's client rect
1483 // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1484 // on all sides (including the top) to avoid the client area extending onto adjacent
1485 // monitors.
1486 //
1487 // For non-maximized windows, things become complicated:
1488 //
1489 // - On Windows 10
1490 // The top inset must be zero, since if there is any nonclient area, Windows will draw
1491 // a full native titlebar outside the client area. (This doesn't occur in the maximized
1492 // case.)
1493 //
1494 // - On Windows 11
1495 // The top inset is calculated using an empirical formula that I derived through various
1496 // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1497 let dpi = unsafe { GetDpiForWindow(handle) };
1498 let frame_thickness = get_frame_thickness(dpi);
1499 let top_insets = if is_maximized {
1500 frame_thickness
1501 } else {
1502 match windows_version {
1503 WindowsVersion::Win10 => 0,
1504 WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1505 }
1506 };
1507 RECT {
1508 left: frame_thickness,
1509 top: top_insets,
1510 right: frame_thickness,
1511 bottom: frame_thickness,
1512 }
1513}
1514
1515// there is some additional non-visible space when talking about window
1516// borders on Windows:
1517// - SM_CXSIZEFRAME: The resize handle.
1518// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1519fn get_frame_thickness(dpi: u32) -> i32 {
1520 let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1521 let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1522 resize_frame_thickness + padding_thickness
1523}
1524
1525fn notify_frame_changed(handle: HWND) {
1526 unsafe {
1527 SetWindowPos(
1528 handle,
1529 None,
1530 0,
1531 0,
1532 0,
1533 0,
1534 SWP_FRAMECHANGED
1535 | SWP_NOACTIVATE
1536 | SWP_NOCOPYBITS
1537 | SWP_NOMOVE
1538 | SWP_NOOWNERZORDER
1539 | SWP_NOREPOSITION
1540 | SWP_NOSENDCHANGING
1541 | SWP_NOSIZE
1542 | SWP_NOZORDER,
1543 )
1544 .log_err();
1545 }
1546}