Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bindings/py/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ authors = ["Microsoft"]
name = "dynwinrt"
crate-type = ["cdylib"]

[features]
test-hooks = ["dynwinrt/test-hooks"]

[dependencies]
dynwinrt = { path = "../../crates/dynwinrt" }
pyo3 = "0.29.0"
Expand Down
54 changes: 54 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,38 @@ When the required WinUI metadata is generated, `Application.create()` installs
`Application.create_with_metadata_provider(...)` is available when the
application supplies its own provider.

Python retains the validated WinUI implementation DLL after its first actual
WinUI activation until the process terminates. One named native owner keeps
one ordinary loader reference to `Microsoft.UI.Xaml.dll`; repeated activation
does not accumulate references. Retained native module handles determine
identity, so legal differences in path spelling or casing do not imply a
different runtime. If WinUI activation requires the DLL-probing
fallback, its successful loader reference is transferred to the same owner
(one reference per required implementation DLL), rather than leaked per call.
Imports, ordinary WinRT activation, and COM apartment initialization do not
load or retain WinUI or CoreMessaging.
When a WinUI metadata provider loads Controls before XAML, the runtime resolves
the actual `Application` activation factory to establish this lifetime before
returning the provider's factory; it does not create an Application or start
its message loop.

This is a process-lifetime module policy, not an object cache. Continue to
close windows, unsubscribe events, release projected/native objects, and
balance COM initialization on each thread as shown below. WinUI module-level
static state can remain after those application-owned resources are released.
The retained XAML mapping keeps its code valid when Controls static destruction
runs during COM cleanup, even when another MTA exits after the UI STA.

No new context manager or async executor is required. The Python runtime does
not release the published module reference from `RoApartment.close()`, Python
`atexit`, or wrapper finalizers: the operating system reclaims it at process
termination. Consequently, in-process unloading/hot replacement of that WinUI
implementation is not supported. This does not prohibit WinUI's documented
thread-level XAML/DispatcherQueue shutdown, guarantee repeated
`Application.start()` in one process, or imply that all SDK static resources
are gone when a window closes. The JavaScript and independent WinRT/COM
lifetime policies are unchanged.

Python subclasses of public composable controls preserve one COM identity for
inherited properties and methods. Metadata-supported
`measure_override`, `arrange_override`, and `on_apply_template` callbacks run
Expand Down Expand Up @@ -411,6 +443,28 @@ python -m maturin develop
python -m pytest
```

The focused WinUI lifetime regressions are in `tests\test_winui_lifetime.py`.
Without optional inputs they check ordinary WinRT imports and cleanup. Set
`DYNWINRT_WINUI_SAMPLE_ROOT` to a prepared Hello World directory (unchanged
`app.py`, `generated`, and `.runtime`) to exercise real STA, managed/external
MTA, exception, and default-async process teardown. Run each case in its own
process; process exit status is part of the assertion.

For native ownership inspection and the test-only shutdownable Tokio fixture,
build a separate test environment with `maturin develop --features test-hooks`.
This adds private test helpers only, not a production executor or public API.
`DYNWINRT_WINUI_REQUIRE_OWNER_HOOK=1` additionally checks the retained owner.
From a matching-architecture Visual Studio developer shell, build
`tests\e2e\fixtures\winui_activation.cpp` with
`cl /LD /EHsc /std:c++17 winui_activation.cpp /link runtimeobject.lib /OUT:Microsoft.UI.Xaml.dll`
in a private output directory and set `DYNWINRT_WINUI_FIXTURE_DIR` to it.
Copy that fixture DLL as `Microsoft.UI.Xaml.Controls.dll` in the same directory
for the dependency path-spelling regressions.
That SDK-typed factory tests actual loader-reference transfer, concurrent
fallback activation, failed/null factories, identity mismatch, and retry
without requiring WinUI installation. Do not use this fixture DLL in the real
sample directory.

## Release process

The release tag supplies one unified npm/Cargo version. For example,
Expand Down
17 changes: 16 additions & 1 deletion bindings/py/src/async_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,35 @@ thread_local! {
static TOKIO_RO_INITIALIZED: Cell<bool> = const { Cell::new(false) };
}

#[cfg(feature = "test-hooks")]
pub(crate) static MTA_THREAD_EVENTS: Mutex<Vec<(bool, u32)>> = Mutex::new(Vec::new());

pub(crate) fn init_async_runtime() {
pyo3_async_runtimes::tokio::init(runtime_builder());
}

pub(crate) fn runtime_builder() -> tokio::runtime::Builder {
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.enable_all();
builder.on_thread_start(|| {
unsafe { RoInitialize(RO_INIT_MULTITHREADED) }
.expect("failed to initialize a dynwinrt asyncio worker as MTA");
TOKIO_RO_INITIALIZED.set(true);
#[cfg(feature = "test-hooks")]
MTA_THREAD_EVENTS.lock().unwrap().push((true, unsafe {
windows::Win32::System::Threading::GetCurrentThreadId()
}));
});
builder.on_thread_stop(|| {
if TOKIO_RO_INITIALIZED.replace(false) {
unsafe { RoUninitialize() };
#[cfg(feature = "test-hooks")]
MTA_THREAD_EVENTS.lock().unwrap().push((false, unsafe {
windows::Win32::System::Threading::GetCurrentThreadId()
}));
}
});
pyo3_async_runtimes::tokio::init(builder);
builder
}

fn ensure_async(value: &dynwinrt::WinRTValue) -> PyResult<()> {
Expand Down
17 changes: 17 additions & 0 deletions bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ mod errors;
mod implementation;
mod runtime;
mod values;
#[cfg(feature = "test-hooks")]
mod winui_test_hooks;

#[pymodule]
mod dynwinrt {
Expand Down Expand Up @@ -594,6 +596,21 @@ _Coroutine.register(_DynWinRTAsyncWithProgress)
m
)?)?;
m.add_function(wrap_pyfunction!(super::runtime::get_computer_name, m)?)?;
#[cfg(feature = "test-hooks")]
{
m.add_function(wrap_pyfunction!(
super::winui_test_hooks::_test_winui_owned_references,
m
)?)?;
m.add_function(wrap_pyfunction!(
super::winui_test_hooks::_test_winui_module_paths,
m
)?)?;
m.add_function(wrap_pyfunction!(
super::winui_test_hooks::_test_winui_with_mta_runtime,
m
)?)?;
}
m.py().run(
c"
__all__ = [name for name in __all__ if not name.startswith('_')]
Expand Down
9 changes: 7 additions & 2 deletions bindings/py/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_win
static TABLE: std::sync::LazyLock<Arc<dynwinrt::MetadataTable>> =
std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new());

pub(crate) static WINUI_MODULES: dynwinrt::WinUiProcessModules =
dynwinrt::WinUiProcessModules::new();

pub(crate) fn wrap_python_callback_context(
py: Python<'_>,
callback: Py<PyAny>,
Expand Down Expand Up @@ -1181,7 +1184,8 @@ pub struct DynWinRTValue(pub(crate) dynwinrt::WinRTValue);
impl DynWinRTValue {
#[staticmethod]
fn activation_factory(name: String) -> PyResult<DynWinRTValue> {
dynwinrt::ro_get_activation_factory_2(&HSTRING::from(name))
WINUI_MODULES
.activation_factory(&HSTRING::from(name))
.map(DynWinRTValue)
.map_err(map_dynwinrt_error)
}
Expand Down Expand Up @@ -1225,7 +1229,8 @@ impl DynWinRTValue {
})
})
.transpose()?;
dynwinrt::create_xaml_application(&provider, callback.as_ref())
WINUI_MODULES
.create_xaml_application(&provider, callback.as_ref())
.map(DynWinRTValue)
.map_err(map_dynwinrt_error)
}
Expand Down
73 changes: 73 additions & 0 deletions bindings/py/src/winui_test_hooks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use pyo3::{exceptions::PyRuntimeError, prelude::*};
use windows::core::HSTRING;

use crate::errors::map_windows_error;

#[pyfunction]
pub(crate) fn _test_winui_owned_references() -> usize {
crate::runtime::WINUI_MODULES.owned_reference_count()
}

#[pyfunction]
pub(crate) fn _test_winui_module_paths() -> PyResult<Vec<String>> {
crate::runtime::WINUI_MODULES
.retained_module_paths()
.map(|paths| {
paths
.into_iter()
.map(|path| path.to_string_lossy().into_owned())
.collect()
})
.map_err(map_windows_error)
}

#[pyfunction]
pub(crate) fn _test_winui_with_mta_runtime(
py: Python<'_>,
callback: Py<PyAny>,
) -> PyResult<Vec<(bool, u32)>> {
let start = crate::async_runtime::MTA_THREAD_EVENTS
.lock()
.unwrap()
.len();
let runtime = crate::async_runtime::runtime_builder()
.worker_threads(2)
.build()
.map_err(|error| {
PyRuntimeError::new_err(format!("test runtime creation failed: {error}"))
})?;

fn use_winrt() -> windows::core::Result<bool> {
let uri = windows::Foundation::Uri::CreateUri(&HSTRING::from("https://example.com/"))?;
Ok(uri.Host()? == "example.com")
}

let async_job = runtime.spawn(async { use_winrt() });
let blocking_job = runtime.spawn_blocking(use_winrt);
let prepared = py.detach(|| {
runtime.block_on(async {
let async_result = async_job.await;
let blocking_result = blocking_job.await;
for result in [async_result, blocking_result] {
if !result
.map_err(|error| PyRuntimeError::new_err(format!("test job failed: {error}")))?
.map_err(map_windows_error)?
{
return Err(PyRuntimeError::new_err(
"test worker returned an invalid URI",
));
}
}
Ok(())
})
});
let result = prepared.and_then(|()| callback.call0(py));
// Use the production apartment hooks but a fixture-owned runtime so its
// actual async and blocking threads can all be stopped, not timeout-leaked.
py.detach(|| drop(runtime));
result?;
Ok(crate::async_runtime::MTA_THREAD_EVENTS.lock().unwrap()[start..].to_vec())
}
Loading
Loading