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