Skip to content

Commit f4f0ec0

Browse files
authored
Keep a lone Alt or F10 from freezing the Desktop window on Windows (#1648)
* Keep a lone Alt or F10 from freezing the Desktop window on Windows A lone Alt or F10 makes DefWindowProc send the top-level window WM_SYSCOMMAND/SC_KEYMENU with lParam 0, which starts a modal menu loop on the window's thread even though the window has no menu bar. While the thread is in it, WebView2's page and OpenBot stop hearing each other: an invoke's answer does not reach the page and the page's next invoke does not reach OpenBot, until a click, Esc or Alt+Tab. On a Windows box a lone Alt during `local update` held the update's answer back from the page for 530 s, until a right-click on the tray icon. The main and Status windows now answer that one command themselves. Alt+Space, Alt with a letter and a click on the window icon still reach DefWindowProc, and the page still gets Alt's keydown and keyup. OpenBot also stops pressing Alt itself: tao's set_focus presses and releases Alt when SetForegroundWindow is refused. Every window now comes forward through one helper that uses SetForegroundWindow and flashes the taskbar when Windows refuses, as bring_to_front already did. * Allow the lone-menu-key rule to go unused off Windows
1 parent 5df3238 commit f4f0ec0

3 files changed

Lines changed: 345 additions & 24 deletions

File tree

‎desktop/src-tauri/src/desktop_host_access.rs‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,7 @@ impl<R: tauri::Runtime> NativeApproval<R> {
139139
.get_webview_window("main")
140140
.ok_or_else(|| refused("The local OpenBot window is closed."))?;
141141
window.show().map_err(|error| refused(error.to_string()))?;
142-
window
143-
.set_focus()
144-
.map_err(|error| refused(error.to_string()))?;
142+
crate::focus(&window, "a Bot asks to use this computer");
145143
Ok(window)
146144
}
147145

@@ -151,9 +149,7 @@ impl<R: tauri::Runtime> NativeApproval<R> {
151149
.get_webview_window("main")
152150
.ok_or_else(|| refused("The local OpenBot window is closed."))?;
153151
window.show().map_err(|error| refused(error.to_string()))?;
154-
window
155-
.set_focus()
156-
.map_err(|error| refused(error.to_string()))?;
152+
crate::focus(&window, "a Bot asks to use this computer");
157153
let allowed = self
158154
.0
159155
.dialog()
@@ -182,9 +178,7 @@ impl<R: tauri::Runtime> HostApprovalUi for NativeApproval<R> {
182178
.get_webview_window("main")
183179
.ok_or_else(|| refused("The local OpenBot window is closed."))?;
184180
window.show().map_err(|error| refused(error.to_string()))?;
185-
window
186-
.set_focus()
187-
.map_err(|error| refused(error.to_string()))?;
181+
crate::focus(&window, "a Bot asks to use this computer");
188182
let picked = self
189183
.0
190184
.dialog()

‎desktop/src-tauri/src/key_menu.rs‎

Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
//! WINDOWS. A lone Alt or F10 never puts an OpenBot window into Windows' menu mode.
2+
//!
3+
//! Alt pressed and released on its own, or F10, makes `DefWindowProc` send the top-level window
4+
//! `WM_SYSCOMMAND` with `SC_KEYMENU` and an `lParam` of 0 ("the character code of the key that is
5+
//! used with the ALT key", none). Handled by `DefWindowProc`, that starts a modal menu loop on the
6+
//! window's thread even though OpenBot's windows have no menu bar, so nothing on screen says so.
7+
//! While the thread is in it, WebView2's page and OpenBot stop hearing each other in both
8+
//! directions: an invoke's answer does not reach the page and the page's next invoke does not
9+
//! reach OpenBot. The page itself keeps painting, so its timers tick. It lasts until a click
10+
//! anywhere, Esc or Alt+Tab ends the menu loop. tao (0.37.2) hands `SC_KEYMENU` to `DefWindowProc`
11+
//! as it is.
12+
//!
13+
//! MEASURED on Windows box H (internal-ce5bfbece1df): a lone Alt reached the setup window at
14+
//! 20:54:32 during `local update`. The page's one-second download poll stopped there, and the
15+
//! update's answer, handed back at 20:56:41, reached the page 530.2 s later, within a second of
16+
//! a right-click on the tray icon. Other Tauri apps measured the same and fixed it the same way,
17+
//! by answering `SC_KEYMENU` with a zero `lParam` themselves.
18+
//!
19+
//! What still reaches `DefWindowProc`: Alt+Space (`lParam` is the space), which opens the window
20+
//! menu as on every Windows window; Alt with a letter; a click on the window's icon
21+
//! (`SC_MOUSEMENU`). The page still gets Alt's and F10's own keydown and keyup, which come before
22+
//! this command and are not touched, so its Alt shortcuts work as they did.
23+
24+
/// `SC_KEYMENU` (winuser.h).
25+
#[cfg_attr(not(windows), allow(dead_code))]
26+
const SC_KEYMENU: usize = 0xF100;
27+
28+
/// The bits of a `WM_SYSCOMMAND` `wParam` that name the command: "the four low-order bits of the
29+
/// wParam parameter are used internally by the system" (`WM_SYSCOMMAND`).
30+
#[cfg_attr(not(windows), allow(dead_code))]
31+
const COMMAND: usize = 0xFFF0;
32+
33+
/// Whether a `WM_SYSCOMMAND` with `wparam` and `lparam` is a menu key pressed alone: Alt or F10,
34+
/// with no character after it.
35+
#[cfg_attr(not(windows), allow(dead_code))]
36+
pub fn lone_menu_key(wparam: usize, lparam: isize) -> bool {
37+
wparam & COMMAND == SC_KEYMENU && lparam == 0
38+
}
39+
40+
/// The id of this subclass among the window's subclasses.
41+
#[cfg(windows)]
42+
const SUBCLASS: usize = 0x0A17;
43+
44+
/**
45+
Keeps the top-level window `hwnd` out of menu mode on a lone Alt or F10 (see the module). Called on
46+
the window's own thread, which `SetWindowSubclass` requires. False when Windows refused.
47+
*/
48+
#[cfg(windows)]
49+
pub fn ignore_lone_menu_key(hwnd: isize) -> bool {
50+
use windows::Win32::Foundation::HWND;
51+
use windows::Win32::UI::Shell::SetWindowSubclass;
52+
// SAFETY: `hwnd` is a live window of this thread's; the subclass procedure keeps no state.
53+
unsafe { SetWindowSubclass(HWND(hwnd as *mut _), Some(subclass), SUBCLASS, 0) }.as_bool()
54+
}
55+
56+
/// The window's messages, ahead of tao's: a lone Alt or F10's `SC_KEYMENU` stops here, answered
57+
/// as handled (0, "an application should return zero if it processes this message"); every other
58+
/// message goes on as before.
59+
#[cfg(windows)]
60+
unsafe extern "system" fn subclass(
61+
hwnd: windows::Win32::Foundation::HWND,
62+
message: u32,
63+
wparam: windows::Win32::Foundation::WPARAM,
64+
lparam: windows::Win32::Foundation::LPARAM,
65+
_id: usize,
66+
_data: usize,
67+
) -> windows::Win32::Foundation::LRESULT {
68+
use windows::Win32::Foundation::LRESULT;
69+
use windows::Win32::UI::Shell::DefSubclassProc;
70+
use windows::Win32::UI::WindowsAndMessaging::WM_SYSCOMMAND;
71+
if message == WM_SYSCOMMAND && lone_menu_key(wparam.0, lparam.0) {
72+
return LRESULT(0);
73+
}
74+
// SAFETY: called by Windows on the window's own thread with its own message.
75+
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
76+
}
77+
78+
#[cfg(test)]
79+
mod tests {
80+
use super::*;
81+
82+
/// The commands a lone Alt or F10 sends are the ones dropped; Alt+Space, Alt with a letter,
83+
/// a click on the window's icon and every other command still reach `DefWindowProc`.
84+
#[test]
85+
fn only_a_menu_key_pressed_alone_is_dropped() {
86+
// Alt or F10 alone, with or without the system's low bits set.
87+
assert!(lone_menu_key(0xF100, 0));
88+
assert!(lone_menu_key(0xF100 | 0x0002, 0));
89+
// Alt+Space opens the window menu; Alt+F looks for a menu letter.
90+
assert!(!lone_menu_key(0xF100, b' ' as isize));
91+
assert!(!lone_menu_key(0xF100, b'f' as isize));
92+
// SC_MOUSEMENU (a click on the icon), SC_CLOSE (Alt+F4), SC_MINIMIZE, SC_RESTORE.
93+
for command in [0xF090, 0xF060, 0xF020, 0xF120] {
94+
assert!(!lone_menu_key(command, 0), "{command:#x}");
95+
}
96+
}
97+
98+
/**
99+
A real lone Alt's `SC_KEYMENU`, posted to two windows on a thread of their own, as tao's are:
100+
a plain one goes into menu mode (`GetGUIThreadInfo` says `GUI_INMENUMODE`), which shows this
101+
desktop reproduces it. OpenBot's, with the subclass, never goes into menu mode, and a message
102+
posted to it after (as wry posts an invoke's answer) is handled at once. Without the subclass
103+
the second window behaves as the first and this fails.
104+
*/
105+
#[cfg(windows)]
106+
#[test]
107+
fn a_lone_alt_puts_no_subclassed_window_in_menu_mode() {
108+
use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering};
109+
use std::sync::mpsc;
110+
use std::time::{Duration, Instant};
111+
use windows::core::{w, PCWSTR};
112+
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
113+
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
114+
use windows::Win32::System::Threading::GetCurrentThreadId;
115+
use windows::Win32::UI::WindowsAndMessaging::{
116+
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetGUIThreadInfo,
117+
GetMessageW, PostMessageW, PostThreadMessageW, RegisterClassExW, SendMessageTimeoutW,
118+
SetForegroundWindow, ShowWindow, TranslateMessage, GUITHREADINFO, GUI_INMENUMODE, MSG,
119+
SMTO_ABORTIFHUNG, SW_SHOW, WM_APP, WM_CANCELMODE, WM_QUIT, WM_SYSCOMMAND, WNDCLASSEXW,
120+
WS_OVERLAPPEDWINDOW,
121+
};
122+
123+
static PLAIN: AtomicIsize = AtomicIsize::new(0);
124+
static PLAIN_HEARD: AtomicUsize = AtomicUsize::new(0);
125+
static OURS_HEARD: AtomicUsize = AtomicUsize::new(0);
126+
const FRONT: u32 = WM_APP + 1;
127+
128+
unsafe extern "system" fn procedure(
129+
window: HWND,
130+
message: u32,
131+
wparam: WPARAM,
132+
lparam: LPARAM,
133+
) -> LRESULT {
134+
// Each window comes to the front on its own thread before its Alt, as the window a
135+
// person presses Alt in is.
136+
if message == FRONT {
137+
let _ = unsafe { SetForegroundWindow(window) };
138+
return LRESULT(0);
139+
}
140+
if message == WM_APP {
141+
let heard = if window.0 as isize == PLAIN.load(Ordering::SeqCst) {
142+
&PLAIN_HEARD
143+
} else {
144+
&OURS_HEARD
145+
};
146+
heard.fetch_add(1, Ordering::SeqCst);
147+
return LRESULT(0);
148+
}
149+
// SAFETY: Windows's own handling of a window's message.
150+
unsafe { DefWindowProcW(window, message, wparam, lparam) }
151+
}
152+
153+
// SAFETY: plain calls on windows this thread creates and owns.
154+
let window = |instance: HINSTANCE| unsafe {
155+
let window = CreateWindowExW(
156+
Default::default(),
157+
w!("OpenBotKeyMenuTest"),
158+
w!("OpenBot"),
159+
WS_OVERLAPPEDWINDOW,
160+
100,
161+
100,
162+
600,
163+
400,
164+
None,
165+
None,
166+
Some(instance),
167+
None,
168+
)
169+
.unwrap();
170+
let _ = ShowWindow(window, SW_SHOW);
171+
window
172+
};
173+
174+
let (made, windows) = mpsc::channel();
175+
let (finished, done) = mpsc::channel();
176+
std::thread::spawn(move || {
177+
// SAFETY: this thread's own windows and message loop.
178+
unsafe {
179+
let instance: HINSTANCE = GetModuleHandleW(PCWSTR::null()).map(Into::into).unwrap();
180+
let class = WNDCLASSEXW {
181+
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
182+
lpfnWndProc: Some(procedure),
183+
hInstance: instance,
184+
lpszClassName: w!("OpenBotKeyMenuTest"),
185+
..Default::default()
186+
};
187+
RegisterClassExW(&class);
188+
let plain = window(instance);
189+
PLAIN.store(plain.0 as isize, Ordering::SeqCst);
190+
let ours = window(instance);
191+
let subclassed = ignore_lone_menu_key(ours.0 as isize);
192+
made.send((
193+
plain.0 as isize,
194+
ours.0 as isize,
195+
GetCurrentThreadId(),
196+
subclassed,
197+
))
198+
.unwrap();
199+
let mut message = MSG::default();
200+
while GetMessageW(&mut message, None, 0, 0).as_bool() {
201+
let _ = TranslateMessage(&message);
202+
DispatchMessageW(&message);
203+
}
204+
let _ = DestroyWindow(plain);
205+
let _ = DestroyWindow(ours);
206+
}
207+
let _ = finished.send(());
208+
});
209+
let (plain, ours, thread, subclassed) =
210+
windows.recv_timeout(Duration::from_secs(10)).unwrap();
211+
assert!(subclassed, "Windows refused the subclass");
212+
213+
let in_menu_mode = || {
214+
let mut info = GUITHREADINFO {
215+
cbSize: std::mem::size_of::<GUITHREADINFO>() as u32,
216+
..Default::default()
217+
};
218+
// SAFETY: a read-only question about the window thread, into a struct sized for it.
219+
unsafe { GetGUIThreadInfo(thread, &mut info) }.is_ok()
220+
&& info.flags.contains(GUI_INMENUMODE)
221+
};
222+
let within = |limit: Duration, done: &dyn Fn() -> bool| {
223+
let until = Instant::now() + limit;
224+
while Instant::now() < until {
225+
if done() {
226+
return true;
227+
}
228+
std::thread::sleep(Duration::from_millis(20));
229+
}
230+
done()
231+
};
232+
// A lone Alt's command, then a message posted after it; what each window did with them.
233+
let lone_alt = |window: isize, heard: &'static AtomicUsize| {
234+
let window = HWND(window as *mut _);
235+
let before = heard.load(Ordering::SeqCst);
236+
// SAFETY: posting to a live window of the other thread.
237+
unsafe {
238+
PostMessageW(Some(window), FRONT, WPARAM(0), LPARAM(0)).unwrap();
239+
PostMessageW(Some(window), WM_SYSCOMMAND, WPARAM(SC_KEYMENU), LPARAM(0)).unwrap();
240+
PostMessageW(Some(window), WM_APP, WPARAM(0), LPARAM(0)).unwrap();
241+
}
242+
let menu_mode = within(Duration::from_secs(2), &in_menu_mode);
243+
let answered = within(Duration::from_secs(1), &|| {
244+
heard.load(Ordering::SeqCst) > before
245+
});
246+
// Out of menu mode again, as a click does: `WM_CANCELMODE` "cancels internal menu
247+
// processing", and a menu loop still takes a sent message.
248+
// SAFETY: a message with no pointers, to a live window, never waiting long.
249+
let _ = unsafe {
250+
SendMessageTimeoutW(
251+
window,
252+
WM_CANCELMODE,
253+
WPARAM(0),
254+
LPARAM(0),
255+
SMTO_ABORTIFHUNG,
256+
2_000,
257+
None,
258+
)
259+
};
260+
assert!(
261+
within(Duration::from_secs(5), &|| !in_menu_mode()),
262+
"still in menu mode"
263+
);
264+
(menu_mode, answered)
265+
};
266+
267+
let (plain_menu_mode, plain_answered) = lone_alt(plain, &PLAIN_HEARD);
268+
let (ours_menu_mode, ours_answered) = lone_alt(ours, &OURS_HEARD);
269+
// SAFETY: a message to the window thread's own queue.
270+
let _ = unsafe { PostThreadMessageW(thread, WM_QUIT, WPARAM(0), LPARAM(0)) };
271+
let _ = done.recv_timeout(Duration::from_secs(5));
272+
273+
assert!(
274+
plain_menu_mode,
275+
"a plain window did not go into menu mode, so this desktop cannot show the fix"
276+
);
277+
assert!(
278+
!ours_menu_mode,
279+
"a lone Alt put OpenBot's window into menu mode"
280+
);
281+
assert!(
282+
ours_answered,
283+
"a message posted after a lone Alt was not handled (plain window: {plain_answered})"
284+
);
285+
}
286+
}

0 commit comments

Comments
 (0)