Skip to content

Commit 2c6405a

Browse files
committed
fix(runtime): don't pump messages inside XAML's dispatcher; keep Application.Current an Application
WinUI 3 apps froze a few seconds after they started rendering every frame: timers, requestAnimationFrame and native callbacks all stopped while the UI thread sat idle in GetMessage. WinUI's dispatcher is a Microsoft.UI.Dispatching.DispatcherQueue, so init_ui_dispatcher finds no Windows.System.DispatcherQueue and makes its own controller. needs_win32_pump() was then true under XAML too, and runtime_pump_timers (and the napi engines' host pump) drained the thread's messages with PeekMessage/DispatchMessage from inside the host's DispatcherQueue work item. Dispatching the queues' wake messages re-entrantly can lose a wake, after which XAML's queue, its timers and the runtime's own queue never run again. A frame loop makes it happen within seconds. host_pumps_messages() now detects a XAML host (Microsoft.UI.Xaml.dll loaded), and the host pumps leave messages to XAML's loop there. Console executables and workers keep pumping. Also: Application.Current came back as Microsoft.UI.Xaml. IApplicationOverrides, with no Exit, so core could never end the app when its last window closed. The template's C# App has no WinMD, so CsWinRT reports one of its interfaces as the runtime class name. resolve_runtime_class no longer swaps a declared class for an interface name.
1 parent b1a25b2 commit 2c6405a

5 files changed

Lines changed: 67 additions & 4 deletions

File tree

‎nativescript/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,8 @@ pub extern "C" fn runtime_pump_timers() {
443443
runtime::node_api::drain();
444444
// This frame's requestAnimationFrame callbacks, then their microtasks.
445445
runtime::animation_frames::pump();
446-
if runtime::ui_dispatcher::needs_win32_pump() {
446+
// (a WinUI host has a runtime-made dispatcher too: see `host_pumps_messages`)
447+
if runtime::ui_dispatcher::needs_win32_pump() && !runtime::ui_dispatcher::host_pumps_messages() {
447448
runtime::pump_messages();
448449
} else {
449450
runtime::pump_dispatcher();

‎runtime/src/napi_engine/event_loop.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,20 @@ pub fn install_loop_natives(env: &Env) -> napi::Result<()> {
6666
/// `run_event_loop` repeats; hosts that own their own frame loop (e.g. the WinUI 3 DLL, driven
6767
/// from `CompositionTarget.Rendering`) call it directly once per frame instead.
6868
pub fn pump_once<F: FnMut()>(env: &Env, drain_microtasks: &mut F) {
69+
pump_iteration(env, drain_microtasks, true);
70+
}
71+
72+
/// `pump_once` for a host that calls it from its own message loop: Win32 messages are left to that
73+
/// loop when it is XAML's (see `ui_dispatcher::host_pumps_messages`).
74+
pub fn pump_once_from_host<F: FnMut()>(env: &Env, drain_microtasks: &mut F) {
75+
pump_iteration(env, drain_microtasks, !crate::ui_dispatcher::host_pumps_messages());
76+
}
77+
78+
fn pump_iteration<F: FnMut()>(env: &Env, drain_microtasks: &mut F, pump_messages: bool) {
6979
drain_microtasks();
70-
crate::pump_messages();
80+
if pump_messages {
81+
crate::pump_messages();
82+
}
7183
drain_microtasks();
7284
crate::napi_engine::websocket::pump(env);
7385
drain_microtasks();

‎runtime/src/napi_engine/host_abi.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ pub fn initialize_runtime(env: &Env, app_root: &str) -> napi::Result<()> {
5959
/// call this once per frame from `CompositionTarget.Rendering`; it never blocks. `drain_microtasks`
6060
/// is the engine's microtask pump (e.g. `js_execute_pending_jobs` / `jsr_drain_microtasks`).
6161
pub fn pump_once<F: FnMut()>(env: &Env, drain_microtasks: &mut F) {
62-
event_loop::pump_once(env, drain_microtasks);
62+
event_loop::pump_once_from_host(env, drain_microtasks);
6363
}
6464

6565
/// True when the loop has no outstanding work (no timers, zero keep-alive count) — a self-hosted

‎runtime/src/ns_proxy.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2039,6 +2039,12 @@ pub(crate) fn create_ns_object<'a>(
20392039

20402040
/// The metadata class named by `instance`'s GetRuntimeClassName, when it differs from
20412041
/// `declared` and neither name is a generic instance.
2042+
///
2043+
/// An interface name only replaces a declared interface (or an undeclared type), never a declared
2044+
/// class. A type authored outside WinMD, like the app template's C# `App : Application`, can't
2045+
/// name itself, so CsWinRT reports one of its interfaces, e.g.
2046+
/// `Microsoft.UI.Xaml.IApplicationOverrides`. Wrapping `Application.Current` as that interface
2047+
/// would drop every `Application` member, such as `Exit`, `Resources` and `RequestedTheme`.
20422048
pub(crate) fn resolve_runtime_class(
20432049
instance: &IUnknown,
20442050
declared: &str,
@@ -2053,7 +2059,18 @@ pub(crate) fn resolve_runtime_class(
20532059
.map(|cn| cn.to_string_lossy())
20542060
.filter(|cn| !cn.is_empty() && cn != declared && !cn.contains('<'))
20552061
.and_then(|cn| MetadataReader::find_by_name(&cn).map(|d| (cn, d)))
2056-
.filter(|(_, d)| !matches!(d.read().kind(), DeclarationKind::Struct))
2062+
.filter(|(_, d)| match d.read().kind() {
2063+
DeclarationKind::Struct => false,
2064+
DeclarationKind::Interface | DeclarationKind::GenericInterfaceInstance => {
2065+
!declared_is_class(declared)
2066+
}
2067+
_ => true,
2068+
})
2069+
}
2070+
2071+
fn declared_is_class(declared: &str) -> bool {
2072+
MetadataReader::find_by_name(declared)
2073+
.is_some_and(|d| matches!(d.read().kind(), DeclarationKind::Class))
20572074
}
20582075

20592076
pub(crate) fn create_ns_ctor_instance_object<'a>(

‎runtime/src/ui_dispatcher.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,33 @@ pub fn needs_win32_pump() -> bool {
217217
UI_DQ_CONTROLLER.get().is_some()
218218
}
219219

220+
/// True when a XAML host runs the UI thread's message loop, so the runtime's pump must not drain
221+
/// Win32 messages itself.
222+
///
223+
/// WinUI 3's own dispatcher is a `Microsoft.UI.Dispatching.DispatcherQueue`, so
224+
/// `init_ui_dispatcher` finds no `Windows.System.DispatcherQueue` there and makes its own
225+
/// controller, which makes `needs_win32_pump` true even under XAML. XAML's loop dispatches that
226+
/// controller's work as well.
227+
///
228+
/// The host calls the pump from inside a `DispatcherQueue` work item. Pumping messages there
229+
/// dispatches the queues' wake messages re-entrantly, and a wake can be lost: XAML's queue, its
230+
/// timers and the runtime's own queue then never run again. Timers, frames and native callbacks
231+
/// all stop while the UI thread sits idle in `GetMessage`. Console hosts have no such loop and
232+
/// keep pumping.
233+
///
234+
/// Settled on the first call. Every caller is a pump, and a WinUI host only starts pumping from
235+
/// inside `Application.Start`, after XAML has loaded.
236+
pub fn host_pumps_messages() -> bool {
237+
static XAML_HOST: OnceLock<bool> = OnceLock::new();
238+
*XAML_HOST.get_or_init(xaml_loaded)
239+
}
240+
241+
fn xaml_loaded() -> bool {
242+
use windows::core::w;
243+
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
244+
unsafe { GetModuleHandleW(w!("Microsoft.UI.Xaml.dll")) }.is_ok()
245+
}
246+
220247
#[cfg(test)]
221248
mod tests {
222249
use super::*;
@@ -232,6 +259,12 @@ mod tests {
232259
assert!(UI_THREAD_ID.get().is_none());
233260
}
234261

262+
#[test]
263+
fn console_host_keeps_pumping_messages() {
264+
// No XAML in a test process: the runtime's pump still drains Win32 messages.
265+
assert!(!host_pumps_messages());
266+
}
267+
235268
#[test]
236269
fn post_fallback_runs_closure_inline() {
237270
let fired = Arc::new(AtomicBool::new(false));

0 commit comments

Comments
 (0)