diff --git a/README.md b/README.md index a62214b3..4a18bc2f 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, 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..0c4e2e1e 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -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 diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 379d146d..20d60ff5 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -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", @@ -22,6 +33,7 @@ __all__ = [ "WinRTAsyncWithProgress", "ProjectedLifetimeScope", "projected_lifetime_scope", + "project_as", "release_projected", "init_winappsdk", "ro_initialize", @@ -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: ... @@ -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, @@ -81,7 +93,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 +101,11 @@ class ProjectedLifetimeScope: def projected_lifetime_scope() -> ProjectedLifetimeScope: ... + +def project_as( + value: object, wrapper_type: type[_RuntimeClass] +) -> _RuntimeClass: ... + def release_projected(value: object) -> None: ... diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index ec40b5cd..b4dec891 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -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: @@ -479,6 +511,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..772f1fd1 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, @@ -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( @@ -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"): diff --git a/docs/status/PYTHON_CHECKLIST.md b/docs/status/PYTHON_CHECKLIST.md index e2095731..15963f78 100644 --- a/docs/status/PYTHON_CHECKLIST.md +++ b/docs/status/PYTHON_CHECKLIST.md @@ -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. @@ -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. @@ -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, diff --git a/samples/python/README.md b/samples/python/README.md new file mode 100644 index 00000000..02aabcf1 --- /dev/null +++ b/samples/python/README.md @@ -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`. 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..f446515f --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/README.md @@ -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`. 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..0d655305 --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/app.py @@ -0,0 +1,194 @@ +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, + major: int, + minor: int, +) -> None: + runtime = init_winappsdk(major, minor) + 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, major: int, minor: int) -> None: + runtime = init_winappsdk(major, minor) + 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, major: int, minor: 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), + "--major", + str(major), + "--minor", + str(minor), + 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, + "--major", + str(major), + "--minor", + str(minor), + 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) + parser.add_argument("--major", type=int, default=2) + parser.add_argument("--minor", type=int, default=3) + args = parser.parse_args() + + if args.loopback: + asyncio.run(run_loopback(args.timeout, args.major, args.minor)) + 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, + args.major, + args.minor, + ) + ) + else: + if not args.key: + parser.error("--redirect requires --key") + asyncio.run(redirect_to_primary(args.key, args.major, args.minor)) + + +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..83b50a03 --- /dev/null +++ b/samples/python/app-lifecycle-single-instance/run.ps1 @@ -0,0 +1,29 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [int]$Major = 2, + [int]$Minor = 3 +) + +$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 ` + --major $Major ` + --minor $Minor +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..4b2131c2 --- /dev/null +++ b/samples/python/app-notification/README.md @@ -0,0 +1,49 @@ +# 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 -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 sample subscribes before registration, displays the notification, waits +for activation, removes the notification, and clears all sample registration +data before exiting. Registration cleanup still runs if notification removal +fails. + +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..d552f08b --- /dev/null +++ b/samples/python/app-notification/app.py @@ -0,0 +1,114 @@ +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, + major: int, + minor: int, +) -> None: + runtime = init_winappsdk(major, minor) + 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: + try: + unsubscribe() + finally: + if registered: + try: + await manager.remove_by_tag_async(TAG) + finally: + manager.unregister_all() + 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) + parser.add_argument("--major", type=int, default=2) + parser.add_argument("--minor", type=int, default=3) + args = parser.parse_args() + asyncio.run(run(args.smoke, args.timeout, args.major, args.minor)) + + +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..d8ecb9ae --- /dev/null +++ b/samples/python/app-notification/run.ps1 @@ -0,0 +1,40 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [switch]$Smoke, + [int]$TimeoutSeconds = 30, + [int]$Major = 2, + [int]$Minor = 3 +) + +$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, + "--major", + $Major, + "--minor", + $Minor +) +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..a911e7e2 --- /dev/null +++ b/samples/python/async-file-io/README.md @@ -0,0 +1,20 @@ +# 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`; +- normalized Python overloads (`create_file_async(name)` or + `create_file_async(name, options)`); +- normal Python temporary-directory management; +- structural interface typing, so `StorageFile` is accepted directly where + `IStorageFile` is required; 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..6cd7111d --- /dev/null +++ b/samples/python/async-file-io/app.py @@ -0,0 +1,45 @@ +import asyncio +import tempfile +from pathlib import Path + +from dynwinrt import RoApartment, projected_lifetime_scope +from generated.windows.storage import ( + FileIO, + 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") + if file is None: + raise RuntimeError("StorageFolder returned no file") + await FileIO.write_text_async(file, "Hello from dynwinrt.") + await FileIO.append_text_async( + file, + "\nAsync WinRT file I/O works.", + ) + actual = await FileIO.read_text_async(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..653c5d85 --- /dev/null +++ b/samples/python/device-watcher/README.md @@ -0,0 +1,18 @@ +# Python device watcher + +This sample enumerates devices with `DeviceInformation.create_watcher()` and +demonstrates typed `Added`, `Updated`, `Removed`, `EnumerationCompleted`, and +`Stopped` event subscriptions. + +Callbacks read WinRT objects on the callback apartment, then safely schedule +only Python-native values 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..83f5578e --- /dev/null +++ b/samples/python/device-watcher/app.py @@ -0,0 +1,140 @@ +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( + device_id: str, + name: str, + enabled: bool, + kind: str, + ) -> None: + devices[device_id] = { + "name": name, + "enabled": enabled, + "kind": kind, + } + + def mark_updated(device_id: str) -> None: + current = devices.get(device_id) + if current is not None: + current["updated"] = True + + def remove_device(device_id: str) -> None: + devices.pop(device_id, None) + + def on_added( + _sender: DeviceWatcher | None, + info: DeviceInformation | None, + ) -> None: + if info is not None: + loop.call_soon_threadsafe( + add_device, + info.id, + info.name, + info.is_enabled, + info.kind.name, + ) + + 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.id) + + 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), + ] + started = False + stop_requested = False + try: + watcher.start() + started = True + await asyncio.wait_for( + enumeration_completed.wait(), + timeout=timeout, + ) + watcher.stop() + stop_requested = True + await asyncio.wait_for(stopped.wait(), timeout=5) + started = False + finally: + try: + if started and not stop_requested: + watcher.stop() + stop_requested = True + if started: + 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/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..7ebe7e0d --- /dev/null +++ b/samples/python/ocr-image/README.md @@ -0,0 +1,26 @@ +# Python OCR image + +This sample reads an image with `Windows.Storage`, decodes it with +`BitmapDecoder`, and recognizes its text with `Windows.Media.Ocr`. It explicitly +projects the returned content-type stream to `IRandomAccessStream`, so the +required interface IID is validated before decoding. + +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 +``` + +Custom images are accepted without assuming their contents. Use +`-Expect WORD1,WORD2` to require specific recognized words. + +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..6cd4c9cc --- /dev/null +++ b/samples/python/ocr-image/app.py @@ -0,0 +1,68 @@ +import argparse +import asyncio +import re +from pathlib import Path + +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( + stream.as_interface(IRandomAccessStream) + ) + 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=[], + ) + 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..8a993af2 --- /dev/null +++ b/samples/python/ocr-image/run.ps1 @@ -0,0 +1,40 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python", + [string]$Image, + [string[]]$Expect +) + +$ErrorActionPreference = "Stop" +$expectWasExplicit = $PSBoundParameters.ContainsKey("Expect") +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 + if (-not $expectWasExplicit) { + $Expect = @("DYNWINRT", "OCR", "42") + } +} +$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) + } +} + +$arguments = @((Join-Path $PSScriptRoot "app.py"), "--image", $Image) +if ($Expect.Count -gt 0) { + $arguments += "--expect" + $arguments += $Expect +} +& $Python @arguments +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..3d43694b --- /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; +- structural interface typing that passes `SpeechSynthesisStream` directly + where `IRandomAccessStream` is required; +- 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..c3267524 --- /dev/null +++ b/samples/python/text-to-speech/app.py @@ -0,0 +1,63 @@ +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 + + +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) + 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..816aff08 --- /dev/null +++ b/samples/python/winui-hello-world/README.md @@ -0,0 +1,47 @@ +# 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()`; +- pass a generated `StackPanel` directly to the base `UIElement` API; +- 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 -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. + +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..f3596534 --- /dev/null +++ b/samples/python/winui-hello-world/app.py @@ -0,0 +1,127 @@ +import argparse +import os +from pathlib import Path +from typing import Callable + +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, Window +from generated.microsoft.ui.xaml.controls import Button, StackPanel, TextBlock +from generated.microsoft.ui.xaml.markup import XamlReader + + +XAML = """ + + +