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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --cla

Python [`dynwinrt`](https://pypi.org/project/dynwinrt/) runtime wheels target
CPython 3.11–3.14 on Windows x64 and ARM64. The standalone
[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) wheel runs on
Python 3.8–3.14 and needs no Rust installation at consumption time.
[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) wheel includes
the prebuilt generator and requires no Rust installation.

Python runtime, codegen, packaging, and WinUI readiness are tracked in
[`docs/status/PYTHON_CHECKLIST.md`](docs/status/PYTHON_CHECKLIST.md).
Expand Down
9 changes: 9 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,15 @@ with RoApartment(0), projected_lifetime_scope():

Scopes nest in LIFO order. Wrappers that survive a closed scope remain Python
objects, but their native values are released and further WinRT calls fail.
Each scope is thread-affine: enter, use, and close it inside that thread's
`RoApartment`. Same-thread asyncio tasks inherit the active scope, while worker
threads must open their own ordered
`with RoApartment(...), projected_lifetime_scope():`. Native callbacks invoked
on a foreign thread preserve other captured context but do not inherit the
creator thread's lifetime scope. This includes generated delegates, raw progress
handlers, and element-factory callbacks. Retained callback values remain
user-owned; open an explicit callback-local scope for deterministic temporary
cleanup.

Normal construction remains unavailable for protected-only composable classes
and system-returned classes without public activation metadata. Named Python
Expand Down
40 changes: 38 additions & 2 deletions bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ from collections.abc import (
)
from datetime import datetime as _datetime, timedelta as _timedelta, timezone as _timezone
from itertools import count as _count
from contextvars import ContextVar as _ContextVar
from contextvars import ContextVar as _ContextVar, copy_context as _copy_context
from operator import index as _index
from threading import get_ident as _thread_get_ident
from threading import current_thread as _thread_current_thread, get_ident as _thread_get_ident
from types import TracebackType as _TracebackType
from typing import Any as _Any, Awaitable as _Awaitable, Callable as _Callable
from typing import Protocol as _Protocol, TypeVar as _TypeVar
Expand Down Expand Up @@ -169,6 +169,7 @@ class ProjectedLifetimeScope:
def __init__(self):
self._registry = {}
self._token = None
self._owner_thread = None
self._active = False
self._disposed = False
self._retry_pending = False
Expand All @@ -178,11 +179,24 @@ class ProjectedLifetimeScope:
def disposed(self):
return self._disposed

def _require_owner_thread(self, operation):
if (
self._owner_thread is not None
and _thread_current_thread() is not self._owner_thread
):
raise RuntimeError(
f'Cannot {operation} a projection lifetime scope from a different '
'thread. Worker threads must use their own ordered '
'`with RoApartment(...), projected_lifetime_scope():`.'
)

def __enter__(self):
self._require_owner_thread('enter')
if self._disposed:
raise RuntimeError('Cannot enter a disposed projection lifetime scope.')
if self._active:
raise RuntimeError('The projection lifetime scope is already active.')
self._owner_thread = _thread_current_thread()
self._token = _active_projected_lifetime_scope.set(self)
self._active = True
return self
Expand All @@ -198,13 +212,15 @@ class ProjectedLifetimeScope:
return False

def track(self, value, type_name=None):
self._require_owner_thread('track values in')
if not self._active or self._disposed:
raise RuntimeError('Cannot track values in an inactive projection lifetime scope.')
for native in _dynwinrt_projected_native_values(value):
self._registry.setdefault(id(native), (native, type_name))
return value

def close(self):
self._require_owner_thread('close')
if self._disposed:
return
if not self._active:
Expand Down Expand Up @@ -247,6 +263,26 @@ def _dynwinrt_append_exception_cause(error, cleanup_error):
def projected_lifetime_scope():
return ProjectedLifetimeScope()

def _dynwinrt_wrap_delegate_callback(callback):
context = _copy_context()
owner_thread = _thread_current_thread()

def invoke(*args):
callback_context = context.copy()
if _thread_current_thread() is owner_thread:
return callback_context.run(callback, *args)

def invoke_foreign_thread():
token = _active_projected_lifetime_scope.set(None)
try:
return callback(*args)
finally:
_active_projected_lifetime_scope.reset(token)

return callback_context.run(invoke_foreign_thread)

return invoke

def _dynwinrt_track_projected(value, type_name=None):
scope = _active_projected_lifetime_scope.get()
if scope is not None and scope._active and not scope._disposed:
Expand Down
85 changes: 43 additions & 42 deletions bindings/py/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ 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());

fn wrap_python_callback_context(py: Python<'_>, callback: Py<PyAny>) -> PyResult<Py<PyAny>> {
Ok(py
.import("dynwinrt.dynwinrt")?
.getattr("_dynwinrt_wrap_delegate_callback")?
.call1((callback,))?
.unbind())
}

fn checked_index(index: i64) -> PyResult<usize> {
usize::try_from(index)
.map_err(|_| PyIndexError::new_err(format!("index {index} out of bounds")))
Expand Down Expand Up @@ -1395,22 +1403,18 @@ impl DynWinRTValue {
let handler_iid = async_info.progress_handler_iid().ok_or_else(|| {
PyRuntimeError::new_err("on_progress: cannot compute progress handler IID")
})?;
let callback_context = py
.import("contextvars")?
.getattr("copy_context")?
.call0()?
.unbind();
let callback_for_error = callback.clone_ref(py);
let callback = wrap_python_callback_context(py, callback)?;

let progress_cb: dynwinrt::ProgressCallback = Box::new(move |val: dynwinrt::WinRTValue| {
Python::attach(|py| {
let result = (|| -> PyResult<()> {
let py_val = Py::new(py, DynWinRTValue(val))?;
let context = callback_context.call_method0(py, "copy")?;
context.call_method1(py, "run", (callback.clone_ref(py), py_val))?;
callback.call1(py, (py_val,))?;
Ok(())
})();
if let Err(error) = result {
error.write_unraisable(py, Some(callback.bind(py)));
error.write_unraisable(py, Some(callback_for_error.bind(py)));
}
});
});
Expand Down Expand Up @@ -2326,10 +2330,14 @@ impl DynWinRtDelegate {
// DynWinRtElementFactory — synchronous WinUI IElementFactory binding
// ======================================================================

struct ElementFactoryCallback {
invoke: Py<PyAny>,
error_target: Py<PyAny>,
}

struct ElementFactoryCallbacks {
get_element: Option<Py<PyAny>>,
recycle_element: Option<Py<PyAny>>,
context: Option<Py<PyAny>>,
get_element: Option<ElementFactoryCallback>,
recycle_element: Option<ElementFactoryCallback>,
}

#[pyclass]
Expand All @@ -2347,7 +2355,6 @@ impl DynWinRtElementFactory {
(
callbacks.get_element.take(),
callbacks.recycle_element.take(),
callbacks.context.take(),
)
};
drop(released);
Expand All @@ -2368,43 +2375,40 @@ impl DynWinRtElementFactory {
const RO_E_CLOSED: windows::core::HRESULT = windows::core::HRESULT(0x80000013_u32 as i32);

let element_iid = element_iid.0;
let context = py
.import("contextvars")?
.getattr("copy_context")?
.call0()?
.unbind();
let get_element = ElementFactoryCallback {
error_target: get_element.clone_ref(py),
invoke: wrap_python_callback_context(py, get_element)?,
};
let recycle_element = ElementFactoryCallback {
error_target: recycle_element.clone_ref(py),
invoke: wrap_python_callback_context(py, recycle_element)?,
};
let callbacks = Arc::new(Mutex::new(ElementFactoryCallbacks {
get_element: Some(get_element),
recycle_element: Some(recycle_element),
context: Some(context),
}));

let get_callbacks = callbacks.clone();
let get_callback: dynwinrt::ElementFactoryGetCallback = Box::new(move |args| {
Python::attach(|py| {
let (callback, context) = {
let (callback, error_target) = {
let callbacks = get_callbacks.lock().map_err(|_| E_FAIL)?;
let callback = callbacks
.get_element
.as_ref()
.ok_or(RO_E_CLOSED)?
.clone_ref(py);
let context = callbacks.context.as_ref().ok_or(RO_E_CLOSED)?.clone_ref(py);
(callback, context)
let callback = callbacks.get_element.as_ref().ok_or(RO_E_CLOSED)?;
(
callback.invoke.clone_ref(py),
callback.error_target.clone_ref(py),
)
};
let result = (|| -> PyResult<dynwinrt::WinRTValue> {
let argument = Py::new(py, DynWinRTValue(args.clone()))?;
let context = context.call_method0(py, "copy")?;
let result = context
.bind(py)
.call_method1("run", (callback.clone_ref(py), argument))?;
let value = result.extract::<PyRef<DynWinRTValue>>()?;
let result = callback.call1(py, (argument,))?;
let value = result.extract::<PyRef<DynWinRTValue>>(py)?;
value.0.cast(&element_iid).map_err(map_dynwinrt_error)
})();
match result {
Ok(value) => Ok(value),
Err(error) => {
error.write_unraisable(py, Some(callback.bind(py)));
error.write_unraisable(py, Some(error_target.bind(py)));
Err(E_FAIL)
}
}
Expand All @@ -2414,31 +2418,28 @@ impl DynWinRtElementFactory {
let recycle_callbacks = callbacks.clone();
let recycle_callback: dynwinrt::ElementFactoryRecycleCallback = Box::new(move |args| {
Python::attach(|py| {
let (callback, context) = {
let (callback, error_target) = {
let callbacks = match recycle_callbacks.lock() {
Ok(callbacks) => callbacks,
Err(_) => return E_FAIL,
};
let Some(callback) = callbacks.recycle_element.as_ref() else {
return RO_E_CLOSED;
};
let Some(context) = callbacks.context.as_ref() else {
return RO_E_CLOSED;
};
(callback.clone_ref(py), context.clone_ref(py))
(
callback.invoke.clone_ref(py),
callback.error_target.clone_ref(py),
)
};
let result = (|| -> PyResult<()> {
let argument = Py::new(py, DynWinRTValue(args.clone()))?;
let context = context.call_method0(py, "copy")?;
context
.bind(py)
.call_method1("run", (callback.clone_ref(py), argument))?;
callback.call1(py, (argument,))?;
Ok(())
})();
match result {
Ok(()) => windows::core::HRESULT(0),
Err(error) => {
error.write_unraisable(py, Some(callback.bind(py)));
error.write_unraisable(py, Some(error_target.bind(py)));
E_FAIL
}
}
Expand Down
63 changes: 60 additions & 3 deletions bindings/py/tests/test_e2e_winrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@

import asyncio
from collections.abc import Coroutine
from contextvars import ContextVar
import gc
import http.server
import sys
import threading
import time
import weakref
Expand All @@ -29,11 +31,15 @@
DynWinRTValue,
DynWinRTArray,
DynWinRTStruct,
projected_lifetime_scope,
WinGUID,
ro_initialize,
unbox_object,
)
from dynwinrt.dynwinrt import _DynWinRTAsyncWithProgress
from dynwinrt.dynwinrt import (
_DynWinRTAsyncWithProgress,
_dynwinrt_track_projected,
)

# Initialize WinRT once for the entire module
ro_initialize(1)
Expand Down Expand Up @@ -652,8 +658,59 @@ def test_struct_progress_survives_asyncio_dispatch(self):
),
[DynWinRTValue.from_hstring(url)],
)
def create_operation():
return client_type.method(11).invoke(client.cast(client_iid), [uri])
def create_operation(target=uri):
return client_type.method(11).invoke(client.cast(client_iid), [target])

class GeneratedStyleProjection:
def __init__(self, value):
self._obj = value
_dynwinrt_track_projected(self, "GeneratedStyleProgress")

raw_progress_threads = []
progress_marker = ContextVar(
"dynwinrt_test_raw_progress_marker",
default=None,
)
raw_progress_markers = []
unraisable = []
previous_unraisablehook = sys.unraisablehook
owner_thread = threading.get_ident()
marker_token = progress_marker.set("captured")
try:
sys.unraisablehook = unraisable.append
with projected_lifetime_scope():
raw_uri = uri_factory.method(6).invoke(
DynWinRTValue.activation_factory(
"Windows.Foundation.Uri"
).cast(uri_factory_iid),
[DynWinRTValue.from_hstring(f"{url}?raw-progress=1")],
)
raw_operation = create_operation(raw_uri)

def raw_progress(value):
progress = value.as_struct()
projection = GeneratedStyleProjection(
DynWinRTValue.from_i32(progress.get_i32(0))
)
assert not projection._obj.is_null()
raw_progress_threads.append(threading.get_ident())
raw_progress_markers.append(progress_marker.get())

raw_operation.on_progress(raw_progress)
raw_result = raw_operation.wait()
raw_body = raw_result.to_string()
raw_result.release()
raw_operation.release()
raw_uri.release()
finally:
progress_marker.reset(marker_token)
sys.unraisablehook = previous_unraisablehook

assert raw_body == payload
assert raw_progress_threads
assert all(thread != owner_thread for thread in raw_progress_threads)
assert all(marker == "captured" for marker in raw_progress_markers)
assert not unraisable

operation = create_operation()

Expand Down
Loading
Loading