From 8e9ea973d7bd81c9b61b1e74fb5e04630bf50c5c Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 25 Aug 2026 15:28:13 +0800 Subject: [PATCH 01/17] Add Python projection helpers and samples Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 565c4300-9e07-40c2-8ad3-875138379a86 --- README.md | 4 + bindings/js/README.md | 23 ++- bindings/py/README.md | 31 ++++ bindings/py/dynwinrt.pyi | 12 +- bindings/py/src/lib.rs | 26 +++ bindings/py/tests/test_phase1.py | 32 ++++ docs/status/PYTHON_CHECKLIST.md | 6 +- samples/python/README.md | 23 +++ .../app-lifecycle-single-instance/.gitignore | 4 + .../app-lifecycle-single-instance/README.md | 31 ++++ .../app-lifecycle-single-instance/app.py | 170 ++++++++++++++++++ .../generate.ps1 | 64 +++++++ .../app-lifecycle-single-instance/run.ps1 | 24 +++ samples/python/app-notification/.gitignore | 4 + samples/python/app-notification/README.md | 43 +++++ samples/python/app-notification/app.py | 103 +++++++++++ samples/python/app-notification/generate.ps1 | 73 ++++++++ samples/python/app-notification/run.ps1 | 34 ++++ samples/python/async-file-io/.gitignore | 3 + samples/python/async-file-io/README.md | 17 ++ samples/python/async-file-io/app.py | 52 ++++++ samples/python/async-file-io/generate.ps1 | 54 ++++++ samples/python/async-file-io/run.ps1 | 21 +++ samples/python/cryptography/.gitignore | 3 + samples/python/cryptography/README.md | 12 ++ samples/python/cryptography/app.py | 42 +++++ samples/python/cryptography/generate.ps1 | 54 ++++++ samples/python/cryptography/run.ps1 | 22 +++ .../python/custom-winmd-codegen/.gitignore | 3 + samples/python/custom-winmd-codegen/README.md | 47 +++++ .../python/custom-winmd-codegen/generate.ps1 | 67 +++++++ .../custom-winmd-codegen/inspect_generated.py | 61 +++++++ samples/python/custom-winmd-codegen/run.ps1 | 30 ++++ samples/python/device-watcher/.gitignore | 3 + samples/python/device-watcher/README.md | 17 ++ samples/python/device-watcher/app.py | 117 ++++++++++++ samples/python/device-watcher/generate.ps1 | 54 ++++++ samples/python/device-watcher/run.ps1 | 30 ++++ .../python/global-media-session/.gitignore | 4 + samples/python/global-media-session/README.md | 49 +++++ samples/python/global-media-session/app.py | 93 ++++++++++ .../global-media-session/appxmanifest.xml.in | 45 +++++ .../python/global-media-session/generate.ps1 | 54 ++++++ .../global-media-session/remove-identity.ps1 | 12 ++ samples/python/global-media-session/run.ps1 | 32 ++++ .../global-media-session/setup-identity.ps1 | 69 +++++++ samples/python/ocr-image/.gitignore | 4 + samples/python/ocr-image/README.md | 21 +++ samples/python/ocr-image/app.py | 69 +++++++ samples/python/ocr-image/generate.ps1 | 54 ++++++ samples/python/ocr-image/make-test-image.ps1 | 35 ++++ samples/python/ocr-image/run.ps1 | 30 ++++ samples/python/text-to-speech/.gitignore | 3 + samples/python/text-to-speech/README.md | 35 ++++ samples/python/text-to-speech/app.py | 66 +++++++ samples/python/text-to-speech/generate.ps1 | 54 ++++++ samples/python/text-to-speech/run.ps1 | 28 +++ samples/python/winui-hello-world/.gitignore | 4 + samples/python/winui-hello-world/README.md | 42 +++++ samples/python/winui-hello-world/app.py | 125 +++++++++++++ samples/python/winui-hello-world/generate.ps1 | 72 ++++++++ samples/python/winui-hello-world/run.ps1 | 29 +++ .../src/codegen/winrt/python/method.rs | 77 ++++++-- .../src/codegen/winrt/python/stubs.rs | 16 +- tools/dynwinrt-codegen/src/main.rs | 5 + .../python_context_manager_typing_test.rs | 38 ++++ 66 files changed, 2555 insertions(+), 26 deletions(-) create mode 100644 samples/python/README.md create mode 100644 samples/python/app-lifecycle-single-instance/.gitignore create mode 100644 samples/python/app-lifecycle-single-instance/README.md create mode 100644 samples/python/app-lifecycle-single-instance/app.py create mode 100644 samples/python/app-lifecycle-single-instance/generate.ps1 create mode 100644 samples/python/app-lifecycle-single-instance/run.ps1 create mode 100644 samples/python/app-notification/.gitignore create mode 100644 samples/python/app-notification/README.md create mode 100644 samples/python/app-notification/app.py create mode 100644 samples/python/app-notification/generate.ps1 create mode 100644 samples/python/app-notification/run.ps1 create mode 100644 samples/python/async-file-io/.gitignore create mode 100644 samples/python/async-file-io/README.md create mode 100644 samples/python/async-file-io/app.py create mode 100644 samples/python/async-file-io/generate.ps1 create mode 100644 samples/python/async-file-io/run.ps1 create mode 100644 samples/python/cryptography/.gitignore create mode 100644 samples/python/cryptography/README.md create mode 100644 samples/python/cryptography/app.py create mode 100644 samples/python/cryptography/generate.ps1 create mode 100644 samples/python/cryptography/run.ps1 create mode 100644 samples/python/custom-winmd-codegen/.gitignore create mode 100644 samples/python/custom-winmd-codegen/README.md create mode 100644 samples/python/custom-winmd-codegen/generate.ps1 create mode 100644 samples/python/custom-winmd-codegen/inspect_generated.py create mode 100644 samples/python/custom-winmd-codegen/run.ps1 create mode 100644 samples/python/device-watcher/.gitignore create mode 100644 samples/python/device-watcher/README.md create mode 100644 samples/python/device-watcher/app.py create mode 100644 samples/python/device-watcher/generate.ps1 create mode 100644 samples/python/device-watcher/run.ps1 create mode 100644 samples/python/global-media-session/.gitignore create mode 100644 samples/python/global-media-session/README.md create mode 100644 samples/python/global-media-session/app.py create mode 100644 samples/python/global-media-session/appxmanifest.xml.in create mode 100644 samples/python/global-media-session/generate.ps1 create mode 100644 samples/python/global-media-session/remove-identity.ps1 create mode 100644 samples/python/global-media-session/run.ps1 create mode 100644 samples/python/global-media-session/setup-identity.ps1 create mode 100644 samples/python/ocr-image/.gitignore create mode 100644 samples/python/ocr-image/README.md create mode 100644 samples/python/ocr-image/app.py create mode 100644 samples/python/ocr-image/generate.ps1 create mode 100644 samples/python/ocr-image/make-test-image.ps1 create mode 100644 samples/python/ocr-image/run.ps1 create mode 100644 samples/python/text-to-speech/.gitignore create mode 100644 samples/python/text-to-speech/README.md create mode 100644 samples/python/text-to-speech/app.py create mode 100644 samples/python/text-to-speech/generate.ps1 create mode 100644 samples/python/text-to-speech/run.ps1 create mode 100644 samples/python/winui-hello-world/.gitignore create mode 100644 samples/python/winui-hello-world/README.md create mode 100644 samples/python/winui-hello-world/app.py create mode 100644 samples/python/winui-hello-world/generate.ps1 create mode 100644 samples/python/winui-hello-world/run.ps1 create mode 100644 tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs diff --git a/README.md b/README.md index a62214b3..3910a367 100644 --- a/README.md +++ b/README.md @@ -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, global media +sessions, 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 diff --git a/bindings/js/README.md b/bindings/js/README.md index 7f4b0bc6..a7daaa6f 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -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 diff --git a/bindings/py/README.md b/bindings/py/README.md index 44415f31..8f411f6d 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -124,6 +124,37 @@ 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()` 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 +runtime-class wrapper to another generated interface. 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 diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 379d146d..902b859a 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,4 +1,4 @@ -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) @@ -22,6 +22,7 @@ __all__ = [ "WinRTAsyncWithProgress", "ProjectedLifetimeScope", "projected_lifetime_scope", + "project_as", "release_projected", "init_winappsdk", "ro_initialize", @@ -45,7 +46,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: ... @@ -63,7 +64,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, @@ -81,7 +82,7 @@ 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: ... @@ -89,6 +90,9 @@ class ProjectedLifetimeScope: def projected_lifetime_scope() -> ProjectedLifetimeScope: ... + +def project_as(value: object, wrapper_type: type[_Tracked]) -> _Tracked: ... + def release_projected(value: object) -> None: ... diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index ec40b5cd..7ac6c6b0 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -233,6 +233,31 @@ 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 another generated type. + + 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.') + projector = getattr(wrapper_type, '_from_native', None) + if not callable(projector): + raise TypeError('project_as requires a generated projection 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: @@ -479,6 +504,7 @@ for _name in ( 'WinRTAsyncWithProgress', 'ProjectedLifetimeScope', 'projected_lifetime_scope', + 'project_as', 'release_projected', ): if _name not in __all__: diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index de4ce45f..ba2be4a5 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -33,6 +33,7 @@ DynWinRtDelegate, DynWinRtElementFactory, RoApartment, + project_as, projected_lifetime_scope, release_projected, WinRTAsync, @@ -597,6 +598,37 @@ 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 projection type"): + project_as(raw, object) + assert not raw.is_null() + raw.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"): diff --git a/docs/status/PYTHON_CHECKLIST.md b/docs/status/PYTHON_CHECKLIST.md index e2095731..fae74fff 100644 --- a/docs/status/PYTHON_CHECKLIST.md +++ b/docs/status/PYTHON_CHECKLIST.md @@ -119,6 +119,10 @@ 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, matching JavaScript `projectAs`. +- [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. @@ -128,7 +132,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, diff --git a/samples/python/README.md b/samples/python/README.md new file mode 100644 index 00000000..3bf581cd --- /dev/null +++ b/samples/python/README.md @@ -0,0 +1,23 @@ +# 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 | +| [`global-media-session`](global-media-session/) | GSMTC session discovery, collections, media properties, and change 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`. diff --git a/samples/python/app-lifecycle-single-instance/.gitignore b/samples/python/app-lifecycle-single-instance/.gitignore new file mode 100644 index 00000000..e9a9942e --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/.gitignore @@ -0,0 +1,4 @@ +generated/ +.runtime/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/app-lifecycle-single-instance/README.md b/samples/python/app-lifecycle-single-instance/README.md new file mode 100644 index 00000000..47798f06 --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/README.md @@ -0,0 +1,31 @@ +# 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 +``` + +The loopback succeeds only after the secondary process redirects its launch +activation and the primary receives it. It prints `python-app-lifecycle-ok`. diff --git a/samples/python/app-lifecycle-single-instance/app.py b/samples/python/app-lifecycle-single-instance/app.py new file mode 100644 index 00000000..d2a9844c --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/app.py @@ -0,0 +1,170 @@ +import argparse +import asyncio +import os +import sys +import tempfile +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +os.environ["WINAPPSDK_BOOTSTRAP_DLL_PATH"] = str( + ROOT / ".runtime" / "Microsoft.WindowsAppRuntime.Bootstrap.dll" +) + +from dynwinrt import RoApartment, init_winappsdk, projected_lifetime_scope +from generated.microsoft.windows.app_lifecycle import ( + AppActivationArguments, + AppInstance, +) + + +async def run_primary(key: str, ready: Path, timeout: int) -> None: + runtime = init_winappsdk(2, 3) + try: + with RoApartment(1), projected_lifetime_scope(): + instance = AppInstance.find_or_register_for_key(key) + if instance is None or not instance.is_current: + raise RuntimeError("Could not register the primary instance") + + loop = asyncio.get_running_loop() + activated = asyncio.Event() + activation_kind: list[str] = [] + + def on_activated( + _sender: object, + args: AppActivationArguments | None, + ) -> None: + activation_kind.append( + "None" if args is None else args.kind.name + ) + loop.call_soon_threadsafe(activated.set) + + unsubscribe = instance.subscribe_activated(on_activated) + ready.write_text(str(os.getpid()), encoding="utf-8") + try: + await asyncio.wait_for(activated.wait(), timeout=timeout) + print( + "primary-received-activation", + activation_kind[-1], + flush=True, + ) + finally: + unsubscribe() + instance.unregister_key() + finally: + del runtime + + +async def redirect_to_primary(key: str) -> None: + runtime = init_winappsdk(2, 3) + try: + with RoApartment(1), projected_lifetime_scope(): + current = AppInstance.get_current() + target = AppInstance.find_or_register_for_key(key) + if current is None or target is None: + raise RuntimeError("AppInstance is unavailable") + if target.is_current: + target.unregister_key() + raise RuntimeError("No primary instance was registered") + arguments = current.get_activated_event_args() + if arguments is None: + raise RuntimeError("Current process has no activation arguments") + await target.redirect_activation_to_async(arguments) + print("secondary-redirected-activation", flush=True) + finally: + del runtime + + +async def run_loopback(timeout: int) -> None: + key = f"dynwinrt-python-{uuid.uuid4()}" + with tempfile.TemporaryDirectory(prefix="dynwinrt-app-lifecycle-") as temp: + ready = Path(temp) / "ready.txt" + primary = await asyncio.create_subprocess_exec( + sys.executable, + str(Path(__file__).resolve()), + "--primary", + "--key", + key, + "--ready", + str(ready), + "--timeout", + str(timeout), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + try: + for _ in range(timeout * 10): + if ready.exists(): + break + if primary.returncode is not None: + break + await asyncio.sleep(0.1) + if not ready.exists(): + stdout, stderr = await primary.communicate() + raise RuntimeError( + "Primary instance did not become ready:\n" + + stdout.decode(errors="replace") + + stderr.decode(errors="replace") + ) + + secondary = await asyncio.create_subprocess_exec( + sys.executable, + str(Path(__file__).resolve()), + "--redirect", + "--key", + key, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + secondary_stdout, secondary_stderr = await secondary.communicate() + if secondary.returncode: + raise RuntimeError( + "Secondary instance failed:\n" + + secondary_stdout.decode(errors="replace") + + secondary_stderr.decode(errors="replace") + ) + + primary_stdout, primary_stderr = await asyncio.wait_for( + primary.communicate(), + timeout=timeout, + ) + if primary.returncode: + raise RuntimeError( + "Primary instance failed:\n" + + primary_stdout.decode(errors="replace") + + primary_stderr.decode(errors="replace") + ) + print(secondary_stdout.decode().strip()) + print(primary_stdout.decode().strip()) + print("python-app-lifecycle-ok") + finally: + if primary.returncode is None: + primary.terminate() + await primary.wait() + + +def main() -> None: + parser = argparse.ArgumentParser() + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--loopback", action="store_true") + mode.add_argument("--primary", action="store_true") + mode.add_argument("--redirect", action="store_true") + parser.add_argument("--key") + parser.add_argument("--ready", type=Path) + parser.add_argument("--timeout", type=int, default=15) + args = parser.parse_args() + + if args.loopback: + asyncio.run(run_loopback(args.timeout)) + elif args.primary: + if not args.key or args.ready is None: + parser.error("--primary requires --key and --ready") + asyncio.run(run_primary(args.key, args.ready, args.timeout)) + else: + if not args.key: + parser.error("--redirect requires --key") + asyncio.run(redirect_to_primary(args.key)) + + +if __name__ == "__main__": + main() diff --git a/samples/python/app-lifecycle-single-instance/generate.ps1 b/samples/python/app-lifecycle-single-instance/generate.ps1 new file mode 100644 index 00000000..1b93a9a7 --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/generate.ps1 @@ -0,0 +1,64 @@ +#!/usr/bin/env pwsh + +param( + [Parameter(Mandatory)] + [string]$AppLifecycleWinmd, + + [Parameter(Mandatory)] + [string]$RefList, + + [Parameter(Mandatory)] + [string]$BootstrapDll, + + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +$AppLifecycleWinmd = Resolve-CallerPath $AppLifecycleWinmd +$RefList = Resolve-CallerPath $RefList +$BootstrapDll = Resolve-CallerPath $BootstrapDll +foreach ($path in @($AppLifecycleWinmd, $RefList, $BootstrapDll)) { + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { + throw "Required input was not found: $path" + } +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +$runtime = Join-Path $PSScriptRoot ".runtime" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} +New-Item -ItemType Directory -Force -Path $output, $runtime | Out-Null + +& $codegenCommand generate ` + --winmd $AppLifecycleWinmd ` + --ref-list $RefList ` + --class-name "Microsoft.Windows.AppLifecycle.AppInstance" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Copy-Item -LiteralPath $BootstrapDll ` + -Destination (Join-Path $runtime "Microsoft.WindowsAppRuntime.Bootstrap.dll") ` + -Force + +Write-Host "Generated AppLifecycle bindings in $output" +Write-Host "Copied the bootstrap DLL to $runtime" diff --git a/samples/python/app-lifecycle-single-instance/run.ps1 b/samples/python/app-lifecycle-single-instance/run.ps1 new file mode 100644 index 00000000..7e4741a0 --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/run.ps1 @@ -0,0 +1,24 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python" +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll"))) { + throw "The WinAppSDK bootstrap DLL was not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +& $Python (Join-Path $PSScriptRoot "app.py") --loopback +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/app-notification/.gitignore b/samples/python/app-notification/.gitignore new file mode 100644 index 00000000..e9a9942e --- /dev/null +++ b/samples/python/app-notification/.gitignore @@ -0,0 +1,4 @@ +generated/ +.runtime/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/app-notification/README.md b/samples/python/app-notification/README.md new file mode 100644 index 00000000..ba2d4589 --- /dev/null +++ b/samples/python/app-notification/README.md @@ -0,0 +1,43 @@ +# Python AppNotification + +This sample uses Windows App SDK `AppNotificationBuilder` and +`AppNotificationManager` to build and display a notification from an unpackaged +Python process. It demonstrates: + +- Windows App SDK bootstrap; +- a fluent generated builder API; +- an activation event delivered to Python; and +- asynchronous cleanup of the notification. + +Unlike PyWinRT's +[toast activation sample](https://github.com/pywinrt/pywinrt/blob/main/samples/toast_activation.py), +this version uses the Windows App SDK registration API and does not require a +custom `comtypes` local server or manual registry keys. + +## Prerequisites + +- `Microsoft.Windows.AppNotifications.winmd`; +- `Microsoft.Windows.AppNotifications.Builder.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 ` + -AppNotificationsWinmd C:\fixtures\Microsoft.Windows.AppNotifications.winmd ` + -BuilderWinmd C:\fixtures\Microsoft.Windows.AppNotifications.Builder.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 +``` + +The sample subscribes before registration, displays the notification, waits +for activation, removes the notification, and unregisters before exiting. + +Use `-Smoke` to validate support and build the notification payload without +registering or displaying it. diff --git a/samples/python/app-notification/app.py b/samples/python/app-notification/app.py new file mode 100644 index 00000000..f9834341 --- /dev/null +++ b/samples/python/app-notification/app.py @@ -0,0 +1,103 @@ +import argparse +import asyncio +import os +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +os.environ["WINAPPSDK_BOOTSTRAP_DLL_PATH"] = str( + ROOT / ".runtime" / "Microsoft.WindowsAppRuntime.Bootstrap.dll" +) + +from dynwinrt import RoApartment, init_winappsdk, projected_lifetime_scope +from generated.microsoft.windows.app_notifications import ( + AppNotification, + AppNotificationActivatedEventArgs, + AppNotificationManager, +) +from generated.microsoft.windows.app_notifications.builder import ( + AppNotificationBuilder, +) + + +TAG = "dynwinrt-python-sample" + + +def build_notification() -> AppNotification: + builder = AppNotificationBuilder() + builder.add_text("Hello from dynwinrt") + builder.add_text("This notification was created by generated Python bindings.") + builder.add_argument("source", "dynwinrt-python-sample") + builder.set_tag(TAG) + notification = builder.build_notification() + if notification is None: + raise RuntimeError("AppNotificationBuilder returned no notification") + return notification + + +async def run(smoke: bool, timeout: int) -> None: + runtime = init_winappsdk(2, 3) + try: + with RoApartment(1), projected_lifetime_scope(): + supported = AppNotificationManager.is_supported() + notification = build_notification() + if smoke: + print( + "python-app-notification-ok", + { + "supported": supported, + "payload_length": len(notification.payload), + }, + ) + return + if not supported: + raise RuntimeError("App notifications are not supported") + + manager = AppNotificationManager.get_default() + if manager is None: + raise RuntimeError("AppNotificationManager is unavailable") + + loop = asyncio.get_running_loop() + invoked = asyncio.Event() + + def on_invoked( + _sender: AppNotificationManager | None, + args: AppNotificationActivatedEventArgs | None, + ) -> None: + argument = "" if args is None else args.argument + print("Notification activated:", argument) + loop.call_soon_threadsafe(invoked.set) + + unsubscribe = manager.subscribe_notification_invoked(on_invoked) + registered = False + try: + manager.register() + registered = True + manager.show(notification) + print(f"Notification shown. Click it within {timeout} seconds.") + try: + await asyncio.wait_for(invoked.wait(), timeout=timeout) + except TimeoutError: + print("No activation was received before the timeout.") + finally: + unsubscribe() + if registered: + await manager.remove_by_tag_async(TAG) + manager.unregister() + finally: + del runtime + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke", + action="store_true", + help="Build the notification without registering or displaying it.", + ) + parser.add_argument("--timeout", type=int, default=30) + args = parser.parse_args() + asyncio.run(run(args.smoke, args.timeout)) + + +if __name__ == "__main__": + main() diff --git a/samples/python/app-notification/generate.ps1 b/samples/python/app-notification/generate.ps1 new file mode 100644 index 00000000..27810b2d --- /dev/null +++ b/samples/python/app-notification/generate.ps1 @@ -0,0 +1,73 @@ +#!/usr/bin/env pwsh + +param( + [Parameter(Mandatory)] + [string]$AppNotificationsWinmd, + + [Parameter(Mandatory)] + [string]$BuilderWinmd, + + [Parameter(Mandatory)] + [string]$RefList, + + [Parameter(Mandatory)] + [string]$BootstrapDll, + + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +$AppNotificationsWinmd = Resolve-CallerPath $AppNotificationsWinmd +$BuilderWinmd = Resolve-CallerPath $BuilderWinmd +$RefList = Resolve-CallerPath $RefList +$BootstrapDll = Resolve-CallerPath $BootstrapDll +foreach ($path in @( + $AppNotificationsWinmd, + $BuilderWinmd, + $RefList, + $BootstrapDll +)) { + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { + throw "Required input was not found: $path" + } +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +$runtime = Join-Path $PSScriptRoot ".runtime" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} +New-Item -ItemType Directory -Force -Path $output, $runtime | Out-Null + +& $codegenCommand generate ` + --winmd "$AppNotificationsWinmd;$BuilderWinmd" ` + --ref-list $RefList ` + --class-name "Microsoft.Windows.AppNotifications.AppNotificationManager,Microsoft.Windows.AppNotifications.Builder.AppNotificationBuilder" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Copy-Item -LiteralPath $BootstrapDll ` + -Destination (Join-Path $runtime "Microsoft.WindowsAppRuntime.Bootstrap.dll") ` + -Force + +Write-Host "Generated AppNotification bindings in $output" +Write-Host "Copied the bootstrap DLL to $runtime" diff --git a/samples/python/app-notification/run.ps1 b/samples/python/app-notification/run.ps1 new file mode 100644 index 00000000..3b04fd46 --- /dev/null +++ b/samples/python/app-notification/run.ps1 @@ -0,0 +1,34 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [switch]$Smoke, + [int]$TimeoutSeconds = 30 +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll"))) { + throw "The WinAppSDK bootstrap DLL was not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +$arguments = @( + (Join-Path $PSScriptRoot "app.py"), + "--timeout", + $TimeoutSeconds +) +if ($Smoke) { + $arguments += "--smoke" +} +& $Python @arguments +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/async-file-io/.gitignore b/samples/python/async-file-io/.gitignore new file mode 100644 index 00000000..7809e3e2 --- /dev/null +++ b/samples/python/async-file-io/.gitignore @@ -0,0 +1,3 @@ +generated/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/async-file-io/README.md b/samples/python/async-file-io/README.md new file mode 100644 index 00000000..18b90f11 --- /dev/null +++ b/samples/python/async-file-io/README.md @@ -0,0 +1,17 @@ +# Python async file I/O + +This deterministic sample uses generated `Windows.Storage` bindings to create, +write, append, and read a temporary file. It demonstrates: + +- WinRT asynchronous methods with native Python `await`; +- normal Python temporary-directory management; +- interface projection from `StorageFile` to `IStorageFile`; and +- deterministic projected-object cleanup. + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +.\run.ps1 -Python C:\path\to\python.exe +``` + +The sample deletes its temporary directory when complete and prints +`python-file-io-ok` on success. diff --git a/samples/python/async-file-io/app.py b/samples/python/async-file-io/app.py new file mode 100644 index 00000000..508dc83e --- /dev/null +++ b/samples/python/async-file-io/app.py @@ -0,0 +1,52 @@ +import asyncio +import tempfile +from pathlib import Path + +from dynwinrt import RoApartment, projected_lifetime_scope +from generated.windows.storage import ( + CreationCollisionOption, + FileIO, + IStorageFile, + StorageFolder, +) + + +async def run() -> None: + expected = "Hello from dynwinrt.\nAsync WinRT file I/O works." + + with tempfile.TemporaryDirectory(prefix="dynwinrt-python-") as directory: + with RoApartment(1), projected_lifetime_scope(): + folder = await StorageFolder.get_folder_from_path_async(directory) + if folder is None: + raise RuntimeError("StorageFolder returned no temporary folder") + + file = await folder.create_file_async( + "sample.txt", + CreationCollisionOption.ReplaceExisting, + ) + if file is None: + raise RuntimeError("StorageFolder returned no file") + storage_file = file.as_interface(IStorageFile) + + await FileIO.write_text_async(storage_file, "Hello from dynwinrt.") + await FileIO.append_text_async( + storage_file, + "\nAsync WinRT file I/O works.", + ) + actual = await FileIO.read_text_async(storage_file) + if actual != expected: + raise RuntimeError( + f"Unexpected file contents: {actual!r}" + ) + + print( + "python-file-io-ok", + { + "path": str(Path(directory) / "sample.txt"), + "characters": len(actual), + }, + ) + + +if __name__ == "__main__": + asyncio.run(run()) diff --git a/samples/python/async-file-io/generate.ps1 b/samples/python/async-file-io/generate.ps1 new file mode 100644 index 00000000..71b14571 --- /dev/null +++ b/samples/python/async-file-io/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Storage.StorageFolder,Windows.Storage.FileIO" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated file I/O bindings in $output" diff --git a/samples/python/async-file-io/run.ps1 b/samples/python/async-file-io/run.ps1 new file mode 100644 index 00000000..2eab6299 --- /dev/null +++ b/samples/python/async-file-io/run.ps1 @@ -0,0 +1,21 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python" +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +& $Python (Join-Path $PSScriptRoot "app.py") +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/cryptography/.gitignore b/samples/python/cryptography/.gitignore new file mode 100644 index 00000000..7809e3e2 --- /dev/null +++ b/samples/python/cryptography/.gitignore @@ -0,0 +1,3 @@ +generated/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/cryptography/README.md b/samples/python/cryptography/README.md new file mode 100644 index 00000000..7b7f5864 --- /dev/null +++ b/samples/python/cryptography/README.md @@ -0,0 +1,12 @@ +# Python cryptography + +This sample computes SHA-256 with generated Windows Runtime cryptography APIs +and verifies the result against Python's `hashlib`. + +It demonstrates primitive enums, `IBuffer` values, static WinRT APIs, and +hexadecimal conversion without files, hardware, or network access. + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +.\run.ps1 -Python C:\path\to\python.exe -Text "Hello from dynwinrt." +``` diff --git a/samples/python/cryptography/app.py b/samples/python/cryptography/app.py new file mode 100644 index 00000000..c9c67488 --- /dev/null +++ b/samples/python/cryptography/app.py @@ -0,0 +1,42 @@ +import argparse +import hashlib + +from dynwinrt import RoApartment, projected_lifetime_scope +from generated.windows.security.cryptography import ( + BinaryStringEncoding, + CryptographicBuffer, +) +from generated.windows.security.cryptography.core import HashAlgorithmProvider + + +def sha256(text: str) -> str: + with RoApartment(1), projected_lifetime_scope(): + provider = HashAlgorithmProvider.open_algorithm("SHA256") + if provider is None: + raise RuntimeError("SHA256 provider is unavailable") + data = CryptographicBuffer.convert_string_to_binary( + text, + BinaryStringEncoding.Utf8, + ) + if data is None: + raise RuntimeError("CryptographicBuffer returned no input buffer") + digest = provider.hash_data(data) + if digest is None: + raise RuntimeError("HashAlgorithmProvider returned no digest") + return CryptographicBuffer.encode_to_hex_string(digest).lower() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--text", default="Hello from dynwinrt.") + args = parser.parse_args() + + actual = sha256(args.text) + expected = hashlib.sha256(args.text.encode("utf-8")).hexdigest() + if actual != expected: + raise RuntimeError(f"SHA256 mismatch: {actual} != {expected}") + print("python-cryptography-ok", actual) + + +if __name__ == "__main__": + main() diff --git a/samples/python/cryptography/generate.ps1 b/samples/python/cryptography/generate.ps1 new file mode 100644 index 00000000..c6d6e862 --- /dev/null +++ b/samples/python/cryptography/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Security.Cryptography.CryptographicBuffer,Windows.Security.Cryptography.Core.HashAlgorithmProvider" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated cryptography bindings in $output" diff --git a/samples/python/cryptography/run.ps1 b/samples/python/cryptography/run.ps1 new file mode 100644 index 00000000..41bff018 --- /dev/null +++ b/samples/python/cryptography/run.ps1 @@ -0,0 +1,22 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [string]$Text = "Hello from dynwinrt." +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +& $Python (Join-Path $PSScriptRoot "app.py") --text $Text +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/custom-winmd-codegen/.gitignore b/samples/python/custom-winmd-codegen/.gitignore new file mode 100644 index 00000000..7809e3e2 --- /dev/null +++ b/samples/python/custom-winmd-codegen/.gitignore @@ -0,0 +1,3 @@ +generated/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/custom-winmd-codegen/README.md b/samples/python/custom-winmd-codegen/README.md new file mode 100644 index 00000000..69c0582a --- /dev/null +++ b/samples/python/custom-winmd-codegen/README.md @@ -0,0 +1,47 @@ +# Generate Python bindings from a custom WinMD + +This sample is a reusable template for metadata shipped outside the Windows +SDK, including a private component, a vendor SDK, or an individual Windows App +SDK package. + +It demonstrates: + +- passing an explicit WinMD and reference set to `dynwinrt-codegen`; +- generating a typed Python package with `.pyi` files and `py.typed`; +- importing every generated module; and +- inspecting public generated types and documentation. + +## Generate + +```powershell +.\generate.ps1 ` + -Winmd C:\path\to\Contoso.Component.winmd ` + -Namespace Contoso.Component ` + -RefList C:\path\to\references.txt ` + -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +``` + +Limit generation to selected runtime classes when the namespace is large: + +```powershell +.\generate.ps1 ` + -Winmd C:\path\to\Contoso.Component.winmd ` + -Namespace Contoso.Component ` + -ClassName "Widget,WidgetOptions" ` + -RefList C:\path\to\references.txt +``` + +Each non-empty line in `references.txt` is an additional WinMD used for type +resolution but not emitted. + +## Inspect + +```powershell +.\run.ps1 -Python C:\path\to\python.exe +.\run.ps1 -Python C:\path\to\python.exe -Symbol Widget +``` + +The default command imports every generated module and prints the first public +symbols. Activation and method calls require the component that implements the +WinMD to be installed, registered, or bootstrapped according to that +component's deployment model. diff --git a/samples/python/custom-winmd-codegen/generate.ps1 b/samples/python/custom-winmd-codegen/generate.ps1 new file mode 100644 index 00000000..985bba69 --- /dev/null +++ b/samples/python/custom-winmd-codegen/generate.ps1 @@ -0,0 +1,67 @@ +#!/usr/bin/env pwsh + +param( + [Parameter(Mandatory)] + [string]$Winmd, + + [Parameter(Mandatory)] + [string]$Namespace, + + [string]$ClassName, + [string]$RefList, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +$Winmd = Resolve-CallerPath $Winmd +if (-not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "WinMD was not found: $Winmd" +} +if ($RefList) { + $RefList = Resolve-CallerPath $RefList + if (-not (Test-Path -LiteralPath $RefList -PathType Leaf)) { + throw "Reference list was not found: $RefList" + } +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +$arguments = @( + "generate", + "--winmd", $Winmd, + "--namespace", $Namespace, + "--lang", "py", + "--output", $output +) +if ($ClassName) { + $arguments += @("--class-name", $ClassName) +} +if ($RefList) { + $arguments += @("--ref-list", $RefList) +} + +& $codegenCommand @arguments +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated custom WinMD bindings in $output" diff --git a/samples/python/custom-winmd-codegen/inspect_generated.py b/samples/python/custom-winmd-codegen/inspect_generated.py new file mode 100644 index 00000000..f2e34b4c --- /dev/null +++ b/samples/python/custom-winmd-codegen/inspect_generated.py @@ -0,0 +1,61 @@ +import argparse +import importlib +import inspect +import pkgutil + +import generated + + +def import_all_modules() -> int: + failures: list[tuple[str, Exception]] = [] + modules = sorted( + module.name + for module in pkgutil.walk_packages( + generated.__path__, + prefix=f"{generated.__name__}.", + ) + ) + for module_name in modules: + try: + importlib.import_module(module_name) + except Exception as error: + failures.append((module_name, error)) + if failures: + details = "\n".join( + f" {module}: {type(error).__name__}: {error}" + for module, error in failures + ) + raise RuntimeError(f"Generated modules failed to import:\n{details}") + return len(modules) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--symbol") + parser.add_argument("--limit", type=int, default=25) + args = parser.parse_args() + + count = import_all_modules() + exports = tuple(getattr(generated, "__all__", ())) + print(f"Imported {count} generated modules.") + print(f"The package exposes {len(exports)} public symbols.") + + if args.symbol: + value = getattr(generated, args.symbol) + try: + signature = str(inspect.signature(value)) + except (TypeError, ValueError): + signature = "" + print(f"{args.symbol}: {value!r}") + print(f"module: {getattr(value, '__module__', None)}") + print(f"signature: {signature}") + print(inspect.getdoc(value) or "") + return + + for name in exports[: args.limit]: + value = getattr(generated, name) + print(f"{name}: {getattr(value, '__module__', None)}") + + +if __name__ == "__main__": + main() diff --git a/samples/python/custom-winmd-codegen/run.ps1 b/samples/python/custom-winmd-codegen/run.ps1 new file mode 100644 index 00000000..68f00127 --- /dev/null +++ b/samples/python/custom-winmd-codegen/run.ps1 @@ -0,0 +1,30 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [string]$Symbol, + [int]$Limit = 25 +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +$arguments = @( + (Join-Path $PSScriptRoot "inspect_generated.py"), + "--limit", $Limit +) +if ($Symbol) { + $arguments += @("--symbol", $Symbol) +} +& $Python @arguments +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/device-watcher/.gitignore b/samples/python/device-watcher/.gitignore new file mode 100644 index 00000000..7809e3e2 --- /dev/null +++ b/samples/python/device-watcher/.gitignore @@ -0,0 +1,3 @@ +generated/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/device-watcher/README.md b/samples/python/device-watcher/README.md new file mode 100644 index 00000000..33be55d8 --- /dev/null +++ b/samples/python/device-watcher/README.md @@ -0,0 +1,17 @@ +# Python device watcher + +This sample enumerates devices with `DeviceInformation.create_watcher()` and +demonstrates typed `Added`, `Updated`, `Removed`, `EnumerationCompleted`, and +`Stopped` event subscriptions. + +Callbacks safely schedule their work back onto the `asyncio` loop. The watcher +is stopped and every subscription is removed before the apartment exits. + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +.\run.ps1 -Python C:\path\to\python.exe +``` + +The exact devices vary by machine. A successful run prints +`python-device-watcher-ok` and counts by device kind. Pass `-ShowNames` to +`run.ps1` to also print up to ten discovered device names. diff --git a/samples/python/device-watcher/app.py b/samples/python/device-watcher/app.py new file mode 100644 index 00000000..b6133a1b --- /dev/null +++ b/samples/python/device-watcher/app.py @@ -0,0 +1,117 @@ +import argparse +import asyncio +import json +from collections import Counter +from collections.abc import Callable + +from dynwinrt import DynWinRTValue, RoApartment, projected_lifetime_scope +from generated.windows.devices.enumeration import ( + DeviceInformation, + DeviceInformationUpdate, + DeviceWatcher, +) + + +async def enumerate_devices(timeout: int, show_names: bool) -> None: + with RoApartment(1), projected_lifetime_scope(): + watcher = DeviceInformation.create_watcher() + if watcher is None: + raise RuntimeError("DeviceInformation returned no watcher") + + loop = asyncio.get_running_loop() + enumeration_completed = asyncio.Event() + stopped = asyncio.Event() + devices: dict[str, dict[str, object]] = {} + + def add_device(info: DeviceInformation) -> None: + devices[info.id] = { + "name": info.name, + "enabled": info.is_enabled, + "kind": info.kind.name, + } + + def mark_updated(device_id: str) -> None: + current = devices.get(device_id) + if current is not None: + current["updated"] = True + + def remove_device(update: DeviceInformationUpdate) -> None: + devices.pop(update.id, None) + + def on_added( + _sender: DeviceWatcher | None, + info: DeviceInformation | None, + ) -> None: + if info is not None: + loop.call_soon_threadsafe(add_device, info) + + def on_updated( + _sender: DeviceWatcher | None, + update: DeviceInformationUpdate | None, + ) -> None: + if update is not None: + loop.call_soon_threadsafe(mark_updated, update.id) + + def on_removed( + _sender: DeviceWatcher | None, + update: DeviceInformationUpdate | None, + ) -> None: + if update is not None: + loop.call_soon_threadsafe(remove_device, update) + + def on_enumeration_completed( + _sender: DeviceWatcher | None, + _args: DynWinRTValue | None, + ) -> None: + loop.call_soon_threadsafe(enumeration_completed.set) + + def on_stopped( + _sender: DeviceWatcher | None, + _args: DynWinRTValue | None, + ) -> None: + loop.call_soon_threadsafe(stopped.set) + + unsubscribers: list[Callable[[], None]] = [ + watcher.subscribe_added(on_added), + watcher.subscribe_updated(on_updated), + watcher.subscribe_removed(on_removed), + watcher.subscribe_enumeration_completed( + on_enumeration_completed + ), + watcher.subscribe_stopped(on_stopped), + ] + try: + watcher.start() + await asyncio.wait_for( + enumeration_completed.wait(), + timeout=timeout, + ) + watcher.stop() + await asyncio.wait_for(stopped.wait(), timeout=5) + finally: + for unsubscribe in reversed(unsubscribers): + unsubscribe() + + values = sorted( + devices.values(), + key=lambda item: str(item["name"]).casefold(), + ) + summary: dict[str, object] = { + "count": len(values), + "kinds": dict(Counter(str(value["kind"]) for value in values)), + } + if show_names: + summary["devices"] = values[:10] + print("python-device-watcher-ok", json.dumps(summary, indent=2)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--timeout", type=int, default=10) + parser.add_argument("--show-names", action="store_true") + args = parser.parse_args() + asyncio.run(enumerate_devices(args.timeout, args.show_names)) + + +if __name__ == "__main__": + main() diff --git a/samples/python/device-watcher/generate.ps1 b/samples/python/device-watcher/generate.ps1 new file mode 100644 index 00000000..f42e0440 --- /dev/null +++ b/samples/python/device-watcher/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Devices.Enumeration.DeviceInformation" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated device watcher bindings in $output" diff --git a/samples/python/device-watcher/run.ps1 b/samples/python/device-watcher/run.ps1 new file mode 100644 index 00000000..8ffa8421 --- /dev/null +++ b/samples/python/device-watcher/run.ps1 @@ -0,0 +1,30 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [int]$TimeoutSeconds = 10, + [switch]$ShowNames +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +$arguments = @( + (Join-Path $PSScriptRoot "app.py"), + "--timeout", $TimeoutSeconds +) +if ($ShowNames) { + $arguments += "--show-names" +} +& $Python @arguments +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/global-media-session/.gitignore b/samples/python/global-media-session/.gitignore new file mode 100644 index 00000000..9b054c59 --- /dev/null +++ b/samples/python/global-media-session/.gitignore @@ -0,0 +1,4 @@ +generated/ +.identity/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/global-media-session/README.md b/samples/python/global-media-session/README.md new file mode 100644 index 00000000..1ad4eae2 --- /dev/null +++ b/samples/python/global-media-session/README.md @@ -0,0 +1,49 @@ +# Python global media sessions + +This sample lists the media sessions exposed through +`GlobalSystemMediaTransportControlsSessionManager` (GSMTC). It is a compact +Python counterpart to the repository's Electron SMTC/GSMTC sample and +demonstrates: + +- a WinRT async factory; +- projected collections and enums; +- media properties, playback state, and timeline values; and +- typed session-change subscriptions. + +## Prerequisites + +- Windows 10 version 2004 or later; +- Developer Mode, required to register the sparse debug identity; +- a Windows SDK containing `Windows.winmd`; +- `dynwinrt` installed in the selected Python interpreter; and +- `dynwinrt-codegen` on `PATH`, or passed with `-Codegen`. + +GSMTC requires the restricted `globalMediaControl` capability. The sample's +`setup-identity.ps1` creates a local sparse package identity for the selected +Python executable. It removes and replaces only the +`dynwinrt-python-gsmtc-sample` registration. + +## Run + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +.\run.ps1 -Python C:\path\to\python.exe +``` + +The command prints JSON for every visible media session. Start music or video +playback in another application if the list is empty. + +Watch for session changes: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe -Watch -SkipIdentity +``` + +`-SkipIdentity` is useful after the identity has already been registered for +that Python interpreter. + +Remove the sample identity when finished: + +```powershell +.\remove-identity.ps1 +``` diff --git a/samples/python/global-media-session/app.py b/samples/python/global-media-session/app.py new file mode 100644 index 00000000..01b699d7 --- /dev/null +++ b/samples/python/global-media-session/app.py @@ -0,0 +1,93 @@ +import argparse +import asyncio +import json +from typing import Any + +from dynwinrt import RoApartment, projected_lifetime_scope +from generated.windows.media.control import ( + GlobalSystemMediaTransportControlsSession, + GlobalSystemMediaTransportControlsSessionManager, +) + + +async def describe_session( + session: GlobalSystemMediaTransportControlsSession, +) -> dict[str, Any]: + properties = await session.try_get_media_properties_async() + playback = session.get_playback_info() + timeline = session.get_timeline_properties() + return { + "app_user_model_id": session.source_app_user_model_id, + "title": "" if properties is None else properties.title, + "artist": "" if properties is None else properties.artist, + "album": "" if properties is None else properties.album_title, + "status": ( + None if playback is None else playback.playback_status.name + ), + "position_seconds": ( + None if timeline is None else timeline.position.total_seconds() + ), + "duration_seconds": ( + None if timeline is None else timeline.end_time.total_seconds() + ), + } + + +async def snapshot( + manager: GlobalSystemMediaTransportControlsSessionManager, +) -> list[dict[str, Any]]: + sessions = manager.get_sessions() or () + return [ + await describe_session(session) + for session in sessions + if session is not None + ] + + +async def run(watch: bool) -> None: + with RoApartment(1), projected_lifetime_scope(): + manager = ( + await GlobalSystemMediaTransportControlsSessionManager.request_async() + ) + if manager is None: + raise RuntimeError("GSMTC session manager is unavailable") + + print(json.dumps(await snapshot(manager), indent=2)) + if not watch: + return + + loop = asyncio.get_running_loop() + changed = asyncio.Event() + + def notify(_sender: object, _args: object) -> None: + loop.call_soon_threadsafe(changed.set) + + unsubscribe_sessions = manager.subscribe_sessions_changed(notify) + unsubscribe_current = manager.subscribe_current_session_changed(notify) + print("Watching media sessions. Press Ctrl+C to stop.") + try: + while True: + await changed.wait() + changed.clear() + print(json.dumps(await snapshot(manager), indent=2)) + finally: + unsubscribe_current() + unsubscribe_sessions() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--watch", + action="store_true", + help="Print a new snapshot whenever the global sessions change.", + ) + args = parser.parse_args() + try: + asyncio.run(run(args.watch)) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/samples/python/global-media-session/appxmanifest.xml.in b/samples/python/global-media-session/appxmanifest.xml.in new file mode 100644 index 00000000..e0638ddd --- /dev/null +++ b/samples/python/global-media-session/appxmanifest.xml.in @@ -0,0 +1,45 @@ + + + + + dynwinrt Python GSMTC Sample + Microsoft Corporation + Assets\StoreLogo.png + true + + + + + + + + + + + + + + + + + diff --git a/samples/python/global-media-session/generate.ps1 b/samples/python/global-media-session/generate.ps1 new file mode 100644 index 00000000..09c87857 --- /dev/null +++ b/samples/python/global-media-session/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated GSMTC bindings in $output" diff --git a/samples/python/global-media-session/remove-identity.ps1 b/samples/python/global-media-session/remove-identity.ps1 new file mode 100644 index 00000000..5990fffd --- /dev/null +++ b/samples/python/global-media-session/remove-identity.ps1 @@ -0,0 +1,12 @@ +#!/usr/bin/env pwsh + +$ErrorActionPreference = "Stop" +$packages = @( + Get-AppxPackage ` + -Name "dynwinrt-python-gsmtc-sample" ` + -ErrorAction SilentlyContinue +) +foreach ($package in $packages) { + Remove-AppxPackage -Package $package.PackageFullName +} +Write-Host "Removed the dynwinrt Python GSMTC sample identity" diff --git a/samples/python/global-media-session/run.ps1 b/samples/python/global-media-session/run.ps1 new file mode 100644 index 00000000..6be065a1 --- /dev/null +++ b/samples/python/global-media-session/run.ps1 @@ -0,0 +1,32 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [switch]$Watch, + [switch]$SkipIdentity +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } else { + $Python = (Get-Command $Python -ErrorAction Stop).Source + } +} +if (-not $SkipIdentity) { + & (Join-Path $PSScriptRoot "setup-identity.ps1") -Python $Python +} + +$arguments = @((Join-Path $PSScriptRoot "app.py")) +if ($Watch) { + $arguments += "--watch" +} +& $Python @arguments +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/global-media-session/setup-identity.ps1 b/samples/python/global-media-session/setup-identity.ps1 new file mode 100644 index 00000000..72cb52b9 --- /dev/null +++ b/samples/python/global-media-session/setup-identity.ps1 @@ -0,0 +1,69 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python" +) + +$ErrorActionPreference = "Stop" +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $Python = (Get-Command $Python -ErrorAction Stop).Source +} +$Python = [System.IO.Path]::GetFullPath($Python) +$externalLocation = Split-Path $Python -Parent +$executable = Split-Path $Python -Leaf + +$identity = Join-Path $PSScriptRoot ".identity" +$assets = Join-Path $identity "Assets" +New-Item -ItemType Directory -Force -Path $identity, $assets | Out-Null + +Add-Type -AssemblyName System.Drawing +foreach ($asset in @( + @{ Name = "StoreLogo.png"; Size = 50 }, + @{ Name = "Square44x44Logo.png"; Size = 44 }, + @{ Name = "Square150x150Logo.png"; Size = 150 } +)) { + $path = Join-Path $assets $asset.Name + $bitmap = [System.Drawing.Bitmap]::new($asset.Size, $asset.Size) + $graphics = [System.Drawing.Graphics]::FromImage($bitmap) + try { + $graphics.Clear([System.Drawing.Color]::FromArgb(0, 95, 184)) + $font = [System.Drawing.Font]::new( + "Segoe UI", + [single]($asset.Size * 0.45), + [System.Drawing.FontStyle]::Bold, + [System.Drawing.GraphicsUnit]::Pixel) + $brush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::White) + $format = [System.Drawing.StringFormat]::new() + try { + $format.Alignment = [System.Drawing.StringAlignment]::Center + $format.LineAlignment = [System.Drawing.StringAlignment]::Center + $graphics.DrawString( + "P", + $font, + $brush, + [System.Drawing.RectangleF]::new(0, 0, $asset.Size, $asset.Size), + $format) + } finally { + $format.Dispose() + $brush.Dispose() + $font.Dispose() + } + $bitmap.Save($path, [System.Drawing.Imaging.ImageFormat]::Png) + } finally { + $graphics.Dispose() + $bitmap.Dispose() + } +} + +$template = Get-Content (Join-Path $PSScriptRoot "appxmanifest.xml.in") -Raw +$manifest = Join-Path $identity "AppxManifest.xml" +Set-Content ` + -LiteralPath $manifest ` + -Value $template.Replace("__EXECUTABLE__", $executable) ` + -Encoding utf8 + +Get-AppxPackage -Name "dynwinrt-python-gsmtc-sample" -ErrorAction SilentlyContinue | + Remove-AppxPackage -ErrorAction SilentlyContinue +Add-AppxPackage -Register $manifest -ExternalLocation $externalLocation + +Write-Host "Registered the globalMediaControl identity for $Python" diff --git a/samples/python/ocr-image/.gitignore b/samples/python/ocr-image/.gitignore new file mode 100644 index 00000000..36f645eb --- /dev/null +++ b/samples/python/ocr-image/.gitignore @@ -0,0 +1,4 @@ +generated/ +sample.png +.mypy_cache/ +__pycache__/ diff --git a/samples/python/ocr-image/README.md b/samples/python/ocr-image/README.md new file mode 100644 index 00000000..d015c981 --- /dev/null +++ b/samples/python/ocr-image/README.md @@ -0,0 +1,21 @@ +# Python OCR image + +This sample reads an image with `Windows.Storage`, decodes it with +`BitmapDecoder`, and recognizes its text with `Windows.Media.Ocr`. + +The default run creates a local PNG containing `DYNWINRT OCR 42`, so the sample +does not require a camera, network access, or external image asset. + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +.\run.ps1 -Python C:\path\to\python.exe +``` + +Recognize another image: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe -Image C:\path\to\image.png +``` + +Windows must have an OCR language matching one of the current user's profile +languages. diff --git a/samples/python/ocr-image/app.py b/samples/python/ocr-image/app.py new file mode 100644 index 00000000..21eb01b7 --- /dev/null +++ b/samples/python/ocr-image/app.py @@ -0,0 +1,69 @@ +import argparse +import asyncio +import re +from pathlib import Path +from typing import cast + +from dynwinrt import RoApartment, projected_lifetime_scope +from generated.windows.graphics.imaging import BitmapDecoder +from generated.windows.media.ocr import OcrEngine +from generated.windows.storage import StorageFile +from generated.windows.storage.streams import IRandomAccessStream + + +def normalized_words(value: str) -> set[str]: + return set(re.findall(r"[A-Z0-9]+", value.upper())) + + +async def recognize(path: Path) -> str: + with RoApartment(1), projected_lifetime_scope(): + file = await StorageFile.get_file_from_path_async(str(path.resolve())) + if file is None: + raise RuntimeError("StorageFile returned no image file") + stream = await file.open_read_async() + if stream is None: + raise RuntimeError("StorageFile returned no image stream") + + decoder = await BitmapDecoder.create_async( + cast(IRandomAccessStream, stream) + ) + if decoder is None: + raise RuntimeError("BitmapDecoder returned no decoder") + bitmap = await decoder.get_software_bitmap_async() + if bitmap is None: + raise RuntimeError("BitmapDecoder returned no SoftwareBitmap") + + with bitmap: + engine = OcrEngine.try_create_from_user_profile_languages() + if engine is None: + raise RuntimeError( + "No OCR engine is available for the user profile languages" + ) + result = await engine.recognize_async(bitmap) + if result is None: + raise RuntimeError("OcrEngine returned no result") + return result.text + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--image", type=Path, required=True) + parser.add_argument( + "--expect", + nargs="*", + default=["DYNWINRT", "OCR", "42"], + ) + args = parser.parse_args() + + text = asyncio.run(recognize(args.image)) + words = normalized_words(text) + missing = [word for word in args.expect if word.upper() not in words] + if missing: + raise RuntimeError( + f"OCR result {text!r} did not contain expected words {missing!r}" + ) + print("python-ocr-ok", text.strip()) + + +if __name__ == "__main__": + main() diff --git a/samples/python/ocr-image/generate.ps1 b/samples/python/ocr-image/generate.ps1 new file mode 100644 index 00000000..1eed5834 --- /dev/null +++ b/samples/python/ocr-image/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Media.Ocr.OcrEngine,Windows.Graphics.Imaging.BitmapDecoder,Windows.Storage.StorageFile" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated OCR bindings in $output" diff --git a/samples/python/ocr-image/make-test-image.ps1 b/samples/python/ocr-image/make-test-image.ps1 new file mode 100644 index 00000000..21bece1f --- /dev/null +++ b/samples/python/ocr-image/make-test-image.ps1 @@ -0,0 +1,35 @@ +#!/usr/bin/env pwsh + +param( + [string]$Output = (Join-Path $PSScriptRoot "sample.png") +) + +$ErrorActionPreference = "Stop" +Add-Type -AssemblyName System.Drawing + +$bitmap = [System.Drawing.Bitmap]::new(900, 180) +$graphics = [System.Drawing.Graphics]::FromImage($bitmap) +try { + $graphics.Clear([System.Drawing.Color]::White) + $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit + $font = [System.Drawing.Font]::new( + "Segoe UI", + 52, + [System.Drawing.FontStyle]::Bold, + [System.Drawing.GraphicsUnit]::Pixel) + $brush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::Black) + try { + $graphics.DrawString("DYNWINRT OCR 42", $font, $brush, 30, 45) + } finally { + $brush.Dispose() + $font.Dispose() + } + $bitmap.Save( + [System.IO.Path]::GetFullPath($Output), + [System.Drawing.Imaging.ImageFormat]::Png) +} finally { + $graphics.Dispose() + $bitmap.Dispose() +} + +Write-Host "Created OCR test image at $Output" diff --git a/samples/python/ocr-image/run.ps1 b/samples/python/ocr-image/run.ps1 new file mode 100644 index 00000000..fb1db8c6 --- /dev/null +++ b/samples/python/ocr-image/run.ps1 @@ -0,0 +1,30 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [string]$Image +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not $Image) { + $Image = Join-Path $PSScriptRoot "sample.png" + & (Join-Path $PSScriptRoot "make-test-image.ps1") -Output $Image +} +$Image = [System.IO.Path]::GetFullPath($Image) +if (-not (Test-Path -LiteralPath $Image -PathType Leaf)) { + throw "Image was not found: $Image" +} +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +& $Python (Join-Path $PSScriptRoot "app.py") --image $Image +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/text-to-speech/.gitignore b/samples/python/text-to-speech/.gitignore new file mode 100644 index 00000000..7809e3e2 --- /dev/null +++ b/samples/python/text-to-speech/.gitignore @@ -0,0 +1,3 @@ +generated/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/text-to-speech/README.md b/samples/python/text-to-speech/README.md new file mode 100644 index 00000000..7b2aa0d2 --- /dev/null +++ b/samples/python/text-to-speech/README.md @@ -0,0 +1,35 @@ +# Python text-to-speech + +This sample adapts PyWinRT's +[text-to-speech example](https://github.com/pywinrt/pywinrt/blob/main/samples/text_to_speech.py) +to generated dynwinrt bindings. It demonstrates: + +- native Python `asyncio` over a WinRT asynchronous operation; +- a generated `SpeechSynthesisStream` passed through its + `IRandomAccessStream` interface; +- a typed `MediaPlayer.MediaEnded` callback; and +- deterministic COM/WinRT cleanup. + +## Prerequisites + +- Windows 10 or 11 with a Windows SDK installed; +- `dynwinrt` installed in the selected Python interpreter; and +- `dynwinrt-codegen` on `PATH`, or passed to `generate.ps1` with `-Codegen`. + +Generate the bindings: + +```powershell +.\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe +``` + +Play synthesized speech: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe -Text "Hello from dynwinrt." +``` + +For non-interactive validation, synthesize the stream without playing it: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe -Smoke +``` diff --git a/samples/python/text-to-speech/app.py b/samples/python/text-to-speech/app.py new file mode 100644 index 00000000..e678b256 --- /dev/null +++ b/samples/python/text-to-speech/app.py @@ -0,0 +1,66 @@ +import argparse +import asyncio + +from dynwinrt import DynWinRTValue, RoApartment, projected_lifetime_scope +from generated.windows.media.playback import ( + MediaPlayer, + MediaPlayerAudioCategory, +) +from generated.windows.media.speech_synthesis import SpeechSynthesizer +from generated.windows.storage.streams import IRandomAccessStream + + +async def speak(text: str, smoke: bool) -> None: + with RoApartment(1), projected_lifetime_scope(): + with SpeechSynthesizer() as synthesizer: + stream = await synthesizer.synthesize_text_to_stream_async(text) + if stream is None: + raise RuntimeError("SpeechSynthesizer returned no stream") + + with stream: + if smoke: + print( + "python-tts-ok", + { + "content_type": stream.content_type, + "size": stream.size, + }, + ) + return + + loop = asyncio.get_running_loop() + ended = asyncio.Event() + + def on_media_ended( + _sender: MediaPlayer | None, + _args: DynWinRTValue | None, + ) -> None: + loop.call_soon_threadsafe(ended.set) + + with MediaPlayer() as player: + unsubscribe = player.once_media_ended(on_media_ended) + try: + player.audio_category = MediaPlayerAudioCategory.Speech + player.set_stream_source( + stream.as_interface(IRandomAccessStream) + ) + player.play() + await asyncio.wait_for(ended.wait(), timeout=30) + finally: + unsubscribe() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--text", default="Hello from dynwinrt.") + parser.add_argument( + "--smoke", + action="store_true", + help="Synthesize without playing audio.", + ) + args = parser.parse_args() + asyncio.run(speak(args.text, args.smoke)) + + +if __name__ == "__main__": + main() diff --git a/samples/python/text-to-speech/generate.ps1 b/samples/python/text-to-speech/generate.ps1 new file mode 100644 index 00000000..e44519f2 --- /dev/null +++ b/samples/python/text-to-speech/generate.ps1 @@ -0,0 +1,54 @@ +#!/usr/bin/env pwsh + +param( + [string]$Winmd, + [string]$Codegen = "dynwinrt-codegen" +) + +$ErrorActionPreference = "Stop" +$caller = (Get-Location).Path + +function Resolve-CallerPath([string]$Path) { + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + return [System.IO.Path]::GetFullPath((Join-Path $caller $Path)) +} + +if ($Winmd) { + $Winmd = Resolve-CallerPath $Winmd +} else { + $Winmd = Get-ChildItem ` + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd ` + -Recurse ` + -ErrorAction SilentlyContinue | + Sort-Object FullName -Descending | + Select-Object -First 1 -ExpandProperty FullName +} +if (-not $Winmd -or -not (Test-Path -LiteralPath $Winmd -PathType Leaf)) { + throw "Windows.winmd was not found. Install a Windows 10/11 SDK or pass -Winmd." +} + +$codegenCandidate = Resolve-CallerPath $Codegen +if (Test-Path -LiteralPath $codegenCandidate -PathType Leaf) { + $codegenCommand = $codegenCandidate +} else { + $codegenCommand = (Get-Command $Codegen -ErrorAction Stop).Source +} + +$output = Join-Path $PSScriptRoot "generated" +if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force +} + +& $codegenCommand generate ` + --winmd $Winmd ` + --class-name "Windows.Media.SpeechSynthesis.SpeechSynthesizer,Windows.Media.Playback.MediaPlayer" ` + --lang py ` + --output $output +if ($LASTEXITCODE -ne 0) { + throw "dynwinrt-codegen failed with exit code $LASTEXITCODE" +} + +Write-Host "Generated text-to-speech bindings in $output" diff --git a/samples/python/text-to-speech/run.ps1 b/samples/python/text-to-speech/run.ps1 new file mode 100644 index 00000000..0f34c077 --- /dev/null +++ b/samples/python/text-to-speech/run.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [string]$Text = "Hello from dynwinrt.", + [switch]$Smoke +) + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} + +if (-not [System.IO.Path]::IsPathRooted($Python)) { + $callerPython = Join-Path (Get-Location).Path $Python + if (Test-Path -LiteralPath $callerPython -PathType Leaf) { + $Python = [System.IO.Path]::GetFullPath($callerPython) + } +} + +$arguments = @((Join-Path $PSScriptRoot "app.py"), "--text", $Text) +if ($Smoke) { + $arguments += "--smoke" +} +& $Python @arguments +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/winui-hello-world/.gitignore b/samples/python/winui-hello-world/.gitignore new file mode 100644 index 00000000..e9a9942e --- /dev/null +++ b/samples/python/winui-hello-world/.gitignore @@ -0,0 +1,4 @@ +generated/ +.runtime/ +.mypy_cache/ +__pycache__/ diff --git a/samples/python/winui-hello-world/README.md b/samples/python/winui-hello-world/README.md new file mode 100644 index 00000000..8e32cb94 --- /dev/null +++ b/samples/python/winui-hello-world/README.md @@ -0,0 +1,42 @@ +# Python WinUI 3 Hello World + +This is the smallest WinUI 3 sample in the repository. It complements the +Tic-Tac-Toe samples by showing only the setup required to: + +- bootstrap the Windows App SDK; +- enter a single-threaded WinRT apartment; +- load a small XAML fragment; +- project raw XAML objects with `project_as()`; +- create and activate a `Window`; +- subscribe to `Button.Click`; and +- release projected objects before leaving the apartment. + +The flow is intentionally comparable to PyWinRT's +[WinUI 3 Hello World](https://github.com/pywinrt/pywinrt/blob/main/samples/winui3/hello_app.py), +while using dynwinrt's generated bootstrap and lifetime APIs. + +## Prerequisites + +The inputs are the same as the other Python WinUI samples: + +- `Microsoft.UI.Xaml.winmd`; +- a newline-separated reference-WinMD list; +- the matching architecture's + `Microsoft.WindowsAppRuntime.Bootstrap.dll`; +- `dynwinrt` installed in the selected Python interpreter; and +- `dynwinrt-codegen` on `PATH`, or passed with `-Codegen`. + +## Run + +```powershell +.\generate.ps1 ` + -WinuiWinmd C:\fixtures\winappsdk\metadata\Microsoft.UI.Xaml.winmd ` + -RefList C:\fixtures\winappsdk\winmd-reference-list.txt ` + -BootstrapDll C:\fixtures\winappsdk\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll ` + -Codegen ..\..\..\target\release\dynwinrt-codegen.exe + +.\run.ps1 -Python C:\path\to\python.exe +``` + +Use `-Smoke` to create the window and controls, update the text once, print +`python-winui-hello-ok`, and exit automatically. diff --git a/samples/python/winui-hello-world/app.py b/samples/python/winui-hello-world/app.py new file mode 100644 index 00000000..121be301 --- /dev/null +++ b/samples/python/winui-hello-world/app.py @@ -0,0 +1,125 @@ +import argparse +import os +from pathlib import Path +from typing import Callable, cast + +ROOT = Path(__file__).resolve().parent +os.environ["WINAPPSDK_BOOTSTRAP_DLL_PATH"] = str( + ROOT / ".runtime" / "Microsoft.WindowsAppRuntime.Bootstrap.dll" +) + +from dynwinrt import ( + RoApartment, + init_winappsdk, + project_as, + projected_lifetime_scope, +) +from generated.microsoft.ui.xaml import Application, UIElement, Window +from generated.microsoft.ui.xaml.controls import Button, StackPanel, TextBlock +from generated.microsoft.ui.xaml.markup import XamlReader + + +XAML = """ + + +