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: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ instructions are in [`bindings/py/README.md`](bindings/py/README.md).
Python runtime, codegen, packaging, and WinUI readiness are tracked in
[`docs/status/PYTHON_CHECKLIST.md`](docs/status/PYTHON_CHECKLIST.md).

Python samples cover
[files, OCR, cryptography, devices, AppLifecycle, text-to-speech, app
notifications, WinUI, and custom WinMD generation](samples/python/README.md).

Electron samples include:

- [Windows Hello](samples/js/windows-hello/README.md) — WinRT async APIs and
Expand Down
23 changes: 20 additions & 3 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,26 @@ native values strongly for deterministic release; `releaseProjected()` removes
an individually released wrapper from its scope. Projects that never create a
scope do not retain projected values. Direct runtime users can release an
individual `DynWinRtValue` with `value.release()`.
`projectAs(value, Type)` borrows its input and creates a separately releasable
interface projection; internal generated `_fromNative()` paths consume native
return values.
`projectAs(value, Type)` is the public conversion for APIs whose metadata
returns `Object`/`IInspectable` even though the application knows the concrete
runtime class. It accepts either a raw projected value or an existing wrapper,
borrows the input, and creates a separately releasable projection:

```js
import { projectAs } from "./generated/lifetime.js";
import { XamlReader } from "./generated/XamlReader.js";
import { StackPanel } from "./generated/StackPanel.js";

const raw = XamlReader.load(xaml);
if (raw === null) throw new Error("XamlReader returned no value");
const panel = projectAs(raw, StackPanel);
```

Use `wrapper.as(InterfaceClass)` when converting an existing runtime-class
wrapper to another interface view. Use `projectAs(raw, RuntimeClass)` when
converting a raw value to a generated runtime class. A failed QueryInterface is
reported as an error. Internal generated `_fromNative()` paths consume native
return values; application code should use `projectAs()` instead.

Generated WinUI `IElementFactory` bindings expose `IElementFactory.create()`.
It creates a synchronous, UI-thread factory backed by JavaScript
Expand Down
33 changes: 33 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,39 @@ composition, raise a class-named `TypeError` on normal construction and their
stubs expose no public constructor. Native return values still use the internal
`_from_native`/`DynWinRTValue` wrapping path.

## Raw object projection

Use `project_as(value, Type)` when metadata returns `Object`/`IInspectable` but
the application knows the concrete generated type. This is common with XAML
APIs such as `XamlReader.load()` and `FrameworkElement.find_name()`:

```python
from dynwinrt import project_as
from generated.microsoft.ui.xaml.controls import Button, StackPanel
from generated.microsoft.ui.xaml.markup import XamlReader

raw_panel = XamlReader.load(XAML)
if raw_panel is None:
raise RuntimeError("XamlReader returned no value")
panel = project_as(raw_panel, StackPanel)

raw_button = panel.find_name("Submit")
if raw_button is None:
raise RuntimeError("Submit was not found")
button = project_as(raw_button, Button)
```

`project_as()` accepts generated runtime classes only and borrows its input:
the raw value or source wrapper remains valid. The returned wrapper owns the
QueryInterface result, participates in the active
`projected_lifetime_scope()`, and preserves the projection identity cache.
Incompatible types raise the ordinary WinRT `OSError`.

Use `wrapper.as_interface(InterfaceClass)` when converting an existing
wrapper to an interface view. Use `InterfaceClass.from_value(raw)` for a raw
`DynWinRTValue`. Do not call the internal `_from_native()` method from
application code.

## COM apartments and cleanup

Use `RoApartment` to initialize COM for a thread and balance every successful
Expand Down
25 changes: 21 additions & 4 deletions bindings/py/dynwinrt.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
from typing import Awaitable, Callable, List, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final
from typing import Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final

_T = TypeVar("_T", covariant=True)
_P = TypeVar("_P", covariant=True)
_Tracked = TypeVar("_Tracked")
_Projected_co = TypeVar("_Projected_co", covariant=True)
_RuntimeClass = TypeVar("_RuntimeClass", bound="_DynWinRTRuntimeClass")


class _DynWinRTProjector(Protocol[_Projected_co]):
@classmethod
def from_value(cls, obj: "DynWinRTValue") -> _Projected_co: ...


class _DynWinRTRuntimeClass: ...


__all__ = [
"WinAppSDKContext",
Expand All @@ -22,6 +33,7 @@ __all__ = [
"WinRTAsyncWithProgress",
"ProjectedLifetimeScope",
"projected_lifetime_scope",
"project_as",
"release_projected",
"init_winappsdk",
"ro_initialize",
Expand All @@ -45,7 +57,7 @@ class RoApartment:
def __enter__(self) -> RoApartment: ...
def __exit__(
self, exc_type: object, exc_value: object, traceback: object
) -> bool: ...
) -> Literal[False]: ...
def close(self) -> None: ...
def __repr__(self) -> str: ...

Expand All @@ -63,7 +75,7 @@ class DynWinRTXamlRegistration:
def __enter__(self) -> DynWinRTXamlRegistration: ...
def __exit__(
self, exc_type: object, exc_value: object, traceback: object
) -> bool: ...
) -> Literal[False]: ...

def register_xaml_runtime_class(
runtime_class_name: str,
Expand All @@ -81,14 +93,19 @@ class ProjectedLifetimeScope:
def __enter__(self) -> ProjectedLifetimeScope: ...
def __exit__(
self, exc_type: object, exc_value: object, traceback: object
) -> bool: ...
) -> Literal[False]: ...
def track(
self, value: _Tracked, type_name: Optional[str] = ...
) -> _Tracked: ...
def close(self) -> None: ...


def projected_lifetime_scope() -> ProjectedLifetimeScope: ...

def project_as(
value: object, wrapper_type: type[_RuntimeClass]
) -> _RuntimeClass: ...

def release_projected(value: object) -> None: ...


Expand Down
33 changes: 33 additions & 0 deletions bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,38 @@ def _dynwinrt_track_projected(value, type_name=None):
scope.track(value, type_name)
return value

def project_as(value, wrapper_type):
'''Borrow a projected value and expose it as a generated runtime class.

The input remains valid. The returned wrapper owns its QueryInterface
result and participates in the active projected lifetime scope.
'''
source = getattr(value, '_obj', value)
if not isinstance(source, DynWinRTValue):
raise TypeError('project_as requires a DynWinRTValue or projected wrapper.')
if getattr(wrapper_type, '_dynwinrt_interface_type', False):
raise TypeError(
'project_as only accepts generated runtime classes; use '
'Interface.from_value(raw) or wrapper.as_interface(Interface).'
)
if not getattr(wrapper_type, '_dynwinrt_runtime_class_type', False):
raise TypeError('project_as requires a generated runtime class type.')
projector = getattr(wrapper_type, '_from_native', None)
if not callable(projector):
raise TypeError('project_as requires a generated runtime class type.')
borrowed = source.cast(
WinGUID.parse('00000000-0000-0000-c000-000000000046')
)
try:
projected = projector(borrowed)
except BaseException:
borrowed.release()
raise
if not _dynwinrt_projected_native_values(projected):
borrowed.release()
raise TypeError('The generated type returned an invalid projection.')
return projected

def release_projected(value):
native_values = _dynwinrt_projected_native_values(value)
if not native_values:
Expand Down Expand Up @@ -479,6 +511,7 @@ for _name in (
'WinRTAsyncWithProgress',
'ProjectedLifetimeScope',
'projected_lifetime_scope',
'project_as',
'release_projected',
):
if _name not in __all__:
Expand Down
52 changes: 52 additions & 0 deletions bindings/py/tests/test_phase1.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
DynWinRtDelegate,
DynWinRtElementFactory,
RoApartment,
project_as,
projected_lifetime_scope,
release_projected,
WinRTAsync,
Expand Down Expand Up @@ -74,6 +75,8 @@ def _setup_module():

def _projected_wrapper_type(name):
class Wrapper:
_dynwinrt_runtime_class_type = True

def __new__(cls, *args, **kwargs):
if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue):
return _dynwinrt_projected_from_native(
Expand Down Expand Up @@ -597,6 +600,55 @@ def absolute_uri(self):
release_projected(uri)


def test_project_as_borrows_input_and_returns_managed_projection():
Wrapper = _projected_wrapper_type("ProjectAsWrapper")

with RoApartment(1):
raw = DynWinRTValue.activation_factory("Windows.Foundation.Uri")
identity = raw.identity_raw()
projected = project_as(raw, Wrapper)

assert projected._obj is not raw
assert projected._obj.identity_raw() == identity
assert raw.identity_raw() == identity

release_projected(projected)
assert raw.identity_raw() == identity
raw.release()


def test_project_as_rejects_invalid_values_and_types():
Wrapper = _projected_wrapper_type("ProjectAsValidationWrapper")

with pytest.raises(TypeError, match="DynWinRTValue or projected wrapper"):
project_as(object(), Wrapper)

with RoApartment(1):
raw = DynWinRTValue.activation_factory("Windows.Foundation.Uri")
with pytest.raises(TypeError, match="generated runtime class type"):
project_as(raw, object)
with pytest.raises(TypeError, match="generated runtime class type"):
project_as(raw, int)
assert not raw.is_null()
raw.release()


def test_project_as_rejects_interface_targets():
InterfaceWrapper = _projected_wrapper_type("ProjectAsInterfaceWrapper")
InterfaceWrapper._dynwinrt_interface_type = True
InterfaceWrapper._dynwinrt_interface_iid = WinGUID.parse(IID_IURI)

with RoApartment(1):
factory = DynWinRTValue.activation_factory("Windows.Foundation.Uri")
with pytest.raises(
TypeError,
match="only accepts generated runtime classes",
):
project_as(factory, InterfaceWrapper)
assert not factory.is_null()
factory.release()


def test_native_override_interface_rejects_unknown_or_unsupported_callback_shapes():
iid = WinGUID.parse("FFC6FD98-F38C-5904-9CE4-97A3427CF4BA")
with pytest.raises(RuntimeError, match="unsupported native override ABI shape"):
Expand Down
9 changes: 8 additions & 1 deletion docs/status/PYTHON_CHECKLIST.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ of a dynamic projection.
resolution.
- [x] Keep referenced types visible to static type checkers through
`TYPE_CHECKING` imports.
- [x] Model WinRT runtime-class and interface compatibility structurally in
input annotations without changing runtime inheritance.
- [x] Add an import regression for a real cyclic graph such as
`Windows.Data.Xml.Dom.XmlDocument`.
- [x] Preserve `Uri` implementation and `.pyi` snapshots.
Expand Down Expand Up @@ -119,6 +121,11 @@ of a dynamic projection.
- [x] Add overload-aware runtime dispatch and `typing.overload` stubs.
- [x] Generate idiomatic constructors such as `Uri(...)` while retaining an
internal wrapper path for returned native objects.
- [x] Expose `project_as(value, Type)` for typed, non-consuming projection of
raw `Object`/`IInspectable` values to RuntimeClasses, matching JavaScript
`projectAs`; use `as_interface()` / interface `from_value()` for QI views.
- [x] Declare non-suppressing runtime and generated context managers as
`Literal[False]`.
- [x] Replace deprecated PyO3 automatic `FromPyObject` behavior explicitly.
- [x] Document COM apartment ownership and provide a balanced context manager.

Expand All @@ -128,7 +135,7 @@ of a dynamic projection.
orchestration command.
- [x] Generate package names and imports consistently across Windows SDK,
Windows App SDK, and custom WinMD namespaces.
- [ ] Add runnable samples for files, notifications, imaging, async, events,
- [x] Add runnable samples for files, notifications, imaging, async, events,
collections, and custom WinMD consumption.
- [ ] Document generated-code version compatibility with `dynwinrt`.
- [ ] Add troubleshooting for metadata, apartment, bootstrap, architecture,
Expand Down
22 changes: 22 additions & 0 deletions samples/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Python samples

All Python samples use generated bindings and the local `dynwinrt` runtime.
Run each sample's `generate.ps1` before `run.ps1`.

| Sample | Demonstrates |
| --- | --- |
| [`async-file-io`](async-file-io/) | Temporary files, storage interfaces, and native `asyncio` |
| [`ocr-image`](ocr-image/) | Self-contained image creation, bitmap decoding, and Windows OCR |
| [`app-lifecycle-single-instance`](app-lifecycle-single-instance/) | Multi-process activation redirection with Windows App SDK AppLifecycle |
| [`cryptography`](cryptography/) | SHA-256, `IBuffer`, text encoding, and hex conversion |
| [`device-watcher`](device-watcher/) | Device enumeration and thread-safe typed event subscriptions |
| [`text-to-speech`](text-to-speech/) | `asyncio`, speech synthesis, media playback, and typed events |
| [`app-notification`](app-notification/) | Windows App SDK bootstrap, notification builder, display, activation, and cleanup |
| [`winui-hello-world`](winui-hello-world/) | Minimal WinUI 3 XAML, controls, events, STA, and projected lifetime management |
| [`custom-winmd-codegen`](custom-winmd-codegen/) | Generate, type, and import a Python package from an external WinMD |
| [`winui-tic-tac-toe`](winui-tic-tac-toe/) | XAML, a Python-defined WinUI control, native layout overrides, and Fluent resources |
| [`winui-tic-tac-toe-code-only`](winui-tic-tac-toe-code-only/) | A larger programmatic WinUI application without XAML |

The WinUI and AppNotification samples require matching Windows App SDK
metadata, reference WinMDs, runtime packages, and bootstrap DLL. The stock
Windows samples auto-detect the newest installed Windows SDK `Windows.winmd`.
4 changes: 4 additions & 0 deletions samples/python/app-lifecycle-single-instance/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
generated/
.runtime/
.mypy_cache/
__pycache__/
35 changes: 35 additions & 0 deletions samples/python/app-lifecycle-single-instance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Python AppLifecycle single instance

This Windows App SDK sample launches two Python processes and demonstrates:

- registering a primary instance with `AppInstance`;
- retrieving the second process's activation arguments;
- redirecting activation asynchronously to the primary process; and
- receiving and unsubscribing from the typed `Activated` event.

## Prerequisites

- `Microsoft.Windows.AppLifecycle.winmd`;
- a newline-separated reference-WinMD list for the matching Windows App SDK;
- the matching architecture's bootstrap DLL;
- `dynwinrt` installed in the selected Python interpreter; and
- `dynwinrt-codegen` on `PATH`, or passed with `-Codegen`.

## Run

```powershell
.\generate.ps1 `
-AppLifecycleWinmd C:\fixtures\Microsoft.Windows.AppLifecycle.winmd `
-RefList C:\fixtures\winmd-reference-list.txt `
-BootstrapDll C:\fixtures\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll `
-Codegen ..\..\..\target\release\dynwinrt-codegen.exe

.\run.ps1 -Python C:\path\to\python.exe -Major 2 -Minor 3
```

`Major` and `Minor` default to `2` and `3`. They must exactly match the Windows
App SDK product version represented by the metadata, bootstrap DLL, and
installed runtime.

The loopback succeeds only after the secondary process redirects its launch
activation and the primary receives it. It prints `python-app-lifecycle-ok`.
Loading
Loading