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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ jobs:
cd bindings/py
python -m venv .venv
.venv/Scripts/Activate.ps1
pip install pytest maturin "mypy>=1.13,<2" --quiet
pip install pytest maturin "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet
maturin build --quiet
pip install (Get-ChildItem ../../target/wheels/*.whl | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName --force-reinstall --quiet
- name: Test Python binding
Expand All @@ -291,8 +291,45 @@ jobs:
.\eng\release\python\test_generated_python_long_paths.ps1 `
-Python .\bindings\py\.venv\Scripts\python.exe `
-Codegen .\target\release\dynwinrt-codegen.exe
- name: Test generated implementation symbol identities
shell: pwsh
run: |
$env:DYNWINRT_TEST_PYTHON = (Resolve-Path .\bindings\py\.venv\Scripts\python.exe).Path
$env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1'
cargo test -p dynwinrt-codegen --test implementation_naming_test
- name: Run E2E tests
run: .\tests\e2e\e2e_test.ps1 -SkipBuild
# This optional-SDK behavioral smoke is separate from generated coverage
# totals. The receiver/GIL regressions also run in instrumented core and
# binding tests; no WinAppSDK runtime bootstrap or UI loop is needed here.
- name: Test metadata-generated dispatcher implementation
shell: pwsh
run: |
$packages = Join-Path $env:RUNNER_TEMP 'dispatcher-metadata'
nuget install Microsoft.WindowsAppSDK.InteractiveExperiences `
-Version 1.8.251104001 -OutputDirectory $packages -DirectDownload -NonInteractive
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$metadata = Join-Path $packages 'Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.251104001\metadata\10.0.18362.0'
$hashes = @{
'Microsoft.UI.winmd' = 'BA28DFC20E18630F3037AF2B91897082E41F1FA0E1DBB001D900505AB3577FE1'
'Microsoft.Foundation.winmd' = '56A37D003D6CD568B4BEFC95990AB28F576F128C00033C0372EAE390123F9C1F'
'Microsoft.Graphics.winmd' = '63165F774C2699E5A44E323F932A10BEE7BD5E11F25D82A730F5FB728107EA83'
}
foreach ($entry in $hashes.GetEnumerator()) {
if ((Get-FileHash -LiteralPath (Join-Path $metadata $entry.Key) -Algorithm SHA256).Hash -ne $entry.Value) {
throw "Unexpected WinAppSDK metadata: $($entry.Key)"
}
}
$windows = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\UnionMetadata" `
-Filter Windows.winmd -File -Recurse | Sort-Object FullName -Descending | Select-Object -First 1
if (-not $windows) { throw 'Windows SDK metadata is required for the dispatcher smoke' }
$output = Join-Path $PWD 'artifacts\dispatcher-implementation-smoke'
.\target\release\dynwinrt-codegen.exe generate `
--winmd (Join-Path $metadata 'Microsoft.UI.winmd') --ref $windows.FullName `
--namespace Microsoft.UI.Dispatching --class-name DispatcherQueue `
--lang py --output $output
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
.\bindings\py\.venv\Scripts\python.exe .\tests\e2e\runners\dispatcher_implementation_py.py --generated $output
- name: Test JS TSFN lifecycle and queue handling
working-directory: bindings/js
run: npm run test:tsfn
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@ names, native Python values, asyncio-compatible awaitables, and type stubs.
- [Python codegen package guide](tools/dynwinrt-codegen/python/README.md)
- [Python runtime guide](bindings/py/README.md)

### Implementing WinRT interfaces

Node.js and Python can supply synchronous handlers for complete non-generic
WinRT interfaces. Generated `.implementation(...)` descriptors compose multiple
interfaces into a standalone IInspectable object, and `.implement(...)` creates
its management handle. `impl.value` is a stable typed primary interface, and
`impl.dispose()` manages cleanup (Python also supports `with ... as impl`).
Public typed interface views can be passed to ordinary native
consumers without a WinUI composable base or OS registration.

The first release is non-agile and owner-thread-only. Reference release and
object-wide callback disposal are separate operations. See
[WinRT interface implementations](docs/guides/windows/winrt-interface-implementations.md)
for both language APIs, supported method/property/event/array/output contracts,
ownership, and the separate IBackgroundTask deployment concerns.

### WinUI `Application + Window`

When `Microsoft.UI.Xaml.Application` is selected, codegen emits helpers for
Expand Down
2 changes: 1 addition & 1 deletion bindings/js/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt"
crate-type = ["cdylib"]

[features]
test-hooks = ["dynwinrt/test-hooks", "windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_Media_Audio_Endpoints", "windows/Win32_UI_Shell_PropertiesSystem"]
test-hooks = ["dynwinrt/test-hooks", "windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/Win32_Media_Audio_Endpoints", "windows/Win32_UI_Shell_PropertiesSystem", "windows/ApplicationModel_Background"]

[dependencies]
napi = { version = "3", features = ["napi7"] }
Expand Down
108 changes: 108 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,112 @@ contains duplicate short names, each canonical module keeps its native symbol
name while the root barrel uses a namespace-qualified name, such as
`AIFoundationEmbeddingVector` or `SemanticSearchEmbeddingVector`.

### Standalone WinRT interface implementations

Metadata-generated standalone WinRT interfaces expose `implementation(handlers)`
and `implement(handlers, ...additionalDescriptors)`. The latter creates a native
instance and returns `DynWinRtImplementationHandle<GeneratedInterface>`:

```js
const impl = IBackgroundTask.implement(taskHandlers, {
interfaces: [[IStringable, textHandlers]],
})
try {
impl.value.run(instanceView)
} finally {
impl.dispose()
}
```

`.value` is a stable, lazily created typed primary view, managed by the handle.
`release()` releases its primary view and owner without disconnecting other
native references; `dispose()` additionally disconnects the object. Neither
allows `.value` to recreate a view afterward. The common pattern does not need
`releaseProjected(impl.value)`.
`GeneratedInterface.fromImplementation(impl)` remains the advanced,
independently owned view path; positional descriptors and raw native owners
remain supported. Low-level users must select an interface with
`value.cast(iid)` before invoking that interface's method handles: `toValue()`
returns the canonical `IInspectable`, not an arbitrary interface's vtable.
These are local, synchronous, non-agile WinRT objects, not COM class
registrations or OS background-task registrations.

The npm root also exports the low-level primitives for metadata-driven callers:

```ts
DynWinRtInterfacePlan.create(name, interfaceType, [
{ name: 'ToString', vtableIndex: 6, signature },
], requiredIids)

DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => {
return [DynWinRtValue.hstring('implemented in JavaScript')]
}, runtimeClassName)
```

Plans must describe each complete interface, including every contiguous native
slot starting at 6. Required interfaces need separate plans. The dispatcher
receives `DynWinRtValue[]` and must return an array of **all** outputs in signature
order (`[]` for void). Fill-array inputs are capacities; their returned arrays
must have exactly that length. Async functions, promises, and thenable results
are unsupported. Dispatch errors fail the native call; `takeError()` returns and
clears the latest diagnostic, or `null` when there is none.

In this low-level callback API, incoming reference values own retained native
references. A callback that rejects an input without retaining it should release
that `DynWinRtValue`, including on a throwing path. Waiting for garbage collection
can keep a delegate's event-loop resource alive. Conversely, a value deliberately
retained before throwing stays valid until explicitly released or collected.
This is not a requirement to release hidden arguments of generated typed
handlers: the generated adapters retain their own conversion/lifetime contract.

Low-level owner `release()` and garbage collection drop only its native reference.
Separately retained native values keep their callbacks alive. `disconnect()`
closes every view while retaining the owner reference; `dispose()` disconnects
and releases it, and both are idempotent. Disposing during a callback allows that
active invocation to finish safely. `isClosed` describes object-wide callback
disconnection, not merely whether this owner was released.

**Always dispose deterministically when handlers capture their owner or a native
view.** Such cross-runtime cycles cannot be collected by JavaScript alone.
Disposal breaks native callback roots; final reference cleanup runs on a later
event-loop turn. Cleanup TSFNs do not keep Node alive. Environment shutdown
disconnects all live implementations before releasing handler references, and
callbacks from other threads fail rather than touching the JS environment.

Native delegates received by an implementation can be invoked with
`value.invokeDelegate(iid, signature, args)`. For repeated calls, cache a
`DynWinRtDelegateMethod.create(iid, signature)` and use its `invoke(value, args)`
method instead. Both query the metadata's concrete delegate IID, retain the
managed values for the call, and return all outputs in signature order (`[]` for void). Delegate
`Invoke` occupies `IUnknown` slot 3; do not register it as an ordinary slot-6
WinRT interface method. The IID and full signature must come from delegate
metadata, including concrete type arguments for generic delegates. This helper
uses only the WinRT call planner and performs no COM registration.
Its arguments follow the existing outbound `invokeAll()` contract: a fill-array
input is a preallocated, correctly typed `DynWinRtArray.toValue()`, not a U32
capacity value. Only reverse-entry implementation handlers receive capacities.
Generated callable delegate bridges must allocate this outbound storage before
invoking the helper.

`DynWinRtDelegate.release()` deterministically drops the creator's native
reference, without disconnecting references retained by a native event source.
Event registration code must release its temporary `toValue()` result and the
creator in `finally` after the add call, on success and failure. A successful
event source owns the delegate independently until removal. Retaining a creator
in the same closure context as its native callback can otherwise form a
cross-runtime cycle and keep the delegate's referenced TSFN alive after
unsubscribe. Releasing the creator twice is harmless; `toValue()` after release
throws. This does not unref active event callbacks or force process exit.

For metadata whose native type is HRESULT, use `DynWinRtValue.fromHResult(code)`
(also available as `hresult(code)`)
or `DynWinRtArray.fromHresultValues(codes)` to preserve its semantic type,
especially for array parameters. Codes must be signed 32-bit integers (for
example, `0x80004005 | 0`). These factories do not change the existing `i32()`
or `fromI32Values()` behavior. Read results with `toNumber()` or `toI32Vec()`.

### Classic COM

Classic COM is a preview under active development. It uses a separate subpath
from the same package, keeping the WinRT root API unchanged:

Expand All @@ -91,6 +197,8 @@ See the repository's
codegen, current coverage and limitations, GUID/IID/CLSID, lifetime, Automation,
and `/com/unsafe` examples.

### Generated WinRT values

Unambiguous public WinRT activation metadata is projected as JavaScript constructors.
Parameterized and composable activations support idiomatic forms such as
`new Uri(base, relative)` and `new StackPanel()`. The generated static factory
Expand Down
5 changes: 4 additions & 1 deletion bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => {

test('package facades exactly partition native exports', (t) => {
const nativeKeys = moduleKeys(nativeRuntime)
const expectedWinrt = nativeKeys.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom')
const expectedWinrt = [
...nativeKeys.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom'),
'DynWinRtImplementationHandle',
].sort()
const safeComNames = new Set([
'DynComDispatchParams',
'DynComAllocation',
Expand Down
139 changes: 139 additions & 0 deletions bindings/js/__test__/winrt-event-lifetime-child.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import assert from 'node:assert/strict'
import {
DynWinRtDelegate,
DynWinRtImplementation,
DynWinRtInterfacePlan,
DynWinRtMethodSig,
DynWinRtStruct,
DynWinRtType,
DynWinRtValue,
WinGuid,
roInitialize,
} from '../dist/winrt.js'

roInitialize(1)
const mode = process.argv[2]
const referenceIid = WinGuid.parse('fbc4dd29-245b-11e4-af98-689423260cf8')
const closableIid = WinGuid.parse('30d5a829-7fa4-4026-83bb-d75bae4ea99e')
const delegateType = DynWinRtType.parameterized(
WinGuid.parse('9de1c534-6ae1-11e0-84e1-18a905bcc53f'),
[DynWinRtType.interface(referenceIid), DynWinRtType.object()],
)
const delegateIid = delegateType.iid()
const delegateArgs = [DynWinRtType.interface(referenceIid), DynWinRtType.object()]
const invokeSignature = new DynWinRtMethodSig().addIn(delegateArgs[0]).addIn(delegateArgs[1])
const tokenType = DynWinRtType.structType('Windows.Foundation.EventRegistrationToken', [DynWinRtType.i64()])
const methods = [
{ name: 'get_Capacity', vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.u32()) },
{ name: 'add_Closed', vtableIndex: 7, signature: new DynWinRtMethodSig().addIn(delegateType).addOut(tokenType) },
{ name: 'remove_Closed', vtableIndex: 8, signature: new DynWinRtMethodSig().addIn(tokenType) },
]
let referenceType = DynWinRtType.registerInterface('Windows.Foundation.IMemoryBufferReference', referenceIid)
for (const method of methods) referenceType = referenceType.addMethod(method.name, method.signature)
const closeSignature = new DynWinRtMethodSig()
const closableType = DynWinRtType.registerInterface('Windows.Foundation.IClosable', closableIid)
.addMethod('Close', closeSignature)
const referencePlan = DynWinRtInterfacePlan.create(
'Windows.Foundation.IMemoryBufferReference', referenceType, methods, [closableIid],
)
const closePlan = DynWinRtInterfacePlan.create('Windows.Foundation.IClosable', closableType, [
{ name: 'Close', vtableIndex: 6, signature: closeSignature },
])

let retained
let sender
let delivered = 0
let removed = 0
const owner = DynWinRtImplementation.create([referencePlan, closePlan], (index, slot, args) => {
if (index === 1) {
retained?.invokeDelegate(delegateIid, invokeSignature, [sender, DynWinRtValue.nullValue()])
return []
}
if (slot === 6) return [DynWinRtValue.u32(4096)]
if (slot === 7) {
if (mode === 'add-failure') {
// Low-level callback arguments own retained references. This rejecting
// source keeps none; release its input rather than waiting for V8 GC.
args[0].release()
throw new Error('expected subscription rejection')
}
retained = args[0]
if (mode === 'add-failure-retained') throw new Error('expected subscription rejection')
const token = DynWinRtStruct.create(tokenType)
token.setI64(0, 1n)
return [token.toValue()]
}
assert.equal(args[0].asStruct().getI64(0), 1n)
retained.release()
retained = undefined
removed++
return []
})
const canonical = owner.toValue()
sender = canonical.cast(referenceIid)
const closer = canonical.cast(closableIid)
canonical.release()

function onClosed(callback) {
// Mirror generated events: sibling closures share the context containing
// wrapped, handler, and the returned unsubscribe closure.
const wrapped = (nativeSender, args) => callback(nativeSender, args)
const handler = DynWinRtDelegate.create(delegateIid, delegateArgs, wrapped)
let value
let token
try {
value = handler.toValue()
token = referenceType.method(7).invoke(sender, [value])
} finally {
value?.release()
handler.release()
}
return () => {
void handler
referenceType.method(8).invoke(sender, [token])
}
}

try {
if (mode === 'add-failure' || mode === 'add-failure-retained') {
assert.throws(() => onClosed(() => { delivered++ }), /expected subscription rejection/)
if (mode === 'add-failure-retained') {
assert.ok(retained)
retained.invokeDelegate(delegateIid, invokeSignature, [sender, DynWinRtValue.nullValue()])
assert.equal(delivered, 1)
retained.release()
retained = undefined
} else {
assert.equal(retained, undefined)
assert.equal(delivered, 0)
}
} else {
assert.ok(mode === 'remove' || mode === 'once')
const unsubscribe = onClosed((nativeSender, args) => {
assert.equal(referenceType.method(6).invoke(nativeSender, []).toNumber(), 4096)
assert.equal(args.isNull(), true)
delivered++
if (mode === 'once') unsubscribe()
})
// Keeping the unsubscribe function reachable must not keep an unsubscribed
// native delegate alive. No GC or forced process exit is used in this test.
globalThis.retainedUnsubscribe = unsubscribe
owner.release()
closableType.method(6).invokeAll(closer, [])
assert.equal(delivered, 1)
if (mode === 'remove') unsubscribe()
assert.equal(removed, 1)
assert.equal(retained, undefined)
closableType.method(6).invokeAll(closer, [])
assert.equal(delivered, 1)
}
} finally {
retained?.release()
sender.release()
closer.release()
owner.dispose()
}
console.log(`generated-event-lifetime-ok:${mode}`)
Loading
Loading