diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml index 0f2acaaf..91a910fe 100644 --- a/.github/workflows/python-release.yml +++ b/.github/workflows/python-release.yml @@ -441,18 +441,18 @@ jobs: run: | $wheels = (Get-ChildItem dist\*.whl -Recurse).FullName $releaseFound = $false - for ($attempt = 1; $attempt -le 40; $attempt++) { + for ($attempt = 1; $attempt -le 120; $attempt++) { & gh release view $env:TAG --repo $env:GH_REPO *> $null if ($LASTEXITCODE -eq 0) { $releaseFound = $true break } - Write-Host "Waiting for the JavaScript release $env:TAG ($attempt/40)..." + Write-Host "Waiting for the JavaScript release $env:TAG ($attempt/120)..." Start-Sleep -Seconds 30 } if (-not $releaseFound) { - throw "JavaScript GitHub release $env:TAG was not found after 20 minutes" + throw "JavaScript GitHub release $env:TAG was not found after 60 minutes" } $arguments = @('release', 'upload', $env:TAG, '--repo', $env:GH_REPO, '--clobber') diff --git a/.pipelines/release.yml b/.pipelines/release.yml index 009e446a..5a7f3d04 100644 --- a/.pipelines/release.yml +++ b/.pipelines/release.yml @@ -23,7 +23,7 @@ parameters: - name: PublishPyPI displayName: Publish Python packages to PyPI type: boolean - default: false + default: true - name: signingIdentity type: object default: @@ -297,7 +297,7 @@ extends: } $ready = $false - for ($attempt = 1; $attempt -le 20; $attempt++) { + for ($attempt = 1; $attempt -le 60; $attempt++) { $jobs = Invoke-GitHubApi "$($run.jobs_url)?per_page=100" $assembly = @($jobs.jobs | Where-Object name -EQ 'assemble-release') if ($assembly.Count -eq 1 -and $assembly[0].status -eq 'completed') { @@ -310,11 +310,11 @@ extends: if ($run.status -eq 'completed' -and $run.conclusion -ne 'success') { throw "Python tag workflow concluded '$($run.conclusion)'" } - Write-Host "Waiting for Python release assembly (attempt $attempt/20)..." + Write-Host "Waiting for Python release assembly (attempt $attempt/60)..." Start-Sleep -Seconds 60 } if (-not $ready) { - throw 'Python release assembly did not pass within 20 minutes' + throw 'Python release assembly did not pass within 60 minutes' } - stage: Release_GitHub @@ -367,7 +367,7 @@ extends: ```bash npm install @microsoft/dynwinrt npm install -D @microsoft/dynwinrt-codegen - python -m pip install dynwinrt dynwinrt-codegen + python -m pip install --pre dynwinrt dynwinrt-codegen ``` ## What's Included @@ -426,7 +426,7 @@ extends: } } $ready = $false - for ($attempt = 1; $attempt -le 40; $attempt++) { + for ($attempt = 1; $attempt -le 120; $attempt++) { $release = Invoke-GitHubApi $uri if ($release.target_commitish -ne '$(Build.SourceVersion)') { throw "GitHub release target '$($release.target_commitish)' does not match $(Build.SourceVersion)" @@ -439,11 +439,11 @@ extends: if ($wheels.Count -gt 10) { throw "Expected 10 Python wheel assets, found $($wheels.Count)" } - Write-Host "Waiting for Python release wheels ($($wheels.Count)/10, attempt $attempt/40)..." + Write-Host "Waiting for Python release wheels ($($wheels.Count)/10, attempt $attempt/120)..." Start-Sleep -Seconds 30 } if (-not $ready) { - throw 'The complete tested Python wheel set was not attached within 20 minutes' + throw 'The complete tested Python wheel set was not attached within 60 minutes' } - task: DownloadGitHubRelease@0 diff --git a/bindings/py/README.md b/bindings/py/README.md index d6d47c54..69f0796e 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -1,66 +1,20 @@ # dynwinrt -`dynwinrt` is the native CPython runtime for generated dynwinrt projections. -Release wheels support CPython 3.11 through 3.14 on Windows x64 and ARM64. -The floor is intentionally the first CPython line for which the release -infrastructure can install and execute a native Windows ARM64 interpreter; the -project does not ship cross-compiled, untested ARM64 wheels. +`dynwinrt` is the native CPython runtime for Python projections generated by +[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/). It supports +CPython 3.11–3.14 on Windows x64 and ARM64. -Install the runtime and the standalone generator from an approved feed or a -downloaded release: +## Install ```powershell -python -m pip install dynwinrt dynwinrt-codegen +python -m pip install --pre dynwinrt dynwinrt-codegen dynwinrt-codegen generate --namespace Windows.Foundation --class-name Uri ` --lang py --output generated_uri ``` -Generated Python package manifests pin `dynwinrt` to exactly the version of -`dynwinrt-codegen` that emitted them. - -## Develop - -Run `uv run maturin develop` to build the package - -Use `uv run pytest` to run the tests - -After modification `uv sync --reinstall` may be needed to reinstall the package - -The wheel includes `__init__.pyi` and `py.typed` for static type checking. - -## Release process - -`.github\workflows\python-release.yml` builds and consumes every CPython -3.11–3.14 runtime wheel on x64 and native ARM64. It also builds standalone -`py3-none-win_amd64` and `py3-none-win_arm64` codegen wheels, then exercises the -installed command with Rust removed from `PATH`. - -Pull requests run the x64 matrix. ARM64 jobs run only for manual dispatches and -`v*` release tags on GitHub-hosted `windows-11-vs2026-arm` runners. A release -remains blocked rather than producing ARM64 artifacts if one of its native -CPython versions cannot build or pass its isolated consumer test. - -To release: - -1. Create the ordinary repository release tag (for example, - `v0.1.0-preview.20`). The workflow derives the Python package version from - the tag and updates its build workspaces without modifying the repository. - PEP 440 normalizes `preview.N` wheel versions to `rcN`. -2. The official 1ES ADO release pipeline creates the shared GitHub release and - publishes the npm packages. After all ten Python wheels pass their - consumption tests, the GitHub workflow uploads them alongside the npm - tarballs. It never creates a separate Python GitHub release. -3. The ADO pipeline waits for the complete wheel set, downloads it through the - repository's GitHub service connection, and revalidates every filename, - platform tag, Python ABI tag, metadata record, type stub, and native payload. -4. PyPI publication is opt-in: the ADO `PublishPyPI` parameter is disabled by - default. When explicitly enabled with `DoEsrp`, ADO publishes the eight - `dynwinrt` wheels first and the two `dynwinrt-codegen` wheels second through - the Microsoft ESRP release identity. PyPI publication is not available from - GitHub Actions. - -Before the first release, onboard both PyPI project names to the configured ESRP -service connection and confirm the signing identity, owners, and approvers. +Generated package manifests pin `dynwinrt` to the exact version of +`dynwinrt-codegen` that produced them. The runtime wheel includes +`__init__.pyi` and `py.typed` for static type checking. Generated `IReference` values are projected as `T | None`; native values, `None`, and generated `IReference_*` wrappers are accepted as inputs. @@ -81,7 +35,7 @@ Regenerated bindings no longer block inside async methods. Existing code that expects an immediate result must use `await operation` or `operation.wait()`. `asyncio` task cancellation calls `IAsyncInfo.Cancel()` on the underlying -WinRT operation. Operations with scalar progress values also expose +WinRT operation. Operations with supported progress values also expose `operation.progress(callback)`. Fast operations can finish before registration; in that case no future progress exists and registration is a no-op. @@ -98,8 +52,9 @@ restricted WinRT error information when Windows provides it. Generated collection projections implement the standard `collections.abc` protocols: vectors behave as sequences, maps as mappings, and WinRT iterables -and iterators work with `iter()` and `next()`. Mutable vectors and maps support -normal indexing, slicing, assignment, insertion, and deletion. +and iterators work with `iter()` and `next()`. Mutable vectors support indexing, +slicing, assignment, insertion, and deletion; mutable maps support standard +mapping assignment and deletion. Method inputs accept normal Python sequences and mappings in place of compatible WinRT collection interfaces. Byte arrays accept `bytes` and `bytearray`; GUID, @@ -184,40 +139,27 @@ Generated runtime classes that implement `IClosable` support `with` and an idempotent `close()` method. Prefer deterministic cleanup instead of relying on Python garbage collection. -## Experimental WinUI bootstrap - -When `Microsoft.UI.Xaml.Application` is generated with the WinUI metadata -provider and controls resources, codegen also emits -`Application.create_with_metadata_provider(...)` and `Application.create(...)`. -The latter installs `XamlControlsResources` and configures unpackaged resource -resolution when the required metadata is available. - -Public composable constructors keep their existing exact-class behavior. A -Python subclass of such a class is constructed with a non-null aggregated outer, -so ordinary inherited WinUI properties and methods retain one COM identity. -Metadata-supported native overrides are exposed through local overridable -interfaces. WinUI `IFrameworkElementOverrides.MeasureOverride`, -`ArrangeOverride`, and `OnApplyTemplate` are supported; size callbacks receive -and return `(width, height)` tuples. Callbacks run synchronously on the creating -WinUI apartment under the `ContextVar` context captured during construction. -Exceptions are reported through `sys.unraisablehook` and returned to WinUI as a -failing HRESULT. Unsupported override ABI shapes raise `TypeError` during -subclass construction. - -The WinUI 2.3 metadata contract used by the live test is -`IFrameworkElementOverrides` -(`ffc6fd98-f38c-5904-9ce4-97a3427cf4ba`): inherited by `StackPanel`, with -`MeasureOverride(Size) -> Size` at slot 6, `ArrangeOverride(Size) -> Size` at -slot 7, `OnApplyTemplate() -> void` at slot 8, and -`GoToElementStateCore(HSTRING, Boolean) -> Boolean` at slot 9. `Size` is two -ABI `f32` fields. Parameters are borrowed for the synchronous call and the -result is caller-owned out storage. StackPanel is metadata-agile, while Python -override callbacks remain intentionally bound to their creating UI apartment. - -Publicly composable controls can also register a Python subclass for XAML -markup activation: +## Experimental WinUI support + +When the required WinUI metadata is generated, `Application.create()` installs +`XamlControlsResources` and configures unpackaged resource resolution. +`Application.create_with_metadata_provider(...)` is available when the +application supplies its own provider. + +Python subclasses of public composable controls preserve one COM identity for +inherited properties and methods. Metadata-supported +`measure_override`, `arrange_override`, and `on_apply_template` callbacks run +synchronously on the creating UI apartment with the `contextvars` context +captured during construction. Unsupported native override shapes fail during +construction instead of falling back to an unsafe ABI. + +After creating the generated application, publicly composable controls can +register a Python subclass for activation by `XamlReader`: ```python +from generated.microsoft.ui.xaml.controls import StackPanel +from generated.microsoft.ui.xaml.markup import XamlReader + class PythonPanel(StackPanel): def measure_override(self, available_size): return available_size @@ -226,44 +168,36 @@ registration = StackPanel.register_xaml_runtime_class( "MyApp.Controls.PythonPanel", PythonPanel, ) -panel = StackPanel(XamlReader.load( - '' -)) -# Remove every instance from the XAML tree before releasing Python owners. +raw_panel = XamlReader.load( + '' +) +if raw_panel is None: + raise RuntimeError("XamlReader returned no value") +panel = StackPanel(raw_panel) + +# First remove every instance from the XAML tree and release application owners. panel = None +raw_panel = None registration.unregister() registration.release_instances() ``` -Registrations are process-local, duplicate names fail, and dropping or closing -the returned registration removes new lookups. The composed Application -metadata provider checks Python registrations before -`XamlControlsXamlMetaDataProvider`. Its `IXamlType` delegates inherited content -and member metadata to the declared WinUI base and activates through the Python -constructor on the registering STA. Constructor callbacks and captured `ContextVar` context remain available for -new activation until unregister. XAML-created Python owners stay process-rooted -until `release_instances()` so live native controls cannot lose their override -targets; call it only after those controls leave the XAML tree. Unsupported native -override ABIs, generic names, collection/dictionary/markup-extension bases, and -Python-defined XAML members fail closed. - -This deliberately does **not** call `RoRegisterActivationFactories`: ordinary -`RoActivateInstance("MyApp.Controls.PythonPanel")` remains unavailable. -`XamlReader` does not need that global activation path; WinUI resolves the name -through `IXamlMetadataProvider` and calls `IXamlType.ActivateInstance` directly -(WinUI source: `components/metadata/MetadataAPI.cpp` and -`ExtMetadataProvider/XamlType.cpp`). A class that must be activated outside this -Application/XAML provider boundary still requires a static WinMD plus packaged -manifest/in-process server registration. Protected composition and -system-returned classes remain non-constructible. +Registrations are process-local, and duplicate names fail. Unregistering, +closing, or dropping the registration prevents new XAML metadata lookups. +XAML-created Python owners remain rooted until `release_instances()`; call it +only after every corresponding native control has left the XAML tree. +Registration does not make the class globally activatable through +`RoActivateInstance`. Generated `Application.start()` and `DispatcherQueue.run_event_loop()` calls -remain on the caller's native thread but release the Python GIL while WinUI -pumps messages. WinRT callbacks reacquire the GIL, and worker-thread asyncio -code can use `DispatcherQueue.try_enqueue()` to return to the UI thread. +stay on the caller's native thread but release the Python GIL while WinUI pumps +messages. WinRT callbacks reacquire the GIL, and worker threads can use +`DispatcherQueue.try_enqueue()` to return to the UI thread. -Use a projected lifetime scope inside the COM apartment so generated wrappers -release their native values before `RoUninitialize`: +Use a projection lifetime scope inside the COM apartment so wrappers release +their native values before `RoUninitialize`: ```python from dynwinrt import RoApartment, projected_lifetime_scope @@ -273,17 +207,40 @@ with RoApartment(0), projected_lifetime_scope(): # Create and use WinUI objects here. ``` -Scopes nest in LIFO order. Wrappers that survive the scope remain Python -objects, but their native values are released and further WinRT calls fail -instead of releasing COM references after apartment teardown. +Scopes nest in LIFO order. Wrappers that survive a closed scope remain Python +objects, but their native values are released and further WinRT calls fail. + +Normal construction remains unavailable for protected-only composable classes +and system-returned classes without public activation metadata. Named Python +XAML registration does not support generic names, collection or dictionary +bases, markup-extension bases, or Python-defined XAML members. -The live x64 smoke test accepts explicit WinAppSDK metadata and bootstrap -inputs: +## Develop + +From `bindings\py`: ```powershell -.\tests\e2e\python_winui_e2e.ps1 ` - -WinuiWinmd ` - -RefList ` - -BootstrapDll ` - -Major 2 -Minor 3 -``` \ No newline at end of file +python -m pip install "maturin>=1.11,<2" "pytest>=8.3.5" "mypy>=1.13,<2" +python -m maturin develop +python -m pytest +``` + +## Release process + +The release tag supplies one unified npm/Cargo version. For example, +`v0.1.0-preview.21` produces npm version `0.1.0-preview.21` and Python version +`0.1.0rc21` after PEP 440 normalization. + +1. GitHub Actions builds and consumes eight CPython 3.11–3.14 runtime wheels + and two standalone codegen wheels on Windows x64 and native ARM64. +2. The official 1ES ADO pipeline builds both npm packages and waits for the + complete Python wheel matrix. +3. ADO creates one shared GitHub Release with the npm tarballs. GitHub Actions + attaches the ten tested Python wheels, and ADO downloads and revalidates the + complete set. +4. With `DoEsrp` enabled, ADO publishes both npm packages. `PublishPyPI` + defaults to enabled and publishes the eight `dynwinrt` wheels before the two + `dynwinrt-codegen` wheels. Disable it only for a non-PyPI rehearsal. + +PyPI publication uses the Microsoft ESRP release identity and is not available +from GitHub Actions. \ No newline at end of file diff --git a/bindings/py/pyproject.toml b/bindings/py/pyproject.toml index 94b3f0b7..0964ed49 100644 --- a/bindings/py/pyproject.toml +++ b/bindings/py/pyproject.toml @@ -5,6 +5,7 @@ build-backend = "maturin" [project] name = "dynwinrt" description = "Python bindings for dynamic WinRT API invocation" +readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11,<3.15" license = {text = "MIT"} authors = [ diff --git a/docs/status/PYTHON_CHECKLIST.md b/docs/status/PYTHON_CHECKLIST.md index a350d650..e22ec718 100644 --- a/docs/status/PYTHON_CHECKLIST.md +++ b/docs/status/PYTHON_CHECKLIST.md @@ -102,9 +102,9 @@ of a dynamic projection. wheel set to the shared JavaScript GitHub release. - [ ] Publish signed/provenanced wheels to an approved internal Python feed. - [x] Route production PyPI publication through the official 1ES ADO release - pipeline and Microsoft ESRP identity, behind the opt-in `PublishPyPI` - parameter that is disabled by default. -- [ ] Complete one-time ESRP/PyPI onboarding for `dynwinrt` and + pipeline and Microsoft ESRP identity. `PublishPyPI` is enabled by default + for tag releases and can be disabled for non-PyPI rehearsals. +- [x] Complete one-time ESRP/PyPI onboarding for `dynwinrt` and `dynwinrt-codegen`, including release owners and approvers. - [x] Add complete tested Python wheel assets and installation notes to GitHub releases. diff --git a/eng/release/python/verify_python_release.py b/eng/release/python/verify_python_release.py index f872a5e6..cde07ef7 100644 --- a/eng/release/python/verify_python_release.py +++ b/eng/release/python/verify_python_release.py @@ -20,6 +20,17 @@ CODEGEN_REQUIRES = ">=3.8,<3.15" RUNTIME_MINORS = tuple(f"3.{minor}" for minor in range(11, 15)) PLATFORM_TAGS = ("win_amd64", "win_arm64") +README_SPECS = { + "dynwinrt": {"file": "README.md", "content-type": "text/markdown"}, + "dynwinrt-codegen": { + "file": "python/README.md", + "content-type": "text/markdown", + }, +} +README_HEADINGS = { + "dynwinrt": "# dynwinrt", + "dynwinrt-codegen": "# dynwinrt-codegen", +} def load_toml(path: Path) -> dict: @@ -57,6 +68,8 @@ def verify_source(tag: str | None, release_version: str | None) -> None: assert SpecifierSet(codegen_project["requires-python"]) == SpecifierSet( CODEGEN_REQUIRES ) + assert runtime_project["readme"] == README_SPECS["dynwinrt"] + assert codegen_project["readme"] == README_SPECS["dynwinrt-codegen"] generated_manifest = ( ROOT / "tools" / "dynwinrt-codegen" / "src" / "codegen" / "package.rs" @@ -117,6 +130,17 @@ def verify_wheel(args: argparse.Namespace) -> None: ) dependencies = metadata.get_all("Requires-Dist", []) assert dependencies == [], f"Unexpected wheel dependencies: {dependencies}" + content_type = metadata["Description-Content-Type"] + assert content_type == "text/markdown", ( + f"Expected Markdown long description, got {content_type!r}" + ) + payload = metadata.get_payload(decode=True) + assert isinstance(payload, bytes), "Wheel long description is missing" + description = payload.decode("utf-8").strip() + expected_heading = README_HEADINGS[args.package] + assert description.startswith(expected_heading), ( + f"Wheel long description must start with {expected_heading!r}" + ) names = archive.namelist() if args.package == "dynwinrt": assert any(name.endswith(".pyd") for name in names) diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 5ce88b87..710aba30 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -1,150 +1,148 @@ # dynwinrt-codegen -Read Windows metadata (`.winmd`) files and generate typed bindings that use `@microsoft/dynwinrt` at runtime. +`dynwinrt-codegen` reads Windows metadata (`.winmd`) and generates typed +bindings for [dynwinrt](https://github.com/microsoft/dynwinrt): -## Install +- WinRT JavaScript (`.js`) with TypeScript declarations (`.d.ts`) +- WinRT Python (`.py`) with type stubs (`.pyi`) and a `py.typed` marker +- Supported Classic COM APIs from `Windows.Win32.winmd` as JavaScript and + TypeScript -```bash -npm install -D @microsoft/dynwinrt-codegen -``` +The command is available for Windows x64 and ARM64. Generated JavaScript uses +`@microsoft/dynwinrt`; generated Python uses `dynwinrt`. + +## Install -Python users can install the standalone native command: +### Python ```powershell -python -m pip install dynwinrt-codegen +python -m pip install --pre dynwinrt-codegen dynwinrt-codegen generate --namespace Windows.Foundation --class-name Uri ` - --lang py --output generated_uri + --lang py --output .\generated ``` -The Python distribution contains only the executable. Its wheels are -`py3-none-win_amd64` and `py3-none-win_arm64`, work with CPython 3.8–3.14, and -do not install or invoke Cargo/Rust. Generated Python packages require CPython -3.11–3.14 and pin `dynwinrt` to the exact codegen version. +The Python distribution is a standalone native command. Its +`py3-none-win_amd64` and `py3-none-win_arm64` wheels require Python 3.8–3.14 +but do not require Cargo or Rust. Generated Python package manifests require +CPython 3.11–3.14 and pin `dynwinrt` to the generator's exact version. -Generated Python module components longer than 120 characters use a stable -readable-prefix plus hash suffix. This keeps wheel build and installation paths -within practical Windows limits; public namespace imports remain unchanged. +### npm -## Usage - -```bash -npx dynwinrt-codegen generate [OPTIONS] +```powershell +npm install @microsoft/dynwinrt +npm install --save-dev @microsoft/dynwinrt-codegen +npx dynwinrt-codegen generate --namespace Windows.Foundation --class-name Uri ` + --output .\generated ``` -### Arguments - -| Argument | Required | Description | -|---|---|---| -| `--winmd` | No | Path to `.winmd` file(s), separated by `;`. Auto-detects Windows SDK if omitted | -| `--folder` | No | Directory containing `.winmd` files | -| `--namespace` | No | Generate only this namespace. If omitted, generates all non-Windows namespaces | -| `--class-name` | No | Class name(s) to generate, comma-separated (requires `--namespace`). E.g. `StorageFile` or `StorageFile,StorageFolder` | -| `--ref` | No | Additional `.winmd` files for type resolution only (no code generated). Paths separated by `;` | -| `--lang` | No | Target language: `js` (default, emits `.js` + `.d.ts`) or `py` (emits `.py`, optionally `.pyi`) | -| `--output` | No | Codegen-owned output directory (default: `./generated`). Existing contents may be replaced or removed; do not store handwritten files here. | -| `--dry-run` | No | Validate metadata and resolve dependencies without writing files | +## Generate -With `--lang js` (default), the tool emits plain ESM JavaScript (`.js`) plus matching ambient TypeScript declarations (`.d.ts`). No TypeScript compiler is needed — the output works for both JS and TS consumers. JSDoc comments are preserved so VS Code IntelliSense shows API descriptions. - -Repeated commands may append bindings to the same output directory when they -use the same restored metadata version. After changing WinMD files, SDK -versions, or reference inputs, delete the codegen-owned output directory and -run all generation commands again. +```text +dynwinrt-codegen generate [OPTIONS] +``` -> **Note:** Legacy flags `--lang ts`, `--lang cjs`, `--source-map`, `--declaration`, and `--no-declaration` are accepted by the npm CLI wrapper for backwards compatibility but are silently mapped to `--lang js` behavior. +Use `npx dynwinrt-codegen` instead of `dynwinrt-codegen` when running the npm +package. + +| Option | Description | +|---|---| +| `--winmd PATH[;PATH...]` | Metadata file paths. Sibling `.winmd` files are discovered automatically. The Windows SDK is auto-detected when no input supplies `Windows.*` metadata. | +| `--winmd-list FILE` | Newline-separated metadata paths to emit; blank lines and `#` comments are ignored. | +| `--folder DIR` | Load every `.winmd` file directly inside a directory. | +| `--namespace NS` | Generate one namespace. Without it, generate all non-`Windows.*` namespaces in the input. | +| `--class-name NAME[,NAME...]` | Generate specific classes or public interfaces. Use fully qualified names, or unqualified names together with `--namespace`. | +| `--ref PATH[;PATH...]` | Metadata used only for type resolution. Sibling discovery is disabled for references. | +| `--ref-list FILE` | Newline-separated reference metadata paths; blank lines and `#` comments are ignored. | +| `--lang js\|py` | `js` emits ESM `.js` and `.d.ts` files (default); `py` emits `.py`, `.pyi`, and `py.typed`. | +| `--output DIR` | Dedicated codegen-owned output directory (default `./generated`). Existing contents may be replaced or removed. | +| `--import-name NAME` | Runtime package imported by generated JavaScript (default `@microsoft/dynwinrt`). | +| `--dry-run` | Validate metadata, dependencies, ABI contracts, and layout without writing files. | +| `--pyi` | With `--lang py`, explicitly request the default type stubs; retained for compatibility. | +| `--no-pyi` | With `--lang py`, omit `.pyi` files and `py.typed`. | ### Examples -Generate JavaScript (ESM) bindings from a WinAppSDK metadata folder: - -```bash -npx dynwinrt-codegen generate \ - --folder path/to/metadata \ - --output ./generated-js \ - --lang js -``` +Generate two Windows SDK classes as JavaScript and TypeScript: -Generate bindings for a specific class (emits `.js` + `.d.ts`): - -```bash -npx dynwinrt-codegen generate \ - --namespace Windows.Storage \ - --class-name StorageFile \ - --output ./generated +```powershell +dynwinrt-codegen generate ` + --namespace Windows.Storage ` + --class-name StorageFile,StorageFolder ` + --output .\generated ``` -Generate multiple classes in one pass (shares the winmd index): +Generate Python from a restored metadata folder: -```bash -npx dynwinrt-codegen generate \ - --namespace Windows.Storage \ - --class-name StorageFile,StorageFolder \ - --output ./generated +```powershell +dynwinrt-codegen generate ` + --folder C:\path\to\metadata ` + --lang py ` + --output .\generated-python ``` -Generate all namespaces from multiple `.winmd` files: +Load emitted metadata and reference metadata from list files: -```bash -npx dynwinrt-codegen generate \ - --winmd "path/to/Windows.winmd;path/to/Microsoft.WindowsAppSDK.winmd" \ - --output ./generated +```powershell +dynwinrt-codegen generate ` + --winmd-list .\winmd-inputs.txt ` + --ref-list .\winmd-references.txt ` + --output .\generated ``` -Validate metadata without writing files: +Validate a generation request without changing the output directory: -```bash -npx dynwinrt-codegen generate \ - --folder path/to/metadata \ +```powershell +dynwinrt-codegen generate ` + --folder C:\path\to\metadata ` --dry-run ``` -## Output +### Other commands -For each WinRT class, the tool generates: +`dynwinrt-codegen capabilities` prints the command's supported features, one +machine-readable value per line. -- **Interface registration** -- `DynWinRtType.registerInterface()` with all methods and type signatures -- **Wrapper class** -- typed class with properties and methods -- **Constructors** -- unambiguous public WinRT activations projected as idiomatic JavaScript constructors -- **Factory methods** -- original static activation methods retained for compatibility -- **Enums** -- enum declarations -- **Collection types** -- `IVector`, `IVectorView`, `IMap`, etc. -- **Index file** -- re-exporting all generated types +`dynwinrt-codegen com-census --winmd [--json]` measures how many eligible +interfaces in `Windows.Win32.winmd` have complete safe Classic COM generation. -Dependencies are resolved automatically -- specifying `--class StorageFile` will also generate referenced types like `Uri`, enums, and interfaces. +## Generated output -## Build from Source +The generator resolves transitive dependencies and emits namespace index files. +WinRT output includes typed classes and interfaces, public activation +constructors, static factory methods, enums, structs, delegates, async +operations, and generic collections. -```bash -cargo build -p dynwinrt-codegen --release -``` +JavaScript output is ESM and needs no TypeScript compilation step. Python output +uses snake_case names and includes type information by default. Documentation +from sibling XML files is included when available. -The compiled executable needs to be copied into the npm package before publishing: +Classic COM generation is available only with `--lang js`. It is isolated in a +`com` subpackage and fails closed when metadata does not provide enough ABI, +layout, ownership, or cleanup information. See the +[Classic COM usage guide](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/classic-com-usage.md). -```bash -# x64 -cargo build -p dynwinrt-codegen --release -cp target/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/x64/ +The output directory belongs to codegen; do not store handwritten files in it. +After changing metadata files, SDK versions, or reference inputs, regenerate the +complete output. Python module components longer than 120 characters are +shortened with a stable readable prefix and hash suffix while public type names +remain unchanged. -# arm64 -cargo build -p dynwinrt-codegen --release --target aarch64-pc-windows-msvc -cp target/aarch64-pc-windows-msvc/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/arm64/ -``` +The npm wrapper accepts the legacy `--source-map`, `--declaration`, and +`--no-declaration` flags as no-ops. The Rust command accepts only `js` and `py` +for `--lang`. -Then publish: +## Build and test from source -```bash -cd tools/dynwinrt-codegen/npm -npm publish -``` +From the repository root: -In CI, this is handled automatically by the build workflow. - -## Testing - -```bash +```powershell +cargo build -p dynwinrt-codegen --release cargo test -p dynwinrt-codegen ``` -Tests include: -- Unit tests for type mapping, dependency resolution, and code generation helpers -- Snapshot test for `Windows.Foundation.Uri` (regenerate with `cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --class-name Uri --lang js --output tests/snapshots/uri`) +Official npm and PyPI packages are built and published by the repository release +pipelines. + +## License + +[MIT](https://github.com/microsoft/dynwinrt/blob/main/LICENSE) diff --git a/tools/dynwinrt-codegen/pyproject.toml b/tools/dynwinrt-codegen/pyproject.toml index 43ecafbc..e9bbd559 100644 --- a/tools/dynwinrt-codegen/pyproject.toml +++ b/tools/dynwinrt-codegen/pyproject.toml @@ -5,6 +5,7 @@ build-backend = "maturin" [project] name = "dynwinrt-codegen" description = "WinRT metadata reader and typed wrapper code generator for dynwinrt" +readme = { file = "python/README.md", content-type = "text/markdown" } requires-python = ">=3.8,<3.15" license = {text = "MIT"} authors = [ diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md new file mode 100644 index 00000000..6cabb82f --- /dev/null +++ b/tools/dynwinrt-codegen/python/README.md @@ -0,0 +1,158 @@ +# dynwinrt-codegen + +**Generate typed Python bindings for Windows Runtime (WinRT) APIs from `.winmd` +metadata.** + +`dynwinrt-codegen` reads the metadata shipped by the Windows SDK, WinAppSDK, and +other Windows components. It emits Python modules that use +[`dynwinrt`](https://pypi.org/project/dynwinrt/) to invoke those APIs at runtime. +The generated API uses Python naming, values, collections, type annotations, and +asyncio-compatible operations. + +## Why use this? + +Calling a WinRT API without an existing Python projection normally requires a +native extension or handwritten metadata, COM ABI, and marshaling code. +`dynwinrt-codegen` derives that information from `.winmd` files and generates: + +- Python classes with snake_case properties and methods +- type-checked overloads and `.pyi` type stubs +- asyncio-compatible WinRT operations +- Python-native collections, GUIDs, dates, times, and byte arrays +- enums, structs, delegates, and event helpers +- a package manifest pinned to the matching `dynwinrt` runtime version + +The generator is a standalone Windows executable. Installing or running it does +not require Cargo or Rust. + +## Install and generate + +```powershell +python -m pip install --pre dynwinrt-codegen + +# Generate one Windows SDK class. +dynwinrt-codegen generate ` + --namespace Windows.Foundation ` + --class-name Uri ` + --lang py ` + --output .\generated_uri + +# Install the generated package and its exact dynwinrt runtime dependency. +python -m pip install .\generated_uri +``` + +The generated package can then be imported normally: + +```python +from dynwinrt import RoApartment, projected_lifetime_scope +from generated_uri.windows.foundation import Uri + +with RoApartment(1), projected_lifetime_scope(): + uri = Uri("https://example.com/path") + print(uri.host) +``` + +## CLI options + +| Option | Description | +|---|---| +| `--winmd PATH[;PATH...]` | Metadata file paths. Sibling `.winmd` files are discovered automatically. The Windows SDK is auto-detected when no input supplies `Windows.*` metadata. | +| `--winmd-list FILE` | Newline-separated metadata paths to emit; blank lines and `#` comments are ignored. | +| `--folder DIR` | Load every `.winmd` file directly inside a directory. | +| `--namespace NS` | Generate one namespace. Without it, generate all non-`Windows.*` namespaces in the input. | +| `--class-name NAME[,NAME...]` | Generate specific classes or public interfaces. Use fully qualified names, or unqualified names together with `--namespace`. | +| `--ref PATH[;PATH...]` | Metadata used only for type resolution. Sibling discovery is disabled for references. | +| `--ref-list FILE` | Newline-separated reference metadata paths; blank lines and `#` comments are ignored. | +| `--output DIR` | Dedicated codegen-owned output directory (default `./generated`). Existing contents may be replaced or removed. | +| `--dry-run` | Validate metadata and dependencies without writing files. | +| `--pyi` | Explicitly request the default Python type stubs; retained for compatibility. | +| `--no-pyi` | Omit `.pyi` files and the `py.typed` marker. | + +Use `--lang py` for every Python generation command. Run +`dynwinrt-codegen generate --help` for the complete command reference. + +### More examples + +Generate two classes from the Windows SDK: + +```powershell +dynwinrt-codegen generate ` + --namespace Windows.Storage ` + --class-name StorageFile,StorageFolder ` + --lang py ` + --output .\storage_bindings +``` + +Generate all non-system namespaces from a restored metadata folder: + +```powershell +dynwinrt-codegen generate ` + --folder C:\path\to\metadata ` + --lang py ` + --output .\component_bindings +``` + +Use explicit reference metadata for a reproducible generation: + +```powershell +dynwinrt-codegen generate ` + --winmd-list .\winmd-inputs.txt ` + --ref-list .\winmd-references.txt ` + --lang py ` + --output .\component_bindings +``` + +Validate a request without changing its output directory: + +```powershell +dynwinrt-codegen generate ` + --folder C:\path\to\metadata ` + --lang py ` + --output .\component_bindings ` + --dry-run +``` + +## Generated output + +The output is an installable Python package. Its generated `pyproject.toml` pins +`dynwinrt` to the generator's exact version and requires CPython 3.11–3.14. +`.pyi` files and a `py.typed` marker are emitted by default. + +Transitive metadata dependencies are resolved automatically. Namespace packages +and imports mirror the metadata hierarchy, while public members use Python +snake_case naming. XML documentation found beside the input metadata is +included when available. + +Generated async methods return typed awaitable objects. WinRT collections +implement standard `collections.abc` protocols, flags use `enum.IntFlag`, and +compatible method inputs accept native Python sequences, mappings, `bytes`, +`bytearray`, `uuid.UUID`, `datetime.datetime`, and `datetime.timedelta`. + +The output directory belongs to codegen; do not store handwritten files in it. +After changing metadata files, SDK versions, or reference inputs, regenerate the +complete output. + +## Platform and limitations + +- The standalone generator has `py3-none-win_amd64` and + `py3-none-win_arm64` wheels for Python 3.8–3.14. +- Generated bindings and the `dynwinrt` runtime require CPython 3.11–3.14 on + Windows x64 or ARM64. +- Python generation currently supports WinRT metadata. Classic COM generation + from `Windows.Win32.winmd` is currently available only for JavaScript and + TypeScript. +- Some APIs require their Windows component, package identity, or framework + bootstrap to be present at runtime. + +Python module components longer than 120 characters are shortened with a stable +readable prefix and hash suffix while public type names remain unchanged. + +## Links + +- [`dynwinrt` runtime on PyPI](https://pypi.org/project/dynwinrt/) +- [Python runtime documentation](https://github.com/microsoft/dynwinrt/blob/main/bindings/py/README.md) +- [Source and issue tracker](https://github.com/microsoft/dynwinrt) + +## License + +[MIT](https://github.com/microsoft/dynwinrt/blob/main/LICENSE) diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 5f53e8e6..07bef6ff 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -25,10 +25,12 @@ use dynwinrt_codegen::xml_doc::DocTable; #[derive(Parser)] #[command(name = "dynwinrt-codegen")] -#[command(about = "Generate typed language bindings from WinRT metadata (.winmd) files")] +#[command(about = "Generate typed language bindings from Windows metadata (.winmd) files")] #[command( long_about = "dynwinrt-codegen reads .winmd metadata and generates typed bindings\n\ - that use @microsoft/dynwinrt at runtime to call Windows Runtime APIs dynamically.\n\n\ + for dynamic Windows API invocation. JavaScript and TypeScript output uses\n\ + @microsoft/dynwinrt; Python output uses dynwinrt. Supported Classic COM APIs\n\ + from Windows.Win32 metadata are available for JavaScript and TypeScript.\n\n\ It auto-detects Windows SDK metadata and discovers sibling .winmd files\n\ in the same directory, so you typically only need to point at one file." )]