Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@ jobs:
run: |
.\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q
.\bindings\py\.venv\Scripts\python.exe -m mypy.stubtest dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases
- name: Test generated Python long paths
run: |
.\eng\release\python\test_generated_python_long_paths.ps1 `
-Python .\bindings\py\.venv\Scripts\python.exe `
-Codegen .\target\release\dynwinrt-codegen.exe
- name: Run E2E tests
run: .\tests\e2e\e2e_test.ps1 -SkipBuild
- name: Test JS TSFN lifecycle and queue handling
Expand Down
7 changes: 6 additions & 1 deletion bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,12 @@ button = project_as(raw_button, Button)
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`.
Classes with a verifiable default-interface IID remain valid projection
targets even when metadata exposes them only through `Object`/`IInspectable`.
Projection always performs QueryInterface, so a static-only declaration cannot
produce a wrapper unless the input actually implements that default interface.
Incompatible types raise the ordinary WinRT `OSError`. Static-only metadata
classes with no instance surface are not projection targets.

Use `wrapper.as_interface(InterfaceClass)` when converting an existing
wrapper to an interface view. Use `InterfaceClass.from_value(raw)` for a raw
Expand Down
11 changes: 7 additions & 4 deletions bindings/py/dynwinrt.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@ _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")
_ProjectableClass = TypeVar("_ProjectableClass", bound="_DynWinRTProjectableClass")


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


class _DynWinRTRuntimeClass: ...
class _DynWinRTProjectableClass: ...


class _DynWinRTRuntimeClass(_DynWinRTProjectableClass): ...


__all__ = [
Expand Down Expand Up @@ -103,8 +106,8 @@ class ProjectedLifetimeScope:
def projected_lifetime_scope() -> ProjectedLifetimeScope: ...

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

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

Expand Down
5 changes: 4 additions & 1 deletion bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,10 @@ def project_as(value, wrapper_type):
'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):
if not (
getattr(wrapper_type, '_dynwinrt_runtime_class_type', False)
or getattr(wrapper_type, '_dynwinrt_projectable_class_type', False)
):
raise TypeError('project_as requires a generated runtime class type.')
projector = getattr(wrapper_type, '_from_native', None)
if not callable(projector):
Expand Down
14 changes: 14 additions & 0 deletions bindings/py/tests/test_phase1.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,20 @@ def test_project_as_borrows_input_and_returns_managed_projection():
raw.release()


def test_project_as_accepts_qi_only_generated_class():
Wrapper = _projected_wrapper_type("ProjectAsQiOnlyWrapper")
del Wrapper._dynwinrt_runtime_class_type
Wrapper._dynwinrt_projectable_class_type = True

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

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


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

Expand Down
175 changes: 175 additions & 0 deletions eng/release/python/test_generated_python_long_paths.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

param(
[Parameter(Mandatory = $true)][string]$Python,
[Parameter(Mandatory = $true)][string]$Codegen
)

$ErrorActionPreference = "Stop"
$tempRoot = [System.IO.Path]::GetTempPath().TrimEnd("\")
$prefix = "dynwinrt-python-long-path-"
$paddingLength = 104 - $tempRoot.Length - 1 - $prefix.Length
if ($paddingLength -lt 8) {
throw "Temporary directory is too long for the generated Python path test"
}
$longSegment = $prefix + ("x" * $paddingLength)
$root = Join-Path $tempRoot $longSegment
if ($root.Length -ne 104) {
throw "Long-path test root must be 104 characters, got $($root.Length)"
}
$source = Join-Path $root "source\generated_bindings"
$wheelDirectory = Join-Path $root "wheels"
$install = Join-Path $root "installed"

try {
Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $wheelDirectory | Out-Null

& $Codegen generate `
--class-name Windows.Devices.Enumeration.DeviceInformationCustomPairing `
--lang py `
--output $source
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

$modules = Get-ChildItem -LiteralPath $source -File -Filter *.py
$tooLong = $modules | Where-Object { $_.BaseName.Length -gt 120 }
if ($tooLong) {
throw "Generated Python module exceeds 120 characters: $($tooLong[0].Name)"
}
if (-not ($modules | Where-Object { $_.BaseName -match "_[0-9a-f]{16}$" })) {
throw "Long-path fixture did not generate a hashed Python module"
}

$targetSymbol =
"TypedEventHandler_DeviceInformationCustomPairing_DevicePairingSetMembersRequestedEventArgs"
$shortModule = $modules |
Where-Object {
$_.BaseName -match "_[0-9a-f]{16}$" -and
(Select-String -LiteralPath $_.FullName -Pattern $targetSymbol -Quiet)
} |
Select-Object -First 1
if (-not $shortModule) {
throw "Long-path fixture did not generate the expected typed event handler"
}

$buildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
if (-not $buildBaseMatch) {
throw "Generated setup.cfg does not define a scoped build cache"
}
$initialBuildBase = $buildBaseMatch.Matches[0].Groups[1].Value.Trim()
$initialScopedCache = Join-Path $source $initialBuildBase
$cachedPackages = @(
(Join-Path $source "build\lib\generated_bindings"),
(Join-Path $initialScopedCache "lib\generated_bindings"),
(Join-Path $source ".venv\Lib\site-packages\generated_bindings"),
(Join-Path $source "venv\Lib\site-packages\generated_bindings"),
(Join-Path $source "env\Lib\site-packages\generated_bindings"),
(Join-Path $source ".tox\py\Lib\site-packages\generated_bindings"),
(Join-Path $source ".nox\py\Lib\site-packages\generated_bindings")
)
foreach ($cachedPackage in $cachedPackages) {
New-Item -ItemType Directory -Force -Path $cachedPackage | Out-Null
foreach ($extension in @("py", "pyi")) {
Copy-Item `
-LiteralPath (Join-Path $source "$($shortModule.BaseName).$extension") `
-Destination $cachedPackage
}
}
$eggInfo = Join-Path $source "generated_bindings.egg-info"
New-Item -ItemType Directory -Force -Path $eggInfo | Out-Null
Set-Content -LiteralPath (Join-Path $eggInfo "SOURCES.txt") -Value $shortModule.BaseName
$dist = Join-Path $source "dist"
New-Item -ItemType Directory -Force -Path $dist | Out-Null
Set-Content -LiteralPath (Join-Path $dist "old-generated-bindings.whl") -Value $shortModule.BaseName
$pycache = Join-Path $source "__pycache__"
New-Item -ItemType Directory -Force -Path $pycache | Out-Null
Set-Content -LiteralPath (Join-Path $pycache "old.pyc") -Value $shortModule.BaseName
$preservedArtifacts = @(
(Join-Path $source "build"),
$initialScopedCache,
(Join-Path $source ".venv"),
(Join-Path $source "venv"),
(Join-Path $source "env"),
(Join-Path $source ".tox"),
(Join-Path $source ".nox"),
$dist,
$pycache,
$eggInfo
)

& $Codegen generate `
--class-name Windows.Foundation.Uri `
--lang py `
--output $source
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
foreach ($artifact in $preservedArtifacts) {
if (-not (Test-Path -LiteralPath $artifact)) {
throw "Incremental generation deleted user artifact $artifact"
}
}
$newBuildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
$newBuildBase = $newBuildBaseMatch.Matches[0].Groups[1].Value.Trim()
if ($newBuildBase -eq $initialBuildBase) {
throw "Generated file layout change did not rotate the scoped build cache"
}
foreach ($extension in @("py", "pyi")) {
if (-not (Test-Path -LiteralPath (
Join-Path $source "$($shortModule.BaseName).$extension"))) {
throw "Unrelated incremental generation removed $($shortModule.BaseName).$extension"
}
}

$preRenameBuildBase = $newBuildBase
$renamedSource = Join-Path (Split-Path $source -Parent) "renamed_bindings"
Move-Item -LiteralPath $source -Destination $renamedSource
$source = $renamedSource
$staleOldPackage = Join-Path $source (
Join-Path $preRenameBuildBase "lib\generated_bindings")
New-Item -ItemType Directory -Force -Path $staleOldPackage | Out-Null
Set-Content `
-LiteralPath (Join-Path $staleOldPackage "stale_old_package.py") `
-Value "STALE = True"
Set-Content `
-LiteralPath (Join-Path $staleOldPackage "stale_old_package.pyi") `
-Value "STALE: bool"

& $Codegen generate `
--class-name Windows.Foundation.Uri `
--lang py `
--output $source
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$renamedBuildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
$renamedBuildBase = $renamedBuildBaseMatch.Matches[0].Groups[1].Value.Trim()
if ($renamedBuildBase -eq $preRenameBuildBase) {
throw "Output package rename did not rotate the scoped build cache"
}
if (-not (Test-Path -LiteralPath $staleOldPackage)) {
throw "Output package rename deleted the old build cache"
}

& $Python -m pip wheel $source --no-deps --wheel-dir $wheelDirectory
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$wheel = Get-ChildItem -LiteralPath $wheelDirectory -Filter *.whl -File |
Select-Object -First 1
if (-not $wheel) { throw "Generated bindings wheel was not created" }

& $Python -m pip install $wheel.FullName --no-deps --target $install
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") `
--source $source `
--install $install `
--package renamed_bindings
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if (Test-Path -LiteralPath (Join-Path $install "generated_bindings")) {
throw "Renamed wheel retained the old generated_bindings package"
}
} finally {
Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue
}
78 changes: 78 additions & 0 deletions eng/release/python/verify_generated_python_install.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

import argparse
import importlib
import sys
from pathlib import Path


def package_files(root: Path) -> set[Path]:
return {
path.relative_to(root)
for extension in ("*.py", "*.pyi")
for path in root.rglob(extension)
}


def generated_source_files(root: Path) -> set[Path]:
inventory = root / ".dynwinrt-generated-files"
files = {
Path(line)
for line in inventory.read_text(encoding="utf-8").splitlines()
if Path(line).suffix in {".py", ".pyi"}
}
invalid = [path for path in files if path.is_absolute() or ".." in path.parts]
if invalid:
raise RuntimeError(f"Generated inventory contains invalid paths: {invalid[:10]}")
missing = [path for path in files if not (root / path).is_file()]
if missing:
raise RuntimeError(f"Generated inventory references missing files: {missing[:10]}")
return files


def module_name(package: str, relative: Path) -> str:
parts = (
relative.parts[:-1]
if relative.name == "__init__.py"
else relative.with_suffix("").parts
)
return ".".join((package, *parts))


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--install", type=Path, required=True)
parser.add_argument("--package", required=True)
args = parser.parse_args()

source = args.source.resolve()
installed = (args.install.resolve() / args.package)
expected = generated_source_files(source)
actual = package_files(installed)
missing = sorted(expected - actual)
if missing:
raise RuntimeError(
f"Installed package is missing {len(missing)} generated files: {missing[:10]}"
)
unexpected = sorted(actual - expected)
if unexpected:
raise RuntimeError(
f"Installed package has {len(unexpected)} unexpected generated files: "
f"{unexpected[:10]}"
)

sys.path.insert(0, str(args.install.resolve()))
modules = {
module_name(args.package, path)
for path in expected
if path.suffix == ".py"
}
for name in sorted(modules):
importlib.import_module(name)
print(f"verified {len(expected)} files and imported {len(modules)} modules")


if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions tools/dynwinrt-codegen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ The Python distribution contains only the executable. Its wheels are
do not install or invoke Cargo/Rust. Generated Python packages require CPython
3.11–3.14 and pin `dynwinrt` to the exact codegen 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.

## Usage

```bash
Expand Down
Loading
Loading