diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml new file mode 100644 index 00000000..d542c2a8 --- /dev/null +++ b/.github/workflows/python-release.yml @@ -0,0 +1,496 @@ +name: Python wheels + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +on: + pull_request: + branches: [main] + paths: + - '.github/workflows/python-release.yml' + - 'bindings/py/**' + - 'crates/dynwinrt/**' + - 'scripts/test_python_*_wheel.ps1' + - 'scripts/verify_python_release.py' + - 'tools/dynwinrt-codegen/**' + - 'Cargo.lock' + - 'Cargo.toml' + push: + tags: ['python-v*'] + workflow_dispatch: + inputs: + release_version: + description: Cargo/package version expected from the selected ref + required: false + type: string + publish_pypi: + description: Publish through the protected pypi environment (tag refs only) + required: true + default: false + type: boolean + +permissions: + contents: read + +concurrency: + group: python-release-${{ github.ref }} + cancel-in-progress: false + +jobs: + validate: + runs-on: windows-latest + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Validate release metadata and tag + id: version + shell: pwsh + env: + RELEASE_VERSION: ${{ inputs.release_version }} + PUBLISH_PYPI: ${{ inputs.publish_pypi }} + REF_NAME: ${{ github.ref_name }} + REF_TYPE: ${{ github.ref_type }} + run: | + python -m pip install "packaging>=24,<27" --quiet + $cargo = Get-Content bindings\py\Cargo.toml -Raw + $version = [regex]::Match($cargo, '(?m)^version = "([^"]+)"$').Groups[1].Value + if (-not $version) { throw 'Could not read bindings/py Cargo version' } + + $arguments = @('scripts\verify_python_release.py', 'source') + if ($env:RELEASE_VERSION) { + $arguments += @('--release-version', $env:RELEASE_VERSION) + } + if ($env:REF_TYPE -eq 'tag') { + $arguments += @('--tag', $env:REF_NAME) + } + python @arguments + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + if ($env:PUBLISH_PYPI -eq 'true' -and + ($env:REF_TYPE -ne 'tag' -or $env:REF_NAME -notlike 'python-v*')) { + throw 'PyPI publication requires dispatching an existing python-v tag' + } + if ($env:PUBLISH_PYPI -eq 'true' -and -not $env:RELEASE_VERSION) { + throw 'PyPI publication requires an explicit release_version confirmation' + } + "version=$version" >> $env:GITHUB_OUTPUT + + runtime-x64: + needs: validate + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: + - { python: '3.11', tag: cp311 } + - { python: '3.12', tag: cp312 } + - { python: '3.13', tag: cp313 } + - { python: '3.14', tag: cp314 } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + architecture: x64 + - uses: dtolnay/rust-toolchain@stable + - name: Build and inspect runtime wheel + shell: pwsh + env: + VERSION: ${{ needs.validate.outputs.version }} + run: | + python -c "import platform, sys; assert platform.machine().lower() in ('amd64', 'x86_64'); assert f'{sys.version_info.major}.{sys.version_info.minor}' == '${{ matrix.python }}'" + python -m pip install "maturin>=1.11,<2" "packaging>=24,<27" --quiet + Remove-Item artifacts\runtime -Recurse -Force -ErrorAction SilentlyContinue + python -m maturin build --release --locked ` + --manifest-path bindings\py\Cargo.toml ` + --interpreter python ` + --out artifacts\runtime + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $wheel = @(Get-ChildItem artifacts\runtime\*.whl) + if ($wheel.Count -ne 1) { throw "Expected one runtime wheel, found $($wheel.Count)" } + python scripts\verify_python_release.py wheel ` + --wheel $wheel[0].FullName ` + --package dynwinrt-py ` + --version $env:VERSION ` + --python-tag '${{ matrix.tag }}' ` + --abi-tag '${{ matrix.tag }}' ` + --platform-tag win_amd64 + - uses: actions/upload-artifact@v4 + with: + name: python-runtime-${{ matrix.tag }}-x64 + path: artifacts\runtime\*.whl + if-no-files-found: error + + runtime-arm64: + if: github.event_name != 'pull_request' + needs: validate + runs-on: [self-hosted, Windows, ARM64, winui] + strategy: + fail-fast: false + matrix: + include: + - { python: '3.11', tag: cp311 } + - { python: '3.12', tag: cp312 } + - { python: '3.13', tag: cp313 } + - { python: '3.14', tag: cp314 } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + architecture: arm64 + - uses: dtolnay/rust-toolchain@stable + - name: Build and inspect native ARM64 runtime wheel + shell: pwsh + env: + VERSION: ${{ needs.validate.outputs.version }} + run: | + python -c "import platform, struct, sys; assert platform.machine().lower() in ('arm64', 'aarch64'); assert struct.calcsize('P') == 8; assert f'{sys.version_info.major}.{sys.version_info.minor}' == '${{ matrix.python }}'" + python -m pip install "maturin>=1.11,<2" "packaging>=24,<27" --quiet + Remove-Item artifacts\runtime -Recurse -Force -ErrorAction SilentlyContinue + python -m maturin build --release --locked ` + --manifest-path bindings\py\Cargo.toml ` + --interpreter python ` + --out artifacts\runtime + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $wheel = @(Get-ChildItem artifacts\runtime\*.whl) + if ($wheel.Count -ne 1) { throw "Expected one runtime wheel, found $($wheel.Count)" } + python scripts\verify_python_release.py wheel ` + --wheel $wheel[0].FullName ` + --package dynwinrt-py ` + --version $env:VERSION ` + --python-tag '${{ matrix.tag }}' ` + --abi-tag '${{ matrix.tag }}' ` + --platform-tag win_arm64 + - uses: actions/upload-artifact@v4 + with: + name: python-runtime-${{ matrix.tag }}-arm64 + path: artifacts\runtime\*.whl + if-no-files-found: error + + codegen-x64: + needs: validate + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.8' + architecture: x64 + - uses: dtolnay/rust-toolchain@stable + - name: Build and inspect standalone codegen wheel + shell: pwsh + env: + VERSION: ${{ needs.validate.outputs.version }} + run: | + python -m pip install "maturin>=1.11,<2" "packaging>=24,<27" --quiet + Remove-Item artifacts\codegen -Recurse -Force -ErrorAction SilentlyContinue + python -m maturin build --release --locked ` + --manifest-path tools\dynwinrt-codegen\Cargo.toml ` + --out artifacts\codegen + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $wheel = @(Get-ChildItem artifacts\codegen\*.whl) + if ($wheel.Count -ne 1) { throw "Expected one codegen wheel, found $($wheel.Count)" } + python scripts\verify_python_release.py wheel ` + --wheel $wheel[0].FullName ` + --package dynwinrt-codegen ` + --version $env:VERSION ` + --python-tag py3 ` + --abi-tag none ` + --platform-tag win_amd64 + - uses: actions/upload-artifact@v4 + with: + name: python-codegen-x64 + path: artifacts\codegen\*.whl + if-no-files-found: error + + codegen-arm64: + if: github.event_name != 'pull_request' + needs: validate + runs-on: [self-hosted, Windows, ARM64, winui] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + architecture: arm64 + - uses: dtolnay/rust-toolchain@stable + - name: Build and inspect native ARM64 standalone codegen wheel + shell: pwsh + env: + VERSION: ${{ needs.validate.outputs.version }} + run: | + python -c "import platform, struct; assert platform.machine().lower() in ('arm64', 'aarch64'); assert struct.calcsize('P') == 8" + python -m pip install "maturin>=1.11,<2" "packaging>=24,<27" --quiet + Remove-Item artifacts\codegen -Recurse -Force -ErrorAction SilentlyContinue + python -m maturin build --release --locked ` + --manifest-path tools\dynwinrt-codegen\Cargo.toml ` + --out artifacts\codegen + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $wheel = @(Get-ChildItem artifacts\codegen\*.whl) + if ($wheel.Count -ne 1) { throw "Expected one codegen wheel, found $($wheel.Count)" } + python scripts\verify_python_release.py wheel ` + --wheel $wheel[0].FullName ` + --package dynwinrt-codegen ` + --version $env:VERSION ` + --python-tag py3 ` + --abi-tag none ` + --platform-tag win_arm64 + - uses: actions/upload-artifact@v4 + with: + name: python-codegen-arm64 + path: artifacts\codegen\*.whl + if-no-files-found: error + + consume-codegen-x64: + needs: [validate, codegen-x64] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.8' + architecture: x64 + - uses: actions/download-artifact@v4 + with: + name: python-codegen-x64 + path: artifacts\codegen + - name: Consume standalone wheel without Rust + shell: pwsh + run: | + python -m pip install "packaging>=24,<27" --quiet + $wheel = @(Get-ChildItem artifacts\codegen\*.whl) + python scripts\verify_python_release.py wheel --wheel $wheel[0].FullName ` + --package dynwinrt-codegen --version '${{ needs.validate.outputs.version }}' ` + --python-tag py3 --abi-tag none --platform-tag win_amd64 + .\scripts\test_python_codegen_wheel.ps1 -Python (Get-Command python).Source ` + -WheelDirectory artifacts\codegen ` + -Version '${{ needs.validate.outputs.version }}' -Architecture x64 + + consume-codegen-arm64: + if: github.event_name != 'pull_request' + needs: [validate, codegen-arm64] + runs-on: [self-hosted, Windows, ARM64, winui] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + architecture: arm64 + - uses: actions/download-artifact@v4 + with: + name: python-codegen-arm64 + path: artifacts\codegen + - name: Consume native standalone wheel without Rust + shell: pwsh + run: | + python -m pip install "packaging>=24,<27" --quiet + .\scripts\test_python_codegen_wheel.ps1 -Python (Get-Command python).Source ` + -WheelDirectory artifacts\codegen ` + -Version '${{ needs.validate.outputs.version }}' -Architecture arm64 + + consume-runtime-x64: + needs: [validate, runtime-x64, codegen-x64] + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: + - { python: '3.11', tag: cp311 } + - { python: '3.12', tag: cp312 } + - { python: '3.13', tag: cp313 } + - { python: '3.14', tag: cp314 } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + architecture: x64 + - uses: actions/download-artifact@v4 + with: + name: python-runtime-${{ matrix.tag }}-x64 + path: artifacts\runtime + - uses: actions/download-artifact@v4 + with: + name: python-codegen-x64 + path: artifacts\codegen + - name: Import wheel and call Windows.Foundation.Uri + shell: pwsh + run: | + .\scripts\test_python_runtime_wheel.ps1 -Python (Get-Command python).Source ` + -RuntimeWheelDirectory artifacts\runtime ` + -CodegenWheelDirectory artifacts\codegen ` + -Version '${{ needs.validate.outputs.version }}' ` + -Architecture x64 -PythonMinor '${{ matrix.python }}' + + consume-runtime-arm64: + if: github.event_name != 'pull_request' + needs: [validate, runtime-arm64, codegen-arm64] + runs-on: [self-hosted, Windows, ARM64, winui] + strategy: + fail-fast: false + matrix: + include: + - { python: '3.11', tag: cp311 } + - { python: '3.12', tag: cp312 } + - { python: '3.13', tag: cp313 } + - { python: '3.14', tag: cp314 } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + architecture: arm64 + - uses: actions/download-artifact@v4 + with: + name: python-runtime-${{ matrix.tag }}-arm64 + path: artifacts\runtime + - uses: actions/download-artifact@v4 + with: + name: python-codegen-arm64 + path: artifacts\codegen + - name: Import native wheel and call Windows.Foundation.Uri + shell: pwsh + run: | + .\scripts\test_python_runtime_wheel.ps1 -Python (Get-Command python).Source ` + -RuntimeWheelDirectory artifacts\runtime ` + -CodegenWheelDirectory artifacts\codegen ` + -Version '${{ needs.validate.outputs.version }}' ` + -Architecture arm64 -PythonMinor '${{ matrix.python }}' + + assemble-release: + if: github.event_name != 'pull_request' + needs: + - validate + - consume-codegen-x64 + - consume-codegen-arm64 + - consume-runtime-x64 + - consume-runtime-arm64 + runs-on: windows-latest + steps: + - uses: actions/download-artifact@v4 + with: + pattern: python-runtime-* + path: dist\runtime + merge-multiple: true + - uses: actions/download-artifact@v4 + with: + pattern: python-codegen-* + path: dist\codegen + merge-multiple: true + - name: Require the complete tested release set + shell: pwsh + run: | + $runtime = @(Get-ChildItem dist\runtime\*.whl) + $codegen = @(Get-ChildItem dist\codegen\*.whl) + if ($runtime.Count -ne 8) { throw "Expected 8 runtime wheels, found $($runtime.Count)" } + if ($codegen.Count -ne 2) { throw "Expected 2 codegen wheels, found $($codegen.Count)" } + $all = @($runtime + $codegen) + if (($all.Name | Sort-Object -Unique).Count -ne 10) { + throw 'Release wheel filenames are not unique' + } + - uses: actions/upload-artifact@v4 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist\**\*.whl + if-no-files-found: error + retention-days: 30 + + github-release: + if: github.event_name == 'push' && github.ref_type == 'tag' + needs: [validate, assemble-release] + runs-on: windows-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist + - name: Attach tested wheels to GitHub release + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + VERSION: ${{ needs.validate.outputs.version }} + run: | + $wheels = (Get-ChildItem dist\*.whl -Recurse).FullName + & gh release view $env:TAG *> $null + if ($LASTEXITCODE -eq 0) { + & gh release upload $env:TAG --clobber @wheels + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + exit 0 + } + $arguments = @( + 'release', 'create', $env:TAG, + '--verify-tag', + '--generate-notes', + '--title', "Python v$env:VERSION" + ) + if ($env:VERSION -match '-') { $arguments += '--prerelease' } + $arguments += $wheels + & gh @arguments + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + publish-runtime: + if: >- + github.event_name == 'workflow_dispatch' && + inputs.publish_pypi && + github.ref_type == 'tag' && + startsWith(github.ref_name, 'python-v') + needs: [validate, assemble-release] + runs-on: ubuntu-latest + environment: pypi + permissions: + contents: read + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist + - name: Stage runtime wheels only + shell: bash + run: | + mkdir -p publish/runtime + find dist -type f -name 'dynwinrt_py-*.whl' -exec cp '{}' publish/runtime/ \; + test "$(find publish/runtime -type f -name '*.whl' | wc -l)" -eq 8 + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: publish/runtime + attestations: true + skip-existing: true + + publish-codegen: + if: >- + github.event_name == 'workflow_dispatch' && + inputs.publish_pypi && + github.ref_type == 'tag' && + startsWith(github.ref_name, 'python-v') + needs: [validate, assemble-release, publish-runtime] + runs-on: ubuntu-latest + environment: pypi + permissions: + contents: read + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist + - name: Stage codegen wheels only + shell: bash + run: | + mkdir -p publish/codegen + find dist -type f -name 'dynwinrt_codegen-*.whl' -exec cp '{}' publish/codegen/ \; + test "$(find publish/codegen -type f -name '*.whl' | wc -l)" -eq 2 + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: publish/codegen + attestations: true + skip-existing: true diff --git a/.github/workflows/winui-arm64.yml b/.github/workflows/winui-arm64.yml new file mode 100644 index 00000000..765f84c6 --- /dev/null +++ b/.github/workflows/winui-arm64.yml @@ -0,0 +1,92 @@ +name: Python WinUI ARM64 + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +on: + workflow_dispatch: + +jobs: + live-winui: + # This runner must have an interactive desktop session and the ARM64 + # Microsoft.WindowsAppRuntime.2 framework installed. + runs-on: [self-hosted, Windows, ARM64, winui] + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: NuGet/setup-nuget@v2 + + - name: Verify native ARM64 environment + shell: pwsh + run: | + python -c "import platform, struct; assert platform.machine().lower() in ('arm64', 'aarch64'); assert struct.calcsize('P') == 8" + $runtime = Get-AppxPackage Microsoft.WindowsAppRuntime.2 | + Where-Object Architecture -eq Arm64 | + Sort-Object Version -Descending | + Select-Object -First 1 + if (-not $runtime) { + throw 'Microsoft.WindowsAppRuntime.2 ARM64 must be installed on the live WinUI runner' + } + + - name: Restore WinAppSDK metadata and bootstrap + shell: pwsh + run: | + $packages = Join-Path $env:RUNNER_TEMP 'winappsdk' + nuget install Microsoft.WindowsAppSDK.Foundation -Version 2.3.5 -OutputDirectory $packages -DirectDownload -NonInteractive + nuget install Microsoft.WindowsAppSDK.InteractiveExperiences -Version 2.1.3 -OutputDirectory $packages -DirectDownload -NonInteractive + nuget install Microsoft.WindowsAppSDK.WinUI -Version 2.3.0 -OutputDirectory $packages -DirectDownload -NonInteractive + + $winui = Get-ChildItem $packages -Filter Microsoft.UI.Xaml.winmd -File -Recurse | + Select-Object -First 1 + $bootstrap = Get-ChildItem $packages -Filter Microsoft.WindowsAppRuntime.Bootstrap.dll -File -Recurse | + Where-Object FullName -Match 'runtimes[\\/]win-arm64[\\/]native' | + Select-Object -First 1 + if (-not $winui -or -not $bootstrap) { + throw 'WinAppSDK metadata or ARM64 bootstrap DLL was not restored' + } + + $refs = Get-ChildItem $packages -Filter *.winmd -File -Recurse | + Where-Object { + $_.FullName -ne $winui.FullName -and ( + $_.FullName -Match 'Foundation' -or + $_.FullName -Match 'metadata[\\/]10\.0\.18362\.0' -or + $_.Name -eq 'Microsoft.UI.Text.winmd' + ) + } | + Sort-Object FullName -Unique + $refList = Join-Path $env:RUNNER_TEMP 'winappsdk-refs.txt' + $refs.FullName | Set-Content -LiteralPath $refList -Encoding utf8 + + "WINUI_WINMD=$($winui.FullName)" >> $env:GITHUB_ENV + "WINUI_REFS=$refList" >> $env:GITHUB_ENV + "WINUI_BOOTSTRAP=$($bootstrap.FullName)" >> $env:GITHUB_ENV + + - name: Build ARM64 codegen and Python runtime + shell: pwsh + run: | + cargo build -p dynwinrt-codegen --release + python -m venv bindings\py\.venv + $python = Join-Path $PWD 'bindings\py\.venv\Scripts\python.exe' + & $python -m pip install "maturin>=1.11,<2" --quiet + $env:VIRTUAL_ENV = Join-Path $PWD 'bindings\py\.venv' + Push-Location bindings\py + try { + & $python -m maturin develop --release + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } finally { + Pop-Location + } + "WINUI_PYTHON=$python" >> $env:GITHUB_ENV + + - name: Run live Python WinUI ARM64 E2E + shell: pwsh + run: | + .\tests\python_winui_e2e.ps1 ` + -WinuiWinmd $env:WINUI_WINMD ` + -RefList $env:WINUI_REFS ` + -BootstrapDll $env:WINUI_BOOTSTRAP ` + -Major 2 ` + -Minor 3 ` + -Python $env:WINUI_PYTHON ` + -SkipBuild diff --git a/.gitignore b/.gitignore index 04c6e8b5..9be59a2a 100644 --- a/.gitignore +++ b/.gitignore @@ -440,3 +440,4 @@ bench-electron/out/ **/settings.local.json # Generated E2E projections are recreated and removed by tests/e2e_test.ps1. tests/e2e_generated/ +.python-release/ diff --git a/PYTHON_CHECKLIST.md b/PYTHON_CHECKLIST.md index a28ea69b..7e74d573 100644 --- a/PYTHON_CHECKLIST.md +++ b/PYTHON_CHECKLIST.md @@ -56,6 +56,8 @@ of a dynamic projection. - [x] Accept `T | None` in `IReference` input positions. - [x] Project null reference returns and reference-array elements as `T | None` consistently in runtime code and stubs. +- [x] Project `IReference` struct fields as native `T | None` on reads while + accepting native values, `None`, and legacy wrappers on writes. - [x] Preserve the full `UInt32` / `UInt64` range when converting to Python integers. - [x] Make Python stubs part of E2E and run a static type checker. @@ -75,13 +77,21 @@ of a dynamic projection. - [x] Execute all tests under `bindings/py/tests` in CI. - [x] Build and install wheels before running Python E2E. -- [ ] Test supported CPython versions on x64 and ARM64. -- [ ] Remove unverified PyPy metadata or add real PyPy coverage. -- [ ] Derive the Python package version from the release tag. +- [ ] Complete the first live CPython 3.11–3.14 x64/ARM64 release-matrix run. + The native ARM64 jobs are configured on the existing self-hosted WinUI + runner and fail closed; local x64 validation does not count as ARM64 + validation. +- [x] Remove unverified PyPy metadata. +- [x] Require `python-v` release tags to match both Cargo package + versions rather than rewriting release sources in CI. - [ ] Publish signed/provenanced wheels to an approved internal Python feed. -- [ ] Add Python wheel assets and installation notes to GitHub releases. -- [ ] Provide a Python-native or standalone codegen installation path. -- [ ] Add a clean-machine consumer test that uses only released artifacts. +- [x] Add a protected-environment, OIDC trusted-publishing path that requires + manual opt-in from an existing release tag. +- [x] Add complete tested Python wheel assets and installation notes to GitHub + releases. +- [x] Provide a Python-native codegen CLI wheel using maturin binary bindings. +- [x] Add clean, isolated wheel consumers that import/call stock WinRT and run + codegen with Cargo/Rust unavailable. ## P1: Python-native behavior @@ -126,8 +136,17 @@ of a dynamic projection. for parity and still exposes its raw ABI shape. - [x] Keep protected composable constructors out of generated Python `__init__` overloads. -- [ ] Hide or explicitly mark constructors for all system-returned classes. -- [ ] Add composition/aggregation support required by XAML runtime classes. +- [x] Make WinMD activation/composition metadata the constructor boundary: + system-returned and protected-composition classes retain native wrapping + but reject public construction and expose no constructible `.pyi` overload. +- [x] Add a reusable outer/inner aggregation host for public composable Python + subclasses, preserving controlling COM identity and inner ownership. +- [x] Add metadata-driven local overridable-interface vtables for public + composable subclasses, including native-invoked FrameworkElement + measure/arrange/template callbacks and fail-closed ABI validation. +- [x] Register arbitrary Python runtime-class names and compose them into the + XAML metadata-provider chain so custom types can be instantiated by name + from XAML markup. - [ ] Make Windows App SDK initialization idempotent and version-aware. - [ ] Auto-discover or explicitly provision the bootstrap DLL. - [x] Expose the selected framework `resources.pri` path. @@ -139,7 +158,14 @@ of a dynamic projection. - [x] Validate worker-thread and `asyncio` scheduling while the WinUI DispatcherQueue owns the UI thread, including a WinRT async completion and `try_enqueue` back to the UI thread. -- [ ] Load Fluent Light, Dark, and High Contrast resources. +- [x] Add projected lifetime scopes that release UI/COM wrappers before + apartment teardown. +- [x] Add awaitable DispatcherQueue result/error/priority scheduling helpers. +- [x] Project `IObservableVector` as a mutable Python sequence with typed + `VectorChanged` events. +- [x] Add a GIL-safe Python `IElementFactory` bridge and live ItemsRepeater + get/recycle identity coverage. +- [x] Load and validate Fluent Light, Dark, and High Contrast resources. - [x] Add a real Python WinUI application E2E on x64. - [ ] Add Python WinUI application E2E coverage on ARM64. @@ -174,6 +200,7 @@ of a dynamic projection. 19. [x] Balance COM initialization with `RoApartment` and add deterministic `IClosable` cleanup. 20. [x] Make reference returns null-safe without lying in generated annotations. 21. [x] Preserve `UInt32` / `UInt64` values across the Python boundary. +22. [x] Project and box `IReference` struct fields, including struct-valued `T`. 22. [x] Add typed event arguments while preserving token subscriptions and adding idempotent unsubscribe helpers. 23. [x] Project public composable constructors and reject protected composition. diff --git a/README.md b/README.md index 516ee180..0206fb8d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,8 @@ common-interface test matrix, unsupported native types, and ownership rules. Generated bindings project unambiguous public WinRT activation metadata as JavaScript constructors, including overloads such as `new Uri(base, relative)`. Existing static factory methods remain available. Classes that can only be returned by -the system, or that expose only protected composition, remain non-constructible. +the system, or that expose only protected composition, remain non-constructible; +Python stubs do not advertise their internal native-value wrapping path. Bindings also include async + progress support, generic collections (`IVector`, `IMap`), structs, enums, and delegates — see `tools/dynwinrt-codegen/npm/README.md` for the full feature list. @@ -110,7 +111,7 @@ dynwinrt/ ├── crates/dynwinrt/ # Core Rust runtime (FFI, metadata, async, delegates, collections) ├── bindings/ │ ├── js/ # @microsoft/dynwinrt — JS / TS bindings (napi-rs) -│ └── py/ # Python bindings (PyO3, experimental — not published) +│ └── py/ # Python bindings (PyO3; release workflow ready) ├── tools/ │ └── dynwinrt-codegen/ # @microsoft/dynwinrt-codegen — typed-binding generator ├── tests/ # Integration tests + sample E2E projects @@ -135,6 +136,11 @@ cargo build -p dynwinrt-codegen --release cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --class-name Uri --output ./generated ``` +Python runtime wheels target CPython 3.11–3.14 on Windows x64 and ARM64. The +standalone `dynwinrt-codegen` Python wheel targets CPython 3.8–3.14 and needs no +Rust installation at consumption time. Release and trusted-publishing +instructions are in [`bindings/py/README.md`](bindings/py/README.md). + Python runtime, codegen, packaging, and WinUI readiness are tracked in [`PYTHON_CHECKLIST.md`](PYTHON_CHECKLIST.md). diff --git a/TODO.md b/TODO.md index b9de7df1..db9508c6 100644 --- a/TODO.md +++ b/TODO.md @@ -8,6 +8,12 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy ## P1 — Correctness / quality (near-term) +- [ ] **Complete the first native Python ARM64 release-matrix run**. The + fail-closed wheel workflow targets the existing + `[self-hosted, Windows, ARM64, winui]` runner for CPython 3.11–3.14, but this + worktree can validate only x64. Do not mark ARM64 wheels releasable until all + native consumer jobs have imported them and called `Windows.Foundation.Uri`. + - [ ] **Panic-free COM entrypoints**. Several `extern "system"` COM callbacks still `unwrap()` on raw pointer inputs, which is UB across the FFI boundary if a caller passes a bad pointer: - `crates/dynwinrt/src/delegate.rs:309` — `IUnknown::from_raw_borrowed(&raw).unwrap()` inside `marshal_abi_ptr` (fires whenever WinRT passes a null pointer arg to a delegate; not just malicious callers) - `crates/dynwinrt/src/com_helpers.rs:42, 53` — same pattern in `com_to_usize` / `com_usize_addref_out` @@ -30,9 +36,15 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy - [ ] **Codegen: `extract_iid` silently zero-fills malformed GuidAttribute**. `tools/dynwinrt-codegen/src/meta.rs:1030-1051` — if any GuidAttribute field is the wrong integer width, helpers return `0`, producing a plausible-but-wrong IID that will corrupt interface registration without any error. Treat non-matching shapes as a hard error / empty IID. -- [ ] **Codegen: generic ancestors are dropped from projected classes**. `tools/dynwinrt-codegen/src/meta.rs:717-760` — the inherited-interface flattening skips any ancestor whose `TypeName` has generics, so classes inheriting a generic interface via a base class lose those members. Resolve generic ancestors to concrete instantiations (or document + guard the gap). +- [x] **Codegen: project concrete generic ancestor interfaces**. Inherited generic + interfaces are resolved with their concrete arguments, deduplicated by full + instantiated identity, and covered with `ColorPaletteResources` inheriting + `IMap` from `ResourceDictionary`. -- [ ] **Codegen: composable `.ctor` on instance interfaces**. Runtime classes whose instance interface exposes a bare `.ctor(IInspectable* base, IInspectable** inner)` (the COM aggregation pattern used by XAML) still fall through the generic instance-method path. Confirmed unaffected outside `Microsoft.UI.Xaml.*`. Minimal fix: skip `method.name == ".ctor"` in `codegen/method.rs` + TS/Py generators; the `add_method(".ctor", ...)` vtable entry can stay so parameterized IID computation is unaffected. Full fix requires composition/aggregation support — out of scope until we take on XAML hosting. +- [x] **Named Python XAML custom types**. Process-local registrations are chained + into the composed `IXamlMetadataProvider`; `XamlReader` activates generated + Python control subclasses by arbitrary qualified names and preserves native + overrides/identity. OS activation remains deliberately outside this boundary. - [ ] **Codegen: default-interface lookup returns first hit**. `tools/dynwinrt-codegen/src/meta.rs:1075-1090` — `find_default_interface_iid` returns on the first `DefaultAttribute` it resolves, which may not be the actual default in edge cases with malformed metadata. Validate against parsed default interface metadata or fail loudly. @@ -56,7 +68,14 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy - [ ] **Nullable / `IReference` handling**. Null COM pointers surface as `WinRTValue::Null`; codegen wrappers should surface `T | null` in `.d.ts` for these return positions. -- [ ] **`IReference` as struct field**. `napi` has `getObject`/`setObject` and codegen has a fallback path, but this is exercised only by `Windows.Web.Http.HttpProgress` in Windows.winmd and untested. Add coverage. +- [x] **Python `IReference` as struct field**. Generated structs read native + `T | None`, accept native values and legacy wrappers, and box through + `DynWinRTStruct.set_object`; covered by SDK `HttpProgress` and synthetic + `IReference`. +- [x] **JS `IReference` as struct field**. Generated structs read native + `T | null`, accept native values, `null`, and legacy wrappers, and box + through `DynWinRtStruct.setObject`; covered by SDK `HttpProgress`, + synthetic `IReference`, and a runtime object-field round trip. - [ ] **Guid array / bool array fast paths**. Currently per-element via `.toValues().map(...)`. Add `toGuidVec()` / `toBoolVec()` if any real workload hits these. @@ -82,8 +101,8 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy collections, structs, typed delegates/events, nullable references, and an experimental WinUI Application bootstrap. Remaining work is tracked in `PYTHON_CHECKLIST.md`, especially generated package layout, CPython/architecture - coverage, DispatcherQueue/GIL integration, general XAML aggregation, object - identity, and delegates with more than two ABI parameters. + coverage, native XAML custom-control registration/overrides, object identity, + and delegates with more than two ABI parameters. - [ ] **Troubleshooting docs in READMEs**. Common failure modes not covered end-to-end: `WINAPPSDK_BOOTSTRAP_DLL_PATH` not set, mismatched apartment, missing capability. Root `README.md` has a small table; grow it based on the last three GitHub issues that repeated. @@ -132,6 +151,9 @@ Kept for reference; git history is the source of truth. Grouped by area. - [x] Python `.pyi` type stubs and `py.typed` marker by default with `--lang py` ### Distribution / CI +- [x] Python runtime wheel matrix for CPython 3.11–3.14 on x64/native ARM64, + standalone `py3-none-win_` codegen wheels, isolated artifact consumers, + GitHub release assets, and manual OIDC trusted-publishing gates - [x] npm prebuilds for `win32-x64-msvc` + `win32-arm64-msvc` - [x] `.github/workflows/build.yml` builds winrt-meta and dynwinrt-js on x64 + arm64, plus publishing and sample generation - [x] `winapp init --add-js-bindings` toolchain integration diff --git a/bindings/js/README.md b/bindings/js/README.md index 59e22783..75f9c6ef 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -62,6 +62,8 @@ methods remain available for compatibility. Generated `IReference` values use `T | null` in JavaScript. Native values, `null`, and generated `IReference_*` wrappers are accepted as inputs. +The same projection applies when `IReference` appears inside a WinRT struct; +packing boxes the field automatically and unpacking returns the native value. Generated packages export `createProjectedLifetimeScope()`. WinUI/XAML hosts can create a scope after Application and Window setup, then dispose it before diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index fbb7a73f..6d6f92b1 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -10,6 +10,7 @@ import { fileURLToPath } from 'node:url' import { DynWinRtArray, DynWinRtMethodSig, + DynWinRtStruct, DynWinRtType, DynWinRtValue, WinGuid, @@ -374,6 +375,19 @@ if (missingWinuiFixtures.length > 0) { test('round-trip WinRT values', (t) => { t.is(DynWinRtValue.i32(42).toNumber(), 42) + t.is(DynWinRtValue.i64(-42n).toI64Bigint(), -42n) + t.is(DynWinRtValue.u64(2n ** 63n).toU64Bigint(), 2n ** 63n) + t.is(DynWinRtValue.u64(42).toI64(), 42) + t.throws(() => DynWinRtValue.u64(-1), { + message: /non-negative safe integer/, + }) + t.throws(() => DynWinRtValue.i64(1.5), { message: /safe integer/ }) + t.throws(() => DynWinRtValue.u64(Number.POSITIVE_INFINITY), { + message: /safe integer/, + }) + t.throws(() => DynWinRtValue.u64(Number.MAX_SAFE_INTEGER + 1), { + message: /use bigint/, + }) t.is(DynWinRtValue.hstring('hello').toString(), 'hello') t.true(DynWinRtValue.nullValue().isNull()) }) @@ -391,6 +405,34 @@ test('box IReference values', (t) => { t.true(DynWinRtValue.boxReference(DynWinRtValue.nullValue(), valueType).isNull()) }) +test('round-trip IReference struct fields', (t) => { + roInitialize(1) + const valueType = DynWinRtType.u64() + const referenceType = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [valueType]) + const reference = DynWinRtType.registerInterface('IReference_UInt64_Struct_Test', referenceType.iid()).addMethod( + 'get_Value', + new DynWinRtMethodSig().addOut(valueType), + ) + const holderType = DynWinRtType.structType('DynWinRT.Tests.OptionalUInt64Holder', [referenceType]) + const holder = DynWinRtStruct.create(holderType) + + holder.setObject(0, DynWinRtValue.boxReference(DynWinRtValue.u64(17n), valueType)) + t.is(reference.method(6).invoke(holder.getObject(0), []).toU64Bigint(), 17n) + + const incompatible = DynWinRtValue.activationFactory('Windows.Foundation.Uri') + t.throws(() => holder.setObject(0, incompatible), { + message: /80004002|No such interface/i, + }) + incompatible.release() + t.is(reference.method(6).invoke(holder.getObject(0), []).toU64Bigint(), 17n) + + holder.setObject(0, DynWinRtValue.nullValue()) + t.true(holder.getObject(0).isNull()) + t.throws(() => holder.setObject(0, DynWinRtValue.u64(17n)), { + message: /WinRT object or null/, + }) +}) + test('release WinRT object values deterministically', (t) => { const value = DynWinRtValue.activationFactory('Windows.Foundation.Uri') value.release() @@ -415,10 +457,7 @@ test('create empty vectors for large struct element types', (t) => { DynWinRtType.i32(), ]) const vector = DynWinRtValue.createVector([], rectType) - const vectorIid = DynWinRtType.parameterized( - WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), - [rectType], - ).iid() + const vectorIid = DynWinRtType.parameterized(WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), [rectType]).iid() t.notThrows(() => vector.cast(vectorIid)) }) diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 0ab45e88..f05c759d 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -11,11 +11,11 @@ use std::{ }; use dynwinrt; -use napi::bindgen_prelude::{BigInt, PromiseRaw}; -use napi::threadsafe_function::ThreadsafeFunctionCallMode; use napi::Env; +use napi::bindgen_prelude::{BigInt, Either, PromiseRaw}; +use napi::threadsafe_function::ThreadsafeFunctionCallMode; use napi_derive::napi; -use windows::core::{IUnknown, Interface, HSTRING}; +use windows::core::{HSTRING, IUnknown, Interface}; mod com; pub use com::{DynCom, DynComInterface, DynComMethodHandle, DynComMethodSig, DynComType}; @@ -105,7 +105,7 @@ pub fn get_winappsdk_resource_pri_path() -> napi::Result { #[napi] pub fn ro_initialize(apartment_type: Option) { use windows::Win32::System::WinRT::{ - RoInitialize, RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, + RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, RoInitialize, }; let init_type = match apartment_type.unwrap_or(1) { 0 => RO_INIT_SINGLETHREADED, @@ -729,12 +729,53 @@ impl DynWinRTValue { DynWinRTValue::new(dynwinrt::WinRTValue::U32(value)) } #[napi] - pub fn i64(value: i64) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::I64(value)) + pub fn i64(value: Either) -> napi::Result { + let value = match value { + Either::A(value) => { + let (value, lossless) = value.get_i64(); + if !lossless { + return Err(napi::Error::from_reason( + "i64 value must fit in a signed 64-bit integer", + )); + } + value + } + Either::B(value) => { + if !value.is_finite() || value.fract() != 0.0 || value.abs() > 9_007_199_254_740_991.0 { + return Err(napi::Error::from_reason( + "i64 number value must be a safe integer; use bigint for larger values", + )); + } + value as i64 + } + }; + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I64(value))) } #[napi] - pub fn u64(value: i64) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::U64(value as u64)) + pub fn u64(value: Either) -> napi::Result { + let value = match value { + Either::A(value) => { + let (negative, value, lossless) = value.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "u64 value must fit in an unsigned 64-bit integer", + )); + } + value + } + Either::B(value) => { + if !value.is_finite() + || value.fract() != 0.0 + || !(0.0..=9_007_199_254_740_991.0).contains(&value) + { + return Err(napi::Error::from_reason( + "u64 number value must be a non-negative safe integer; use bigint for larger values", + )); + } + value as u64 + } + }; + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U64(value))) } #[napi] pub fn f32(value: f64) -> DynWinRTValue { @@ -969,6 +1010,26 @@ impl DynWinRTValue { } } + #[napi] + pub fn to_i64_bigint(&self) -> napi::Result { + match &self.0 { + dynwinrt::WinRTValue::I64(value) => Ok(BigInt::from(*value)), + _ => Err(napi::Error::from_reason( + "toI64Bigint requires a signed 64-bit value", + )), + } + } + + #[napi] + pub fn to_u64_bigint(&self) -> napi::Result { + match &self.0 { + dynwinrt::WinRTValue::U64(value) => Ok(BigInt::from(*value)), + _ => Err(napi::Error::from_reason( + "toU64Bigint requires an unsigned 64-bit value", + )), + } + } + #[napi] pub fn to_f64(&self) -> f64 { match &self.0 { @@ -1470,40 +1531,30 @@ impl DynWinRTStruct { #[napi] pub fn get_object(&self, index: u32) -> napi::Result { - let inner = self.0.get_field_struct(index as usize); - let raw = unsafe { *(inner.as_ptr() as *const *mut std::ffi::c_void) }; - if raw.is_null() { - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)) - } else { - let obj = unsafe { IUnknown::from_raw_borrowed(&raw) } - .ok_or_else(|| napi::Error::from_reason("null COM pointer"))? - .clone(); - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Object(obj))) + match self + .0 + .get_field_object(index as usize) + .map_err(|error| napi::Error::from_reason(error.message()))? + { + Some(object) => Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Object(object))), + None => Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)), } } #[napi] - pub fn set_object(&mut self, index: u32, value: &DynWinRTValue) { + pub fn set_object(&mut self, index: u32, value: &DynWinRTValue) -> napi::Result<()> { match &value.0 { - dynwinrt::WinRTValue::Object(obj) => { - let field_handle = self.0.type_handle().field_type(index as usize); - let mut field_val = field_handle.default_value(); - unsafe { - // Clone the object (AddRef) and write the raw pointer - let cloned = obj.clone(); - let raw = cloned.into_raw(); - (field_val.as_mut_ptr() as *mut *mut std::ffi::c_void).write(raw); - } - // set_field_struct duplicates non-blittable fields, so field_val's COM pointer - // will be cloned (AddRef) into parent. Let field_val drop to release the original. - self.0.set_field_struct(index as usize, &field_val); - } - dynwinrt::WinRTValue::Null => { - let field_handle = self.0.type_handle().field_type(index as usize); - let field_val = field_handle.default_value(); - self.0.set_field_struct(index as usize, &field_val); - } - _ => {} + dynwinrt::WinRTValue::Object(obj) => self + .0 + .set_field_object(index as usize, Some(obj)) + .map_err(|error| napi::Error::from_reason(error.message())), + dynwinrt::WinRTValue::Null => self + .0 + .set_field_object(index as usize, None) + .map_err(|error| napi::Error::from_reason(error.message())), + _ => Err(napi::Error::from_reason( + "setObject requires a WinRT object or null value", + )), } } @@ -1531,8 +1582,8 @@ pub fn has_package_identity() -> bool { pub fn get_computer_name() -> napi::Result { #[cfg(target_os = "windows")] { - use windows::core::PWSTR; use windows::Win32::System::WindowsProgramming::GetComputerNameW; + use windows::core::PWSTR; let mut buffer = [0u16; 256]; let mut size = buffer.len() as u32; @@ -1735,8 +1786,8 @@ impl DynWinRtDelegate { #[napi(ts_arg_type = "(...args: DynWinRTValue[]) => void")] callback: napi::bindgen_prelude::Function<'static, Vec, ()>, ) -> napi::Result { - use napi::bindgen_prelude::ToNapiValue; use napi::JsValue; + use napi::bindgen_prelude::ToNapiValue; use windows::Win32::System::Threading::GetCurrentThreadId; // Track the thread we were registered on. WinRT delegate callbacks that @@ -1955,8 +2006,8 @@ impl DynWinRtElementFactory { #[napi(ts_arg_type = "(args: DynWinRtValue) => void")] recycle_element: ElementFactoryRecycleFunction, ) -> napi::Result { - use napi::bindgen_prelude::{FromNapiValue, ToNapiValue}; use napi::JsValue; + use napi::bindgen_prelude::{FromNapiValue, ToNapiValue}; use windows::Win32::System::Threading::GetCurrentThreadId; const E_FAIL: windows::core::HRESULT = windows::core::HRESULT(0x80004005u32 as i32); diff --git a/bindings/py/README.md b/bindings/py/README.md index be9b28b8..7142fe6a 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -1,7 +1,24 @@ # dynwinrt-py +`dynwinrt-py` 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. -Develop +Install the runtime and the standalone generator from an approved feed or a +downloaded release: + +```powershell +python -m pip install dynwinrt-py dynwinrt-codegen +dynwinrt-codegen generate --namespace Windows.Foundation --class-name Uri ` + --lang py --output generated_uri +``` + +Generated Python package manifests pin `dynwinrt-py` to exactly the version of +`dynwinrt-codegen` that emitted them. + +## Develop Run `uv run maturin develop` to build the package @@ -11,6 +28,35 @@ 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 +`python-v*` tags on the repository's existing +`[self-hosted, Windows, ARM64, winui]` runner. This avoids executing untrusted +pull-request code on a self-hosted machine. A release remains blocked rather +than producing ARM64 artifacts if that runner or one of its native CPython +versions is unavailable. + +To release: + +1. Set the same version in `bindings\py\Cargo.toml` and + `tools\dynwinrt-codegen\Cargo.toml`, update `Cargo.lock`, and merge it. +2. Create `python-v` (for example, `python-v0.1.0`). The workflow + rejects mismatched or malformed tags and attaches only the complete tested + wheel set to the GitHub release. A hyphenated version is marked prerelease. +3. Configure the protected `pypi` GitHub environment with required reviewers + and PyPI trusted publishers for both projects. To publish, manually dispatch + the workflow **from that existing tag** with `publish_pypi` enabled and + `release_version` set. OIDC trusted publishing is used; no API token is + stored in the repository. + +Do not enable publication from a branch, pull request, or ordinary push. + Generated `IReference` values are projected as `T | None`; native values, `None`, and generated `IReference_*` wrappers are accepted as inputs. @@ -68,7 +114,12 @@ unsubscribe function. `once_*` subscribes for at most one callback invocation. WinRT flags enums are projected as `enum.IntFlag`. Overloaded methods share one Python name with runtime type/arity dispatch and `typing.overload` declarations. Activatable runtime classes use normal constructors, for example -`Uri("https://example.com")`; native return values use an internal wrapper path. +`Uri("https://example.com")`. Constructor overloads come only from WinMD +`ActivatableAttribute` and public `ComposableAttribute` declarations. Classes +without that metadata, including system-returned classes and protected-only +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. ## COM apartments and cleanup @@ -98,15 +149,91 @@ provider and controls resources, codegen also emits The latter installs `XamlControlsResources` and configures unpackaged resource resolution when the required metadata is available. -This is a bootstrap slice, not general WinUI support. Arbitrary -composition/aggregation, custom controls, and ARM64 UI validation remain tracked in -[`PYTHON_CHECKLIST.md`](../../PYTHON_CHECKLIST.md). +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: + +```python +class PythonPanel(StackPanel): + def measure_override(self, available_size): + return available_size + +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. +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. 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. +Use a projected lifetime scope inside the COM apartment so generated wrappers +release their native values before `RoUninitialize`: + +```python +from dynwinrt_py import RoApartment, projected_lifetime_scope + +with RoApartment(0), projected_lifetime_scope(): + app = Application.create() + # 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. + The live x64 smoke test accepts explicit WinAppSDK metadata and bootstrap inputs: diff --git a/bindings/py/dynwinrt_py.pyi b/bindings/py/dynwinrt_py.pyi index ad36e302..379d146d 100644 --- a/bindings/py/dynwinrt_py.pyi +++ b/bindings/py/dynwinrt_py.pyi @@ -1,7 +1,8 @@ -from typing import Awaitable, Callable, List, Optional, Protocol, Sequence, TypeVar, Union, final +from typing import Awaitable, Callable, List, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final _T = TypeVar("_T", covariant=True) _P = TypeVar("_P", covariant=True) +_Tracked = TypeVar("_Tracked") __all__ = [ "WinAppSDKContext", @@ -10,15 +11,22 @@ __all__ = [ "DynWinRTType", "DynWinRTMethodSig", "DynWinRTMethodHandle", + "DynWinRTOverrideInterface", + "DynWinRTXamlRegistration", "DynWinRTValue", "DynWinRTArray", "DynWinRTStruct", "DynWinRtDelegate", + "DynWinRtElementFactory", "WinRTAsync", "WinRTAsyncWithProgress", + "ProjectedLifetimeScope", + "projected_lifetime_scope", + "release_projected", "init_winappsdk", "ro_initialize", "ro_uninitialize", + "register_xaml_runtime_class", "has_package_identity", "get_winappsdk_resource_pri_path", "get_computer_name", @@ -41,6 +49,48 @@ class RoApartment: def close(self) -> None: ... def __repr__(self) -> str: ... +@final +class DynWinRTXamlRegistration: + @property + def name(self) -> Optional[str]: ... + @property + def active(self) -> bool: ... + @property + def supported_overrides(self) -> List[str]: ... + def unregister(self) -> bool: ... + def release_instances(self) -> int: ... + def close(self) -> bool: ... + def __enter__(self) -> DynWinRTXamlRegistration: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> bool: ... + +def register_xaml_runtime_class( + runtime_class_name: str, + base_type_name: str, + base_iid: WinGUID, + constructor: Callable[[], object], + supported_overrides: Optional[Sequence[str]] = ..., +) -> DynWinRTXamlRegistration: ... + + +@final +class ProjectedLifetimeScope: + @property + def disposed(self) -> bool: ... + def __enter__(self) -> ProjectedLifetimeScope: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> bool: ... + def track( + self, value: _Tracked, type_name: Optional[str] = ... + ) -> _Tracked: ... + def close(self) -> None: ... + + +def projected_lifetime_scope() -> ProjectedLifetimeScope: ... +def release_projected(value: object) -> None: ... + @final class WinGUID: @@ -135,6 +185,16 @@ class DynWinRTMethodSig: def add_out_fill(self, typ: DynWinRTType) -> DynWinRTMethodSig: ... +@final +class DynWinRTOverrideInterface: + def __new__( + cls, + iid: WinGUID, + abi_shapes: Sequence[str], + callbacks: Mapping[int, Callable[..., object]], + ) -> DynWinRTOverrideInterface: ... + + @final class DynWinRTMethodHandle: def invoke( @@ -146,6 +206,25 @@ class DynWinRTMethodHandle: def invoke_all( self, obj: DynWinRTValue, args: Sequence[DynWinRTValue] ) -> List[DynWinRTValue]: ... + def invoke_composed( + self, + factory: DynWinRTValue, + args: Sequence[DynWinRTValue], + outer_index: int, + inner_output_index: int, + instance_output_index: int, + agile: bool, + ) -> DynWinRTValue: ... + def invoke_composed_with_overrides( + self, + factory: DynWinRTValue, + args: Sequence[DynWinRTValue], + outer_index: int, + inner_output_index: int, + instance_output_index: int, + agile: bool, + override_interfaces: Sequence[DynWinRTOverrideInterface], + ) -> DynWinRTValue: ... def get_string(self, obj: DynWinRTValue) -> str: ... def get_i32(self, obj: DynWinRTValue) -> int: ... def get_bool(self, obj: DynWinRTValue) -> bool: ... @@ -224,7 +303,9 @@ class DynWinRTValue: def to_f64(self) -> float: ... def to_guid(self) -> WinGUID: ... def is_null(self) -> bool: ... + def release(self) -> None: ... def as_raw(self) -> int: ... + def identity_raw(self) -> int: ... def cast(self, iid: WinGUID) -> DynWinRTValue: ... def activate(self) -> DynWinRTValue: ... def call_0( @@ -254,6 +335,7 @@ class DynWinRTValue: class WinRTAsync(Awaitable[_T], Protocol[_T]): def wait(self) -> _T: ... def cancel(self) -> None: ... + def release(self) -> None: ... class WinRTAsyncWithProgress(WinRTAsync[_T], Protocol[_T, _P]): @@ -358,6 +440,19 @@ class DynWinRtDelegate: callback: Callable[..., object], ) -> DynWinRtDelegate: ... def to_value(self) -> DynWinRTValue: ... + + +@final +class DynWinRtElementFactory: + @staticmethod + def create( + element_iid: WinGUID, + get_element: Callable[[DynWinRTValue], DynWinRTValue], + recycle_element: Callable[[DynWinRTValue], object], + ) -> DynWinRtElementFactory: ... + def to_value(self) -> DynWinRTValue: ... + def release_callbacks(self) -> None: ... + def release(self) -> None: ... def __repr__(self) -> str: ... diff --git a/bindings/py/pyproject.toml b/bindings/py/pyproject.toml index 491afaff..ec519c12 100644 --- a/bindings/py/pyproject.toml +++ b/bindings/py/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "maturin" [project] name = "dynwinrt-py" description = "Python bindings for dynamic WinRT API invocation" -requires-python = ">=3.8" +requires-python = ">=3.11,<3.15" license = {text = "MIT"} authors = [ {name = "Microsoft"}, @@ -13,7 +13,10 @@ authors = [ classifiers = [ "Programming Language :: Rust", "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "License :: OSI Approved :: MIT License", "Operating System :: Microsoft :: Windows", ] diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index a93a3a0d..a131e7d6 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -140,6 +140,21 @@ impl AsyncOperation { .map_err(|_| PyRuntimeError::new_err("async operation state lock was poisoned")) } + fn release(&self, py: Python<'_>) -> PyResult<()> { + let _ = self.cancel(); + let future = { + let mut state = self.lock_state()?; + match std::mem::replace(&mut *state, ExecutionState::Idle) { + ExecutionState::Future(future) => Some(future), + ExecutionState::Idle | ExecutionState::Blocking => None, + } + }; + if let Some(future) = future { + future.call_method0(py, "cancel")?; + } + Ok(()) + } + fn future<'py>(&self, py: Python<'py>) -> PyResult> { let mut state = self.lock_state()?; match &*state { @@ -222,7 +237,15 @@ impl AsyncOperation { #[pyclass(name = "_DynWinRTAsync")] pub struct DynWinRTAsync { - operation: Arc, + operation: Option>, +} + +impl DynWinRTAsync { + fn operation(&self) -> PyResult<&Arc> { + self.operation + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("the WinRT async operation has been released")) + } } #[pymethods] @@ -230,20 +253,28 @@ impl DynWinRTAsync { #[new] fn new(value: &DynWinRTValue, result_converter: Py) -> PyResult { Ok(Self { - operation: Arc::new(AsyncOperation::new(value, result_converter)?), + operation: Some(Arc::new(AsyncOperation::new(value, result_converter)?)), }) } fn __await__<'py>(&self, py: Python<'py>) -> PyResult> { - self.operation.await_iter(py) + self.operation()?.await_iter(py) } fn wait(&self, py: Python<'_>) -> PyResult> { - self.operation.wait(py) + self.operation()?.wait(py) } fn cancel(&self) -> PyResult<()> { - self.operation.cancel() + self.operation()?.cancel() + } + + fn release(&mut self, py: Python<'_>) -> PyResult<()> { + if let Some(operation) = &self.operation { + operation.release(py)?; + } + self.operation = None; + Ok(()) } fn __repr__(&self) -> &'static str { @@ -253,10 +284,18 @@ impl DynWinRTAsync { #[pyclass(name = "_DynWinRTAsyncWithProgress")] pub struct DynWinRTAsyncWithProgress { - operation: Arc, + operation: Option>, progress_converter: Py, } +impl DynWinRTAsyncWithProgress { + fn operation(&self) -> PyResult<&Arc> { + self.operation + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("the WinRT async operation has been released")) + } +} + #[pymethods] impl DynWinRTAsyncWithProgress { #[new] @@ -276,21 +315,29 @@ impl DynWinRTAsyncWithProgress { )); } Ok(Self { - operation, + operation: Some(operation), progress_converter, }) } fn __await__<'py>(&self, py: Python<'py>) -> PyResult> { - self.operation.await_iter(py) + self.operation()?.await_iter(py) } fn wait(&self, py: Python<'_>) -> PyResult> { - self.operation.wait(py) + self.operation()?.wait(py) } fn cancel(&self) -> PyResult<()> { - self.operation.cancel() + self.operation()?.cancel() + } + + fn release(&mut self, py: Python<'_>) -> PyResult<()> { + if let Some(operation) = &self.operation { + operation.release(py)?; + } + self.operation = None; + Ok(()) } fn progress(&self, py: Python<'_>, callback: Py) -> PyResult<()> { @@ -302,7 +349,8 @@ impl DynWinRTAsyncWithProgress { })? .unbind(); - let info = match &self.operation.value { + let operation = self.operation()?; + let info = match &operation.value { dynwinrt::WinRTValue::Async(info) => info, _ => { return Err(PyRuntimeError::new_err( @@ -327,15 +375,23 @@ impl DynWinRTAsyncWithProgress { .import("dynwinrt_py.dynwinrt_py")? .getattr("_dynwinrt_dispatch_progress")? .unbind(); + let callback_context = py + .import("contextvars")? + .getattr("copy_context")? + .call0()? + .unbind(); let progress_callback: dynwinrt::ProgressCallback = Box::new(move |value| { Python::attach(|py| { let result = (|| -> PyResult<()> { let raw = Py::new(py, DynWinRTValue(value))?; + let context = callback_context.call_method0(py, "copy")?; + let context_run = context.getattr(py, "run")?; loop_.call_method1( py, "call_soon_threadsafe", ( + context_run, dispatch_progress.clone_ref(py), callback.clone_ref(py), converter.clone_ref(py), diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index f7a31e68..1deace6c 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -26,6 +26,7 @@ from collections.abc import ( Sequence as _Sequence, ) from datetime import datetime as _datetime, timedelta as _timedelta, timezone as _timezone +from contextvars import ContextVar as _ContextVar from operator import index as _index from typing import Protocol as _Protocol, TypeVar as _TypeVar from typing import Awaitable as _Awaitable, Callable as _Callable @@ -38,10 +39,129 @@ _WINRT_EPOCH = _datetime(1601, 1, 1, tzinfo=_timezone.utc) class WinRTAsync(_Awaitable[_T], _Protocol[_T]): def wait(self) -> _T: ... def cancel(self) -> None: ... + def release(self) -> None: ... class WinRTAsyncWithProgress(WinRTAsync[_T], _Protocol[_T, _P]): def progress(self, callback: _Callable[[_P], object]) -> None: ... +_active_projected_lifetime_scope = _ContextVar( + 'dynwinrt_active_projected_lifetime_scope', + default=None, +) + +def _dynwinrt_projected_native_values(value): + native_values = [] + seen = set() + for attribute in ( + '_obj', + '_collection_obj', + '_observable_obj', + '_element_factory_implementation', + ): + native = getattr(value, attribute, None) + if native is None or id(native) in seen: + continue + if callable(getattr(native, 'release', None)): + seen.add(id(native)) + native_values.append(native) + if not native_values and callable(getattr(value, 'release', None)): + native_values.append(value) + return native_values + +class ProjectedLifetimeScope: + def __init__(self): + self._registry = {} + self._token = None + self._active = False + self._disposed = False + self._retry_pending = False + + @property + def disposed(self): + return self._disposed + + def __enter__(self): + if self._disposed: + raise RuntimeError('Cannot enter a disposed projection lifetime scope.') + if self._active: + raise RuntimeError('The projection lifetime scope is already active.') + self._token = _active_projected_lifetime_scope.set(self) + self._active = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + try: + self.close() + except BaseException as cleanup_error: + if exc_value is not None: + _dynwinrt_append_exception_cause(exc_value, cleanup_error) + raise exc_value.with_traceback(traceback) + raise + return False + + def track(self, value, type_name=None): + if not self._active or self._disposed: + raise RuntimeError('Cannot track values in an inactive projection lifetime scope.') + for native in _dynwinrt_projected_native_values(value): + self._registry.setdefault(id(native), (native, type_name)) + return value + + def close(self): + if self._disposed: + return + if not self._active: + if not self._retry_pending: + raise RuntimeError('Cannot close a projection lifetime scope before entering it.') + elif _active_projected_lifetime_scope.get() is not self: + raise RuntimeError('Projection lifetime scopes must be closed in LIFO order.') + else: + _active_projected_lifetime_scope.reset(self._token) + self._token = None + self._active = False + + first_error = None + for key, (native, _) in reversed(list(self._registry.items())): + try: + native.release() + del self._registry[key] + except BaseException as error: + if first_error is None: + first_error = error + if first_error is not None: + self._retry_pending = True + raise first_error + + self._token = None + self._active = False + self._retry_pending = False + self._disposed = True + +def _dynwinrt_append_exception_cause(error, cleanup_error): + current = error + seen = set() + while current.__cause__ is not None and id(current) not in seen: + seen.add(id(current)) + current = current.__cause__ + if id(current) not in seen and current is not cleanup_error: + current.__cause__ = cleanup_error + current.__suppress_context__ = True + +def projected_lifetime_scope(): + return ProjectedLifetimeScope() + +def _dynwinrt_track_projected(value, type_name=None): + scope = _active_projected_lifetime_scope.get() + if scope is not None and scope._active and not scope._disposed: + scope.track(value, type_name) + return value + +def release_projected(value): + native_values = _dynwinrt_projected_native_values(value) + if not native_values: + raise TypeError('release_projected requires a generated projected wrapper.') + for native in reversed(native_values): + native.release() + def _dynwinrt_guid(value): if isinstance(value, WinGUID): return value @@ -89,6 +209,9 @@ def _dynwinrt_vector(value, wrap, element_type): return raw return DynWinRTValue.create_vector([wrap(item) for item in raw], element_type) +def _dynwinrt_new_vector(value, wrap, element_type): + return DynWinRTValue.create_vector([wrap(item) for item in value], element_type) + def _dynwinrt_map(value, wrap_key, wrap_value, key_type, value_type): raw = getattr(value, '_obj', value) if isinstance(raw, DynWinRTValue): @@ -244,10 +367,13 @@ def _dynwinrt_dispatch_progress(callback, converter, value): m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -255,6 +381,10 @@ def _dynwinrt_dispatch_progress(callback, converter, value): m.add_function(wrap_pyfunction!(super::runtime::init_winappsdk, m)?)?; m.add_function(wrap_pyfunction!(super::runtime::ro_initialize, m)?)?; m.add_function(wrap_pyfunction!(super::runtime::ro_uninitialize, m)?)?; + m.add_function(wrap_pyfunction!( + super::runtime::register_xaml_runtime_class, + m + )?)?; m.add_function(wrap_pyfunction!(super::runtime::has_package_identity, m)?)?; m.add_function(wrap_pyfunction!( super::runtime::get_winappsdk_resource_pri_path, @@ -265,7 +395,13 @@ def _dynwinrt_dispatch_progress(callback, converter, value): m.py().run( c" __all__ = [name for name in __all__ if not name.startswith('_')] -for _name in ('WinRTAsync', 'WinRTAsyncWithProgress'): +for _name in ( + 'WinRTAsync', + 'WinRTAsyncWithProgress', + 'ProjectedLifetimeScope', + 'projected_lifetime_scope', + 'release_projected', +): if _name not in __all__: __all__.append(_name) ", diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 8c0d5393..8e8f58eb 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use dynwinrt; -use pyo3::exceptions::PyRuntimeError; +use pyo3::exceptions::{PyRuntimeError, PyTypeError}; use pyo3::prelude::*; +use pyo3::types::PyDict; use windows::core::{GUID, HSTRING, IUnknown, Interface}; use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_windows_error}; @@ -131,6 +132,169 @@ pub fn ro_uninitialize() { unsafe { RoUninitialize() }; } +// ====================================================================== +// Process-local named XAML runtime classes +// ====================================================================== + +#[pyclass] +pub struct DynWinRTXamlRegistration { + registration: Option, + instances: Arc>>>, +} + +static XAML_INSTANCE_ROOTS: std::sync::LazyLock>>>>>> = + std::sync::LazyLock::new(|| Mutex::new(Vec::new())); + +#[pymethods] +impl DynWinRTXamlRegistration { + #[getter] + fn name(&self) -> Option { + self.registration + .as_ref() + .map(|registration| registration.name().to_string()) + } + + #[getter] + fn active(&self) -> bool { + self.registration.is_some() + } + + #[getter] + fn supported_overrides(&self) -> Vec { + self.registration + .as_ref() + .map(|registration| registration.supported_overrides().to_vec()) + .unwrap_or_default() + } + + fn unregister(&mut self) -> bool { + self.registration + .take() + .is_some_and(|registration| registration.unregister()) + } + + fn release_instances(&self) -> PyResult { + let instances = { + let mut instances = self.instances.lock().map_err(|_| { + PyRuntimeError::new_err("registered XAML instance state is poisoned") + })?; + std::mem::take(&mut *instances) + }; + let count = instances.len(); + drop(instances); + Ok(count) + } + + fn close(&mut self) -> bool { + self.unregister() + } + + fn __enter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { + slf + } + + fn __exit__( + &mut self, + _exc_type: &Bound<'_, PyAny>, + _exc_value: &Bound<'_, PyAny>, + _traceback: &Bound<'_, PyAny>, + ) -> bool { + self.unregister(); + false + } +} + +/// Register a Python constructor with the process-local XAML metadata provider. +/// +/// The registration is only visible to `Application.create()` / +/// `create_xaml_application`; it never changes machine or package activation +/// metadata. The callback is apartment-bound to the registering thread. +#[pyfunction] +#[pyo3(signature = (runtime_class_name, base_type_name, base_iid, constructor, supported_overrides=None))] +pub fn register_xaml_runtime_class( + py: Python<'_>, + runtime_class_name: String, + base_type_name: String, + base_iid: &WinGUID, + constructor: Py, + supported_overrides: Option>, +) -> PyResult { + if !constructor.bind(py).is_callable() { + return Err(PyRuntimeError::new_err( + "register_xaml_runtime_class: constructor must be callable", + )); + } + let context = py + .import("contextvars")? + .call_method0("copy_context")? + .unbind(); + let callback = constructor.clone_ref(py); + let callback_for_error = constructor.clone_ref(py); + let thread_id = std::thread::current().id(); + let instances = Arc::new(Mutex::new(Vec::new())); + XAML_INSTANCE_ROOTS + .lock() + .map_err(|_| PyRuntimeError::new_err("registered XAML root state is poisoned"))? + .push(instances.clone()); + let active_instances = instances.clone(); + let activator: dynwinrt::XamlRuntimeClassActivator = Arc::new(move || { + if std::thread::current().id() != thread_id { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT( + 0x8001010Eu32 as i32, + ))); + } + Python::attach(|py| { + let result = (|| -> PyResult { + let invocation_context = context.call_method0(py, "copy")?; + let instance = invocation_context.call_method1(py, "run", (callback.bind(py),))?; + let native = match instance.getattr(py, "_obj") { + Ok(native) => native, + Err(error) + if error.is_instance_of::(py) => + { + instance.clone_ref(py) + } + Err(error) => return Err(error), + }; + let value = native.extract::>(py)?; + let object = value.0.as_object().ok_or_else(|| { + PyRuntimeError::new_err( + "registered XAML constructor must return an object with a DynWinRTValue '_obj'", + ) + })?; + active_instances + .lock() + .map_err(|_| { + PyRuntimeError::new_err("registered XAML instance state is poisoned") + })? + .push(instance); + Ok(object) + })(); + match result { + Ok(instance) => Ok(instance), + Err(error) => { + error.write_unraisable(py, Some(callback_for_error.bind(py))); + Err(windows::core::Error::from_hresult( + PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION, + )) + } + } + }) + }); + let registration = dynwinrt::register_xaml_runtime_class( + &runtime_class_name, + &base_type_name, + base_iid.0, + supported_overrides.unwrap_or_default(), + activator, + ) + .map_err(map_windows_error)?; + Ok(DynWinRTXamlRegistration { + registration: Some(registration), + instances, + }) +} + // ====================================================================== // WinGUID // ====================================================================== @@ -397,6 +561,173 @@ impl DynWinRTMethodSig { #[pyclass] pub struct DynWinRTMethodHandle(dynwinrt::MethodHandle); +#[pyclass] +pub struct DynWinRTOverrideInterface { + iid: GUID, + methods: Vec, + callbacks: Vec<(usize, Py)>, + context: Py, + thread_id: std::thread::ThreadId, +} + +impl DynWinRTOverrideInterface { + fn to_core(&self, py: Python<'_>) -> PyResult { + let mut interface = dynwinrt::LocalOverrideInterface::new(self.iid, self.methods.clone()) + .map_err(map_windows_error)?; + for (vtable_index, callback) in &self.callbacks { + let callback = callback.clone_ref(py); + let context = self.context.clone_ref(py); + let thread_id = self.thread_id; + let method_index = vtable_index - 6; + match self.methods[method_index] { + dynwinrt::LocalOverrideAbi::Void0 => { + let callback = Arc::new(move || { + if std::thread::current().id() != thread_id { + return windows::core::HRESULT(0x8001010Eu32 as i32); + } + Python::attach(|py| { + let result = (|| -> PyResult<()> { + let invocation_context = context.call_method0(py, "copy")?; + invocation_context.call_method1(py, "run", (callback.bind(py),))?; + Ok(()) + })(); + match result { + Ok(()) => windows::core::HRESULT(0), + Err(error) => { + error.write_unraisable(py, Some(callback.bind(py))); + PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION + } + } + }) + }); + interface = interface + .with_void_callback(*vtable_index, callback) + .map_err(map_windows_error)?; + } + dynwinrt::LocalOverrideAbi::SizeF32ToSizeF32 => { + let callback = Arc::new( + move |width: f32, + height: f32, + result_width: &mut f32, + result_height: &mut f32| { + if std::thread::current().id() != thread_id { + return windows::core::HRESULT(0x8001010Eu32 as i32); + } + Python::attach(|py| { + let result = (|| -> PyResult<(f32, f32)> { + let invocation_context = context.call_method0(py, "copy")?; + let result = invocation_context.call_method1( + py, + "run", + (callback.bind(py), (width, height)), + )?; + if let Ok(size) = result.extract::<(f32, f32)>(py) { + return Ok(size); + } + let bound = result.bind(py); + Ok(( + bound.getattr("width")?.extract()?, + bound.getattr("height")?.extract()?, + )) + })(); + match result { + Ok((width, height)) => { + *result_width = width; + *result_height = height; + windows::core::HRESULT(0) + } + Err(error) => { + error.write_unraisable(py, Some(callback.bind(py))); + PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION + } + } + }) + }, + ); + interface = interface + .with_size_callback(*vtable_index, callback) + .map_err(map_windows_error)?; + } + dynwinrt::LocalOverrideAbi::HStringBoolToBool => { + unreachable!("constructor rejects callbacks for unsupported ABI shapes") + } + } + } + Ok(interface) + } +} + +#[pymethods] +impl DynWinRTOverrideInterface { + #[new] + fn new( + py: Python<'_>, + iid: &WinGUID, + abi_shapes: Vec, + callbacks: &Bound<'_, PyDict>, + ) -> PyResult { + let methods = abi_shapes + .iter() + .enumerate() + .map(|(index, shape)| match shape.as_str() { + "void0" => Ok(dynwinrt::LocalOverrideAbi::Void0), + "size_f32_to_size_f32" => Ok(dynwinrt::LocalOverrideAbi::SizeF32ToSizeF32), + "hstring_bool_to_bool" => Ok(dynwinrt::LocalOverrideAbi::HStringBoolToBool), + _ => Err(PyRuntimeError::new_err(format!( + "unsupported native override ABI shape '{shape}' at vtable index {}", + index + 6 + ))), + }) + .collect::>>()?; + if methods.is_empty() { + return Err(PyRuntimeError::new_err( + "native override interface must contain at least one method", + )); + } + + let mut captured = Vec::with_capacity(callbacks.len()); + for (key, value) in callbacks.iter() { + let vtable_index = key.extract::().map_err(|_| { + PyRuntimeError::new_err("native override callback keys must be vtable indexes") + })?; + let Some(method_index) = vtable_index.checked_sub(6) else { + return Err(PyRuntimeError::new_err(format!( + "native override vtable index {vtable_index} is below IInspectable slot 6" + ))); + }; + if !matches!( + methods.get(method_index), + Some( + dynwinrt::LocalOverrideAbi::Void0 + | dynwinrt::LocalOverrideAbi::SizeF32ToSizeF32 + ) + ) { + return Err(PyRuntimeError::new_err(format!( + "native override callback at vtable index {vtable_index} has an unsupported ABI shape" + ))); + } + if !value.is_callable() { + return Err(PyRuntimeError::new_err(format!( + "native override callback at vtable index {vtable_index} is not callable" + ))); + } + captured.push((vtable_index, value.unbind())); + } + captured.sort_by_key(|(index, _)| *index); + let context = py + .import("contextvars")? + .call_method0("copy_context")? + .unbind(); + Ok(Self { + iid: iid.0, + methods, + callbacks: captured, + context, + thread_id: std::thread::current().id(), + }) + } +} + #[pymethods] impl DynWinRTMethodHandle { /// Invoke this method on a COM object. @@ -491,6 +822,84 @@ impl DynWinRTMethodHandle { Ok(results.into_iter().map(DynWinRTValue).collect()) } + /// Invoke a WinRT composable factory with a runtime-provided outer host. + fn invoke_composed( + &self, + factory: &DynWinRTValue, + args: Vec, + outer_index: usize, + inner_output_index: usize, + instance_output_index: usize, + agile: bool, + ) -> PyResult { + let factory = factory.0.as_object().ok_or_else(|| { + PyRuntimeError::new_err("invoke_composed() requires an Object factory") + })?; + let args = args + .into_iter() + .map(|argument| argument.0) + .collect::>(); + dynwinrt::compose_winrt( + &factory, + &self.0, + &args, + outer_index, + inner_output_index, + instance_output_index, + agile, + ) + .map(DynWinRTValue) + .map_err(map_dynwinrt_error) + } + + /// Invoke a composable factory with metadata-described local overrides. + #[allow(clippy::too_many_arguments)] + fn invoke_composed_with_overrides( + &self, + py: Python<'_>, + factory: &DynWinRTValue, + args: Vec, + outer_index: usize, + inner_output_index: usize, + instance_output_index: usize, + agile: bool, + override_interfaces: Vec>, + ) -> PyResult { + if override_interfaces.is_empty() { + return self.invoke_composed( + factory, + args, + outer_index, + inner_output_index, + instance_output_index, + agile, + ); + } + let factory = factory.0.as_object().ok_or_else(|| { + PyRuntimeError::new_err("invoke_composed_with_overrides() requires an Object factory") + })?; + let args = args + .into_iter() + .map(|argument| argument.0) + .collect::>(); + let overrides = override_interfaces + .iter() + .map(|interface| interface.to_core(py)) + .collect::>>()?; + dynwinrt::compose_winrt_with_overrides( + &factory, + &self.0, + &args, + outer_index, + inner_output_index, + instance_output_index, + agile, + overrides, + ) + .map(DynWinRTValue) + .map_err(map_dynwinrt_error) + } + // --- Fast paths: skip Vec alloc for common getter patterns --- /// Getter → string (0 args, zero Vec allocation) @@ -774,7 +1183,7 @@ impl DynWinRTValue { } /// Register a progress callback on an async-with-progress operation. - fn on_progress(&self, callback: Py) -> PyResult<()> { + fn on_progress(&self, py: Python<'_>, callback: Py) -> PyResult<()> { let async_info = match &self.0 { dynwinrt::WinRTValue::Async(a) => a, _ => return Err(PyRuntimeError::new_err("on_progress: not an async value")), @@ -788,12 +1197,18 @@ impl DynWinRTValue { let handler_iid = async_info.progress_handler_iid().ok_or_else(|| { PyRuntimeError::new_err("on_progress: cannot compute progress handler IID") })?; + let callback_context = py + .import("contextvars")? + .getattr("copy_context")? + .call0()? + .unbind(); let progress_cb: dynwinrt::ProgressCallback = Box::new(move |val: dynwinrt::WinRTValue| { Python::attach(|py| { let result = (|| -> PyResult<()> { let py_val = Py::new(py, DynWinRTValue(val))?; - callback.call1(py, (py_val,))?; + let context = callback_context.call_method0(py, "copy")?; + context.call_method1(py, "run", (callback.clone_ref(py), py_val))?; Ok(()) })(); if let Err(error) = result { @@ -935,6 +1350,15 @@ impl DynWinRTValue { self.0.is_null_object() } + /// Release resources owned by this value and replace it with Null. + /// + /// This is idempotent so projected lifetime scopes can safely retry + /// cleanup without double-releasing COM references. + fn release(&mut self) { + let value = std::mem::replace(&mut self.0, dynwinrt::WinRTValue::Null); + drop(value); + } + fn as_raw(&self) -> PyResult { match &self.0 { dynwinrt::WinRTValue::Object(o) => Ok(o.as_raw() as i64), @@ -944,6 +1368,18 @@ impl DynWinRTValue { } } + fn identity_raw(&self) -> PyResult { + match &self.0 { + dynwinrt::WinRTValue::Object(object) => object + .cast::() + .map(|identity| identity.as_raw() as i64) + .map_err(map_windows_error), + _ => Err(PyRuntimeError::new_err( + "Cannot get COM identity from a non-object value", + )), + } + } + /// COM QueryInterface — cast to a different interface. fn cast(&self, iid: &WinGUID) -> PyResult { self.0 @@ -1461,36 +1897,25 @@ impl DynWinRTStruct { } fn get_object(&self, index: usize) -> PyResult { - let inner = self.0.get_field_struct(index); - let raw = unsafe { *(inner.as_ptr() as *const *mut std::ffi::c_void) }; - if raw.is_null() { - Ok(DynWinRTValue(dynwinrt::WinRTValue::Null)) - } else { - let obj = unsafe { IUnknown::from_raw_borrowed(&raw) } - .ok_or_else(|| PyRuntimeError::new_err("null COM pointer"))? - .clone(); - Ok(DynWinRTValue(dynwinrt::WinRTValue::Object(obj))) + match self.0.get_field_object(index).map_err(map_dynwinrt_error)? { + Some(object) => Ok(DynWinRTValue(dynwinrt::WinRTValue::Object(object))), + None => Ok(DynWinRTValue(dynwinrt::WinRTValue::Null)), } } - fn set_object(&mut self, index: usize, value: &DynWinRTValue) { + fn set_object(&mut self, index: usize, value: &DynWinRTValue) -> PyResult<()> { match &value.0 { - dynwinrt::WinRTValue::Object(obj) => { - let field_handle = self.0.type_handle().field_type(index); - let mut field_val = field_handle.default_value(); - unsafe { - let cloned = obj.clone(); - let raw = cloned.into_raw(); - (field_val.as_mut_ptr() as *mut *mut std::ffi::c_void).write(raw); - } - self.0.set_field_struct(index, &field_val); - } - dynwinrt::WinRTValue::Null => { - let field_handle = self.0.type_handle().field_type(index); - let field_val = field_handle.default_value(); - self.0.set_field_struct(index, &field_val); - } - _ => {} + dynwinrt::WinRTValue::Object(obj) => self + .0 + .set_field_object(index, Some(obj)) + .map_err(map_dynwinrt_error), + dynwinrt::WinRTValue::Null => self + .0 + .set_field_object(index, None) + .map_err(map_dynwinrt_error), + _ => Err(PyTypeError::new_err( + "set_object requires a WinRT object or null value", + )), } } @@ -1577,6 +2002,155 @@ impl DynWinRtDelegate { } } +// ====================================================================== +// DynWinRtElementFactory — synchronous WinUI IElementFactory binding +// ====================================================================== + +struct ElementFactoryCallbacks { + get_element: Option>, + recycle_element: Option>, + context: Option>, +} + +#[pyclass] +pub struct DynWinRtElementFactory { + value: dynwinrt::WinRTValue, + callbacks: Arc>, +} + +impl DynWinRtElementFactory { + fn clear_callbacks(&self) -> PyResult<()> { + let released = { + let mut callbacks = self.callbacks.lock().map_err(|_| { + PyRuntimeError::new_err("IElementFactory callback state is poisoned") + })?; + ( + callbacks.get_element.take(), + callbacks.recycle_element.take(), + callbacks.context.take(), + ) + }; + drop(released); + Ok(()) + } +} + +#[pymethods] +impl DynWinRtElementFactory { + #[staticmethod] + fn create( + py: Python<'_>, + element_iid: &WinGUID, + get_element: Py, + recycle_element: Py, + ) -> PyResult { + const E_FAIL: windows::core::HRESULT = windows::core::HRESULT(0x80004005_u32 as i32); + const RO_E_CLOSED: windows::core::HRESULT = windows::core::HRESULT(0x80000013_u32 as i32); + + let element_iid = element_iid.0; + let context = py + .import("contextvars")? + .getattr("copy_context")? + .call0()? + .unbind(); + let callbacks = Arc::new(Mutex::new(ElementFactoryCallbacks { + get_element: Some(get_element), + recycle_element: Some(recycle_element), + context: Some(context), + })); + + let get_callbacks = callbacks.clone(); + let get_callback: dynwinrt::ElementFactoryGetCallback = Box::new(move |args| { + Python::attach(|py| { + let (callback, context) = { + let callbacks = get_callbacks.lock().map_err(|_| E_FAIL)?; + let callback = callbacks + .get_element + .as_ref() + .ok_or(RO_E_CLOSED)? + .clone_ref(py); + let context = callbacks.context.as_ref().ok_or(RO_E_CLOSED)?.clone_ref(py); + (callback, context) + }; + let result = (|| -> PyResult { + let argument = Py::new(py, DynWinRTValue(args.clone()))?; + let context = context.call_method0(py, "copy")?; + let result = context + .bind(py) + .call_method1("run", (callback.clone_ref(py), argument))?; + let value = result.extract::>()?; + value.0.cast(&element_iid).map_err(map_dynwinrt_error) + })(); + match result { + Ok(value) => Ok(value), + Err(error) => { + error.write_unraisable(py, Some(callback.bind(py))); + Err(E_FAIL) + } + } + }) + }); + + let recycle_callbacks = callbacks.clone(); + let recycle_callback: dynwinrt::ElementFactoryRecycleCallback = Box::new(move |args| { + Python::attach(|py| { + let (callback, context) = { + let callbacks = match recycle_callbacks.lock() { + Ok(callbacks) => callbacks, + Err(_) => return E_FAIL, + }; + let Some(callback) = callbacks.recycle_element.as_ref() else { + return RO_E_CLOSED; + }; + let Some(context) = callbacks.context.as_ref() else { + return RO_E_CLOSED; + }; + (callback.clone_ref(py), context.clone_ref(py)) + }; + let result = (|| -> PyResult<()> { + let argument = Py::new(py, DynWinRTValue(args.clone()))?; + let context = context.call_method0(py, "copy")?; + context + .bind(py) + .call_method1("run", (callback.clone_ref(py), argument))?; + Ok(()) + })(); + match result { + Ok(()) => windows::core::HRESULT(0), + Err(error) => { + error.write_unraisable(py, Some(callback.bind(py))); + E_FAIL + } + } + }) + }); + + Ok(Self { + value: dynwinrt::create_element_factory_value(get_callback, recycle_callback), + callbacks, + }) + } + + fn to_value(&self) -> DynWinRTValue { + DynWinRTValue(self.value.clone()) + } + + fn release_callbacks(&self) -> PyResult<()> { + self.clear_callbacks() + } + + fn release(&mut self) -> PyResult<()> { + self.clear_callbacks()?; + let value = std::mem::replace(&mut self.value, dynwinrt::WinRTValue::Null); + drop(value); + Ok(()) + } + + fn __repr__(&self) -> &'static str { + "DynWinRtElementFactory(...)" + } +} + // ====================================================================== // System info utilities // ====================================================================== diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index b2797ed7..cff3e023 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -13,8 +13,12 @@ """ import asyncio +from contextvars import copy_context from datetime import datetime, timedelta, timezone +import gc import threading +import weakref +from types import SimpleNamespace import pytest @@ -22,18 +26,27 @@ from dynwinrt_py import ( DynWinRTType, DynWinRTMethodSig, + DynWinRTOverrideInterface, + DynWinRTXamlRegistration, DynWinRTValue, DynWinRTArray, + DynWinRtDelegate, + DynWinRtElementFactory, RoApartment, + projected_lifetime_scope, + release_projected, WinRTAsync, WinRTAsyncWithProgress, WinGUID, ro_initialize, + register_xaml_runtime_class, ) from dynwinrt_py.dynwinrt_py import ( _DynWinRTAsync, _DynWinRTAsyncWithProgress, _dynwinrt_datetime_to_ticks, + _dynwinrt_new_vector, + _dynwinrt_track_projected, _dynwinrt_ticks_to_datetime, _dynwinrt_ticks_to_timedelta, _dynwinrt_timedelta_to_ticks, @@ -46,6 +59,7 @@ IID_IURI = "9E365E57-48B2-4160-956F-C7385120BBFC" IID_ISTORAGE_FILE = "FA3F6186-4214-428C-A64C-14C9AC7315EA" IID_ISTORAGE_FILE_STATICS = "5984C710-DAF2-43C8-8BB4-A4D3EACFD03F" +IID_IINSPECTABLE = WinGUID.parse("AF86E2E0-B12D-4C6A-9C5A-D7AA65101E90") def _setup_module(): @@ -208,6 +222,282 @@ def test_progress_wrapper_rejects_non_async_value(): ) +def test_observable_vector_reports_mutations_and_unsubscribes(): + observable_piid = WinGUID.parse("5917EB53-50B4-4A0D-B309-65862B3F1DBC") + vector_piid = WinGUID.parse("913337E9-11A1-4345-A3A2-4E7F956E222D") + handler_piid = WinGUID.parse("0C051752-9FBF-4C70-AA0C-0E4C82D9A761") + event_args_iid = WinGUID.parse("575933DF-34FE-4480-AF15-07691F3D5D9B") + element_type = DynWinRTType.hstring() + observable_type = DynWinRTType.parameterized( + observable_piid, [element_type] + ) + vector_type = DynWinRTType.parameterized(vector_piid, [element_type]) + handler_type = DynWinRTType.parameterized(handler_piid, [element_type]) + event_args_type = DynWinRTType.interface(event_args_iid) + + observable_interface = DynWinRTType.register_interface( + "IObservableVector_HString_Test", + observable_type.iid(), + ) + observable_interface.add_method( + "add_VectorChanged", + DynWinRTMethodSig() + .add_in(handler_type) + .add_out(DynWinRTType.i64_type()), + ) + observable_interface.add_method( + "remove_VectorChanged", + DynWinRTMethodSig().add_in(DynWinRTType.i64_type()), + ) + + vector_interface = DynWinRTType.register_interface( + "IVector_HString_Test", + vector_type.iid(), + ) + for index in range(7): + vector_interface.add_method( + f"unused_{index}", + DynWinRTMethodSig(), + ) + vector_interface.add_method( + "Append", + DynWinRTMethodSig().add_in(element_type), + ) + + event_args_interface = DynWinRTType.register_interface( + "IVectorChangedEventArgs_Test", + event_args_iid, + ) + event_args_interface.add_method( + "get_CollectionChange", + DynWinRTMethodSig().add_out(DynWinRTType.i32_type()), + ) + event_args_interface.add_method( + "get_Index", + DynWinRTMethodSig().add_out(DynWinRTType.u32_type()), + ) + + notifications = [] + + def changed(_sender, args): + event_args = args.cast(event_args_iid) + change = event_args_interface.method(6).invoke(event_args, []).to_number() + index = event_args_interface.method(7).invoke(event_args, []).to_u32() + notifications.append((change, index)) + + with RoApartment(1): + vector_value = DynWinRTValue.create_vector( + [DynWinRTValue.from_hstring("first")], + element_type, + ) + observable_value = vector_value.cast(observable_type.iid()) + mutable_value = vector_value.cast(vector_type.iid()) + delegate = DynWinRtDelegate.create( + handler_type.iid(), + [observable_type, event_args_type], + changed, + ) + token = observable_interface.method(6).invoke( + observable_value, + [delegate.to_value()], + ) + + vector_interface.method(13).invoke( + mutable_value, + [DynWinRTValue.from_hstring("second")], + ) + assert notifications == [(1, 1)] + + observable_interface.method(7).invoke(observable_value, [token]) + vector_interface.method(13).invoke( + mutable_value, + [DynWinRTValue.from_hstring("third")], + ) + assert notifications == [(1, 1)] + + mutable_value.release() + observable_value.release() + vector_value.release() + del delegate + + +def test_new_vector_copies_projected_iterables_for_observable_use(): + class ProjectedIterable: + def __init__(self, native): + self._obj = native + + def __iter__(self): + return iter(["first", "second"]) + + element_type = DynWinRTType.hstring() + source = DynWinRTValue.create_vector( + [DynWinRTValue.from_hstring("source")], + element_type, + ) + copied = _dynwinrt_new_vector( + ProjectedIterable(source), + DynWinRTValue.from_hstring, + element_type, + ) + observable_iid = DynWinRTType.parameterized( + WinGUID.parse("5917EB53-50B4-4A0D-B309-65862B3F1DBC"), + [element_type], + ).iid() + observable = copied.cast(observable_iid) + assert not observable.is_null() + observable.release() + copied.release() + source.release() + + +def test_com_identity_and_element_factory_callback_release(): + element_factory_iid = WinGUID.parse( + "75FABA47-2CF2-54AE-91E6-0581556FDDAA" + ) + uri_iid = WinGUID.parse(IID_IURI) + + with RoApartment(1): + factory = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + uri_factory = factory.cast(WinGUID.parse(IID_IURI_FACTORY)) + assert factory.identity_raw() == uri_factory.identity_raw() + + implementation = DynWinRtElementFactory.create( + uri_iid, + lambda value: value, + lambda _value: None, + ) + value = implementation.to_value() + projected = value.cast(element_factory_iid) + assert value.identity_raw() == projected.identity_raw() + + implementation.release_callbacks() + implementation.release_callbacks() + implementation.release() + projected.release() + value.release() + uri_factory.release() + 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"): + DynWinRTOverrideInterface(iid, ["object_to_object"], {}) + with pytest.raises(RuntimeError, match="unsupported ABI shape"): + DynWinRTOverrideInterface( + iid, + ["hstring_bool_to_bool"], + {6: lambda: False}, + ) + with pytest.raises(RuntimeError, match="not callable"): + DynWinRTOverrideInterface(iid, ["void0"], {6: object()}) + + +def test_native_override_interface_accepts_metadata_supported_framework_shapes(): + interface = DynWinRTOverrideInterface( + WinGUID.parse("FFC6FD98-F38C-5904-9CE4-97A3427CF4BA"), + [ + "size_f32_to_size_f32", + "size_f32_to_size_f32", + "void0", + "hstring_bool_to_bool", + ], + { + 6: lambda size: size, + 8: lambda: None, + }, + ) + assert interface is not None + + +def test_named_xaml_registration_validates_duplicates_and_unregisters(): + class Constructor: + def __call__(self): + raise AssertionError("metadata lookup must not invoke the constructor") + + callback = Constructor() + callback_ref = weakref.ref(callback) + registration = register_xaml_runtime_class( + "DynWinRT.Tests.UnitControl", + "Microsoft.UI.Xaml.Controls.Control", + IID_IINSPECTABLE, + callback, + ["measure_override"], + ) + assert isinstance(registration, DynWinRTXamlRegistration) + assert registration.active + assert registration.name == "DynWinRT.Tests.UnitControl" + assert registration.supported_overrides == ["measure_override"] + + with pytest.raises(OSError): + register_xaml_runtime_class( + "DynWinRT.Tests.UnitControl", + "Microsoft.UI.Xaml.Controls.Control", + IID_IINSPECTABLE, + lambda: None, + ) + del callback + gc.collect() + assert callback_ref() is not None + assert registration.unregister() + assert not registration.active + assert registration.name is None + assert not registration.unregister() + gc.collect() + assert callback_ref() is None + + +def test_named_xaml_registration_rejects_unsupported_shapes(): + with pytest.raises(OSError): + register_xaml_runtime_class( + "Unqualified", + "Microsoft.UI.Xaml.Controls.Control", + IID_IINSPECTABLE, + lambda: None, + ) + with pytest.raises(OSError): + register_xaml_runtime_class( + "DynWinRT.Tests.Generic`1", + "Microsoft.UI.Xaml.Controls.Control", + IID_IINSPECTABLE, + lambda: None, + ) + with pytest.raises(OSError): + register_xaml_runtime_class( + "DynWinRT.Tests.DuplicateOverrides", + "Microsoft.UI.Xaml.Controls.Control", + IID_IINSPECTABLE, + lambda: None, + ["measure_override", "measure_override"], + ) + + +def test_element_factory_callback_cleanup_allows_reentrant_destructors(): + holder = {} + destructor_called = [] + + class Callback: + def __call__(self, value): + return value + + def __del__(self): + destructor_called.append(True) + factory = holder.get("factory") + if factory is not None: + factory.release_callbacks() + + implementation = DynWinRtElementFactory.create( + WinGUID.parse(IID_IURI), + Callback(), + lambda _value: None, + ) + holder["factory"] = implementation + implementation.release_callbacks() + gc.collect() + assert destructor_called + implementation.release() + + def test_async_protocols_are_public(): assert WinRTAsync.__name__ == "WinRTAsync" assert WinRTAsyncWithProgress.__name__ == "WinRTAsyncWithProgress" @@ -242,6 +532,205 @@ def worker(): assert not errors +def test_projected_lifetime_scope_releases_native_values_before_apartment_exit(): + with RoApartment(1): + scope = projected_lifetime_scope() + with scope: + first = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + second = first.cast(WinGUID.parse(IID_IURI_FACTORY)) + _dynwinrt_track_projected(SimpleNamespace(_obj=first), "Factory") + _dynwinrt_track_projected(SimpleNamespace(_obj=second), "UriFactory") + assert not first.is_null() + assert not second.is_null() + + assert scope.disposed + assert first.is_null() + assert second.is_null() + + release_projected(SimpleNamespace(_obj=first)) + release_projected(SimpleNamespace(_obj=second)) + + +def test_projected_lifetime_scope_enforces_lifo_order(): + outer = projected_lifetime_scope() + inner = projected_lifetime_scope() + outer.__enter__() + inner.__enter__() + with pytest.raises(RuntimeError, match="LIFO"): + outer.close() + inner.close() + outer.close() + assert inner.disposed + assert outer.disposed + + +def test_projected_lifetime_scope_retries_only_failed_releases(): + class Native: + def __init__(self, failures=0): + self.failures = failures + self.attempts = 0 + + def release(self): + self.attempts += 1 + if self.attempts <= self.failures: + raise RuntimeError("retry release") + + flaky = Native(failures=1) + stable = Native() + scope = projected_lifetime_scope() + with pytest.raises(RuntimeError, match="retry release"): + with scope: + _dynwinrt_track_projected(SimpleNamespace(_obj=flaky), "Flaky") + _dynwinrt_track_projected(SimpleNamespace(_obj=stable), "Stable") + + assert not scope.disposed + assert flaky.attempts == 1 + assert stable.attempts == 1 + + scope.close() + assert scope.disposed + assert flaky.attempts == 2 + assert stable.attempts == 1 + + +def test_nested_scope_release_failure_does_not_mask_original_error(): + class FlakyNative: + def __init__(self): + self.attempts = 0 + + def release(self): + self.attempts += 1 + if self.attempts == 1: + raise RuntimeError("inner release failed") + + flaky = FlakyNative() + outer = projected_lifetime_scope() + inner = projected_lifetime_scope() + with pytest.raises(RuntimeError, match="inner release failed"): + with outer: + with inner: + _dynwinrt_track_projected(SimpleNamespace(_obj=flaky), "Flaky") + + assert outer.disposed + assert not inner.disposed + inner.close() + assert inner.disposed + assert flaky.attempts == 2 + + +def test_closed_scope_in_copied_context_is_ignored(): + native = type( + "Native", + (), + {"release": lambda self: setattr(self, "released", True)}, + )() + native.released = False + + with projected_lifetime_scope(): + inherited_context = copy_context() + + inherited_context.run( + _dynwinrt_track_projected, + SimpleNamespace(_obj=native), + "LateValue", + ) + assert not native.released + + +def test_inherited_context_cannot_close_parent_scope(): + class Native: + def __init__(self): + self.released = False + + def release(self): + self.released = True + + native = Native() + scope = projected_lifetime_scope() + scope.__enter__() + _dynwinrt_track_projected(SimpleNamespace(_obj=native), "Native") + inherited_context = copy_context() + + with pytest.raises(ValueError, match="different Context"): + inherited_context.run(scope.close) + + assert not native.released + assert not scope.disposed + scope.close() + assert native.released + assert scope.disposed + + +def test_nested_cleanup_preserves_the_first_failure(): + class FailingNative: + def __init__(self, message): + self.message = message + self.attempts = 0 + + def release(self): + self.attempts += 1 + if self.attempts == 1: + raise RuntimeError(self.message) + + outer_native = FailingNative("outer cleanup failed") + inner_native = FailingNative("inner cleanup failed") + outer = projected_lifetime_scope() + inner = projected_lifetime_scope() + + with pytest.raises(RuntimeError, match="inner cleanup failed") as exc_info: + with outer: + _dynwinrt_track_projected( + SimpleNamespace(_obj=outer_native), "Outer" + ) + with inner: + _dynwinrt_track_projected( + SimpleNamespace(_obj=inner_native), "Inner" + ) + + assert isinstance(exc_info.value.__cause__, RuntimeError) + assert "outer cleanup failed" in str(exc_info.value.__cause__) + inner.close() + outer.close() + + +def test_body_and_nested_cleanup_failures_are_all_preserved(): + class FailingNative: + def __init__(self, message): + self.message = message + self.attempts = 0 + + def release(self): + self.attempts += 1 + if self.attempts == 1: + raise RuntimeError(self.message) + + outer_native = FailingNative("outer cleanup failed") + inner_native = FailingNative("inner cleanup failed") + outer = projected_lifetime_scope() + inner = projected_lifetime_scope() + + with pytest.raises(ValueError, match="body failed") as exc_info: + with outer: + _dynwinrt_track_projected( + SimpleNamespace(_obj=outer_native), "Outer" + ) + with inner: + _dynwinrt_track_projected( + SimpleNamespace(_obj=inner_native), "Inner" + ) + raise ValueError("body failed") + + inner_error = exc_info.value.__cause__ + assert isinstance(inner_error, RuntimeError) + assert "inner cleanup failed" in str(inner_error) + outer_error = inner_error.__cause__ + assert isinstance(outer_error, RuntimeError) + assert "outer cleanup failed" in str(outer_error) + + inner.close() + outer.close() + + def test_ro_apartment_rejects_changed_mode(): errors = [] diff --git a/crates/dynwinrt/src/composition.rs b/crates/dynwinrt/src/composition.rs new file mode 100644 index 00000000..d31e3916 --- /dev/null +++ b/crates/dynwinrt/src/composition.rs @@ -0,0 +1,1427 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#![allow(unsafe_op_in_unsafe_fn)] + +//! Reusable WinRT outer/inner composition support. +//! +//! A composed outer owns the factory's non-delegating `inner` pointer. Public +//! interfaces are obtained by forwarding QI to that inner, but every forwarded +//! interface must return the outer from QI(IUnknown). This preserves one COM +//! identity and fails closed if a factory does not honor WinRT aggregation. + +use core::ffi::c_void; +use std::collections::HashMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Mutex}; + +use windows::Win32::System::Com::{CoTaskMemAlloc, CoTaskMemFree}; +use windows_core::{GUID, HRESULT, IInspectable, IUnknown, Interface}; + +use crate::com_helpers::{E_FAIL, E_NOINTERFACE, E_POINTER, IInspectableVtbl, S_OK}; +use crate::{MethodHandle, WinRTValue}; + +const E_OUTOFMEMORY: HRESULT = HRESULT(0x8007000Eu32 as i32); +const E_INVALIDARG: HRESULT = HRESULT(0x80070057u32 as i32); +const E_UNEXPECTED: HRESULT = HRESULT(0x8000FFFFu32 as i32); + +/// ABI shapes currently understood by the dynamic local-interface host. +/// +/// A local interface is only constructed when every slot has an exact shape. +/// Python callbacks are currently accepted for `Void0` and +/// `SizeF32ToSizeF32`; other or unimplemented slots forward to the inner object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LocalOverrideAbi { + Void0, + SizeF32ToSizeF32, + HStringBoolToBool, +} + +pub type LocalOverrideVoidCallback = Arc HRESULT + Send + Sync>; +pub type LocalOverrideSizeCallback = + Arc HRESULT + Send + Sync>; + +enum LocalOverrideCallback { + Void(LocalOverrideVoidCallback), + Size(LocalOverrideSizeCallback), +} + +/// Metadata-derived description of one overridable local WinRT interface. +pub struct LocalOverrideInterface { + iid: GUID, + methods: Vec, + callbacks: HashMap, +} + +impl LocalOverrideInterface { + pub fn new(iid: GUID, methods: Vec) -> windows_core::Result { + if methods.is_empty() { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + Ok(Self { + iid, + methods, + callbacks: HashMap::new(), + }) + } + + /// Install a callback by absolute vtable index. + pub fn with_void_callback( + mut self, + vtable_index: usize, + callback: LocalOverrideVoidCallback, + ) -> windows_core::Result { + let Some(method_index) = vtable_index.checked_sub(6) else { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + }; + if self.methods.get(method_index) != Some(&LocalOverrideAbi::Void0) + || self + .callbacks + .insert(method_index, LocalOverrideCallback::Void(callback)) + .is_some() + { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + Ok(self) + } + + pub fn with_size_callback( + mut self, + vtable_index: usize, + callback: LocalOverrideSizeCallback, + ) -> windows_core::Result { + let Some(method_index) = vtable_index.checked_sub(6) else { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + }; + if self.methods.get(method_index) != Some(&LocalOverrideAbi::SizeF32ToSizeF32) + || self + .callbacks + .insert(method_index, LocalOverrideCallback::Size(callback)) + .is_some() + { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + Ok(self) + } +} + +/// Shared identity, refcount, and owned-inner state for composed outer objects. +/// +/// `WeakRefCount` is atomic. The inner pointer is protected because QI and +/// destruction can occur on COM-managed threads. Implementors embedding this +/// state may only claim `Send`/`Sync` when every additional local-interface +/// field and callback is independently thread-safe; the state does not make an +/// apartment-bound WinRT object agile. +pub(crate) struct CompositionState { + ref_count: windows_core::imp::WeakRefCount, + inner: Mutex>, + agile: bool, +} + +impl CompositionState { + pub(crate) fn new(agile: bool) -> Self { + Self { + ref_count: windows_core::imp::WeakRefCount::new(), + inner: Mutex::new(None), + agile, + } + } + + pub(crate) fn add_ref(&self) -> u32 { + self.ref_count.add_ref() + } + + pub(crate) fn release(&self) -> u32 { + self.ref_count.release() + } + + pub(crate) fn set_inner(&self, inner: IUnknown) -> windows_core::Result<()> { + let mut slot = self + .inner + .lock() + .map_err(|_| windows_core::Error::from_hresult(E_FAIL))?; + if slot.is_some() { + return Err(windows_core::Error::from_hresult(E_UNEXPECTED)); + } + *slot = Some(inner); + Ok(()) + } + + fn inner(&self) -> std::result::Result, HRESULT> { + self.inner + .lock() + .map(|inner| inner.clone()) + .map_err(|_| E_FAIL) + } + + unsafe fn inner_interface(&self, iid: &GUID) -> std::result::Result { + let Some(inner) = self.inner()? else { + return Err(E_NOINTERFACE); + }; + let mut result = std::ptr::null_mut(); + let hr = inner.query(iid, &mut result); + if hr.is_err() { + if !result.is_null() { + drop(IUnknown::from_raw(result)); + } + return Err(hr); + } + if result.is_null() { + return Err(E_NOINTERFACE); + } + Ok(IUnknown::from_raw(result)) + } + + /// Resolve local interfaces before forwarding to the aggregated inner. + pub(crate) unsafe fn query_interface( + &self, + identity: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + local: impl FnOnce(&GUID) -> Option<*mut c_void>, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let iid = &*iid; + + if *iid == IUnknown::IID || *iid == IInspectable::IID { + *result = identity; + self.add_ref(); + return S_OK; + } + if self.agile && *iid == windows_core::imp::IAgileObject::IID { + *result = identity; + self.add_ref(); + return S_OK; + } + if self.agile && *iid == windows_core::imp::IMarshal::IID { + self.add_ref(); + return windows_core::imp::marshaler(core::mem::transmute(identity), result); + } + if let Some(local) = local(iid) { + *result = local; + self.add_ref(); + return S_OK; + } + let weak = self.ref_count.query(iid, identity); + if !weak.is_null() { + *result = weak; + return S_OK; + } + + let Some(inner) = (match self.inner() { + Ok(inner) => inner, + Err(error) => return error, + }) else { + return E_NOINTERFACE; + }; + let mut forwarded = std::ptr::null_mut(); + let hr = inner.query(iid, &mut forwarded); + if hr.is_err() { + if !forwarded.is_null() { + drop(IUnknown::from_raw(forwarded)); + } + return hr; + } + if forwarded.is_null() { + return E_NOINTERFACE; + } + + // Aggregated public interfaces must delegate IUnknown to this outer. + let forwarded_owner = IUnknown::from_raw(forwarded); + let mut controlling = std::ptr::null_mut(); + let identity_hr = forwarded_owner.query(&IUnknown::IID, &mut controlling); + if identity_hr.is_err() || controlling != identity { + if !controlling.is_null() { + drop(IUnknown::from_raw(controlling)); + } + return E_NOINTERFACE; + } + drop(IUnknown::from_raw(controlling)); + *result = forwarded_owner.as_raw(); + std::mem::forget(forwarded_owner); + S_OK + } + + pub(crate) unsafe fn get_iids( + &self, + local_iids: &[GUID], + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + if count.is_null() || result.is_null() { + return E_POINTER; + } + *count = 0; + *result = std::ptr::null_mut(); + + let mut inner_count = 0; + let mut inner_iids = std::ptr::null_mut(); + match self.inner() { + Ok(Some(inner)) => { + let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); + let hr = ((*vtable).get_iids)(inner.as_raw(), &mut inner_count, &mut inner_iids); + if hr.is_err() { + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + return hr; + } + if inner_count != 0 && inner_iids.is_null() { + return E_FAIL; + } + } + Ok(None) => {} + Err(error) => return error, + } + + let total = match local_iids.len().checked_add(inner_count as usize) { + Some(total) => total, + None => { + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + return E_OUTOFMEMORY; + } + }; + if total > u32::MAX as usize { + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + return E_OUTOFMEMORY; + } + if total == 0 { + return S_OK; + } + let bytes = match total.checked_mul(std::mem::size_of::()) { + Some(bytes) => bytes, + None => { + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + return E_OUTOFMEMORY; + } + }; + let combined = CoTaskMemAlloc(bytes) as *mut GUID; + if combined.is_null() { + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + return E_OUTOFMEMORY; + } + std::ptr::copy_nonoverlapping(local_iids.as_ptr(), combined, local_iids.len()); + if inner_count != 0 { + std::ptr::copy_nonoverlapping( + inner_iids, + combined.add(local_iids.len()), + inner_count as usize, + ); + } + if !inner_iids.is_null() { + CoTaskMemFree(Some(inner_iids.cast())); + } + *count = total as u32; + *result = combined; + S_OK + } + + pub(crate) unsafe fn get_runtime_class_name(&self, result: *mut *mut c_void) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + match self.inner() { + Ok(Some(inner)) => { + let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); + ((*vtable).get_runtime_class_name)(inner.as_raw(), result) + } + Ok(None) => { + *result = std::ptr::null_mut(); + S_OK + } + Err(error) => error, + } + } + + pub(crate) unsafe fn get_trust_level(&self, result: *mut i32) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + match self.inner() { + Ok(Some(inner)) => { + let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); + ((*vtable).get_trust_level)(inner.as_raw(), result) + } + Ok(None) => { + *result = 0; + S_OK + } + Err(error) => error, + } + } +} + +#[repr(C)] +struct GenericOuter { + vtable: *const IInspectableVtbl, + state: CompositionState, +} + +impl GenericOuter { + const VTABLE: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }; + + fn create(agile: bool) -> IUnknown { + let outer = Box::new(Self { + vtable: &Self::VTABLE, + state: CompositionState::new(agile), + }); + unsafe { IUnknown::from_raw(Box::into_raw(outer).cast()) } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct AbiSize { + width: f32, + height: f32, +} + +#[repr(C)] +struct DynamicLocalInterface { + vtable: *const *const c_void, + owner: *mut DynamicOuter, + interface_index: usize, + _vtable_storage: Box<[*const c_void]>, +} + +#[repr(C)] +struct DynamicOuter { + vtable: *const IInspectableVtbl, + state: CompositionState, + local_interfaces: Vec>, + local_iids: Vec, + callbacks: Vec>>, +} + +// The outer's mutable state is synchronized and callbacks explicitly require +// Send + Sync. Raw pointers only point into the same pinned allocation. +unsafe impl Send for DynamicOuter {} +unsafe impl Sync for DynamicOuter {} + +macro_rules! void_thunk { + ($name:ident, $index:expr) => { + unsafe extern "system" fn $name(this: *mut c_void) -> HRESULT { + DynamicOuter::dispatch_void0(this, $index) + } + }; +} + +macro_rules! size_thunk { + ($name:ident, $index:expr) => { + unsafe extern "system" fn $name( + this: *mut c_void, + value: AbiSize, + result: *mut AbiSize, + ) -> HRESULT { + DynamicOuter::dispatch_size_to_size(this, $index, value, result) + } + }; +} + +macro_rules! string_bool_thunk { + ($name:ident, $index:expr) => { + unsafe extern "system" fn $name( + this: *mut c_void, + value: *mut c_void, + flag: u8, + result: *mut u8, + ) -> HRESULT { + DynamicOuter::dispatch_hstring_bool_to_bool(this, $index, value, flag, result) + } + }; +} + +void_thunk!(void_0, 0); +void_thunk!(void_1, 1); +void_thunk!(void_2, 2); +void_thunk!(void_3, 3); +void_thunk!(void_4, 4); +void_thunk!(void_5, 5); +void_thunk!(void_6, 6); +void_thunk!(void_7, 7); +size_thunk!(size_0, 0); +size_thunk!(size_1, 1); +size_thunk!(size_2, 2); +size_thunk!(size_3, 3); +size_thunk!(size_4, 4); +size_thunk!(size_5, 5); +size_thunk!(size_6, 6); +size_thunk!(size_7, 7); +string_bool_thunk!(string_bool_0, 0); +string_bool_thunk!(string_bool_1, 1); +string_bool_thunk!(string_bool_2, 2); +string_bool_thunk!(string_bool_3, 3); +string_bool_thunk!(string_bool_4, 4); +string_bool_thunk!(string_bool_5, 5); +string_bool_thunk!(string_bool_6, 6); +string_bool_thunk!(string_bool_7, 7); + +const VOID_THUNKS: [unsafe extern "system" fn(*mut c_void) -> HRESULT; 8] = [ + void_0, void_1, void_2, void_3, void_4, void_5, void_6, void_7, +]; +const SIZE_THUNKS: [unsafe extern "system" fn(*mut c_void, AbiSize, *mut AbiSize) -> HRESULT; 8] = [ + size_0, size_1, size_2, size_3, size_4, size_5, size_6, size_7, +]; +const STRING_BOOL_THUNKS: [unsafe extern "system" fn( + *mut c_void, + *mut c_void, + u8, + *mut u8, +) -> HRESULT; 8] = [ + string_bool_0, + string_bool_1, + string_bool_2, + string_bool_3, + string_bool_4, + string_bool_5, + string_bool_6, + string_bool_7, +]; + +impl DynamicOuter { + const VTABLE: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }; + + fn create(agile: bool, specs: Vec) -> windows_core::Result { + if specs.is_empty() { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + let mut local_interfaces = Vec::with_capacity(specs.len()); + let mut local_iids = Vec::with_capacity(specs.len()); + let mut callbacks = Vec::with_capacity(specs.len()); + for spec in specs { + let mut slots = vec![ + Self::local_query_interface as *const () as *const c_void, + Self::local_add_ref as *const () as *const c_void, + Self::local_release as *const () as *const c_void, + Self::local_get_iids as *const () as *const c_void, + Self::local_get_runtime_class_name as *const () as *const c_void, + Self::local_get_trust_level as *const () as *const c_void, + ]; + if spec.methods.len() > VOID_THUNKS.len() { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + for (index, method) in spec.methods.iter().enumerate() { + slots.push(match method { + LocalOverrideAbi::Void0 => VOID_THUNKS[index] as *const () as *const c_void, + LocalOverrideAbi::SizeF32ToSizeF32 => { + SIZE_THUNKS[index] as *const () as *const c_void + } + LocalOverrideAbi::HStringBoolToBool => { + STRING_BOOL_THUNKS[index] as *const () as *const c_void + } + }); + } + let storage = slots.into_boxed_slice(); + let vtable = storage.as_ptr(); + let mut method_callbacks = (0..spec.methods.len()).map(|_| None).collect::>(); + for (index, callback) in spec.callbacks { + method_callbacks[index] = Some(callback); + } + local_iids.push(spec.iid); + callbacks.push(method_callbacks); + local_interfaces.push(Box::new(DynamicLocalInterface { + vtable, + owner: std::ptr::null_mut(), + interface_index: local_interfaces.len(), + _vtable_storage: storage, + })); + } + + let mut outer = Box::new(Self { + vtable: &Self::VTABLE, + state: CompositionState::new(agile), + local_interfaces, + local_iids, + callbacks, + }); + let owner = (&mut *outer) as *mut Self; + for interface in &mut outer.local_interfaces { + interface.owner = owner; + } + Ok(unsafe { IUnknown::from_raw(Box::into_raw(outer).cast()) }) + } +} + +impl DynamicOuter { + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe fn local_from_ptr(this: *mut c_void) -> &'static DynamicLocalInterface { + &*(this as *const DynamicLocalInterface) + } + + unsafe fn owner_from_local(this: *mut c_void) -> &'static Self { + &*Self::local_from_ptr(this).owner + } + + unsafe fn local_ptr(&self, index: usize) -> *mut c_void { + (&*self.local_interfaces[index] as *const DynamicLocalInterface) + .cast_mut() + .cast() + } + + unsafe fn forward_interface( + &self, + interface_index: usize, + ) -> std::result::Result { + self.state + .inner_interface(&self.local_iids[interface_index]) + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + let outer = Self::from_ptr(this); + outer.state.query_interface(this, iid, result, |iid| { + outer + .local_iids + .iter() + .position(|candidate| candidate == iid) + .map(|index| outer.local_ptr(index)) + }) + })) { + Ok(hr) => hr, + Err(_) => { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_FAIL + } + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| Self::from_ptr(this).state.add_ref())).unwrap_or(0) + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + let outer = Self::from_ptr(this); + let remaining = outer.state.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + })) + .unwrap_or(0) + } + + unsafe extern "system" fn get_iids( + this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + let outer = Self::from_ptr(this); + outer.state.get_iids(&outer.local_iids, count, result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn get_runtime_class_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).state.get_runtime_class_name(result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn get_trust_level(this: *mut c_void, result: *mut i32) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).state.get_trust_level(result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn local_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + let local = Self::local_from_ptr(this); + Self::query_interface(local.owner.cast(), iid, result) + })) { + Ok(hr) => hr, + Err(_) => { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_FAIL + } + } + } + + unsafe extern "system" fn local_add_ref(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + Self::owner_from_local(this).state.add_ref() + })) + .unwrap_or(0) + } + + unsafe extern "system" fn local_release(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + let owner = Self::local_from_ptr(this).owner; + Self::release(owner.cast()) + })) + .unwrap_or(0) + } + + unsafe extern "system" fn local_get_iids( + this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + let owner = Self::owner_from_local(this); + owner.state.get_iids(&owner.local_iids, count, result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn local_get_runtime_class_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::owner_from_local(this) + .state + .get_runtime_class_name(result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn local_get_trust_level( + this: *mut c_void, + result: *mut i32, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::owner_from_local(this).state.get_trust_level(result) + })) + .unwrap_or(E_FAIL) + } + + unsafe fn dispatch_void0(this: *mut c_void, method_index: usize) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + let local = Self::local_from_ptr(this); + let owner = &*local.owner; + if let Some(LocalOverrideCallback::Void(callback)) = + owner.callbacks[local.interface_index][method_index].as_ref() + { + return callback(); + } + let Ok(inner) = owner.forward_interface(local.interface_index) else { + return E_NOINTERFACE; + }; + crate::call::call_winrt_method_0(method_index + 6, inner.as_raw()) + })) { + Ok(hr) => hr, + Err(_) => E_FAIL, + } + } + + unsafe fn dispatch_size_to_size( + this: *mut c_void, + method_index: usize, + value: AbiSize, + result: *mut AbiSize, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + if result.is_null() { + return E_POINTER; + } + let local = Self::local_from_ptr(this); + let owner = &*local.owner; + if let Some(LocalOverrideCallback::Size(callback)) = + owner.callbacks[local.interface_index][method_index].as_ref() + { + let mut width = 0.0; + let mut height = 0.0; + let hr = callback(value.width, value.height, &mut width, &mut height); + if hr.is_ok() { + *result = AbiSize { width, height }; + } + return hr; + } + let Ok(inner) = owner.forward_interface(local.interface_index) else { + return E_NOINTERFACE; + }; + let method = crate::call::get_vtable_function_ptr(inner.as_raw(), method_index + 6); + let method: unsafe extern "system" fn(*mut c_void, AbiSize, *mut AbiSize) -> HRESULT = + std::mem::transmute(method); + method(inner.as_raw(), value, result) + })) { + Ok(hr) => hr, + Err(_) => E_FAIL, + } + } + + unsafe fn dispatch_hstring_bool_to_bool( + this: *mut c_void, + method_index: usize, + value: *mut c_void, + flag: u8, + result: *mut u8, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + if result.is_null() { + return E_POINTER; + } + let local = Self::local_from_ptr(this); + let owner = &*local.owner; + let Ok(inner) = owner.forward_interface(local.interface_index) else { + return E_NOINTERFACE; + }; + let method = crate::call::get_vtable_function_ptr(inner.as_raw(), method_index + 6); + let method: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + u8, + *mut u8, + ) -> HRESULT = std::mem::transmute(method); + method(inner.as_raw(), value, flag, result) + })) { + Ok(hr) => hr, + Err(_) => E_FAIL, + } + } +} + +impl GenericOuter { + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this) + .state + .query_interface(this, iid, result, |_| None) + })) { + Ok(hr) => hr, + Err(_) => { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_FAIL + } + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| Self::from_ptr(this).state.add_ref())).unwrap_or(0) + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + let outer = Self::from_ptr(this); + let remaining = outer.state.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + })) + .unwrap_or(0) + } + + unsafe extern "system" fn get_iids( + this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).state.get_iids(&[], count, result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn get_runtime_class_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).state.get_runtime_class_name(result) + })) + .unwrap_or(E_FAIL) + } + + unsafe extern "system" fn get_trust_level(this: *mut c_void, result: *mut i32) -> HRESULT { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).state.get_trust_level(result) + })) + .unwrap_or(E_FAIL) + } +} + +fn validate_nondelegating_inner(inner: &IUnknown, outer: &IUnknown) -> windows_core::Result<()> { + let mut inner_identity = std::ptr::null_mut(); + unsafe { inner.query(&IUnknown::IID, &mut inner_identity) }.ok()?; + if inner_identity.is_null() { + return Err(windows_core::Error::from_hresult(E_NOINTERFACE)); + } + let delegates_to_outer = inner_identity == outer.as_raw(); + unsafe { drop(IUnknown::from_raw(inner_identity)) }; + if delegates_to_outer { + Err(windows_core::Error::from_hresult(E_NOINTERFACE)) + } else { + Ok(()) + } +} + +/// Invoke a WinRT composable factory with a non-null outer and retain its inner. +/// +/// `args` contains only public constructor arguments. `outer_index` identifies +/// where the ABI-only outer belongs. Factory outputs are ordered exactly as +/// `MethodHandle::invoke` returns them (out parameters, then return value). +pub fn compose_winrt( + factory: &IUnknown, + method: &MethodHandle, + args: &[WinRTValue], + outer_index: usize, + inner_output_index: usize, + instance_output_index: usize, + agile: bool, +) -> crate::Result { + compose_winrt_with_outer( + GenericOuter::create(agile), + factory, + method, + args, + outer_index, + inner_output_index, + instance_output_index, + ) +} + +/// Compose using metadata-described local override interfaces. +pub fn compose_winrt_with_overrides( + factory: &IUnknown, + method: &MethodHandle, + args: &[WinRTValue], + outer_index: usize, + inner_output_index: usize, + instance_output_index: usize, + agile: bool, + overrides: Vec, +) -> crate::Result { + let outer = DynamicOuter::create(agile, overrides)?; + compose_winrt_with_outer( + outer, + factory, + method, + args, + outer_index, + inner_output_index, + instance_output_index, + ) +} + +fn compose_winrt_with_outer( + outer: IUnknown, + factory: &IUnknown, + method: &MethodHandle, + args: &[WinRTValue], + outer_index: usize, + inner_output_index: usize, + instance_output_index: usize, +) -> crate::Result { + let mut invoke_args = args.to_vec(); + if outer_index > invoke_args.len() { + return Err(windows_core::Error::from_hresult(E_UNEXPECTED).into()); + } + invoke_args.insert(outer_index, WinRTValue::Object(outer.clone())); + let mut outputs = method.invoke(factory.as_raw(), &invoke_args)?; + if inner_output_index >= outputs.len() + || instance_output_index >= outputs.len() + || inner_output_index == instance_output_index + { + return Err(windows_core::Error::from_hresult(E_UNEXPECTED).into()); + } + + let inner = outputs[inner_output_index] + .as_object() + .ok_or_else(|| windows_core::Error::from_hresult(E_POINTER))?; + let instance = outputs[instance_output_index] + .as_object() + .ok_or_else(|| windows_core::Error::from_hresult(E_POINTER))?; + validate_nondelegating_inner(&inner, &outer)?; + // CompositionState is at the same offset in both pinned outer layouts. + let vtable = unsafe { *(outer.as_raw() as *const *const IInspectableVtbl) }; + if std::ptr::eq(vtable, &GenericOuter::VTABLE) { + unsafe { GenericOuter::from_ptr(outer.as_raw()) } + .state + .set_inner(inner)?; + } else if std::ptr::eq(vtable, &DynamicOuter::VTABLE) { + unsafe { DynamicOuter::from_ptr(outer.as_raw()) } + .state + .set_inner(inner)?; + } else { + return Err(windows_core::Error::from_hresult(E_UNEXPECTED).into()); + } + + let mut controlling = std::ptr::null_mut(); + unsafe { instance.query(&IUnknown::IID, &mut controlling) }.ok()?; + if controlling != outer.as_raw() { + if !controlling.is_null() { + unsafe { drop(IUnknown::from_raw(controlling)) }; + } + return Err(windows_core::Error::from_hresult(E_NOINTERFACE).into()); + } + unsafe { drop(IUnknown::from_raw(controlling)) }; + + // Move the requested output out without cloning; all other factory outputs + // are released normally. + Ok(outputs.swap_remove(instance_output_index)) +} + +#[cfg(test)] +mod tests { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + + use super::*; + + const IID_FORWARDED: GUID = GUID::from_u128(0x11111111_2222_3333_4444_555555555555); + + #[repr(C)] + struct TestInner { + nondelegating_vtable: *const IInspectableVtbl, + forwarded_vtable: *const IInspectableVtbl, + ref_count: windows_core::imp::RefCount, + outer: *mut c_void, + drops: Arc, + } + + impl Drop for TestInner { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + } + } + + impl TestInner { + const NONDELEGATING: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_nondelegating, + AddRef: Self::add_ref_nondelegating, + Release: Self::release_nondelegating, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }; + const FORWARDED: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_forwarded, + AddRef: Self::add_ref_forwarded, + Release: Self::release_forwarded, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }; + + fn create(outer: *mut c_void, drops: Arc) -> IUnknown { + let inner = Box::new(Self { + nondelegating_vtable: &Self::NONDELEGATING, + forwarded_vtable: &Self::FORWARDED, + ref_count: windows_core::imp::RefCount::new(1), + outer, + drops, + }); + unsafe { IUnknown::from_raw(Box::into_raw(inner).cast()) } + } + + unsafe fn from_nondelegating(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe fn from_forwarded(this: *mut c_void) -> &'static Self { + &*((this as *const *const c_void).sub(1) as *const Self) + } + + unsafe fn forwarded_ptr(&self) -> *mut c_void { + (self as *const Self as *mut *mut c_void).add(1).cast() + } + + unsafe extern "system" fn query_nondelegating( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let inner = Self::from_nondelegating(this); + if *iid == IUnknown::IID || *iid == IInspectable::IID { + *result = this; + inner.ref_count.add_ref(); + S_OK + } else if *iid == IID_FORWARDED { + *result = inner.forwarded_ptr(); + Self::add_ref_forwarded(*result); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn add_ref_nondelegating(this: *mut c_void) -> u32 { + Self::from_nondelegating(this).ref_count.add_ref() + } + + unsafe extern "system" fn release_nondelegating(this: *mut c_void) -> u32 { + let inner = Self::from_nondelegating(this); + let remaining = inner.ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + } + + unsafe extern "system" fn query_forwarded( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let inner = Self::from_forwarded(this); + if *iid == IUnknown::IID || *iid == IInspectable::IID { + *result = inner.outer; + Self::add_ref_forwarded(this); + S_OK + } else if *iid == IID_FORWARDED { + *result = this; + Self::add_ref_forwarded(this); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn add_ref_forwarded(this: *mut c_void) -> u32 { + let outer = Self::from_forwarded(this).outer; + let vtable = *(outer as *const *const windows_core::IUnknown_Vtbl); + ((*vtable).AddRef)(outer) + } + + unsafe extern "system" fn release_forwarded(this: *mut c_void) -> u32 { + let outer = Self::from_forwarded(this).outer; + let vtable = *(outer as *const *const windows_core::IUnknown_Vtbl); + ((*vtable).Release)(outer) + } + + unsafe extern "system" fn get_iids( + _this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + if count.is_null() || result.is_null() { + return E_POINTER; + } + let allocated = CoTaskMemAlloc(std::mem::size_of::()) as *mut GUID; + if allocated.is_null() { + return E_OUTOFMEMORY; + } + allocated.write(IID_FORWARDED); + *count = 1; + *result = allocated; + S_OK + } + + unsafe extern "system" fn get_runtime_class_name( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + S_OK + } + + unsafe extern "system" fn get_trust_level(_this: *mut c_void, result: *mut i32) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = 0; + S_OK + } + } + + #[test] + fn forwarded_interfaces_preserve_outer_identity_and_inner_ownership() { + let drops = Arc::new(AtomicUsize::new(0)); + let outer = GenericOuter::create(false); + let inner = TestInner::create(outer.as_raw(), drops.clone()); + unsafe { GenericOuter::from_ptr(outer.as_raw()) } + .state + .set_inner(inner) + .unwrap(); + + let mut forwarded = std::ptr::null_mut(); + unsafe { outer.query(&IID_FORWARDED, &mut forwarded) } + .ok() + .unwrap(); + let forwarded = unsafe { IUnknown::from_raw(forwarded) }; + let mut identity = std::ptr::null_mut(); + unsafe { forwarded.query(&IUnknown::IID, &mut identity) } + .ok() + .unwrap(); + assert_eq!(identity, outer.as_raw()); + unsafe { drop(IUnknown::from_raw(identity)) }; + + drop(forwarded); + assert_eq!(drops.load(Ordering::SeqCst), 0); + drop(outer); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn local_interfaces_win_before_inner_forwarding() { + let drops = Arc::new(AtomicUsize::new(0)); + let outer = GenericOuter::create(false); + let host = unsafe { GenericOuter::from_ptr(outer.as_raw()) }; + host.state + .set_inner(TestInner::create(outer.as_raw(), drops.clone())) + .unwrap(); + + let mut local = std::ptr::null_mut(); + let hr = unsafe { + host.state + .query_interface(outer.as_raw(), &IID_FORWARDED, &mut local, |_| { + Some(outer.as_raw()) + }) + }; + assert!(hr.is_ok()); + assert_eq!(local, outer.as_raw()); + unsafe { drop(IUnknown::from_raw(local)) }; + drop(outer); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn inner_can_only_be_attached_once_and_null_outputs_are_rejected() { + let drops = Arc::new(AtomicUsize::new(0)); + let outer = GenericOuter::create(false); + let host = unsafe { GenericOuter::from_ptr(outer.as_raw()) }; + host.state + .set_inner(TestInner::create(outer.as_raw(), drops.clone())) + .unwrap(); + assert!( + host.state + .set_inner(TestInner::create(outer.as_raw(), drops.clone())) + .is_err() + ); + + let vtable = unsafe { *(outer.as_raw() as *const *const IInspectableVtbl) }; + assert_eq!( + unsafe { + ((*vtable).base.QueryInterface)( + outer.as_raw(), + std::ptr::null(), + std::ptr::null_mut(), + ) + }, + E_POINTER + ); + drop(outer); + assert_eq!(drops.load(Ordering::SeqCst), 2); + } + + #[test] + fn agile_behavior_is_exposed_only_when_declared() { + let apartment_bound = GenericOuter::create(false); + let mut result = std::ptr::null_mut(); + assert_eq!( + unsafe { apartment_bound.query(&windows_core::imp::IAgileObject::IID, &mut result,) }, + E_NOINTERFACE + ); + assert!(result.is_null()); + + let agile = GenericOuter::create(true); + unsafe { + agile + .query(&windows_core::imp::IAgileObject::IID, &mut result) + .ok() + .unwrap(); + } + assert_eq!(result, agile.as_raw()); + unsafe { drop(IUnknown::from_raw(result)) }; + + let mut marshal = std::ptr::null_mut(); + unsafe { + agile + .query(&windows_core::imp::IMarshal::IID, &mut marshal) + .ok() + .unwrap(); + } + assert!(!marshal.is_null()); + unsafe { drop(IUnknown::from_raw(marshal)) }; + } + + #[test] + fn delegating_inner_is_rejected_before_attachment() { + let outer = GenericOuter::create(false); + assert!(validate_nondelegating_inner(&outer, &outer).is_err()); + + let drops = Arc::new(AtomicUsize::new(0)); + let inner = TestInner::create(outer.as_raw(), drops); + assert!(validate_nondelegating_inner(&inner, &outer).is_ok()); + } + + #[test] + fn dynamic_local_qi_dispatch_identity_and_callback_lifetime() { + let calls = Arc::new(AtomicUsize::new(0)); + let retained = calls.clone(); + let callback: LocalOverrideVoidCallback = Arc::new(move || { + retained.fetch_add(1, Ordering::SeqCst); + S_OK + }); + let callback_lifetime = callback.clone(); + let spec = LocalOverrideInterface::new(IID_FORWARDED, vec![LocalOverrideAbi::Void0]) + .unwrap() + .with_void_callback(6, callback) + .unwrap(); + let outer = DynamicOuter::create(false, vec![spec]).unwrap(); + + let mut local = std::ptr::null_mut(); + unsafe { outer.query(&IID_FORWARDED, &mut local) } + .ok() + .unwrap(); + assert_ne!(local, outer.as_raw()); + let local_vtable = unsafe { *(local as *const *const *const c_void) }; + let invoke: unsafe extern "system" fn(*mut c_void) -> HRESULT = + unsafe { std::mem::transmute(*local_vtable.add(6)) }; + assert_eq!(unsafe { invoke(local) }, S_OK); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + let mut identity = std::ptr::null_mut(); + let local_unknown = unsafe { IUnknown::from_raw(local) }; + unsafe { local_unknown.query(&IUnknown::IID, &mut identity) } + .ok() + .unwrap(); + assert_eq!(identity, outer.as_raw()); + unsafe { drop(IUnknown::from_raw(identity)) }; + drop(local_unknown); + drop(outer); + assert_eq!(Arc::strong_count(&callback_lifetime), 1); + } + + #[test] + fn dynamic_local_callback_panics_fail_closed() { + let callback: LocalOverrideVoidCallback = Arc::new(|| panic!("callback panic")); + let spec = LocalOverrideInterface::new(IID_FORWARDED, vec![LocalOverrideAbi::Void0]) + .unwrap() + .with_void_callback(6, callback) + .unwrap(); + let outer = DynamicOuter::create(false, vec![spec]).unwrap(); + let mut local = std::ptr::null_mut(); + unsafe { outer.query(&IID_FORWARDED, &mut local) } + .ok() + .unwrap(); + let vtable = unsafe { *(local as *const *const *const c_void) }; + let invoke: unsafe extern "system" fn(*mut c_void) -> HRESULT = + unsafe { std::mem::transmute(*vtable.add(6)) }; + assert_eq!(unsafe { invoke(local) }, E_FAIL); + unsafe { drop(IUnknown::from_raw(local)) }; + } + + #[test] + fn dynamic_size_override_dispatches_exact_abi() { + let callback: LocalOverrideSizeCallback = + Arc::new(|width, height, result_width, result_height| { + *result_width = width / 2.0; + *result_height = height / 4.0; + S_OK + }); + let spec = + LocalOverrideInterface::new(IID_FORWARDED, vec![LocalOverrideAbi::SizeF32ToSizeF32]) + .unwrap() + .with_size_callback(6, callback) + .unwrap(); + let outer = DynamicOuter::create(false, vec![spec]).unwrap(); + let mut local = std::ptr::null_mut(); + unsafe { outer.query(&IID_FORWARDED, &mut local) } + .ok() + .unwrap(); + let vtable = unsafe { *(local as *const *const *const c_void) }; + let invoke: unsafe extern "system" fn(*mut c_void, AbiSize, *mut AbiSize) -> HRESULT = + unsafe { std::mem::transmute(*vtable.add(6)) }; + let mut result = AbiSize { + width: 0.0, + height: 0.0, + }; + assert_eq!( + unsafe { + invoke( + local, + AbiSize { + width: 80.0, + height: 40.0, + }, + &mut result, + ) + }, + S_OK + ); + assert_eq!((result.width, result.height), (40.0, 10.0)); + unsafe { drop(IUnknown::from_raw(local)) }; + } + + #[test] + fn dynamic_override_specs_reject_wrong_slots_and_shapes() { + let callback: LocalOverrideVoidCallback = Arc::new(|| S_OK); + assert!(LocalOverrideInterface::new(IID_FORWARDED, vec![]).is_err()); + assert!( + LocalOverrideInterface::new(IID_FORWARDED, vec![LocalOverrideAbi::SizeF32ToSizeF32],) + .unwrap() + .with_void_callback(6, callback) + .is_err() + ); + } +} diff --git a/crates/dynwinrt/src/element_factory.rs b/crates/dynwinrt/src/element_factory.rs index 17ebd3e5..6f61a970 100644 --- a/crates/dynwinrt/src/element_factory.rs +++ b/crates/dynwinrt/src/element_factory.rs @@ -86,10 +86,17 @@ impl DynamicElementFactory { *result = std::ptr::null_mut(); let factory = Self::from_ptr(this); let iid = &*iid; - if *iid == IUnknown::IID || *iid == IInspectable::IID || *iid == IID_IELEMENT_FACTORY { + if *iid == IUnknown::IID + || *iid == IInspectable::IID + || *iid == windows_core::imp::IAgileObject::IID + || *iid == IID_IELEMENT_FACTORY + { *result = this; factory.ref_count.add_ref(); S_OK + } else if *iid == windows_core::imp::IMarshal::IID { + factory.ref_count.add_ref(); + windows_core::imp::marshaler(core::mem::transmute(this), result) } else { E_NOINTERFACE } @@ -265,4 +272,21 @@ mod tests { assert!(hr.is_ok()); assert_eq!(recycle_count.load(Ordering::SeqCst), 1); } + + #[test] + fn element_factory_is_agile_and_marshalable() { + let factory = create_element_factory(Box::new(|_| Err(E_FAIL)), Box::new(|_| S_OK)); + + let mut agile = std::ptr::null_mut(); + let hr = unsafe { factory.query(&windows_core::imp::IAgileObject::IID, &mut agile) }; + assert!(hr.is_ok()); + assert!(!agile.is_null()); + drop(unsafe { IUnknown::from_raw(agile) }); + + let mut marshal = std::ptr::null_mut(); + let hr = unsafe { factory.query(&windows_core::imp::IMarshal::IID, &mut marshal) }; + assert!(hr.is_ok()); + assert!(!marshal.is_null()); + drop(unsafe { IUnknown::from_raw(marshal) }); + } } diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 0f900016..d7f3ea63 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -6,6 +6,7 @@ use windows::core::*; mod abi; mod call; pub mod com; +mod composition; mod interfaces; mod native_call; mod result; @@ -29,6 +30,10 @@ mod reference; pub mod vector; pub use crate::array::ArrayData; +pub use crate::composition::{ + LocalOverrideAbi, LocalOverrideInterface, LocalOverrideSizeCallback, LocalOverrideVoidCallback, + compose_winrt, compose_winrt_with_overrides, +}; pub use crate::dasync::{ AsyncCompletedCallback, ProgressCallback, WinRTAsyncFuture, create_progress_handler, get_async_results, set_async_completed_handler, @@ -45,7 +50,10 @@ pub use crate::roapi::ro_get_activation_factory_2; pub use crate::signature::{InterfaceSignature, MethodSignature}; pub use crate::value::{ArrayOfIUnknownData, AsyncInfo, WinRTValue}; pub use crate::winapp::{WinAppSdkContext, initialize_winappsdk}; -pub use crate::xaml_application::create_xaml_application; +pub use crate::xaml_application::{ + XamlRuntimeClassActivator, XamlRuntimeClassRegistration, create_xaml_application, + register_xaml_runtime_class, +}; pub use interfaces::uri_vtable; pub async fn get_async_string( diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 2745d2b5..d8fc4dfe 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -180,6 +180,58 @@ impl ValueTypeData { unsafe { (self.ptr.add(offset) as *mut T).write(value) } } + pub fn get_field_object(&self, index: usize) -> crate::result::Result> { + let h = &self.type_handle; + let field_handle = h.field_type(index); + if !field_handle.kind().is_com_pointer() { + return Err(crate::result::Error::expect_object_type( + field_handle.kind(), + )); + } + let offset = h.field_offset(index); + let raw = unsafe { *(self.ptr.add(offset) as *const *mut c_void) }; + if raw.is_null() { + Ok(None) + } else { + Ok(unsafe { IUnknown::from_raw_borrowed(&raw) }.map(Clone::clone)) + } + } + + pub fn set_field_object( + &mut self, + index: usize, + value: Option<&IUnknown>, + ) -> crate::result::Result<()> { + let h = &self.type_handle; + let field_handle = h.field_type(index); + if !field_handle.kind().is_com_pointer() { + return Err(crate::result::Error::expect_object_type( + field_handle.kind(), + )); + } + let offset = h.field_offset(index); + let field = unsafe { &mut *(self.ptr.add(offset) as *mut *mut c_void) }; + let new_raw = if let Some(object) = value { + let iid = if field_handle.kind() == TypeKind::Object { + windows_core::IInspectable::IID + } else { + field_handle.iid().ok_or_else(|| { + crate::result::Error::NotAnInterface(field_handle.signature_string()) + })? + }; + let mut queried = std::ptr::null_mut(); + unsafe { object.query(&iid, &mut queried) }.ok()?; + queried + } else { + std::ptr::null_mut() + }; + let old_raw = std::mem::replace(field, new_raw); + if !old_raw.is_null() { + unsafe { drop(IUnknown::from_raw(old_raw)) }; + } + Ok(()) + } + pub fn get_field_struct(&self, index: usize) -> ValueTypeData { let h = &self.type_handle; let offset = h.field_offset(index); diff --git a/crates/dynwinrt/src/reference.rs b/crates/dynwinrt/src/reference.rs index 230cbbb3..cc0bd61a 100644 --- a/crates/dynwinrt/src/reference.rs +++ b/crates/dynwinrt/src/reference.rs @@ -180,6 +180,73 @@ mod tests { assert_eq!(reference.Value().unwrap(), "hello"); } + #[test] + fn stores_reference_object_fields_with_owned_lifetime() { + let table = MetadataTable::new(); + let value_type = table.u64_type(); + let generic = table.generic(IREFERENCE, 1); + let reference_type = table.parameterized(&generic, std::slice::from_ref(&value_type)); + let holder_type = table.struct_type("Test.OptionalUInt64Holder", &[reference_type.clone()]); + let mut holder = holder_type.default_value(); + let boxed = box_ireference(WinRTValue::U64(17), value_type.clone()).unwrap(); + let boxed_object = boxed.as_object().unwrap(); + + holder + .set_field_object(0, Some(&boxed_object)) + .expect("store reference object"); + drop(boxed); + drop(boxed_object); + let stored = holder + .get_field_object(0) + .expect("read reference field") + .expect("non-null reference field"); + let interface = table + .register_interface( + "IReference_UInt64_Struct_Test", + reference_type.iid().unwrap(), + ) + .add_method( + "get_Value", + MethodSignature::new(&table).add_out(value_type), + ); + let result = interface + .method(6) + .unwrap() + .invoke(stored.as_raw(), &[]) + .unwrap(); + assert!(matches!(result[0], WinRTValue::U64(17))); + + let incompatible = box_ireference(WinRTValue::U32(9), table.u32_type()).unwrap(); + let incompatible_object = incompatible.as_object().unwrap(); + assert!( + holder + .set_field_object(0, Some(&incompatible_object)) + .is_err() + ); + let unchanged = holder + .get_field_object(0) + .unwrap() + .expect("failed replacement must preserve the old field"); + let result = interface + .method(6) + .unwrap() + .invoke(unchanged.as_raw(), &[]) + .unwrap(); + assert!(matches!(result[0], WinRTValue::U64(17))); + + holder + .set_field_object(0, None) + .expect("clear reference object"); + assert!(holder.get_field_object(0).unwrap().is_none()); + assert!( + table + .struct_type("Test.ScalarHolder", &[table.u32_type()]) + .default_value() + .get_field_object(0) + .is_err() + ); + } + #[test] fn boxes_enum_and_struct_values() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/xaml_application.rs b/crates/dynwinrt/src/xaml_application.rs index 92dc449f..7a176c65 100644 --- a/crates/dynwinrt/src/xaml_application.rs +++ b/crates/dynwinrt/src/xaml_application.rs @@ -4,23 +4,188 @@ #![allow(unsafe_op_in_unsafe_fn)] use core::ffi::c_void; -use std::sync::Mutex; +use std::collections::HashMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, LazyLock, Mutex}; -use windows::Win32::System::Com::{CoTaskMemAlloc, CoTaskMemFree}; +use windows::Win32::System::Com::CoTaskMemAlloc; use windows::Win32::System::Threading::GetCurrentProcess; use windows::Win32::UI::HiDpi::{ AreDpiAwarenessContextsEqual, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, GetDpiAwarenessContextForProcess, SetProcessDpiAwarenessContext, SetThreadDpiAwarenessContext, }; -use windows_core::{GUID, HRESULT, HSTRING, IInspectable, IUnknown, Interface}; +use windows_core::{GUID, HRESULT, HSTRING, IUnknown, Interface}; -use crate::com_helpers::{E_FAIL, E_NOINTERFACE, E_POINTER, IInspectableVtbl, S_OK}; +use crate::com_helpers::{E_FAIL, E_NOINTERFACE, E_NOTIMPL, E_POINTER, IInspectableVtbl, S_OK}; +use crate::composition::CompositionState; use crate::{Result, WinRTValue}; const IID_IAPPLICATION_FACTORY: GUID = GUID::from_u128(0x9fd96657_5294_5a65_a1db_4fea143597da); const IID_IAPPLICATION_OVERRIDES: GUID = GUID::from_u128(0xa33e81ef_c665_503b_8827_d27ef1720a06); const IID_IXAML_METADATA_PROVIDER: GUID = GUID::from_u128(0xa96251f0_2214_5d53_8746_ce99a2593cd7); +const IID_IXAML_TYPE: GUID = GUID::from_u128(0xd24219df_7ec9_57f1_a27b_6af251d9c5bc); const IID_XAML_LAUNCHED_CALLBACK: GUID = GUID::from_u128(0xf81c4e72_7a18_4a30_9126_6f62b6bdac83); +const E_INVALIDARG: HRESULT = HRESULT(0x80070057u32 as i32); +const E_OUTOFMEMORY: HRESULT = HRESULT(0x8007000Eu32 as i32); +const HRESULT_ALREADY_EXISTS: HRESULT = HRESULT(0x800700B7u32 as i32); +const TYPE_KIND_METADATA: i32 = 1; +const TYPE_KIND_CUSTOM: i32 = 2; +const RO_E_CLOSED: HRESULT = HRESULT(0x80000013_u32 as i32); + +/// Synchronous constructor used by a registered XAML runtime class. +pub type XamlRuntimeClassActivator = Arc windows_core::Result + Send + Sync>; + +struct XamlRuntimeClassEntry { + id: u64, + name: String, + base_type: String, + base_iid: GUID, + activator: XamlRuntimeClassActivator, + active: Arc, +} + +static XAML_RUNTIME_CLASSES: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); +static NEXT_XAML_RUNTIME_CLASS_ID: AtomicU64 = AtomicU64::new(1); + +/// Owns one process-local XAML runtime-class registration. +/// +/// Dropping or explicitly unregistering the handle prevents new metadata +/// lookups. IXamlType objects already handed to XAML retain the entry until +/// their in-flight use completes. +pub struct XamlRuntimeClassRegistration { + name: String, + id: u64, + supported_overrides: Vec, + active: Arc, +} + +impl XamlRuntimeClassRegistration { + pub fn name(&self) -> &str { + &self.name + } + + pub fn supported_overrides(&self) -> &[String] { + &self.supported_overrides + } + + pub fn unregister(&self) -> bool { + if !self.active.load(Ordering::Acquire) { + return false; + } + let Ok(mut registrations) = XAML_RUNTIME_CLASSES.lock() else { + return false; + }; + if !self.active.swap(false, Ordering::AcqRel) { + return false; + } + if registrations + .get(&self.name) + .is_some_and(|entry| entry.id == self.id) + { + registrations.remove(&self.name); + true + } else { + false + } + } +} + +impl Drop for XamlRuntimeClassRegistration { + fn drop(&mut self) { + self.unregister(); + } +} + +fn valid_runtime_class_name(name: &str) -> bool { + let mut count = 0; + for segment in name.split('.') { + count += 1; + let mut chars = segment.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !(first == '_' || first.is_alphabetic()) + || chars.any(|character| !(character == '_' || character.is_alphanumeric())) + { + return false; + } + } + count >= 2 +} + +fn valid_override_name(name: &str) -> bool { + let mut chars = name.chars(); + chars + .next() + .is_some_and(|first| first == '_' || first.is_alphabetic()) + && chars.all(|character| character == '_' || character.is_alphanumeric()) +} + +/// Register a process-local runtime-class name for XAML metadata activation. +/// +/// This does not modify the machine/package activation catalog. The class is +/// visible only through dynwinrt's composed `IXamlMetadataProvider`, and its +/// base must be a non-generic WinUI type supplied by the chained provider. +pub fn register_xaml_runtime_class( + name: &str, + base_type: &str, + base_iid: GUID, + supported_overrides: Vec, + activator: XamlRuntimeClassActivator, +) -> windows_core::Result { + if !valid_runtime_class_name(name) + || !valid_runtime_class_name(base_type) + || name == base_type + || supported_overrides + .iter() + .any(|name| !valid_override_name(name)) + { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + let mut supported_overrides = supported_overrides; + supported_overrides.sort(); + if supported_overrides + .windows(2) + .any(|pair| pair[0] == pair[1]) + { + return Err(windows_core::Error::from_hresult(E_INVALIDARG)); + } + + let id = NEXT_XAML_RUNTIME_CLASS_ID.fetch_add(1, Ordering::Relaxed); + let active = Arc::new(AtomicBool::new(true)); + let entry = Arc::new(XamlRuntimeClassEntry { + id, + name: name.to_string(), + base_type: base_type.to_string(), + base_iid, + activator, + active: active.clone(), + }); + let mut registrations = XAML_RUNTIME_CLASSES + .lock() + .map_err(|_| windows_core::Error::from_hresult(E_FAIL))?; + if registrations.contains_key(name) { + return Err(windows_core::Error::from_hresult(HRESULT_ALREADY_EXISTS)); + } + registrations.insert(name.to_string(), entry); + Ok(XamlRuntimeClassRegistration { + name: name.to_string(), + id, + supported_overrides, + active, + }) +} + +fn registered_xaml_runtime_class( + name: &str, +) -> std::result::Result>, HRESULT> { + XAML_RUNTIME_CLASSES + .lock() + .map(|registrations| registrations.get(name).cloned()) + .map_err(|_| E_FAIL) +} #[repr(C)] struct ApplicationFactoryVtbl { @@ -61,31 +226,602 @@ struct XamlMetadataProviderVtbl { this: *mut c_void, full_name: *mut c_void, result: *mut *mut c_void, - ) -> HRESULT, - get_xmlns_definitions: unsafe extern "system" fn( - this: *mut c_void, - count: *mut u32, + ) -> HRESULT, + get_xmlns_definitions: unsafe extern "system" fn( + this: *mut c_void, + count: *mut u32, + result: *mut *mut c_void, + ) -> HRESULT, +} + +#[repr(C)] +struct XamlTypeVtbl { + base: IInspectableVtbl, + get_base_type: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_content_property: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_full_name: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_is_array: unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_is_collection: unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_is_constructible: unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_is_dictionary: unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_is_markup_extension: + unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_is_bindable: unsafe extern "system" fn(this: *mut c_void, result: *mut u8) -> HRESULT, + get_item_type: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_key_type: unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_boxed_type: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + get_underlying_type: + unsafe extern "system" fn(this: *mut c_void, result: *mut AbiTypeName) -> HRESULT, + activate_instance: + unsafe extern "system" fn(this: *mut c_void, result: *mut *mut c_void) -> HRESULT, + create_from_string: unsafe extern "system" fn( + this: *mut c_void, + value: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT, + get_member: unsafe extern "system" fn( + this: *mut c_void, + name: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT, + add_to_vector: unsafe extern "system" fn( + this: *mut c_void, + instance: *mut c_void, + value: *mut c_void, + ) -> HRESULT, + add_to_map: unsafe extern "system" fn( + this: *mut c_void, + instance: *mut c_void, + key: *mut c_void, + value: *mut c_void, + ) -> HRESULT, + run_initializer: unsafe extern "system" fn(this: *mut c_void) -> HRESULT, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct AbiTypeName { + name: *mut c_void, + kind: i32, +} + +#[repr(C)] +struct RegisteredXamlType { + vtable: *const XamlTypeVtbl, + ref_count: windows_core::imp::WeakRefCount, + entry: Arc, + base_type: IUnknown, + metadata_base: Option, +} + +impl RegisteredXamlType { + const VTABLE: XamlTypeVtbl = XamlTypeVtbl { + base: IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }, + get_base_type: Self::get_base_type, + get_content_property: Self::get_content_property, + get_full_name: Self::get_full_name, + get_is_array: Self::get_is_array, + get_is_collection: Self::get_is_collection, + get_is_constructible: Self::get_is_constructible, + get_is_dictionary: Self::get_is_dictionary, + get_is_markup_extension: Self::get_is_markup_extension, + get_is_bindable: Self::get_is_bindable, + get_item_type: Self::get_item_type, + get_key_type: Self::get_key_type, + get_boxed_type: Self::get_boxed_type, + get_underlying_type: Self::get_underlying_type, + activate_instance: Self::activate_instance, + create_from_string: Self::create_from_string, + get_member: Self::get_member, + add_to_vector: Self::add_to_vector, + add_to_map: Self::add_to_map, + run_initializer: Self::run_initializer, + }; + + fn create( + entry: Arc, + base_type: IUnknown, + metadata_base: Option, + ) -> IUnknown { + let value = Box::new(Self { + vtable: &Self::VTABLE, + ref_count: windows_core::imp::WeakRefCount::new(), + entry, + base_type, + metadata_base, + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } + } + + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe fn write_object(result: *mut *mut c_void, value: IUnknown) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = value.as_raw(); + std::mem::forget(value); + S_OK + } + + unsafe fn write_hstring(result: *mut *mut c_void, value: &str) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + (result as *mut HSTRING).write(HSTRING::from(value)); + S_OK + } + + unsafe fn metadata_base_vtable(&self) -> Option<(*mut c_void, *const XamlTypeVtbl)> { + self.metadata_base.as_ref().map(|base| { + ( + base.as_raw(), + *(base.as_raw() as *const *const XamlTypeVtbl), + ) + }) + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID + || *iid == windows_core::IInspectable::IID + || *iid == IID_IXAML_TYPE + { + *result = this; + Self::from_ptr(this).ref_count.add_ref(); + S_OK + } else { + E_NOINTERFACE + } + })) { + Ok(hr) => hr, + Err(_) => E_FAIL, + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + Self::from_ptr(this).ref_count.add_ref() + })) + .unwrap_or(0) + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + catch_unwind(AssertUnwindSafe(|| { + let remaining = Self::from_ptr(this).ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + })) + .unwrap_or(0) + } + + unsafe extern "system" fn get_iids( + _this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + if count.is_null() || result.is_null() { + return E_POINTER; + } + *count = 0; + *result = std::ptr::null_mut(); + let value = CoTaskMemAlloc(std::mem::size_of::()) as *mut GUID; + if value.is_null() { + return E_OUTOFMEMORY; + } + value.write(IID_IXAML_TYPE); + *count = 1; + *result = value; + S_OK + } + + unsafe extern "system" fn get_runtime_class_name( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_hstring(result, "DynWinRT.XamlRuntimeClassType") + } + + unsafe extern "system" fn get_trust_level(_this: *mut c_void, result: *mut i32) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = 0; + S_OK + } + + unsafe extern "system" fn get_base_type( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_object(result, Self::from_ptr(this).base_type.clone()) + } + + unsafe extern "system" fn get_content_property( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let value = Self::from_ptr(this); + match value.metadata_base_vtable() { + Some((base, vtable)) => ((*vtable).get_content_property)(base, result), + None => S_OK, + } + } + + unsafe extern "system" fn get_full_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_hstring(result, &Self::from_ptr(this).entry.name) + } + + unsafe fn write_bool(result: *mut u8, value: bool) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = u8::from(value); + S_OK + } + + unsafe extern "system" fn get_is_array(_this: *mut c_void, result: *mut u8) -> HRESULT { + Self::write_bool(result, false) + } + + unsafe extern "system" fn get_is_collection(_this: *mut c_void, result: *mut u8) -> HRESULT { + Self::write_bool(result, false) + } + + unsafe extern "system" fn get_is_constructible(_this: *mut c_void, result: *mut u8) -> HRESULT { + Self::write_bool(result, true) + } + + unsafe extern "system" fn get_is_dictionary(_this: *mut c_void, result: *mut u8) -> HRESULT { + Self::write_bool(result, false) + } + + unsafe extern "system" fn get_is_markup_extension( + _this: *mut c_void, + result: *mut u8, + ) -> HRESULT { + Self::write_bool(result, false) + } + + unsafe extern "system" fn get_is_bindable(this: *mut c_void, result: *mut u8) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + let value = Self::from_ptr(this); + match value.metadata_base_vtable() { + Some((base, vtable)) => ((*vtable).get_is_bindable)(base, result), + None => Self::write_bool(result, true), + } + } + + unsafe fn write_optional_null(result: *mut *mut c_void) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + S_OK + } + + unsafe extern "system" fn get_item_type( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_optional_null(result) + } + + unsafe extern "system" fn get_key_type( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_optional_null(result) + } + + unsafe extern "system" fn get_boxed_type( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::write_optional_null(result) + } + + unsafe extern "system" fn get_underlying_type( + this: *mut c_void, + result: *mut AbiTypeName, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + result.write(AbiTypeName { + name: std::mem::transmute(HSTRING::from(&Self::from_ptr(this).entry.name)), + kind: TYPE_KIND_CUSTOM, + }); + S_OK + } + + unsafe extern "system" fn activate_instance( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + match catch_unwind(AssertUnwindSafe(|| { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if !Self::from_ptr(this).entry.active.load(Ordering::Acquire) { + return RO_E_CLOSED; + } + match (Self::from_ptr(this).entry.activator)() { + Ok(instance) if !instance.as_raw().is_null() => { + let mut base = std::ptr::null_mut(); + let hr = instance.query(&Self::from_ptr(this).entry.base_iid, &mut base); + if hr.is_err() || base.is_null() { + if !base.is_null() { + drop(IUnknown::from_raw(base)); + } + return if hr.is_err() { hr } else { E_NOINTERFACE }; + } + let base = IUnknown::from_raw(base); + let Ok(instance_identity) = instance.cast::() else { + return E_NOINTERFACE; + }; + let Ok(base_identity) = base.cast::() else { + return E_NOINTERFACE; + }; + if instance_identity.as_raw() != base_identity.as_raw() { + return E_NOINTERFACE; + } + Self::write_object(result, instance) + } + Ok(_) => E_FAIL, + Err(error) => error.code(), + } + })) { + Ok(hr) => hr, + Err(_) => E_FAIL, + } + } + + unsafe extern "system" fn create_from_string( + _this: *mut c_void, + _value: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_NOTIMPL + } + + unsafe extern "system" fn get_member( + this: *mut c_void, + name: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let value = Self::from_ptr(this); + match value.metadata_base_vtable() { + Some((base, vtable)) => ((*vtable).get_member)(base, name, result), + None => S_OK, + } + } + + unsafe extern "system" fn add_to_vector( + _this: *mut c_void, + _instance: *mut c_void, + _value: *mut c_void, + ) -> HRESULT { + E_NOTIMPL + } + + unsafe extern "system" fn add_to_map( + _this: *mut c_void, + _instance: *mut c_void, + _key: *mut c_void, + _value: *mut c_void, + ) -> HRESULT { + E_NOTIMPL + } + + unsafe extern "system" fn run_initializer(_this: *mut c_void) -> HRESULT { + S_OK + } +} + +/// Minimal IXamlType reference used for WinUI built-in base types that are not +/// surfaced by XamlControlsXamlMetaDataProvider. WinUI resolves its +/// UnderlyingType against the built-in metadata table; it is never activatable. +#[repr(C)] +struct ReferencedXamlType { + vtable: *const XamlTypeVtbl, + ref_count: windows_core::imp::WeakRefCount, + name: String, +} + +impl ReferencedXamlType { + const VTABLE: XamlTypeVtbl = XamlTypeVtbl { + base: IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: RegisteredXamlType::get_iids, + get_runtime_class_name: RegisteredXamlType::get_runtime_class_name, + get_trust_level: RegisteredXamlType::get_trust_level, + }, + get_base_type: Self::get_object, + get_content_property: Self::get_object, + get_full_name: Self::get_full_name, + get_is_array: Self::get_false, + get_is_collection: Self::get_false, + get_is_constructible: Self::get_false, + get_is_dictionary: Self::get_false, + get_is_markup_extension: Self::get_false, + get_is_bindable: Self::get_true, + get_item_type: Self::get_object, + get_key_type: Self::get_object, + get_boxed_type: Self::get_object, + get_underlying_type: Self::get_underlying_type, + activate_instance: Self::activate_instance, + create_from_string: Self::create_from_string, + get_member: Self::get_member, + add_to_vector: RegisteredXamlType::add_to_vector, + add_to_map: RegisteredXamlType::add_to_map, + run_initializer: RegisteredXamlType::run_initializer, + }; + + fn create(name: String) -> IUnknown { + let value = Box::new(Self { + vtable: &Self::VTABLE, + ref_count: windows_core::imp::WeakRefCount::new(), + name, + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } + } + + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID + || *iid == windows_core::IInspectable::IID + || *iid == IID_IXAML_TYPE + { + *result = this; + Self::from_ptr(this).ref_count.add_ref(); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + Self::from_ptr(this).ref_count.add_ref() + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let remaining = Self::from_ptr(this).ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + } + + unsafe extern "system" fn get_object(_this: *mut c_void, result: *mut *mut c_void) -> HRESULT { + RegisteredXamlType::write_optional_null(result) + } + + unsafe extern "system" fn get_full_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + RegisteredXamlType::write_hstring(result, &Self::from_ptr(this).name) + } + + unsafe extern "system" fn get_false(_this: *mut c_void, result: *mut u8) -> HRESULT { + RegisteredXamlType::write_bool(result, false) + } + + unsafe extern "system" fn get_true(_this: *mut c_void, result: *mut u8) -> HRESULT { + RegisteredXamlType::write_bool(result, true) + } + + unsafe extern "system" fn get_underlying_type( + this: *mut c_void, + result: *mut AbiTypeName, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + result.write(AbiTypeName { + name: std::mem::transmute(HSTRING::from(&Self::from_ptr(this).name)), + kind: TYPE_KIND_METADATA, + }); + S_OK + } + + unsafe extern "system" fn activate_instance( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_NOTIMPL + } + + unsafe extern "system" fn create_from_string( + _this: *mut c_void, + _value: *mut c_void, result: *mut *mut c_void, - ) -> HRESULT, -} + ) -> HRESULT { + Self::activate_instance(std::ptr::null_mut(), result) + } -#[repr(C)] -#[derive(Clone, Copy)] -struct AbiTypeName { - name: *mut c_void, - kind: i32, + unsafe extern "system" fn get_member( + _this: *mut c_void, + _name: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + RegisteredXamlType::write_optional_null(result) + } } #[repr(C)] struct XamlApplicationHost { vtable_overrides: *const ApplicationOverridesVtbl, vtable_metadata: *const XamlMetadataProviderVtbl, - ref_count: windows_core::imp::WeakRefCount, + state: CompositionState, metadata_provider: IUnknown, launched_callback: Option, - inner: Mutex>, } +// Safety: local COM fields are immutable IUnknown handles and CompositionState +// protects its inner. This does not expose IAgileObject; WinUI remains STA-bound. unsafe impl Send for XamlApplicationHost {} unsafe impl Sync for XamlApplicationHost {} @@ -124,10 +860,9 @@ impl XamlApplicationHost { Box::new(Self { vtable_overrides: &Self::OVERRIDES_VTBL, vtable_metadata: &Self::METADATA_VTBL, - ref_count: windows_core::imp::WeakRefCount::new(), + state: CompositionState::new(true), metadata_provider, launched_callback, - inner: Mutex::new(None), }) } @@ -148,13 +883,6 @@ impl XamlApplicationHost { unsafe { (self.identity_ptr() as *mut *mut c_void).add(1) as *mut c_void } } - fn inner(&self) -> std::result::Result, HRESULT> { - self.inner - .lock() - .map(|inner| inner.clone()) - .map_err(|_| E_FAIL) - } - unsafe extern "system" fn query_interface_overrides( this: *mut c_void, iid: *const GUID, @@ -176,49 +904,24 @@ impl XamlApplicationHost { iid: *const GUID, result: *mut *mut c_void, ) -> HRESULT { - if iid.is_null() || result.is_null() { - return E_POINTER; - } - - *result = std::ptr::null_mut(); - let iid = &*iid; - if *iid == IUnknown::IID - || *iid == IInspectable::IID - || *iid == IID_IAPPLICATION_OVERRIDES - || *iid == windows_core::imp::IAgileObject::IID - { - *result = host.identity_ptr(); - host.ref_count.add_ref(); - return S_OK; - } - if *iid == IID_IXAML_METADATA_PROVIDER { - *result = host.metadata_ptr(); - host.ref_count.add_ref(); - return S_OK; - } - if *iid == windows_core::imp::IMarshal::IID { - host.ref_count.add_ref(); - return windows_core::imp::marshaler(core::mem::transmute(host.identity_ptr()), result); - } - let tear_off = host.ref_count.query(iid, host.identity_ptr()); - if !tear_off.is_null() { - *result = tear_off; - return S_OK; - } - - match host.inner() { - Ok(Some(inner)) => inner.query(iid, result), - Ok(None) => E_NOINTERFACE, - Err(hr) => hr, - } + host.state + .query_interface(host.identity_ptr(), iid, result, |iid| { + if *iid == IID_IAPPLICATION_OVERRIDES { + Some(host.identity_ptr()) + } else if *iid == IID_IXAML_METADATA_PROVIDER { + Some(host.metadata_ptr()) + } else { + None + } + }) } unsafe extern "system" fn add_ref_overrides(this: *mut c_void) -> u32 { - Self::from_overrides_ptr(this).ref_count.add_ref() + Self::from_overrides_ptr(this).state.add_ref() } unsafe extern "system" fn add_ref_metadata(this: *mut c_void) -> u32 { - Self::from_metadata_ptr(this).ref_count.add_ref() + Self::from_metadata_ptr(this).state.add_ref() } unsafe extern "system" fn release_overrides(this: *mut c_void) -> u32 { @@ -230,7 +933,7 @@ impl XamlApplicationHost { } unsafe fn release_impl(host: &Self) -> u32 { - let remaining = host.ref_count.release(); + let remaining = host.state.release(); if remaining == 0 { drop(Box::from_raw(host.identity_ptr() as *mut Self)); } @@ -258,48 +961,11 @@ impl XamlApplicationHost { return E_POINTER; } - let local_iids = [IID_IAPPLICATION_OVERRIDES, IID_IXAML_METADATA_PROVIDER]; - let mut inner_count = 0; - let mut inner_iids = std::ptr::null_mut(); - match host.inner() { - Ok(Some(inner)) => { - let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); - let hr = ((*vtable).get_iids)(inner.as_raw(), &mut inner_count, &mut inner_iids); - if hr.is_err() { - return hr; - } - } - Ok(None) => {} - Err(hr) => return hr, - } - - let total = local_iids.len() + inner_count as usize; - let bytes = total - .checked_mul(std::mem::size_of::()) - .unwrap_or(usize::MAX); - let combined = CoTaskMemAlloc(bytes) as *mut GUID; - if combined.is_null() { - if !inner_iids.is_null() { - CoTaskMemFree(Some(inner_iids.cast())); - } - return HRESULT(0x8007000Eu32 as i32); - } - - std::ptr::copy_nonoverlapping(local_iids.as_ptr(), combined, local_iids.len()); - if inner_count != 0 { - std::ptr::copy_nonoverlapping( - inner_iids, - combined.add(local_iids.len()), - inner_count as usize, - ); - } - if !inner_iids.is_null() { - CoTaskMemFree(Some(inner_iids.cast())); - } - - *count = total as u32; - *result = combined; - S_OK + host.state.get_iids( + &[IID_IAPPLICATION_OVERRIDES, IID_IXAML_METADATA_PROVIDER], + count, + result, + ) } unsafe extern "system" fn get_runtime_class_name_overrides( @@ -317,20 +983,7 @@ impl XamlApplicationHost { } unsafe fn get_runtime_class_name_impl(host: &Self, result: *mut *mut c_void) -> HRESULT { - if result.is_null() { - return E_POINTER; - } - match host.inner() { - Ok(Some(inner)) => { - let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); - ((*vtable).get_runtime_class_name)(inner.as_raw(), result) - } - Ok(None) => { - *result = std::ptr::null_mut(); - S_OK - } - Err(hr) => hr, - } + host.state.get_runtime_class_name(result) } unsafe extern "system" fn get_trust_level_overrides( @@ -348,20 +1001,7 @@ impl XamlApplicationHost { } unsafe fn get_trust_level_impl(host: &Self, result: *mut i32) -> HRESULT { - if result.is_null() { - return E_POINTER; - } - match host.inner() { - Ok(Some(inner)) => { - let vtable = *(inner.as_raw() as *const *const IInspectableVtbl); - ((*vtable).get_trust_level)(inner.as_raw(), result) - } - Ok(None) => { - *result = 0; - S_OK - } - Err(hr) => hr, - } + host.state.get_trust_level(result) } unsafe extern "system" fn on_launched(this: *mut c_void, args: *mut c_void) -> HRESULT { @@ -380,6 +1020,21 @@ impl XamlApplicationHost { result: *mut *mut c_void, ) -> HRESULT { let host = Self::from_metadata_ptr(this); + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let name = hstring_from_abi(type_name.name); + match registered_xaml_runtime_class(&name) { + Ok(Some(entry)) => { + if type_name.kind != TYPE_KIND_CUSTOM { + return E_INVALIDARG; + } + return create_registered_xaml_type(&host.metadata_provider, entry, result); + } + Ok(None) => {} + Err(error) => return error, + } let provider = host.metadata_provider.as_raw(); let vtable = *(provider as *const *const XamlMetadataProviderVtbl); ((*vtable).get_xaml_type)(provider, type_name, result) @@ -391,6 +1046,18 @@ impl XamlApplicationHost { result: *mut *mut c_void, ) -> HRESULT { let host = Self::from_metadata_ptr(this); + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let name = hstring_from_abi(full_name); + match registered_xaml_runtime_class(&name) { + Ok(Some(entry)) => { + return create_registered_xaml_type(&host.metadata_provider, entry, result); + } + Ok(None) => {} + Err(error) => return error, + } let provider = host.metadata_provider.as_raw(); let vtable = *(provider as *const *const XamlMetadataProviderVtbl); ((*vtable).get_xaml_type_by_full_name)(provider, full_name, result) @@ -408,6 +1075,74 @@ impl XamlApplicationHost { } } +unsafe fn hstring_from_abi(value: *mut c_void) -> String { + let value: &HSTRING = &*(&value as *const *mut c_void as *const HSTRING); + value.to_string() +} + +unsafe fn create_registered_xaml_type( + provider: &IUnknown, + entry: Arc, + result: *mut *mut c_void, +) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + let provider_ptr = provider.as_raw(); + let provider_vtable = *(provider_ptr as *const *const XamlMetadataProviderVtbl); + let base_name = HSTRING::from(&entry.base_type); + let mut base = std::ptr::null_mut(); + let hr = ((*provider_vtable).get_xaml_type_by_full_name)( + provider_ptr, + std::mem::transmute_copy(&base_name), + &mut base, + ); + if hr.is_err() { + if !base.is_null() { + drop(IUnknown::from_raw(base)); + } + return hr; + } + let (base_type, metadata_base) = if base.is_null() { + (ReferencedXamlType::create(entry.base_type.clone()), None) + } else { + let base = IUnknown::from_raw(base); + let mut base_type = std::ptr::null_mut(); + let hr = base.query(&IID_IXAML_TYPE, &mut base_type); + if hr.is_err() || base_type.is_null() { + if !base_type.is_null() { + drop(IUnknown::from_raw(base_type)); + } + return if hr.is_err() { hr } else { E_NOINTERFACE }; + } + let base_type = IUnknown::from_raw(base_type); + + let vtable = *(base_type.as_raw() as *const *const XamlTypeVtbl); + for getter in [ + (*vtable).get_is_array, + (*vtable).get_is_collection, + (*vtable).get_is_dictionary, + (*vtable).get_is_markup_extension, + ] { + let mut unsupported = 0; + let hr = getter(base_type.as_raw(), &mut unsupported); + if hr.is_err() { + return hr; + } + if unsupported != 0 { + return E_INVALIDARG; + } + } + (base_type.clone(), Some(base_type)) + }; + + let xaml_type = RegisteredXamlType::create(entry, base_type, metadata_base); + *result = xaml_type.as_raw(); + std::mem::forget(xaml_type); + S_OK +} + fn query_interface(object: &IUnknown, iid: &GUID) -> windows_core::Result { let mut result = std::ptr::null_mut(); unsafe { @@ -486,10 +1221,7 @@ fn compose_xaml_application( unsafe { let inner = IUnknown::from_raw(inner); let application = IUnknown::from_raw(instance); - *(*host_ptr) - .inner - .lock() - .map_err(|_| windows_core::Error::from_hresult(E_FAIL))? = Some(inner); + (*host_ptr).state.set_inner(inner)?; Ok(application) } } @@ -518,8 +1250,596 @@ pub fn create_xaml_application( #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; use windows::Win32::UI::HiDpi::GetThreadDpiAwarenessContext; + #[repr(C)] + struct TestInspectable { + vtable: *const IInspectableVtbl, + ref_count: windows_core::imp::WeakRefCount, + } + + unsafe extern "system" fn test_qi( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID || *iid == windows_core::IInspectable::IID { + *result = this; + (*(this as *const TestInspectable)).ref_count.add_ref(); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn test_add_ref(this: *mut c_void) -> u32 { + (*(this as *const TestInspectable)).ref_count.add_ref() + } + + unsafe extern "system" fn test_release(this: *mut c_void) -> u32 { + let remaining = (*(this as *const TestInspectable)).ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut TestInspectable)); + } + remaining + } + + unsafe extern "system" fn test_get_iids( + _this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + if count.is_null() || result.is_null() { + return E_POINTER; + } + *count = 0; + *result = std::ptr::null_mut(); + S_OK + } + + unsafe extern "system" fn test_runtime_name( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + RegisteredXamlType::write_hstring(result, "DynWinRT.TestInspectable") + } + + unsafe extern "system" fn test_trust(_this: *mut c_void, result: *mut i32) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = 0; + S_OK + } + + static TEST_INSPECTABLE_VTABLE: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: test_qi, + AddRef: test_add_ref, + Release: test_release, + }, + get_iids: test_get_iids, + get_runtime_class_name: test_runtime_name, + get_trust_level: test_trust, + }; + + fn test_inspectable() -> IUnknown { + let value = Box::new(TestInspectable { + vtable: &TEST_INSPECTABLE_VTABLE, + ref_count: windows_core::imp::WeakRefCount::new(), + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } + } + + #[repr(C)] + struct TestBaseXamlType { + vtable: *const XamlTypeVtbl, + ref_count: windows_core::imp::WeakRefCount, + } + + impl TestBaseXamlType { + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe extern "system" fn qi( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID + || *iid == windows_core::IInspectable::IID + || *iid == IID_IXAML_TYPE + { + *result = this; + Self::from_ptr(this).ref_count.add_ref(); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + Self::from_ptr(this).ref_count.add_ref() + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let remaining = Self::from_ptr(this).ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + } + + unsafe extern "system" fn object(_this: *mut c_void, result: *mut *mut c_void) -> HRESULT { + RegisteredXamlType::write_optional_null(result) + } + + unsafe extern "system" fn full_name( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + RegisteredXamlType::write_hstring(result, "Microsoft.UI.Xaml.Controls.Control") + } + + unsafe extern "system" fn false_value(_this: *mut c_void, result: *mut u8) -> HRESULT { + RegisteredXamlType::write_bool(result, false) + } + + unsafe extern "system" fn true_value(_this: *mut c_void, result: *mut u8) -> HRESULT { + RegisteredXamlType::write_bool(result, true) + } + + unsafe extern "system" fn underlying( + _this: *mut c_void, + result: *mut AbiTypeName, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + result.write(AbiTypeName { + name: std::mem::transmute(HSTRING::from("Microsoft.UI.Xaml.Controls.Control")), + kind: TYPE_KIND_CUSTOM, + }); + S_OK + } + + unsafe extern "system" fn activate( + _this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if !result.is_null() { + *result = std::ptr::null_mut(); + } + E_NOTIMPL + } + + unsafe extern "system" fn create_from_string( + _this: *mut c_void, + _value: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::activate(std::ptr::null_mut(), result) + } + + unsafe extern "system" fn get_member( + _this: *mut c_void, + _name: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + RegisteredXamlType::write_optional_null(result) + } + + unsafe extern "system" fn add_vector( + _this: *mut c_void, + _instance: *mut c_void, + _value: *mut c_void, + ) -> HRESULT { + E_NOTIMPL + } + + unsafe extern "system" fn add_map( + _this: *mut c_void, + _instance: *mut c_void, + _key: *mut c_void, + _value: *mut c_void, + ) -> HRESULT { + E_NOTIMPL + } + + unsafe extern "system" fn initialize(_this: *mut c_void) -> HRESULT { + S_OK + } + + const VTABLE: XamlTypeVtbl = XamlTypeVtbl { + base: IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::qi, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: test_get_iids, + get_runtime_class_name: test_runtime_name, + get_trust_level: test_trust, + }, + get_base_type: Self::object, + get_content_property: Self::object, + get_full_name: Self::full_name, + get_is_array: Self::false_value, + get_is_collection: Self::false_value, + get_is_constructible: Self::true_value, + get_is_dictionary: Self::false_value, + get_is_markup_extension: Self::false_value, + get_is_bindable: Self::true_value, + get_item_type: Self::object, + get_key_type: Self::object, + get_boxed_type: Self::object, + get_underlying_type: Self::underlying, + activate_instance: Self::activate, + create_from_string: Self::create_from_string, + get_member: Self::get_member, + add_to_vector: Self::add_vector, + add_to_map: Self::add_map, + run_initializer: Self::initialize, + }; + + fn create() -> IUnknown { + let value = Box::new(Self { + vtable: &Self::VTABLE, + ref_count: windows_core::imp::WeakRefCount::new(), + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } + } + } + + #[repr(C)] + struct TestMetadataProvider { + vtable: *const XamlMetadataProviderVtbl, + ref_count: windows_core::imp::WeakRefCount, + base_type: IUnknown, + } + + impl TestMetadataProvider { + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + &*(this as *const Self) + } + + unsafe extern "system" fn qi( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID + || *iid == windows_core::IInspectable::IID + || *iid == IID_IXAML_METADATA_PROVIDER + { + *result = this; + Self::from_ptr(this).ref_count.add_ref(); + S_OK + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + Self::from_ptr(this).ref_count.add_ref() + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let remaining = Self::from_ptr(this).ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + } + + unsafe fn get(this: *mut c_void, name: &str, result: *mut *mut c_void) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + *result = std::ptr::null_mut(); + if name != "Microsoft.UI.Xaml.Controls.Control" { + return S_OK; + } + let base = Self::from_ptr(this).base_type.clone(); + *result = base.as_raw(); + std::mem::forget(base); + S_OK + } + + unsafe extern "system" fn get_type( + this: *mut c_void, + name: AbiTypeName, + result: *mut *mut c_void, + ) -> HRESULT { + Self::get(this, &hstring_from_abi(name.name), result) + } + + unsafe extern "system" fn get_name( + this: *mut c_void, + name: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + Self::get(this, &hstring_from_abi(name), result) + } + + unsafe extern "system" fn get_xmlns( + _this: *mut c_void, + count: *mut u32, + result: *mut *mut c_void, + ) -> HRESULT { + if count.is_null() || result.is_null() { + return E_POINTER; + } + *count = 0; + *result = std::ptr::null_mut(); + S_OK + } + + const VTABLE: XamlMetadataProviderVtbl = XamlMetadataProviderVtbl { + base: IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::qi, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: test_get_iids, + get_runtime_class_name: test_runtime_name, + get_trust_level: test_trust, + }, + get_xaml_type: Self::get_type, + get_xaml_type_by_full_name: Self::get_name, + get_xmlns_definitions: Self::get_xmlns, + }; + + fn create() -> IUnknown { + let value = Box::new(Self { + vtable: &Self::VTABLE, + ref_count: windows_core::imp::WeakRefCount::new(), + base_type: TestBaseXamlType::create(), + }); + unsafe { IUnknown::from_raw(Box::into_raw(value).cast()) } + } + } + + fn test_registration( + name: &str, + activator: XamlRuntimeClassActivator, + ) -> XamlRuntimeClassRegistration { + register_xaml_runtime_class( + name, + "Microsoft.UI.Xaml.Controls.Control", + windows_core::IInspectable::IID, + vec!["measure_override".to_string()], + activator, + ) + .unwrap() + } + + #[test] + fn registration_rejects_duplicates_and_unsupported_shapes() { + let activator: XamlRuntimeClassActivator = Arc::new(|| Ok(test_inspectable())); + assert!( + register_xaml_runtime_class( + "NotQualified", + "Microsoft.UI.Xaml.Controls.Control", + windows_core::IInspectable::IID, + Vec::new(), + activator.clone(), + ) + .is_err() + ); + assert!( + register_xaml_runtime_class( + "DynWinRT.Tests.BadGeneric`1", + "Microsoft.UI.Xaml.Controls.Control", + windows_core::IInspectable::IID, + Vec::new(), + activator.clone(), + ) + .is_err() + ); + assert!( + register_xaml_runtime_class( + "DynWinRT.Tests.DuplicateOverride", + "Microsoft.UI.Xaml.Controls.Control", + windows_core::IInspectable::IID, + vec!["measure_override".into(), "measure_override".into()], + activator.clone(), + ) + .is_err() + ); + + let registration = test_registration("DynWinRT.Tests.Duplicate", activator.clone()); + assert!( + register_xaml_runtime_class( + "DynWinRT.Tests.Duplicate", + "Microsoft.UI.Xaml.Controls.Control", + windows_core::IInspectable::IID, + Vec::new(), + activator, + ) + .is_err() + ); + assert!(registration.unregister()); + assert!(!registration.unregister()); + } + + #[test] + fn unregister_releases_callback_and_removes_lookup() { + struct DropMarker(Arc); + impl Drop for DropMarker { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let marker = DropMarker(drops.clone()); + let activator: XamlRuntimeClassActivator = Arc::new(move || { + let _ = ▮ + Ok(test_inspectable()) + }); + let registration = test_registration("DynWinRT.Tests.Lifetime", activator); + assert!( + registered_xaml_runtime_class("DynWinRT.Tests.Lifetime") + .unwrap() + .is_some() + ); + assert_eq!(drops.load(Ordering::SeqCst), 0); + assert!(registration.unregister()); + assert!( + registered_xaml_runtime_class("DynWinRT.Tests.Lifetime") + .unwrap() + .is_none() + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn provider_lookup_activates_with_controlling_identity_and_unregisters() { + let instance = test_inspectable(); + let expected_identity = instance.as_raw(); + let instance_ptr = instance.as_raw() as usize; + let activator: XamlRuntimeClassActivator = Arc::new(move || unsafe { + let pointer = instance_ptr as *mut c_void; + Ok(IUnknown::from_raw_borrowed(&pointer).unwrap().clone()) + }); + let registration = test_registration("DynWinRT.Tests.NamedControl", activator); + let host = XamlApplicationHost::new(TestMetadataProvider::create(), None); + let metadata = host.metadata_ptr(); + let name = HSTRING::from("DynWinRT.Tests.NamedControl"); + let mut xaml_type = std::ptr::null_mut(); + let hr = unsafe { + (XamlApplicationHost::METADATA_VTBL.get_xaml_type_by_full_name)( + metadata, + std::mem::transmute_copy(&name), + &mut xaml_type, + ) + }; + assert!(hr.is_ok()); + assert!(!xaml_type.is_null()); + + let vtable = unsafe { *(xaml_type as *const *const XamlTypeVtbl) }; + let mut full_name = HSTRING::new(); + assert!( + unsafe { + ((*vtable).get_full_name)( + xaml_type, + (&mut full_name as *mut HSTRING).cast::<*mut c_void>(), + ) + } + .is_ok() + ); + assert_eq!(full_name, "DynWinRT.Tests.NamedControl"); + + let mut activated = std::ptr::null_mut(); + assert!(unsafe { ((*vtable).activate_instance)(xaml_type, &mut activated) }.is_ok()); + assert!(!activated.is_null()); + let activated = unsafe { IUnknown::from_raw(activated) }; + assert_eq!(activated.as_raw(), expected_identity); + + unsafe { drop(IUnknown::from_raw(xaml_type)) }; + let mut by_type_name = std::ptr::null_mut(); + let hr = unsafe { + (XamlApplicationHost::METADATA_VTBL.get_xaml_type)( + metadata, + AbiTypeName { + name: std::mem::transmute_copy(&name), + kind: TYPE_KIND_CUSTOM, + }, + &mut by_type_name, + ) + }; + assert!(hr.is_ok()); + assert!(!by_type_name.is_null()); + + let mut unsupported_kind = 1usize as *mut c_void; + let hr = unsafe { + (XamlApplicationHost::METADATA_VTBL.get_xaml_type)( + metadata, + AbiTypeName { + name: std::mem::transmute_copy(&name), + kind: TYPE_KIND_METADATA, + }, + &mut unsupported_kind, + ) + }; + assert_eq!(hr, E_INVALIDARG); + assert!(unsupported_kind.is_null()); + + assert!(registration.unregister()); + let cached_vtable = unsafe { *(by_type_name as *const *const XamlTypeVtbl) }; + let mut cached_activation = std::ptr::null_mut(); + assert_eq!( + unsafe { ((*cached_vtable).activate_instance)(by_type_name, &mut cached_activation,) }, + RO_E_CLOSED + ); + assert!(cached_activation.is_null()); + unsafe { drop(IUnknown::from_raw(by_type_name)) }; + let mut missing = std::ptr::null_mut(); + let hr = unsafe { + (XamlApplicationHost::METADATA_VTBL.get_xaml_type_by_full_name)( + metadata, + std::mem::transmute_copy(&name), + &mut missing, + ) + }; + assert!(hr.is_ok()); + assert!(missing.is_null()); + } + + #[test] + fn activation_errors_fail_without_success_shaped_nulls() { + let activator: XamlRuntimeClassActivator = + Arc::new(|| Err(windows_core::Error::from_hresult(E_INVALIDARG))); + let registration = test_registration("DynWinRT.Tests.FailingControl", activator); + let entry = registered_xaml_runtime_class("DynWinRT.Tests.FailingControl") + .unwrap() + .unwrap(); + let base = TestBaseXamlType::create(); + let xaml_type = RegisteredXamlType::create(entry, base.clone(), Some(base)); + let vtable = unsafe { *(xaml_type.as_raw() as *const *const XamlTypeVtbl) }; + let mut result = 1usize as *mut c_void; + let hr = unsafe { ((*vtable).activate_instance)(xaml_type.as_raw(), &mut result) }; + assert_eq!(hr, E_INVALIDARG); + assert!(result.is_null()); + assert!(registration.unregister()); + + let wrong_base = register_xaml_runtime_class( + "DynWinRT.Tests.WrongBase", + "Microsoft.UI.Xaml.Controls.Control", + GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee), + Vec::new(), + Arc::new(|| Ok(test_inspectable())), + ) + .unwrap(); + let entry = registered_xaml_runtime_class("DynWinRT.Tests.WrongBase") + .unwrap() + .unwrap(); + let base = TestBaseXamlType::create(); + let xaml_type = RegisteredXamlType::create(entry, base.clone(), Some(base)); + let vtable = unsafe { *(xaml_type.as_raw() as *const *const XamlTypeVtbl) }; + let mut result = 1usize as *mut c_void; + let hr = unsafe { ((*vtable).activate_instance)(xaml_type.as_raw(), &mut result) }; + assert_eq!(hr, E_NOINTERFACE); + assert!(result.is_null()); + assert!(wrong_base.unregister()); + } + #[test] fn enables_per_monitor_v2_on_the_process_and_ui_thread() { enable_per_monitor_v2().unwrap(); diff --git a/samples/python/winui-tic-tac-toe-code-only/.gitignore b/samples/python/winui-tic-tac-toe-code-only/.gitignore new file mode 100644 index 00000000..002cc443 --- /dev/null +++ b/samples/python/winui-tic-tac-toe-code-only/.gitignore @@ -0,0 +1,4 @@ +generated/ +.runtime/ +__pycache__/ +*.py[cod] diff --git a/samples/python/winui-tic-tac-toe-code-only/README.md b/samples/python/winui-tic-tac-toe-code-only/README.md new file mode 100644 index 00000000..ea7ed6bc --- /dev/null +++ b/samples/python/winui-tic-tac-toe-code-only/README.md @@ -0,0 +1,59 @@ +# Python WinUI Tic-Tac-Toe (code-only) + +A polished, playable 3x3 Tic-Tac-Toe sample built entirely in Python with +generated WinUI 3 projections. `Application`, `Window`, every layout object, +grid definition, control, event handler, and game-state transition is created +programmatically. The sample uses the default Fluent control resources and a +Mica system backdrop; it does not load or register XAML. + +`MicaBackdrop` currently reaches an ambiguous composition-metadata closure when +generated directly. The sample therefore activates that runtime class through +its low-level `IMicaBackdropFactory.CreateInstance` ABI and safely wraps the +returned object as the projected `SystemBackdrop` expected by +`Window.system_backdrop`. + +## Prerequisites + +- Windows 11 on x64 with Python and Rust/Cargo available. +- An unpackaged **x64** WinAppSDK 2.3 fixture: `Microsoft.UI.Xaml.winmd`, a + newline-separated reference-WinMD list, and the matching x64 + `Microsoft.WindowsAppRuntime.Bootstrap.dll`. The matching x64 WinAppSDK + framework/runtime packages and resources must also be installed or available + to the unpackaged runtime. +- `dynwinrt_py` installed in the Python interpreter used to run the sample. +- A compatible `dynwinrt-codegen` executable, either on `PATH` or passed with + `-Codegen`. + +From the repository root, build codegen and install the Python runtime: + +```powershell +cargo build -p dynwinrt-codegen --release +Push-Location bindings\py +python -m pip install maturin +python -m maturin develop --release +Pop-Location +``` + +Generate the local projection package and copy the bootstrap DLL: + +```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 +``` + +If codegen is installed on `PATH`, omit `-Codegen`. Run with the Python +environment that contains `dynwinrt_py`: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe +``` + +Players alternate selecting cells. Choose **New game** after a win or draw to +reset the board. Closing the window exits the WinUI application and releases +projected objects deterministically. + +`generated\`, `.runtime\`, and Python caches are local artifacts and are not +tracked. diff --git a/samples/python/winui-tic-tac-toe-code-only/app.py b/samples/python/winui-tic-tac-toe-code-only/app.py new file mode 100644 index 00000000..3bbc60d0 --- /dev/null +++ b/samples/python/winui-tic-tac-toe-code-only/app.py @@ -0,0 +1,316 @@ +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_py import ( + DynWinRTMethodSig, + DynWinRTType, + DynWinRTValue, + RoApartment, + WinGUID, + init_winappsdk, + projected_lifetime_scope, +) +from generated.microsoft.ui.windowing import SizeInt32 +from generated.microsoft.ui.xaml import ( + Application, + ApplicationTheme, + GridUnitType, + HorizontalAlignment, + VerticalAlignment, + Window, +) +from generated.microsoft.ui.xaml.automation import AutomationProperties +from generated.microsoft.ui.xaml.controls import ( + Button, + ColumnDefinition, + CornerRadius, + FontWeight, + Grid, + GridLength, + RowDefinition, + StackPanel, + TextBlock, + Thickness, +) +from generated.microsoft.ui.xaml.media import SystemBackdrop + + +WINNING_LINES = ( + (0, 1, 2), + (3, 4, 5), + (6, 7, 8), + (0, 3, 6), + (1, 4, 7), + (2, 5, 8), + (0, 4, 8), + (2, 4, 6), +) + +IID_IMICA_BACKDROP = WinGUID.parse("c156a404-3dac-593a-b1f3-7a33c289dc83") +IID_IMICA_BACKDROP_FACTORY = WinGUID.parse( + "774379ce-74bd-59d4-849d-d99c4184d838" +) +IMICA_BACKDROP_FACTORY = DynWinRTType.register_interface( + "IMicaBackdropFactory", + IID_IMICA_BACKDROP_FACTORY, +).add_method( + "CreateInstance", + DynWinRTMethodSig() + .add_in(DynWinRTType.object()) + .add_out(DynWinRTType.object()) + .add_out( + DynWinRTType.runtime_class( + "Microsoft.UI.Xaml.Media.MicaBackdrop", + DynWinRTType.interface(IID_IMICA_BACKDROP), + ) + ), +) + + +def make_text( + text: str, + size: float, + weight: int = 400, + opacity: float = 1.0, +) -> TextBlock: + block = TextBlock() + block.text = text + block.font_size = size + block.font_weight = FontWeight(weight) + block.opacity = opacity + block.horizontal_alignment = HorizontalAlignment.Center + return block + + +def create_mica_backdrop() -> SystemBackdrop: + factory = DynWinRTValue.activation_factory( + "Microsoft.UI.Xaml.Media.MicaBackdrop" + ).cast(IID_IMICA_BACKDROP_FACTORY) + results = IMICA_BACKDROP_FACTORY.method(6).invoke_all( + factory, + [DynWinRTValue.null_value()], + ) + if len(results) != 2 or results[1].is_null(): + raise RuntimeError("MicaBackdrop composable activation returned no instance") + return SystemBackdrop(results[1]) + + +def run() -> None: + runtime = init_winappsdk(2, 3) + state: dict[str, object] = {} + + try: + with RoApartment(0), projected_lifetime_scope(): + + def initialize(_params: object) -> None: + def launched() -> None: + app = Application.get_current() + if app is None: + raise RuntimeError("Application.current is unavailable") + + resources = app.resources + merged = None if resources is None else resources.merged_dictionaries + if merged is None or len(merged) == 0: + raise RuntimeError("WinUI Fluent control resources are unavailable") + + root = StackPanel() + root.width = 520.0 + root.spacing = 14.0 + root.padding = Thickness(32.0, 28.0, 32.0, 28.0) + root.horizontal_alignment = HorizontalAlignment.Center + root.vertical_alignment = VerticalAlignment.Center + + title = make_text("Tic-Tac-Toe", 36.0, 600) + subtitle = make_text( + "Python · code-only WinUI 3 · Mica", + 14.0, + opacity=0.65, + ) + AutomationProperties.set_automation_id(title, "GameTitle") + AutomationProperties.set_automation_id(subtitle, "GameSubtitle") + + board_grid = Grid() + board_grid.width = 420.0 + board_grid.height = 420.0 + board_grid.row_spacing = 8.0 + board_grid.column_spacing = 8.0 + board_grid.margin = Thickness(0.0, 12.0, 0.0, 4.0) + board_grid.horizontal_alignment = HorizontalAlignment.Center + AutomationProperties.set_automation_id(board_grid, "GameBoard") + + row_definitions = board_grid.row_definitions + column_definitions = board_grid.column_definitions + children = board_grid.children + if ( + row_definitions is None + or column_definitions is None + or children is None + ): + raise RuntimeError("Grid collections are unavailable") + + star = GridLength(1.0, GridUnitType.Star) + for _ in range(3): + row = RowDefinition() + row.height = star + row_definitions.append(row) + + column = ColumnDefinition() + column.width = star + column_definitions.append(column) + + cells: list[Button] = [] + cell_text: list[TextBlock] = [] + for index in range(9): + button = Button() + button.horizontal_alignment = HorizontalAlignment.Stretch + button.vertical_alignment = VerticalAlignment.Stretch + button.corner_radius = CornerRadius(12.0, 12.0, 12.0, 12.0) + + mark = make_text("", 48.0, 600) + button.content = mark + Grid.set_row(button, index // 3) + Grid.set_column(button, index % 3) + AutomationProperties.set_automation_id(button, f"Cell{index}") + AutomationProperties.set_name(button, f"Cell {index + 1}, empty") + children.append(button) + cells.append(button) + cell_text.append(mark) + + status = make_text("Player X's turn", 18.0, 600) + status.margin = Thickness(0.0, 4.0, 0.0, 4.0) + AutomationProperties.set_automation_id(status, "GameStatus") + + reset_button = Button() + reset_label = make_text("New game", 14.0, 600) + reset_button.content = reset_label + reset_button.padding = Thickness(28.0, 8.0, 28.0, 8.0) + reset_button.horizontal_alignment = HorizontalAlignment.Center + AutomationProperties.set_automation_id(reset_button, "ResetButton") + AutomationProperties.set_name(reset_button, "New game") + + root_children = root.children + if root_children is None: + raise RuntimeError("StackPanel children are unavailable") + for child in (title, subtitle, board_grid, status, reset_button): + root_children.append(child) + + board = [""] * 9 + current_player = ["X"] + game_over = [False] + event_tokens = [] + + def reset_game( + _sender: object = None, + _args: object = None, + ) -> None: + board[:] = [""] * 9 + current_player[0] = "X" + game_over[0] = False + status.text = "Player X's turn" + for index, (button, mark) in enumerate( + zip(cells, cell_text) + ): + mark.text = "" + button.is_enabled = True + AutomationProperties.set_name( + button, f"Cell {index + 1}, empty" + ) + + def play(index: int) -> None: + if game_over[0] or board[index]: + return + + player = current_player[0] + board[index] = player + cell_text[index].text = player + cells[index].is_enabled = False + AutomationProperties.set_name( + cells[index], f"Cell {index + 1}, {player}" + ) + + winner = next( + ( + player + for a, b, c in WINNING_LINES + if board[a] == board[b] == board[c] != "" + ), + None, + ) + if winner is not None: + game_over[0] = True + status.text = f"Player {winner} wins!" + for cell in cells: + cell.is_enabled = False + return + + if all(board): + game_over[0] = True + status.text = "It's a draw" + return + + current_player[0] = "O" if player == "X" else "X" + status.text = f"Player {current_player[0]}'s turn" + + for index, button in enumerate(cells): + event_tokens.append( + button.on_click( + lambda _sender, _args, index=index: play(index) + ) + ) + event_tokens.append(reset_button.on_click(reset_game)) + + window = Window() + mica = create_mica_backdrop() + window.system_backdrop = mica + if window.system_backdrop is None: + raise RuntimeError("MicaBackdrop was not assigned") + + def closed(_sender: object, _args: object) -> None: + current = Application.get_current() + if current is not None: + current.exit() + + event_tokens.append(window.on_closed(closed)) + window.title = "Tic-Tac-Toe · dynwinrt Python · code-only" + window.content = root + window.activate() + + app_window = window.app_window + if app_window is not None: + app_window.resize(SizeInt32(620, 760)) + + state.update( + app=app, + window=window, + root=root, + cells=cells, + cell_text=cell_text, + status=status, + reset_button=reset_button, + event_tokens=event_tokens, + mica=mica, + ) + print( + f"Fluent resources: {len(merged)}; MicaBackdrop active", + flush=True, + ) + + app = Application.create(launched) + app.requested_theme = ApplicationTheme.Dark + state["app"] = app + + Application.start(initialize) + state.clear() + finally: + del runtime + + print("Exited cleanly", flush=True) + + +if __name__ == "__main__": + run() diff --git a/samples/python/winui-tic-tac-toe-code-only/generate.ps1 b/samples/python/winui-tic-tac-toe-code-only/generate.ps1 new file mode 100644 index 00000000..3bf5a952 --- /dev/null +++ b/samples/python/winui-tic-tac-toe-code-only/generate.ps1 @@ -0,0 +1,75 @@ +#!/usr/bin/env pwsh + +param( + [Parameter(Mandatory)] + [string]$WinuiWinmd, + + [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)) +} + +$WinuiWinmd = Resolve-CallerPath $WinuiWinmd +$RefList = Resolve-CallerPath $RefList +$BootstrapDll = Resolve-CallerPath $BootstrapDll + +foreach ($path in @($WinuiWinmd, $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 { + $command = Get-Command $Codegen -ErrorAction Stop + $codegenCommand = $command.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 + +$generations = @( + @("Microsoft.UI.Xaml", "Application,Window"), + @("Microsoft.UI.Xaml.Controls", "StackPanel,Grid,RowDefinition,ColumnDefinition,Button,TextBlock"), + @("Microsoft.UI.Xaml.Automation", "AutomationProperties") +) + +foreach ($generation in $generations) { + & $codegenCommand generate ` + --winmd $WinuiWinmd ` + --ref-list $RefList ` + --namespace $generation[0] ` + --class-name $generation[1] ` + --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 bindings in $output" +Write-Host "Copied the bootstrap DLL to $runtime" diff --git a/samples/python/winui-tic-tac-toe-code-only/run.ps1 b/samples/python/winui-tic-tac-toe-code-only/run.ps1 new file mode 100644 index 00000000..20edef25 --- /dev/null +++ b/samples/python/winui-tic-tac-toe-code-only/run.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh + +param( + [string]$Python = "python" +) + +$ErrorActionPreference = "Stop" +$generated = Join-Path $PSScriptRoot "generated\__init__.py" +$bootstrap = Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll" + +if (-not (Test-Path -LiteralPath $generated -PathType Leaf)) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (-not (Test-Path -LiteralPath $bootstrap -PathType Leaf)) { + 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") +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/samples/python/winui-tic-tac-toe/.gitignore b/samples/python/winui-tic-tac-toe/.gitignore new file mode 100644 index 00000000..a2f5e64a --- /dev/null +++ b/samples/python/winui-tic-tac-toe/.gitignore @@ -0,0 +1,3 @@ +generated/ +.runtime/ +__pycache__/ diff --git a/samples/python/winui-tic-tac-toe/README.md b/samples/python/winui-tic-tac-toe/README.md new file mode 100644 index 00000000..1b765337 --- /dev/null +++ b/samples/python/winui-tic-tac-toe/README.md @@ -0,0 +1,50 @@ +# Python WinUI Tic-Tac-Toe + +A polished Mica/Fluent 3x3 Tic-Tac-Toe window built from generated WinUI +projections. It demonstrates unpackaged WinAppSDK startup, XAML loading, events, +window resizing, a named Python `TicTacToePanel` XAML registration, a native +`measure_override`, and deterministic registration cleanup. + +## Prerequisites + +- Windows 11 on x64 with Python and Rust/Cargo available. +- An unpackaged **x64** WinAppSDK 2.3 fixture: `Microsoft.UI.Xaml.winmd`, a + newline-separated reference-WinMD list, and the matching x64 + `Microsoft.WindowsAppRuntime.Bootstrap.dll`. The matching x64 WinAppSDK + framework/runtime packages and resources must also be installed or available + to the unpackaged runtime. +- `dynwinrt_py` installed in the Python interpreter used to run the sample. +- A compatible `dynwinrt-codegen` executable, either on `PATH` or passed with + `-Codegen`. + +No published package is assumed. From the repository root, build the codegen +executable and install the runtime into the active Python environment: + +```powershell +cargo build -p dynwinrt-codegen --release +Push-Location bindings\py +python -m pip install maturin +python -m maturin develop --release +Pop-Location +``` + +From this sample directory, generate the local package and copy the bootstrap +DLL (replace the fixture paths): + +```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 +``` + +If the CLI is installed on `PATH`, omit `-Codegen`. Run with the same Python +environment that contains `dynwinrt_py`: + +```powershell +.\run.ps1 -Python C:\path\to\python.exe +``` + +`generated\`, `.runtime\`, and Python caches are local build artifacts and are +not tracked. diff --git a/samples/python/winui-tic-tac-toe/app.py b/samples/python/winui-tic-tac-toe/app.py new file mode 100644 index 00000000..3cfa5393 --- /dev/null +++ b/samples/python/winui-tic-tac-toe/app.py @@ -0,0 +1,279 @@ +import math +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_py import RoApartment, init_winappsdk, projected_lifetime_scope +from generated.microsoft.ui.windowing import SizeInt32 +from generated.microsoft.ui.xaml import Application, ApplicationTheme, Window +from generated.microsoft.ui.xaml.controls import Button, Size, StackPanel, TextBlock +from generated.microsoft.ui.xaml.markup import XamlReader + + +class TicTacToePanel(StackPanel): + measure_count = 0 + + def measure_override( + self, available_size: tuple[float, float] + ) -> tuple[float, float]: + """Handle WinUI's native layout callback in Python.""" + type(self).measure_count += 1 + width = available_size[0] + if not math.isfinite(width) or width <= 0: + width = 560.0 + width = min(width, 560.0) + + desired_width = 0.0 + desired_height = 0.0 + children = self.children + if children is not None: + for child in children: + if child is None: + continue + child.measure(Size(width, 1200.0)) + desired = child.desired_size + desired_width = max(desired_width, desired.width) + desired_height += desired.height + + return (max(desired_width, 480.0), max(desired_height, 640.0)) + + +WINNING_LINES = ( + (0, 1, 2), + (3, 4, 5), + (6, 7, 8), + (0, 3, 6), + (1, 4, 7), + (2, 5, 8), + (0, 4, 8), + (2, 4, 6), +) + + +def run() -> None: + runtime = init_winappsdk(2, 3) + state: dict[str, object] = {} + + try: + with RoApartment(0), projected_lifetime_scope(): + registration = StackPanel.register_xaml_runtime_class( + "DynWinRT.Example.TicTacToePanel", + TicTacToePanel, + ) + released = 0 + try: + + def initialize(_params: object) -> None: + def launched() -> None: + app = Application.get_current() + if app is None: + raise RuntimeError("Application.current is unavailable") + + value = XamlReader.load( + """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +