From 9640f65cd426c2af3fee6914df49c1cd678ba0eb Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 2 Sep 2026 23:58:54 +0800 Subject: [PATCH 1/2] Add explicit WinRT property unboxing helpers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/README.md | 23 +++ bindings/js/__test__/index.spec.ts | 108 ++++++++++++ bindings/js/package-lock.json | 18 ++ bindings/js/package.json | 1 + bindings/js/src/lib.rs | 128 +++++++++++++- bindings/py/README.md | 22 +++ bindings/py/dynwinrt.pyi | 25 ++- bindings/py/src/lib.rs | 2 + bindings/py/src/runtime.rs | 95 ++++++++++- bindings/py/tests/test_e2e_winrt.py | 102 +++++++++++ crates/dynwinrt/src/lib.rs | 4 + crates/dynwinrt/src/property_value.rs | 233 ++++++++++++++++++++++++++ 12 files changed, 758 insertions(+), 3 deletions(-) create mode 100644 crates/dynwinrt/src/property_value.rs diff --git a/bindings/js/README.md b/bindings/js/README.md index 0ad1b018..b386b2b0 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -125,6 +125,29 @@ converting a raw value to a generated runtime class. A failed QueryInterface is reported as an error. Internal generated `_fromNative()` paths consume native return values; application code should use `projectAs()` instead. +### Explicit boxed-value unboxing + +Generic WinRT `Object`/`IInspectable` results remain raw `DynWinRtValue` +instances. Use `unboxObject()` only where the application expects a boxed +`Windows.Foundation.IPropertyValue`, such as values from +`DeviceInformation.properties`: + +```js +import { unboxObject } from '@microsoft/dynwinrt' + +const raw = deviceInformation.properties.get('System.Devices.DeviceInstanceId') +const instanceId = unboxObject(raw) +``` + +The helper borrows its argument. It maps supported numeric, Boolean, string, +character, GUID, and corresponding array property types to JavaScript values; +`Int64` and `UInt64` use `bigint`, GUIDs use strings, and `UInt8Array` uses +`Uint8Array`. `null` stays `null`. If the object does not implement +`IPropertyValue`, the exact same JavaScript object is returned, so identity and +later projection remain intact. Unsupported property types (including +`DateTime`, `TimeSpan`, geometry, inspectable, and other types) and native getter +failures throw. + Generated WinUI `IElementFactory` bindings expose `IElementFactory.create()`. It creates a synchronous, UI-thread factory backed by JavaScript `getElement`/`recycleElement` callbacks. Call `releaseCallbacks()` on the diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 24bc4a74..af849ed4 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -20,6 +20,7 @@ import { getWindowsDirectory, hasPackageIdentity, roInitialize, + unboxObject, } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' import * as comRuntime from '../dist/com.js' @@ -748,6 +749,113 @@ test('invoke WinRT through dynamic metadata', (t) => { t.is(uriType.methodByName('get_AbsoluteUri').invoke(uri, []).toString(), expected) }) +test('explicitly unbox WinRT property values without changing raw objects', (t) => { + roInitialize(1) + const staticsIid = WinGuid.parse('629bdbc8-d932-4ff4-96b9-8d96c5c1e858') + const objectType = DynWinRtType.object() + const methods: Array<[string, InstanceType]> = [ + ['CreateEmpty', new DynWinRtMethodSig().addOut(objectType)], + ['CreateUInt8', new DynWinRtMethodSig().addIn(DynWinRtType.u8()).addOut(objectType)], + ['CreateInt16', new DynWinRtMethodSig().addIn(DynWinRtType.i16()).addOut(objectType)], + ['CreateUInt16', new DynWinRtMethodSig().addIn(DynWinRtType.u16()).addOut(objectType)], + ['CreateInt32', new DynWinRtMethodSig().addIn(DynWinRtType.i32()).addOut(objectType)], + ['CreateUInt32', new DynWinRtMethodSig().addIn(DynWinRtType.u32()).addOut(objectType)], + ['CreateInt64', new DynWinRtMethodSig().addIn(DynWinRtType.i64()).addOut(objectType)], + ['CreateUInt64', new DynWinRtMethodSig().addIn(DynWinRtType.u64()).addOut(objectType)], + ['CreateSingle', new DynWinRtMethodSig().addIn(DynWinRtType.f32()).addOut(objectType)], + ['CreateDouble', new DynWinRtMethodSig().addIn(DynWinRtType.f64()).addOut(objectType)], + ['CreateChar16', new DynWinRtMethodSig().addIn(DynWinRtType.char16()).addOut(objectType)], + ['CreateBoolean', new DynWinRtMethodSig().addIn(DynWinRtType.boolType()).addOut(objectType)], + ['CreateString', new DynWinRtMethodSig().addIn(DynWinRtType.hstring()).addOut(objectType)], + ['CreateInspectable', new DynWinRtMethodSig().addIn(objectType).addOut(objectType)], + ['SkippedCreateGuid', new DynWinRtMethodSig()], + [ + 'CreateDateTime', + new DynWinRtMethodSig() + .addIn(DynWinRtType.structType('Windows.Foundation.DateTime', [DynWinRtType.i64()])) + .addOut(objectType), + ], + ['SkippedCreateTimeSpan', new DynWinRtMethodSig()], + ['SkippedCreatePoint', new DynWinRtMethodSig()], + ['SkippedCreateSize', new DynWinRtMethodSig()], + ['SkippedCreateRect', new DynWinRtMethodSig()], + ['CreateUInt8Array', new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.u8())).addOut(objectType)], + ['SkippedCreateInt16Array', new DynWinRtMethodSig()], + ['SkippedCreateUInt16Array', new DynWinRtMethodSig()], + ['CreateInt32Array', new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.i32())).addOut(objectType)], + ['SkippedCreateUInt32Array', new DynWinRtMethodSig()], + ['SkippedCreateInt64Array', new DynWinRtMethodSig()], + ['SkippedCreateUInt64Array', new DynWinRtMethodSig()], + ['SkippedCreateSingleArray', new DynWinRtMethodSig()], + ['SkippedCreateDoubleArray', new DynWinRtMethodSig()], + [ + 'CreateChar16Array', + new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.char16())).addOut(objectType), + ], + ] + let staticsType = DynWinRtType.registerInterface('IPropertyValueStaticsUnboxTest', staticsIid) + for (const [name, signature] of methods) { + staticsType = staticsType.addMethod(name, signature) + } + const factory = DynWinRtValue.activationFactory('Windows.Foundation.PropertyValue').cast(staticsIid) + + const boxedString = staticsType.methodByName('CreateString').invoke(factory, [DynWinRtValue.hstring('BLE Device')]) + const boxedInt64 = staticsType.methodByName('CreateInt64').invoke(factory, [DynWinRtValue.i64(-(2n ** 63n))]) + const boxedChar = staticsType.methodByName('CreateChar16').invoke(factory, [DynWinRtValue.u16(0xd800)]) + const boxedBytes = staticsType + .methodByName('CreateUInt8Array') + .invoke(factory, [DynWinRtArray.fromU8Values([0, 1, 127, 255]).toValue()]) + const boxedInts = staticsType + .methodByName('CreateInt32Array') + .invoke(factory, [DynWinRtArray.fromI32Values([-1, 0, 42]).toValue()]) + const boxedChars = staticsType + .methodByName('CreateChar16Array') + .invoke(factory, [DynWinRtArray.fromU16Values([0xd800, 0x61]).toValue()]) + + t.is(unboxObject(boxedString), 'BLE Device') + t.is(unboxObject(boxedInt64), -(2n ** 63n)) + t.is((unboxObject(boxedChar) as string).charCodeAt(0), 0xd800) + t.deepEqual([...(unboxObject(boxedBytes) as Uint8Array)], [0, 1, 127, 255]) + t.deepEqual(unboxObject(boxedInts), [-1, 0, 42]) + t.deepEqual( + (unboxObject(boxedChars) as string[]).map((value) => value.charCodeAt(0)), + [0xd800, 0x61], + ) + t.is(unboxObject(null), null) + t.is(unboxObject(DynWinRtValue.nullValue()), null) + + const uriFactory = DynWinRtValue.activationFactory('Windows.Foundation.Uri') + const identity = uriFactory.identityRaw() + t.is(unboxObject(uriFactory), uriFactory) + t.is(uriFactory.identityRaw(), identity) + + const dateTime = DynWinRtStruct.create(DynWinRtType.structType('Windows.Foundation.DateTime', [DynWinRtType.i64()])) + dateTime.setI64(0, 0n) + const unsupported = staticsType.methodByName('CreateDateTime').invoke(factory, [dateTime.toValue()]) + t.throws(() => unboxObject(unsupported), { message: /Unsupported WinRT IPropertyValue type/ }) + + const keyType = DynWinRtType.hstring() + const propertyMap = DynWinRtValue.createMap( + [DynWinRtValue.hstring('System.Devices.DeviceInstanceId')], + [boxedString], + keyType, + objectType, + ) + const mapType = DynWinRtType.parameterized(WinGuid.parse('3c2925fe-8519-45c1-aa79-197b6718c1c1'), [ + keyType, + objectType, + ]) + const mapInterface = DynWinRtType.registerInterface('IMap_String_Object_UnboxTest', mapType.iid()).addMethod( + 'Lookup', + new DynWinRtMethodSig().addIn(keyType).addOut(objectType), + ) + const deviceProperty = mapInterface + .methodByName('Lookup') + .invoke(propertyMap.cast(mapType.iid()), [DynWinRtValue.hstring('System.Devices.DeviceInstanceId')]) + t.is(unboxObject(deviceProperty), 'BLE Device') + t.is(unboxObject(boxedString), 'BLE Device') +}) + test('resolve WinRT async operations through the Node event loop', async (t) => { roInitialize(1) const staticsIid = WinGuid.parse('5984c710-daf2-43c8-8bb4-a4d3eacfd03f') diff --git a/bindings/js/package-lock.json b/bindings/js/package-lock.json index 7b19b7d9..8d6bb87e 100644 --- a/bindings/js/package-lock.json +++ b/bindings/js/package-lock.json @@ -16,6 +16,7 @@ "@oxc-node/core": "^0.0.35", "@taplo/cli": "^0.7.0", "@tybys/wasm-util": "^0.10.0", + "@types/node": "^24.13.3", "ava": "^6.4.1", "c8": "12.0.0", "chalk": "^5.6.2", @@ -2658,6 +2659,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "24.13.3", + "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/node/-/node-24.13.3.tgz", + "integrity": "sha1-SfGL08ZHhm3NpRoHVsFF4UWQzhY=", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, "node_modules/@vercel/nft": { "version": "0.29.4", "resolved": "https://registry.npmjs.org/@vercel/nft/-/nft-0.29.4.tgz", @@ -5652,6 +5663,13 @@ "node": ">=14.17" } }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha1-KTV6iee3ykrvO/D9P9DNc4hCKek=", + "dev": true, + "license": "MIT" + }, "node_modules/unicorn-magic": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", diff --git a/bindings/js/package.json b/bindings/js/package.json index 141f02c0..4cb7e5a3 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -93,6 +93,7 @@ "@oxc-node/core": "^0.0.35", "@taplo/cli": "^0.7.0", "@tybys/wasm-util": "^0.10.0", + "@types/node": "^24.13.3", "ava": "^6.4.1", "c8": "12.0.0", "chalk": "^5.6.2", diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 8efd292a..e212aea9 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -11,7 +11,7 @@ use std::{ }; use dynwinrt; -use napi::bindgen_prelude::{BigInt, Either, PromiseRaw}; +use napi::bindgen_prelude::{BigInt, Either, FromNapiValue, PromiseRaw, ToNapiValue, Unknown}; use napi::Env; use napi_derive::napi; use windows::core::{IUnknown, Interface, HSTRING}; @@ -172,6 +172,132 @@ fn js_safe_i64(value: i64, context: &str) -> napi::Result { "{context}: value is outside the JavaScript safe-integer range; use the bigint conversion instead", ))); } + + fn property_value_guid(value: windows::core::GUID) -> String { + format!("{value:?}") + } + + fn to_unknown<'env, T: ToNapiValue>(env: Env, value: T) -> napi::Result> { + let value = unsafe { T::to_napi_value(env.raw(), value) }?; + unsafe { Unknown::from_napi_value(env.raw(), value) } + } + + fn utf16_unknown<'env>(env: Env, value: &[u16]) -> napi::Result> { + let length = isize::try_from(value.len()) + .map_err(|_| napi::Error::from_reason("WinRT Char16 string is too large for JavaScript"))?; + let mut result = std::ptr::null_mut(); + napi::check_status!( + unsafe { + napi::sys::napi_create_string_utf16(env.raw(), value.as_ptr(), length, &mut result) + }, + "Failed to create JavaScript UTF-16 string" + )?; + unsafe { Unknown::from_napi_value(env.raw(), result) } + } + + fn utf16_array_unknown<'env>(env: Env, values: Vec) -> napi::Result> { + let mut result = std::ptr::null_mut(); + napi::check_status!( + unsafe { napi::sys::napi_create_array_with_length(env.raw(), values.len(), &mut result) }, + "Failed to create JavaScript Char16 array" + )?; + for (index, value) in values.into_iter().enumerate() { + let value = utf16_unknown(env, &[value])?; + napi::check_status!( + unsafe { + napi::sys::napi_set_element(env.raw(), result, index as u32, napi::JsValue::raw(&value)) + }, + "Failed to populate JavaScript Char16 array" + )?; + } + unsafe { Unknown::from_napi_value(env.raw(), result) } + } + + fn null_unknown<'env>(env: Env) -> napi::Result> { + let mut value = std::ptr::null_mut(); + napi::check_status!( + unsafe { napi::sys::napi_get_null(env.raw(), &mut value) }, + "Failed to create JavaScript null" + )?; + unsafe { Unknown::from_napi_value(env.raw(), value) } + } + + fn property_value_to_javascript<'env>( + env: Env, + value: dynwinrt::PropertyValueData, + ) -> napi::Result> { + use dynwinrt::PropertyValueData; + + match value { + PropertyValueData::UInt8(value) => to_unknown(env, u32::from(value)), + PropertyValueData::Int16(value) => to_unknown(env, i32::from(value)), + PropertyValueData::UInt16(value) => to_unknown(env, u32::from(value)), + PropertyValueData::Int32(value) => to_unknown(env, value), + PropertyValueData::UInt32(value) => to_unknown(env, value), + PropertyValueData::Int64(value) => to_unknown(env, BigInt::from(value)), + PropertyValueData::UInt64(value) => to_unknown(env, BigInt::from(value)), + PropertyValueData::Single(value) => to_unknown(env, value), + PropertyValueData::Double(value) => to_unknown(env, value), + PropertyValueData::Char16(value) => utf16_unknown(env, &[value]), + PropertyValueData::Boolean(value) => to_unknown(env, value), + PropertyValueData::String(value) => to_unknown(env, value), + PropertyValueData::Guid(value) => to_unknown(env, property_value_guid(value)), + PropertyValueData::UInt8Array(value) => { + to_unknown(env, napi::bindgen_prelude::Buffer::from(value)) + } + PropertyValueData::Int16Array(value) => { + to_unknown(env, value.into_iter().map(i32::from).collect::>()) + } + PropertyValueData::UInt16Array(value) => { + to_unknown(env, value.into_iter().map(u32::from).collect::>()) + } + PropertyValueData::Int32Array(value) => to_unknown(env, value), + PropertyValueData::UInt32Array(value) => to_unknown(env, value), + PropertyValueData::Int64Array(value) => { + to_unknown(env, value.into_iter().map(BigInt::from).collect::>()) + } + PropertyValueData::UInt64Array(value) => { + to_unknown(env, value.into_iter().map(BigInt::from).collect::>()) + } + PropertyValueData::SingleArray(value) => to_unknown(env, value), + PropertyValueData::DoubleArray(value) => to_unknown(env, value), + PropertyValueData::Char16Array(value) => utf16_array_unknown(env, value), + PropertyValueData::BooleanArray(value) => to_unknown(env, value), + PropertyValueData::StringArray(value) => to_unknown(env, value), + PropertyValueData::GuidArray(value) => to_unknown( + env, + value + .into_iter() + .map(property_value_guid) + .collect::>(), + ), + } + } + + /// Explicitly unbox a supported WinRT `IPropertyValue`. + /// + /// JavaScript `null` and WinRT null are returned as `null`. A non-`IPropertyValue` + /// `DynWinRtValue` is returned unchanged, preserving JavaScript and COM identity. + #[napi( + ts_args_type = "value: DynWinRtValue | null", + ts_return_type = "boolean | number | bigint | string | Uint8Array | number[] | bigint[] | boolean[] | string[] | DynWinRtValue | null" + )] + pub fn unbox_object<'env>(env: Env, value: Unknown<'env>) -> napi::Result> { + if value.get_type()? == napi::ValueType::Null { + return Ok(value); + } + + let raw = unsafe { + <&DynWinRTValue as FromNapiValue>::from_napi_value(env.raw(), napi::JsValue::raw(&value)) + }?; + match dynwinrt::unbox_property_value(&raw.0) + .map_err(|error| napi::Error::from_reason(error.message()))? + { + dynwinrt::PropertyValueUnboxResult::Null => null_unknown(env), + dynwinrt::PropertyValueUnboxResult::NotPropertyValue => Ok(value), + dynwinrt::PropertyValueUnboxResult::Value(value) => property_value_to_javascript(env, value), + } + } Ok(value) } diff --git a/bindings/py/README.md b/bindings/py/README.md index 69f0796e..ae1d8fad 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -114,6 +114,28 @@ produce a wrapper unless the input actually implements that default interface. Incompatible types raise the ordinary WinRT `OSError`. Static-only metadata classes with no instance surface are not projection targets. +### Explicit boxed-value unboxing + +Generic WinRT `Object`/`IInspectable` results remain raw `DynWinRTValue` +instances. Use `unbox_object()` only where the application expects a boxed +`Windows.Foundation.IPropertyValue`, such as values from +`DeviceInformation.properties`: + +```python +from dynwinrt import unbox_object + +raw = device_information.properties["System.Devices.DeviceInstanceId"] +instance_id = unbox_object(raw) +``` + +The helper borrows its argument. It maps supported numeric, Boolean, string, +character, GUID, and corresponding array property types to Python values; +64-bit integers use `int`, GUIDs use `uuid.UUID`, and `UInt8Array` uses `bytes`. +`None` stays `None`. If the object does not implement `IPropertyValue`, the +exact same Python object is returned, so identity and later projection remain +intact. Unsupported property types (including `DateTime`, `TimeSpan`, geometry, +inspectable, and other types) and native getter failures raise an exception. + Use `wrapper.as_interface(InterfaceClass)` when converting an existing wrapper to an interface view. Use `InterfaceClass.from_value(raw)` for a raw `DynWinRTValue`. Do not call the internal `_from_native()` method from diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 42432ff7..da5ed508 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,4 +1,5 @@ -from typing import Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final +from typing import Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload +from uuid import UUID _T = TypeVar("_T", covariant=True) _P = TypeVar("_P", covariant=True) @@ -38,6 +39,7 @@ __all__ = [ "projected_lifetime_scope", "project_as", "release_projected", + "unbox_object", "init_winappsdk", "ro_initialize", "ro_uninitialize", @@ -111,6 +113,27 @@ def project_as( def release_projected(value: object) -> None: ... +_UnboxedPropertyValue = Union[ + bool, + int, + float, + str, + UUID, + bytes, + List[int], + List[float], + List[bool], + List[str], + List[UUID], +] + +@overload +def unbox_object(value: None) -> None: ... +@overload +def unbox_object( + value: "DynWinRTValue", +) -> Union[_UnboxedPropertyValue, "DynWinRTValue", None]: ... + @final class WinGUID: diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 8353ad20..5fadc18c 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -496,6 +496,7 @@ 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::unbox_object, m)?)?; m.add_function(wrap_pyfunction!( super::runtime::register_xaml_runtime_class, m @@ -516,6 +517,7 @@ for _name in ( 'projected_lifetime_scope', 'project_as', 'release_projected', + 'unbox_object', ): if _name not in __all__: __all__.append(_name) diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index a2029aba..04d1f61a 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use dynwinrt; use pyo3::exceptions::{PyIndexError, PyOverflowError, PyRuntimeError, PyTypeError}; use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::{PyBytes, PyDict, PyList}; use windows::core::{GUID, HSTRING, IUnknown, Interface}; use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_windows_error}; @@ -210,6 +210,99 @@ pub fn ro_uninitialize() { unsafe { RoUninitialize() }; } +fn python_uuid(py: Python<'_>, value: GUID) -> PyResult> { + Ok(py + .import("uuid")? + .getattr("UUID")? + .call1((format!("{value:?}"),))? + .unbind()) +} + +fn python_char(py: Python<'_>, value: u16) -> PyResult> { + Ok(py + .import("builtins")? + .getattr("chr")? + .call1((u32::from(value),))? + .unbind()) +} + +fn property_value_to_python( + py: Python<'_>, + value: dynwinrt::PropertyValueData, +) -> PyResult> { + use dynwinrt::PropertyValueData; + + macro_rules! into_python { + ($value:expr) => { + Ok($value.into_pyobject(py)?.into_any().unbind()) + }; + } + + match value { + PropertyValueData::UInt8(value) => into_python!(value), + PropertyValueData::Int16(value) => into_python!(value), + PropertyValueData::UInt16(value) => into_python!(value), + PropertyValueData::Int32(value) => into_python!(value), + PropertyValueData::UInt32(value) => into_python!(value), + PropertyValueData::Int64(value) => into_python!(value), + PropertyValueData::UInt64(value) => into_python!(value), + PropertyValueData::Single(value) => into_python!(value), + PropertyValueData::Double(value) => into_python!(value), + PropertyValueData::Char16(value) => python_char(py, value), + PropertyValueData::Boolean(value) => { + Ok(value.into_pyobject(py)?.to_owned().into_any().unbind()) + } + PropertyValueData::String(value) => into_python!(value), + PropertyValueData::Guid(value) => python_uuid(py, value), + PropertyValueData::UInt8Array(value) => Ok(PyBytes::new(py, &value).into_any().unbind()), + PropertyValueData::Int16Array(value) => into_python!(value), + PropertyValueData::UInt16Array(value) => into_python!(value), + PropertyValueData::Int32Array(value) => into_python!(value), + PropertyValueData::UInt32Array(value) => into_python!(value), + PropertyValueData::Int64Array(value) => into_python!(value), + PropertyValueData::UInt64Array(value) => into_python!(value), + PropertyValueData::SingleArray(value) => into_python!(value), + PropertyValueData::DoubleArray(value) => into_python!(value), + PropertyValueData::Char16Array(value) => { + let values = value + .into_iter() + .map(|value| python_char(py, value)) + .collect::>>()?; + Ok(PyList::new(py, values)?.into_any().unbind()) + } + PropertyValueData::BooleanArray(value) => into_python!(value), + PropertyValueData::StringArray(value) => into_python!(value), + PropertyValueData::GuidArray(value) => { + let values = value + .into_iter() + .map(|value| python_uuid(py, value)) + .collect::>>()?; + Ok(PyList::new(py, values)?.into_any().unbind()) + } + } +} + +/// Explicitly unbox a supported WinRT `IPropertyValue`. +/// +/// Python `None` and WinRT null are returned as `None`. A non-`IPropertyValue` +/// `DynWinRTValue` is returned unchanged, preserving Python and COM identity. +#[pyfunction] +pub fn unbox_object(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult> { + if value.is_none() { + return Ok(py.None()); + } + + let result = { + let raw = value.extract::>()?; + dynwinrt::unbox_property_value(&raw.0).map_err(map_dynwinrt_error)? + }; + match result { + dynwinrt::PropertyValueUnboxResult::Null => Ok(py.None()), + dynwinrt::PropertyValueUnboxResult::NotPropertyValue => Ok(value.clone().unbind()), + dynwinrt::PropertyValueUnboxResult::Value(value) => property_value_to_python(py, value), + } +} + // ====================================================================== // Process-local named XAML runtime classes // ====================================================================== diff --git a/bindings/py/tests/test_e2e_winrt.py b/bindings/py/tests/test_e2e_winrt.py index e9dcfff5..18d0e6dd 100644 --- a/bindings/py/tests/test_e2e_winrt.py +++ b/bindings/py/tests/test_e2e_winrt.py @@ -26,6 +26,7 @@ DynWinRTStruct, WinGUID, ro_initialize, + unbox_object, ) from dynwinrt.dynwinrt import _DynWinRTAsyncWithProgress @@ -315,6 +316,27 @@ def _setup(self): ("CreateChar16", [DynWinRTType.char16()], [obj]), # [16] ("CreateBoolean", [bool_t], [obj]), # [17] ("CreateString", [hstr], [obj]), # [18] + ("CreateInspectable", [obj], [obj]), # [19] + ("SkippedCreateGuid", [], []), # [20] + ("CreateDateTime", [DynWinRTType.struct_type( + "Windows.Foundation.DateTime", [DynWinRTType.i64_type()] + )], [obj]), # [21] + ("SkippedCreateTimeSpan", [], []), # [22] + ("SkippedCreatePoint", [], []), # [23] + ("SkippedCreateSize", [], []), # [24] + ("SkippedCreateRect", [], []), # [25] + ("CreateUInt8Array", [DynWinRTType.array_type(DynWinRTType.u8_type())], [obj]), # [26] + ("SkippedCreateInt16Array", [], []), # [27] + ("SkippedCreateUInt16Array", [], []), # [28] + ("CreateInt32Array", [DynWinRTType.array_type(i32)], [obj]), # [29] + ("SkippedCreateUInt32Array", [], []), # [30] + ("SkippedCreateInt64Array", [], []), # [31] + ("SkippedCreateUInt64Array", [], []), # [32] + ("SkippedCreateSingleArray", [], []), # [33] + ("SkippedCreateDoubleArray", [], []), # [34] + ("CreateChar16Array", [DynWinRTType.array_type( + DynWinRTType.char16() + )], [obj]), # [35] ] _, statics_iid, statics_h = _register("E2E_IPropertyValueStatics", self.IPVSTATICS_IID, statics_methods) @@ -370,6 +392,86 @@ def test_create_and_get_string(self): pv_cast = pv.cast(pv_iid) assert pv_h["GetString"].get_string(pv_cast) == "hello dynwinrt" + def test_explicit_unbox_object_for_device_property_values(self): + statics_h, _, _, factory = self._setup() + boxed_string = statics_h["CreateString"].invoke( + factory, [DynWinRTValue.from_hstring("BLE Device")] + ) + boxed_int64 = statics_h["CreateInt64"].invoke( + factory, [DynWinRTValue.from_i64(-(2**63))] + ) + boxed_char = statics_h["CreateChar16"].invoke( + factory, [DynWinRTValue.from_u16(0xD800)] + ) + boxed_bytes = statics_h["CreateUInt8Array"].invoke( + factory, + [DynWinRTArray.from_u8_values([0, 1, 127, 255]).to_value()], + ) + boxed_ints = statics_h["CreateInt32Array"].invoke( + factory, + [DynWinRTArray.from_i32_values([-1, 0, 42]).to_value()], + ) + boxed_chars = statics_h["CreateChar16Array"].invoke( + factory, + [DynWinRTArray.from_u16_values([0xD800, 0x61]).to_value()], + ) + + assert unbox_object(boxed_string) == "BLE Device" + assert unbox_object(boxed_int64) == -(2**63) + assert ord(unbox_object(boxed_char)) == 0xD800 + assert unbox_object(boxed_bytes) == bytes([0, 1, 127, 255]) + assert unbox_object(boxed_ints) == [-1, 0, 42] + assert [ord(value) for value in unbox_object(boxed_chars)] == [ + 0xD800, + 0x61, + ] + assert unbox_object(None) is None + assert unbox_object(DynWinRTValue.null_value()) is None + + uri_factory = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + identity = uri_factory.identity_raw() + assert unbox_object(uri_factory) is uri_factory + assert uri_factory.identity_raw() == identity + + date_time = DynWinRTStruct.create( + DynWinRTType.struct_type( + "Windows.Foundation.DateTime", [DynWinRTType.i64_type()] + ) + ) + date_time.set_i64(0, 0) + unsupported = statics_h["CreateDateTime"].invoke( + factory, [date_time.to_value()] + ) + import pytest + + with pytest.raises(OSError, match="Unsupported WinRT IPropertyValue type"): + unbox_object(unsupported) + + key_type = DynWinRTType.hstring() + object_type = DynWinRTType.object() + properties = DynWinRTValue.create_map( + [DynWinRTValue.from_hstring("System.Devices.DeviceInstanceId")], + [boxed_string], + key_type, + object_type, + ) + map_type = DynWinRTType.parameterized( + WinGUID.parse("3c2925fe-8519-45c1-aa79-197b6718c1c1"), + [key_type, object_type], + ) + map_interface = DynWinRTType.register_interface( + "IMap_String_Object_UnboxTest", map_type.iid() + ).add_method( + "Lookup", + DynWinRTMethodSig().add_in(key_type).add_out(object_type), + ) + device_property = map_interface.method_by_name("Lookup").invoke( + properties.cast(map_type.iid()), + [DynWinRTValue.from_hstring("System.Devices.DeviceInstanceId")], + ) + assert unbox_object(device_property) == "BLE Device" + assert unbox_object(boxed_string) == "BLE Device" + def test_is_numeric_scalar(self): """IsNumericScalar returns False for both int and string PropertyValues (this matches the actual Windows API behavior).""" diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index c72cca64..614f4aeb 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -10,6 +10,7 @@ mod composition; mod interfaces; mod native_call; mod native_callback; +mod property_value; mod result; mod roapi; mod signature; @@ -47,6 +48,9 @@ pub use crate::element_factory::{ create_element_factory_value, }; pub use crate::metadata_table::{MetadataTable, MethodHandle, TypeHandle, TypeKind, ValueTypeData}; +pub use crate::property_value::{ + PropertyValueData, PropertyValueUnboxResult, unbox_property_value, +}; pub use crate::reference::box_ireference; pub use crate::result::{Error, Result}; pub use crate::roapi::ro_get_activation_factory_2; diff --git a/crates/dynwinrt/src/property_value.rs b/crates/dynwinrt/src/property_value.rs new file mode 100644 index 00000000..f318d8ad --- /dev/null +++ b/crates/dynwinrt/src/property_value.rs @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use windows::Foundation::{IPropertyValue, PropertyType}; +use windows_core::{Array, GUID, HRESULT, HSTRING, Interface}; + +use crate::{Error, Result, WinRTValue}; + +const E_NOINTERFACE: HRESULT = HRESULT(0x80004002_u32 as i32); +const E_NOTIMPL: HRESULT = HRESULT(0x80004001_u32 as i32); + +/// A language-neutral value explicitly read from a WinRT `IPropertyValue`. +#[derive(Debug, Clone, PartialEq)] +pub enum PropertyValueData { + UInt8(u8), + Int16(i16), + UInt16(u16), + Int32(i32), + UInt32(u32), + Int64(i64), + UInt64(u64), + Single(f32), + Double(f64), + Char16(u16), + Boolean(bool), + String(String), + Guid(GUID), + UInt8Array(Vec), + Int16Array(Vec), + UInt16Array(Vec), + Int32Array(Vec), + UInt32Array(Vec), + Int64Array(Vec), + UInt64Array(Vec), + SingleArray(Vec), + DoubleArray(Vec), + Char16Array(Vec), + BooleanArray(Vec), + StringArray(Vec), + GuidArray(Vec), +} + +/// Result of explicitly attempting to unbox a raw WinRT object. +#[derive(Debug, Clone, PartialEq)] +pub enum PropertyValueUnboxResult { + /// The input was the WinRT null object. + Null, + /// The input does not implement `IPropertyValue` and must be preserved. + NotPropertyValue, + /// The input was a supported boxed property value. + Value(PropertyValueData), +} + +macro_rules! read_array { + ($property_value:expr, $getter:ident, $typ:ty) => {{ + let mut values = Array::<$typ>::new(); + $property_value.$getter(&mut values)?; + values.to_vec() + }}; +} + +/// Explicitly reads a supported `IPropertyValue` without consuming or mutating `value`. +/// +/// A QueryInterface failure with `E_NOINTERFACE` is reported as +/// [`PropertyValueUnboxResult::NotPropertyValue`]. Other QueryInterface failures, +/// unsupported `PropertyType` values, and getter failures are surfaced as errors. +pub fn unbox_property_value(value: &WinRTValue) -> Result { + if value.is_null_object() { + return Ok(PropertyValueUnboxResult::Null); + } + + let Some(object) = value.as_object() else { + return Ok(PropertyValueUnboxResult::NotPropertyValue); + }; + let property_value = match object.cast::() { + Ok(value) => value, + Err(error) if error.code() == E_NOINTERFACE => { + return Ok(PropertyValueUnboxResult::NotPropertyValue); + } + Err(error) => return Err(Error::WindowsError(error)), + }; + + let property_type = property_value.Type()?; + let value = match property_type { + PropertyType::UInt8 => PropertyValueData::UInt8(property_value.GetUInt8()?), + PropertyType::Int16 => PropertyValueData::Int16(property_value.GetInt16()?), + PropertyType::UInt16 => PropertyValueData::UInt16(property_value.GetUInt16()?), + PropertyType::Int32 => PropertyValueData::Int32(property_value.GetInt32()?), + PropertyType::UInt32 => PropertyValueData::UInt32(property_value.GetUInt32()?), + PropertyType::Int64 => PropertyValueData::Int64(property_value.GetInt64()?), + PropertyType::UInt64 => PropertyValueData::UInt64(property_value.GetUInt64()?), + PropertyType::Single => PropertyValueData::Single(property_value.GetSingle()?), + PropertyType::Double => PropertyValueData::Double(property_value.GetDouble()?), + PropertyType::Char16 => PropertyValueData::Char16(property_value.GetChar16()?), + PropertyType::Boolean => PropertyValueData::Boolean(property_value.GetBoolean()?), + PropertyType::String => PropertyValueData::String(property_value.GetString()?.to_string()), + PropertyType::Guid => PropertyValueData::Guid(property_value.GetGuid()?), + PropertyType::UInt8Array => { + PropertyValueData::UInt8Array(read_array!(property_value, GetUInt8Array, u8)) + } + PropertyType::Int16Array => { + PropertyValueData::Int16Array(read_array!(property_value, GetInt16Array, i16)) + } + PropertyType::UInt16Array => { + PropertyValueData::UInt16Array(read_array!(property_value, GetUInt16Array, u16)) + } + PropertyType::Int32Array => { + PropertyValueData::Int32Array(read_array!(property_value, GetInt32Array, i32)) + } + PropertyType::UInt32Array => { + PropertyValueData::UInt32Array(read_array!(property_value, GetUInt32Array, u32)) + } + PropertyType::Int64Array => { + PropertyValueData::Int64Array(read_array!(property_value, GetInt64Array, i64)) + } + PropertyType::UInt64Array => { + PropertyValueData::UInt64Array(read_array!(property_value, GetUInt64Array, u64)) + } + PropertyType::SingleArray => { + PropertyValueData::SingleArray(read_array!(property_value, GetSingleArray, f32)) + } + PropertyType::DoubleArray => { + PropertyValueData::DoubleArray(read_array!(property_value, GetDoubleArray, f64)) + } + PropertyType::Char16Array => { + PropertyValueData::Char16Array(read_array!(property_value, GetChar16Array, u16)) + } + PropertyType::BooleanArray => { + PropertyValueData::BooleanArray(read_array!(property_value, GetBooleanArray, bool)) + } + PropertyType::StringArray => { + let values = read_array!(property_value, GetStringArray, HSTRING); + PropertyValueData::StringArray( + values.into_iter().map(|value| value.to_string()).collect(), + ) + } + PropertyType::GuidArray => { + PropertyValueData::GuidArray(read_array!(property_value, GetGuidArray, GUID)) + } + _ => { + return Err(Error::WindowsError(windows_core::Error::new( + E_NOTIMPL, + format!("Unsupported WinRT IPropertyValue type: {}", property_type.0), + ))); + } + }; + + Ok(PropertyValueUnboxResult::Value(value)) +} + +#[cfg(test)] +mod tests { + use windows::Foundation::{DateTime, PropertyValue, Uri}; + use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; + use windows_core::{HSTRING, Interface}; + + use super::*; + + fn as_value(value: &T) -> WinRTValue { + WinRTValue::Object(value.cast().expect("IPropertyValue as IUnknown")) + } + + #[test] + fn unboxes_scalar_and_array_property_values() -> windows_core::Result<()> { + let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + + let string = PropertyValue::CreateString(&HSTRING::from("BLE Device"))?; + assert_eq!( + unbox_property_value(&as_value(&string)).unwrap(), + PropertyValueUnboxResult::Value(PropertyValueData::String("BLE Device".to_string())) + ); + + let int64 = PropertyValue::CreateInt64(i64::MIN)?; + assert_eq!( + unbox_property_value(&as_value(&int64)).unwrap(), + PropertyValueUnboxResult::Value(PropertyValueData::Int64(i64::MIN)) + ); + + let bytes = PropertyValue::CreateUInt8Array(&[0, 1, 127, 255])?; + assert_eq!( + unbox_property_value(&as_value(&bytes)).unwrap(), + PropertyValueUnboxResult::Value(PropertyValueData::UInt8Array(vec![0, 1, 127, 255])) + ); + + let strings = + PropertyValue::CreateStringArray(&[HSTRING::from("one"), HSTRING::from("two")])?; + assert_eq!( + unbox_property_value(&as_value(&strings)).unwrap(), + PropertyValueUnboxResult::Value(PropertyValueData::StringArray(vec![ + "one".to_string(), + "two".to_string() + ])) + ); + + Ok(()) + } + + #[test] + fn preserves_null_and_non_property_objects() -> windows_core::Result<()> { + let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + + assert_eq!( + unbox_property_value(&WinRTValue::Null).unwrap(), + PropertyValueUnboxResult::Null + ); + + let uri = Uri::CreateUri(&HSTRING::from("https://example.com"))?; + let raw = uri.as_raw(); + let value = as_value(&uri); + assert_eq!( + unbox_property_value(&value).unwrap(), + PropertyValueUnboxResult::NotPropertyValue + ); + assert_eq!(value.as_object().unwrap().as_raw(), raw); + assert_eq!(uri.Host()?, "example.com"); + + Ok(()) + } + + #[test] + fn rejects_unsupported_property_types() -> windows_core::Result<()> { + let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + + let date_time = PropertyValue::CreateDateTime(DateTime { UniversalTime: 0 })?; + let error = unbox_property_value(&as_value(&date_time)).unwrap_err(); + assert!(error.message().contains(&format!( + "Unsupported WinRT IPropertyValue type: {}", + PropertyType::DateTime.0 + ))); + + Ok(()) + } +} From 5105b071eccab4d267f2b21251d5a741e038cdc6 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 3 Sep 2026 11:05:00 +0800 Subject: [PATCH 2/2] Fix unboxObject TypeScript input type Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/__test__/index.spec.ts | 6 +++++- bindings/js/package.json | 1 + bindings/js/src/lib.rs | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index af849ed4..f81c86db 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -852,8 +852,12 @@ test('explicitly unbox WinRT property values without changing raw objects', (t) const deviceProperty = mapInterface .methodByName('Lookup') .invoke(propertyMap.cast(mapType.iid()), [DynWinRtValue.hstring('System.Devices.DeviceInstanceId')]) - t.is(unboxObject(deviceProperty), 'BLE Device') + const generatedObjectResult: unknown = deviceProperty + t.is(unboxObject(generatedObjectResult), 'BLE Device') t.is(unboxObject(boxedString), 'BLE Device') + t.throws(() => unboxObject('not a DynWinRtValue'), { + message: /Failed to recover `DynWinRTValue` type from napi value/, + }) }) test('resolve WinRT async operations through the Node event loop', async (t) => { diff --git a/bindings/js/package.json b/bindings/js/package.json index 4cb7e5a3..1e67585d 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -82,6 +82,7 @@ "format:rs": "cargo fmt", "lint": "oxlint", "test": "ava", + "test:types": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts", "test:tsfn": "npm run build:test-hooks && ava __test__/tsfn.spec.ts", "version": "napi version" }, diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index e212aea9..4a2de6a7 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -279,7 +279,7 @@ fn js_safe_i64(value: i64, context: &str) -> napi::Result { /// JavaScript `null` and WinRT null are returned as `null`. A non-`IPropertyValue` /// `DynWinRtValue` is returned unchanged, preserving JavaScript and COM identity. #[napi( - ts_args_type = "value: DynWinRtValue | null", + ts_args_type = "value: unknown", ts_return_type = "boolean | number | bigint | string | Uint8Array | number[] | bigint[] | boolean[] | string[] | DynWinRtValue | null" )] pub fn unbox_object<'env>(env: Env, value: Unknown<'env>) -> napi::Result> {