From ced2271313543966e24af9aa959e7e8a9cf9b432 Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 15:20:43 -0400 Subject: [PATCH 01/21] Add standalone Tizen Essentials package for .NET 11 Ports the dotnet/maui net11.0 Tizen Essentials implementations into a standalone `Maui.Tizen.Essentials` package that targets .NET 11+ and consumes the neutral (non platform specific) MAUI packages. The net11.0 branch of dotnet/maui hard-disables its in-box Tizen target frameworks, so a Tizen backend must now ship separately. * Converts every MAUI partial implementation fragment into an independently named public class under `Microsoft.Maui.Platforms.Tizen.Essentials` implementing the public Essentials contract. * Adds `AddTizenEssentials(MauiAppBuilder)` / `(IServiceCollection)` using singleton `TryAdd` registrations, so applications can override any individual service. * Relies on the .NET 11 Essentials DI-to-static-facade bridge (dotnet/maui#36657) instead of `SetDefault` reflection, and on the dispatcher/MainThread bridge instead of a private MainThread hook. `MainThread.tizen.cs` is deliberately not ported. * Implements screenshot for real through the neutral `IScreenshot` and `IViewScreenshot` contracts using `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders, replacing the upstream stub whose members all threw. * Classifies unsupported capabilities explicitly by Tizen device profile. Nothing returns a success-shaped fallback. * Adds 193 host-side tests covering DI registration, facade and MainThread ownership, permission privilege mapping, unsupported capability classification, and the ported translation logic. * Documents implemented/partial/unsupported services, and the MAUI internal-API gaps found while porting, in `docs/tizen-essentials-service-coverage.md`, asserted by tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .gitignore | 3 + Directory.Build.props | 28 ++ Directory.Packages.props | 35 ++ Maui.Tizen.slnx | 8 + NuGet.config | 7 + docs/tizen-essentials-service-coverage.md | 89 ++++++ dotnet.config | 2 + global.json | 7 + .../Accelerometer/TizenAccelerometer.cs | 125 ++++++++ .../Accelerometer/TizenAccelerometerQueue.cs | 81 +++++ .../AppActions/TizenAppActions.cs | 45 +++ .../AppInfo/TizenAppInfo.cs | 55 ++++ .../Barometer/TizenBarometer.cs | 34 ++ .../Battery/TizenBattery.cs | 104 ++++++ .../Browser/TizenBrowser.cs | 41 +++ .../Clipboard/TizenClipboard.cs | 46 +++ .../Compass/TizenCompass.cs | 46 +++ .../Connectivity/TizenConnectivity.cs | 133 ++++++++ .../Contacts/TizenContacts.cs | 123 +++++++ .../DeviceDisplay/TizenDeviceDisplay.cs | 164 ++++++++++ .../DeviceInfo/TizenDeviceInfo.cs | 62 ++++ src/Maui.Tizen.Essentials/Email/TizenEmail.cs | 86 +++++ .../FilePicker/TizenFilePicker.cs | 101 ++++++ .../FileSystem/TizenFileSystem.cs | 56 ++++ .../Flashlight/TizenFlashlight.cs | 43 +++ .../Geocoding/TizenGeocoding.cs | 124 +++++++ .../Geolocation/TizenGeolocation.cs | 150 +++++++++ .../Gyroscope/TizenGyroscope.cs | 34 ++ .../HapticFeedback/TizenHapticFeedback.cs | 58 ++++ ...TizenEssentialsMauiAppBuilderExtensions.cs | 140 ++++++++ .../Launcher/TizenLauncher.cs | 92 ++++++ .../Magnetometer/TizenMagnetometer.cs | 34 ++ src/Maui.Tizen.Essentials/Map/TizenMap.cs | 80 +++++ .../Maui.Tizen.Essentials.csproj | 31 ++ .../MediaPicker/TizenMediaPicker.cs | 109 +++++++ .../TizenOrientationSensor.cs | 34 ++ .../Passkeys/TizenPasskeys.cs | 37 +++ .../Permissions/TizenPermissions.cs | 302 ++++++++++++++++++ .../PhoneDialer/TizenPhoneDialer.cs | 36 +++ .../Platform/TizenEssentialsSupport.cs | 61 ++++ .../Platform/TizenPlatform.cs | 80 +++++ .../Platform/TizenSystemInformation.cs | 117 +++++++ .../Preferences/TizenPreferences.cs | 123 +++++++ .../Screenshot/TizenScreenshot.cs | 288 +++++++++++++++++ .../SecureStorage/TizenSecureStorage.cs | 98 ++++++ .../TizenSemanticScreenReader.cs | 19 ++ src/Maui.Tizen.Essentials/Share/TizenShare.cs | 78 +++++ src/Maui.Tizen.Essentials/Sms/TizenSms.cs | 48 +++ .../TextToSpeech/TizenTextToSpeech.cs | 229 +++++++++++++ .../Types/TizenFileMimeTypes.cs | 58 ++++ .../Types/TizenSensorBase.cs | 129 ++++++++ .../Types/TizenSensors.cs | 96 ++++++ .../Vibration/TizenVibration.cs | 44 +++ .../WebAuthenticator/TizenWebAuthenticator.cs | 48 +++ .../FacadeAndMainThreadOwnershipTests.cs | 133 ++++++++ .../Maui.Tizen.Essentials.Tests.csproj | 42 +++ .../ServiceCoverageMatrixTests.cs | 158 +++++++++ .../TizenAccelerometerQueueTests.cs | 108 +++++++ .../TizenEssentialsRegistrationTests.cs | 203 ++++++++++++ .../TizenHostAssemblyResolver.cs | 38 +++ .../TizenPermissionsTests.cs | 135 ++++++++ .../TizenTranslationTests.cs | 184 +++++++++++ .../TizenUnsupportedCapabilityTests.cs | 112 +++++++ 63 files changed, 5414 insertions(+) create mode 100644 .gitignore create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 Maui.Tizen.slnx create mode 100644 NuGet.config create mode 100644 docs/tizen-essentials-service-coverage.md create mode 100644 dotnet.config create mode 100644 global.json create mode 100644 src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs create mode 100644 src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs create mode 100644 src/Maui.Tizen.Essentials/AppActions/TizenAppActions.cs create mode 100644 src/Maui.Tizen.Essentials/AppInfo/TizenAppInfo.cs create mode 100644 src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs create mode 100644 src/Maui.Tizen.Essentials/Battery/TizenBattery.cs create mode 100644 src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs create mode 100644 src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs create mode 100644 src/Maui.Tizen.Essentials/Compass/TizenCompass.cs create mode 100644 src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs create mode 100644 src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs create mode 100644 src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs create mode 100644 src/Maui.Tizen.Essentials/DeviceInfo/TizenDeviceInfo.cs create mode 100644 src/Maui.Tizen.Essentials/Email/TizenEmail.cs create mode 100644 src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs create mode 100644 src/Maui.Tizen.Essentials/FileSystem/TizenFileSystem.cs create mode 100644 src/Maui.Tizen.Essentials/Flashlight/TizenFlashlight.cs create mode 100644 src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs create mode 100644 src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs create mode 100644 src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs create mode 100644 src/Maui.Tizen.Essentials/HapticFeedback/TizenHapticFeedback.cs create mode 100644 src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs create mode 100644 src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs create mode 100644 src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs create mode 100644 src/Maui.Tizen.Essentials/Map/TizenMap.cs create mode 100644 src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj create mode 100644 src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs create mode 100644 src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs create mode 100644 src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs create mode 100644 src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs create mode 100644 src/Maui.Tizen.Essentials/PhoneDialer/TizenPhoneDialer.cs create mode 100644 src/Maui.Tizen.Essentials/Platform/TizenEssentialsSupport.cs create mode 100644 src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs create mode 100644 src/Maui.Tizen.Essentials/Platform/TizenSystemInformation.cs create mode 100644 src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs create mode 100644 src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs create mode 100644 src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs create mode 100644 src/Maui.Tizen.Essentials/SemanticScreenReader/TizenSemanticScreenReader.cs create mode 100644 src/Maui.Tizen.Essentials/Share/TizenShare.cs create mode 100644 src/Maui.Tizen.Essentials/Sms/TizenSms.cs create mode 100644 src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs create mode 100644 src/Maui.Tizen.Essentials/Types/TizenFileMimeTypes.cs create mode 100644 src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs create mode 100644 src/Maui.Tizen.Essentials/Types/TizenSensors.cs create mode 100644 src/Maui.Tizen.Essentials/Vibration/TizenVibration.cs create mode 100644 src/Maui.Tizen.Essentials/WebAuthenticator/TizenWebAuthenticator.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj create mode 100644 tests/Maui.Tizen.Essentials.Tests/ServiceCoverageMatrixTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenAccelerometerQueueTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenEssentialsRegistrationTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenHostAssemblyResolver.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..afb96ed6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +artifacts/ +bin/ +obj/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..b79a07fc --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,28 @@ + + + + + net11.0 + latest + enable + disable + false + true + true + false + true + + + + Maui.Tizen contributors + https://github.com/Redth/Maui.Tizen + https://github.com/Redth/Maui.Tizen + git + MIT + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000..403642c9 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,35 @@ + + + + + 11.0.0-preview.7.26406.9 + + 11.0.0.18033 + + + + + + + + + + + + + + diff --git a/Maui.Tizen.slnx b/Maui.Tizen.slnx new file mode 100644 index 00000000..01c8c0a0 --- /dev/null +++ b/Maui.Tizen.slnx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/NuGet.config b/NuGet.config new file mode 100644 index 00000000..765346e5 --- /dev/null +++ b/NuGet.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md new file mode 100644 index 00000000..1a0fe0f2 --- /dev/null +++ b/docs/tizen-essentials-service-coverage.md @@ -0,0 +1,89 @@ +# Tizen Essentials service coverage matrix + +`Maui.Tizen.Essentials` provides Tizen implementations of the .NET MAUI Essentials service +contracts as a standalone platform backend for **.NET 11 and newer**. + +Support levels: + +| Level | Meaning | +| --- | --- | +| `Implemented` | The whole contract is backed by native Tizen APIs. | +| `Partial` | Part of the contract is backed by native Tizen APIs. The remaining members throw `FeatureNotSupportedException` with an explicit reason. | +| `Unsupported` | Tizen has no API that can satisfy the contract. Every member throws `FeatureNotSupportedException`. Nothing is faked. | + +Nothing in this backend returns a success-shaped fallback (an empty collection, `null`, or a +completed `Task`) to stand in for a capability the platform does not have. + +Profile column values are the Tizen device profiles on which the service is usable: +`Mobile`, `Wearable`, `TV`, `Common` (IoT headed), or `All`. + + + +| Contract | Implementation | Level | Profiles | Notes | +| --- | --- | --- | --- | --- | +| `IAccelerometer` | `TizenAccelerometer` | Implemented | All | `Tizen.Sensor.Accelerometer`. Shake detection reimplemented (MAUI's `AccelerometerQueue` is internal). | +| `IAppActions` | `TizenAppActions` | Unsupported | – | Tizen has no home-screen shortcut / quick action API. `IsSupported` is `false`. | +| `IAppInfo` | `TizenAppInfo` | Partial | All | `RequestedTheme` is `Unspecified` and `RequestedLayoutDirection` is `LeftToRight`: Tizen exposes neither to applications. | +| `IAppleSignInAuthenticator` | `TizenAppleSignInAuthenticator` | Unsupported | – | Native Sign in with Apple is Apple-platform only. | +| `IBarometer` | `TizenBarometer` | Implemented | All | `Tizen.Sensor.PressureSensor`. | +| `IBattery` | `TizenBattery` | Partial | All | `EnergySaverStatus` / `EnergySaverStatusChanged` throw: Tizen exposes no application-visible power saving state. | +| `IBrowser` | `TizenBrowser` | Partial | All | Always opens the system browser: Tizen has no in-app browser, so `BrowserLaunchMode` cannot be honoured. | +| `IClipboard` | `TizenClipboard` | Unsupported | – | Tizen scopes copy/paste to the focused NUI/EFL window selection buffer; there is no headless clipboard service. | +| `ICompass` | `TizenCompass` | Implemented | All | Azimuth from `Tizen.Sensor.OrientationSensor`. `applyLowPassFilter` has no extra effect (Tizen already fuses and filters). | +| `IConnectivity` | `TizenConnectivity` | Implemented | All | `Tizen.Network.Connection`. Requires `network.get` + `internet` privileges. | +| `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. Requires `contact.read`. | +| `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | +| `IDeviceInfo` | `TizenDeviceInfo` | Implemented | All | System / feature information keys. | +| `IEmail` | `TizenEmail` | Partial | Mobile | Attachments are rejected: the Tizen `compose` AppControl accepts no attachment payload. Gated on the `email` feature key. | +| `IFilePicker` | `TizenFilePicker` | Partial | All | Tizen's `pick` operation accepts one MIME filter, so only the first entry of `PickOptions.FileTypes` is applied. | +| `IFileSystem` | `TizenFileSystem` | Implemented | All | Application `DirectoryInfo` data / cache / resource paths. | +| `IFlashlight` | `TizenFlashlight` | Implemented | Mobile | `Tizen.System.Led`. Gated on `camera.back.flash`; requires the `led` privilege. | +| `IGeocoding` | `TizenGeocoding` | Implemented | All | `Tizen.Maps` (HERE). Requires a map service token; also registered as `IPlatformGeocoding`. | +| `IGeolocation` | `TizenGeolocation` | Partial | All | One-shot `GetLocationAsync` works. `StartListeningForegroundAsync` / `StopListeningForeground` throw. | +| `IGyroscope` | `TizenGyroscope` | Implemented | All | `Tizen.Sensor.Gyroscope`. | +| `IHapticFeedback` | `TizenHapticFeedback` | Implemented | Mobile, Wearable | `Tizen.System.Feedback`. Unsupported patterns throw instead of silently doing nothing. | +| `ILauncher` | `TizenLauncher` | Implemented | All | AppControl launch requests, with scheme-based operation selection. | +| `IMagnetometer` | `TizenMagnetometer` | Implemented | All | `Tizen.Sensor.Magnetometer`. | +| `IMap` | `TizenMap` | Partial | All | `geo:` AppControl. `MapLaunchOptions.NavigationMode` and the launch name cannot be honoured. | +| `IMediaPicker` | `TizenMediaPicker` | Implemented | Mobile | Picking delegates to `TizenFilePicker`; capture uses the `image_capture` / `video_capture` AppControls. | +| `IOrientationSensor` | `TizenOrientationSensor` | Implemented | All | `Tizen.Sensor.RotationVectorSensor`. | +| `IPasskeys` | `TizenPasskeys` | Unsupported | – | Tizen ships FIDO UAF, not a WebAuthn / CTAP2 credential manager. `IsSupported` is `false`. | +| `IPermissions` | `TizenPermissions` | Implemented | All | Maps every built-in `Permissions.*` type to its Tizen privileges; runtime privileges go through `PrivacyPrivilegeManager`. | +| `IPhoneDialer` | `TizenPhoneDialer` | Implemented | Mobile | `tel:` AppControl, gated on the `contact` feature key. | +| `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with a `{sharedName}~{key}` prefix. | +| `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders. Also implements `IViewScreenshot`. | +| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager (`Tizen.Security.SecureRepository.DataManager`). | +| `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | +| `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | +| `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | +| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | +| `IVibration` | `TizenVibration` | Implemented | Mobile, Wearable | `Tizen.System.Vibrator`; requires the `haptic` privilege. | +| `IWebAuthenticator` | `TizenWebAuthenticator` | Unsupported | – | Tizen has no callback URI registration that returns an external browser response to the app. | + + + +## Deliberately not provided + +| Contract | Why | +| --- | --- | +| `IVersionTracking` | MAUI's own `VersionTrackingImplementation` is platform neutral; it is built from `IPreferences` and `IAppInfo`, both of which this package registers. Registering a Tizen-specific version would take facade ownership away from MAUI's lazy `VersionTracking.Default` wrapper for no benefit. | +| `MainThread` | Main-thread marshalling is bridged from the registered `IDispatcher` by MAUI for platform backends that are not in-box. The Tizen dispatcher supplied by the core Tizen backend is therefore the single source of truth, and this package deliberately ships no `MainThread` platform hook and never touches `EcoreMainloop`. | +| `IActivityStateManager` | Android only. | +| `IWindowStateManager` | Windows / Apple only; MAUI does not bridge it elsewhere. | + +## MAUI public API gaps found while porting + +These are internal-only MAUI APIs that the in-box Tizen backend relied on and that a standalone +platform backend cannot use. Each one is worked around in this package. + +| MAUI API | Accessibility | Impact | Workaround | +| --- | --- | --- | --- | +| `Microsoft.Maui.Media.Locale..ctor(string, string, string, string)` | `internal` | **Blocking.** `ITextToSpeech.GetLocalesAsync` must return `IEnumerable`, and `SpeechOptions.Locale` must be given one, but no external assembly can construct a `Locale`. | `GetLocalesAsync` throws with an explicit reason; `TizenTextToSpeech.GetSupportedVoiceLanguagesAsync()` and `SpeakAsync(text, language, rate, ct)` expose the same capability. | +| `Microsoft.Maui.Storage.FileMimeTypes` | `internal` | MIME constants used by pickers and launchers. | `TizenFileMimeTypes`. | +| `Microsoft.Maui.Devices.Sensors.PlacemarkExtensions.GetEscapedAddress` | `internal` | Address formatting for `geo:0,0?q=` queries. | `TizenPlacemarkExtensions.GetEscapedAddress`. | +| `Microsoft.Maui.Devices.Sensors.AccelerometerQueue` | `internal` | Shake detection window. | `TizenAccelerometerQueue`. | +| `Microsoft.Maui.Devices.DeviceDisplay.BaseLogicalDpi` | `internal` | Density calculation. | `TizenDeviceDisplay.BaseLogicalDpi`. | +| `Microsoft.Maui.ApplicationModel.Permissions.BasePlatformPermission` and the nested `Permissions.Camera`, `Permissions.LocationWhenInUse`, ... types | `public`, but declared `partial` and only implemented per in-box platform | A standalone backend cannot add a platform half to a partial class in another assembly, so the built-in permission types resolve to the neutral implementation whose members throw. | `TizenPermissions` maps the built-in permission types to Tizen privileges itself, and `TizenBasePlatformPermission` is provided for user-defined permissions. | +| `Microsoft.Maui.ApplicationModel.Platform` (Tizen members: `CurrentPackage`, `MapServiceToken`) | `public`, but the Tizen members are compiled only into the Tizen build | The neutral assembly already declares the type, so the Tizen members cannot be added from outside. | `TizenPlatform.CurrentPackage`; the map token flows through `IPlatformGeocoding.MapServiceToken`. | +| `Microsoft.Maui.Media.IPlatformScreenshot` | `public`, but declares no members outside an in-box platform build | Cannot carry a Tizen-typed capture contract. | `TizenScreenshot` implements the neutral `IViewScreenshot`; Tizen-typed overloads live on `TizenScreenshotExtensions`. | +| `Microsoft.Maui.Utils.ParseVersion` | `internal` | Version parsing for `IAppInfo` / `IDeviceInfo`. | `TizenPlatform.ParseVersion`. | diff --git a/dotnet.config b/dotnet.config new file mode 100644 index 00000000..da0410e3 --- /dev/null +++ b/dotnet.config @@ -0,0 +1,2 @@ +[dotnet.test.runner] +name = "Microsoft.Testing.Platform" diff --git a/global.json b/global.json new file mode 100644 index 00000000..e7c8c327 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "11.0.100-preview.7.26381.103", + "rollForward": "latestMajor", + "allowPrerelease": true + } +} diff --git a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs new file mode 100644 index 00000000..875309c7 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs @@ -0,0 +1,125 @@ +using System; +using System.Numerics; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using TizenAccelerometerSensor = Tizen.Sensor.Accelerometer; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Sensor.Accelerometer. + /// + public sealed class TizenAccelerometer : IAccelerometer + { + const double AccelerationThreshold = 169; + const double Gravity = 9.81; + + readonly TizenAccelerometerQueue _queue = new(); + + bool _useSyncContext; + + /// + public event EventHandler? ReadingChanged; + + /// + public event EventHandler? ShakeDetected; + + /// + public bool IsSupported => TizenAccelerometerSensor.IsSupported; + + /// + public bool IsMonitoring { get; private set; } + + static TizenAccelerometerSensor DefaultSensor => + (TizenAccelerometerSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Accelerometer); + + /// + public void Start(SensorSpeed sensorSpeed) + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{nameof(IAccelerometer)}.{nameof(Start)}", "This device has no accelerometer."); + + if (IsMonitoring) + throw new InvalidOperationException("Accelerometer has already been started."); + + IsMonitoring = true; + _useSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; + + try + { + var sensor = DefaultSensor; + sensor.Interval = sensorSpeed.ToPlatform(); + sensor.DataUpdated += OnDataUpdated; + sensor.Start(); + } + catch + { + IsMonitoring = false; + throw; + } + } + + /// + public void Stop() + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{nameof(IAccelerometer)}.{nameof(Stop)}", "This device has no accelerometer."); + + if (!IsMonitoring) + return; + + IsMonitoring = false; + + try + { + var sensor = DefaultSensor; + sensor.DataUpdated -= OnDataUpdated; + sensor.Stop(); + } + catch + { + IsMonitoring = true; + throw; + } + } + + void OnDataUpdated(object? sender, global::Tizen.Sensor.AccelerometerDataUpdatedEventArgs e) => + RaiseReadingChanged(new AccelerometerData(e.X, e.Y, e.Z)); + + void RaiseReadingChanged(AccelerometerData reading) + { + var args = new AccelerometerChangedEventArgs(reading); + + if (_useSyncContext) + MainThread.BeginInvokeOnMainThread(() => ReadingChanged?.Invoke(this, args)); + else + ReadingChanged?.Invoke(this, args); + + if (ShakeDetected is not null) + ProcessShakeEvent(reading.Acceleration); + } + + void ProcessShakeEvent(Vector3 acceleration) + { + var now = TizenAccelerometerQueue.ToNanoseconds(DateTime.UtcNow); + + var x = acceleration.X * Gravity; + var y = acceleration.Y * Gravity; + var z = acceleration.Z * Gravity; + + _queue.Add(now, (x * x) + (y * y) + (z * z) > AccelerationThreshold); + + if (!_queue.IsShaking) + return; + + _queue.Clear(); + + var args = EventArgs.Empty; + + if (_useSyncContext) + MainThread.BeginInvokeOnMainThread(() => ShakeDetected?.Invoke(this, args)); + else + ShakeDetected?.Invoke(this, args); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs new file mode 100644 index 00000000..5b056007 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Sliding window of accelerometer samples used to detect a shake gesture. + /// + /// + /// Behavioural port of the internal Microsoft.Maui.Devices.Sensors.AccelerometerQueue + /// used by dotnet/maui, reimplemented here because that type is not public. A shake is reported + /// when the window covers at least 250ms and more than three quarters of the samples in it + /// exceeded the acceleration threshold. + /// + internal sealed class TizenAccelerometerQueue + { + const long MaxWindowSizeNanoseconds = 500_000_000; + const long MinWindowSizeNanoseconds = 250_000_000; + const int MinQueueSize = 4; + + readonly Queue<(long Timestamp, bool IsAccelerating)> _samples = new(); + + int _acceleratingCount; + + internal void Add(long timestamp, bool accelerating) + { + Purge(timestamp - MaxWindowSizeNanoseconds); + + _samples.Enqueue((timestamp, accelerating)); + + if (accelerating) + _acceleratingCount++; + } + + internal void Clear() + { + _samples.Clear(); + _acceleratingCount = 0; + } + + internal bool IsShaking + { + get + { + if (_samples.Count == 0) + return false; + + var oldest = _samples.Peek().Timestamp; + var newest = NewestTimestamp; + var count = _samples.Count; + + return newest - oldest >= MinWindowSizeNanoseconds && + _acceleratingCount >= (count >> 1) + (count >> 2); + } + } + + long NewestTimestamp + { + get + { + var newest = 0L; + foreach (var sample in _samples) + newest = sample.Timestamp; + return newest; + } + } + + void Purge(long cutoff) + { + while (_samples.Count >= MinQueueSize && cutoff - _samples.Peek().Timestamp > 0) + { + var removed = _samples.Dequeue(); + if (removed.IsAccelerating) + _acceleratingCount--; + } + } + + internal static long ToNanoseconds(DateTime time) => + time.Ticks / TimeSpan.TicksPerMillisecond * 1_000_000; + } +} diff --git a/src/Maui.Tizen.Essentials/AppActions/TizenAppActions.cs b/src/Maui.Tizen.Essentials/AppActions/TizenAppActions.cs new file mode 100644 index 00000000..b753afc1 --- /dev/null +++ b/src/Maui.Tizen.Essentials/AppActions/TizenAppActions.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Tizen has no home-screen shortcut / quick action contract comparable to Android app shortcuts, + /// iOS home screen quick actions, or Windows jump lists. reports + /// and the mutating members throw + /// instead of silently accepting actions that would + /// never be surfaced to the user. + /// + public sealed class TizenAppActions : IAppActions + { + const string Reason = + "Tizen provides no home screen shortcut or quick action API on any device profile " + + "(mobile, wearable, TV or common)."; + + /// + public bool IsSupported => false; + + /// + /// Never raised: Tizen cannot activate app actions. + public event EventHandler? AppActionActivated + { + add { } + remove { } + } + + /// + /// Always thrown. + public Task> GetAsync() => + throw TizenEssentialsSupport.NotSupported($"{nameof(IAppActions)}.{nameof(GetAsync)}", Reason); + + /// + /// Always thrown. + public Task SetAsync(IEnumerable actions) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IAppActions)}.{nameof(SetAsync)}", Reason); + } +} diff --git a/src/Maui.Tizen.Essentials/AppInfo/TizenAppInfo.cs b/src/Maui.Tizen.Essentials/AppInfo/TizenAppInfo.cs new file mode 100644 index 00000000..82d17b2a --- /dev/null +++ b/src/Maui.Tizen.Essentials/AppInfo/TizenAppInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Globalization; +using Microsoft.Maui.ApplicationModel; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenApplication = Tizen.Applications.Application; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + public sealed class TizenAppInfo : IAppInfo + { + /// + public string PackageName => TizenApplication.Current.ApplicationInfo.PackageId; + + /// + public string Name => TizenApplication.Current.ApplicationInfo.Label; + + /// + public Version Version => TizenPlatform.ParseVersion(VersionString); + + /// + public string VersionString => TizenPlatform.CurrentPackage.Version; + + /// + public string BuildString => Version.Build.ToString(CultureInfo.InvariantCulture); + + /// + public void ShowSettingsUI() + { + TizenPermissions.EnsureDeclared(); + + TizenAppControl.SendLaunchRequest(new TizenAppControl + { + Operation = TizenAppControlOperations.Setting, + }); + } + + /// + /// + /// Tizen exposes no cross-profile system theme query, so the theme is reported as + /// rather than guessing light or dark. + /// + public AppTheme RequestedTheme => AppTheme.Unspecified; + + /// + public AppPackagingModel PackagingModel => AppPackagingModel.Packaged; + + /// + /// Tizen does not expose a system-level RTL layout flag to applications. + public LayoutDirection RequestedLayoutDirection => LayoutDirection.LeftToRight; + } +} diff --git a/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs b/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs new file mode 100644 index 00000000..59d75d94 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenPressureSensor = Tizen.Sensor.PressureSensor; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Sensor.PressureSensor. + /// + public sealed class TizenBarometer : TizenSensorBase, IBarometer + { + /// + public event EventHandler? ReadingChanged; + + /// + public override bool IsSupported => TizenPressureSensor.IsSupported; + + /// + protected override string SensorName => nameof(IBarometer); + + /// + protected override TizenPressureSensor Sensor => + (TizenPressureSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Barometer); + + /// + protected override void Subscribe(TizenPressureSensor sensor) => sensor.DataUpdated += OnDataUpdated; + + /// + protected override void Unsubscribe(TizenPressureSensor sensor) => sensor.DataUpdated -= OnDataUpdated; + + void OnDataUpdated(object? sender, global::Tizen.Sensor.PressureSensorDataUpdatedEventArgs e) => + Raise(ReadingChanged, new BarometerChangedEventArgs(new BarometerData(e.Pressure))); + } +} diff --git a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs new file mode 100644 index 00000000..4c08ffa4 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs @@ -0,0 +1,104 @@ +using System; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenBatteryInfo = Tizen.System.Battery; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.System.Battery. + /// + /// + /// Tizen has no power-saving-mode query that is available to applications, so + /// and throw rather than + /// reporting , which would be + /// indistinguishable from a real "power saving is disabled" answer. + /// + public sealed class TizenBattery : IBattery + { + const string EnergySaverReason = + "Tizen exposes no application-visible power saving mode state."; + + readonly object _locker = new(); + + EventHandler? _batteryInfoChanged; + bool _listening; + + /// + public double ChargeLevel => (double)TizenBatteryInfo.Percent / 100; + + /// + public BatteryState State => + TizenBatteryInfo.IsCharging ? BatteryState.Charging : BatteryState.Discharging; + + /// + public BatteryPowerSource PowerSource => + TizenBatteryInfo.IsCharging ? BatteryPowerSource.Usb : BatteryPowerSource.Battery; + + /// + /// Always thrown. + public EnergySaverStatus EnergySaverStatus => + throw TizenEssentialsSupport.NotSupported($"{nameof(IBattery)}.{nameof(EnergySaverStatus)}", EnergySaverReason); + + /// + public event EventHandler? BatteryInfoChanged + { + add + { + lock (_locker) + { + var start = _batteryInfoChanged is null; + _batteryInfoChanged += value; + if (start && _batteryInfoChanged is not null) + StartListeners(); + } + } + remove + { + lock (_locker) + { + _batteryInfoChanged -= value; + if (_batteryInfoChanged is null) + StopListeners(); + } + } + } + + /// + /// Thrown when subscribing or unsubscribing. + public event EventHandler EnergySaverStatusChanged + { + add => throw TizenEssentialsSupport.NotSupported($"{nameof(IBattery)}.{nameof(EnergySaverStatusChanged)}", EnergySaverReason); + remove => throw TizenEssentialsSupport.NotSupported($"{nameof(IBattery)}.{nameof(EnergySaverStatusChanged)}", EnergySaverReason); + } + + void StartListeners() + { + if (_listening) + return; + + TizenBatteryInfo.PercentChanged += OnChanged; + TizenBatteryInfo.ChargingStateChanged += OnChanged; + TizenBatteryInfo.LevelChanged += OnChanged; + _listening = true; + } + + void StopListeners() + { + if (!_listening) + return; + + TizenBatteryInfo.PercentChanged -= OnChanged; + TizenBatteryInfo.ChargingStateChanged -= OnChanged; + TizenBatteryInfo.LevelChanged -= OnChanged; + _listening = false; + } + + void OnChanged(object? sender, object e) => + MainThread.BeginInvokeOnMainThread(() => + { + var args = new BatteryInfoChangedEventArgs(ChargeLevel, State, PowerSource); + _batteryInfoChanged?.Invoke(this, args); + }); + } +} diff --git a/src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs b/src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs new file mode 100644 index 00000000..6f7858f3 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the AppControl view operation. + /// + /// + /// Tizen has no in-app browser control equivalent to Chrome Custom Tabs or SFSafariViewController, + /// so is only used to validate the request: every launch mode + /// resolves to the system browser. + /// + public sealed class TizenBrowser : IBrowser + { + /// + public Task OpenAsync(Uri uri, BrowserLaunchOptions options) + { + ArgumentNullException.ThrowIfNull(uri); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.View, + Uri = uri.AbsoluteUri, + }; + + var hasMatches = TizenAppControl.GetMatchedApplicationIds(appControl).Any(); + + if (hasMatches) + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(hasMatches); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs new file mode 100644 index 00000000..ec761210 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.DataTransfer; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Tizen exposes clipboard access only through the UI toolkit's per-window copy/paste + /// (Ecore/NUI selection buffers), not through a headless system clipboard service. + /// There is therefore no implementation that can satisfy this contract from an Essentials + /// service, so every member throws instead of pretending the clipboard is empty. + /// + public sealed class TizenClipboard : IClipboard + { + const string Reason = + "Tizen has no headless system clipboard API; copy and paste is scoped to the focused " + + "NUI/EFL window's selection buffer."; + + /// + /// Always thrown. + public bool HasText => + throw TizenEssentialsSupport.NotSupported($"{nameof(IClipboard)}.{nameof(HasText)}", Reason); + + /// + /// Never raised: Tizen exposes no clipboard change notification. + public event EventHandler ClipboardContentChanged + { + add { } + remove { } + } + + /// + /// Always thrown. + public Task GetTextAsync() => + throw TizenEssentialsSupport.NotSupported($"{nameof(IClipboard)}.{nameof(GetTextAsync)}", Reason); + + /// + /// Always thrown. + public Task SetTextAsync(string? text) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IClipboard)}.{nameof(SetTextAsync)}", Reason); + } +} diff --git a/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs b/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs new file mode 100644 index 00000000..4a889dc8 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenOrientationSensorNative = Tizen.Sensor.OrientationSensor; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the azimuth reported by + /// Tizen.Sensor.OrientationSensor. + /// + /// + /// Tizen's orientation sensor is already fused and low-pass filtered in the platform, so the + /// applyLowPassFilter argument has no additional effect. It is accepted for source + /// compatibility rather than silently changing behaviour. + /// + public sealed class TizenCompass : TizenSensorBase, ICompass + { + /// + public event EventHandler? ReadingChanged; + + /// + public override bool IsSupported => TizenOrientationSensorNative.IsSupported; + + /// + protected override string SensorName => nameof(ICompass); + + /// + protected override TizenOrientationSensorNative Sensor => + (TizenOrientationSensorNative)TizenSensors.GetDefaultSensor(TizenSensorType.Compass); + + /// + public new void Start(SensorSpeed sensorSpeed) => base.Start(sensorSpeed); + + /// + public void Start(SensorSpeed sensorSpeed, bool applyLowPassFilter) => base.Start(sensorSpeed); + + /// + protected override void Subscribe(TizenOrientationSensorNative sensor) => sensor.DataUpdated += OnDataUpdated; + + /// + protected override void Unsubscribe(TizenOrientationSensorNative sensor) => sensor.DataUpdated -= OnDataUpdated; + + void OnDataUpdated(object? sender, global::Tizen.Sensor.OrientationSensorDataUpdatedEventArgs e) => + Raise(ReadingChanged, new CompassChangedEventArgs(new CompassData(e.Azimuth))); + } +} diff --git a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs new file mode 100644 index 00000000..49a777c6 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Networking; +using TizenConnectionManager = Tizen.Network.Connection.ConnectionManager; +using TizenConnectionProfileManager = Tizen.Network.Connection.ConnectionProfileManager; +using TizenConnectionProfileType = Tizen.Network.Connection.ConnectionProfileType; +using TizenConnectionType = Tizen.Network.Connection.ConnectionType; +using TizenConnectionTypeEventArgs = Tizen.Network.Connection.ConnectionTypeEventArgs; +using TizenProfileListType = Tizen.Network.Connection.ProfileListType; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Network.Connection. + /// + public sealed class TizenConnectivity : IConnectivity + { + readonly object _locker = new(); + + List _profiles = new(); + EventHandler? _connectivityChanged; + bool _listening; + + /// + public NetworkAccess NetworkAccess + { + get + { + TizenPermissions.EnsureDeclared(); + + return TizenConnectionManager.CurrentConnection.Type switch + { + TizenConnectionType.WiFi or + TizenConnectionType.Cellular or + TizenConnectionType.Ethernet => NetworkAccess.Internet, + _ => NetworkAccess.None, + }; + } + } + + /// + public IEnumerable ConnectionProfiles + { + get + { + lock (_locker) + return _profiles.ToArray(); + } + } + + /// + public event EventHandler ConnectivityChanged + { + add + { + lock (_locker) + { + var start = _connectivityChanged is null; + _connectivityChanged += value; + if (start && _connectivityChanged is not null) + StartListeners(); + } + } + remove + { + lock (_locker) + { + _connectivityChanged -= value; + if (_connectivityChanged is null) + StopListeners(); + } + } + } + + void StartListeners() + { + if (_listening) + return; + + TizenPermissions.EnsureDeclared(); + + TizenConnectionManager.ConnectionTypeChanged += OnConnectionTypeChanged; + _listening = true; + + _ = RefreshProfilesAsync(raise: false); + } + + void StopListeners() + { + if (!_listening) + return; + + TizenConnectionManager.ConnectionTypeChanged -= OnConnectionTypeChanged; + _listening = false; + } + + void OnConnectionTypeChanged(object? sender, TizenConnectionTypeEventArgs e) => + _ = RefreshProfilesAsync(raise: true); + + async System.Threading.Tasks.Task RefreshProfilesAsync(bool raise) + { + var list = await TizenConnectionProfileManager.GetProfileListAsync(TizenProfileListType.Connected).ConfigureAwait(false); + + var profiles = new List(); + foreach (var result in list) + { + var mapped = MapProfileType(result.Type); + if (mapped is { } profile) + profiles.Add(profile); + } + + lock (_locker) + _profiles = profiles; + + if (!raise) + return; + + var args = new ConnectivityChangedEventArgs(NetworkAccess, profiles); + MainThread.BeginInvokeOnMainThread(() => _connectivityChanged?.Invoke(this, args)); + } + + internal static ConnectionProfile? MapProfileType(TizenConnectionProfileType type) => + type switch + { + TizenConnectionProfileType.Bt => ConnectionProfile.Bluetooth, + TizenConnectionProfileType.Cellular => ConnectionProfile.Cellular, + TizenConnectionProfileType.Ethernet => ConnectionProfile.Ethernet, + TizenConnectionProfileType.WiFi => ConnectionProfile.WiFi, + _ => null, + }; + } +} diff --git a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs new file mode 100644 index 00000000..b05a9079 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using Tizen.Pims.Contacts; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlLaunchMode = Tizen.Applications.AppControlLaunchMode; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenAppControlReplyResult = Tizen.Applications.AppControlReplyResult; +using TizenContact = Tizen.Pims.Contacts.ContactsViews.Contact; +using TizenEmailView = Tizen.Pims.Contacts.ContactsViews.Email; +using TizenNameView = Tizen.Pims.Contacts.ContactsViews.Name; +using TizenNumberView = Tizen.Pims.Contacts.ContactsViews.Number; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Pims.Contacts. + /// + public sealed class TizenContacts : IContacts + { + static readonly Lazy Manager = new(static () => new ContactsManager()); + + /// + public async Task PickContactAsync() + { + TizenPermissions.EnsureDeclared(); + TizenPermissions.EnsureDeclared(); + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Pick, + LaunchMode = TizenAppControlLaunchMode.Single, + Mime = "application/vnd.tizen.contact", + }; + appControl.ExtraData.Add(TizenAppControlData.SectionMode, "single"); + + TizenAppControl.SendLaunchRequest(appControl, (request, reply, result) => + { + Contact? contact = null; + + if (result == TizenAppControlReplyResult.Succeeded) + { + reply.ExtraData.TryGet(TizenAppControlData.Selected, out IEnumerable selected); + var contactId = selected?.FirstOrDefault(); + + if (int.TryParse(contactId, out var id)) + { + var record = Manager.Value.Database.Get(TizenContact.Uri, id); + if (record is not null) + contact = ToContact(record); + } + } + + tcs.TrySetResult(contact); + }); + + return await tcs.Task.ConfigureAwait(false); + } + + /// + public Task> GetAllAsync(CancellationToken cancellationToken = default) + { + TizenPermissions.EnsureDeclared(); + + cancellationToken.ThrowIfCancellationRequested(); + + var contactsList = Manager.Value.Database.GetAll(TizenContact.Uri, 0, 0); + + return Task.FromResult(Enumerate()); + + IEnumerable Enumerate() + { + for (var i = 0; i < contactsList?.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + yield return ToContact(contactsList.GetCurrentRecord()); + + contactsList.MoveNext(); + } + } + } + + static Contact ToContact(ContactsRecord contactsRecord) + { + var nameRecord = contactsRecord.GetChildRecord(TizenContact.Name, 0); + + var phones = new List(); + var phoneCount = contactsRecord.GetChildRecordCount(TizenContact.Number); + for (var i = 0; i < phoneCount; i++) + { + var numberRecord = contactsRecord.GetChildRecord(TizenContact.Number, i); + phones.Add(new ContactPhone(numberRecord.Get(TizenNumberView.NumberData))); + } + + var emails = new List(); + var emailCount = contactsRecord.GetChildRecordCount(TizenContact.Email); + for (var i = 0; i < emailCount; i++) + { + var emailRecord = contactsRecord.GetChildRecord(TizenContact.Email, i); + emails.Add(new ContactEmail(emailRecord.Get(TizenEmailView.Address))); + } + + return new Contact( + nameRecord is null ? null : nameRecord.Get(TizenNameView.ContactId).ToString(System.Globalization.CultureInfo.InvariantCulture), + nameRecord?.Get(TizenNameView.Prefix), + nameRecord?.Get(TizenNameView.First), + nameRecord?.Get(TizenNameView.Addition), + nameRecord?.Get(TizenNameView.Last), + nameRecord?.Get(TizenNameView.Suffix), + phones, + emails); + } + } +} diff --git a/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs new file mode 100644 index 00000000..84db7635 --- /dev/null +++ b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenApplication = Tizen.Applications.Application; +using TizenCoreApplication = Tizen.Applications.CoreApplication; +using TizenDeviceOrientation = Tizen.Applications.DeviceOrientation; +using TizenDeviceOrientationEventArgs = Tizen.Applications.DeviceOrientationEventArgs; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Screen metrics come from the screen.width, screen.height and screen.dpi + /// feature keys; rotation is tracked through CoreApplication.DeviceOrientationChanged. + /// Keep-screen-on is implemented with device_power_request_lock. + /// + public sealed partial class TizenDeviceDisplay : IDeviceDisplay + { + // Matches Microsoft.Maui.Devices.DeviceDisplay.BaseLogicalDpi for Android/Tizen, which is internal. + internal const float BaseLogicalDpi = 160.0f; + + [LibraryImport("libcapi-system-device.so.0", EntryPoint = "device_power_request_lock")] + private static partial int RequestPowerLock(int type, int timeout); + + [LibraryImport("libcapi-system-device.so.0", EntryPoint = "device_power_release_lock")] + private static partial int ReleasePowerLock(int type); + + const int PowerLockDisplay = 1; + + readonly object _locker = new(); + + EventHandler? _mainDisplayInfoChanged; + bool _listening; + bool _keepScreenOn; + DisplayRotation _displayRotation = DisplayRotation.Rotation0; + DisplayOrientation _displayOrientation = DisplayOrientation.Unknown; + + static TizenCoreApplication? CoreApplication => TizenApplication.Current as TizenCoreApplication; + + static int DisplayWidth => TizenSystemInformation.GetFeatureInfo("screen.width"); + + static int DisplayHeight => TizenSystemInformation.GetFeatureInfo("screen.height"); + + static int DisplayDpi => + TizenSystemInformation.CurrentProfile == TizenDeviceProfile.TV + ? 72 + : TizenSystemInformation.GetFeatureInfo("screen.dpi"); + + /// + public bool KeepScreenOn + { + get => _keepScreenOn; + set + { + var result = value + ? RequestPowerLock(PowerLockDisplay, 0) + : ReleasePowerLock(PowerLockDisplay); + + if (result != 0) + { + throw new InvalidOperationException( + $"Unable to {(value ? "acquire" : "release")} the Tizen display power lock (error {result}). " + + "Declare 'http://tizen.org/privilege/display' in tizen-manifest.xml."); + } + + _keepScreenOn = value; + } + } + + /// + public DisplayInfo MainDisplayInfo + { + get + { + var width = DisplayWidth; + var height = DisplayHeight; + + return new DisplayInfo( + width: width, + height: height, + density: DisplayDpi / BaseLogicalDpi, + orientation: _displayOrientation == DisplayOrientation.Unknown + ? GetNaturalOrientation(width, height) + : _displayOrientation, + rotation: _displayRotation); + } + } + + /// + public event EventHandler MainDisplayInfoChanged + { + add + { + lock (_locker) + { + var start = _mainDisplayInfoChanged is null; + _mainDisplayInfoChanged += value; + if (start && _mainDisplayInfoChanged is not null) + StartListeners(); + } + } + remove + { + lock (_locker) + { + _mainDisplayInfoChanged -= value; + if (_mainDisplayInfoChanged is null) + StopListeners(); + } + } + } + + void StartListeners() + { + if (_listening || CoreApplication is not { } app) + return; + + app.DeviceOrientationChanged += OnRotationChanged; + _listening = true; + } + + void StopListeners() + { + if (!_listening || CoreApplication is not { } app) + return; + + app.DeviceOrientationChanged -= OnRotationChanged; + _listening = false; + } + + static DisplayOrientation GetNaturalOrientation(int width, int height) => + height >= width ? DisplayOrientation.Portrait : DisplayOrientation.Landscape; + + internal static (DisplayRotation Rotation, DisplayOrientation Orientation) MapOrientation( + TizenDeviceOrientation deviceOrientation, + DisplayOrientation naturalOrientation) + { + var rotated = naturalOrientation == DisplayOrientation.Portrait + ? DisplayOrientation.Landscape + : DisplayOrientation.Portrait; + + return deviceOrientation switch + { + TizenDeviceOrientation.Orientation_0 => (DisplayRotation.Rotation0, naturalOrientation), + TizenDeviceOrientation.Orientation_90 => (DisplayRotation.Rotation90, rotated), + TizenDeviceOrientation.Orientation_180 => (DisplayRotation.Rotation180, naturalOrientation), + TizenDeviceOrientation.Orientation_270 => (DisplayRotation.Rotation270, rotated), + _ => (DisplayRotation.Unknown, DisplayOrientation.Unknown), + }; + } + + void OnRotationChanged(object? sender, TizenDeviceOrientationEventArgs e) + { + var natural = GetNaturalOrientation(DisplayWidth, DisplayHeight); + (_displayRotation, _displayOrientation) = MapOrientation(e.DeviceOrientation, natural); + + var args = new DisplayInfoChangedEventArgs(MainDisplayInfo); + MainThread.BeginInvokeOnMainThread(() => _mainDisplayInfoChanged?.Invoke(this, args)); + } + } +} diff --git a/src/Maui.Tizen.Essentials/DeviceInfo/TizenDeviceInfo.cs b/src/Maui.Tizen.Essentials/DeviceInfo/TizenDeviceInfo.cs new file mode 100644 index 00000000..b2d26082 --- /dev/null +++ b/src/Maui.Tizen.Essentials/DeviceInfo/TizenDeviceInfo.cs @@ -0,0 +1,62 @@ +using System; +using Microsoft.Maui.Devices; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen system and feature information keys. + /// + public sealed class TizenDeviceInfo : IDeviceInfo + { + /// + public string Model => TizenSystemInformation.GetSystemInfo("model_name") ?? string.Empty; + + /// + public string Manufacturer => TizenSystemInformation.GetSystemInfo("manufacturer") ?? string.Empty; + + /// + public string Name => TizenSystemInformation.GetSystemInfo("device_name") ?? string.Empty; + + /// + public string VersionString => TizenSystemInformation.GetFeatureInfo("platform.version") ?? string.Empty; + + /// + public Version Version => TizenPlatform.ParseVersion(VersionString); + + /// + public DevicePlatform Platform => DevicePlatform.Tizen; + + /// + public DeviceIdiom Idiom => TizenSystemInformation.CurrentProfile switch + { + TizenDeviceProfile.Mobile => DeviceIdiom.Phone, + TizenDeviceProfile.Wearable => DeviceIdiom.Watch, + TizenDeviceProfile.TV => DeviceIdiom.TV, + _ => DeviceIdiom.Unknown, + }; + + /// + public DeviceType DeviceType + { + get + { + var arch = TizenSystemInformation.GetFeatureInfo("platform.core.cpu.arch"); + var armv7 = TizenSystemInformation.GetFeatureInfo("platform.core.cpu.arch.armv7"); + var x86 = TizenSystemInformation.GetFeatureInfo("platform.core.cpu.arch.x86"); + + return ClassifyDeviceType(arch, armv7, x86); + } + } + + internal static DeviceType ClassifyDeviceType(string? arch, bool armv7, bool x86) + { + if (string.Equals(arch, "armv7", StringComparison.Ordinal) && armv7 && !x86) + return DeviceType.Physical; + + if (string.Equals(arch, "x86", StringComparison.Ordinal) && !armv7 && x86) + return DeviceType.Virtual; + + return DeviceType.Unknown; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs new file mode 100644 index 00000000..b1bcd17d --- /dev/null +++ b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs @@ -0,0 +1,86 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the mailto: compose AppControl. + /// + /// + /// Tizen's compose operation has no attachment slot, so + /// is rejected rather than silently dropped, and HTML bodies are sent as plain text. + /// + public sealed class TizenEmail : IEmail + { + /// + public bool IsComposeSupported => + TizenSystemInformation.GetFeatureInfo("email"); + + /// + public Task ComposeAsync(EmailMessage? message) + { + if (!IsComposeSupported) + throw TizenEssentialsSupport.NotSupportedOnProfile($"{nameof(IEmail)}.{nameof(ComposeAsync)}", TizenDeviceProfile.Mobile); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Compose, + Uri = "mailto:", + }; + + if (message is not null) + { + if (message.Attachments?.Count > 0) + { + throw TizenEssentialsSupport.NotSupported( + $"{nameof(IEmail)}.{nameof(ComposeAsync)} with attachments", + "The Tizen 'compose' AppControl operation accepts no attachment payload."); + } + + if (message.Bcc?.Count > 0) + appControl.ExtraData.Add(TizenAppControlData.Bcc, message.Bcc); + if (!string.IsNullOrEmpty(message.Body)) + appControl.ExtraData.Add(TizenAppControlData.Text, message.Body); + if (message.Cc?.Count > 0) + appControl.ExtraData.Add(TizenAppControlData.Cc, message.Cc); + if (!string.IsNullOrEmpty(message.Subject)) + appControl.ExtraData.Add(TizenAppControlData.Subject, message.Subject); + if (message.To?.Count > 0) + appControl.ExtraData.Add(TizenAppControlData.To, message.To); + } + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.CompletedTask; + } + + /// + /// Composes an email with the supplied subject, body and recipients. + /// + /// The email subject. + /// The email body. + /// The recipients. + /// A task that completes once the compose request has been sent. + public Task ComposeAsync(string subject, string body, params string[] to) => + ComposeAsync(new EmailMessage + { + Subject = subject, + Body = body, + To = to?.ToList() ?? new System.Collections.Generic.List(), + }); + + /// + /// Opens the platform email composer with an empty message. + /// + /// A task that completes once the compose request has been sent. + public Task ComposeAsync() => ComposeAsync(null); + } +} diff --git a/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs b/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs new file mode 100644 index 00000000..82a684fb --- /dev/null +++ b/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Storage; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlLaunchMode = Tizen.Applications.AppControlLaunchMode; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenAppControlReplyResult = Tizen.Applications.AppControlReplyResult; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the pick AppControl operation. + /// + public sealed class TizenFilePicker : IFilePicker + { + /// + public async Task PickAsync(PickOptions? options = null) => + (await PlatformPickAsync(options, allowMultiple: false).ConfigureAwait(false)).FirstOrDefault(); + + /// + public async Task?> PickMultipleAsync(PickOptions? options = null) => + await PlatformPickAsync(options, allowMultiple: true).ConfigureAwait(false); + + async Task> PlatformPickAsync(PickOptions? options, bool allowMultiple) + { + TizenPermissions.EnsureDeclared(); + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); + + var tcs = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Pick, + LaunchMode = TizenAppControlLaunchMode.Single, + Mime = ResolveMimeType(options), + }; + appControl.ExtraData.Add(TizenAppControlData.SectionMode, allowMultiple ? "multiple" : "single"); + + TizenAppControl.SendLaunchRequest(appControl, (request, reply, result) => + { + var files = new List(); + + if (result == TizenAppControlReplyResult.Succeeded && + reply.ExtraData.TryGet(TizenAppControlData.Selected, out IEnumerable selected) && + selected is not null) + { + files.AddRange(selected.Select(static f => new FileResult(f))); + } + + tcs.TrySetResult(files); + }); + + return await tcs.Task.ConfigureAwait(false); + } + + static string ResolveMimeType(PickOptions? options) + { + if (options?.FileTypes?.Value is not { } values) + return TizenFileMimeTypes.All; + + // Tizen's pick operation accepts exactly one MIME filter. + return values.FirstOrDefault() ?? TizenFileMimeTypes.All; + } + + /// + /// Creates a for the supplied Tizen MIME types. + /// + /// The MIME types to accept. + /// A Tizen-scoped . + /// + /// The built-in -style helpers resolve their Tizen entry + /// from the in-box dotnet/maui Tizen backend, which is not present in the neutral + /// Microsoft.Maui.Essentials assembly. Use these helpers instead when targeting Tizen. + /// + public static FilePickerFileType CreateFileType(params string[] mimeTypes) => + new(new Dictionary> + { + [DevicePlatform.Tizen] = mimeTypes, + }); + + /// Gets a Tizen that matches all image files. + public static FilePickerFileType ImageFileType { get; } = CreateFileType(TizenFileMimeTypes.ImageAll); + + /// Gets a Tizen that matches PNG files. + public static FilePickerFileType PngFileType { get; } = CreateFileType(TizenFileMimeTypes.ImagePng); + + /// Gets a Tizen that matches JPEG files. + public static FilePickerFileType JpegFileType { get; } = CreateFileType(TizenFileMimeTypes.ImageJpg); + + /// Gets a Tizen that matches all video files. + public static FilePickerFileType VideoFileType { get; } = CreateFileType(TizenFileMimeTypes.VideoAll); + + /// Gets a Tizen that matches PDF files. + public static FilePickerFileType PdfFileType { get; } = CreateFileType(TizenFileMimeTypes.Pdf); + } +} diff --git a/src/Maui.Tizen.Essentials/FileSystem/TizenFileSystem.cs b/src/Maui.Tizen.Essentials/FileSystem/TizenFileSystem.cs new file mode 100644 index 00000000..8212c555 --- /dev/null +++ b/src/Maui.Tizen.Essentials/FileSystem/TizenFileSystem.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Maui.Storage; +using TizenApplication = Tizen.Applications.Application; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the application's + /// DirectoryInfo data, cache and resource paths. + /// + public sealed class TizenFileSystem : IFileSystem + { + /// + public string CacheDirectory => TizenApplication.Current.DirectoryInfo.Cache; + + /// + public string AppDataDirectory => TizenApplication.Current.DirectoryInfo.Data; + + /// + public Task OpenAppPackageFileAsync(string filename) => + Task.FromResult(File.OpenRead(GetFullAppPackageFilePath(filename))); + + /// + public Task AppPackageFileExistsAsync(string filename) => + Task.FromResult(File.Exists(GetFullAppPackageFilePath(filename))); + + /// + /// Resolves a packaged resource file name to its full on-device path. + /// + /// The resource-relative file name. + /// The absolute path inside the application's resource directory. + public static string GetFullAppPackageFilePath(string filename) + { + if (string.IsNullOrWhiteSpace(filename)) + throw new ArgumentNullException(nameof(filename)); + + return Path.Combine( + TizenApplication.Current.DirectoryInfo.Resource, + filename.Replace('\\', Path.DirectorySeparatorChar)); + } + + /// + /// Resolves the MIME type for a file extension using Tizen.Content.MimeType. + /// + /// The file extension, with or without a leading dot. + /// The resolved MIME type. + public static string GetContentType(string extension) + { + ArgumentNullException.ThrowIfNull(extension); + + return global::Tizen.Content.MimeType.MimeUtil.GetMimeType(extension.TrimStart('.')); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Flashlight/TizenFlashlight.cs b/src/Maui.Tizen.Essentials/Flashlight/TizenFlashlight.cs new file mode 100644 index 00000000..56718b0d --- /dev/null +++ b/src/Maui.Tizen.Essentials/Flashlight/TizenFlashlight.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenLed = Tizen.System.Led; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.System.Led. + /// + public sealed class TizenFlashlight : IFlashlight + { + static bool IsSupported => + TizenSystemInformation.GetFeatureInfo("camera.back.flash"); + + /// + public Task IsSupportedAsync() => Task.FromResult(IsSupported); + + /// + public Task TurnOnAsync() => SwitchAsync(true); + + /// + public Task TurnOffAsync() => SwitchAsync(false); + + static Task SwitchAsync(bool on) + { + TizenPermissions.EnsureDeclared(); + + return Task.Run(() => + { + if (!IsSupported) + { + throw TizenEssentialsSupport.NotSupportedOnProfile( + $"{nameof(IFlashlight)}.{(on ? nameof(TurnOnAsync) : nameof(TurnOffAsync))}", + TizenDeviceProfile.Mobile); + } + + TizenLed.Brightness = on ? TizenLed.MaxBrightness : 0; + }); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs b/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs new file mode 100644 index 00000000..25dec519 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs @@ -0,0 +1,124 @@ +// MapService is marked deprecated from Tizen API level 11 onwards, but Tizen ships no replacement +// geocoding service, so this backend keeps using it (as dotnet/maui did). +#pragma warning disable CS0618 // Type or member is obsolete + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using Tizen.Maps; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Maps (HERE provider). + /// + /// + /// A map service token is required. Supply it with + /// builder.ConfigureEssentials(e => e.UseMapServiceToken("...")): the .NET 11 Essentials + /// DI bridge forwards configured map tokens to the registered . + /// + public sealed class TizenGeocoding : IPlatformGeocoding, IDisposable + { + readonly SemaphoreSlim _mapServiceLock = new(1, 1); + + MapService? _mapService; + bool _disposed; + + /// + public string? MapServiceToken { get; set; } + + /// + public async Task> GetPlacemarksAsync(double latitude, double longitude) + { + var map = await GetMapServiceAsync().ConfigureAwait(false); + + var request = map.CreateReverseGeocodeRequest(latitude, longitude); + + var placemarks = new List(); + foreach (var address in await request.GetResponseAsync().ConfigureAwait(false)) + { + placemarks.Add(new Placemark + { + CountryCode = address.CountryCode, + CountryName = address.Country, + AdminArea = address.State, + SubAdminArea = address.County, + Locality = address.City, + SubLocality = address.District, + Thoroughfare = address.Street, + SubThoroughfare = address.Building, + FeatureName = address.Street, + Location = new Location(latitude, longitude), + PostalCode = address.PostalCode, + }); + } + + return placemarks; + } + + /// + public async Task> GetLocationsAsync(string address) + { + ArgumentNullException.ThrowIfNull(address); + + var map = await GetMapServiceAsync().ConfigureAwait(false); + + var request = map.CreateGeocodeRequest(address); + + var locations = new List(); + foreach (var position in await request.GetResponseAsync().ConfigureAwait(false)) + locations.Add(new Location(position.Latitude, position.Longitude)); + + return locations; + } + + async Task GetMapServiceAsync() + { + ObjectDisposedException.ThrowIf(_disposed, this); + + var token = MapServiceToken; + + if (string.IsNullOrWhiteSpace(token)) + { + throw new ArgumentNullException( + nameof(MapServiceToken), + "Set the map service token to be able to use geocoding on Tizen, for example with " + + "builder.ConfigureEssentials(essentials => essentials.UseMapServiceToken(\"...\"))."); + } + + TizenPermissions.EnsureDeclared(); + + await _mapServiceLock.WaitAsync().ConfigureAwait(false); + try + { + if (_mapService is null) + { + var service = new MapService("HERE", token); + await service.RequestUserConsent().ConfigureAwait(false); + _mapService = service; + } + + return _mapService; + } + finally + { + _mapServiceLock.Release(); + } + } + + /// + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _mapService?.Dispose(); + _mapService = null; + _mapServiceLock.Dispose(); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs new file mode 100644 index 00000000..f1011ddb --- /dev/null +++ b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs @@ -0,0 +1,150 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using TizenLocationChangedEventArgs = Tizen.Location.LocationChangedEventArgs; +using TizenLocationType = Tizen.Location.LocationType; +using TizenLocator = Tizen.Location.Locator; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Location.Locator. + /// + /// + /// Continuous foreground listening is not implemented by this backend: + /// and throw + /// rather than silently succeeding while never raising . + /// One-shot location requests are fully supported. + /// + public sealed class TizenGeolocation : IGeolocation + { + const string ListeningReason = + "Continuous foreground location updates are not implemented by the Tizen Essentials backend. " + + "Use GetLocationAsync for one-shot requests."; + + readonly object _locker = new(); + + Location? _lastKnownLocation; + + /// + public bool IsListeningForeground => false; + + /// + public bool IsEnabled => + TizenSystemInformation.GetFeatureInfo("location.gps") || + TizenSystemInformation.GetFeatureInfo("location.wps"); + + /// + /// Never raised: continuous listening is unsupported on this backend. + public event EventHandler? LocationChanged + { + add { } + remove { } + } + + /// + /// Never raised: continuous listening is unsupported on this backend. + public event EventHandler? ListeningFailed + { + add { } + remove { } + } + + /// + public Task GetLastKnownLocationAsync() + { + lock (_locker) + return Task.FromResult(_lastKnownLocation); + } + + /// + public async Task GetLocationAsync(GeolocationRequest request, CancellationToken cancelToken) + { + ArgumentNullException.ThrowIfNull(request); + + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); + + using var locator = new TizenLocator(ResolveLocationType()); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancelToken); + if (request.Timeout > TimeSpan.Zero) + timeoutSource.CancelAfter(request.Timeout); + + void OnLocationChanged(object? sender, TizenLocationChangedEventArgs e) + { + if (e.Location is null) + return; + + var location = new Location + { + Accuracy = e.Location.Accuracy, + Altitude = e.Location.Altitude, + Course = e.Location.Direction, + Latitude = e.Location.Latitude, + Longitude = e.Location.Longitude, + Speed = KilometersPerHourToMetersPerSecond(e.Location.Speed), + Timestamp = e.Location.Timestamp, + }; + + lock (_locker) + _lastKnownLocation = location; + + tcs.TrySetResult(location); + } + + locator.LocationChanged += OnLocationChanged; + + using var registration = timeoutSource.Token.Register(() => tcs.TrySetResult(null)); + + try + { + locator.Start(); + return await tcs.Task.ConfigureAwait(false); + } + finally + { + locator.LocationChanged -= OnLocationChanged; + + try + { + locator.Stop(); + } + catch + { + // The locator may already have stopped; nothing actionable. + } + } + } + + /// + /// Always thrown. + public Task StartListeningForegroundAsync(GeolocationListeningRequest request) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IGeolocation)}.{nameof(StartListeningForegroundAsync)}", ListeningReason); + + /// + /// Always thrown. + public void StopListeningForeground() => + throw TizenEssentialsSupport.NotSupported($"{nameof(IGeolocation)}.{nameof(StopListeningForeground)}", ListeningReason); + + internal static TizenLocationType ResolveLocationType() + { + var gps = TizenSystemInformation.GetFeatureInfo("location.gps"); + var wps = TizenSystemInformation.GetFeatureInfo("location.wps"); + + return (gps, wps) switch + { + (true, true) => TizenLocationType.Hybrid, + (true, false) => TizenLocationType.Gps, + (false, true) => TizenLocationType.Wps, + _ => TizenLocationType.Passive, + }; + } + + internal static double KilometersPerHourToMetersPerSecond(double kilometersPerHour) => + kilometersPerHour * 0.277778; + } +} diff --git a/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs b/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs new file mode 100644 index 00000000..103b03c3 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenGyroscopeSensor = Tizen.Sensor.Gyroscope; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Sensor.Gyroscope. + /// + public sealed class TizenGyroscope : TizenSensorBase, IGyroscope + { + /// + public event EventHandler? ReadingChanged; + + /// + public override bool IsSupported => TizenGyroscopeSensor.IsSupported; + + /// + protected override string SensorName => nameof(IGyroscope); + + /// + protected override TizenGyroscopeSensor Sensor => + (TizenGyroscopeSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Gyroscope); + + /// + protected override void Subscribe(TizenGyroscopeSensor sensor) => sensor.DataUpdated += OnDataUpdated; + + /// + protected override void Unsubscribe(TizenGyroscopeSensor sensor) => sensor.DataUpdated -= OnDataUpdated; + + void OnDataUpdated(object? sender, global::Tizen.Sensor.GyroscopeDataUpdatedEventArgs e) => + Raise(ReadingChanged, new GyroscopeChangedEventArgs(new GyroscopeData(e.X, e.Y, e.Z))); + } +} diff --git a/src/Maui.Tizen.Essentials/HapticFeedback/TizenHapticFeedback.cs b/src/Maui.Tizen.Essentials/HapticFeedback/TizenHapticFeedback.cs new file mode 100644 index 00000000..1c1c1d4a --- /dev/null +++ b/src/Maui.Tizen.Essentials/HapticFeedback/TizenHapticFeedback.cs @@ -0,0 +1,58 @@ +using System; +using System.Diagnostics; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenFeedback = Tizen.System.Feedback; +using TizenFeedbackType = Tizen.System.FeedbackType; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.System.Feedback. + /// + public sealed class TizenHapticFeedback : IHapticFeedback + { + /// + public bool IsSupported + { + get + { + try + { + var feedback = new TizenFeedback(); + return feedback.IsSupportedPattern(TizenFeedbackType.Vibration, "Tap"); + } + catch (Exception ex) + { + Debug.WriteLine($"TizenHapticFeedback.IsSupported failed: {ex.Message}"); + return false; + } + } + } + + /// + public void Perform(HapticFeedbackType type) + { + TizenPermissions.EnsureDeclared(); + + var pattern = ConvertType(type); + var feedback = new TizenFeedback(); + + if (!feedback.IsSupportedPattern(TizenFeedbackType.Vibration, pattern)) + { + throw TizenEssentialsSupport.NotSupported( + $"{nameof(IHapticFeedback)}.{nameof(Perform)}({type})", + $"The Tizen feedback pattern '{pattern}' is not supported by this device."); + } + + feedback.Play(TizenFeedbackType.Vibration, pattern); + } + + internal static string ConvertType(HapticFeedbackType type) => + type switch + { + HapticFeedbackType.LongPress => "Hold", + _ => "Tap", + }; + } +} diff --git a/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs b/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs new file mode 100644 index 00000000..1c234c56 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs @@ -0,0 +1,140 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Maui.Accessibility; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using Microsoft.Maui.ApplicationModel.DataTransfer; +using Microsoft.Maui.Authentication; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Media; +using Microsoft.Maui.Networking; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Microsoft.Maui.Storage; + +namespace Microsoft.Maui.Hosting +{ + /// + /// Registers the Tizen Essentials implementations with a . + /// + public static class TizenEssentialsMauiAppBuilderExtensions + { + /// + /// Registers every Tizen Essentials service implementation into the application's + /// dependency injection container. + /// + /// The app builder to configure. + /// The same , for chaining. + /// + /// + /// Every service is registered as a singleton with TryAdd semantics, so an application + /// (or another platform backend) can replace any individual implementation simply by + /// registering its own before calling this method. + /// + /// + /// Registration alone is enough to also drive the static Essentials facades + /// (Battery.Default, Connectivity.Current, ...). .NET 11 MAUI bridges + /// DI-registered Essentials services onto their facades during MauiApp initialization + /// (dotnet/maui#36657), so this method deliberately performs no SetDefault reflection + /// of its own. + /// + /// + /// MainThread is likewise not configured here: MAUI bridges + /// MainThread.BeginInvokeOnMainThread from the registered IDispatcher for + /// non in-box platforms, so the Tizen dispatcher provided by the core Tizen backend is the + /// single source of truth for main-thread marshalling. + /// + /// + /// Services whose contract Tizen cannot satisfy (, + /// , , + /// and ) are still registered. + /// Their implementations throw with an explicit + /// reason, which is a materially better developer experience than resolving MAUI's neutral + /// "not implemented in reference assembly" fallbacks. + /// + /// + public static MauiAppBuilder AddTizenEssentials(this MauiAppBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + + AddTizenEssentials(builder.Services); + + return builder; + } + + /// + /// Registers every Tizen Essentials service implementation into a service collection. + /// + /// The service collection to configure. + /// The same , for chaining. + public static IServiceCollection AddTizenEssentials(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + + // Application model + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Communication + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Data transfer + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Storage + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Device + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Sensors + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Location + services.TryAddSingleton(); + services.TryAddSingleton(static sp => sp.GetRequiredService()); + services.TryAddSingleton(static sp => sp.GetRequiredService()); + services.TryAddSingleton(); + + // Networking + services.TryAddSingleton(); + + // Media + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + // Accessibility + services.TryAddSingleton(); + + // Authentication + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + return services; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs new file mode 100644 index 00000000..a5997ce6 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs @@ -0,0 +1,92 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Storage; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by AppControl launch requests. + /// + public sealed class TizenLauncher : ILauncher + { + /// + public Task CanOpenAsync(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + return Task.FromResult(uri.IsWellFormedOriginalString()); + } + + /// + public Task OpenAsync(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = GetOperation(uri), + Uri = uri.AbsoluteUri, + }; + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(true); + } + + /// + public Task OpenAsync(OpenFileRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + if (string.IsNullOrEmpty(request.File?.FullPath)) + throw new ArgumentException("An OpenFileRequest requires a file with a full path.", nameof(request)); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.View, + Mime = TizenFileMimeTypes.All, + Uri = "file://" + request.File.FullPath, + }; + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(true); + } + + /// + public async Task TryOpenAsync(Uri uri) + { + var canOpen = await CanOpenAsync(uri).ConfigureAwait(false); + + if (canOpen) + await OpenAsync(uri).ConfigureAwait(false); + + return canOpen; + } + + static string GetOperation(Uri uri) + { + var absoluteUri = uri.AbsoluteUri; + + if (absoluteUri.StartsWith("geo:", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.Pick; + if (absoluteUri.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.View; + if (absoluteUri.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.Compose; + if (absoluteUri.StartsWith("sms:", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.Compose; + if (absoluteUri.StartsWith("tel:", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.Dial; + + return TizenAppControlOperations.ShareText; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs b/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs new file mode 100644 index 00000000..b8bbfff5 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenMagnetometerSensor = Tizen.Sensor.Magnetometer; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Sensor.Magnetometer. + /// + public sealed class TizenMagnetometer : TizenSensorBase, IMagnetometer + { + /// + public event EventHandler? ReadingChanged; + + /// + public override bool IsSupported => TizenMagnetometerSensor.IsSupported; + + /// + protected override string SensorName => nameof(IMagnetometer); + + /// + protected override TizenMagnetometerSensor Sensor => + (TizenMagnetometerSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Magnetometer); + + /// + protected override void Subscribe(TizenMagnetometerSensor sensor) => sensor.DataUpdated += OnDataUpdated; + + /// + protected override void Unsubscribe(TizenMagnetometerSensor sensor) => sensor.DataUpdated -= OnDataUpdated; + + void OnDataUpdated(object? sender, global::Tizen.Sensor.MagnetometerDataUpdatedEventArgs e) => + Raise(ReadingChanged, new MagnetometerChangedEventArgs(new MagnetometerData(e.X, e.Y, e.Z))); + } +} diff --git a/src/Maui.Tizen.Essentials/Map/TizenMap.cs b/src/Maui.Tizen.Essentials/Map/TizenMap.cs new file mode 100644 index 00000000..8990821b --- /dev/null +++ b/src/Maui.Tizen.Essentials/Map/TizenMap.cs @@ -0,0 +1,80 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by geo: AppControl launch requests. + /// + /// + /// Tizen's geo: handler accepts a coordinate or a free-form query only, so + /// and the map launch name cannot be honoured. + /// + public sealed class TizenMap : IMap + { + /// + public Task OpenAsync(double latitude, double longitude, MapLaunchOptions options) => + Launch(CreateAppControl(latitude, longitude, options)); + + /// + public Task OpenAsync(Placemark placemark, MapLaunchOptions options) => + Launch(CreateAppControl(placemark, options)); + + /// + public Task TryOpenAsync(double latitude, double longitude, MapLaunchOptions options) => + TryLaunch(CreateAppControl(latitude, longitude, options)); + + /// + public Task TryOpenAsync(Placemark placemark, MapLaunchOptions options) => + TryLaunch(CreateAppControl(placemark, options)); + + internal static TizenAppControl CreateAppControl(double latitude, double longitude, MapLaunchOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + TizenPermissions.EnsureDeclared(); + + return new TizenAppControl + { + Operation = TizenAppControlOperations.View, + Uri = FormattableString.Invariant($"geo:{latitude.ToString(CultureInfo.InvariantCulture)},{longitude.ToString(CultureInfo.InvariantCulture)}"), + }; + } + + internal static TizenAppControl CreateAppControl(Placemark placemark, MapLaunchOptions options) + { + ArgumentNullException.ThrowIfNull(placemark); + ArgumentNullException.ThrowIfNull(options); + + TizenPermissions.EnsureDeclared(); + + return new TizenAppControl + { + Operation = TizenAppControlOperations.Pick, + Uri = $"geo:0,0?q={placemark.GetEscapedAddress()}", + }; + } + + static Task Launch(TizenAppControl appControl) + { + TizenAppControl.SendLaunchRequest(appControl); + return Task.CompletedTask; + } + + static Task TryLaunch(TizenAppControl appControl) + { + var canLaunch = TizenAppControl.GetMatchedApplicationIds(appControl).Any(); + + if (canLaunch) + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(canLaunch); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj b/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj new file mode 100644 index 00000000..5dd00eaf --- /dev/null +++ b/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj @@ -0,0 +1,31 @@ + + + + $(MauiTizenDotNetTfm) + Maui.Tizen.Essentials + Microsoft.Maui.Platforms.Tizen.Essentials + true + true + true + + true + + + + true + Maui.Tizen.Essentials + maui;tizen;essentials;sensors + Tizen implementations of the .NET MAUI Essentials service contracts, delivered as a standalone platform backend package for .NET 11 and newer. + + + + + + + + + + + + + diff --git a/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs new file mode 100644 index 00000000..ae498dfe --- /dev/null +++ b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Media; +using Microsoft.Maui.Storage; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlLaunchMode = Tizen.Applications.AppControlLaunchMode; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenAppControlReplyResult = Tizen.Applications.AppControlReplyResult; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Picking delegates to the Tizen file picker with an image or video MIME filter; capturing uses + /// the image_capture and video_capture AppControl operations. + /// + public sealed class TizenMediaPicker : IMediaPicker + { + readonly TizenFilePicker _filePicker = new(); + + /// + public bool IsCaptureSupported => + TizenSystemInformation.GetFeatureInfo("camera") || + TizenSystemInformation.GetFeatureInfo("camera.back") || + TizenSystemInformation.GetFeatureInfo("camera.front"); + + /// + [Obsolete("Switch to PickPhotosAsync which also allows multiple selections.")] + public Task PickPhotoAsync(MediaPickerOptions? options = null) => + _filePicker.PickAsync(CreatePickOptions(options, TizenFilePicker.ImageFileType)); + + /// + public async Task> PickPhotosAsync(MediaPickerOptions? options = null) => + (await _filePicker.PickMultipleAsync(CreatePickOptions(options, TizenFilePicker.ImageFileType)).ConfigureAwait(false)) + ?.ToList() ?? new List(); + + /// + [Obsolete("Switch to PickVideosAsync which also allows multiple selections.")] + public Task PickVideoAsync(MediaPickerOptions? options = null) => + _filePicker.PickAsync(CreatePickOptions(options, TizenFilePicker.VideoFileType)); + + /// + public async Task> PickVideosAsync(MediaPickerOptions? options = null) => + (await _filePicker.PickMultipleAsync(CreatePickOptions(options, TizenFilePicker.VideoFileType)).ConfigureAwait(false)) + ?.ToList() ?? new List(); + + /// + public Task CapturePhotoAsync(MediaPickerOptions? options = null) => + CaptureAsync(photo: true); + + /// + public Task CaptureVideoAsync(MediaPickerOptions? options = null) => + CaptureAsync(photo: false); + + static PickOptions CreatePickOptions(MediaPickerOptions? options, FilePickerFileType fileType) => + new() + { + PickerTitle = options?.Title, + FileTypes = fileType, + }; + + async Task CaptureAsync(bool photo) + { + if (!IsCaptureSupported) + { + throw TizenEssentialsSupport.NotSupportedOnProfile( + $"{nameof(IMediaPicker)}.{(photo ? nameof(CapturePhotoAsync) : nameof(CaptureVideoAsync))}", + TizenDeviceProfile.Mobile); + } + + TizenPermissions.EnsureDeclared(); + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var appControl = new TizenAppControl + { + Operation = photo ? TizenAppControlOperations.ImageCapture : TizenAppControlOperations.VideoCapture, + LaunchMode = TizenAppControlLaunchMode.Group, + }; + + var appId = TizenAppControl.GetMatchedApplicationIds(appControl)?.FirstOrDefault(); + if (!string.IsNullOrEmpty(appId)) + appControl.ApplicationId = appId; + + TizenAppControl.SendLaunchRequest(appControl, (request, reply, result) => + { + if (result == TizenAppControlReplyResult.Succeeded && + reply.ExtraData.TryGet(TizenAppControlData.Selected, out IEnumerable selected)) + { + var file = selected?.FirstOrDefault(); + tcs.TrySetResult(string.IsNullOrEmpty(file) ? null : new FileResult(file)); + } + else + { + tcs.TrySetCanceled(); + } + }); + + return await tcs.Task.ConfigureAwait(false); + } + } +} diff --git a/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs new file mode 100644 index 00000000..a74fc4b4 --- /dev/null +++ b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenRotationVectorSensor = Tizen.Sensor.RotationVectorSensor; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Sensor.RotationVectorSensor. + /// + public sealed class TizenOrientationSensor : TizenSensorBase, IOrientationSensor + { + /// + public event EventHandler? ReadingChanged; + + /// + public override bool IsSupported => TizenRotationVectorSensor.IsSupported; + + /// + protected override string SensorName => nameof(IOrientationSensor); + + /// + protected override TizenRotationVectorSensor Sensor => + (TizenRotationVectorSensor)TizenSensors.GetDefaultSensor(TizenSensorType.OrientationSensor); + + /// + protected override void Subscribe(TizenRotationVectorSensor sensor) => sensor.DataUpdated += OnDataUpdated; + + /// + protected override void Unsubscribe(TizenRotationVectorSensor sensor) => sensor.DataUpdated -= OnDataUpdated; + + void OnDataUpdated(object? sender, global::Tizen.Sensor.RotationVectorSensorDataUpdatedEventArgs e) => + Raise(ReadingChanged, new OrientationSensorChangedEventArgs(new OrientationSensorData(e.X, e.Y, e.Z, e.W))); + } +} diff --git a/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs new file mode 100644 index 00000000..b3d9bfcc --- /dev/null +++ b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Authentication; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Tizen exposes FIDO UAF through Tizen.Account.FidoClient, which is a different protocol + /// from the WebAuthn / CTAP2 contract that models. There is no Tizen + /// credential manager that can produce a WebAuthn attestation or assertion, so + /// reports and both operations throw. + /// + public sealed class TizenPasskeys : IPasskeys + { + const string Reason = + "Tizen ships FIDO UAF (Tizen.Account.FidoClient) but no WebAuthn/CTAP2 credential " + + "manager that can satisfy the passkey creation and assertion contract."; + + /// + public bool IsSupported => false; + + /// + /// Always thrown. + public Task CreateAsync(PasskeyCreationOptions options, CancellationToken cancellationToken = default) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IPasskeys)}.{nameof(CreateAsync)}", Reason); + + /// + /// Always thrown. + public Task AssertAsync(PasskeyRequestOptions options, CancellationToken cancellationToken = default) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IPasskeys)}.{nameof(AssertAsync)}", Reason); + } +} diff --git a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs new file mode 100644 index 00000000..6d440870 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs @@ -0,0 +1,302 @@ +// PrivacyPrivilegeManager is marked deprecated from Tizen API level 11 onwards, but Tizen ships no +// replacement for runtime privilege checks, so this backend keeps using it (as dotnet/maui did). +#pragma warning disable CS0618 // Type or member is obsolete + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using TizenPrivacyPrivilegeManager = Tizen.Security.PrivacyPrivilegeManager; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// A Tizen privilege requirement declared by an Essentials permission. + /// + /// The fully qualified Tizen privilege, for example http://tizen.org/privilege/location. + /// + /// when the privilege is a privacy related privilege that must additionally be + /// granted by the user at runtime; when declaring it in + /// tizen-manifest.xml is sufficient. + /// + public readonly record struct TizenPrivilege(string Privilege, bool IsRuntime); + + /// + /// Base class for user defined Tizen permissions. + /// + /// + /// dotnet/maui declared Permissions.BasePlatformPermission as a Tizen specific partial class. + /// Partial classes cannot span assemblies, so this standalone backend provides an equivalent base + /// type. Derive from it to declare additional privileges and pass the derived type to + /// or + /// . + /// + public abstract class TizenBasePlatformPermission : Permissions.BasePermission + { + /// + /// Gets the privileges that must be present in the application's tizen-manifest.xml. + /// + public virtual TizenPrivilege[] RequiredPrivileges { get; } = Array.Empty(); + + /// + public override Task CheckStatusAsync() => + TizenPermissions.CheckPrivilegesAsync(RequiredPrivileges, ask: false); + + /// + public override Task RequestAsync() => + TizenPermissions.CheckPrivilegesAsync(RequiredPrivileges, ask: true); + + /// + public override void EnsureDeclared() => + TizenPermissions.EnsureDeclared(RequiredPrivileges); + + /// + public override bool ShouldShowRationale() => false; + } + + /// + /// Tizen implementation of , backed by + /// and the application's tizen-manifest.xml. + /// + /// + /// The built in Permissions.Camera, Permissions.LocationWhenInUse, ... types in the + /// neutral Microsoft.Maui.Essentials assembly derive from a + /// Permissions.BasePlatformPermission whose members throw. This implementation therefore + /// maps those well known permission types to their Tizen privileges itself instead of delegating + /// to the permission instance, which keeps Permissions.RequestAsync<Permissions.Camera>() + /// source compatible with the in-box dotnet/maui Tizen backend. + /// + public sealed class TizenPermissions : IPermissions + { + internal static readonly IReadOnlyDictionary KnownPermissionPrivileges = + new Dictionary + { + // Declared with no privileges: Tizen requires nothing for these, so they resolve as granted. + [typeof(Permissions.Battery)] = Array.Empty(), + [typeof(Permissions.Bluetooth)] = Array.Empty(), + [typeof(Permissions.CalendarRead)] = Array.Empty(), + [typeof(Permissions.CalendarWrite)] = Array.Empty(), + [typeof(Permissions.Media)] = Array.Empty(), + [typeof(Permissions.NearbyWifiDevices)] = Array.Empty(), + [typeof(Permissions.Phone)] = Array.Empty(), + [typeof(Permissions.Photos)] = Array.Empty(), + [typeof(Permissions.PhotosAddOnly)] = Array.Empty(), + [typeof(Permissions.PostNotifications)] = Array.Empty(), + [typeof(Permissions.Reminders)] = Array.Empty(), + [typeof(Permissions.Sensors)] = Array.Empty(), + [typeof(Permissions.Sms)] = Array.Empty(), + [typeof(Permissions.Speech)] = Array.Empty(), + + [typeof(Permissions.Camera)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/camera", false), + }, + [typeof(Permissions.ContactsRead)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/contact.read", true), + }, + [typeof(Permissions.ContactsWrite)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/contact.write", true), + }, + [typeof(Permissions.Flashlight)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/led", false), + }, + [typeof(Permissions.LaunchApp)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/appmanager.launch", false), + }, + [typeof(Permissions.LocationWhenInUse)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/location", true), + }, + [typeof(Permissions.LocationAlways)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/location", true), + }, + [typeof(Permissions.Maps)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/internet", false), + new TizenPrivilege("http://tizen.org/privilege/mapservice", false), + new TizenPrivilege("http://tizen.org/privilege/network.get", false), + }, + [typeof(Permissions.Microphone)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/recorder", false), + }, + [typeof(Permissions.NetworkState)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/internet", false), + new TizenPrivilege("http://tizen.org/privilege/network.get", false), + }, + [typeof(Permissions.StorageRead)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true), + }, + [typeof(Permissions.StorageWrite)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true), + }, + [typeof(Permissions.Vibrate)] = new[] + { + new TizenPrivilege("http://tizen.org/privilege/haptic", false), + }, + }; + + /// + public Task CheckStatusAsync() + where TPermission : Permissions.BasePermission, new() => + ResolveAsync(ask: false); + + /// + public Task RequestAsync() + where TPermission : Permissions.BasePermission, new() => + ResolveAsync(ask: true); + + /// + /// Tizen has no rationale UI contract, so this always returns . + public bool ShouldShowRationale() + where TPermission : Permissions.BasePermission, new() => false; + + static Task ResolveAsync(bool ask) + where TPermission : Permissions.BasePermission, new() + { + if (TryGetKnownPrivileges(typeof(TPermission), out var privileges)) + return CheckPrivilegesAsync(privileges, ask); + + // Custom permission types own their behaviour (including TizenBasePlatformPermission). + var permission = new TPermission(); + return ask ? permission.RequestAsync() : permission.CheckStatusAsync(); + } + + internal static bool TryGetKnownPrivileges(Type permissionType, [NotNullWhen(true)] out TizenPrivilege[]? privileges) + { + for (var type = permissionType; type is not null; type = type.BaseType) + { + if (KnownPermissionPrivileges.TryGetValue(type, out privileges)) + return true; + } + + privileges = null; + return false; + } + + /// + /// Determines whether the supplied privilege is declared in the application's tizen-manifest.xml. + /// + /// The fully qualified Tizen privilege. + /// when the privilege is declared; otherwise . + public static bool IsPrivilegeDeclared(string tizenPrivilege) + { + if (string.IsNullOrEmpty(tizenPrivilege)) + return false; + + return TizenPlatform.CurrentPackage.Privileges.Contains(tizenPrivilege); + } + + /// + /// Throws when any privilege required by is missing from + /// the application's tizen-manifest.xml. + /// + /// The Essentials permission type. + /// A required privilege is not declared. + public static void EnsureDeclared() + where TPermission : Permissions.BasePermission, new() + { + if (TryGetKnownPrivileges(typeof(TPermission), out var privileges)) + EnsureDeclared(privileges); + else + new TPermission().EnsureDeclared(); + } + + /// + /// Throws when any of the supplied privileges is missing from the application's tizen-manifest.xml. + /// + /// The privileges to validate. + /// A required privilege is not declared. + public static void EnsureDeclared(IEnumerable privileges) + { + ArgumentNullException.ThrowIfNull(privileges); + + foreach (var privilege in privileges) + { + if (!IsPrivilegeDeclared(privilege.Privilege)) + { + throw new PermissionException( + $"You need to declare the privilege: `{privilege.Privilege}` in your tizen-manifest.xml"); + } + } + } + + /// + /// Ensures the supplied permission is granted, throwing when the user denies it. + /// + /// The Essentials permission type. + /// The resulting , which is always . + /// The permission was not granted. + public static async Task EnsureGrantedAsync() + where TPermission : Permissions.BasePermission, new() + { + var status = await ResolveAsync(ask: true).ConfigureAwait(false); + + if (status != PermissionStatus.Granted) + throw new PermissionException($"{typeof(TPermission).Name} permission was not granted: {status}"); + + return status; + } + + internal static async Task CheckPrivilegesAsync(TizenPrivilege[] privileges, bool ask) + { + if (privileges is null || privileges.Length == 0) + return PermissionStatus.Granted; + + EnsureDeclared(privileges); + + foreach (var privilege in privileges.Where(static p => p.IsRuntime)) + { + var checkResult = TizenPrivacyPrivilegeManager.CheckPermission(privilege.Privilege); + + if (checkResult == global::Tizen.Security.CheckResult.Allow) + continue; + + if (checkResult == global::Tizen.Security.CheckResult.Deny) + return PermissionStatus.Denied; + + // CheckResult.Ask + if (!ask) + return PermissionStatus.Denied; + + if (!await RequestPrivilegeAsync(privilege.Privilege).ConfigureAwait(false)) + return PermissionStatus.Denied; + } + + return PermissionStatus.Granted; + } + + static async Task RequestPrivilegeAsync(string privilege) + { + if (!TizenPrivacyPrivilegeManager.GetResponseContext(privilege).TryGetTarget(out var context)) + return false; + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + void OnResponseFetched(object? sender, global::Tizen.Security.RequestResponseEventArgs e) => + tcs.TrySetResult(e.result == global::Tizen.Security.RequestResult.AllowForever); + + context.ResponseFetched += OnResponseFetched; + + try + { + TizenPrivacyPrivilegeManager.RequestPermission(privilege); + return await tcs.Task.ConfigureAwait(false); + } + finally + { + context.ResponseFetched -= OnResponseFetched; + } + } + } +} diff --git a/src/Maui.Tizen.Essentials/PhoneDialer/TizenPhoneDialer.cs b/src/Maui.Tizen.Essentials/PhoneDialer/TizenPhoneDialer.cs new file mode 100644 index 00000000..ad3f12d2 --- /dev/null +++ b/src/Maui.Tizen.Essentials/PhoneDialer/TizenPhoneDialer.cs @@ -0,0 +1,36 @@ +using System; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the tel: dial AppControl. + /// + public sealed class TizenPhoneDialer : IPhoneDialer + { + /// + public bool IsSupported => + TizenSystemInformation.GetFeatureInfo("contact"); + + /// + public void Open(string number) + { + if (string.IsNullOrWhiteSpace(number)) + throw new ArgumentNullException(nameof(number)); + + if (!IsSupported) + throw TizenEssentialsSupport.NotSupportedOnProfile($"{nameof(IPhoneDialer)}.{nameof(Open)}", TizenDeviceProfile.Mobile); + + TizenPermissions.EnsureDeclared(); + + TizenAppControl.SendLaunchRequest(new TizenAppControl + { + Operation = TizenAppControlOperations.Dial, + Uri = "tel:" + number, + }); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenEssentialsSupport.cs b/src/Maui.Tizen.Essentials/Platform/TizenEssentialsSupport.cs new file mode 100644 index 00000000..bd89b55f --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenEssentialsSupport.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.Maui.ApplicationModel; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Declares how an Essentials capability is supported by this Tizen backend. + /// + public enum TizenSupportLevel + { + /// The capability is fully implemented against native Tizen APIs. + Implemented, + + /// + /// The capability is implemented, but only part of the contract can be honoured on Tizen. + /// The unsupported members throw instead of returning a success-shaped result. + /// + Partial, + + /// + /// Tizen has no API that can satisfy the contract. Every member throws + /// ; nothing is silently faked. + /// + Unsupported, + } + + /// + /// Central, explicit classification of Essentials capability support on Tizen. + /// + /// + /// Unsupported capabilities deliberately throw rather than returning empty collections, + /// , or completed tasks. A silent no-op is indistinguishable from success + /// at the call site and hides real portability problems from app authors. + /// + public static class TizenEssentialsSupport + { + /// + /// Creates the exception thrown by capabilities that Tizen cannot provide at all. + /// + /// The Essentials capability name, for example IClipboard.GetTextAsync. + /// Why Tizen cannot provide the capability. + /// A describing the gap. + public static FeatureNotSupportedException NotSupported(string capability, string reason) => + new FeatureNotSupportedException( + $"'{capability}' is not supported by the Tizen platform backend. {reason}"); + + /// + /// Creates the exception thrown by capabilities that exist on Tizen, but not on the + /// device profile the application is currently running on. + /// + /// The Essentials capability name. + /// The Tizen device profiles that do provide the capability. + /// A describing the gap. + public static FeatureNotSupportedException NotSupportedOnProfile( + string capability, + params TizenDeviceProfile[] supportedProfiles) => + new FeatureNotSupportedException( + $"'{capability}' is not available on the '{TizenSystemInformation.CurrentProfile}' Tizen device profile. " + + $"Supported profiles: {string.Join(", ", supportedProfiles)}."); + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs new file mode 100644 index 00000000..a1eaa6ae --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs @@ -0,0 +1,80 @@ +using System; +using System.Globalization; +using System.Text.RegularExpressions; +using TizenApplication = Tizen.Applications.Application; +using TizenPackage = Tizen.Applications.Package; +using TizenPackageManager = Tizen.Applications.PackageManager; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen specific helpers for the Essentials platform backend. + /// + /// + /// dotnet/maui exposed these members on Microsoft.Maui.ApplicationModel.Platform under + /// #if TIZEN. That type also exists in the neutral (non platform specific) + /// Microsoft.Maui.Essentials assembly this package builds against, so the Tizen members + /// are surfaced here instead of colliding with it. + /// + public static class TizenPlatform + { + /// + /// Gets a with information about the current application package. + /// + public static TizenPackage CurrentPackage + { + get + { + var packageId = TizenApplication.Current.ApplicationInfo.PackageId; + return TizenPackageManager.GetPackage(packageId); + } + } + /// + /// Gets the label of the current application package, or the package id when no label is set. + /// + /// Used as the Tizen log tag by this backend. + internal static string CurrentPackageLogTag + { + get + { + try + { + var package = CurrentPackage; + return string.IsNullOrEmpty(package.Label) ? package.Id : package.Label; + } + catch + { + return "Maui.Tizen.Essentials"; + } + } + } + + /// + /// Parses a Tizen package version string into a . + /// + /// + /// Replacement for the internal Microsoft.Maui.Utils.ParseVersion helper. Tizen package + /// versions are not guaranteed to be well formed strings, so a leading + /// numeric prefix is used when a full parse fails. + /// + /// The version string to parse. + /// The parsed , or 0.0 when nothing could be parsed. + public static Version ParseVersion(string? version) + { + if (Version.TryParse(version, out var number)) + return number; + + if (!string.IsNullOrWhiteSpace(version)) + { + var match = Regex.Match(version!, @"\d+(\.\d+)*", RegexOptions.None, TimeSpan.FromSeconds(1)); + if (match.Success && Version.TryParse(match.Value, out number)) + return number; + + if (int.TryParse(version, NumberStyles.Integer, CultureInfo.InvariantCulture, out var major)) + return new Version(major, 0); + } + + return new Version(0, 0); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenSystemInformation.cs b/src/Maui.Tizen.Essentials/Platform/TizenSystemInformation.cs new file mode 100644 index 00000000..c3cbefe3 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenSystemInformation.cs @@ -0,0 +1,117 @@ +using System; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// The Tizen device profile the application is currently running on. + /// + /// + /// Tizen ships several device profiles that expose materially different capability sets. + /// This enumeration is used by to classify which + /// Essentials services are usable on the current device. + /// + public enum TizenDeviceProfile + { + /// The profile could not be determined. + Unknown, + + /// The mobile (handset) profile. + Mobile, + + /// The wearable profile. + Wearable, + + /// The TV profile. + TV, + + /// The IoT / common headed profile. + Common, + } + + /// + /// Reads http://tizen.org/feature/* and http://tizen.org/system/* information keys. + /// + /// + /// This is the standalone replacement for the internal Microsoft.Maui.ApplicationModel.PlatformUtils + /// helper that dotnet/maui used for its in-box Tizen backend. All lookups are lazy so that simply + /// loading this assembly (for example when inspecting DI registrations on a non-Tizen host) never + /// calls into native Tizen libraries. + /// + public static class TizenSystemInformation + { + /// + /// Reads a http://tizen.org/system/{item} value as a . + /// + /// The system information key, without the http://tizen.org/system/ prefix. + /// The value, or when the key is not present. + public static string? GetSystemInfo(string item) => + GetSystemInfo(item); + + /// + /// Reads a http://tizen.org/system/{item} value. + /// + /// The value type to read. + /// The system information key, without the http://tizen.org/system/ prefix. + /// The value, or when the key is not present. + public static T? GetSystemInfo(string item) => + TryRead($"http://tizen.org/system/{item}"); + + /// + /// Reads a http://tizen.org/feature/{item} value as a . + /// + /// The feature key, without the http://tizen.org/feature/ prefix. + /// The value, or when the key is not present. + public static string? GetFeatureInfo(string item) => + GetFeatureInfo(item); + + /// + /// Reads a http://tizen.org/feature/{item} value. + /// + /// The value type to read. + /// The feature key, without the http://tizen.org/feature/ prefix. + /// The value, or when the key is not present. + public static T? GetFeatureInfo(string item) => + TryRead($"http://tizen.org/feature/{item}"); + + // Tizen.System.Information.TryGetValue throws instead of returning false when the key is not + // understood by the running platform, which for a capability probe means "not present". + static T? TryRead(string key) + { + try + { + global::Tizen.System.Information.TryGetValue(key, out var value); + return value; + } + catch (NotSupportedException) + { + return default; + } + catch (ArgumentException) + { + return default; + } + } + + /// + /// Gets the Tizen device profile reported by http://tizen.org/feature/profile. + /// + public static TizenDeviceProfile CurrentProfile => + ParseProfile(GetFeatureInfo("profile")); + + internal static TizenDeviceProfile ParseProfile(string? profile) + { + if (string.IsNullOrEmpty(profile)) + return TizenDeviceProfile.Unknown; + + return char.ToUpperInvariant(profile![0]) switch + { + 'M' => TizenDeviceProfile.Mobile, + 'W' => TizenDeviceProfile.Wearable, + 'T' => TizenDeviceProfile.TV, + 'C' => TizenDeviceProfile.Common, + 'I' => TizenDeviceProfile.Common, + _ => TizenDeviceProfile.Unknown, + }; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs new file mode 100644 index 00000000..dc5fb8a1 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -0,0 +1,123 @@ +using System; +using System.Linq; +using Microsoft.Maui.Storage; +using TizenPreference = Tizen.Applications.Preference; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Applications.Preference. + /// + /// + /// Tizen has a single per-application preference store, so shared names are emulated with a + /// {sharedName}~{key} key prefix, matching the in-box dotnet/maui Tizen backend. + /// + public sealed class TizenPreferences : IPreferences + { + const string Separator = "~"; + + static readonly object Locker = new(); + + /// + public bool ContainsKey(string key, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (Locker) + return TizenPreference.Contains(GetFullKey(key, sharedName)); + } + + /// + public void Remove(string key, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (Locker) + { + var fullKey = GetFullKey(key, sharedName); + if (TizenPreference.Contains(fullKey)) + TizenPreference.Remove(fullKey); + } + } + + /// + public void Clear(string? sharedName = null) + { + lock (Locker) + { + if (string.IsNullOrEmpty(sharedName)) + { + TizenPreference.RemoveAll(); + } + else + { + var prefix = $"{sharedName}{Separator}"; + foreach (var key in TizenPreference.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + TizenPreference.Remove(key); + } + } + } + + /// + public void Set(string key, T value, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (Locker) + { + var fullKey = GetFullKey(key, sharedName); + + switch (value) + { + case null: + if (TizenPreference.Contains(fullKey)) + TizenPreference.Remove(fullKey); + break; + case DateTime dateTime: + TizenPreference.Set(fullKey, dateTime.ToBinary()); + break; + case DateTimeOffset dateTimeOffset: + TizenPreference.Set(fullKey, dateTimeOffset.ToString("O", System.Globalization.CultureInfo.InvariantCulture)); + break; + default: + TizenPreference.Set(fullKey, value); + break; + } + } + } + + /// + public T Get(string key, T defaultValue, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (Locker) + { + var fullKey = GetFullKey(key, sharedName); + + if (!TizenPreference.Contains(fullKey)) + return defaultValue; + + if (typeof(T) == typeof(DateTime)) + return (T)(object)DateTime.FromBinary(TizenPreference.Get(fullKey)); + + if (typeof(T) == typeof(DateTimeOffset)) + { + var saved = TizenPreference.Get(fullKey); + return DateTimeOffset.TryParse( + saved, + System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.RoundtripKind, + out var parsed) + ? (T)(object)parsed + : defaultValue; + } + + return TizenPreference.Get(fullKey); + } + } + + internal static string GetFullKey(string key, string? sharedName) => + string.IsNullOrEmpty(sharedName) ? key : $"{sharedName}{Separator}{key}"; + } +} diff --git a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs new file mode 100644 index 00000000..dd3b9648 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs @@ -0,0 +1,288 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Microsoft.Maui.Media; +using Tizen.NUI; +using TizenColorSpace = Tizen.Multimedia.ColorSpace; +using TizenJpegEncoder = Tizen.Multimedia.Util.JpegEncoder; +using TizenMultimediaSize = Tizen.Multimedia.Size; +using TizenNUISize = Tizen.NUI.Size; +using TizenPngEncoder = Tizen.Multimedia.Util.PngEncoder; +using TizenView = Tizen.NUI.BaseComponents.View; +using TizenWindow = Tizen.NUI.Window; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of and , + /// backed by Tizen.NUI.Capture. + /// + /// + /// The in-box dotnet/maui Tizen backend left screenshot unimplemented (every member threw). + /// This implementation performs a real offscreen capture of the NUI window or view, then encodes + /// the resulting pixel buffer with Tizen.Multimedia.Util. + /// + /// IPlatformScreenshot is intentionally not implemented: in the neutral (non platform + /// specific) Microsoft.Maui.Essentials assembly that interface declares no members, so it + /// carries no Tizen-typed contract. The Tizen-typed overloads live on + /// instead, and element-level capture flows through the + /// neutral contract. + /// + /// + public sealed class TizenScreenshot : IScreenshot, IViewScreenshot + { + /// + public bool IsCaptureSupported => true; + + /// + public Task CaptureAsync() => + CaptureAsync(TizenWindow.Instance); + + /// + /// Captures a screenshot of the supplied NUI window. + /// + /// The window to capture. + /// The captured screenshot. + public async Task CaptureAsync(TizenWindow window) + { + ArgumentNullException.ThrowIfNull(window); + + var size = window.WindowSize; + return await CaptureCoreAsync(window.GetDefaultLayer(), new TizenNUISize(size.Width, size.Height, 0)).ConfigureAwait(false) + ?? throw new InvalidOperationException("Tizen reported a failed window capture."); + } + + /// + /// Captures a screenshot of the supplied NUI view. + /// + /// The view to capture. + /// The captured screenshot, or when Tizen reported a failed capture. + public Task CaptureAsync(TizenView view) + { + ArgumentNullException.ThrowIfNull(view); + + var size = view.Size2D; + return CaptureCoreAsync(view, new TizenNUISize(size.Width, size.Height, 0)); + } + + /// + public Task CaptureViewAsync(object platformView) => + platformView switch + { + TizenView view => CaptureAsync(view), + TizenWindow window => CaptureWindowAsync(window), + _ => Task.FromResult(null), + }; + + async Task CaptureWindowAsync(TizenWindow window) => + await CaptureAsync(window).ConfigureAwait(false); + + static async Task CaptureCoreAsync(Container source, TizenNUISize size) + { + if (size.Width <= 0 || size.Height <= 0) + throw new InvalidOperationException("Cannot capture a screenshot of a zero-sized NUI container."); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + // Capture.Start requires a writable destination path even when the pixel buffer is what + // we actually consume, so a cache-scoped scratch file is used and removed afterwards. + var scratchPath = System.IO.Path.Combine( + global::Tizen.Applications.Application.Current.DirectoryInfo.Cache, + $"maui-screenshot-{Guid.NewGuid():N}.png"); + + var capture = new Capture(); + + void OnFinished(object? sender, CaptureFinishedEventArgs e) => tcs.TrySetResult(e.Success); + + capture.Finished += OnFinished; + + try + { + capture.Start(source, size, scratchPath, Color.Transparent); + + if (!await tcs.Task.ConfigureAwait(false)) + return null; + + var buffer = capture.GetCapturedBuffer(); + if (buffer is null) + return null; + + return TizenScreenshotResult.FromPixelBuffer(buffer); + } + finally + { + capture.Finished -= OnFinished; + capture.Dispose(); + + try + { + if (File.Exists(scratchPath)) + File.Delete(scratchPath); + } + catch + { + // A leftover scratch file in the cache directory is not worth failing a capture. + } + } + } + } + + /// + /// A captured Tizen screenshot, encoded on demand. + /// + public sealed class TizenScreenshotResult : IScreenshotResult + { + readonly byte[] _pixels; + readonly TizenColorSpace _colorSpace; + + TizenScreenshotResult(byte[] pixels, int width, int height, TizenColorSpace colorSpace) + { + _pixels = pixels; + _colorSpace = colorSpace; + Width = width; + Height = height; + } + + /// + public int Width { get; } + + /// + public int Height { get; } + + internal static TizenScreenshotResult FromPixelBuffer(PixelBuffer buffer) + { + var width = (int)buffer.GetWidth(); + var height = (int)buffer.GetHeight(); + var format = buffer.GetPixelFormat(); + var colorSpace = MapColorSpace(format); + var stride = BytesPerPixel(format); + + var pixels = new byte[width * height * stride]; + var native = buffer.GetBuffer(); + + if (native == IntPtr.Zero) + throw new InvalidOperationException("Tizen returned an empty capture buffer."); + + Marshal.Copy(native, pixels, 0, pixels.Length); + + return new TizenScreenshotResult(pixels, width, height, colorSpace); + } + + /// + public async Task OpenReadAsync(ScreenshotFormat format = ScreenshotFormat.Png, int quality = 100) + { + var stream = new MemoryStream(); + await EncodeAsync(stream, format, quality).ConfigureAwait(false); + stream.Position = 0; + return stream; + } + + /// + public Task CopyToAsync(Stream destination, ScreenshotFormat format = ScreenshotFormat.Png, int quality = 100) + { + ArgumentNullException.ThrowIfNull(destination); + + return EncodeAsync(destination, format, quality); + } + + async Task EncodeAsync(Stream destination, ScreenshotFormat format, int quality) + { + ArgumentOutOfRangeException.ThrowIfLessThan(quality, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(quality, 100); + + var resolution = new TizenMultimediaSize(Width, Height); + + switch (format) + { + case ScreenshotFormat.Jpeg: + { + using var encoder = new TizenJpegEncoder(quality); + encoder.SetResolution(resolution); + encoder.SetColorSpace(_colorSpace); + await encoder.EncodeAsync(_pixels, destination).ConfigureAwait(false); + break; + } + + case ScreenshotFormat.Png: + { + using var encoder = new TizenPngEncoder(); + encoder.SetResolution(resolution); + encoder.SetColorSpace(_colorSpace); + await encoder.EncodeAsync(_pixels, destination).ConfigureAwait(false); + break; + } + + default: + throw new ArgumentOutOfRangeException(nameof(format), format, "Unknown screenshot format."); + } + } + + internal static TizenColorSpace MapColorSpace(PixelFormat format) => + format switch + { + PixelFormat.RGBA8888 or PixelFormat.RGB8888 => TizenColorSpace.Rgba8888, + PixelFormat.BGRA8888 or PixelFormat.BGR8888 => TizenColorSpace.Bgra8888, + PixelFormat.RGB888 => TizenColorSpace.Rgb888, + PixelFormat.RGB565 => TizenColorSpace.Rgb565, + _ => throw TizenEssentialsSupport.NotSupported( + $"{nameof(IScreenshot)} capture in pixel format '{format}'", + "Tizen.Multimedia.Util has no matching color space for this NUI pixel format."), + }; + + internal static int BytesPerPixel(PixelFormat format) => + format switch + { + PixelFormat.RGBA8888 or PixelFormat.RGB8888 or PixelFormat.BGRA8888 or PixelFormat.BGR8888 => 4, + PixelFormat.RGB888 => 3, + PixelFormat.RGB565 => 2, + _ => throw TizenEssentialsSupport.NotSupported( + $"{nameof(IScreenshot)} capture in pixel format '{format}'", + "This NUI pixel format has no fixed byte stride understood by this backend."), + }; + } + + /// + /// Tizen-typed capture helpers for . + /// + /// + /// Mirrors the ScreenshotExtensions.CaptureAsync(this IScreenshot, Tizen.NUI.Window) + /// overloads that dotnet/maui only compiled into its Tizen-specific Essentials assembly. + /// + public static class TizenScreenshotExtensions + { + /// + /// Captures a screenshot of the supplied NUI window. + /// + /// The screenshot service. + /// The window to capture. + /// The captured screenshot. + /// The service is not the Tizen implementation. + public static Task CaptureAsync(this IScreenshot screenshot, TizenWindow window) => + AsTizen(screenshot).CaptureAsync(window); + + /// + /// Captures a screenshot of the supplied NUI view. + /// + /// The screenshot service. + /// The view to capture. + /// The captured screenshot, or when Tizen reported a failed capture. + /// The service is not the Tizen implementation. + public static Task CaptureAsync(this IScreenshot screenshot, TizenView view) => + AsTizen(screenshot).CaptureAsync(view); + + static TizenScreenshot AsTizen(IScreenshot screenshot) + { + ArgumentNullException.ThrowIfNull(screenshot); + + if (screenshot is not TizenScreenshot tizen) + { + throw new PlatformNotSupportedException( + $"This implementation of {nameof(IScreenshot)} is not {nameof(TizenScreenshot)}. " + + $"Use {nameof(IViewScreenshot)}.{nameof(IViewScreenshot.CaptureViewAsync)} for platform-neutral view capture."); + } + + return tizen; + } + } +} diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs new file mode 100644 index 00000000..167406da --- /dev/null +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -0,0 +1,98 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Maui.Storage; +using Tizen.Security.SecureRepository; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the Tizen key manager + /// (Tizen.Security.SecureRepository.DataManager). + /// + public sealed class TizenSecureStorage : ISecureStorage + { + /// + public Task GetAsync(string key) + { + ArgumentNullException.ThrowIfNull(key); + + try + { + // The second parameter is the data password, not a default value. + return Task.FromResult(Encoding.UTF8.GetString(DataManager.Get(key, null))); + } + catch (InvalidOperationException) + { + // DataManager.Get throws when the alias does not exist. That is expected and normal. + return Task.FromResult(null); + } + catch + { + global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to load data."); + throw; + } + } + + /// + public Task SetAsync(string key, string value) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + + try + { + try + { + // DataManager.Save throws when the alias already exists, and Tizen offers no + // existence probe that does not throw, so remove unconditionally first. + DataManager.RemoveAlias(key); + } + catch + { + // Expected when the alias did not exist. + } + + DataManager.Save(key, Encoding.UTF8.GetBytes(value), new Policy()); + + return Task.CompletedTask; + } + catch + { + global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to save data."); + throw; + } + } + + /// + public bool Remove(string key) + { + ArgumentNullException.ThrowIfNull(key); + + try + { + DataManager.RemoveAlias(key); + return true; + } + catch + { + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove data."); + return false; + } + } + + /// + public void RemoveAll() + { + try + { + foreach (var alias in DataManager.GetAliases()) + DataManager.RemoveAlias(alias); + } + catch + { + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "No saved data."); + } + } + } +} diff --git a/src/Maui.Tizen.Essentials/SemanticScreenReader/TizenSemanticScreenReader.cs b/src/Maui.Tizen.Essentials/SemanticScreenReader/TizenSemanticScreenReader.cs new file mode 100644 index 00000000..4c2a02e8 --- /dev/null +++ b/src/Maui.Tizen.Essentials/SemanticScreenReader/TizenSemanticScreenReader.cs @@ -0,0 +1,19 @@ +using System; +using Microsoft.Maui.Accessibility; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by NUI accessibility. + /// + public sealed class TizenSemanticScreenReader : ISemanticScreenReader + { + /// + public void Announce(string text) + { + ArgumentNullException.ThrowIfNull(text); + + global::Tizen.NUI.Accessibility.Accessibility.Say(text, true); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Share/TizenShare.cs b/src/Maui.Tizen.Essentials/Share/TizenShare.cs new file mode 100644 index 00000000..629c9120 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Share/TizenShare.cs @@ -0,0 +1,78 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.DataTransfer; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the share and + /// share_text AppControl operations. + /// + public sealed class TizenShare : IShare + { + /// + public Task RequestAsync(ShareTextRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.ShareText, + }; + + if (!string.IsNullOrEmpty(request.Text)) + appControl.ExtraData.Add(TizenAppControlData.Text, request.Text); + if (!string.IsNullOrEmpty(request.Uri)) + appControl.ExtraData.Add(TizenAppControlData.Url, request.Uri); + if (!string.IsNullOrEmpty(request.Subject)) + appControl.ExtraData.Add(TizenAppControlData.Subject, request.Subject); + if (!string.IsNullOrEmpty(request.Title)) + appControl.ExtraData.Add(TizenAppControlData.Title, request.Title); + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.CompletedTask; + } + + /// + public Task RequestAsync(ShareFileRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + return RequestAsync((ShareMultipleFilesRequest)request); + } + + /// + public Task RequestAsync(ShareMultipleFilesRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Share, + }; + + if (!string.IsNullOrEmpty(request.Title)) + appControl.ExtraData.Add(TizenAppControlData.Title, request.Title); + + foreach (var file in request.Files ?? Enumerable.Empty()) + { + if (!string.IsNullOrEmpty(file?.FullPath)) + appControl.ExtraData.Add(TizenAppControlData.Path, file.FullPath); + } + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.CompletedTask; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Sms/TizenSms.cs b/src/Maui.Tizen.Essentials/Sms/TizenSms.cs new file mode 100644 index 00000000..cf2fac64 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Sms/TizenSms.cs @@ -0,0 +1,48 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using TizenAppControl = Tizen.Applications.AppControl; +using TizenAppControlData = Tizen.Applications.AppControlData; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by the sms: compose AppControl. + /// + public sealed class TizenSms : ISms + { + /// + public bool IsComposeSupported => + TizenSystemInformation.GetFeatureInfo("network.telephony.sms"); + + /// + public Task ComposeAsync(SmsMessage? message) + { + if (!IsComposeSupported) + throw TizenEssentialsSupport.NotSupportedOnProfile($"{nameof(ISms)}.{nameof(ComposeAsync)}", TizenDeviceProfile.Mobile); + + TizenPermissions.EnsureDeclared(); + + var appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Compose, + Uri = "sms:", + }; + + if (message is not null) + { + if (!string.IsNullOrEmpty(message.Body)) + appControl.ExtraData.Add(TizenAppControlData.Text, message.Body); + + if (message.Recipients?.Count > 0) + appControl.Uri += string.Join(" ", message.Recipients); + } + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.CompletedTask; + } + } +} diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs new file mode 100644 index 00000000..d940fb4d --- /dev/null +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Media; +using Tizen.Uix.Tts; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Uix.Tts. + /// + /// + /// Tizen's TTS client exposes a speed range but no pitch or volume control, so + /// and cannot be honoured + /// and are rejected rather than silently ignored. + /// + public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable + { + const float RateMax = 2.0f; + + readonly SemaphoreSlim _speakLock = new(1, 1); + + TtsClient? _client; + TaskCompletionSource? _initialize; + TaskCompletionSource? _utterance; + bool _disposed; + + /// + /// Always thrown; see remarks. + /// + /// + /// Blocked by a public API gap in Microsoft.Maui.Essentials: + /// Microsoft.Maui.Media.Locale has only an internal constructor, so a platform + /// backend outside the dotnet/maui assembly cannot construct the values this contract must + /// return. Returning an empty sequence instead would be indistinguishable from "this device + /// supports no voices", so this throws rather than reporting a success-shaped result. + /// + /// + /// Use to enumerate the languages Tizen reports, + /// and pass one of them to . + /// + /// + public Task> GetLocalesAsync() => + throw TizenEssentialsSupport.NotSupported( + $"{nameof(ITextToSpeech)}.{nameof(GetLocalesAsync)}", + "Microsoft.Maui.Media.Locale exposes no public constructor, so a standalone platform " + + "backend cannot create the Locale values this contract returns. " + + $"Use {nameof(TizenTextToSpeech)}.{nameof(GetSupportedVoiceLanguagesAsync)} instead."); + + /// + /// Enumerates the voice languages Tizen reports for the current device, for example en_US. + /// + /// The distinct supported voice languages. + public async Task> GetSupportedVoiceLanguagesAsync() + { + var client = await InitializeAsync().ConfigureAwait(false); + + var languages = new List(); + foreach (var voice in client.GetSupportedVoices()) + { + if (!languages.Any(l => string.Equals(l, voice.Language, StringComparison.OrdinalIgnoreCase))) + languages.Add(voice.Language); + } + + return languages; + } + + /// + /// Speaks the supplied text using an explicit Tizen voice language. + /// + /// The text to speak. + /// A language returned by . + /// The optional speech rate, in the same 0..2 range as . + /// A token used to stop playback. + /// A task that completes when the utterance finishes or is cancelled. + public Task SpeakAsync(string text, string language, float? rate = null, CancellationToken cancelToken = default) => + SpeakCoreAsync(text, language, rate, cancelToken); + + /// + public async Task SpeakAsync(string text, SpeechOptions? options = default, CancellationToken cancelToken = default) + { + ArgumentNullException.ThrowIfNull(text); + + if (options?.Pitch is not null) + { + throw TizenEssentialsSupport.NotSupported( + $"{nameof(ITextToSpeech)}.{nameof(SpeakAsync)} with SpeechOptions.Pitch", + "Tizen's TTS client exposes no pitch control."); + } + + if (options?.Volume is not null) + { + throw TizenEssentialsSupport.NotSupported( + $"{nameof(ITextToSpeech)}.{nameof(SpeakAsync)} with SpeechOptions.Volume", + "Tizen's TTS client exposes no per-utterance volume control."); + } + + await SpeakCoreAsync(text, options?.Locale?.Language, options?.Rate, cancelToken).ConfigureAwait(false); + } + + async Task SpeakCoreAsync(string text, string? language, float? rate, CancellationToken cancelToken) + { + ArgumentNullException.ThrowIfNull(text); + + var client = await InitializeAsync().ConfigureAwait(false); + + await _speakLock.WaitAsync(cancelToken).ConfigureAwait(false); + try + { + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _utterance = utterance; + + using var registration = cancelToken.Register(() => + { + try + { + client.Stop(); + } + catch + { + // The client may already be idle. + } + + utterance.TrySetResult(false); + }); + + var (resolvedLanguage, voiceType) = ResolveVoice(client, language); + + client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); + client.Play(); + + await utterance.Task.ConfigureAwait(false); + } + finally + { + _utterance = null; + _speakLock.Release(); + } + } + + static (string Language, Voice VoiceType) ResolveVoice(TtsClient client, string? requestedLanguage) + { + var language = "en_US"; + var voiceType = Voice.Auto; + + if (requestedLanguage is { } requested) + { + foreach (var voice in client.GetSupportedVoices()) + { + if (string.Equals(voice.Language, requested, StringComparison.OrdinalIgnoreCase)) + { + language = voice.Language; + voiceType = voice.VoiceType; + break; + } + } + } + + return (language, voiceType); + } + + static int ResolveRate(TtsClient client, float? rate) + { + if (rate is not { } value) + return 0; + + return (int)Math.Round(value / RateMax * client.GetSpeedRange().Max, MidpointRounding.AwayFromZero); + } + + Task InitializeAsync() + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_client is { } existing && _initialize is { } pending) + return WrapAsync(pending, existing); + + var client = new TtsClient(); + var initialize = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + client.StateChanged += (_, e) => + { + if (e.Current == State.Ready) + initialize.TrySetResult(true); + }; + + client.UtteranceCompleted += (_, _) => + { + try + { + client.Stop(); + } + catch + { + // The client may already be idle. + } + + _utterance?.TrySetResult(true); + }; + + _client = client; + _initialize = initialize; + + client.Prepare(); + + return WrapAsync(initialize, client); + + static async Task WrapAsync(TaskCompletionSource tcs, TtsClient client) + { + await tcs.Task.ConfigureAwait(false); + return client; + } + } + + /// + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _client?.Dispose(); + _client = null; + _speakLock.Dispose(); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Types/TizenFileMimeTypes.cs b/src/Maui.Tizen.Essentials/Types/TizenFileMimeTypes.cs new file mode 100644 index 00000000..ee5a485e --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenFileMimeTypes.cs @@ -0,0 +1,58 @@ +using System; +using Microsoft.Maui.Devices.Sensors; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// MIME types used by the Tizen AppControl based pickers and launchers. + /// + /// + /// dotnet/maui keeps its equivalent FileMimeTypes constants internal, so a standalone + /// platform backend cannot reference them. + /// + public static class TizenFileMimeTypes + { + /// Matches any file type. + public const string All = "*/*"; + + /// Matches any image file type. + public const string ImageAll = "image/*"; + + /// Matches PNG images. + public const string ImagePng = "image/png"; + + /// Matches JPEG images. + public const string ImageJpg = "image/jpeg"; + + /// Matches any video file type. + public const string VideoAll = "video/*"; + + /// Matches PDF documents. + public const string Pdf = "application/pdf"; + } + + /// + /// Placemark helpers used by the Tizen map integration. + /// + public static class TizenPlacemarkExtensions + { + /// + /// Builds the URL-escaped, single-line address used for geo:0,0?q= map queries. + /// + /// The placemark to format. + /// The escaped address. + /// + /// Behavioural port of the internal PlacemarkExtensions.GetEscapedAddress helper in + /// dotnet/maui, which is not accessible from a standalone platform backend. + /// + public static string GetEscapedAddress(this Placemark placemark) + { + ArgumentNullException.ThrowIfNull(placemark); + + var address = + $"{placemark.Thoroughfare} {placemark.Locality} {placemark.AdminArea} {placemark.PostalCode} {placemark.CountryName}"; + + return Uri.EscapeDataString(address); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs new file mode 100644 index 00000000..ad135827 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs @@ -0,0 +1,129 @@ +using System; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using TizenSensor = Tizen.Sensor.Sensor; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Shared start/stop bookkeeping for the Tizen sensor implementations. + /// + /// The native Tizen sensor type. + /// + /// dotnet/maui expressed this logic once per sensor in a *.shared.cs half of a partial + /// class. Since this backend ships independently named classes, the common behaviour lives here + /// instead of being copied into each implementation. + /// + public abstract class TizenSensorBase + where TSensor : TizenSensor + { + /// + /// Gets a value indicating whether readings should be marshalled to the main thread. + /// + protected bool UseSyncContext { get; private set; } + + /// + /// Gets a value indicating whether the sensor is currently being monitored. + /// + public bool IsMonitoring { get; private set; } + + /// + /// Gets a value indicating whether this device provides the sensor. + /// + public abstract bool IsSupported { get; } + + /// + /// Gets the display name used in diagnostics and exception messages. + /// + protected abstract string SensorName { get; } + + /// + /// Gets the shared native sensor instance. + /// + protected abstract TSensor Sensor { get; } + + /// Attaches the native data-updated handler. + /// The native sensor. + protected abstract void Subscribe(TSensor sensor); + + /// Detaches the native data-updated handler. + /// The native sensor. + protected abstract void Unsubscribe(TSensor sensor); + + /// + /// Starts monitoring the sensor. + /// + /// The requested reporting speed. + /// The device has no such sensor. + /// Monitoring is already in progress. + public void Start(SensorSpeed sensorSpeed) + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{SensorName}.Start", $"This device has no {SensorName} sensor."); + + if (IsMonitoring) + throw new InvalidOperationException($"{SensorName} has already been started."); + + IsMonitoring = true; + UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; + + try + { + var sensor = Sensor; + sensor.Interval = sensorSpeed.ToPlatform(); + Subscribe(sensor); + sensor.Start(); + } + catch + { + IsMonitoring = false; + throw; + } + } + + /// + /// Stops monitoring the sensor. + /// + /// The device has no such sensor. + public void Stop() + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{SensorName}.Stop", $"This device has no {SensorName} sensor."); + + if (!IsMonitoring) + return; + + IsMonitoring = false; + + try + { + var sensor = Sensor; + Unsubscribe(sensor); + sensor.Stop(); + } + catch + { + IsMonitoring = true; + throw; + } + } + + /// + /// Raises a reading changed event, honouring the requested sensor speed. + /// + /// The event argument type. + /// The event handler to invoke. + /// The event arguments. + protected void Raise(EventHandler? handler, TArgs args) + where TArgs : EventArgs + { + if (handler is null) + return; + + if (UseSyncContext) + MainThread.BeginInvokeOnMainThread(() => handler.Invoke(this, args)); + else + handler.Invoke(this, args); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensors.cs b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs new file mode 100644 index 00000000..3f7ae9ce --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs @@ -0,0 +1,96 @@ +using System; +using Microsoft.Maui.Devices.Sensors; +using TizenAccelerometerSensor = Tizen.Sensor.Accelerometer; +using TizenGyroscopeSensor = Tizen.Sensor.Gyroscope; +using TizenMagnetometerSensor = Tizen.Sensor.Magnetometer; +using TizenNativeOrientationSensor = Tizen.Sensor.OrientationSensor; +using TizenPressureSensor = Tizen.Sensor.PressureSensor; +using TizenRotationVectorSensor = Tizen.Sensor.RotationVectorSensor; +using TizenSensor = Tizen.Sensor.Sensor; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// The Tizen sensors used by this backend. + /// + public enum TizenSensorType + { + /// The accelerometer. + Accelerometer, + + /// The pressure (barometer) sensor. + Barometer, + + /// The orientation sensor used to derive a compass heading. + Compass, + + /// The gyroscope. + Gyroscope, + + /// The magnetometer. + Magnetometer, + + /// The rotation vector sensor used for device orientation. + OrientationSensor, + } + + /// + /// Caches one native Tizen sensor instance per sensor type. + /// + /// + /// Replaces the internal PlatformUtils.GetDefaultSensor helper from the in-box dotnet/maui + /// Tizen backend. Instances are created lazily so that loading this assembly never touches native + /// sensor libraries. + /// + public static class TizenSensors + { + static readonly Lazy AccelerometerSensor = new(static () => new TizenAccelerometerSensor()); + static readonly Lazy BarometerSensor = new(static () => new TizenPressureSensor()); + static readonly Lazy CompassSensor = new(static () => new TizenNativeOrientationSensor()); + static readonly Lazy GyroscopeSensor = new(static () => new TizenGyroscopeSensor()); + static readonly Lazy MagnetometerSensor = new(static () => new TizenMagnetometerSensor()); + static readonly Lazy RotationVectorSensor = new(static () => new TizenRotationVectorSensor()); + + /// + /// Gets the shared native sensor instance for the requested type. + /// + /// The sensor to resolve. + /// The shared native sensor instance. + public static TizenSensor GetDefaultSensor(TizenSensorType type) => + type switch + { + TizenSensorType.Accelerometer => AccelerometerSensor.Value, + TizenSensorType.Barometer => BarometerSensor.Value, + TizenSensorType.Compass => CompassSensor.Value, + TizenSensorType.Gyroscope => GyroscopeSensor.Value, + TizenSensorType.Magnetometer => MagnetometerSensor.Value, + TizenSensorType.OrientationSensor => RotationVectorSensor.Value, + _ => throw new ArgumentOutOfRangeException(nameof(type), type, "Unknown Tizen sensor type."), + }; + } + + /// + /// Maps onto Tizen sensor update intervals in milliseconds. + /// + public static class TizenSensorSpeedExtensions + { + internal const uint SensorIntervalFastest = 0; + internal const uint SensorIntervalGame = 20; + internal const uint SensorIntervalUI = 60; + internal const uint SensorIntervalDefault = 200; + + /// + /// Converts a into a Tizen sensor interval in milliseconds. + /// + /// The requested sensor speed. + /// The Tizen sensor interval, in milliseconds. + public static uint ToPlatform(this SensorSpeed sensorSpeed) => + sensorSpeed switch + { + SensorSpeed.Fastest => SensorIntervalFastest, + SensorSpeed.Game => SensorIntervalGame, + SensorSpeed.UI => SensorIntervalUI, + _ => SensorIntervalDefault, + }; + } +} diff --git a/src/Maui.Tizen.Essentials/Vibration/TizenVibration.cs b/src/Maui.Tizen.Essentials/Vibration/TizenVibration.cs new file mode 100644 index 00000000..71825056 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Vibration/TizenVibration.cs @@ -0,0 +1,44 @@ +using System; +using System.Linq; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenVibrator = Tizen.System.Vibrator; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.System.Vibrator. + /// + public sealed class TizenVibration : IVibration + { + const int DefaultIntensity = 100; + + /// + public bool IsSupported => TizenVibrator.NumberOfVibrators > 0; + + /// + public void Vibrate() => Vibrate(TimeSpan.FromMilliseconds(500)); + + /// + public void Vibrate(TimeSpan duration) + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupportedOnProfile($"{nameof(IVibration)}.{nameof(Vibrate)}", TizenDeviceProfile.Mobile, TizenDeviceProfile.Wearable); + + TizenPermissions.EnsureDeclared(); + + TizenVibrator.Vibrators.FirstOrDefault()?.Vibrate((int)duration.TotalMilliseconds, DefaultIntensity); + } + + /// + public void Cancel() + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupportedOnProfile($"{nameof(IVibration)}.{nameof(Cancel)}", TizenDeviceProfile.Mobile, TizenDeviceProfile.Wearable); + + TizenPermissions.EnsureDeclared(); + + TizenVibrator.Vibrators.FirstOrDefault()?.Stop(); + } + } +} diff --git a/src/Maui.Tizen.Essentials/WebAuthenticator/TizenWebAuthenticator.cs b/src/Maui.Tizen.Essentials/WebAuthenticator/TizenWebAuthenticator.cs new file mode 100644 index 00000000..162e3bed --- /dev/null +++ b/src/Maui.Tizen.Essentials/WebAuthenticator/TizenWebAuthenticator.cs @@ -0,0 +1,48 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Authentication; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// Tizen has no app-link / custom-URI-scheme callback contract that can return control to the + /// calling application after an external browser flow, so a web authentication round trip cannot + /// be completed. Both overloads throw rather than returning a partially populated + /// . + /// + public sealed class TizenWebAuthenticator : IWebAuthenticator + { + const string Reason = + "Tizen provides no callback URI registration that can return an external browser " + + "authentication response to the launching application."; + + /// + /// Always thrown. + public Task AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IWebAuthenticator)}.{nameof(AuthenticateAsync)}", Reason); + + /// + /// Always thrown. + public Task AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions, CancellationToken cancellationToken) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IWebAuthenticator)}.{nameof(AuthenticateAsync)}", Reason); + } + + /// + /// Tizen implementation of . + /// + /// Sign in with Apple's native flow is only available on Apple platforms. + public sealed class TizenAppleSignInAuthenticator : IAppleSignInAuthenticator + { + /// + /// Always thrown. + public Task AuthenticateAsync(AppleSignInAuthenticator.Options? options = null) => + throw TizenEssentialsSupport.NotSupported( + $"{nameof(IAppleSignInAuthenticator)}.{nameof(AuthenticateAsync)}", + "Native Sign in with Apple is only available on Apple platforms."); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs new file mode 100644 index 00000000..c89b2d5c --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Guards the two integration invariants this backend depends on: +/// the .NET 11 Essentials DI to static facade bridge owns facade assignment, and the MAUI +/// dispatcher bridge owns main-thread marshalling. +/// +public class FacadeAndMainThreadOwnershipTests +{ + static readonly Assembly Backend = typeof(TizenAppInfo).Assembly; + + /// + /// The Essentials facades that dotnet/maui#36657 bridges from DI. Every contract this backend + /// registers must be in this set, otherwise registering it would never reach the static facade. + /// + static readonly HashSet BridgedContracts = new(StringComparer.Ordinal) + { + "IAccelerometer", "IAppActions", "IAppInfo", "IAppleSignInAuthenticator", "IBarometer", + "IBattery", "IBrowser", "IClipboard", "ICompass", "IConnectivity", "IContacts", + "IDeviceDisplay", "IDeviceInfo", "IEmail", "IFilePicker", "IFileSystem", "IFlashlight", + "IGeocoding", "IGeolocation", "IGyroscope", "IHapticFeedback", "ILauncher", "IMagnetometer", + "IMap", "IMediaPicker", "IOrientationSensor", "IPasskeys", "IPermissions", "IPhoneDialer", + "IPreferences", "IScreenshot", "ISecureStorage", "ISemanticScreenReader", "IShare", "ISms", + "ITextToSpeech", "IVersionTracking", "IVibration", "IWebAuthenticator", + }; + + [Fact] + public void EveryRegisteredContractIsBridgedToItsStaticFacadeByMaui() + { + var notBridged = TizenEssentialsRegistrationTests.ExpectedRegistrations.Keys + .Select(t => t.Name) + .Where(name => !BridgedContracts.Contains(name)) + .ToList(); + + Assert.Empty(notBridged); + } + + [Fact] + public void DoesNotCallSetDefaultOrSetCurrentOnAnyEssentialsFacade() + { + var forbidden = new[] { "SetDefault", "SetCurrent" }; + + var offenders = ReferencedMemberNames() + .Where(name => forbidden.Contains(name, StringComparer.Ordinal)) + .Distinct() + .ToList(); + + Assert.Empty(offenders); + } + + [Fact] + public void DoesNotUseReflectionToReachEssentialsFacadeBackingFields() + { + var reflectionEntryPoints = new[] + { + "GetField", "GetFields", "GetRuntimeField", "GetRuntimeFields", "InvokeMember", + }; + + var offenders = ReferencedMemberNames() + .Where(name => reflectionEntryPoints.Contains(name, StringComparer.Ordinal)) + .Distinct() + .ToList(); + + Assert.Empty(offenders); + } + + [Fact] + public void DoesNotShipItsOwnMainThreadImplementation() + { + // MainThread marshalling is bridged from the registered IDispatcher by MAUI for + // non in-box platforms, so this backend must not declare a MainThread type of its own... + var mainThreadTypes = Backend.GetTypes() + .Where(t => t.Name.Contains("MainThread", StringComparison.Ordinal)) + .ToList(); + + Assert.Empty(mainThreadTypes); + } + + [Fact] + public void DoesNotTouchTheEcoreMainLoopDirectly() + { + // ...nor reach around the dispatcher into the EFL main loop, which is what the + // in-box dotnet/maui MainThread.tizen.cs did. + var offenders = ReferencedTypeNames() + .Where(name => name.Contains("EcoreMainloop", StringComparison.Ordinal)) + .Distinct() + .ToList(); + + Assert.Empty(offenders); + } + + [Fact] + public void MarshalsThroughTheMauiMainThreadFacade() + { + // The bridge replaces MainThread's platform delegate, so calling into MainThread is the + // correct way for this backend to reach the UI thread. + Assert.Contains("MainThread", ReferencedTypeNames()); + } + + [Fact] + public void ExposesGeocodingThroughTheTokenAwarePlatformContract() => + Assert.True(typeof(IPlatformGeocoding).IsAssignableFrom(typeof(TizenGeocoding))); + + static IEnumerable ReferencedMemberNames() + { + using var stream = System.IO.File.OpenRead(Backend.Location); + using var peReader = new PEReader(stream); + var reader = peReader.GetMetadataReader(); + + foreach (var handle in reader.MemberReferences) + yield return reader.GetString(reader.GetMemberReference(handle).Name); + } + + static IEnumerable ReferencedTypeNames() + { + using var stream = System.IO.File.OpenRead(Backend.Location); + using var peReader = new PEReader(stream); + var reader = peReader.GetMetadataReader(); + + foreach (var handle in reader.TypeReferences) + yield return reader.GetString(reader.GetTypeReference(handle).Name); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj b/tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj new file mode 100644 index 00000000..f98dcef4 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj @@ -0,0 +1,42 @@ + + + + $(MauiTizenDotNetTfm) + Maui.Tizen.Essentials.Tests + Maui.Tizen.Essentials.Tests + false + true + Exe + true + false + + + + + + + + + + + + + + + + + + + + <_TizenHostAssembly Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' != '' AND $([System.String]::Copy('%(ReferencePath.NuGetPackageId)').StartsWith('Tizen.NET'))" /> + + + + + diff --git a/tests/Maui.Tizen.Essentials.Tests/ServiceCoverageMatrixTests.cs b/tests/Maui.Tizen.Essentials.Tests/ServiceCoverageMatrixTests.cs new file mode 100644 index 00000000..f70919aa --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/ServiceCoverageMatrixTests.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Keeps docs/tizen-essentials-service-coverage.md honest by asserting it against the real +/// DI registrations rather than trusting it to be updated by hand. +/// +public class ServiceCoverageMatrixTests +{ + static readonly string[] ValidLevels = ["Implemented", "Partial", "Unsupported"]; + + static readonly string[] ValidProfiles = + ["All", "Mobile", "Wearable", "TV", "Common", "–"]; + + sealed record Row(string Contract, string Implementation, string Level, string Profiles, string Notes); + + static IReadOnlyList ReadMatrix() + { + var path = Path.Combine(AppContext.BaseDirectory, "tizen-essentials-service-coverage.md"); + Assert.True(File.Exists(path), $"Coverage matrix not found at '{path}'."); + + var lines = File.ReadAllLines(path); + var begin = Array.FindIndex(lines, l => l.Contains("coverage-matrix:begin", StringComparison.Ordinal)); + var end = Array.FindIndex(lines, l => l.Contains("coverage-matrix:end", StringComparison.Ordinal)); + + Assert.True(begin >= 0 && end > begin, "The coverage matrix markers are missing or out of order."); + + var rows = new List(); + + foreach (var line in lines[(begin + 1)..end]) + { + var trimmed = line.Trim(); + if (!trimmed.StartsWith('|') || trimmed.StartsWith("| ---", StringComparison.Ordinal)) + continue; + + var cells = trimmed.Trim('|').Split('|').Select(c => c.Trim()).ToArray(); + if (cells.Length < 5 || cells[0] == "Contract") + continue; + + rows.Add(new Row( + cells[0].Trim('`'), + cells[1].Trim('`'), + cells[2], + cells[3], + cells[4])); + } + + return rows; + } + + [Fact] + public void DocumentsEveryRegisteredService() + { + var documented = ReadMatrix().Select(r => r.Contract).ToHashSet(StringComparer.Ordinal); + + var missing = TizenEssentialsRegistrationTests.ExpectedRegistrations.Keys + .Select(t => t.Name) + .Where(name => !documented.Contains(name)) + .ToList(); + + Assert.Empty(missing); + } + + [Fact] + public void DocumentsGeocodingEvenThoughItIsRegisteredThroughAFactory() => + Assert.Contains("IGeocoding", ReadMatrix().Select(r => r.Contract)); + + [Fact] + public void DocumentsNothingThatIsNotRegistered() + { + var registered = TizenEssentialsRegistrationTests.ExpectedRegistrations.Keys + .Select(t => t.Name) + .Append("IGeocoding") + .ToHashSet(StringComparer.Ordinal); + + var extra = ReadMatrix() + .Select(r => r.Contract) + .Where(name => !registered.Contains(name)) + .ToList(); + + Assert.Empty(extra); + } + + [Fact] + public void NamesRealImplementationTypesInTheExpectedNamespace() + { + var assembly = typeof(TizenAppInfo).Assembly; + + foreach (var row in ReadMatrix()) + { + var type = assembly.GetType($"Microsoft.Maui.Platforms.Tizen.Essentials.{row.Implementation}", throwOnError: false); + + Assert.True(type is not null, $"'{row.Implementation}' is documented but does not exist in the backend assembly."); + Assert.True(type!.IsPublic, $"'{row.Implementation}' must be public."); + } + } + + [Fact] + public void UsesOnlyTheDefinedSupportLevels() + { + var invalid = ReadMatrix() + .Where(r => !ValidLevels.Contains(r.Level, StringComparer.Ordinal)) + .Select(r => $"{r.Contract} => '{r.Level}'") + .ToList(); + + Assert.Empty(invalid); + } + + [Fact] + public void ClassifiesProfilesForEverySupportedService() + { + var invalid = new List(); + + foreach (var row in ReadMatrix()) + { + var profiles = row.Profiles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + if (profiles.Length == 0 || profiles.Any(p => !ValidProfiles.Contains(p, StringComparer.Ordinal))) + invalid.Add($"{row.Contract} => '{row.Profiles}'"); + + // Unsupported services must not claim any profile. + if (row.Level == "Unsupported" && row.Profiles != "–") + invalid.Add($"{row.Contract} is Unsupported but claims profiles '{row.Profiles}'."); + + // Everything else must claim at least one real profile. + if (row.Level != "Unsupported" && row.Profiles == "–") + invalid.Add($"{row.Contract} is {row.Level} but claims no profile."); + } + + Assert.Empty(invalid); + } + + [Fact] + public void ExplainsEveryPartialAndUnsupportedService() + { + var missingNotes = ReadMatrix() + .Where(r => r.Level != "Implemented" && string.IsNullOrWhiteSpace(r.Notes)) + .Select(r => r.Contract) + .ToList(); + + Assert.Empty(missingNotes); + } + + [Fact] + public void MatchesTheImplementationTypesUsedByDependencyInjection() + { + var byContract = ReadMatrix().ToDictionary(r => r.Contract, r => r.Implementation, StringComparer.Ordinal); + + foreach (var (serviceType, implementationType) in TizenEssentialsRegistrationTests.ExpectedRegistrations) + Assert.Equal(implementationType.Name, byContract[serviceType.Name]); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenAccelerometerQueueTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenAccelerometerQueueTests.cs new file mode 100644 index 00000000..b659195d --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenAccelerometerQueueTests.cs @@ -0,0 +1,108 @@ +using System; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Behavioural tests for the shake-detection window used by . +/// +public class TizenAccelerometerQueueTests +{ + const long Millisecond = 1_000_000; + + [Fact] + public void IsNotShakingWhenEmpty() => + Assert.False(new TizenAccelerometerQueue().IsShaking); + + [Fact] + public void IsNotShakingBeforeTheMinimumWindowElapses() + { + var queue = new TizenAccelerometerQueue(); + + for (var i = 0; i < 8; i++) + queue.Add(i * 10 * Millisecond, accelerating: true); + + // 70ms of samples is well below the 250ms minimum window. + Assert.False(queue.IsShaking); + } + + [Fact] + public void IsShakingWhenMostOfALongEnoughWindowIsAccelerating() + { + var queue = new TizenAccelerometerQueue(); + + for (var i = 0; i < 8; i++) + queue.Add(i * 40 * Millisecond, accelerating: true); + + Assert.True(queue.IsShaking); + } + + [Fact] + public void IsNotShakingWhenTooFewSamplesAreAccelerating() + { + var queue = new TizenAccelerometerQueue(); + + for (var i = 0; i < 8; i++) + queue.Add(i * 40 * Millisecond, accelerating: i < 4); + + Assert.False(queue.IsShaking); + } + + [Fact] + public void ClearResetsTheWindow() + { + var queue = new TizenAccelerometerQueue(); + + for (var i = 0; i < 8; i++) + queue.Add(i * 40 * Millisecond, accelerating: true); + + Assert.True(queue.IsShaking); + + queue.Clear(); + + Assert.False(queue.IsShaking); + } + + [Fact] + public void PurgesSamplesOlderThanTheMaximumWindow() + { + var queue = new TizenAccelerometerQueue(); + + // Old, accelerating samples... + for (var i = 0; i < 8; i++) + queue.Add(i * 10 * Millisecond, accelerating: true); + + // ...followed by fresh, calm samples far beyond the 500ms window. + for (var i = 0; i < 4; i++) + queue.Add((5_000 + (i * 10)) * Millisecond, accelerating: false); + + Assert.False(queue.IsShaking); + } + + [Fact] + public void KeepsAMinimumNumberOfSamplesWhilePurging() + { + // Faithful to dotnet/maui's AccelerometerQueue: purging never drops below four samples, so a + // single fresh sample after a burst still sees the tail of that burst. + var queue = new TizenAccelerometerQueue(); + + for (var i = 0; i < 8; i++) + queue.Add(i * 10 * Millisecond, accelerating: true); + + queue.Add(5_000 * Millisecond, accelerating: false); + + Assert.True(queue.IsShaking); + } + + [Fact] + public void ConvertsUtcTimestampsToNanoseconds() + { + var start = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + var delta = TizenAccelerometerQueue.ToNanoseconds(start.AddMilliseconds(250)) - + TizenAccelerometerQueue.ToNanoseconds(start); + + Assert.Equal(250 * Millisecond, delta); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenEssentialsRegistrationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenEssentialsRegistrationTests.cs new file mode 100644 index 00000000..190e9fe8 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenEssentialsRegistrationTests.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Maui.Accessibility; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using Microsoft.Maui.ApplicationModel.DataTransfer; +using Microsoft.Maui.Authentication; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Media; +using Microsoft.Maui.Networking; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Microsoft.Maui.Storage; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Contracts covering AddTizenEssentials. +/// +/// +/// These assertions inspect metadata instead of resolving through +/// the container wherever possible, so they run on any host without a Tizen device present. +/// +public class TizenEssentialsRegistrationTests +{ + /// + /// Every Essentials contract this backend implements, mapped to its implementation type. + /// + public static readonly IReadOnlyDictionary ExpectedRegistrations = new Dictionary + { + [typeof(IAppActions)] = typeof(TizenAppActions), + [typeof(IAppInfo)] = typeof(TizenAppInfo), + [typeof(IBrowser)] = typeof(TizenBrowser), + [typeof(ILauncher)] = typeof(TizenLauncher), + [typeof(IMap)] = typeof(TizenMap), + [typeof(IPermissions)] = typeof(TizenPermissions), + + [typeof(IContacts)] = typeof(TizenContacts), + [typeof(IEmail)] = typeof(TizenEmail), + [typeof(IPhoneDialer)] = typeof(TizenPhoneDialer), + [typeof(ISms)] = typeof(TizenSms), + + [typeof(IClipboard)] = typeof(TizenClipboard), + [typeof(IShare)] = typeof(TizenShare), + + [typeof(IFilePicker)] = typeof(TizenFilePicker), + [typeof(IFileSystem)] = typeof(TizenFileSystem), + [typeof(IPreferences)] = typeof(TizenPreferences), + [typeof(ISecureStorage)] = typeof(TizenSecureStorage), + + [typeof(IBattery)] = typeof(TizenBattery), + [typeof(IDeviceDisplay)] = typeof(TizenDeviceDisplay), + [typeof(IDeviceInfo)] = typeof(TizenDeviceInfo), + [typeof(IFlashlight)] = typeof(TizenFlashlight), + [typeof(IHapticFeedback)] = typeof(TizenHapticFeedback), + [typeof(IVibration)] = typeof(TizenVibration), + + [typeof(IAccelerometer)] = typeof(TizenAccelerometer), + [typeof(IBarometer)] = typeof(TizenBarometer), + [typeof(ICompass)] = typeof(TizenCompass), + [typeof(IGyroscope)] = typeof(TizenGyroscope), + [typeof(IMagnetometer)] = typeof(TizenMagnetometer), + [typeof(IOrientationSensor)] = typeof(TizenOrientationSensor), + + [typeof(IGeolocation)] = typeof(TizenGeolocation), + + [typeof(IConnectivity)] = typeof(TizenConnectivity), + + [typeof(IMediaPicker)] = typeof(TizenMediaPicker), + [typeof(IScreenshot)] = typeof(TizenScreenshot), + [typeof(ITextToSpeech)] = typeof(TizenTextToSpeech), + + [typeof(ISemanticScreenReader)] = typeof(TizenSemanticScreenReader), + + [typeof(IAppleSignInAuthenticator)] = typeof(TizenAppleSignInAuthenticator), + [typeof(IPasskeys)] = typeof(TizenPasskeys), + [typeof(IWebAuthenticator)] = typeof(TizenWebAuthenticator), + }; + + public static TheoryData ExpectedServiceTypes() + { + var data = new TheoryData(); + foreach (var serviceType in ExpectedRegistrations.Keys) + data.Add(serviceType); + return data; + } + + static IServiceCollection Registered() + { + var services = new ServiceCollection(); + services.AddTizenEssentials(); + return services; + } + + [Theory] + [MemberData(nameof(ExpectedServiceTypes))] + public void RegistersEachEssentialsContractExactlyOnce(Type serviceType) + { + var descriptor = Assert.Single(Registered(), d => d.ServiceType == serviceType); + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + Assert.Equal(ExpectedRegistrations[serviceType], descriptor.ImplementationType); + } + + [Fact] + public void RegistersGeocodingAsASingleSharedInstance() + { + var services = Registered(); + + var concrete = Assert.Single(services, d => d.ServiceType == typeof(TizenGeocoding)); + Assert.Equal(ServiceLifetime.Singleton, concrete.Lifetime); + Assert.Equal(typeof(TizenGeocoding), concrete.ImplementationType); + + // IGeocoding and IPlatformGeocoding must resolve to the *same* instance, otherwise the + // map service token forwarded by the .NET 11 Essentials DI bridge to IPlatformGeocoding + // would not be visible to code resolving IGeocoding. + foreach (var serviceType in new[] { typeof(IGeocoding), typeof(IPlatformGeocoding) }) + { + var descriptor = Assert.Single(services, d => d.ServiceType == serviceType); + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + Assert.NotNull(descriptor.ImplementationFactory); + } + + using var provider = services.BuildServiceProvider(); + + var geocoding = provider.GetRequiredService(); + Assert.Same(geocoding, provider.GetRequiredService()); + Assert.Same(geocoding, provider.GetRequiredService()); + } + + [Fact] + public void EveryServiceResolvesToItsRegisteredSingleton() + { + using var provider = Registered().BuildServiceProvider(); + + foreach (var (serviceType, implementationType) in ExpectedRegistrations) + { + var instance = provider.GetService(serviceType); + + Assert.NotNull(instance); + Assert.IsType(implementationType, instance); + Assert.Same(instance, provider.GetService(serviceType)); + } + } + + [Fact] + public void IsIdempotent() + { + var services = new ServiceCollection(); + services.AddTizenEssentials(); + var afterFirst = services.Count; + + services.AddTizenEssentials(); + + Assert.Equal(afterFirst, services.Count); + } + + [Theory] + [MemberData(nameof(ExpectedServiceTypes))] + public void UsesTryAddSoApplicationsCanOverrideAnyService(Type serviceType) + { + var services = new ServiceCollection(); + var replacement = new object(); + + services.AddSingleton(serviceType, _ => replacement); + services.AddTizenEssentials(); + + var descriptor = Assert.Single(services, d => d.ServiceType == serviceType); + Assert.NotNull(descriptor.ImplementationFactory); + Assert.Null(descriptor.ImplementationType); + } + + [Fact] + public void RejectsANullServiceCollection() => + Assert.Throws( + static () => TizenEssentialsMauiAppBuilderExtensions.AddTizenEssentials((IServiceCollection)null!)); + + [Fact] + public void RejectsANullAppBuilder() => + Assert.Throws( + static () => TizenEssentialsMauiAppBuilderExtensions.AddTizenEssentials((MauiAppBuilder)null!)); + + [Fact] + public void RegistersNothingBeyondTheDocumentedSurface() + { + var allowed = ExpectedRegistrations.Keys + .Append(typeof(TizenGeocoding)) + .Append(typeof(IGeocoding)) + .Append(typeof(IPlatformGeocoding)) + .ToHashSet(); + + var unexpected = Registered() + .Select(d => d.ServiceType) + .Where(t => !allowed.Contains(t)) + .Distinct() + .ToList(); + + Assert.Empty(unexpected); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenHostAssemblyResolver.cs b/tests/Maui.Tizen.Essentials.Tests/TizenHostAssemblyResolver.cs new file mode 100644 index 00000000..650a37a1 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenHostAssemblyResolver.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Resolves the Tizen.NET assemblies that the build copies next to the test binaries. +/// +/// +/// Tizen.NET publishes its assemblies as NuGet ref/ assets, so they never appear in the +/// generated .deps.json and the default host probing logic will not find them even when the +/// files are present. They are real implementation assemblies, so loading them by path is enough to +/// let the host-side tests read Tizen metadata and run managed-only code paths. Calls that actually +/// P/Invoke into Tizen still require a device or emulator. +/// +internal static class TizenHostAssemblyResolver +{ + [ModuleInitializer] + internal static void Initialize() => + AssemblyLoadContext.Default.Resolving += static (context, name) => + { + if (name.Name is not { } simpleName) + return null; + + if (!simpleName.StartsWith("Tizen", StringComparison.Ordinal) && + !simpleName.StartsWith("ElmSharp", StringComparison.Ordinal)) + { + return null; + } + + var path = Path.Combine(AppContext.BaseDirectory, simpleName + ".dll"); + + return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null; + }; +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs new file mode 100644 index 00000000..1d57da82 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs @@ -0,0 +1,135 @@ +using System; +using System.Linq; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Verifies the Tizen privilege mapping that keeps +/// Permissions.RequestAsync<Permissions.Camera>() source compatible with the in-box +/// dotnet/maui Tizen backend. +/// +public class TizenPermissionsTests +{ + [Theory] + [InlineData(typeof(Permissions.Camera), "http://tizen.org/privilege/camera", false)] + [InlineData(typeof(Permissions.ContactsRead), "http://tizen.org/privilege/contact.read", true)] + [InlineData(typeof(Permissions.ContactsWrite), "http://tizen.org/privilege/contact.write", true)] + [InlineData(typeof(Permissions.Flashlight), "http://tizen.org/privilege/led", false)] + [InlineData(typeof(Permissions.LaunchApp), "http://tizen.org/privilege/appmanager.launch", false)] + [InlineData(typeof(Permissions.LocationWhenInUse), "http://tizen.org/privilege/location", true)] + [InlineData(typeof(Permissions.LocationAlways), "http://tizen.org/privilege/location", true)] + [InlineData(typeof(Permissions.Microphone), "http://tizen.org/privilege/recorder", false)] + [InlineData(typeof(Permissions.StorageRead), "http://tizen.org/privilege/mediastorage", true)] + [InlineData(typeof(Permissions.StorageWrite), "http://tizen.org/privilege/mediastorage", true)] + [InlineData(typeof(Permissions.Vibrate), "http://tizen.org/privilege/haptic", false)] + public void MapsWellKnownPermissionsToTizenPrivileges(Type permission, string privilege, bool isRuntime) + { + Assert.True(TizenPermissions.TryGetKnownPrivileges(permission, out var privileges)); + + var match = Assert.Single(privileges!, p => p.Privilege == privilege); + Assert.Equal(isRuntime, match.IsRuntime); + } + + [Fact] + public void MapsMapsPermissionToAllThreeRequiredPrivileges() + { + Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(Permissions.Maps), out var privileges)); + + Assert.Equal( + new[] + { + "http://tizen.org/privilege/internet", + "http://tizen.org/privilege/mapservice", + "http://tizen.org/privilege/network.get", + }, + privileges!.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); + + Assert.All(privileges!, p => Assert.False(p.IsRuntime)); + } + + [Fact] + public void MapsNetworkStatePermissionToInternetAndNetworkGet() + { + Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(Permissions.NetworkState), out var privileges)); + + Assert.Equal( + new[] + { + "http://tizen.org/privilege/internet", + "http://tizen.org/privilege/network.get", + }, + privileges!.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); + } + + [Theory] + [InlineData(typeof(Permissions.Battery))] + [InlineData(typeof(Permissions.Bluetooth))] + [InlineData(typeof(Permissions.CalendarRead))] + [InlineData(typeof(Permissions.Media))] + [InlineData(typeof(Permissions.Phone))] + [InlineData(typeof(Permissions.Photos))] + [InlineData(typeof(Permissions.PostNotifications))] + [InlineData(typeof(Permissions.Sensors))] + [InlineData(typeof(Permissions.Speech))] + public void KnowsPermissionsThatTizenDoesNotGate(Type permission) + { + Assert.True(TizenPermissions.TryGetKnownPrivileges(permission, out var privileges)); + Assert.Empty(privileges!); + } + + [Fact] + public void CoversEveryBuiltInMauiPermissionType() + { + var builtIn = typeof(Permissions) + .GetNestedTypes() + .Where(t => t.IsClass && !t.IsAbstract && typeof(Permissions.BasePermission).IsAssignableFrom(t)) + .ToList(); + + Assert.NotEmpty(builtIn); + + var unmapped = builtIn + .Where(t => !TizenPermissions.TryGetKnownPrivileges(t, out _)) + .Select(t => t.Name) + .ToList(); + + Assert.Empty(unmapped); + } + + [Fact] + public void FallsBackToTheDerivedMappingForSubclassedPermissions() + { + Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(DerivedCameraPermission), out var privileges)); + Assert.Equal("http://tizen.org/privilege/camera", Assert.Single(privileges!).Privilege); + } + + [Fact] + public void LeavesCustomPermissionsToOwnTheirBehaviour() => + Assert.False(TizenPermissions.TryGetKnownPrivileges(typeof(CustomPermission), out _)); + + [Fact] + public void NeverShowsARationaleBecauseTizenHasNoRationaleContract() => + Assert.False(new TizenPermissions().ShouldShowRationale()); + + [Fact] + public void CustomTizenPermissionsDefaultToNoPrivileges() => + Assert.Empty(new CustomPermission().RequiredPrivileges); + + [Fact] + public void RejectsANullPrivilegeCollection() => + Assert.Throws(static () => TizenPermissions.EnsureDeclared(null!)); + + [Fact] + public void TreatsAnEmptyPrivilegeNameAsUndeclared() => + Assert.False(TizenPermissions.IsPrivilegeDeclared(string.Empty)); + + sealed class DerivedCameraPermission : Permissions.Camera + { + } + + sealed class CustomPermission : TizenBasePlatformPermission + { + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs new file mode 100644 index 00000000..bd5d5e22 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs @@ -0,0 +1,184 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Media; +using Microsoft.Maui.Networking; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; +using TizenConnectionProfileType = Tizen.Network.Connection.ConnectionProfileType; +using TizenDeviceOrientation = Tizen.Applications.DeviceOrientation; +using TizenPixelFormat = Tizen.NUI.PixelFormat; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Behavioural tests for the pure translation logic ported from the dotnet/maui Tizen backend. +/// These run without a Tizen device because they never call into native libraries. +/// +public class TizenTranslationTests +{ + [Theory] + [InlineData("1.2.3", 1, 2, 3)] + [InlineData("1.2", 1, 2, -1)] + [InlineData("1.0.0-rc1", 1, 0, 0)] + [InlineData("7", 7, 0, -1)] + [InlineData("", 0, 0, -1)] + [InlineData(null, 0, 0, -1)] + [InlineData("not-a-version", 0, 0, -1)] + public void ParsesTizenPackageVersions(string? input, int major, int minor, int build) + { + var version = TizenPlatform.ParseVersion(input); + + Assert.Equal(major, version.Major); + Assert.Equal(minor, version.Minor); + Assert.Equal(build, version.Build); + } + + [Theory] + [InlineData("mobile", TizenDeviceProfile.Mobile)] + [InlineData("MOBILE", TizenDeviceProfile.Mobile)] + [InlineData("wearable", TizenDeviceProfile.Wearable)] + [InlineData("tv", TizenDeviceProfile.TV)] + [InlineData("common", TizenDeviceProfile.Common)] + [InlineData("iot-headed", TizenDeviceProfile.Common)] + [InlineData("zzz", TizenDeviceProfile.Unknown)] + [InlineData("", TizenDeviceProfile.Unknown)] + [InlineData(null, TizenDeviceProfile.Unknown)] + public void ClassifiesTizenDeviceProfiles(string? profile, TizenDeviceProfile expected) => + Assert.Equal(expected, TizenSystemInformation.ParseProfile(profile)); + + [Theory] + [InlineData("armv7", true, false, DeviceType.Physical)] + [InlineData("x86", false, true, DeviceType.Virtual)] + [InlineData("armv7", true, true, DeviceType.Unknown)] + [InlineData("aarch64", false, false, DeviceType.Unknown)] + [InlineData(null, false, false, DeviceType.Unknown)] + public void ClassifiesDeviceType(string? arch, bool armv7, bool x86, DeviceType expected) => + Assert.Equal(expected, TizenDeviceInfo.ClassifyDeviceType(arch, armv7, x86)); + + [Theory] + [InlineData(SensorSpeed.Fastest, 0u)] + [InlineData(SensorSpeed.Game, 20u)] + [InlineData(SensorSpeed.UI, 60u)] + [InlineData(SensorSpeed.Default, 200u)] + public void MapsSensorSpeedToTizenIntervals(SensorSpeed speed, uint expected) => + Assert.Equal(expected, speed.ToPlatform()); + + [Theory] + [InlineData(HapticFeedbackType.LongPress, "Hold")] + [InlineData(HapticFeedbackType.Click, "Tap")] + public void MapsHapticFeedbackTypes(HapticFeedbackType type, string expected) => + Assert.Equal(expected, TizenHapticFeedback.ConvertType(type)); + + [Theory] + [InlineData(null, "key", "key")] + [InlineData("", "key", "key")] + [InlineData("shared", "key", "shared~key")] + public void PrefixesSharedPreferenceKeys(string? sharedName, string key, string expected) => + Assert.Equal(expected, TizenPreferences.GetFullKey(key, sharedName)); + + [Theory] + [InlineData(TizenConnectionProfileType.WiFi, ConnectionProfile.WiFi)] + [InlineData(TizenConnectionProfileType.Cellular, ConnectionProfile.Cellular)] + [InlineData(TizenConnectionProfileType.Ethernet, ConnectionProfile.Ethernet)] + [InlineData(TizenConnectionProfileType.Bt, ConnectionProfile.Bluetooth)] + public void MapsConnectionProfiles(TizenConnectionProfileType type, ConnectionProfile expected) => + Assert.Equal(expected, TizenConnectivity.MapProfileType(type)); + + [Theory] + [InlineData(TizenDeviceOrientation.Orientation_0, DisplayRotation.Rotation0, DisplayOrientation.Portrait)] + [InlineData(TizenDeviceOrientation.Orientation_90, DisplayRotation.Rotation90, DisplayOrientation.Landscape)] + [InlineData(TizenDeviceOrientation.Orientation_180, DisplayRotation.Rotation180, DisplayOrientation.Portrait)] + [InlineData(TizenDeviceOrientation.Orientation_270, DisplayRotation.Rotation270, DisplayOrientation.Landscape)] + public void MapsDisplayOrientationFromAPortraitNaturalOrientation( + TizenDeviceOrientation deviceOrientation, + DisplayRotation expectedRotation, + DisplayOrientation expectedOrientation) + { + var (rotation, orientation) = TizenDeviceDisplay.MapOrientation(deviceOrientation, DisplayOrientation.Portrait); + + Assert.Equal(expectedRotation, rotation); + Assert.Equal(expectedOrientation, orientation); + } + + [Fact] + public void MapsDisplayOrientationFromALandscapeNaturalOrientation() + { + var (rotation, orientation) = + TizenDeviceDisplay.MapOrientation(TizenDeviceOrientation.Orientation_90, DisplayOrientation.Landscape); + + Assert.Equal(DisplayRotation.Rotation90, rotation); + Assert.Equal(DisplayOrientation.Portrait, orientation); + } + + [Fact] + public void UsesTheAndroidStyleBaseLogicalDpiForDensity() => + Assert.Equal(160.0f, TizenDeviceDisplay.BaseLogicalDpi); + + [Fact] + public void ConvertsGpsSpeedFromKilometresPerHourToMetresPerSecond() => + Assert.Equal(10.0, TizenGeolocation.KilometersPerHourToMetersPerSecond(36), 1); + + [Fact] + public void EscapesPlacemarkAddressesForGeoQueries() + { + var placemark = new Placemark + { + Thoroughfare = "1 Main St", + Locality = "Redmond", + AdminArea = "WA", + PostalCode = "98052", + CountryName = "USA", + }; + + var escaped = placemark.GetEscapedAddress(); + + Assert.DoesNotContain(' ', escaped); + Assert.Equal( + Uri.EscapeDataString("1 Main St Redmond WA 98052 USA"), + escaped); + } + + [Theory] + [InlineData(TizenPixelFormat.RGBA8888, 4)] + [InlineData(TizenPixelFormat.BGRA8888, 4)] + [InlineData(TizenPixelFormat.RGB888, 3)] + [InlineData(TizenPixelFormat.RGB565, 2)] + public void MapsScreenshotPixelStrides(TizenPixelFormat format, int expected) => + Assert.Equal(expected, TizenScreenshotResult.BytesPerPixel(format)); + + [Fact] + public void RejectsScreenshotPixelFormatsWithoutAMatchingColorSpace() + { + Assert.Throws( + static () => { _ = TizenScreenshotResult.MapColorSpace(TizenPixelFormat.A8); }); + Assert.Throws( + static () => { _ = TizenScreenshotResult.BytesPerPixel(TizenPixelFormat.A8); }); + } + + [Fact] + public void ScreenshotImplementsTheNeutralViewCaptureContract() + { + Assert.True(typeof(IScreenshot).IsAssignableFrom(typeof(TizenScreenshot))); + Assert.True(typeof(IViewScreenshot).IsAssignableFrom(typeof(TizenScreenshot))); + } + + [Fact] + public async Task ScreenshotReturnsNullForForeignPlatformViews() => + Assert.Null(await new TizenScreenshot().CaptureViewAsync(new object())); + + [Fact] + public void TizenTypedScreenshotHelpersRejectForeignImplementations() => + Assert.Throws( + static () => { _ = new FakeScreenshot().CaptureAsync((global::Tizen.NUI.Window)null!); }); + + sealed class FakeScreenshot : IScreenshot + { + public bool IsCaptureSupported => false; + + public System.Threading.Tasks.Task CaptureAsync() => + throw new NotSupportedException(); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs new file mode 100644 index 00000000..5024d656 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs @@ -0,0 +1,112 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Verifies that capabilities Tizen cannot provide fail loudly instead of returning +/// success-shaped results (empty collections, , completed tasks). +/// +public class TizenUnsupportedCapabilityTests +{ + [Fact] + public void ClipboardReportsNoSilentFallback() + { + var clipboard = new TizenClipboard(); + + Assert.Throws(() => _ = clipboard.HasText); + Assert.Throws(() => { _ = clipboard.GetTextAsync(); }); + Assert.Throws(() => { _ = clipboard.SetTextAsync("hello"); }); + } + + [Fact] + public void AppActionsReportUnsupportedRatherThanAcceptingActions() + { + var appActions = new TizenAppActions(); + + Assert.False(appActions.IsSupported); + Assert.Throws(() => { _ = appActions.GetAsync(); }); + Assert.Throws(() => { _ = appActions.SetAsync(Array.Empty()); }); + } + + [Fact] + public void PasskeysReportUnsupported() + { + var passkeys = new TizenPasskeys(); + + Assert.False(passkeys.IsSupported); + Assert.Throws(() => { _ = passkeys.CreateAsync(null!, TestContext.Current.CancellationToken); }); + Assert.Throws(() => { _ = passkeys.AssertAsync(null!, TestContext.Current.CancellationToken); }); + } + + [Fact] + public void WebAuthenticatorReportsUnsupported() + { + var authenticator = new TizenWebAuthenticator(); + + Assert.Throws(() => { _ = authenticator.AuthenticateAsync(null!); }); + Assert.Throws( + () => { _ = authenticator.AuthenticateAsync(null!, TestContext.Current.CancellationToken); }); + } + + [Fact] + public void AppleSignInReportsUnsupported() => + Assert.Throws( + static () => { _ = new TizenAppleSignInAuthenticator().AuthenticateAsync(); }); + + [Fact] + public void GeolocationForegroundListeningReportsUnsupported() + { + var geolocation = new TizenGeolocation(); + + Assert.False(geolocation.IsListeningForeground); + Assert.Throws(() => { _ = geolocation.StartListeningForegroundAsync(null!); }); + Assert.Throws(() => geolocation.StopListeningForeground()); + } + + [Fact] + public async Task GeolocationHasNoLastKnownLocationBeforeAnyRequest() => + Assert.Null(await new TizenGeolocation().GetLastKnownLocationAsync()); + + [Fact] + public void BatteryEnergySaverReportsUnsupportedRatherThanOff() + { + var battery = new TizenBattery(); + + Assert.Throws(() => _ = battery.EnergySaverStatus); + Assert.Throws(() => battery.EnergySaverStatusChanged += (_, _) => { }); + Assert.Throws(() => battery.EnergySaverStatusChanged -= (_, _) => { }); + } + + [Fact] + public void TextToSpeechLocalesSurfaceTheMauiApiGap() + { + var exception = Assert.Throws( + static () => { _ = new TizenTextToSpeech().GetLocalesAsync(); }); + + Assert.Contains("Locale", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void UnsupportedMessagesNameTheCapabilityAndTheReason() + { + var exception = TizenEssentialsSupport.NotSupported("IClipboard.HasText", "Because Tizen."); + + Assert.Contains("IClipboard.HasText", exception.Message, StringComparison.Ordinal); + Assert.Contains("Because Tizen.", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void ProfileScopedMessagesNameTheSupportedProfiles() + { + var exception = TizenEssentialsSupport.NotSupportedOnProfile( + "ISms.ComposeAsync", + TizenDeviceProfile.Mobile); + + Assert.Contains("ISms.ComposeAsync", exception.Message, StringComparison.Ordinal); + Assert.Contains(nameof(TizenDeviceProfile.Mobile), exception.Message, StringComparison.Ordinal); + } +} From 7811e769ebcb198f7494b4acbbd441df93e4f9b2 Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 16:45:34 -0400 Subject: [PATCH 02/21] Assert the Essentials test count in CI, not just the exit code `check` only inspects an exit code, which is demonstrably insufficient evidence for this assembly. Test discovery walks assembly-level attributes across the loaded closure, and Tizen.NUI's [XmlnsDefinition] constructor P/Invokes and throws off-device. On the xunit v2 runner that aborted discovery part way through a class and silently dropped the rest while still reporting success - it hid 4 tests before it was caught. xunit v3 handles it today, but "the runner exited 0" is not proof that the tests actually ran, and the failure is invisible by construction. The lane now parses the runner summary and fails if fewer than 195 tests execute. Verified both directions: passes at the real count, and fails with "test discovery regressed" when the floor is raised above it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/build-workload-free.sh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 86378db6..2ff14d84 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -203,6 +203,31 @@ if [[ $BUILD_OK -eq 1 ]]; then ESSENTIALS_TESTS="artifacts/bin/Maui.Tizen.Essentials.Tests/Release/net11.0/Maui.Tizen.Essentials.Tests" check "essentials tests binary was produced" test -x "$ESSENTIALS_TESTS" check "essentials tests" "./$ESSENTIALS_TESTS" + + # Assert the test COUNT, not just the exit code. + # + # This is not belt-and-braces. Discovery over this assembly walks assembly-level attributes + # across the loaded closure, and Tizen.NUI's [XmlnsDefinition] constructor P/Invokes and + # throws off-device. On the xunit v2 runner that aborted discovery part way through a class + # and SILENTLY DROPPED the remaining tests while still reporting success - it hid 4 tests + # before it was noticed. v3 handles it, but "the runner reported success" is demonstrably + # not sufficient evidence here, so the floor is pinned. + # + # Raise this when adding tests; never lower it to make a run go green. + ESSENTIALS_TESTS_MINIMUM=195 + check "essentials tests ran at least $ESSENTIALS_TESTS_MINIMUM tests" bash -c ' + set -euo pipefail + total="$("./$1" 2>/dev/null | sed -n "s/^[[:space:]]*total:[[:space:]]*\([0-9][0-9]*\).*/\1/p" | tail -1)" + if [ -z "$total" ]; then + echo "could not parse a test total from the runner summary" + exit 1 + fi + if [ "$total" -lt "$2" ]; then + echo "test discovery regressed: ran $total, expected at least $2" + exit 1 + fi + echo "ran $total tests" + ' _ "$ESSENTIALS_TESTS" "$ESSENTIALS_TESTS_MINIMUM" else fail "unit tests skipped - a preceding build failed (running --no-build now would only add cascading noise)" FAILURES=$((FAILURES + 1)) From 20e2ae8bec67ae2991e03c8cca793291cebb8cc6 Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 16:48:08 -0400 Subject: [PATCH 03/21] Read the Essentials test count from a report file, not console text The previous commit's count assertion scraped the runner's console summary. It passed locally and failed on the CI runner with "could not parse a test total from the runner summary", because console rendering is not a stable contract across platforms and terminals. Replaced with `eng/assert-test-count.py`, which reads the runner's JUnit report. It counts `` elements rather than trusting the summary attribute, so a report whose header disagrees with its body cannot pass, and it fails when the report is missing entirely - the case that would otherwise let a runner that never started look green. Verified all three paths: passes at the real count, fails with "test discovery regressed" when the floor is raised, and fails with "no test report" when the file is absent. Full lane green from a clean tree, exit code 0. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/assert-test-count.py | 60 ++++++++++++++++++++++++++++++++++++++ eng/build-workload-free.sh | 31 +++++++++----------- 2 files changed, 74 insertions(+), 17 deletions(-) create mode 100755 eng/assert-test-count.py diff --git a/eng/assert-test-count.py b/eng/assert-test-count.py new file mode 100755 index 00000000..50a742a3 --- /dev/null +++ b/eng/assert-test-count.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Assert that a test run actually executed at least a minimum number of tests. + +An exit code alone is not sufficient evidence that a test suite ran. Test discovery over +the Essentials assembly walks assembly-level attributes across the loaded closure, and +Tizen.NUI's [XmlnsDefinition] constructor P/Invokes and throws when no Tizen device is +present. On the xunit v2 runner that aborted discovery part way through a class and +silently dropped the remaining tests while still reporting success. + +The count is read from the runner's JUnit report rather than from its console output. +Console rendering is not a stable contract - an earlier version of this check scraped +stdout, passed locally, and failed on the CI runner. +""" + +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +def main(argv: list[str]) -> int: + if len(argv) != 3: + print(f"usage: {Path(argv[0]).name} ", file=sys.stderr) + return 2 + + report = Path(argv[1]) + try: + minimum = int(argv[2]) + except ValueError: + print(f"minimum must be an integer, got {argv[2]!r}", file=sys.stderr) + return 2 + + if not report.is_file(): + print(f"no test report at '{report}' - the runner did not produce one") + return 1 + + try: + root = ET.parse(report).getroot() + except ET.ParseError as error: + print(f"could not parse '{report}': {error}") + return 1 + + # Count elements rather than trusting the summary attribute, so a report + # whose header disagrees with its body cannot pass. + total = len(list(root.iter("testcase"))) + + if total < minimum: + print(f"test discovery regressed: ran {total}, expected at least {minimum}") + return 1 + + failures = len(list(root.iter("failure"))) + len(list(root.iter("error"))) + if failures: + print(f"{failures} test(s) reported a failure in '{report}'") + return 1 + + print(f"ran {total} tests") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 2ff14d84..c77fa043 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -201,8 +201,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # need the repository-wide dotnet.config MTP opt-in, which would break tests/UnitTests # (xunit v2 on VSTest). See that project's csproj for the full reasoning. ESSENTIALS_TESTS="artifacts/bin/Maui.Tizen.Essentials.Tests/Release/net11.0/Maui.Tizen.Essentials.Tests" - check "essentials tests binary was produced" test -x "$ESSENTIALS_TESTS" - check "essentials tests" "./$ESSENTIALS_TESTS" + ESSENTIALS_RESULTS="$REPO_ROOT/artifacts/test-results/essentials" # Assert the test COUNT, not just the exit code. # @@ -210,24 +209,22 @@ if [[ $BUILD_OK -eq 1 ]]; then # across the loaded closure, and Tizen.NUI's [XmlnsDefinition] constructor P/Invokes and # throws off-device. On the xunit v2 runner that aborted discovery part way through a class # and SILENTLY DROPPED the remaining tests while still reporting success - it hid 4 tests - # before it was noticed. v3 handles it, but "the runner reported success" is demonstrably - # not sufficient evidence here, so the floor is pinned. + # before it was noticed. v3 handles it, but "the runner exited 0" is demonstrably not + # sufficient evidence here, so the floor is pinned. + # + # The count comes from the runner's JUnit report rather than from scraping its console + # summary: the first attempt at this parsed stdout and passed locally but failed on the CI + # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. ESSENTIALS_TESTS_MINIMUM=195 - check "essentials tests ran at least $ESSENTIALS_TESTS_MINIMUM tests" bash -c ' - set -euo pipefail - total="$("./$1" 2>/dev/null | sed -n "s/^[[:space:]]*total:[[:space:]]*\([0-9][0-9]*\).*/\1/p" | tail -1)" - if [ -z "$total" ]; then - echo "could not parse a test total from the runner summary" - exit 1 - fi - if [ "$total" -lt "$2" ]; then - echo "test discovery regressed: ran $total, expected at least $2" - exit 1 - fi - echo "ran $total tests" - ' _ "$ESSENTIALS_TESTS" "$ESSENTIALS_TESTS_MINIMUM" + + check "essentials tests" "$ESSENTIALS_TESTS" \ + --report-xunit-junit --report-xunit-junit-filename results.xml \ + --results-directory "$ESSENTIALS_RESULTS" + + check "essentials tests ran at least $ESSENTIALS_TESTS_MINIMUM tests" \ + python3 "$REPO_ROOT/eng/assert-test-count.py" "$ESSENTIALS_RESULTS/results.xml" "$ESSENTIALS_TESTS_MINIMUM" else fail "unit tests skipped - a preceding build failed (running --no-build now would only add cascading noise)" FAILURES=$((FAILURES + 1)) From 16483a91b69c81c48964cce05887271952f57f3c Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 17:25:21 -0400 Subject: [PATCH 04/21] Merge core head 2610231 (MAUI 26426.4) and pin the Locale gap with a tripwire Merges the final `redth-tizen-core-vertical-slice` head, which upgrades the MAUI development package baseline to 11.0.0-preview.7.26426.4 and brings foundation 1b4960f along with it. No conflicts. Re-verified the blocking `Microsoft.Maui.Media.Locale` API gap against the newer packages rather than assuming it carried forward: the constructor is still `internal` in 26426.4, so `TizenTextToSpeech.GetLocalesAsync` must keep throwing. Replaced that manual re-check with a test. `MauiLocaleStillExposesNoPublicConstructor` asserts the gap is still open, so the moment a public constructor appears the suite fails and its message says exactly what to do: implement GetLocalesAsync properly, drop the GetSupportedVoiceLanguagesAsync workaround from the coverage matrix, and delete the test. That inverts the maintenance burden. Today someone has to remember to re-probe this on every MAUI bump, and forgetting means the workaround silently outlives the problem it works around. Test count 195 -> 196, so the CI floor is raised to match - which is the direction that assertion is meant to move. Verified: `eng/build-workload-free.sh` green from a clean tree under CI semantics against the new packages, including both Essentials lanes, both core lanes, the package graph probe and workload detection regressions. The Essentials ref-pack lane still builds clean with the PublicAPI analyzer enforcing the regenerated baseline. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/tizen-essentials-service-coverage.md | 4 +- eng/build-workload-free.sh | 2 +- .../TizenUnsupportedCapabilityTests.cs | 38 +++++++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 8f801754..fecf33c8 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (193 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (196 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | @@ -118,7 +118,7 @@ platform backend cannot use. Each one is worked around in this package. | MAUI API | Accessibility | Impact | Workaround | | --- | --- | --- | --- | -| `Microsoft.Maui.Media.Locale..ctor(string, string, string, string)` | `internal` | **Blocking.** `ITextToSpeech.GetLocalesAsync` must return `IEnumerable`, and `SpeechOptions.Locale` must be given one, but no external assembly can construct a `Locale`. | `GetLocalesAsync` throws with an explicit reason; `TizenTextToSpeech.GetSupportedVoiceLanguagesAsync()` and `SpeakWithVoiceAsync(text, language, rate, ct)` expose the same capability. | +| `Microsoft.Maui.Media.Locale..ctor(string, string, string, string)` | `internal` (still closed as of `11.0.0-preview.7.26426.4`; pinned by the `MauiLocaleStillExposesNoPublicConstructor` tripwire test, which fails the moment it opens) | **Blocking.** `ITextToSpeech.GetLocalesAsync` must return `IEnumerable`, and `SpeechOptions.Locale` must be given one, but no external assembly can construct a `Locale`. | `GetLocalesAsync` throws with an explicit reason; `TizenTextToSpeech.GetSupportedVoiceLanguagesAsync()` and `SpeakWithVoiceAsync(text, language, rate, ct)` expose the same capability. | | `Microsoft.Maui.Storage.FileMimeTypes` | `internal` | MIME constants used by pickers and launchers. | `TizenFileMimeTypes`. | | `Microsoft.Maui.Devices.Sensors.PlacemarkExtensions.GetEscapedAddress` | `internal` | Address formatting for `geo:0,0?q=` queries. | `TizenPlacemarkExtensions.GetEscapedAddress`. | | `Microsoft.Maui.Devices.Sensors.AccelerometerQueue` | `internal` | Shake detection window. | `TizenAccelerometerQueue`. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index c77fa043..a067b52d 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -217,7 +217,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=195 + ESSENTIALS_TESTS_MINIMUM=196 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs index 0c1ba35b..ffcfc169 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs @@ -1,6 +1,8 @@ using System; +using System.Reflection; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Media; using Microsoft.Maui.Platforms.Tizen.Essentials; using Xunit; @@ -119,6 +121,42 @@ public void TextToSpeechLocalesSurfaceTheMauiApiGap() Assert.Contains("Locale", exception.Message, StringComparison.Ordinal); } + /// + /// Tripwire for the upstream MAUI fix that would let this backend implement + /// properly. + /// + /// + /// + /// When this test fails, that is good news: delete it and implement the API. + /// + /// + /// Microsoft.Maui.Media.Locale currently has only an internal constructor, so no + /// assembly outside Microsoft.Maui.Essentials can construct the values + /// is required to return. That is why + /// throws instead of returning an empty + /// sequence a caller could not distinguish from "this device supports no voices". + /// + /// + /// Asserting the gap rather than re-checking it by hand on every MAUI package bump means the + /// moment a constructor becomes public, this fails and says exactly what to do next. Verified + /// still closed against Microsoft.Maui.Essentials 11.0.0-preview.7.26426.4. + /// + /// + [Fact] + public void MauiLocaleStillExposesNoPublicConstructor() + { + var constructors = typeof(Locale).GetConstructors( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + + Assert.True( + constructors.Length == 0, + $"Microsoft.Maui.Media.Locale now exposes {constructors.Length} public constructor(s). " + + $"The blocking API gap is closed: implement {nameof(TizenTextToSpeech)}." + + $"{nameof(ITextToSpeech.GetLocalesAsync)} properly, drop the " + + $"{nameof(TizenTextToSpeech.GetSupportedVoiceLanguagesAsync)} workaround from the " + + "coverage matrix, and delete this test."); + } + [Fact] public void UnsupportedMessagesNameTheCapabilityAndTheReason() { From 420cc58130d525ebf3227f7bb337f9d25f119845 Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 18:58:07 -0400 Subject: [PATCH 05/21] Address Essentials review: permission truthfulness, DI bridge, and native lifetimes MERGE BLOCKER - permission map no longer reports Granted for gated capabilities. Every built-in Permissions.* type previously mapped to either a privilege list or an EMPTY list, and an empty list meant Granted. So Bluetooth, Calendar, Media, Photos, Phone, PostNotifications, Sensors, Sms and Speech - all of which Tizen genuinely gates - reported Granted without checking anything. Mappings are now one of three explicit kinds: Requires Tizen gates it; privacy privileges also need runtime consent Ungated Tizen genuinely requires no privilege (Battery alone) Unsupported no Tizen equivalent; checking or requesting throws Collapsing the last two into "empty list" is exactly what produced the bug, so they are now distinct types rather than distinct comments. Privileges were read from the privilege annotations in the TizenFX API13 XML documentation rather than from memory. That also caught a second defect: Camera and Microphone were marked isRuntime: false, so resolution skipped PrivacyPrivilegeManager entirely and returned Granted for a capability the user may have denied. A test now asserts every privilege in Tizen's documented privacy set carries isRuntime: true. Permissions.Maps drops http://tizen.org/privilege/mapservice: with Tizen.Maps removed at API15 it gates nothing, so requiring applications to declare it was asking for permission for a dead capability. CORRECTNESS * AddTizenEssentials(MauiAppBuilder) now calls ConfigureEssentials(), which installs MAUI's Essentials initializer. MauiApp.CreateBuilder(useDefaults: true) installs it through the INTERNAL UseEssentials(); nothing installs it when defaults are skipped, so registering services alone left Battery.Default resolving a lazy platform default while DI held the real Tizen service - two live instances and a silently wrong static API. Facade identity is now asserted under useDefaults true AND false. * The facade bridge test no longer declares its expected set by hand. That was a tautology - same author on both sides - and would have passed if MAUI bridged nothing. It now decodes the IL of MAUI's own bridge methods and collects the contracts they actually resolve. * Screenshot: Size2D, Size and PixelBuffer are native handles and were all leaked; they are now disposed. RGBX/BGRX are opaque padding formats, not alpha - BGRX maps to Bgrx8888 and RGBX is converted to opaque RGBA rather than letting driver padding become transparency. Capture.Finished is the only completion signal, so the wait is now bounded instead of hanging and leaking the handle forever when it never arrives. * Connectivity.ConnectionProfiles is queried synchronously per read from ConnectionManager's per-transport state. It was populated only by the refresh started when the first ConnectivityChanged handler was added, so simply asking the question always returned empty. * Battery reads Tizen's own power source (None/Ac/Usb/Wireless) instead of inferring USB from the charging flag, and distinguishes Full and NotCharging from Discharging. * SecureStorage namespaces its aliases. The key manager alias space is shared with certificates and keys, so raw keys risked collision - and RemoveAll deleted every alias the application could see, destroying unrelated secrets. It now removes only aliases this API created. * Preferences escapes shared-name and key components before joining. With plain concatenation, ("a", "b~c") and ("a~b", "c") both produced "a~b~c", so two logical entries shared one physical entry and Clear("a") deleted the unrelated "a~b" store. Default-store keys stay unprefixed for compatibility with existing data. * Sensor Start/Stop are transactional. A throwing Start previously left DataUpdated attached, so the next Start double-subscribed and every reading was raised twice. Accelerometer is consolidated onto TizenSensorBase, which is where it should have been. * TTS initialization is serialized behind a semaphore and cached as one task. Concurrent callers each constructed a TtsClient; the loser's was overwritten and leaked with a live native handle. Prepare failures now dispose and reset so a retry works. Cancellation is re-checked after acquiring the speak lock and again before Play, so a call cancelled while queued cannot start speech. * Contacts.GetAllAsync requests runtime contact.read consent rather than only checking declaration, and materialises results before disposing the native cursor instead of handing back a lazy sequence over it. * Launcher CanOpenAsync/TryOpenAsync query matched application ids, so TryOpenAsync returns false instead of throwing when nothing handles the URI - which is the entire point of a Try method. Tests 196 -> 283; CI floor raised to match. PublicAPI baseline regenerated (0 entries outside this package's namespaces). Coverage matrix updated with the permission model and per-service notes. Verified: eng/build-workload-free.sh green from a clean tree under CI semantics, including both Essentials lanes with the PublicAPI analyzer. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/tizen-essentials-service-coverage.md | 42 ++- eng/build-workload-free.sh | 2 +- .../Accelerometer/TizenAccelerometer.cs | 111 +++---- .../Battery/TizenBattery.cs | 54 +++- .../Connectivity/TizenConnectivity.cs | 96 +++--- .../Contacts/TizenContacts.cs | 40 ++- ...TizenEssentialsMauiAppBuilderExtensions.cs | 11 + .../Launcher/TizenLauncher.cs | 65 +++- .../Permissions/TizenPermissions.cs | 306 +++++++++++++----- .../Preferences/TizenPreferences.cs | 33 +- .../net-tizen/PublicAPI.Unshipped.txt | 25 +- .../Screenshot/TizenScreenshot.cs | 97 +++++- .../SecureStorage/TizenSecureStorage.cs | 89 ++++- .../TextToSpeech/TizenTextToSpeech.cs | 164 +++++++--- .../Types/TizenSensorBase.cs | 123 +++++-- .../Types/TizenStorageKeyEncoding.cs | 93 ++++++ .../FacadeAndMainThreadOwnershipTests.cs | 215 ++++++++++-- .../FacadeBridgeIntegrationTests.cs | 187 +++++++++++ .../TizenPermissionsTests.cs | 243 +++++++++++--- .../TizenServiceBehaviorTests.cs | 285 ++++++++++++++++ .../TizenTranslationTests.cs | 18 +- 21 files changed, 1895 insertions(+), 404 deletions(-) create mode 100644 src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index fecf33c8..bde7ff4c 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -33,12 +33,12 @@ Profile column values are the Tizen device profiles on which the service is usab | `IAppInfo` | `TizenAppInfo` | Partial | All | `RequestedTheme` is `Unspecified` and `RequestedLayoutDirection` is `LeftToRight`: Tizen exposes neither to applications. | | `IAppleSignInAuthenticator` | `TizenAppleSignInAuthenticator` | Unsupported | – | Native Sign in with Apple is Apple-platform only. | | `IBarometer` | `TizenBarometer` | Implemented | All | `Tizen.Sensor.PressureSensor`. | -| `IBattery` | `TizenBattery` | Partial | All | `EnergySaverStatus` / `EnergySaverStatusChanged` throw: Tizen exposes no application-visible power saving state. | +| `IBattery` | `TizenBattery` | Partial | All | Power source read from Tizen's own reading (`None`/`Ac`/`Usb`/`Wireless`); state distinguishes `Full` and `NotCharging`. `EnergySaverStatus` / `EnergySaverStatusChanged` throw: Tizen exposes no application-visible power saving state. | | `IBrowser` | `TizenBrowser` | Partial | All | Always opens the system browser: Tizen has no in-app browser, so `BrowserLaunchMode` cannot be honoured. | | `IClipboard` | `TizenClipboard` | Unsupported | – | Tizen scopes copy/paste to the focused NUI/EFL window selection buffer; there is no headless clipboard service. | | `ICompass` | `TizenCompass` | Implemented | All | Azimuth from `Tizen.Sensor.OrientationSensor`. `applyLowPassFilter` has no extra effect (Tizen already fuses and filters). | -| `IConnectivity` | `TizenConnectivity` | Implemented | All | `Tizen.Network.Connection`. Requires `network.get` + `internet` privileges. | -| `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. Requires `contact.read`. | +| `IConnectivity` | `TizenConnectivity` | Implemented | All | `Tizen.Network.Connection`. `ConnectionProfiles` is queried synchronously per read, so it works without subscribing to `ConnectivityChanged`. Requires `network.get` + `internet`. | +| `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. `GetAllAsync` requests runtime `contact.read` consent and materialises the result before disposing the native cursor. | | `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | | `IDeviceInfo` | `TizenDeviceInfo` | Implemented | All | System / feature information keys. | | `IEmail` | `TizenEmail` | Partial | Mobile | Attachments are rejected: the Tizen `compose` AppControl accepts no attachment payload. Gated on the `email` feature key. | @@ -49,21 +49,21 @@ Profile column values are the Tizen device profiles on which the service is usab | `IGeolocation` | `TizenGeolocation` | Partial | All | One-shot `GetLocationAsync` works. `StartListeningForegroundAsync` / `StopListeningForeground` throw. | | `IGyroscope` | `TizenGyroscope` | Implemented | All | `Tizen.Sensor.Gyroscope`. | | `IHapticFeedback` | `TizenHapticFeedback` | Implemented | Mobile, Wearable | `Tizen.System.Feedback`. Unsupported patterns throw instead of silently doing nothing. | -| `ILauncher` | `TizenLauncher` | Implemented | All | AppControl launch requests, with scheme-based operation selection. | +| `ILauncher` | `TizenLauncher` | Implemented | All | AppControl launch requests with scheme-based operation selection. `CanOpenAsync`/`TryOpenAsync` query matched application ids, so `TryOpenAsync` returns `false` instead of throwing when nothing handles the URI. | | `IMagnetometer` | `TizenMagnetometer` | Implemented | All | `Tizen.Sensor.Magnetometer`. | | `IMap` | `TizenMap` | Partial | All | `geo:` AppControl. `MapLaunchOptions.NavigationMode` and the launch name cannot be honoured. | | `IMediaPicker` | `TizenMediaPicker` | Implemented | Mobile | Picking delegates to `TizenFilePicker`; capture uses the `image_capture` / `video_capture` AppControls. | | `IOrientationSensor` | `TizenOrientationSensor` | Implemented | All | `Tizen.Sensor.RotationVectorSensor`. | | `IPasskeys` | `TizenPasskeys` | Unsupported | – | Tizen ships FIDO UAF, not a WebAuthn / CTAP2 credential manager. `IsSupported` is `false`. | -| `IPermissions` | `TizenPermissions` | Implemented | All | Maps every built-in `Permissions.*` type to its Tizen privileges; runtime privileges go through `PrivacyPrivilegeManager`. | +| `IPermissions` | `TizenPermissions` | Partial | All | Maps every built-in `Permissions.*` type to verified Tizen privileges, with privacy privileges resolved through `PrivacyPrivilegeManager`. `Permissions.Maps` and `Permissions.Reminders` have no Tizen equivalent and throw rather than reporting `Granted`. | | `IPhoneDialer` | `TizenPhoneDialer` | Implemented | Mobile | `tel:` AppControl, gated on the `contact` feature key. | -| `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with a `{sharedName}~{key}` prefix. | -| `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders. Also implements `IViewScreenshot`. | -| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager (`Tizen.Security.SecureRepository.DataManager`). | +| `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with an **escaped** `{sharedName}~{key}` prefix so distinct stores cannot collide. Default-store keys stay unprefixed for compatibility. | +| `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders; native handles disposed, RGBX/BGRX treated as opaque, and a bounded wait for `Capture.Finished`. Also implements `IViewScreenshot`. | +| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. Aliases are stored under a private prefix, so `RemoveAll` deletes only entries this API created rather than every alias the app can see. | | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | | `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | -| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | +| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; initialization is serialized and cancellation re-checked before playback starts. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | | `IVibration` | `TizenVibration` | Implemented | Mobile, Wearable | `Tizen.System.Vibrator`; requires the `haptic` privilege. | | `IWebAuthenticator` | `TizenWebAuthenticator` | Unsupported | – | Tizen has no callback URI registration that returns an external browser response to the app. | @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (196 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (283 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | @@ -103,6 +103,28 @@ over. | `IActivityStateManager` | Android only. | | `IWindowStateManager` | Windows / Apple only; MAUI does not bridge it elsewhere. | +## Permission mapping + +Every built-in `Permissions.*` type maps to exactly one of three explicit kinds. The distinction +matters: collapsing "Tizen does not gate this" and "Tizen cannot do this" into a single empty +privilege list makes both report `Granted`, telling an application to proceed with a capability the +platform will never provide. + +| Kind | Meaning | Members | +| --- | --- | --- | +| `Requires` | Tizen gates the capability. Privacy privileges additionally need runtime consent via `PrivacyPrivilegeManager`. | Bluetooth, CalendarRead/Write, Camera, ContactsRead/Write, Flashlight, LaunchApp, LocationAlways/WhenInUse, Media, Microphone, NearbyWifiDevices, NetworkState, Phone, Photos, PhotosAddOnly, PostNotifications, Sensors, Sms, Speech, StorageRead/Write, Vibrate | +| `Ungated` | Tizen genuinely requires no privilege. An affirmative claim, not a missing mapping. | Battery | +| `Unsupported` | No Tizen equivalent; checking or requesting throws. | Maps, Reminders | + +Privileges are taken from the privilege annotations in the TizenFX API13 XML documentation rather +than from memory, and the `isRuntime` flag is asserted against the documented privacy-privilege set +by `MarksEveryPrivacyPrivilegeAsRuntime`. `Camera` and `Microphone` were previously marked +non-runtime, which skipped the consent check entirely and reported `Granted` on a denied capability. + +`Permissions.Maps` no longer declares `http://tizen.org/privilege/mapservice`: with `Tizen.Maps` +removed at API15 that privilege gates nothing, so requiring applications to declare it was asking +for a permission for a dead capability. + ## Tizen API surface changes found while porting | Tizen API | Status on API15 | Impact | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index a067b52d..44360480 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -217,7 +217,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=196 + ESSENTIALS_TESTS_MINIMUM=283 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs index 875309c7..eef54691 100644 --- a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs +++ b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs @@ -9,14 +9,18 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// /// Tizen implementation of , backed by Tizen.Sensor.Accelerometer. /// - public sealed class TizenAccelerometer : IAccelerometer + /// + /// Consolidated onto so it shares the transactional + /// start/stop handling with every other sensor. It previously duplicated that logic and, in + /// doing so, missed the subscription rollback on a failed start. + /// + public sealed class TizenAccelerometer : TizenSensorBase, IAccelerometer { const double AccelerationThreshold = 169; const double Gravity = 9.81; readonly TizenAccelerometerQueue _queue = new(); - - bool _useSyncContext; + readonly object _queueLocker = new(); /// public event EventHandler? ReadingChanged; @@ -25,75 +29,42 @@ public sealed class TizenAccelerometer : IAccelerometer public event EventHandler? ShakeDetected; /// - public bool IsSupported => TizenAccelerometerSensor.IsSupported; + public override bool IsSupported => TizenAccelerometerSensor.IsSupported; /// - public bool IsMonitoring { get; private set; } + protected override string SensorName => nameof(IAccelerometer); - static TizenAccelerometerSensor DefaultSensor => + /// + protected override TizenAccelerometerSensor Sensor => (TizenAccelerometerSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Accelerometer); /// - public void Start(SensorSpeed sensorSpeed) - { - if (!IsSupported) - throw TizenEssentialsSupport.NotSupported($"{nameof(IAccelerometer)}.{nameof(Start)}", "This device has no accelerometer."); - - if (IsMonitoring) - throw new InvalidOperationException("Accelerometer has already been started."); - - IsMonitoring = true; - _useSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; - - try - { - var sensor = DefaultSensor; - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += OnDataUpdated; - sensor.Start(); - } - catch - { - IsMonitoring = false; - throw; - } - } + protected override void Subscribe(TizenAccelerometerSensor sensor) => sensor.DataUpdated += OnDataUpdated; /// - public void Stop() - { - if (!IsSupported) - throw TizenEssentialsSupport.NotSupported($"{nameof(IAccelerometer)}.{nameof(Stop)}", "This device has no accelerometer."); + protected override void Unsubscribe(TizenAccelerometerSensor sensor) => sensor.DataUpdated -= OnDataUpdated; - if (!IsMonitoring) - return; + /// + /// + /// The shake window is per-session. Carrying samples across a stop/start would let readings + /// from before the gap combine with fresh ones and report a shake that never happened. + /// + protected override void OnStarted() => ClearShakeWindow(); - IsMonitoring = false; + /// + protected override void OnStopped() => ClearShakeWindow(); - try - { - var sensor = DefaultSensor; - sensor.DataUpdated -= OnDataUpdated; - sensor.Stop(); - } - catch - { - IsMonitoring = true; - throw; - } + void ClearShakeWindow() + { + lock (_queueLocker) + _queue.Clear(); } - void OnDataUpdated(object? sender, global::Tizen.Sensor.AccelerometerDataUpdatedEventArgs e) => - RaiseReadingChanged(new AccelerometerData(e.X, e.Y, e.Z)); - - void RaiseReadingChanged(AccelerometerData reading) + void OnDataUpdated(object? sender, global::Tizen.Sensor.AccelerometerDataUpdatedEventArgs e) { - var args = new AccelerometerChangedEventArgs(reading); + var reading = new AccelerometerData(e.X, e.Y, e.Z); - if (_useSyncContext) - MainThread.BeginInvokeOnMainThread(() => ReadingChanged?.Invoke(this, args)); - else - ReadingChanged?.Invoke(this, args); + Raise(ReadingChanged, new AccelerometerChangedEventArgs(reading)); if (ShakeDetected is not null) ProcessShakeEvent(reading.Acceleration); @@ -107,19 +78,31 @@ void ProcessShakeEvent(Vector3 acceleration) var y = acceleration.Y * Gravity; var z = acceleration.Z * Gravity; - _queue.Add(now, (x * x) + (y * y) + (z * z) > AccelerationThreshold); + bool shaking; + + // The native sensor may deliver readings concurrently with a Stop() clearing the window. + lock (_queueLocker) + { + _queue.Add(now, (x * x) + (y * y) + (z * z) > AccelerationThreshold); + + shaking = _queue.IsShaking; - if (!_queue.IsShaking) + if (shaking) + _queue.Clear(); + } + + if (!shaking) return; - _queue.Clear(); + var handler = ShakeDetected; - var args = EventArgs.Empty; + if (handler is null) + return; - if (_useSyncContext) - MainThread.BeginInvokeOnMainThread(() => ShakeDetected?.Invoke(this, args)); + if (UseSyncContext) + MainThread.BeginInvokeOnMainThread(() => handler.Invoke(this, EventArgs.Empty)); else - ShakeDetected?.Invoke(this, args); + handler.Invoke(this, EventArgs.Empty); } } } diff --git a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs index 4c08ffa4..79ea6b19 100644 --- a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs +++ b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs @@ -2,6 +2,7 @@ using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Devices; using TizenBatteryInfo = Tizen.System.Battery; +using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; namespace Microsoft.Maui.Platforms.Tizen.Essentials { @@ -9,7 +10,7 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// Tizen implementation of , backed by Tizen.System.Battery. /// /// - /// Tizen has no power-saving-mode query that is available to applications, so + /// Tizen has no power-saving-mode query available to applications, so /// and throw rather than /// reporting , which would be /// indistinguishable from a real "power saving is disabled" answer. @@ -28,12 +29,43 @@ public sealed class TizenBattery : IBattery public double ChargeLevel => (double)TizenBatteryInfo.Percent / 100; /// + /// + /// Derived from the charging flag, the charge percentage and the connected power source, so + /// that a device sitting on a charger at 100% reports and a + /// device plugged in but not drawing charge reports + /// instead of both collapsing into . + /// public BatteryState State => - TizenBatteryInfo.IsCharging ? BatteryState.Charging : BatteryState.Discharging; + MapState(TizenBatteryInfo.IsCharging, TizenBatteryInfo.Percent, TizenBatteryInfo.PowerSource); /// - public BatteryPowerSource PowerSource => - TizenBatteryInfo.IsCharging ? BatteryPowerSource.Usb : BatteryPowerSource.Battery; + /// Read from Tizen's own power-source reading rather than inferred from charging state. + public BatteryPowerSource PowerSource => MapPowerSource(TizenBatteryInfo.PowerSource); + + internal static BatteryState MapState(bool isCharging, int percent, TizenBatteryPowerSource source) + { + var pluggedIn = source != TizenBatteryPowerSource.None; + + if (percent >= 100 && pluggedIn) + return BatteryState.Full; + + if (isCharging) + return BatteryState.Charging; + + // Connected to a power source but not charging is a distinct state, and the one users + // notice: a device on a weak charger reports it while the level slowly falls. + return pluggedIn ? BatteryState.NotCharging : BatteryState.Discharging; + } + + internal static BatteryPowerSource MapPowerSource(TizenBatteryPowerSource source) => + source switch + { + TizenBatteryPowerSource.Ac => BatteryPowerSource.AC, + TizenBatteryPowerSource.Usb => BatteryPowerSource.Usb, + TizenBatteryPowerSource.Wireless => BatteryPowerSource.Wireless, + TizenBatteryPowerSource.None => BatteryPowerSource.Battery, + _ => BatteryPowerSource.Unknown, + }; /// /// Always thrown. @@ -94,11 +126,19 @@ void StopListeners() _listening = false; } - void OnChanged(object? sender, object e) => + void OnChanged(object? sender, object e) + { + // Snapshot on the native callback thread, then raise on the main thread. + var args = new BatteryInfoChangedEventArgs(ChargeLevel, State, PowerSource); + MainThread.BeginInvokeOnMainThread(() => { - var args = new BatteryInfoChangedEventArgs(ChargeLevel, State, PowerSource); - _batteryInfoChanged?.Invoke(this, args); + EventHandler? handler; + lock (_locker) + handler = _batteryInfoChanged; + + handler?.Invoke(this, args); }); + } } } diff --git a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs index 49a777c6..f1df264d 100644 --- a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs +++ b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs @@ -2,12 +2,11 @@ using System.Collections.Generic; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Networking; +using TizenCellularState = Tizen.Network.Connection.CellularState; using TizenConnectionManager = Tizen.Network.Connection.ConnectionManager; -using TizenConnectionProfileManager = Tizen.Network.Connection.ConnectionProfileManager; -using TizenConnectionProfileType = Tizen.Network.Connection.ConnectionProfileType; +using TizenConnectionState = Tizen.Network.Connection.ConnectionState; using TizenConnectionType = Tizen.Network.Connection.ConnectionType; using TizenConnectionTypeEventArgs = Tizen.Network.Connection.ConnectionTypeEventArgs; -using TizenProfileListType = Tizen.Network.Connection.ProfileListType; namespace Microsoft.Maui.Platforms.Tizen.Essentials { @@ -18,7 +17,6 @@ public sealed class TizenConnectivity : IConnectivity { readonly object _locker = new(); - List _profiles = new(); EventHandler? _connectivityChanged; bool _listening; @@ -33,22 +31,66 @@ public NetworkAccess NetworkAccess { TizenConnectionType.WiFi or TizenConnectionType.Cellular or - TizenConnectionType.Ethernet => NetworkAccess.Internet, + TizenConnectionType.Ethernet or + TizenConnectionType.Bluetooth => NetworkAccess.Internet, _ => NetworkAccess.None, }; } } /// + /// + /// Queried on every read from ConnectionManager's per-transport state properties. + /// + /// An earlier implementation populated this list only from the profile-list refresh started + /// when gained its first subscriber, so an application + /// that merely asked the question - the common case - always saw an empty sequence and had + /// no way to tell that apart from "there are no connections". Reading the state properties + /// requires no subscription, no asynchronous work and no cached state. + /// + /// public IEnumerable ConnectionProfiles { get { - lock (_locker) - return _profiles.ToArray(); + TizenPermissions.EnsureDeclared(); + + return GetConnectionProfiles(); } } + internal static List GetConnectionProfiles() + { + var profiles = new List(4); + + if (IsConnected(TizenConnectionManager.WiFiState)) + profiles.Add(ConnectionProfile.WiFi); + + if (TizenConnectionManager.CellularState == TizenCellularState.Connected) + profiles.Add(ConnectionProfile.Cellular); + + if (IsConnected(TizenConnectionManager.EthernetState)) + profiles.Add(ConnectionProfile.Ethernet); + + if (IsConnected(TizenConnectionManager.BluetoothState)) + profiles.Add(ConnectionProfile.Bluetooth); + + return profiles; + } + + internal static bool IsConnected(TizenConnectionState state) => + state == TizenConnectionState.Connected; + + internal static ConnectionProfile? MapProfileType(TizenConnectionType type) => + type switch + { + TizenConnectionType.Bluetooth => ConnectionProfile.Bluetooth, + TizenConnectionType.Cellular => ConnectionProfile.Cellular, + TizenConnectionType.Ethernet => ConnectionProfile.Ethernet, + TizenConnectionType.WiFi => ConnectionProfile.WiFi, + _ => null, + }; + /// public event EventHandler ConnectivityChanged { @@ -82,8 +124,6 @@ void StartListeners() TizenConnectionManager.ConnectionTypeChanged += OnConnectionTypeChanged; _listening = true; - - _ = RefreshProfilesAsync(raise: false); } void StopListeners() @@ -95,39 +135,19 @@ void StopListeners() _listening = false; } - void OnConnectionTypeChanged(object? sender, TizenConnectionTypeEventArgs e) => - _ = RefreshProfilesAsync(raise: true); - - async System.Threading.Tasks.Task RefreshProfilesAsync(bool raise) + void OnConnectionTypeChanged(object? sender, TizenConnectionTypeEventArgs e) { - var list = await TizenConnectionProfileManager.GetProfileListAsync(TizenProfileListType.Connected).ConfigureAwait(false); + // Snapshot on the native callback thread, then raise on the main thread. + var args = new ConnectivityChangedEventArgs(NetworkAccess, GetConnectionProfiles()); - var profiles = new List(); - foreach (var result in list) + MainThread.BeginInvokeOnMainThread(() => { - var mapped = MapProfileType(result.Type); - if (mapped is { } profile) - profiles.Add(profile); - } - - lock (_locker) - _profiles = profiles; - - if (!raise) - return; + EventHandler? handler; + lock (_locker) + handler = _connectivityChanged; - var args = new ConnectivityChangedEventArgs(NetworkAccess, profiles); - MainThread.BeginInvokeOnMainThread(() => _connectivityChanged?.Invoke(this, args)); + handler?.Invoke(this, args); + }); } - - internal static ConnectionProfile? MapProfileType(TizenConnectionProfileType type) => - type switch - { - TizenConnectionProfileType.Bt => ConnectionProfile.Bluetooth, - TizenConnectionProfileType.Cellular => ConnectionProfile.Cellular, - TizenConnectionProfileType.Ethernet => ConnectionProfile.Ethernet, - TizenConnectionProfileType.WiFi => ConnectionProfile.WiFi, - _ => null, - }; } } diff --git a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs index b05a9079..30e89591 100644 --- a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs +++ b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs @@ -66,27 +66,45 @@ public sealed class TizenContacts : IContacts } /// - public Task> GetAllAsync(CancellationToken cancellationToken = default) + /// + /// + /// Requests the runtime contact.read consent before reading, not merely checking that + /// the privilege is declared. Declaration alone does not grant a Tizen privacy privilege, so + /// the previous implementation could reach the database call and fail there instead of + /// prompting. + /// + /// + /// The result is materialised eagerly and the native ContactsList disposed before + /// returning. Deferred iteration handed the caller a lazy sequence over an undisposed native + /// cursor whose lifetime then depended on whether - and when - the caller finished + /// enumerating. + /// + /// + public async Task> GetAllAsync(CancellationToken cancellationToken = default) { - TizenPermissions.EnsureDeclared(); + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - var contactsList = Manager.Value.Database.GetAll(TizenContact.Uri, 0, 0); + var contacts = new List(); + + using var contactsList = Manager.Value.Database.GetAll(TizenContact.Uri, 0, 0); - return Task.FromResult(Enumerate()); + if (contactsList is null) + return contacts; - IEnumerable Enumerate() + for (var i = 0; i < contactsList.Count; i++) { - for (var i = 0; i < contactsList?.Count; i++) - { - cancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); - yield return ToContact(contactsList.GetCurrentRecord()); + using var record = contactsList.GetCurrentRecord(); + if (record is not null) + contacts.Add(ToContact(record)); - contactsList.MoveNext(); - } + contactsList.MoveNext(); } + + return contacts; } static Contact ToContact(ContactsRecord contactsRecord) diff --git a/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs b/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs index 1c234c56..3833879d 100644 --- a/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs +++ b/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs @@ -58,6 +58,17 @@ public static MauiAppBuilder AddTizenEssentials(this MauiAppBuilder builder) { ArgumentNullException.ThrowIfNull(builder); + // Installing the Essentials initializer is what actually makes the registrations below + // reach the static facades. MauiApp.CreateBuilder(useDefaults: true) installs it via the + // internal UseEssentials(); with useDefaults: false nothing does, so registering the + // services alone would leave Battery.Default and friends resolving lazy platform + // defaults while DI held the real Tizen implementations - two live instances, and the + // static API silently wrong. + // + // ConfigureEssentials is the public entry point onto the same initializer and is + // idempotent (it TryAdds), so calling it here is safe alongside useDefaults: true. + builder.ConfigureEssentials(); + AddTizenEssentials(builder.Services); return builder; diff --git a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs index a5997ce6..3c76ae79 100644 --- a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs +++ b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Storage; @@ -13,11 +14,21 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials public sealed class TizenLauncher : ILauncher { /// + /// + /// Asks Tizen whether any installed application actually handles the URI, rather than only + /// checking that the string is well formed. The previous implementation returned + /// for any syntactically valid URI, so + /// would go on to call and throw when nothing could handle it - + /// which defeats the point of a Try method. + /// public Task CanOpenAsync(Uri uri) { ArgumentNullException.ThrowIfNull(uri); - return Task.FromResult(uri.IsWellFormedOriginalString()); + if (!uri.IsAbsoluteUri || !uri.IsWellFormedOriginalString()) + return Task.FromResult(false); + + return Task.FromResult(HasHandler(CreateAppControl(uri))); } /// @@ -27,13 +38,7 @@ public Task OpenAsync(Uri uri) TizenPermissions.EnsureDeclared(); - var appControl = new TizenAppControl - { - Operation = GetOperation(uri), - Uri = uri.AbsoluteUri, - }; - - TizenAppControl.SendLaunchRequest(appControl); + TizenAppControl.SendLaunchRequest(CreateAppControl(uri)); return Task.FromResult(true); } @@ -61,14 +66,48 @@ public Task OpenAsync(OpenFileRequest request) } /// - public async Task TryOpenAsync(Uri uri) + /// + /// Returns when nothing on the device handles the URI, rather than + /// letting the launch attempt throw. + /// + public Task TryOpenAsync(Uri uri) { - var canOpen = await CanOpenAsync(uri).ConfigureAwait(false); + ArgumentNullException.ThrowIfNull(uri); + + if (!uri.IsAbsoluteUri || !uri.IsWellFormedOriginalString()) + return Task.FromResult(false); + + TizenPermissions.EnsureDeclared(); + + var appControl = CreateAppControl(uri); - if (canOpen) - await OpenAsync(uri).ConfigureAwait(false); + if (!HasHandler(appControl)) + return Task.FromResult(false); - return canOpen; + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(true); + } + + static TizenAppControl CreateAppControl(Uri uri) => + new() + { + Operation = GetOperation(uri), + Uri = uri.AbsoluteUri, + }; + + static bool HasHandler(TizenAppControl appControl) + { + try + { + return TizenAppControl.GetMatchedApplicationIds(appControl).Any(); + } + catch (Exception) + { + // Tizen throws rather than returning an empty set when nothing matches the control. + // For a capability probe that is the same answer as "no handler". + return false; + } } static string GetOperation(Uri uri) diff --git a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs index 6d440870..99c920d2 100644 --- a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs +++ b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs @@ -23,6 +23,84 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public readonly record struct TizenPrivilege(string Privilege, bool IsRuntime); + /// + /// How a MAUI permission relates to the Tizen privilege model. + /// + public enum TizenPermissionKind + { + /// + /// Tizen gates the capability. lists the + /// privileges that must be declared, and any privacy privileges among them must also be + /// granted by the user at runtime. + /// + Requires, + + /// + /// Tizen genuinely does not gate the capability, so it is always available. This is an + /// affirmative statement about the platform, not an absence of mapping. + /// + Ungated, + + /// + /// Tizen has no equivalent capability, so the permission cannot meaningfully be checked or + /// requested. Callers get rather than a status. + /// + Unsupported, + } + + /// + /// The Tizen meaning of a single MAUI permission. + /// + /// + /// The three cases are kept distinct on purpose. Collapsing "Tizen does not gate this" and + /// "Tizen cannot do this at all" into a single empty privilege list makes both report + /// , which tells an application it may proceed with a + /// capability the platform will never provide. + /// + public readonly record struct TizenPermissionMapping + { + TizenPermissionMapping(TizenPermissionKind kind, TizenPrivilege[] privileges, string? reason) + { + Kind = kind; + Privileges = privileges; + Reason = reason; + } + + /// Gets how Tizen treats this permission. + public TizenPermissionKind Kind { get; } + + /// Gets the required privileges. Empty unless is . + public TizenPrivilege[] Privileges { get; } + + /// Gets why the permission is ungated or unsupported, for diagnostics. + public string? Reason { get; } + + /// Creates a mapping for a capability Tizen gates behind privileges. + /// The required privileges. + /// The mapping. + public static TizenPermissionMapping Requires(params TizenPrivilege[] privileges) + { + ArgumentNullException.ThrowIfNull(privileges); + + if (privileges.Length == 0) + throw new ArgumentException("A 'Requires' mapping must list at least one privilege.", nameof(privileges)); + + return new TizenPermissionMapping(TizenPermissionKind.Requires, privileges, null); + } + + /// Creates a mapping for a capability Tizen does not gate. + /// Why no privilege is required. + /// The mapping. + public static TizenPermissionMapping Ungated(string reason) => + new(TizenPermissionKind.Ungated, Array.Empty(), reason); + + /// Creates a mapping for a capability Tizen does not have. + /// Why Tizen cannot provide the capability. + /// The mapping. + public static TizenPermissionMapping Unsupported(string reason) => + new(TizenPermissionKind.Unsupported, Array.Empty(), reason); + } + /// /// Base class for user defined Tizen permissions. /// @@ -70,80 +148,127 @@ public override void EnsureDeclared() => /// public sealed class TizenPermissions : IPermissions { - internal static readonly IReadOnlyDictionary KnownPermissionPrivileges = - new Dictionary + internal static readonly IReadOnlyDictionary KnownPermissions = + new Dictionary { - // Declared with no privileges: Tizen requires nothing for these, so they resolve as granted. - [typeof(Permissions.Battery)] = Array.Empty(), - [typeof(Permissions.Bluetooth)] = Array.Empty(), - [typeof(Permissions.CalendarRead)] = Array.Empty(), - [typeof(Permissions.CalendarWrite)] = Array.Empty(), - [typeof(Permissions.Media)] = Array.Empty(), - [typeof(Permissions.NearbyWifiDevices)] = Array.Empty(), - [typeof(Permissions.Phone)] = Array.Empty(), - [typeof(Permissions.Photos)] = Array.Empty(), - [typeof(Permissions.PhotosAddOnly)] = Array.Empty(), - [typeof(Permissions.PostNotifications)] = Array.Empty(), - [typeof(Permissions.Reminders)] = Array.Empty(), - [typeof(Permissions.Sensors)] = Array.Empty(), - [typeof(Permissions.Sms)] = Array.Empty(), - [typeof(Permissions.Speech)] = Array.Empty(), - - [typeof(Permissions.Camera)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/camera", false), - }, - [typeof(Permissions.ContactsRead)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/contact.read", true), - }, - [typeof(Permissions.ContactsWrite)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/contact.write", true), - }, - [typeof(Permissions.Flashlight)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/led", false), - }, - [typeof(Permissions.LaunchApp)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/appmanager.launch", false), - }, - [typeof(Permissions.LocationWhenInUse)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/location", true), - }, - [typeof(Permissions.LocationAlways)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/location", true), - }, - [typeof(Permissions.Maps)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/internet", false), - new TizenPrivilege("http://tizen.org/privilege/mapservice", false), + // --------------------------------------------------------------------------- + // Genuinely ungated on Tizen. + // + // Reporting Granted here is a true statement, not a fallback: Tizen.System.Battery + // reads require no privilege at all. + // --------------------------------------------------------------------------- + [typeof(Permissions.Battery)] = TizenPermissionMapping.Ungated( + "Tizen.System.Battery requires no privilege."), + + // --------------------------------------------------------------------------- + // Declaration-only privileges. Present in tizen-manifest.xml is sufficient; + // Tizen does not prompt the user for these. + // --------------------------------------------------------------------------- + [typeof(Permissions.Bluetooth)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/bluetooth", false)), + + [typeof(Permissions.Flashlight)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/led", false)), + + [typeof(Permissions.LaunchApp)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/appmanager.launch", false)), + + // MAUI's NearbyWifiDevices models discovering nearby Wi-Fi devices. On Tizen that + // is Tizen.Network.WiFi scanning, which is gated by these two. + [typeof(Permissions.NearbyWifiDevices)] = TizenPermissionMapping.Requires( new TizenPrivilege("http://tizen.org/privilege/network.get", false), - }, - [typeof(Permissions.Microphone)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/recorder", false), - }, - [typeof(Permissions.NetworkState)] = new[] - { + new TizenPrivilege("http://tizen.org/privilege/network.profile", false)), + + [typeof(Permissions.NetworkState)] = TizenPermissionMapping.Requires( new TizenPrivilege("http://tizen.org/privilege/internet", false), - new TizenPrivilege("http://tizen.org/privilege/network.get", false), - }, - [typeof(Permissions.StorageRead)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/mediastorage", true), - }, - [typeof(Permissions.StorageWrite)] = new[] - { + new TizenPrivilege("http://tizen.org/privilege/network.get", false)), + + [typeof(Permissions.Phone)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/telephony", false)), + + [typeof(Permissions.PostNotifications)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/notification", false)), + + [typeof(Permissions.Vibrate)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/haptic", false)), + + // --------------------------------------------------------------------------- + // Tizen privacy privileges. Declaration is necessary but NOT sufficient - the + // user must also grant them at runtime, so these carry isRuntime: true and are + // resolved through PrivacyPrivilegeManager. + // --------------------------------------------------------------------------- + [typeof(Permissions.CalendarRead)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/calendar.read", true)), + + [typeof(Permissions.CalendarWrite)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/calendar.write", true)), + + [typeof(Permissions.Camera)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/camera", true)), + + [typeof(Permissions.ContactsRead)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/contact.read", true)), + + [typeof(Permissions.ContactsWrite)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/contact.write", true)), + + // Tizen draws no foreground/background distinction for location, so both MAUI + // location permissions resolve to the same privilege. LocationAlways therefore + // reports the state of the one consent Tizen actually has, rather than implying a + // background grant the platform never issued. + [typeof(Permissions.LocationWhenInUse)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/location", true)), + + [typeof(Permissions.LocationAlways)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/location", true)), + + [typeof(Permissions.Media)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true)), + + [typeof(Permissions.Microphone)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/recorder", true)), + + [typeof(Permissions.Photos)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true)), + + [typeof(Permissions.PhotosAddOnly)] = TizenPermissionMapping.Requires( new TizenPrivilege("http://tizen.org/privilege/mediastorage", true), - }, - [typeof(Permissions.Vibrate)] = new[] - { - new TizenPrivilege("http://tizen.org/privilege/haptic", false), - }, + new TizenPrivilege("http://tizen.org/privilege/content.write", false)), + + // MAUI's Permissions.Sensors models body sensors. On Tizen the body sensors + // (heart rate, pedometer, sleep monitor) are the ones behind healthinfo; the + // motion sensors this package exposes need no privilege. + [typeof(Permissions.Sensors)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/healthinfo", true)), + + // Reading messages is privacy gated. Composing an SMS through an AppControl is + // not - that path only needs appmanager.launch, which TizenSms declares itself. + [typeof(Permissions.Sms)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/message.read", true)), + + // Speech recognition on Tizen is Tizen.Uix.Stt, which is gated by recorder. + [typeof(Permissions.Speech)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/recorder", true)), + + [typeof(Permissions.StorageRead)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true)), + + [typeof(Permissions.StorageWrite)] = TizenPermissionMapping.Requires( + new TizenPrivilege("http://tizen.org/privilege/mediastorage", true)), + + // --------------------------------------------------------------------------- + // No Tizen equivalent. These throw rather than reporting Granted, because a + // caller cannot distinguish "granted" from "this platform silently ignored you". + // --------------------------------------------------------------------------- + [typeof(Permissions.Maps)] = TizenPermissionMapping.Unsupported( + "Tizen.Maps (MapService) was deprecated in TizenFX API11 and removed by API15, " + + "so the http://tizen.org/privilege/mapservice privilege no longer gates anything " + + "this platform can do."), + + [typeof(Permissions.Reminders)] = TizenPermissionMapping.Unsupported( + "Tizen has no reminders store. MAUI's Permissions.Reminders models the Apple " + + "Reminders database, which has no Tizen counterpart; the calendar permissions " + + "cover Tizen's calendar."), }; /// @@ -164,23 +289,32 @@ public bool ShouldShowRationale() static Task ResolveAsync(bool ask) where TPermission : Permissions.BasePermission, new() { - if (TryGetKnownPrivileges(typeof(TPermission), out var privileges)) - return CheckPrivilegesAsync(privileges, ask); + if (TryGetKnownMapping(typeof(TPermission), out var mapping)) + { + return mapping.Kind switch + { + TizenPermissionKind.Requires => CheckPrivilegesAsync(mapping.Privileges, ask), + TizenPermissionKind.Ungated => Task.FromResult(PermissionStatus.Granted), + _ => throw TizenEssentialsSupport.NotSupported( + $"{nameof(Permissions)}.{typeof(TPermission).Name}", + mapping.Reason ?? "Tizen has no equivalent capability."), + }; + } // Custom permission types own their behaviour (including TizenBasePlatformPermission). var permission = new TPermission(); return ask ? permission.RequestAsync() : permission.CheckStatusAsync(); } - internal static bool TryGetKnownPrivileges(Type permissionType, [NotNullWhen(true)] out TizenPrivilege[]? privileges) + internal static bool TryGetKnownMapping(Type permissionType, out TizenPermissionMapping mapping) { for (var type = permissionType; type is not null; type = type.BaseType) { - if (KnownPermissionPrivileges.TryGetValue(type, out privileges)) + if (KnownPermissions.TryGetValue(type, out mapping)) return true; } - privileges = null; + mapping = default; return false; } @@ -206,10 +340,26 @@ public static bool IsPrivilegeDeclared(string tizenPrivilege) public static void EnsureDeclared() where TPermission : Permissions.BasePermission, new() { - if (TryGetKnownPrivileges(typeof(TPermission), out var privileges)) - EnsureDeclared(privileges); - else + if (!TryGetKnownMapping(typeof(TPermission), out var mapping)) + { new TPermission().EnsureDeclared(); + return; + } + + switch (mapping.Kind) + { + case TizenPermissionKind.Requires: + EnsureDeclared(mapping.Privileges); + break; + + case TizenPermissionKind.Ungated: + break; + + default: + throw TizenEssentialsSupport.NotSupported( + $"{nameof(Permissions)}.{typeof(TPermission).Name}", + mapping.Reason ?? "Tizen has no equivalent capability."); + } } /// diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs index dc5fb8a1..9af4dc5b 100644 --- a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Linq; using Microsoft.Maui.Storage; using TizenPreference = Tizen.Applications.Preference; @@ -9,13 +10,12 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// Tizen implementation of , backed by Tizen.Applications.Preference. /// /// - /// Tizen has a single per-application preference store, so shared names are emulated with a - /// {sharedName}~{key} key prefix, matching the in-box dotnet/maui Tizen backend. + /// Tizen has a single flat per-application preference store, so shared names are emulated with a + /// key prefix. See for why the components are escaped + /// rather than simply concatenated. /// public sealed class TizenPreferences : IPreferences { - const string Separator = "~"; - static readonly object Locker = new(); /// @@ -41,6 +41,11 @@ public void Remove(string key, string? sharedName = null) } /// + /// + /// Clearing a shared name removes only that store's entries. Because the shared name is + /// escaped before being used as a prefix, clearing a cannot remove entries belonging + /// to a different shared name such as a~b. + /// public void Clear(string? sharedName = null) { lock (Locker) @@ -48,13 +53,13 @@ public void Clear(string? sharedName = null) if (string.IsNullOrEmpty(sharedName)) { TizenPreference.RemoveAll(); + return; } - else - { - var prefix = $"{sharedName}{Separator}"; - foreach (var key in TizenPreference.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) - TizenPreference.Remove(key); - } + + var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix(sharedName); + + foreach (var key in TizenPreference.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + TizenPreference.Remove(key); } } @@ -77,7 +82,7 @@ public void Set(string key, T value, string? sharedName = null) TizenPreference.Set(fullKey, dateTime.ToBinary()); break; case DateTimeOffset dateTimeOffset: - TizenPreference.Set(fullKey, dateTimeOffset.ToString("O", System.Globalization.CultureInfo.InvariantCulture)); + TizenPreference.Set(fullKey, dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); break; default: TizenPreference.Set(fullKey, value); @@ -106,8 +111,8 @@ public T Get(string key, T defaultValue, string? sharedName = null) var saved = TizenPreference.Get(fullKey); return DateTimeOffset.TryParse( saved, - System.Globalization.CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.RoundtripKind, + CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var parsed) ? (T)(object)parsed : defaultValue; @@ -118,6 +123,6 @@ public T Get(string key, T defaultValue, string? sharedName = null) } internal static string GetFullKey(string key, string? sharedName) => - string.IsNullOrEmpty(sharedName) ? key : $"{sharedName}{Separator}{key}"; + TizenStorageKeyEncoding.GetFullKey(key, sharedName); } } diff --git a/src/Maui.Tizen.Essentials/PublicAPI/net-tizen/PublicAPI.Unshipped.txt b/src/Maui.Tizen.Essentials/PublicAPI/net-tizen/PublicAPI.Unshipped.txt index 2dd79f0b..dc1844f9 100644 --- a/src/Maui.Tizen.Essentials/PublicAPI/net-tizen/PublicAPI.Unshipped.txt +++ b/src/Maui.Tizen.Essentials/PublicAPI/net-tizen/PublicAPI.Unshipped.txt @@ -12,12 +12,8 @@ const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.Pdf = "applic const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.VideoAll = "video/*" -> string! Microsoft.Maui.Hosting.TizenEssentialsMauiAppBuilderExtensions Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer -Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.IsMonitoring.get -> bool -Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.IsSupported.get -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.ReadingChanged -> System.EventHandler? Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.ShakeDetected -> System.EventHandler? -Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.Start(Microsoft.Maui.Devices.Sensors.SensorSpeed sensorSpeed) -> void -Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.Stop() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.TizenAccelerometer() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.AppActionActivated -> System.EventHandler? @@ -175,6 +171,15 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys.AssertAsync(Microsoft.Ma Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys.CreateAsync(Microsoft.Maui.Authentication.PasskeyCreationOptions! options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys.IsSupported.get -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys.TizenPasskeys() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind.Requires = 0 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind.Ungated = 1 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind.Unsupported = 2 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Kind.get -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionKind +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Privileges.get -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege[]! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Reason.get -> string? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.TizenPermissionMapping() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.CheckStatusAsync() -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.RequestAsync() -> System.Threading.Tasks.Task! @@ -247,6 +252,7 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenSms Microsoft.Maui.Platforms.Tizen.Essentials.TizenSms.ComposeAsync(Microsoft.Maui.ApplicationModel.Communication.SmsMessage? message) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenSms.IsComposeSupported.get -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenSms.TizenSms() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenStorageKeyEncoding Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel.Implemented = 0 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel.Partial = 1 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel @@ -269,6 +275,7 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenWebAuthenticator Microsoft.Maui.Platforms.Tizen.Essentials.TizenWebAuthenticator.AuthenticateAsync(Microsoft.Maui.Authentication.WebAuthenticatorOptions! webAuthenticatorOptions) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenWebAuthenticator.AuthenticateAsync(Microsoft.Maui.Authentication.WebAuthenticatorOptions! webAuthenticatorOptions, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenWebAuthenticator.TizenWebAuthenticator() -> void +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.IsSupported.get -> bool override Microsoft.Maui.Platforms.Tizen.Essentials.TizenBarometer.IsSupported.get -> bool override Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.CheckStatusAsync() -> System.Threading.Tasks.Task! override Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.EnsureDeclared() -> void @@ -290,6 +297,9 @@ static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.PngFileType.get static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.VideoFileType.get -> Microsoft.Maui.Storage.FilePickerFileType! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.GetContentType(string! extension) -> string! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.GetFullAppPackageFilePath(string! filename) -> string! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Requires(params Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege[]! privileges) -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Ungated(string! reason) -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping.Unsupported(string! reason) -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissionMapping static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.EnsureDeclared(System.Collections.Generic.IEnumerable! privileges) -> void static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.EnsureDeclared() -> void static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.EnsureGrantedAsync() -> System.Threading.Tasks.Task! @@ -297,13 +307,20 @@ static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.IsPrivilegeDec static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPlacemarkExtensions.GetEscapedAddress(this Microsoft.Maui.Devices.Sensors.Placemark! placemark) -> string! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPlatform.CurrentPackage.get -> Tizen.Applications.Package! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPlatform.ParseVersion(string? version) -> System.Version! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureTimeout.get -> System.TimeSpan +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureTimeout.set -> void static Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotExtensions.CaptureAsync(this Microsoft.Maui.Media.IScreenshot! screenshot, Tizen.NUI.BaseComponents.View! view) -> System.Threading.Tasks.Task! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotExtensions.CaptureAsync(this Microsoft.Maui.Media.IScreenshot! screenshot, Tizen.NUI.Window! window) -> System.Threading.Tasks.Task! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensors.GetDefaultSensor(Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType type) -> Tizen.Sensor.Sensor! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorSpeedExtensions.ToPlatform(this Microsoft.Maui.Devices.Sensors.SensorSpeed sensorSpeed) -> uint +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenStorageKeyEncoding.Encode(string! value) -> string! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenStorageKeyEncoding.GetFullKey(string! key, string? sharedName) -> string! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenStorageKeyEncoding.GetSharedNamePrefix(string! sharedName) -> string! static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation.CurrentProfile.get -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation.GetFeatureInfo(string! item) -> string? static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation.GetFeatureInfo(string! item) -> T? static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation.GetSystemInfo(string! item) -> string? static Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation.GetSystemInfo(string! item) -> T? virtual Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.RequiredPrivileges.get -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege[]! +virtual Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.OnStarted() -> void +virtual Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.OnStopped() -> void diff --git a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs index 3d4d0677..9ac8f6a8 100644 --- a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs +++ b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using Microsoft.Maui.Media; using Tizen.NUI; @@ -19,9 +20,11 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// backed by Tizen.NUI.Capture. /// /// + /// /// The in-box dotnet/maui Tizen backend left screenshot unimplemented (every member threw). - /// This implementation performs a real offscreen capture of the NUI window or view, then encodes - /// the resulting pixel buffer with Tizen.Multimedia.Util. + /// This performs a real offscreen capture of the NUI window or view, then encodes the resulting + /// pixel buffer with Tizen.Multimedia.Util. + /// /// /// IPlatformScreenshot is intentionally not implemented: in the neutral (non platform /// specific) Microsoft.Maui.Essentials assembly that interface declares no members, so it @@ -32,6 +35,18 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public sealed class TizenScreenshot : IScreenshot, IViewScreenshot { + /// + /// How long to wait for Capture.Finished before giving up. + /// + /// + /// Capture.Finished is the only signal that a capture completed. If the native side + /// never raises it - a destroyed window, a driver failure, a zero-sized surface accepted by + /// Tizen but never rendered - an un-timed wait would hang the caller forever and leak the + /// handle and its scratch file. Failing loudly after a bounded wait is + /// strictly better than an unkillable task. + /// + public static TimeSpan CaptureTimeout { get; set; } = TimeSpan.FromSeconds(10); + /// public bool IsCaptureSupported => true; @@ -48,8 +63,17 @@ public async Task CaptureAsync(TizenWindow window) { ArgumentNullException.ThrowIfNull(window); - var size = window.WindowSize; - return await CaptureCoreAsync(window.GetDefaultLayer(), new TizenNUISize(size.Width, size.Height, 0)).ConfigureAwait(false) + int width; + int height; + + // Size2D is a native handle, not a value type. + using (var size = window.WindowSize) + { + width = size.Width; + height = size.Height; + } + + return await CaptureCoreAsync(window.GetDefaultLayer(), width, height).ConfigureAwait(false) ?? throw new InvalidOperationException("Tizen reported a failed window capture."); } @@ -62,8 +86,16 @@ public async Task CaptureAsync(TizenWindow window) { ArgumentNullException.ThrowIfNull(view); - var size = view.Size2D; - return CaptureCoreAsync(view, new TizenNUISize(size.Width, size.Height, 0)); + int width; + int height; + + using (var size = view.Size2D) + { + width = size.Width; + height = size.Height; + } + + return CaptureCoreAsync(view, width, height); } /// @@ -78,9 +110,9 @@ public async Task CaptureAsync(TizenWindow window) async Task CaptureWindowAsync(TizenWindow window) => await CaptureAsync(window).ConfigureAwait(false); - static async Task CaptureCoreAsync(Container source, TizenNUISize size) + static async Task CaptureCoreAsync(Container source, int width, int height) { - if (size.Width <= 0 || size.Height <= 0) + if (width <= 0 || height <= 0) throw new InvalidOperationException("Cannot capture a screenshot of a zero-sized NUI container."); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -99,16 +131,27 @@ public async Task CaptureAsync(TizenWindow window) try { - capture.Start(source, size, scratchPath, Color.Transparent); + using (var size = new TizenNUISize(width, height, 0)) + using (var background = Color.Transparent) + { + capture.Start(source, size, scratchPath, background); + } + + var completed = await Task.WhenAny(tcs.Task, Task.Delay(CaptureTimeout)).ConfigureAwait(false); + + if (completed != tcs.Task) + { + throw new TimeoutException( + $"Tizen did not raise Capture.Finished within {CaptureTimeout}. " + + "The capture was abandoned rather than waiting indefinitely."); + } if (!await tcs.Task.ConfigureAwait(false)) return null; - var buffer = capture.GetCapturedBuffer(); - if (buffer is null) - return null; + using var buffer = capture.GetCapturedBuffer(); - return TizenScreenshotResult.FromPixelBuffer(buffer); + return buffer is null ? null : TizenScreenshotResult.FromPixelBuffer(buffer); } finally { @@ -120,7 +163,7 @@ public async Task CaptureAsync(TizenWindow window) if (File.Exists(scratchPath)) File.Delete(scratchPath); } - catch + catch (Exception) { // A leftover scratch file in the cache directory is not worth failing a capture. } @@ -166,9 +209,21 @@ internal static TizenScreenshotResult FromPixelBuffer(PixelBuffer buffer) Marshal.Copy(native, pixels, 0, pixels.Length); + // RGBX has no Tizen colour space, so the padding byte is promoted to an opaque alpha and + // the buffer encoded as RGBA. Encoding it as RGBA without this step would treat whatever + // the driver left in the padding byte as transparency. + if (format == PixelFormat.RGB8888) + MakeOpaque(pixels); + return new TizenScreenshotResult(pixels, width, height, colorSpace); } + internal static void MakeOpaque(byte[] pixels) + { + for (var i = 3; i < pixels.Length; i += 4) + pixels[i] = 0xFF; + } + /// public async Task OpenReadAsync(ScreenshotFormat format = ScreenshotFormat.Png, int quality = 100) { @@ -218,11 +273,21 @@ async Task EncodeAsync(Stream destination, ScreenshotFormat format, int quality) } } + /// + /// Maps a NUI pixel format onto the Tizen colour space used to encode it. + /// + /// + /// The X in RGBX/BGRX is padding, not alpha. BGRX has an exact Tizen counterpart + /// (); RGBX does not, so it is converted to opaque + /// RGBA by before encoding. + /// internal static TizenColorSpace MapColorSpace(PixelFormat format) => format switch { - PixelFormat.RGBA8888 or PixelFormat.RGB8888 => TizenColorSpace.Rgba8888, - PixelFormat.BGRA8888 or PixelFormat.BGR8888 => TizenColorSpace.Bgra8888, + PixelFormat.RGBA8888 => TizenColorSpace.Rgba8888, + PixelFormat.BGRA8888 => TizenColorSpace.Bgra8888, + PixelFormat.BGR8888 => TizenColorSpace.Bgrx8888, + PixelFormat.RGB8888 => TizenColorSpace.Rgba8888, PixelFormat.RGB888 => TizenColorSpace.Rgb888, PixelFormat.RGB565 => TizenColorSpace.Rgb565, _ => throw TizenEssentialsSupport.NotSupported( diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 167406da..50d33e22 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Storage; @@ -10,8 +11,30 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// Tizen implementation of , backed by the Tizen key manager /// (Tizen.Security.SecureRepository.DataManager). /// + /// + /// + /// Aliases are stored under a private prefix rather than using the caller's key directly. The + /// key manager alias space is shared with the rest of the application - certificates, keys and + /// any other component's data all live in it - so writing raw keys risked colliding with, and + /// overwriting, data this API does not own. + /// + /// + /// That matters most for : it previously enumerated every alias the + /// application could see and deleted all of them, destroying unrelated secrets. It now removes + /// only aliases this API created. + /// + /// public sealed class TizenSecureStorage : ISecureStorage { + /// + /// Prefix identifying aliases owned by this API. + /// + /// + /// The trailing separator cannot appear in an encoded key, so a prefixed alias can never be + /// confused with another component's alias that merely starts with the same text. + /// + internal const string AliasPrefix = "maui.tizen.securestorage:"; + /// public Task GetAsync(string key) { @@ -20,7 +43,7 @@ public sealed class TizenSecureStorage : ISecureStorage try { // The second parameter is the data password, not a default value. - return Task.FromResult(Encoding.UTF8.GetString(DataManager.Get(key, null))); + return Task.FromResult(Encoding.UTF8.GetString(DataManager.Get(ToAlias(key), null))); } catch (InvalidOperationException) { @@ -40,20 +63,22 @@ public Task SetAsync(string key, string value) ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(value); + var alias = ToAlias(key); + try { try { // DataManager.Save throws when the alias already exists, and Tizen offers no // existence probe that does not throw, so remove unconditionally first. - DataManager.RemoveAlias(key); + DataManager.RemoveAlias(alias); } catch { // Expected when the alias did not exist. } - DataManager.Save(key, Encoding.UTF8.GetBytes(value), new Policy()); + DataManager.Save(alias, Encoding.UTF8.GetBytes(value), new Policy()); return Task.CompletedTask; } @@ -71,7 +96,7 @@ public bool Remove(string key) try { - DataManager.RemoveAlias(key); + DataManager.RemoveAlias(ToAlias(key)); return true; } catch @@ -82,17 +107,69 @@ public bool Remove(string key) } /// + /// + /// Removes only the aliases this API owns. Other secure-repository entries belonging to the + /// application are left untouched. + /// public void RemoveAll() { + IEnumerable aliases; + try { - foreach (var alias in DataManager.GetAliases()) - DataManager.RemoveAlias(alias); + aliases = DataManager.GetAliases(); } catch { global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "No saved data."); + return; } + + foreach (var alias in aliases) + { + if (!IsOwnedAlias(alias)) + continue; + + try + { + DataManager.RemoveAlias(alias); + } + catch + { + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove data."); + } + } + } + + /// + /// Maps a caller key onto the private alias actually stored in the key manager. + /// + /// The caller's key. + /// The namespaced alias. + internal static string ToAlias(string key) => + AliasPrefix + TizenStorageKeyEncoding.Encode(key); + + /// + /// Determines whether an alias was created by this API. + /// + /// The raw key manager alias. + /// when the alias is owned by this API. + /// + /// Tizen may return aliases qualified with the owning package id (pkgid alias), so a + /// trailing match is accepted as well as an exact prefix match. + /// + internal static bool IsOwnedAlias(string alias) + { + if (string.IsNullOrEmpty(alias)) + return false; + + if (alias.StartsWith(AliasPrefix, StringComparison.Ordinal)) + return true; + + var separator = alias.LastIndexOf(' '); + + return separator >= 0 && + alias.AsSpan(separator + 1).StartsWith(AliasPrefix, StringComparison.Ordinal); } } } diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index 260462e5..9f42084a 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -14,17 +14,18 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// /// /// Tizen's TTS client exposes a speed range but no pitch or volume control, so - /// and cannot be honoured - /// and are rejected rather than silently ignored. + /// and are rejected rather + /// than silently ignored. /// public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable { const float RateMax = 2.0f; readonly SemaphoreSlim _speakLock = new(1, 1); + readonly SemaphoreSlim _initializeLock = new(1, 1); TtsClient? _client; - TaskCompletionSource? _initialize; + Task? _initialization; TaskCompletionSource? _utterance; bool _disposed; @@ -39,8 +40,8 @@ public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable /// supports no voices", so this throws rather than reporting a success-shaped result. /// /// - /// Use to enumerate the languages Tizen reports, - /// and pass one of them to . + /// Use to enumerate the languages Tizen + /// reports, and pass one of them to . /// /// public Task> GetLocalesAsync() => @@ -56,9 +57,10 @@ public Task> GetLocalesAsync() => /// The distinct supported voice languages. public async Task> GetSupportedVoiceLanguagesAsync() { - var client = await InitializeAsync().ConfigureAwait(false); + var client = await InitializeAsync(CancellationToken.None).ConfigureAwait(false); var languages = new List(); + foreach (var voice in client.GetSupportedVoices()) { if (!languages.Any(l => string.Equals(l, voice.Language, StringComparison.OrdinalIgnoreCase))) @@ -111,31 +113,36 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati { ArgumentNullException.ThrowIfNull(text); - var client = await InitializeAsync().ConfigureAwait(false); + cancelToken.ThrowIfCancellationRequested(); + + var client = await InitializeAsync(cancelToken).ConfigureAwait(false); await _speakLock.WaitAsync(cancelToken).ConfigureAwait(false); try { + // Re-check after acquiring the lock. Initialization and queuing behind another + // utterance can both take arbitrarily long, and starting speech for a request that + // was cancelled while waiting is exactly the surprise a cancellation token exists to + // prevent. + cancelToken.ThrowIfCancellationRequested(); + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _utterance = utterance; using var registration = cancelToken.Register(() => { - try - { - client.Stop(); - } - catch - { - // The client may already be idle. - } - + StopQuietly(client); utterance.TrySetResult(false); }); var (resolvedLanguage, voiceType) = ResolveVoice(client, language); client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); + + // One last check: the registration above only fires for cancellation that happens + // after it is created, so a token cancelled in between would otherwise still play. + cancelToken.ThrowIfCancellationRequested(); + client.Play(); await utterance.Task.ConfigureAwait(false); @@ -147,6 +154,18 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati } } + static void StopQuietly(TtsClient client) + { + try + { + client.Stop(); + } + catch (Exception) + { + // The client may already be idle; nothing actionable. + } + } + static (string Language, Voice VoiceType) ResolveVoice(TtsClient client, string? requestedLanguage) { var language = "en_US"; @@ -176,47 +195,116 @@ static int ResolveRate(TtsClient client, float? rate) return (int)Math.Round(value / RateMax * client.GetSpeedRange().Max, MidpointRounding.AwayFromZero); } - Task InitializeAsync() + /// + /// Prepares the native TTS client, at most once. + /// + /// + /// + /// Serialized behind a semaphore and cached as a single task. The previous implementation + /// checked two fields without a lock, so concurrent callers could each construct a + /// ; the loser's client was overwritten and leaked, still holding a + /// native handle and an unremovable StateChanged subscription. + /// + /// + /// A failed Prepare disposes the client and clears the cached task, so a later call + /// retries cleanly instead of awaiting a task that will never complete. + /// + /// + async Task InitializeAsync(CancellationToken cancelToken) { ObjectDisposedException.ThrowIf(_disposed, this); - if (_client is { } existing && _initialize is { } pending) - return WrapAsync(pending, existing); + if (_initialization is { } cached) + return await cached.WaitAsync(cancelToken).ConfigureAwait(false); - var client = new TtsClient(); - var initialize = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await _initializeLock.WaitAsync(cancelToken).ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); - client.StateChanged += (_, e) => + _initialization ??= PrepareAsync(); + } + finally { - if (e.Current == State.Ready) - initialize.TrySetResult(true); - }; + _initializeLock.Release(); + } - client.UtteranceCompleted += (_, _) => + try + { + return await _initialization.WaitAsync(cancelToken).ConfigureAwait(false); + } + catch (Exception) when (_initialization?.IsFaulted == true) { + // Let the next caller retry rather than caching the failure forever. + await _initializeLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { - client.Stop(); + if (_initialization?.IsFaulted == true) + _initialization = null; } - catch + finally { - // The client may already be idle. + _initializeLock.Release(); } - _utterance?.TrySetResult(true); - }; + throw; + } + } + + Task PrepareAsync() + { + var client = new TtsClient(); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + client.StateChanged += OnStateChanged; + client.UtteranceCompleted += OnUtteranceCompleted; + + try + { + client.Prepare(); + } + catch (Exception) + { + client.StateChanged -= OnStateChanged; + client.UtteranceCompleted -= OnUtteranceCompleted; + client.Dispose(); + throw; + } _client = client; - _initialize = initialize; - client.Prepare(); + return AwaitReadyAsync(); + + void OnStateChanged(object? sender, StateChangedEventArgs e) + { + if (e.Current == State.Ready) + ready.TrySetResult(true); + } - return WrapAsync(initialize, client); + void OnUtteranceCompleted(object? sender, UtteranceEventArgs e) + { + StopQuietly(client); + _utterance?.TrySetResult(true); + } - static async Task WrapAsync(TaskCompletionSource tcs, TtsClient client) + async Task AwaitReadyAsync() { - await tcs.Task.ConfigureAwait(false); - return client; + try + { + await ready.Task.ConfigureAwait(false); + return client; + } + catch (Exception) + { + client.StateChanged -= OnStateChanged; + client.UtteranceCompleted -= OnUtteranceCompleted; + client.Dispose(); + + if (ReferenceEquals(_client, client)) + _client = null; + + throw; + } } } @@ -229,7 +317,9 @@ public void Dispose() _disposed = true; _client?.Dispose(); _client = null; + _initialization = null; _speakLock.Dispose(); + _initializeLock.Dispose(); } } } diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs index ad135827..c704149a 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs @@ -10,13 +10,24 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// /// The native Tizen sensor type. /// - /// dotnet/maui expressed this logic once per sensor in a *.shared.cs half of a partial + /// + /// dotnet/maui expressed this logic once per sensor in the *.shared.cs half of a partial /// class. Since this backend ships independently named classes, the common behaviour lives here /// instead of being copied into each implementation. + /// + /// + /// Start and Stop are transactional. A native failure part way through leaves no subscription + /// behind and no state claiming the sensor is monitoring when it is not: an earlier version + /// restored but left DataUpdated attached if + /// sensor.Start() threw, so the next Start would double-subscribe and every reading was + /// then raised twice. + /// /// public abstract class TizenSensorBase where TSensor : TizenSensor { + readonly object _locker = new(); + /// /// Gets a value indicating whether readings should be marshalled to the main thread. /// @@ -50,6 +61,20 @@ public abstract class TizenSensorBase /// The native sensor. protected abstract void Unsubscribe(TSensor sensor); + /// + /// Called after the sensor has started, so derived types can reset per-session state. + /// + protected virtual void OnStarted() + { + } + + /// + /// Called after the sensor has stopped, so derived types can release per-session state. + /// + protected virtual void OnStopped() + { + } + /// /// Starts monitoring the sensor. /// @@ -61,24 +86,47 @@ public void Start(SensorSpeed sensorSpeed) if (!IsSupported) throw TizenEssentialsSupport.NotSupported($"{SensorName}.Start", $"This device has no {SensorName} sensor."); - if (IsMonitoring) - throw new InvalidOperationException($"{SensorName} has already been started."); - - IsMonitoring = true; - UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; - - try + lock (_locker) { + if (IsMonitoring) + throw new InvalidOperationException($"{SensorName} has already been started."); + var sensor = Sensor; - sensor.Interval = sensorSpeed.ToPlatform(); - Subscribe(sensor); - sensor.Start(); - } - catch - { - IsMonitoring = false; - throw; + var subscribed = false; + + try + { + sensor.Interval = sensorSpeed.ToPlatform(); + + Subscribe(sensor); + subscribed = true; + + sensor.Start(); + } + catch + { + // Roll the whole attempt back. Leaving the handler attached would double-raise + // every reading after a later successful Start. + if (subscribed) + { + try + { + Unsubscribe(sensor); + } + catch + { + // Nothing further can be done; surface the original failure. + } + } + + throw; + } + + UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; + IsMonitoring = true; } + + OnStarted(); } /// @@ -90,22 +138,41 @@ public void Stop() if (!IsSupported) throw TizenEssentialsSupport.NotSupported($"{SensorName}.Stop", $"This device has no {SensorName} sensor."); - if (!IsMonitoring) - return; - - IsMonitoring = false; - - try + lock (_locker) { + if (!IsMonitoring) + return; + var sensor = Sensor; + + // Unsubscribe first: once the handler is detached no further readings can be + // delivered, so even if Stop() throws the sensor is no longer raising events. Unsubscribe(sensor); - sensor.Stop(); - } - catch - { - IsMonitoring = true; - throw; + + try + { + sensor.Stop(); + } + catch + { + // The native sensor is still running, so restore the subscription to keep the + // object's state and the platform's state consistent. + try + { + Subscribe(sensor); + } + catch + { + // Nothing further can be done; surface the original failure. + } + + throw; + } + + IsMonitoring = false; } + + OnStopped(); } /// diff --git a/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs new file mode 100644 index 00000000..4ba40cc9 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs @@ -0,0 +1,93 @@ +using System; +using System.Text; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Encodes Essentials keys into the flat key spaces Tizen provides. + /// + /// + /// + /// Tizen's preference store and key manager are both flat: there is no per-shared-name + /// namespace, so the shared name and the key have to be combined into a single string. Doing + /// that by simple concatenation is ambiguous, and silently so. + /// + /// + /// With the previous {sharedName}~{key} scheme, shared name a with key + /// b~c and shared name a~b with key c both produced a~b~c. Two + /// different logical entries then shared one physical entry: writing one overwrote the other, + /// and Clear("a") removed the unrelated a~b entry because it merely matched the + /// prefix. + /// + /// + /// The separator is therefore escaped inside each component before joining, which makes the + /// encoding injective: distinct (shared name, key) pairs always produce distinct strings. + /// + /// + public static class TizenStorageKeyEncoding + { + const char Separator = '~'; + const char Escape = '\\'; + + /// + /// Encodes a single component so it can be joined with unambiguously. + /// + /// The component to encode. + /// The escaped component. + public static string Encode(string value) + { + ArgumentNullException.ThrowIfNull(value); + + // Fast path: nothing to escape, which is the overwhelmingly common case. + if (value.IndexOf(Escape) < 0 && value.IndexOf(Separator) < 0) + return value; + + var builder = new StringBuilder(value.Length + 8); + + foreach (var c in value) + { + if (c is Escape or Separator) + builder.Append(Escape); + + builder.Append(c); + } + + return builder.ToString(); + } + + /// + /// Combines an optional shared name and a key into a single storage key. + /// + /// The entry key. + /// The optional shared name. + /// The combined storage key. + public static string GetFullKey(string key, string? sharedName) + { + ArgumentNullException.ThrowIfNull(key); + + // No shared name means the key is used verbatim, which preserves compatibility with + // entries written by the in-box dotnet/maui Tizen backend for the default store - the + // overwhelmingly common case. + if (string.IsNullOrEmpty(sharedName)) + return key; + + return string.Concat(Encode(sharedName), Separator.ToString(), Encode(key)); + } + + /// + /// Gets the prefix that every key belonging to a shared name starts with. + /// + /// The shared name. + /// The prefix, including the trailing separator. + /// + /// Because the shared name is escaped, this prefix cannot match a different shared name that + /// happens to begin with the same characters. + /// + public static string GetSharedNamePrefix(string sharedName) + { + ArgumentNullException.ThrowIfNull(sharedName); + + return Encode(sharedName) + Separator; + } + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs index c89b2d5c..aea8051e 100644 --- a/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs @@ -1,50 +1,153 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using Microsoft.Maui.Devices; using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Networking; using Microsoft.Maui.Platforms.Tizen.Essentials; using Xunit; namespace Maui.Tizen.Essentials.Tests; /// -/// Guards the two integration invariants this backend depends on: -/// the .NET 11 Essentials DI to static facade bridge owns facade assignment, and the MAUI -/// dispatcher bridge owns main-thread marshalling. +/// Guards the two integration invariants this backend depends on: the .NET 11 Essentials +/// DI-to-static-facade bridge owns facade assignment, and the MAUI dispatcher bridge owns +/// main-thread marshalling. /// public class FacadeAndMainThreadOwnershipTests { static readonly Assembly Backend = typeof(TizenAppInfo).Assembly; /// - /// The Essentials facades that dotnet/maui#36657 bridges from DI. Every contract this backend - /// registers must be in this set, otherwise registering it would never reach the static facade. + /// The Essentials contracts MAUI actually bridges from DI onto their static facades, read out of + /// Microsoft.Maui.Hosting.EssentialsExtensions itself. /// - static readonly HashSet BridgedContracts = new(StringComparer.Ordinal) + /// + /// + /// This is deliberately not a hand-maintained list. An earlier version of this test + /// declared the expected set by hand and then asserted that this package's registrations were + /// members of it - which is a tautology, because the same author wrote both sides. It would + /// have passed just as happily if MAUI bridged nothing at all. + /// + /// + /// Instead the bridge methods' IL is decoded and every generic argument passed to their generic + /// helpers (BridgeIfRegistered<T>, TrackAndSet<T>, + /// GetService<T>) is collected. If a future MAUI drops a contract from the bridge, + /// this set shrinks and the dependent test fails. + /// + /// + static readonly Lazy> MauiBridgedContracts = new(DiscoverBridgedContracts); + + static IReadOnlySet DiscoverBridgedContracts() { - "IAccelerometer", "IAppActions", "IAppInfo", "IAppleSignInAuthenticator", "IBarometer", - "IBattery", "IBrowser", "IClipboard", "ICompass", "IConnectivity", "IContacts", - "IDeviceDisplay", "IDeviceInfo", "IEmail", "IFilePicker", "IFileSystem", "IFlashlight", - "IGeocoding", "IGeolocation", "IGyroscope", "IHapticFeedback", "ILauncher", "IMagnetometer", - "IMap", "IMediaPicker", "IOrientationSensor", "IPasskeys", "IPermissions", "IPhoneDialer", - "IPreferences", "IScreenshot", "ISecureStorage", "ISemanticScreenReader", "IShare", "ISms", - "ITextToSpeech", "IVersionTracking", "IVibration", "IWebAuthenticator", - }; + var mauiAssembly = typeof(MauiApp).Assembly; + + var essentialsExtensions = + mauiAssembly.GetType("Microsoft.Maui.Hosting.EssentialsExtensions", throwOnError: true)!; + var essentialsInitializer = + mauiAssembly.GetType("Microsoft.Maui.Hosting.EssentialsExtensions+EssentialsInitializer", throwOnError: true)!; + + var contracts = new SortedSet(StringComparer.Ordinal); + + foreach (var declaringType in new[] { essentialsExtensions, essentialsInitializer }) + { + var typeArguments = declaringType.GetGenericArguments(); + + foreach (var method in declaringType.GetMethods( + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + byte[]? il; + try + { + il = method.GetMethodBody()?.GetILAsByteArray(); + } + catch (Exception) + { + continue; + } + + if (il is null) + continue; + + CollectGenericInterfaceArguments(method, typeArguments, il, contracts); + } + } + + Assert.True( + contracts.Count > 20, + $"Only {contracts.Count} bridged contract(s) were discovered in MAUI's Essentials bridge. " + + "That almost certainly means the IL scan stopped matching, not that MAUI stopped bridging."); + + return contracts; + } + + static void CollectGenericInterfaceArguments( + MethodInfo method, + Type[] typeArguments, + byte[] il, + SortedSet contracts) + { + const byte Call = 0x28; + const byte CallVirt = 0x6F; + + var methodArguments = method.GetGenericArguments(); + + for (var i = 0; i + 4 < il.Length; i++) + { + if (il[i] != Call && il[i] != CallVirt) + continue; + + var token = BitConverter.ToInt32(il, i + 1); + + MemberInfo? member; + try + { + member = method.Module.ResolveMember(token, typeArguments, methodArguments); + } + catch (Exception) + { + // Not every 0x28/0x6F byte is an opcode - some are operand bytes of a preceding + // instruction - so unresolvable tokens are expected noise, not failures. + continue; + } + + if (member is not MethodInfo { IsGenericMethod: true } called) + continue; + + foreach (var argument in called.GetGenericArguments()) + { + if (argument.IsInterface && + argument.Namespace?.StartsWith("Microsoft.Maui", StringComparison.Ordinal) == true) + { + contracts.Add(argument.Name); + } + } + } + } [Fact] - public void EveryRegisteredContractIsBridgedToItsStaticFacadeByMaui() + public void EveryRegisteredContractIsActuallyBridgedByMaui() { + var bridged = MauiBridgedContracts.Value; + var notBridged = TizenEssentialsRegistrationTests.ExpectedRegistrations.Keys .Select(t => t.Name) - .Where(name => !BridgedContracts.Contains(name)) + .Where(name => !bridged.Contains(name)) .ToList(); Assert.Empty(notBridged); } + [Fact] + public void GeocodingIsBridgedEvenThoughItIsRegisteredThroughAFactory() => + Assert.Contains(nameof(IGeocoding), MauiBridgedContracts.Value); + [Fact] public void DoesNotCallSetDefaultOrSetCurrentOnAnyEssentialsFacade() { @@ -107,13 +210,89 @@ public void MarshalsThroughTheMauiMainThreadFacade() Assert.Contains("MainThread", ReferencedTypeNames()); } + [Fact] + public void EveryEventRaisingServiceMarshalsThroughMainThread() + { + // Sensor, connectivity and display events all originate on native Tizen threads. Each of + // these types must hand the event back through MainThread rather than raising inline. + var eventRaisingTypes = new[] + { + typeof(TizenAccelerometer), + typeof(TizenBattery), + typeof(TizenConnectivity), + typeof(TizenDeviceDisplay), + typeof(TizenSensorBase<>), + }; + + var notMarshalling = eventRaisingTypes + .Where(type => !ReferencesMainThread(type)) + .Select(type => type.Name) + .ToList(); + + Assert.Empty(notMarshalling); + } + + static bool ReferencesMainThread(Type type) + { + // Async methods and lambdas are compiled into nested state-machine/closure types, so the + // declaring type alone does not contain the call. Scanning nested types too is what makes + // this assertion meaningful for `async void`/`async Task` event pumps such as + // TizenConnectivity.RefreshProfilesAsync. + if (type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Any(ReferencesMainThreadCore)) + return true; + + return ReferencesMainThreadCore(type); + } + + static bool ReferencesMainThreadCore(Type type) + { + foreach (var method in type.GetMethods( + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + byte[]? il; + try + { + il = method.GetMethodBody()?.GetILAsByteArray(); + } + catch (Exception) + { + continue; + } + + if (il is null) + continue; + + for (var i = 0; i + 4 < il.Length; i++) + { + if (il[i] != 0x28 && il[i] != 0x6F) + continue; + + try + { + if (method.Module.ResolveMember(BitConverter.ToInt32(il, i + 1)) is MethodInfo called && + called.DeclaringType?.Name == "MainThread") + { + return true; + } + } + catch (Exception) + { + // Operand bytes misread as opcodes; see CollectGenericInterfaceArguments. + } + } + } + + return false; + } + [Fact] public void ExposesGeocodingThroughTheTokenAwarePlatformContract() => Assert.True(typeof(IPlatformGeocoding).IsAssignableFrom(typeof(TizenGeocoding))); static IEnumerable ReferencedMemberNames() { - using var stream = System.IO.File.OpenRead(Backend.Location); + using var stream = File.OpenRead(Backend.Location); using var peReader = new PEReader(stream); var reader = peReader.GetMetadataReader(); @@ -123,7 +302,7 @@ static IEnumerable ReferencedMemberNames() static IEnumerable ReferencedTypeNames() { - using var stream = System.IO.File.OpenRead(Backend.Location); + using var stream = File.OpenRead(Backend.Location); using var peReader = new PEReader(stream); var reader = peReader.GetMetadataReader(); diff --git a/tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs b/tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs new file mode 100644 index 00000000..d46e803f --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Networking; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Microsoft.Maui.Storage; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// End-to-end checks that building a with this backend actually hands the +/// Tizen implementations to the static Essentials facades. +/// +/// +/// +/// These are the tests that would have caught the useDefaults: false defect. +/// MauiApp.CreateBuilder(useDefaults: true) installs MAUI's Essentials initializer through +/// the internal UseEssentials(); nothing installs it when defaults are skipped. Simply +/// registering services into DI was therefore not enough - Battery.Default and friends kept +/// resolving lazy platform defaults while DI held the real Tizen implementations, leaving two live +/// instances and a silently wrong static API. +/// +/// +/// They mutate process-global facade state, so they are collected into a non-parallel collection. +/// +/// +[Collection(nameof(EssentialsStaticStateCollection))] +public class FacadeBridgeIntegrationTests +{ + /// + /// Facades whose identity can be asserted without touching a Tizen device. + /// + /// + /// Reading a facade only resolves the registered implementation; it does not call into it. The + /// services excluded here are the ones whose Default/Current getters would + /// construct a lazy platform default that P/Invokes on a non-Tizen host. + /// + public static TheoryData> BridgedFacades() => + new() + { + { typeof(IBattery), static () => Battery.Default }, + { typeof(IConnectivity), static () => Connectivity.Current }, + { typeof(IDeviceDisplay), static () => DeviceDisplay.Current }, + { typeof(IDeviceInfo), static () => DeviceInfo.Current }, + { typeof(IPreferences), static () => Preferences.Default }, + { typeof(ISecureStorage), static () => SecureStorage.Default }, + { typeof(IFileSystem), static () => FileSystem.Current }, + { typeof(IGeolocation), static () => Geolocation.Default }, + { typeof(IAccelerometer), static () => Accelerometer.Default }, + { typeof(ICompass), static () => Compass.Default }, + { typeof(IPermissions), static () => Permissions.Current }, + }; + + static MauiApp BuildApp(bool useDefaults) + { + var builder = MauiApp.CreateBuilder(useDefaults); + builder.AddTizenEssentials(); + return builder.Build(); + } + + [Theory] + [MemberData(nameof(BridgedFacades))] + public void FacadesResolveToTheRegisteredTizenServiceWithoutDefaults(Type serviceType, Func readFacade) + { + using var app = BuildApp(useDefaults: false); + + var fromContainer = app.Services.GetService(serviceType); + Assert.NotNull(fromContainer); + + // Identity, not merely type: a second instance of the right type would still mean the + // static API and DI were talking to different objects. + Assert.Same(fromContainer, readFacade()); + } + + [Theory] + [MemberData(nameof(BridgedFacades))] + public void FacadesResolveToTheRegisteredTizenServiceWithDefaults(Type serviceType, Func readFacade) + { + using var app = BuildApp(useDefaults: true); + + var fromContainer = app.Services.GetService(serviceType); + Assert.NotNull(fromContainer); + Assert.Same(fromContainer, readFacade()); + } + + [Fact] + public void RegisteringEssentialsInstallsMauisInitializerWhenDefaultsAreSkipped() + { + var builder = MauiApp.CreateBuilder(useDefaults: false); + builder.AddTizenEssentials(); + + // The initializer is what performs the bridging. Without it the registrations above are + // inert as far as the static API is concerned. + var initializers = builder.Services + .Where(d => d.ServiceType == typeof(IMauiInitializeService)) + .ToList(); + + Assert.Contains( + initializers, + d => d.ImplementationType?.Name.Contains("EssentialsInitializer", StringComparison.Ordinal) == true); + } + + [Fact] + public void InstallingTheInitializerTwiceDoesNotDuplicateIt() + { + var builder = MauiApp.CreateBuilder(useDefaults: true); + + var before = builder.Services + .Count(d => d.ImplementationType?.Name.Contains("EssentialsInitializer", StringComparison.Ordinal) == true); + + builder.AddTizenEssentials(); + builder.AddTizenEssentials(); + + var after = builder.Services + .Count(d => d.ImplementationType?.Name.Contains("EssentialsInitializer", StringComparison.Ordinal) == true); + + // MAUI's AddEssentialsInitializer uses TryAddEnumerable, so useDefaults: true plus two + // explicit registrations must still yield exactly one initializer. + Assert.Equal(before == 0 ? 1 : before, after); + } + + [Fact] + public void ReleasesTheFacadesWhenTheAppIsDisposed() + { + object bridged; + + using (var app = BuildApp(useDefaults: false)) + { + bridged = app.Services.GetRequiredService(); + Assert.Same(bridged, Battery.Default); + } + + // After disposal the facade must not keep handing out a service whose owning provider is + // gone. MAUI restores the predecessor; the only thing this backend must not do is leave the + // disposed instance installed. + Assert.NotSame(bridged, Battery.Default); + } + + [Fact] + public void ConfiguringAMapServiceTokenDoesNotFailStartup() + { + var builder = MauiApp.CreateBuilder(useDefaults: false); + builder.AddTizenEssentials(); + builder.ConfigureEssentials(essentials => essentials.UseMapServiceToken("map-service-token")); + + // Tizen.Maps is gone at API15, so the token cannot be used for anything - but a + // ConfigureEssentials line must never be the thing that crashes an application at startup. + using var app = builder.Build(); + + Assert.NotNull(app.Services.GetRequiredService()); + } + + [Fact] + public void PlatformGeocodingCarriesNoTokenContractInTheNeutralMauiPackage() + { + // Documents a real gap rather than assuming the token is forwarded. + // + // MAUI declares IPlatformGeocoding.MapServiceToken inside `#if WINDOWS || TIZEN`, so in the + // neutral (non platform specific) Microsoft.Maui.Essentials assembly this package builds + // against, the interface has NO members - and the bridge code that would forward a + // configured token is compiled out with it. + // + // That is harmless here only because geocoding is Unsupported on API15 anyway. If Tizen + // ever regains a geocoding service, the token will have to be plumbed explicitly; it will + // not arrive through this interface. + Assert.Empty(typeof(IPlatformGeocoding).GetMembers( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + + // The concrete implementation still exposes the property, so an application can set it. + Assert.NotNull(typeof(TizenGeocoding).GetProperty(nameof(TizenGeocoding.MapServiceToken))); + } +} + +/// +/// Serializes tests that mutate the process-global Essentials facade state. +/// +[CollectionDefinition(nameof(EssentialsStaticStateCollection), DisableParallelization = true)] +public class EssentialsStaticStateCollection +{ +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs index 1d57da82..d848b94f 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs @@ -7,53 +7,189 @@ namespace Maui.Tizen.Essentials.Tests; /// -/// Verifies the Tizen privilege mapping that keeps -/// Permissions.RequestAsync<Permissions.Camera>() source compatible with the in-box -/// dotnet/maui Tizen backend. +/// Verifies the Tizen privilege mapping behind . /// +/// +/// The central invariant is that a permission never reports +/// for a capability Tizen actually gates. Every mapping is one of three explicit kinds, and each is +/// asserted for what it claims rather than merely for being present. +/// public class TizenPermissionsTests { + /// + /// Privileges Tizen treats as privacy privileges: declaring them is necessary but not + /// sufficient, because the user must also consent at runtime. + /// + /// + /// Taken from the privilege annotations in the TizenFX XML documentation. A privilege in this + /// set mapped with isRuntime: false would skip the PrivacyPrivilegeManager check + /// and report Granted for a capability the user may have denied. + /// + static readonly string[] PrivacyPrivileges = + [ + "http://tizen.org/privilege/apphistory.read", + "http://tizen.org/privilege/calendar.read", + "http://tizen.org/privilege/calendar.write", + "http://tizen.org/privilege/callhistory.read", + "http://tizen.org/privilege/callhistory.write", + "http://tizen.org/privilege/camera", + "http://tizen.org/privilege/contact.read", + "http://tizen.org/privilege/contact.write", + "http://tizen.org/privilege/externalstorage", + "http://tizen.org/privilege/healthinfo", + "http://tizen.org/privilege/location", + "http://tizen.org/privilege/location.coarse", + "http://tizen.org/privilege/mediastorage", + "http://tizen.org/privilege/message.read", + "http://tizen.org/privilege/recorder", + ]; + + static TizenPermissionMapping Mapping(Type permission) + { + Assert.True( + TizenPermissions.TryGetKnownMapping(permission, out var mapping), + $"{permission.Name} has no Tizen mapping."); + + return mapping; + } + + static (Type Permission, TizenPermissionMapping Mapping)[] KnownMappings() => + BuiltInPermissions() + .Select(t => (Permission: t, Found: TizenPermissions.TryGetKnownMapping(t, out var m), Mapping: m)) + .Where(x => x.Found) + .Select(x => (x.Permission, x.Mapping)) + .ToArray(); + + static Type[] BuiltInPermissions() => + typeof(Permissions) + .GetNestedTypes() + .Where(t => t.IsClass && !t.IsAbstract && typeof(Permissions.BasePermission).IsAssignableFrom(t)) + .ToArray(); + [Theory] - [InlineData(typeof(Permissions.Camera), "http://tizen.org/privilege/camera", false)] - [InlineData(typeof(Permissions.ContactsRead), "http://tizen.org/privilege/contact.read", true)] - [InlineData(typeof(Permissions.ContactsWrite), "http://tizen.org/privilege/contact.write", true)] - [InlineData(typeof(Permissions.Flashlight), "http://tizen.org/privilege/led", false)] - [InlineData(typeof(Permissions.LaunchApp), "http://tizen.org/privilege/appmanager.launch", false)] - [InlineData(typeof(Permissions.LocationWhenInUse), "http://tizen.org/privilege/location", true)] - [InlineData(typeof(Permissions.LocationAlways), "http://tizen.org/privilege/location", true)] - [InlineData(typeof(Permissions.Microphone), "http://tizen.org/privilege/recorder", false)] - [InlineData(typeof(Permissions.StorageRead), "http://tizen.org/privilege/mediastorage", true)] - [InlineData(typeof(Permissions.StorageWrite), "http://tizen.org/privilege/mediastorage", true)] - [InlineData(typeof(Permissions.Vibrate), "http://tizen.org/privilege/haptic", false)] - public void MapsWellKnownPermissionsToTizenPrivileges(Type permission, string privilege, bool isRuntime) + [InlineData(typeof(Permissions.Bluetooth), "http://tizen.org/privilege/bluetooth")] + [InlineData(typeof(Permissions.CalendarRead), "http://tizen.org/privilege/calendar.read")] + [InlineData(typeof(Permissions.CalendarWrite), "http://tizen.org/privilege/calendar.write")] + [InlineData(typeof(Permissions.Camera), "http://tizen.org/privilege/camera")] + [InlineData(typeof(Permissions.ContactsRead), "http://tizen.org/privilege/contact.read")] + [InlineData(typeof(Permissions.ContactsWrite), "http://tizen.org/privilege/contact.write")] + [InlineData(typeof(Permissions.Flashlight), "http://tizen.org/privilege/led")] + [InlineData(typeof(Permissions.LaunchApp), "http://tizen.org/privilege/appmanager.launch")] + [InlineData(typeof(Permissions.LocationAlways), "http://tizen.org/privilege/location")] + [InlineData(typeof(Permissions.LocationWhenInUse), "http://tizen.org/privilege/location")] + [InlineData(typeof(Permissions.Media), "http://tizen.org/privilege/mediastorage")] + [InlineData(typeof(Permissions.Microphone), "http://tizen.org/privilege/recorder")] + [InlineData(typeof(Permissions.NearbyWifiDevices), "http://tizen.org/privilege/network.get")] + [InlineData(typeof(Permissions.Phone), "http://tizen.org/privilege/telephony")] + [InlineData(typeof(Permissions.Photos), "http://tizen.org/privilege/mediastorage")] + [InlineData(typeof(Permissions.PhotosAddOnly), "http://tizen.org/privilege/mediastorage")] + [InlineData(typeof(Permissions.PostNotifications), "http://tizen.org/privilege/notification")] + [InlineData(typeof(Permissions.Sensors), "http://tizen.org/privilege/healthinfo")] + [InlineData(typeof(Permissions.Sms), "http://tizen.org/privilege/message.read")] + [InlineData(typeof(Permissions.Speech), "http://tizen.org/privilege/recorder")] + [InlineData(typeof(Permissions.StorageRead), "http://tizen.org/privilege/mediastorage")] + [InlineData(typeof(Permissions.StorageWrite), "http://tizen.org/privilege/mediastorage")] + [InlineData(typeof(Permissions.Vibrate), "http://tizen.org/privilege/haptic")] + public void MapsGatedPermissionsToTheirTizenPrivilege(Type permission, string privilege) + { + var mapping = Mapping(permission); + + Assert.Equal(TizenPermissionKind.Requires, mapping.Kind); + Assert.Contains(privilege, mapping.Privileges.Select(p => p.Privilege)); + } + + [Fact] + public void MarksEveryPrivacyPrivilegeAsRuntime() + { + // The regression that motivated this review: Camera and Microphone were mapped with + // isRuntime: false, so resolution skipped PrivacyPrivilegeManager entirely and reported + // Granted for a capability the user may well have denied. + var wrong = KnownMappings() + .SelectMany(entry => entry.Mapping.Privileges.Select(p => (entry.Permission, Privilege: p))) + .Where(x => PrivacyPrivileges.Contains(x.Privilege.Privilege, StringComparer.Ordinal) && !x.Privilege.IsRuntime) + .Select(x => $"{x.Permission.Name} => {x.Privilege.Privilege}") + .ToList(); + + Assert.Empty(wrong); + } + + [Fact] + public void NeverClaimsToRequirePrivilegesItDoesNotList() { - Assert.True(TizenPermissions.TryGetKnownPrivileges(permission, out var privileges)); + // A 'Requires' mapping with no privileges would silently degrade to unconditional Granted. + var empty = KnownMappings() + .Where(entry => entry.Mapping.Kind == TizenPermissionKind.Requires && entry.Mapping.Privileges.Length == 0) + .Select(entry => entry.Permission.Name) + .ToList(); - var match = Assert.Single(privileges!, p => p.Privilege == privilege); - Assert.Equal(isRuntime, match.IsRuntime); + Assert.Empty(empty); } [Fact] - public void MapsMapsPermissionToAllThreeRequiredPrivileges() + public void OnlyBatteryIsClaimedUngatedAndItSaysWhy() { - Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(Permissions.Maps), out var privileges)); + var ungated = KnownMappings() + .Where(entry => entry.Mapping.Kind == TizenPermissionKind.Ungated) + .ToList(); + // Ungated is an affirmative claim about the platform, so the set is deliberately tiny and + // every member has to justify itself. Assert.Equal( - new[] - { - "http://tizen.org/privilege/internet", - "http://tizen.org/privilege/mapservice", - "http://tizen.org/privilege/network.get", - }, - privileges!.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); + [nameof(Permissions.Battery)], + ungated.Select(e => e.Permission.Name).OrderBy(n => n, StringComparer.Ordinal)); + + Assert.All(ungated, entry => Assert.False(string.IsNullOrWhiteSpace(entry.Mapping.Reason))); + } + + [Theory] + [InlineData(typeof(Permissions.Maps))] + [InlineData(typeof(Permissions.Reminders))] + public void ReportsUnsupportedForCapabilitiesTizenDoesNotHave(Type permission) + { + var mapping = Mapping(permission); - Assert.All(privileges!, p => Assert.False(p.IsRuntime)); + Assert.Equal(TizenPermissionKind.Unsupported, mapping.Kind); + Assert.False(string.IsNullOrWhiteSpace(mapping.Reason)); + Assert.Empty(mapping.Privileges); + } + + [Fact] + public void UnsupportedPermissionsThrowRatherThanReportingAStatus() + { + var permissions = new TizenPermissions(); + + Assert.Throws(() => { _ = permissions.CheckStatusAsync(); }); + Assert.Throws(() => { _ = permissions.RequestAsync(); }); + Assert.Throws(TizenPermissions.EnsureDeclared); + } + + [Fact] + public void NoLongerReferencesTheRemovedMapServicePrivilege() + { + // Tizen.Maps is gone as of API15, so mapservice gates nothing this package can do. + // Keeping it would make applications declare a privilege for a dead capability. + var mapService = KnownMappings() + .SelectMany(entry => entry.Mapping.Privileges.Select(p => (entry.Permission, p.Privilege))) + .Where(x => x.Privilege.Contains("mapservice", StringComparison.Ordinal)) + .Select(x => x.Permission.Name) + .ToList(); + + Assert.Empty(mapService); + } + + [Fact] + public void ExplainsWhyTheMapsPermissionIsUnsupported() + { + var mapping = Mapping(typeof(Permissions.Maps)); + + Assert.Equal(TizenPermissionKind.Unsupported, mapping.Kind); + Assert.Contains("API15", mapping.Reason!, StringComparison.Ordinal); } [Fact] public void MapsNetworkStatePermissionToInternetAndNetworkGet() { - Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(Permissions.NetworkState), out var privileges)); + var mapping = Mapping(typeof(Permissions.NetworkState)); Assert.Equal( new[] @@ -61,53 +197,50 @@ public void MapsNetworkStatePermissionToInternetAndNetworkGet() "http://tizen.org/privilege/internet", "http://tizen.org/privilege/network.get", }, - privileges!.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); - } + mapping.Privileges.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); - [Theory] - [InlineData(typeof(Permissions.Battery))] - [InlineData(typeof(Permissions.Bluetooth))] - [InlineData(typeof(Permissions.CalendarRead))] - [InlineData(typeof(Permissions.Media))] - [InlineData(typeof(Permissions.Phone))] - [InlineData(typeof(Permissions.Photos))] - [InlineData(typeof(Permissions.PostNotifications))] - [InlineData(typeof(Permissions.Sensors))] - [InlineData(typeof(Permissions.Speech))] - public void KnowsPermissionsThatTizenDoesNotGate(Type permission) - { - Assert.True(TizenPermissions.TryGetKnownPrivileges(permission, out var privileges)); - Assert.Empty(privileges!); + Assert.All(mapping.Privileges, p => Assert.False(p.IsRuntime)); } [Fact] public void CoversEveryBuiltInMauiPermissionType() { - var builtIn = typeof(Permissions) - .GetNestedTypes() - .Where(t => t.IsClass && !t.IsAbstract && typeof(Permissions.BasePermission).IsAssignableFrom(t)) - .ToList(); + var builtIn = BuiltInPermissions(); Assert.NotEmpty(builtIn); var unmapped = builtIn - .Where(t => !TizenPermissions.TryGetKnownPrivileges(t, out _)) + .Where(t => !TizenPermissions.TryGetKnownMapping(t, out _)) .Select(t => t.Name) .ToList(); Assert.Empty(unmapped); } + [Fact] + public void UsesFullyQualifiedTizenPrivilegeUris() + { + var malformed = KnownMappings() + .SelectMany(entry => entry.Mapping.Privileges.Select(p => (entry.Permission, p.Privilege))) + .Where(x => !x.Privilege.StartsWith("http://tizen.org/privilege/", StringComparison.Ordinal)) + .Select(x => $"{x.Permission.Name} => {x.Privilege}") + .ToList(); + + Assert.Empty(malformed); + } + [Fact] public void FallsBackToTheDerivedMappingForSubclassedPermissions() { - Assert.True(TizenPermissions.TryGetKnownPrivileges(typeof(DerivedCameraPermission), out var privileges)); - Assert.Equal("http://tizen.org/privilege/camera", Assert.Single(privileges!).Privilege); + var mapping = Mapping(typeof(DerivedCameraPermission)); + + Assert.Equal(TizenPermissionKind.Requires, mapping.Kind); + Assert.Equal("http://tizen.org/privilege/camera", Assert.Single(mapping.Privileges).Privilege); } [Fact] public void LeavesCustomPermissionsToOwnTheirBehaviour() => - Assert.False(TizenPermissions.TryGetKnownPrivileges(typeof(CustomPermission), out _)); + Assert.False(TizenPermissions.TryGetKnownMapping(typeof(CustomPermission), out _)); [Fact] public void NeverShowsARationaleBecauseTizenHasNoRationaleContract() => @@ -125,6 +258,10 @@ public void RejectsANullPrivilegeCollection() => public void TreatsAnEmptyPrivilegeNameAsUndeclared() => Assert.False(TizenPermissions.IsPrivilegeDeclared(string.Empty)); + [Fact] + public void RejectsARequiresMappingWithNoPrivileges() => + Assert.Throws(static () => TizenPermissionMapping.Requires()); + sealed class DerivedCameraPermission : Permissions.Camera { } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs new file mode 100644 index 00000000..6a2654a3 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -0,0 +1,285 @@ +using System; +using System.Linq; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; +using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; +using TizenColorSpace = Tizen.Multimedia.ColorSpace; +using TizenConnectionState = Tizen.Network.Connection.ConnectionState; +using TizenPixelFormat = Tizen.NUI.PixelFormat; + +namespace Maui.Tizen.Essentials.Tests; + +/// +/// Behavioural tests for the review fixes that can be exercised without a Tizen device. +/// +public class TizenServiceBehaviorTests +{ + // ------------------------------------------------------------------------------------------- + // Battery power source and state mapping. + // ------------------------------------------------------------------------------------------- + + [Theory] + [InlineData(TizenBatteryPowerSource.Ac, BatteryPowerSource.AC)] + [InlineData(TizenBatteryPowerSource.Usb, BatteryPowerSource.Usb)] + [InlineData(TizenBatteryPowerSource.Wireless, BatteryPowerSource.Wireless)] + [InlineData(TizenBatteryPowerSource.None, BatteryPowerSource.Battery)] + public void MapsEveryNativeBatteryPowerSource(TizenBatteryPowerSource source, BatteryPowerSource expected) => + Assert.Equal(expected, TizenBattery.MapPowerSource(source)); + + [Fact] + public void ReportsWirelessChargingRatherThanAssumingUsb() + { + // The previous implementation inferred the source from the charging flag alone, so every + // charging device claimed USB - including AC and wireless. + Assert.Equal(BatteryPowerSource.Wireless, TizenBattery.MapPowerSource(TizenBatteryPowerSource.Wireless)); + Assert.Equal(BatteryPowerSource.AC, TizenBattery.MapPowerSource(TizenBatteryPowerSource.Ac)); + } + + [Theory] + // Charging on any source. + [InlineData(true, 50, TizenBatteryPowerSource.Ac, BatteryState.Charging)] + [InlineData(true, 50, TizenBatteryPowerSource.Usb, BatteryState.Charging)] + // Full: on a charger at 100%. + [InlineData(true, 100, TizenBatteryPowerSource.Ac, BatteryState.Full)] + [InlineData(false, 100, TizenBatteryPowerSource.Ac, BatteryState.Full)] + // Plugged in but not charging is its own state, not "discharging". + [InlineData(false, 80, TizenBatteryPowerSource.Usb, BatteryState.NotCharging)] + // Actually running on battery. + [InlineData(false, 80, TizenBatteryPowerSource.None, BatteryState.Discharging)] + [InlineData(false, 100, TizenBatteryPowerSource.None, BatteryState.Discharging)] + public void MapsBatteryStateFromChargingLevelAndSource( + bool isCharging, + int percent, + TizenBatteryPowerSource source, + BatteryState expected) => + Assert.Equal(expected, TizenBattery.MapState(isCharging, percent, source)); + + // ------------------------------------------------------------------------------------------- + // Storage key encoding. + // ------------------------------------------------------------------------------------------- + + [Fact] + public void SharedPreferenceKeysCannotCollide() + { + // The bug this encoding exists to prevent: with naive concatenation both of these produced + // "a~b~c", so two different logical entries shared one physical entry. + var first = TizenStorageKeyEncoding.GetFullKey("b~c", "a"); + var second = TizenStorageKeyEncoding.GetFullKey("c", "a~b"); + + Assert.NotEqual(first, second); + } + + [Theory] + [InlineData("plain", "plain")] + [InlineData("has~separator", "has\\~separator")] + [InlineData("has\\escape", "has\\\\escape")] + public void EscapesSeparatorAndEscapeCharacters(string value, string expected) => + Assert.Equal(expected, TizenStorageKeyEncoding.Encode(value)); + + [Fact] + public void EncodingIsInjectiveAcrossAwkwardInputs() + { + string[] components = ["a", "b", "a~b", "a\\b", "~", "\\", "", "a~", "~a"]; + + var encoded = (from shared in components + from key in components + select TizenStorageKeyEncoding.GetFullKey(key, shared)).ToList(); + + // A shared name of "" means the default store, where the key is used verbatim, so those + // collapse legitimately. Every other pair must stay distinct. + var qualified = (from shared in components.Where(c => c.Length > 0) + from key in components + select TizenStorageKeyEncoding.GetFullKey(key, shared)).ToList(); + + Assert.Equal(qualified.Count, qualified.Distinct(StringComparer.Ordinal).Count()); + Assert.NotEmpty(encoded); + } + + [Fact] + public void DefaultStoreKeysAreUnprefixedForCompatibility() + { + // Entries written by the in-box dotnet/maui Tizen backend for the default store used the + // raw key, so changing that would strand existing data. + Assert.Equal("key", TizenStorageKeyEncoding.GetFullKey("key", null)); + Assert.Equal("key", TizenStorageKeyEncoding.GetFullKey("key", string.Empty)); + Assert.Equal("key", TizenPreferences.GetFullKey("key", null)); + } + + [Fact] + public void ClearingASharedNameCannotMatchADifferentSharedName() + { + var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix("a"); + + // "a~b" encodes to "a\~b", which does not start with "a~", so Clear("a") leaves it alone. + var otherStoreKey = TizenStorageKeyEncoding.GetFullKey("c", "a~b"); + + Assert.False(otherStoreKey.StartsWith(prefix, StringComparison.Ordinal)); + + // ...while keys genuinely in "a" do match. + Assert.StartsWith(prefix, TizenStorageKeyEncoding.GetFullKey("c", "a"), StringComparison.Ordinal); + } + + // ------------------------------------------------------------------------------------------- + // SecureStorage alias namespacing. + // ------------------------------------------------------------------------------------------- + + [Fact] + public void SecureStorageAliasesAreNamespaced() + { + var alias = TizenSecureStorage.ToAlias("token"); + + Assert.StartsWith(TizenSecureStorage.AliasPrefix, alias, StringComparison.Ordinal); + Assert.EndsWith("token", alias, StringComparison.Ordinal); + } + + [Fact] + public void SecureStorageAliasesCannotCollideWithEachOther() + { + Assert.NotEqual(TizenSecureStorage.ToAlias("a~b"), TizenSecureStorage.ToAlias("a\\~b")); + } + + [Theory] + [InlineData("maui.tizen.securestorage:token", true)] + [InlineData("org.example.app maui.tizen.securestorage:token", true)] + [InlineData("some.other.component:token", false)] + [InlineData("maui.tizen.securestorageX", false)] + [InlineData("", false)] + public void RecognisesOnlyItsOwnSecureStorageAliases(string alias, bool owned) => + Assert.Equal(owned, TizenSecureStorage.IsOwnedAlias(alias)); + + [Fact] + public void RemoveAllWouldNotTouchForeignSecureRepositoryAliases() + { + // RemoveAll previously deleted every alias the application could see, including + // certificates and keys owned by unrelated components. + string[] foreign = + [ + "my.app.certificate", + "vpn-client-key", + "maui.tizen.securestorageNOTASEPARATOR", + ]; + + Assert.All(foreign, alias => Assert.False(TizenSecureStorage.IsOwnedAlias(alias))); + } + + // ------------------------------------------------------------------------------------------- + // Screenshot pixel-format handling. + // ------------------------------------------------------------------------------------------- + + [Theory] + [InlineData(TizenPixelFormat.RGBA8888, TizenColorSpace.Rgba8888)] + [InlineData(TizenPixelFormat.BGRA8888, TizenColorSpace.Bgra8888)] + [InlineData(TizenPixelFormat.RGB888, TizenColorSpace.Rgb888)] + [InlineData(TizenPixelFormat.RGB565, TizenColorSpace.Rgb565)] + public void MapsScreenshotColorSpaces(TizenPixelFormat format, TizenColorSpace expected) => + Assert.Equal(expected, TizenScreenshotResult.MapColorSpace(format)); + + [Fact] + public void MapsBgrxToItsOpaqueTizenColorSpace() + { + // The X in BGRX is padding, not alpha. Tizen has an exact counterpart, so no conversion is + // needed - but mapping it to Bgra8888 would have treated driver padding as transparency. + Assert.Equal( + TizenColorSpace.Bgrx8888, + TizenScreenshotResult.MapColorSpace(TizenPixelFormat.BGR8888)); + } + + [Fact] + public void MapsRgbxToRgbaBecauseTizenHasNoRgbxColorSpace() => + Assert.Equal( + TizenColorSpace.Rgba8888, + TizenScreenshotResult.MapColorSpace(TizenPixelFormat.RGB8888)); + + [Fact] + public void ForcesTheAlphaByteOpaqueWhenConvertingRgbx() + { + // Whatever the driver left in the padding byte must not become transparency. + var pixels = new byte[] { 1, 2, 3, 0x00, 4, 5, 6, 0x7F }; + + TizenScreenshotResult.MakeOpaque(pixels); + + Assert.Equal(0xFF, pixels[3]); + Assert.Equal(0xFF, pixels[7]); + + // Colour channels are untouched. + Assert.Equal(new byte[] { 1, 2, 3 }, pixels[..3]); + Assert.Equal(new byte[] { 4, 5, 6 }, pixels[4..7]); + } + + [Theory] + [InlineData(TizenPixelFormat.RGBA8888, 4)] + [InlineData(TizenPixelFormat.BGRA8888, 4)] + [InlineData(TizenPixelFormat.RGB8888, 4)] + [InlineData(TizenPixelFormat.BGR8888, 4)] + [InlineData(TizenPixelFormat.RGB888, 3)] + [InlineData(TizenPixelFormat.RGB565, 2)] + public void MapsScreenshotPixelStrides(TizenPixelFormat format, int expected) => + Assert.Equal(expected, TizenScreenshotResult.BytesPerPixel(format)); + + [Fact] + public void RejectsScreenshotPixelFormatsWithoutAMatchingColorSpace() + { + Assert.Throws( + static () => TizenScreenshotResult.MapColorSpace(TizenPixelFormat.A8)); + Assert.Throws( + static () => TizenScreenshotResult.BytesPerPixel(TizenPixelFormat.A8)); + } + + [Fact] + public void BoundsTheWaitForACaptureThatNeverFinishes() + { + // Capture.Finished is the only completion signal. Without a bound, a capture the native side + // never finishes would hang the caller forever and leak the Capture handle. + Assert.True(TizenScreenshot.CaptureTimeout > TimeSpan.Zero); + Assert.True(TizenScreenshot.CaptureTimeout <= TimeSpan.FromMinutes(1)); + } + + // ------------------------------------------------------------------------------------------- + // Connectivity without a subscription. + // ------------------------------------------------------------------------------------------- + + [Fact] + public void ConnectionProfilesDoesNotDependOnEventSubscription() + { + // The regression: profiles were only populated by the refresh kicked off when the first + // ConnectivityChanged handler was added, so a plain query always saw an empty list. + var property = typeof(TizenConnectivity).GetProperty(nameof(TizenConnectivity.ConnectionProfiles))!; + var getter = property.GetGetMethod()!; + + var il = getter.GetMethodBody()!.GetILAsByteArray()!; + + // The getter must call the shared synchronous query rather than reading a cached field. + var callsQuery = false; + for (var i = 0; i + 4 < il.Length; i++) + { + if (il[i] != 0x28 && il[i] != 0x6F) + continue; + + try + { + if (getter.Module.ResolveMember(BitConverter.ToInt32(il, i + 1)) is System.Reflection.MethodInfo m && + m.Name == nameof(TizenConnectivity.GetConnectionProfiles)) + { + callsQuery = true; + break; + } + } + catch (Exception) + { + // Operand bytes misread as opcodes. + } + } + + Assert.True(callsQuery, "ConnectionProfiles must query connection state directly."); + } + + [Fact] + public void TreatsOnlyConnectedTransportsAsActive() + { + Assert.True(TizenConnectivity.IsConnected(TizenConnectionState.Connected)); + Assert.False(TizenConnectivity.IsConnected(TizenConnectionState.Disconnected)); + Assert.False(TizenConnectivity.IsConnected(TizenConnectionState.Deactivated)); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs index bd5d5e22..ea624e99 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs @@ -7,7 +7,7 @@ using Microsoft.Maui.Networking; using Microsoft.Maui.Platforms.Tizen.Essentials; using Xunit; -using TizenConnectionProfileType = Tizen.Network.Connection.ConnectionProfileType; +using TizenConnectionType = Tizen.Network.Connection.ConnectionType; using TizenDeviceOrientation = Tizen.Applications.DeviceOrientation; using TizenPixelFormat = Tizen.NUI.PixelFormat; @@ -80,13 +80,19 @@ public void PrefixesSharedPreferenceKeys(string? sharedName, string key, string Assert.Equal(expected, TizenPreferences.GetFullKey(key, sharedName)); [Theory] - [InlineData(TizenConnectionProfileType.WiFi, ConnectionProfile.WiFi)] - [InlineData(TizenConnectionProfileType.Cellular, ConnectionProfile.Cellular)] - [InlineData(TizenConnectionProfileType.Ethernet, ConnectionProfile.Ethernet)] - [InlineData(TizenConnectionProfileType.Bt, ConnectionProfile.Bluetooth)] - public void MapsConnectionProfiles(TizenConnectionProfileType type, ConnectionProfile expected) => + [InlineData(TizenConnectionType.WiFi, ConnectionProfile.WiFi)] + [InlineData(TizenConnectionType.Cellular, ConnectionProfile.Cellular)] + [InlineData(TizenConnectionType.Ethernet, ConnectionProfile.Ethernet)] + [InlineData(TizenConnectionType.Bluetooth, ConnectionProfile.Bluetooth)] + public void MapsConnectionProfiles(TizenConnectionType type, ConnectionProfile expected) => Assert.Equal(expected, TizenConnectivity.MapProfileType(type)); + [Theory] + [InlineData(TizenConnectionType.Disconnected)] + [InlineData(TizenConnectionType.NetProxy)] + public void MapsUnknownConnectionTypesToNoProfile(TizenConnectionType type) => + Assert.Null(TizenConnectivity.MapProfileType(type)); + [Theory] [InlineData(TizenDeviceOrientation.Orientation_0, DisplayRotation.Rotation0, DisplayOrientation.Portrait)] [InlineData(TizenDeviceOrientation.Orientation_90, DisplayRotation.Rotation90, DisplayOrientation.Landscape)] From e58d8e6f7ce6ad538fe88466fd027a106841c0e2 Mon Sep 17 00:00:00 2001 From: Redth Date: Wed, 26 Aug 2026 20:16:58 -0400 Subject: [PATCH 06/21] Update coverage doc test count and baseline path Tests 283 -> 284 after the geocoding contract test, and the baseline reference follows the move to PublicAPI/slice/. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/tizen-essentials-service-coverage.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index bde7ff4c..62f6f223 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -74,9 +74,9 @@ Profile column values are the Tizen device profiles on which the service is usab | | Status | | --- | --- | | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | -| The declared public API surface matches `PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | +| The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (283 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (284 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | From 4a8bb7f4956f6c29b6e497c435b0bbeb74c0c3d6 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 00:45:28 -0400 Subject: [PATCH 07/21] Close Essentials migration contract gaps Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 10 +- docs/migration.md | 24 ++- docs/net11-status.md | 19 +++ docs/tizen-essentials-service-coverage.md | 2 +- eng/build-workload-free.sh | 2 +- .../SecureStorage/TizenSecureStorage.cs | 90 ++++++++++- .../TextToSpeech/TizenTextToSpeech.cs | 14 +- .../TizenServiceBehaviorTests.cs | 153 ++++++++++++++++++ 8 files changed, 293 insertions(+), 21 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16c1a7d2..18fbdd2f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -186,12 +186,12 @@ jobs: } >> "$GITHUB_STEP_SUMMARY" fi - - name: Build Tizen projects + - name: First real Tizen build and surface review gate if: steps.probe.outputs.available == 'true' # Installation goes through Samsung's supported side-load path rather than public - # workload search; this step is a placeholder that will fail loudly and visibly - # the first time the gate lifts, which is the point at which a human should wire - # up the real installer. + # workload search. This deliberately remains a blocking first-build gate: API15 and + # neutral-host compilation cannot prove which MAUI assets net11.0-tizen11.0 selects. run: | - echo "::notice::Samsung manifest is published. Wire up the supported Samsung installer / local manifest path, then build." + echo "::error::Samsung manifest is published. Install it through Samsung's supported path, build the shipping Core and Essentials projects, and complete the surface checklist in docs/net11-status.md." + echo "::error::The review must explicitly recheck IPlatformScreenshot, IPlatformGeocoding, Microsoft.Maui.Media.Locale visibility, and regenerated API baselines." exit 1 diff --git a/docs/migration.md b/docs/migration.md index 88b2b280..884c99da 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -55,8 +55,28 @@ working. workload search. The Samsung manifest is third-party and side-loaded, so `dotnet workload install tizen` cannot discover it on a clean runner. 3. Promote that job to a required check and build the Tizen projects for real. -4. Regenerate API baselines against a real Tizen build. -5. Begin Phase 2. +4. Complete the mandatory first-real-build surface review in + [`net11-status.md`](net11-status.md#first-real-net110-tizen110-surface-gate). The API15 and + host-verification lanes cannot prove which MAUI assets a genuine Tizen TFM selects. +5. Regenerate API baselines against a real Tizen build. +6. Begin Phase 2. + +### SecureStorage data migration + +The standalone Essentials package stores secure values under +`maui.tizen.securestorage:`. The in-box Tizen backend stored the caller's raw key in +the application-wide secure-repository alias space. + +`GetAsync` performs a one-way, per-key compatibility migration: it reads the namespaced alias first; +only when that alias is absent does it read the exact legacy raw alias, save the value under the +namespaced alias, and remove that exact raw alias. A migration save failure is surfaced and leaves +the legacy value intact. If cleanup of the raw alias fails after the namespaced save succeeds, the +namespaced value remains authoritative. + +`RemoveAll` deliberately does **not** delete raw aliases. There is no safe way to distinguish an +old SecureStorage raw alias from certificates, keys, or another component's data in the shared +repository. Applications that need eager migration must enumerate their own known SecureStorage +keys and call `GetAsync` for each one before calling `RemoveAll`. ### Target contract provenance diff --git a/docs/net11-status.md b/docs/net11-status.md index 0824004c..7fde8867 100644 --- a/docs/net11-status.md +++ b/docs/net11-status.md @@ -31,6 +31,25 @@ exists so `#if TIZEN` code is checked by a compiler rather than by inspection. > Note: a device build has **not** been performed and must not be claimed. Nothing here validates > runtime behaviour on Tizen. +### First-real `net11.0-tizen11.0` surface gate + +The first build after Samsung's workload becomes available is a migration gate, not a routine green +CI run. The conditional `tizen-workload-gate` job must build the shipping projects against the +genuine `net11.0-tizen11.0` asset graph and remain non-required until the following review is +recorded: + +1. Verify `IPlatformScreenshot` resolves from the real Tizen-flavoured MAUI framework surface and + that `TizenScreenshot` still implements the selected contract without a neutral-host assumption. +2. Verify `IPlatformGeocoding` the same way for `TizenGeocoding`. +3. Reinspect `Microsoft.Maui.Media.Locale` in the selected `Microsoft.Maui.Essentials` asset. If its + constructor is public, replace the temporary Tizen voice-language API with the public + `ITextToSpeech.GetLocalesAsync` implementation before promoting the lane. +4. Regenerate and review the package's API baseline from that real build. + +The API15 reference-pack lane proves TizenFX compatibility, and the host lane proves the neutral +MAUI facade bridge. Neither lane proves which MAUI compile assets the Tizen TFM will select, so they +cannot satisfy or waive this gate. + --- ## 2. External blockers diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 62f6f223..ce8539d8 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (284 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (290 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 5474823b..6a3fd0b1 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=284 + ESSENTIALS_TESTS_MINIMUM=290 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 50d33e22..90b7b004 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -26,6 +26,8 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public sealed class TizenSecureStorage : ISecureStorage { + readonly ITizenSecureRepository _repository; + /// /// Prefix identifying aliases owned by this API. /// @@ -35,6 +37,19 @@ public sealed class TizenSecureStorage : ISecureStorage /// internal const string AliasPrefix = "maui.tizen.securestorage:"; + /// + /// Creates a secure-storage service backed by Tizen's secure repository. + /// + public TizenSecureStorage() + : this(TizenSecureRepository.Instance) + { + } + + internal TizenSecureStorage(ITizenSecureRepository repository) + { + _repository = repository; + } + /// public Task GetAsync(string key) { @@ -43,18 +58,45 @@ public sealed class TizenSecureStorage : ISecureStorage try { // The second parameter is the data password, not a default value. - return Task.FromResult(Encoding.UTF8.GetString(DataManager.Get(ToAlias(key), null))); + return Task.FromResult(Encoding.UTF8.GetString(_repository.Get(ToAlias(key)))); } catch (InvalidOperationException) { - // DataManager.Get throws when the alias does not exist. That is expected and normal. - return Task.FromResult(null); + // The namespaced alias does not exist. Try the exact raw alias used by the in-box + // backend, then migrate it one-way before returning it. } catch { global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to load data."); throw; } + + byte[] legacyValue; + + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } + + // Save before deleting so a migration failure cannot remove the only readable copy. + _repository.Save(ToAlias(key), legacyValue); + + try + { + _repository.RemoveAlias(key); + } + catch + { + // The namespaced copy is now authoritative. A stale legacy alias is safe to leave + // behind and can be cleaned up by a later explicit application migration. + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove migrated legacy data."); + } + + return Task.FromResult(Encoding.UTF8.GetString(legacyValue)); } /// @@ -71,14 +113,14 @@ public Task SetAsync(string key, string value) { // DataManager.Save throws when the alias already exists, and Tizen offers no // existence probe that does not throw, so remove unconditionally first. - DataManager.RemoveAlias(alias); + _repository.RemoveAlias(alias); } catch { // Expected when the alias did not exist. } - DataManager.Save(alias, Encoding.UTF8.GetBytes(value), new Policy()); + _repository.Save(alias, Encoding.UTF8.GetBytes(value)); return Task.CompletedTask; } @@ -96,7 +138,7 @@ public bool Remove(string key) try { - DataManager.RemoveAlias(ToAlias(key)); + _repository.RemoveAlias(ToAlias(key)); return true; } catch @@ -117,7 +159,7 @@ public void RemoveAll() try { - aliases = DataManager.GetAliases(); + aliases = _repository.GetAliases(); } catch { @@ -132,7 +174,7 @@ public void RemoveAll() try { - DataManager.RemoveAlias(alias); + _repository.RemoveAlias(alias); } catch { @@ -172,4 +214,36 @@ internal static bool IsOwnedAlias(string alias) alias.AsSpan(separator + 1).StartsWith(AliasPrefix, StringComparison.Ordinal); } } + + internal interface ITizenSecureRepository + { + byte[] Get(string alias); + + void Save(string alias, byte[] value); + + void RemoveAlias(string alias); + + IEnumerable GetAliases(); + } + + sealed class TizenSecureRepository : ITizenSecureRepository + { + public static TizenSecureRepository Instance { get; } = new(); + + TizenSecureRepository() + { + } + + public byte[] Get(string alias) => + DataManager.Get(alias, null); + + public void Save(string alias, byte[] value) => + DataManager.Save(alias, value, new Policy()); + + public void RemoveAlias(string alias) => + DataManager.RemoveAlias(alias); + + public IEnumerable GetAliases() => + DataManager.GetAliases(); + } } diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index 9f42084a..dda15ed1 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -130,10 +130,7 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati _utterance = utterance; using var registration = cancelToken.Register(() => - { - StopQuietly(client); - utterance.TrySetResult(false); - }); + CancelUtterance(utterance, cancelToken, () => StopQuietly(client))); var (resolvedLanguage, voiceType) = ResolveVoice(client, language); @@ -154,6 +151,15 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati } } + internal static void CancelUtterance( + TaskCompletionSource utterance, + CancellationToken cancelToken, + Action stop) + { + utterance.TrySetCanceled(cancelToken); + stop(); + } + static void StopQuietly(TtsClient client) { try diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 6a2654a3..5e402282 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -1,5 +1,9 @@ using System; +using System.Collections.Generic; using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Devices; using Microsoft.Maui.Platforms.Tizen.Essentials; @@ -164,6 +168,111 @@ public void RemoveAllWouldNotTouchForeignSecureRepositoryAliases() Assert.All(foreign, alias => Assert.False(TizenSecureStorage.IsOwnedAlias(alias))); } + [Fact] + public async Task SecureStorageReadsAndMigratesAnExactLegacyAlias() + { + var repository = new FakeSecureRepository + { + ["token"] = "legacy-value", + ["unrelated"] = "leave-me", + }; + var storage = new TizenSecureStorage(repository); + + var value = await storage.GetAsync("token"); + + Assert.Equal("legacy-value", value); + Assert.False(repository.Contains("token")); + Assert.Equal("legacy-value", repository[TizenSecureStorage.ToAlias("token")]); + Assert.Equal("leave-me", repository["unrelated"]); + } + + [Fact] + public async Task SecureStoragePrefersTheNamespacedAliasOverLegacyData() + { + var repository = new FakeSecureRepository + { + ["token"] = "legacy-value", + [TizenSecureStorage.ToAlias("token")] = "new-value", + }; + var storage = new TizenSecureStorage(repository); + + Assert.Equal("new-value", await storage.GetAsync("token")); + Assert.Equal("legacy-value", repository["token"]); + } + + [Fact] + public void SecureStorageRemoveAllDeletesOnlyNamespacedAliases() + { + var repository = new FakeSecureRepository + { + ["legacy-token"] = "legacy-value", + ["unrelated"] = "leave-me", + [TizenSecureStorage.ToAlias("owned")] = "delete-me", + }; + var storage = new TizenSecureStorage(repository); + + storage.RemoveAll(); + + Assert.False(repository.Contains(TizenSecureStorage.ToAlias("owned"))); + Assert.Equal("legacy-value", repository["legacy-token"]); + Assert.Equal("leave-me", repository["unrelated"]); + } + + [Fact] + public async Task SecureStorageMigrationFailureLeavesLegacyDataIntact() + { + var repository = new FakeSecureRepository + { + ["token"] = "legacy-value", + SaveException = new InvalidOperationException("save failed"), + }; + var storage = new TizenSecureStorage(repository); + + var exception = await Assert.ThrowsAsync(() => storage.GetAsync("token")); + + Assert.Equal("save failed", exception.Message); + Assert.Equal("legacy-value", repository["token"]); + Assert.False(repository.Contains(TizenSecureStorage.ToAlias("token"))); + } + + // ------------------------------------------------------------------------------------------- + // TextToSpeech cancellation. + // ------------------------------------------------------------------------------------------- + + [Fact] + public async Task TextToSpeechPreCancellationUsesTheCallerToken() + { + using var source = new CancellationTokenSource(); + source.Cancel(); + using var textToSpeech = new TizenTextToSpeech(); + + var exception = await Assert.ThrowsAnyAsync( + () => textToSpeech.SpeakAsync("cancelled", cancelToken: source.Token)); + + Assert.Equal(source.Token, exception.CancellationToken); + } + + [Fact] + public async Task TextToSpeechInFlightCancellationUsesTheCallerToken() + { + using var source = new CancellationTokenSource(); + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var stopped = false; + var cancellationWonBeforeStop = false; + + TizenTextToSpeech.CancelUtterance(utterance, source.Token, () => + { + cancellationWonBeforeStop = utterance.Task.IsCanceled; + stopped = true; + }); + + var exception = await Assert.ThrowsAnyAsync(() => utterance.Task); + + Assert.True(stopped); + Assert.True(cancellationWonBeforeStop); + Assert.Equal(source.Token, exception.CancellationToken); + } + // ------------------------------------------------------------------------------------------- // Screenshot pixel-format handling. // ------------------------------------------------------------------------------------------- @@ -282,4 +391,48 @@ public void TreatsOnlyConnectedTransportsAsActive() Assert.False(TizenConnectivity.IsConnected(TizenConnectionState.Disconnected)); Assert.False(TizenConnectivity.IsConnected(TizenConnectionState.Deactivated)); } + + sealed class FakeSecureRepository : ITizenSecureRepository + { + readonly Dictionary _values = new(StringComparer.Ordinal); + + public Exception? SaveException { get; init; } + + public string this[string alias] + { + get => Encoding.UTF8.GetString(_values[alias]); + set => _values[alias] = Encoding.UTF8.GetBytes(value); + } + + public void Add(string alias, string value) => + _values.Add(alias, Encoding.UTF8.GetBytes(value)); + + public bool Contains(string alias) => + _values.ContainsKey(alias); + + public byte[] Get(string alias) => + _values.TryGetValue(alias, out var value) + ? value + : throw new InvalidOperationException("alias not found"); + + public void Save(string alias, byte[] value) + { + if (SaveException is not null) + throw SaveException; + + if (_values.ContainsKey(alias)) + throw new InvalidOperationException("alias already exists"); + + _values.Add(alias, value); + } + + public void RemoveAlias(string alias) + { + if (!_values.Remove(alias)) + throw new InvalidOperationException("alias not found"); + } + + public IEnumerable GetAliases() => + _values.Keys.ToArray(); + } } From 3fc6ff3868296a6e68cf5e2469f7caf9a41b4303 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 02:16:16 -0400 Subject: [PATCH 08/21] Harden Essentials platform contracts Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/migration.md | 14 ++ docs/tizen-essentials-service-coverage.md | 2 +- eng/build-workload-free.sh | 2 +- .../Connectivity/TizenConnectivity.cs | 70 +++++-- .../Contacts/TizenContacts.cs | 31 ++- .../Launcher/TizenLauncher.cs | 4 +- .../Preferences/TizenPreferences.cs | 175 ++++++++++++---- .../TextToSpeech/TizenTextToSpeech.cs | 102 +++++++-- .../Types/TizenSensorBase.cs | 58 ++++-- .../Types/TizenSensors.cs | 59 +++++- .../Types/TizenStorageKeyEncoding.cs | 36 +++- .../TizenServiceBehaviorTests.cs | 195 +++++++++++++++++- .../TizenTranslationTests.cs | 20 +- 13 files changed, 633 insertions(+), 135 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index 884c99da..bef18749 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -78,6 +78,20 @@ old SecureStorage raw alias from certificates, keys, or another component's data repository. Applications that need eager migration must enumerate their own known SecureStorage keys and call `GetAsync` for each one before calling `RemoveAll`. +### Preferences data migration + +Preferences now use a versioned `maui.tizen.preferences:v2:` physical namespace with distinct +default-store and named-store prefixes. This fixes two collisions in the old flat layout: a default +key such as `a~b` could alias named store `a`, key `b`, and clearing the default store called Tizen's +application-wide `RemoveAll`, deleting every named store too. + +Reads prefer the v2 key and fall back to the exact legacy alias used by the in-box backend and the +first standalone package revision. A successful legacy read copies the value into v2. The old alias +is intentionally retained because the legacy layout is ambiguous: deleting `a~b` cannot prove +whether it belonged to the default store or a named store. Explicit per-key `Remove`/null `Set` +removes the requested legacy candidates; `Clear` removes only the selected store's unambiguous v2 +entries and never performs a native global clear. + ### Target contract provenance The `tizen11.0` / API15 contract is **verified from Samsung workload PR #310**, not diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index ce8539d8..6f181b7a 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (290 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (302 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 6a3fd0b1..e93338e6 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=290 + ESSENTIALS_TESTS_MINIMUM=302 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs index f1df264d..426a7cd4 100644 --- a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs +++ b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs @@ -27,14 +27,7 @@ public NetworkAccess NetworkAccess { TizenPermissions.EnsureDeclared(); - return TizenConnectionManager.CurrentConnection.Type switch - { - TizenConnectionType.WiFi or - TizenConnectionType.Cellular or - TizenConnectionType.Ethernet or - TizenConnectionType.Bluetooth => NetworkAccess.Internet, - _ => NetworkAccess.None, - }; + return GetNetworkAccess(static () => TizenConnectionManager.CurrentConnection.Type); } } @@ -60,22 +53,59 @@ public IEnumerable ConnectionProfiles } internal static List GetConnectionProfiles() + => GetConnectionProfiles( + static () => IsConnected(TizenConnectionManager.WiFiState), + static () => TizenConnectionManager.CellularState == TizenCellularState.Connected, + static () => IsConnected(TizenConnectionManager.EthernetState), + static () => IsConnected(TizenConnectionManager.BluetoothState)); + + internal static List GetConnectionProfiles( + Func isWiFiConnected, + Func isCellularConnected, + Func isEthernetConnected, + Func isBluetoothConnected) { var profiles = new List(4); - if (IsConnected(TizenConnectionManager.WiFiState)) - profiles.Add(ConnectionProfile.WiFi); - - if (TizenConnectionManager.CellularState == TizenCellularState.Connected) - profiles.Add(ConnectionProfile.Cellular); + TryAddProfile(profiles, ConnectionProfile.WiFi, isWiFiConnected); + TryAddProfile(profiles, ConnectionProfile.Cellular, isCellularConnected); + TryAddProfile(profiles, ConnectionProfile.Ethernet, isEthernetConnected); + TryAddProfile(profiles, ConnectionProfile.Bluetooth, isBluetoothConnected); - if (IsConnected(TizenConnectionManager.EthernetState)) - profiles.Add(ConnectionProfile.Ethernet); + return profiles; + } - if (IsConnected(TizenConnectionManager.BluetoothState)) - profiles.Add(ConnectionProfile.Bluetooth); + internal static NetworkAccess GetNetworkAccess(Func getConnectionType) + { + try + { + return getConnectionType() switch + { + TizenConnectionType.WiFi or + TizenConnectionType.Cellular or + TizenConnectionType.Ethernet or + TizenConnectionType.Bluetooth or + TizenConnectionType.NetProxy => NetworkAccess.Internet, + _ => NetworkAccess.None, + }; + } + catch (Exception) + { + return NetworkAccess.None; + } + } - return profiles; + static void TryAddProfile(List profiles, ConnectionProfile profile, Func isConnected) + { + try + { + if (isConnected()) + profiles.Add(profile); + } + catch (Exception) + { + // A transport can be unsupported on a device profile; probe the others independently. + } } internal static bool IsConnected(TizenConnectionState state) => @@ -138,7 +168,9 @@ void StopListeners() void OnConnectionTypeChanged(object? sender, TizenConnectionTypeEventArgs e) { // Snapshot on the native callback thread, then raise on the main thread. - var args = new ConnectivityChangedEventArgs(NetworkAccess, GetConnectionProfiles()); + var args = new ConnectivityChangedEventArgs( + GetNetworkAccess(static () => TizenConnectionManager.CurrentConnection.Type), + GetConnectionProfiles()); MainThread.BeginInvokeOnMainThread(() => { diff --git a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs index 30e89591..52dc3fe1 100644 --- a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs +++ b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs @@ -53,9 +53,11 @@ public sealed class TizenContacts : IContacts if (int.TryParse(contactId, out var id)) { - var record = Manager.Value.Database.Get(TizenContact.Uri, id); - if (record is not null) - contact = ToContact(record); + CompleteLookup( + tcs, + () => Manager.Value.Database.Get(TizenContact.Uri, id), + ToContact); + return; } } @@ -109,13 +111,13 @@ public async Task> GetAllAsync(CancellationToken cancellati static Contact ToContact(ContactsRecord contactsRecord) { - var nameRecord = contactsRecord.GetChildRecord(TizenContact.Name, 0); + using var nameRecord = contactsRecord.GetChildRecord(TizenContact.Name, 0); var phones = new List(); var phoneCount = contactsRecord.GetChildRecordCount(TizenContact.Number); for (var i = 0; i < phoneCount; i++) { - var numberRecord = contactsRecord.GetChildRecord(TizenContact.Number, i); + using var numberRecord = contactsRecord.GetChildRecord(TizenContact.Number, i); phones.Add(new ContactPhone(numberRecord.Get(TizenNumberView.NumberData))); } @@ -123,7 +125,7 @@ static Contact ToContact(ContactsRecord contactsRecord) var emailCount = contactsRecord.GetChildRecordCount(TizenContact.Email); for (var i = 0; i < emailCount; i++) { - var emailRecord = contactsRecord.GetChildRecord(TizenContact.Email, i); + using var emailRecord = contactsRecord.GetChildRecord(TizenContact.Email, i); emails.Add(new ContactEmail(emailRecord.Get(TizenEmailView.Address))); } @@ -137,5 +139,22 @@ static Contact ToContact(ContactsRecord contactsRecord) phones, emails); } + + internal static void CompleteLookup( + TaskCompletionSource completion, + Func lookup, + Func project) + where TRecord : class, IDisposable + { + try + { + using var record = lookup(); + completion.TrySetResult(record is null ? null : project(record)); + } + catch (Exception ex) + { + completion.TrySetException(ex); + } + } } } diff --git a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs index 3c76ae79..314abf06 100644 --- a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs +++ b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs @@ -110,7 +110,7 @@ static bool HasHandler(TizenAppControl appControl) } } - static string GetOperation(Uri uri) + internal static string GetOperation(Uri uri) { var absoluteUri = uri.AbsoluteUri; @@ -125,7 +125,7 @@ static string GetOperation(Uri uri) if (absoluteUri.StartsWith("tel:", StringComparison.OrdinalIgnoreCase)) return TizenAppControlOperations.Dial; - return TizenAppControlOperations.ShareText; + return TizenAppControlOperations.View; } } } diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs index 9af4dc5b..35fa7f73 100644 --- a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Maui.Storage; @@ -17,6 +18,20 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials public sealed class TizenPreferences : IPreferences { static readonly object Locker = new(); + readonly ITizenPreferencesStore _store; + + /// + /// Creates a preferences service backed by Tizen's application preference store. + /// + public TizenPreferences() + : this(TizenPreferencesStore.Instance) + { + } + + internal TizenPreferences(ITizenPreferencesStore store) + { + _store = store; + } /// public bool ContainsKey(string key, string? sharedName = null) @@ -24,7 +39,12 @@ public bool ContainsKey(string key, string? sharedName = null) ArgumentNullException.ThrowIfNull(key); lock (Locker) - return TizenPreference.Contains(GetFullKey(key, sharedName)); + { + if (_store.Contains(GetFullKey(key, sharedName))) + return true; + + return TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName).Any(_store.Contains); + } } /// @@ -35,8 +55,14 @@ public void Remove(string key, string? sharedName = null) lock (Locker) { var fullKey = GetFullKey(key, sharedName); - if (TizenPreference.Contains(fullKey)) - TizenPreference.Remove(fullKey); + if (_store.Contains(fullKey)) + _store.Remove(fullKey); + + foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) + { + if (_store.Contains(legacyKey)) + _store.Remove(legacyKey); + } } } @@ -50,16 +76,10 @@ public void Clear(string? sharedName = null) { lock (Locker) { - if (string.IsNullOrEmpty(sharedName)) - { - TizenPreference.RemoveAll(); - return; - } + var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix(sharedName ?? string.Empty); - var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix(sharedName); - - foreach (var key in TizenPreference.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) - TizenPreference.Remove(key); + foreach (var key in _store.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + _store.Remove(key); } } @@ -70,24 +90,9 @@ public void Set(string key, T value, string? sharedName = null) lock (Locker) { - var fullKey = GetFullKey(key, sharedName); - - switch (value) - { - case null: - if (TizenPreference.Contains(fullKey)) - TizenPreference.Remove(fullKey); - break; - case DateTime dateTime: - TizenPreference.Set(fullKey, dateTime.ToBinary()); - break; - case DateTimeOffset dateTimeOffset: - TizenPreference.Set(fullKey, dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); - break; - default: - TizenPreference.Set(fullKey, value); - break; - } + SetCore(GetFullKey(key, sharedName), value); + if (value is null) + RemoveLegacyKeys(key, sharedName); } } @@ -100,29 +105,109 @@ public T Get(string key, T defaultValue, string? sharedName = null) { var fullKey = GetFullKey(key, sharedName); - if (!TizenPreference.Contains(fullKey)) - return defaultValue; - - if (typeof(T) == typeof(DateTime)) - return (T)(object)DateTime.FromBinary(TizenPreference.Get(fullKey)); + if (_store.Contains(fullKey)) + return GetCore(fullKey, defaultValue); - if (typeof(T) == typeof(DateTimeOffset)) + foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) { - var saved = TizenPreference.Get(fullKey); - return DateTimeOffset.TryParse( - saved, - CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind, - out var parsed) - ? (T)(object)parsed - : defaultValue; + if (!_store.Contains(legacyKey)) + continue; + + var value = GetCore(legacyKey, defaultValue); + SetCore(fullKey, value); + return value; } - return TizenPreference.Get(fullKey); + return defaultValue; + } + } + + void SetCore(string fullKey, T value) + { + switch (value) + { + case null: + if (_store.Contains(fullKey)) + _store.Remove(fullKey); + break; + case DateTime dateTime: + _store.Set(fullKey, dateTime.ToBinary()); + break; + case DateTimeOffset dateTimeOffset: + _store.Set(fullKey, dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); + break; + default: + _store.Set(fullKey, value); + break; + } + } + + T GetCore(string fullKey, T defaultValue) + { + if (typeof(T) == typeof(DateTime)) + return (T)(object)DateTime.FromBinary(_store.Get(fullKey)); + + if (typeof(T) == typeof(DateTimeOffset)) + { + var saved = _store.Get(fullKey); + return DateTimeOffset.TryParse( + saved, + CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, + out var parsed) + ? (T)(object)parsed + : defaultValue; + } + + return _store.Get(fullKey); + } + + void RemoveLegacyKeys(string key, string? sharedName) + { + foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) + { + if (_store.Contains(legacyKey)) + _store.Remove(legacyKey); } } internal static string GetFullKey(string key, string? sharedName) => TizenStorageKeyEncoding.GetFullKey(key, sharedName); } + + internal interface ITizenPreferencesStore + { + IEnumerable Keys { get; } + + bool Contains(string key); + + void Remove(string key); + + void Set(string key, T value); + + T Get(string key); + } + + sealed class TizenPreferencesStore : ITizenPreferencesStore + { + public static TizenPreferencesStore Instance { get; } = new(); + + TizenPreferencesStore() + { + } + + public IEnumerable Keys => TizenPreference.Keys; + + public bool Contains(string key) => + TizenPreference.Contains(key); + + public void Remove(string key) => + TizenPreference.Remove(key); + + public void Set(string key, T value) => + TizenPreference.Set(key, value); + + public T Get(string key) => + TizenPreference.Get(key); + } } diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index dda15ed1..ce9e0d83 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -26,6 +26,7 @@ public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable TtsClient? _client; Task? _initialization; + TaskCompletionSource? _readiness; TaskCompletionSource? _utterance; bool _disposed; @@ -130,17 +131,25 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati _utterance = utterance; using var registration = cancelToken.Register(() => - CancelUtterance(utterance, cancelToken, () => StopQuietly(client))); + CancelUtterance(utterance, cancelToken, () => InvalidateClient(client))); - var (resolvedLanguage, voiceType) = ResolveVoice(client, language); + try + { + cancelToken.ThrowIfCancellationRequested(); - client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); + var (resolvedLanguage, voiceType) = ResolveVoice(client, language); + client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); - // One last check: the registration above only fires for cancellation that happens - // after it is created, so a token cancelled in between would otherwise still play. - cancelToken.ThrowIfCancellationRequested(); + // Clear any text queued by a cancellation racing AddText before playback starts. + cancelToken.ThrowIfCancellationRequested(); - client.Play(); + client.Play(); + } + catch (Exception) when (cancelToken.IsCancellationRequested) + { + cancelToken.ThrowIfCancellationRequested(); + throw; + } await utterance.Task.ConfigureAwait(false); } @@ -157,7 +166,14 @@ internal static void CancelUtterance( Action stop) { utterance.TrySetCanceled(cancelToken); - stop(); + try + { + stop(); + } + catch (Exception) + { + // Cancellation has already won the task contract. + } } static void StopQuietly(TtsClient client) @@ -261,9 +277,12 @@ Task PrepareAsync() { var client = new TtsClient(); var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cleanedUp = 0; + _readiness = ready; client.StateChanged += OnStateChanged; client.UtteranceCompleted += OnUtteranceCompleted; + client.ErrorOccurred += OnErrorOccurred; try { @@ -271,9 +290,7 @@ Task PrepareAsync() } catch (Exception) { - client.StateChanged -= OnStateChanged; - client.UtteranceCompleted -= OnUtteranceCompleted; - client.Dispose(); + CleanupClient(); throw; } @@ -293,6 +310,15 @@ void OnUtteranceCompleted(object? sender, UtteranceEventArgs e) _utterance?.TrySetResult(true); } + void OnErrorOccurred(object? sender, ErrorOccurredEventArgs e) + { + var exception = new InvalidOperationException( + $"Tizen text-to-speech failed ({e.ErrorValue}): {e.ErrorMessage}"); + + FailPendingTasks(ready, _utterance, exception); + CleanupClient(); + } + async Task AwaitReadyAsync() { try @@ -302,18 +328,52 @@ async Task AwaitReadyAsync() } catch (Exception) { - client.StateChanged -= OnStateChanged; - client.UtteranceCompleted -= OnUtteranceCompleted; - client.Dispose(); + CleanupClient(); + throw; + } + } - if (ReferenceEquals(_client, client)) - _client = null; + void CleanupClient() + { + if (Interlocked.Exchange(ref cleanedUp, 1) != 0) + return; - throw; + client.StateChanged -= OnStateChanged; + client.UtteranceCompleted -= OnUtteranceCompleted; + client.ErrorOccurred -= OnErrorOccurred; + + if (ReferenceEquals(_client, client)) + { + _client = null; + _initialization = null; } + if (ReferenceEquals(_readiness, ready)) + _readiness = null; + + client.Dispose(); } } + void InvalidateClient(TtsClient client) + { + if (ReferenceEquals(_client, client)) + { + _client = null; + _initialization = null; + } + + client.Dispose(); + } + + internal static void FailPendingTasks( + TaskCompletionSource? readiness, + TaskCompletionSource? utterance, + Exception exception) + { + readiness?.TrySetException(exception); + utterance?.TrySetException(exception); + } + /// public void Dispose() { @@ -321,11 +381,15 @@ public void Dispose() return; _disposed = true; + FailPendingTasks( + _readiness, + _utterance, + new ObjectDisposedException(nameof(TizenTextToSpeech))); + _client?.Dispose(); _client = null; _initialization = null; - _speakLock.Dispose(); - _initializeLock.Dispose(); + _readiness = null; } } } diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs index c704149a..b1c4b894 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs @@ -93,6 +93,7 @@ public void Start(SensorSpeed sensorSpeed) var sensor = Sensor; var subscribed = false; + var started = false; try { @@ -102,31 +103,52 @@ public void Start(SensorSpeed sensorSpeed) subscribed = true; sensor.Start(); + started = true; + + OnStarted(); + + UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; + IsMonitoring = true; } catch { - // Roll the whole attempt back. Leaving the handler attached would double-raise - // every reading after a later successful Start. - if (subscribed) - { - try - { - Unsubscribe(sensor); - } - catch - { - // Nothing further can be done; surface the original failure. - } - } - + RollbackFailedStart( + started, + subscribed, + () => sensor.Stop(), + () => Unsubscribe(sensor), + () => TizenSensors.ResetDefaultSensor(sensor)); throw; } - - UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; - IsMonitoring = true; } + } + + internal static void RollbackFailedStart( + bool started, + bool subscribed, + Action stop, + Action unsubscribe, + Action reset) + { + if (subscribed) + TryRollback(unsubscribe); - OnStarted(); + if (started) + TryRollback(stop); + + TryRollback(reset); + } + + static void TryRollback(Action action) + { + try + { + action(); + } + catch (Exception) + { + // Preserve the failure that caused the rollback. + } } /// diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensors.cs b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs index 3f7ae9ce..c4db3ccb 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenSensors.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs @@ -44,12 +44,12 @@ public enum TizenSensorType /// public static class TizenSensors { - static readonly Lazy AccelerometerSensor = new(static () => new TizenAccelerometerSensor()); - static readonly Lazy BarometerSensor = new(static () => new TizenPressureSensor()); - static readonly Lazy CompassSensor = new(static () => new TizenNativeOrientationSensor()); - static readonly Lazy GyroscopeSensor = new(static () => new TizenGyroscopeSensor()); - static readonly Lazy MagnetometerSensor = new(static () => new TizenMagnetometerSensor()); - static readonly Lazy RotationVectorSensor = new(static () => new TizenRotationVectorSensor()); + static readonly ResettableSensor AccelerometerSensor = new(static () => new TizenAccelerometerSensor()); + static readonly ResettableSensor BarometerSensor = new(static () => new TizenPressureSensor()); + static readonly ResettableSensor CompassSensor = new(static () => new TizenNativeOrientationSensor()); + static readonly ResettableSensor GyroscopeSensor = new(static () => new TizenGyroscopeSensor()); + static readonly ResettableSensor MagnetometerSensor = new(static () => new TizenMagnetometerSensor()); + static readonly ResettableSensor RotationVectorSensor = new(static () => new TizenRotationVectorSensor()); /// /// Gets the shared native sensor instance for the requested type. @@ -67,6 +67,53 @@ public static TizenSensor GetDefaultSensor(TizenSensorType type) => TizenSensorType.OrientationSensor => RotationVectorSensor.Value, _ => throw new ArgumentOutOfRangeException(nameof(type), type, "Unknown Tizen sensor type."), }; + + internal static void ResetDefaultSensor(TizenSensor sensor) + { + if (AccelerometerSensor.Reset(sensor) || + BarometerSensor.Reset(sensor) || + CompassSensor.Reset(sensor) || + GyroscopeSensor.Reset(sensor) || + MagnetometerSensor.Reset(sensor) || + RotationVectorSensor.Reset(sensor)) + { + sensor.Dispose(); + } + } + + sealed class ResettableSensor + where TSensor : TizenSensor + { + readonly object _locker = new(); + readonly Func _factory; + TSensor? _value; + + public ResettableSensor(Func factory) + { + _factory = factory; + } + + public TSensor Value + { + get + { + lock (_locker) + return _value ??= _factory(); + } + } + + public bool Reset(TizenSensor sensor) + { + lock (_locker) + { + if (!ReferenceEquals(_value, sensor)) + return false; + + _value = null; + return true; + } + } + } } /// diff --git a/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs index 4ba40cc9..4c0e3b4f 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text; namespace Microsoft.Maui.Platforms.Tizen.Essentials @@ -20,14 +21,18 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// prefix. /// /// - /// The separator is therefore escaped inside each component before joining, which makes the - /// encoding injective: distinct (shared name, key) pairs always produce distinct strings. + /// Each store kind has a versioned prefix, and the separator is escaped inside named-store + /// components before joining. The result is injective across default and named stores as well as + /// within each named store. /// /// public static class TizenStorageKeyEncoding { const char Separator = '~'; const char Escape = '\\'; + const string VersionPrefix = "maui.tizen.preferences:v2:"; + const string DefaultStorePrefix = VersionPrefix + "d:"; + const string NamedStorePrefix = VersionPrefix + "n:"; /// /// Encodes a single component so it can be joined with unambiguously. @@ -65,13 +70,10 @@ public static string GetFullKey(string key, string? sharedName) { ArgumentNullException.ThrowIfNull(key); - // No shared name means the key is used verbatim, which preserves compatibility with - // entries written by the in-box dotnet/maui Tizen backend for the default store - the - // overwhelmingly common case. if (string.IsNullOrEmpty(sharedName)) - return key; + return DefaultStorePrefix + Encode(key); - return string.Concat(Encode(sharedName), Separator.ToString(), Encode(key)); + return string.Concat(NamedStorePrefix, Encode(sharedName), Separator.ToString(), Encode(key)); } /// @@ -87,7 +89,25 @@ public static string GetSharedNamePrefix(string sharedName) { ArgumentNullException.ThrowIfNull(sharedName); - return Encode(sharedName) + Separator; + return string.IsNullOrEmpty(sharedName) + ? DefaultStorePrefix + : NamedStorePrefix + Encode(sharedName) + Separator; + } + + internal static IEnumerable GetLegacyKeys(string key, string? sharedName) + { + if (string.IsNullOrEmpty(sharedName)) + { + yield return key; + yield break; + } + + var escaped = string.Concat(Encode(sharedName), Separator.ToString(), Encode(key)); + yield return escaped; + + var raw = string.Concat(sharedName, Separator.ToString(), key); + if (!string.Equals(raw, escaped, StringComparison.Ordinal)) + yield return raw; } } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 5e402282..bea001ef 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -5,7 +5,9 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; using Microsoft.Maui.Devices; +using Microsoft.Maui.Networking; using Microsoft.Maui.Platforms.Tizen.Essentials; using Xunit; using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; @@ -102,13 +104,14 @@ from key in components } [Fact] - public void DefaultStoreKeysAreUnprefixedForCompatibility() + public void DefaultAndNamedStoreKeysCannotCollide() { - // Entries written by the in-box dotnet/maui Tizen backend for the default store used the - // raw key, so changing that would strand existing data. - Assert.Equal("key", TizenStorageKeyEncoding.GetFullKey("key", null)); - Assert.Equal("key", TizenStorageKeyEncoding.GetFullKey("key", string.Empty)); - Assert.Equal("key", TizenPreferences.GetFullKey("key", null)); + var defaultKey = TizenStorageKeyEncoding.GetFullKey("a~b", null); + var namedKey = TizenStorageKeyEncoding.GetFullKey("b", "a"); + + Assert.NotEqual(defaultKey, namedKey); + Assert.StartsWith("maui.tizen.preferences:v2:d:", defaultKey, StringComparison.Ordinal); + Assert.StartsWith("maui.tizen.preferences:v2:n:", namedKey, StringComparison.Ordinal); } [Fact] @@ -125,6 +128,58 @@ public void ClearingASharedNameCannotMatchADifferentSharedName() Assert.StartsWith(prefix, TizenStorageKeyEncoding.GetFullKey("c", "a"), StringComparison.Ordinal); } + [Fact] + public void ClearingDefaultPreferencesLeavesNamedAndLegacyEntriesAlone() + { + var store = new FakePreferencesStore + { + [TizenPreferences.GetFullKey("default", null)] = "delete-me", + [TizenPreferences.GetFullKey("named", "shared")] = "keep-me", + ["legacy-default"] = "keep-conservatively", + ["shared~legacy"] = "keep-conservatively", + }; + var preferences = new TizenPreferences(store); + + preferences.Clear(); + + Assert.False(store.Contains(TizenPreferences.GetFullKey("default", null))); + Assert.Equal("keep-me", store[TizenPreferences.GetFullKey("named", "shared")]); + Assert.Equal("keep-conservatively", store["legacy-default"]); + Assert.Equal("keep-conservatively", store["shared~legacy"]); + } + + [Fact] + public void PreferencesReadAndMigrateLegacyDefaultAndNamedEntries() + { + var store = new FakePreferencesStore + { + ["legacy-default"] = "default-value", + ["shared~legacy-named"] = "named-value", + }; + var preferences = new TizenPreferences(store); + + Assert.Equal("default-value", preferences.Get("legacy-default", "missing")); + Assert.Equal("named-value", preferences.Get("legacy-named", "missing", "shared")); + Assert.Equal("default-value", store["legacy-default"]); + Assert.Equal("named-value", store["shared~legacy-named"]); + Assert.Equal("default-value", store[TizenPreferences.GetFullKey("legacy-default", null)]); + Assert.Equal("named-value", store[TizenPreferences.GetFullKey("legacy-named", "shared")]); + } + + [Fact] + public void PreferencesPreferVersionedEntriesOverLegacyAliases() + { + var store = new FakePreferencesStore + { + ["token"] = "legacy-value", + [TizenPreferences.GetFullKey("token", null)] = "new-value", + }; + var preferences = new TizenPreferences(store); + + Assert.Equal("new-value", preferences.Get("token", "missing")); + Assert.Equal("legacy-value", store["token"]); + } + // ------------------------------------------------------------------------------------------- // SecureStorage alias namespacing. // ------------------------------------------------------------------------------------------- @@ -273,6 +328,37 @@ public async Task TextToSpeechInFlightCancellationUsesTheCallerToken() Assert.Equal(source.Token, exception.CancellationToken); } + [Fact] + public async Task TextToSpeechAsyncErrorsFaultReadinessAndPlayback() + { + var readiness = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var failure = new InvalidOperationException("native failure"); + + TizenTextToSpeech.FailPendingTasks(readiness, utterance, failure); + + Assert.Same(failure, await Assert.ThrowsAsync(() => readiness.Task)); + Assert.Same(failure, await Assert.ThrowsAsync(() => utterance.Task)); + } + + [Fact] + public async Task TextToSpeechDisposalSettlesAllPendingTasks() + { + var readiness = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var textToSpeech = new TizenTextToSpeech(); + + typeof(TizenTextToSpeech).GetField("_readiness", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(textToSpeech, readiness); + typeof(TizenTextToSpeech).GetField("_utterance", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(textToSpeech, utterance); + + textToSpeech.Dispose(); + + await Assert.ThrowsAsync(() => readiness.Task); + await Assert.ThrowsAsync(() => utterance.Task); + } + // ------------------------------------------------------------------------------------------- // Screenshot pixel-format handling. // ------------------------------------------------------------------------------------------- @@ -392,6 +478,70 @@ public void TreatsOnlyConnectedTransportsAsActive() Assert.False(TizenConnectivity.IsConnected(TizenConnectionState.Deactivated)); } + [Fact] + public void ConnectivityProbesUnsupportedTransportsIndependently() + { + var profiles = TizenConnectivity.GetConnectionProfiles( + static () => throw new PlatformNotSupportedException("No Wi-Fi"), + static () => true, + static () => throw new InvalidOperationException("No Ethernet"), + static () => true); + + Assert.Equal([ConnectionProfile.Cellular, ConnectionProfile.Bluetooth], profiles); + } + + [Fact] + public void ConnectivityReturnsNoneWhenCurrentTransportCannotBeQueried() => + Assert.Equal( + NetworkAccess.None, + TizenConnectivity.GetNetworkAccess( + static () => throw new PlatformNotSupportedException("Unsupported device profile"))); + + [Fact] + public async Task ContactLookupDisposesTheOwningRecord() + { + var record = new FakeContactRecord(); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + TizenContacts.CompleteLookup(completion, () => record, static _ => new Contact()); + + Assert.NotNull(await completion.Task); + Assert.True(record.Disposed); + } + + [Fact] + public async Task ContactProjectionFailureDisposesTheRecordAndFaultsTheTask() + { + var record = new FakeContactRecord(); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var failure = new InvalidOperationException("projection failed"); + + TizenContacts.CompleteLookup( + completion, + () => record, + _ => throw failure); + + Assert.Same(failure, await Assert.ThrowsAsync(() => completion.Task)); + Assert.True(record.Disposed); + } + + [Fact] + public void SensorStartRollbackResetsEvenWhenCleanupFails() + { + var stopped = false; + var reset = false; + + TizenSensorBase.RollbackFailedStart( + started: true, + subscribed: true, + stop: () => stopped = true, + unsubscribe: static () => throw new InvalidOperationException("unsubscribe failed"), + reset: () => reset = true); + + Assert.True(stopped); + Assert.True(reset); + } + sealed class FakeSecureRepository : ITizenSecureRepository { readonly Dictionary _values = new(StringComparer.Ordinal); @@ -435,4 +585,37 @@ public void RemoveAlias(string alias) public IEnumerable GetAliases() => _values.Keys.ToArray(); } + + sealed class FakePreferencesStore : ITizenPreferencesStore + { + readonly Dictionary _values = new(StringComparer.Ordinal); + + public IEnumerable Keys => _values.Keys.ToArray(); + + public object? this[string key] + { + get => _values[key]; + set => _values[key] = value; + } + + public bool Contains(string key) => + _values.ContainsKey(key); + + public void Remove(string key) => + _values.Remove(key); + + public void Set(string key, T value) => + _values[key] = value; + + public T Get(string key) => + (T)_values[key]!; + } + + sealed class FakeContactRecord : IDisposable + { + public bool Disposed { get; private set; } + + public void Dispose() => + Disposed = true; + } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs index ea624e99..73dd132a 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs @@ -10,6 +10,7 @@ using TizenConnectionType = Tizen.Network.Connection.ConnectionType; using TizenDeviceOrientation = Tizen.Applications.DeviceOrientation; using TizenPixelFormat = Tizen.NUI.PixelFormat; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; namespace Maui.Tizen.Essentials.Tests; @@ -73,9 +74,9 @@ public void MapsHapticFeedbackTypes(HapticFeedbackType type, string expected) => Assert.Equal(expected, TizenHapticFeedback.ConvertType(type)); [Theory] - [InlineData(null, "key", "key")] - [InlineData("", "key", "key")] - [InlineData("shared", "key", "shared~key")] + [InlineData(null, "key", "maui.tizen.preferences:v2:d:key")] + [InlineData("", "key", "maui.tizen.preferences:v2:d:key")] + [InlineData("shared", "key", "maui.tizen.preferences:v2:n:shared~key")] public void PrefixesSharedPreferenceKeys(string? sharedName, string key, string expected) => Assert.Equal(expected, TizenPreferences.GetFullKey(key, sharedName)); @@ -89,10 +90,21 @@ public void MapsConnectionProfiles(TizenConnectionType type, ConnectionProfile e [Theory] [InlineData(TizenConnectionType.Disconnected)] - [InlineData(TizenConnectionType.NetProxy)] public void MapsUnknownConnectionTypesToNoProfile(TizenConnectionType type) => Assert.Null(TizenConnectivity.MapProfileType(type)); + [Fact] + public void MapsNetProxyToInternetAccess() => + Assert.Equal( + NetworkAccess.Internet, + TizenConnectivity.GetNetworkAccess(static () => TizenConnectionType.NetProxy)); + + [Theory] + [InlineData("custom://resource")] + [InlineData("unknown:value")] + public void UsesViewOperationForCustomUriSchemes(string uri) => + Assert.Equal(TizenAppControlOperations.View, TizenLauncher.GetOperation(new Uri(uri))); + [Theory] [InlineData(TizenDeviceOrientation.Orientation_0, DisplayRotation.Rotation0, DisplayOrientation.Portrait)] [InlineData(TizenDeviceOrientation.Orientation_90, DisplayRotation.Rotation90, DisplayOrientation.Landscape)] From 36d9ab3a26f7c5c0428dbee36750e88c30153d91 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 09:10:45 -0400 Subject: [PATCH 09/21] Prevent legacy storage resurrection Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/migration.md | 23 +- docs/tizen-essentials-service-coverage.md | 2 +- eng/build-workload-free.sh | 2 +- .../Preferences/TizenPreferences.cs | 35 ++- .../SecureStorage/TizenSecureStorage.cs | 226 +++++++++++------ .../Types/TizenStorageKeyEncoding.cs | 18 ++ .../TizenServiceBehaviorTests.cs | 228 ++++++++++++++++-- 7 files changed, 411 insertions(+), 123 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index bef18749..df8cc251 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -68,15 +68,15 @@ The standalone Essentials package stores secure values under the application-wide secure-repository alias space. `GetAsync` performs a one-way, per-key compatibility migration: it reads the namespaced alias first; -only when that alias is absent does it read the exact legacy raw alias, save the value under the -namespaced alias, and remove that exact raw alias. A migration save failure is surfaced and leaves -the legacy value intact. If cleanup of the raw alias fails after the namespaced save succeeds, the -namespaced value remains authoritative. +only when that alias is absent does it read the exact legacy raw alias and save the value under the +namespaced alias. It never deletes the raw alias because the application-wide secure repository +cannot prove that alias is owned by SecureStorage. A migration save failure is surfaced and leaves +the legacy value intact. -`RemoveAll` deliberately does **not** delete raw aliases. There is no safe way to distinguish an -old SecureStorage raw alias from certificates, keys, or another component's data in the shared -repository. Applications that need eager migration must enumerate their own known SecureStorage -keys and call `GetAsync` for each one before calling `RemoveAll`. +`Remove` and `RemoveAll` delete only namespaced aliases and write tombstones in the application +preference store. Those tombstones suppress legacy fallback, so an unowned raw alias cannot +resurrect a removed SecureStorage value. There is no safe way to distinguish an old SecureStorage +raw alias from certificates, keys, or another component's data in the shared repository. ### Preferences data migration @@ -88,9 +88,10 @@ application-wide `RemoveAll`, deleting every named store too. Reads prefer the v2 key and fall back to the exact legacy alias used by the in-box backend and the first standalone package revision. A successful legacy read copies the value into v2. The old alias is intentionally retained because the legacy layout is ambiguous: deleting `a~b` cannot prove -whether it belonged to the default store or a named store. Explicit per-key `Remove`/null `Set` -removes the requested legacy candidates; `Clear` removes only the selected store's unambiguous v2 -entries and never performs a native global clear. +whether it belonged to the default store or a named store. Per-key `Remove`/null `Set` and +per-store `Clear` write v2 tombstones instead of deleting ambiguous aliases, so later reads cannot +resurrect removed data or cross-delete another logical store. `Clear` removes only the selected +store's unambiguous v2 entries and never performs a native global clear. ### Target contract provenance diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 6f181b7a..82cd1e79 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (302 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (310 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index e93338e6..08f9a98b 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=302 + ESSENTIALS_TESTS_MINIMUM=310 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs index 35fa7f73..0a09c8e4 100644 --- a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -42,6 +42,8 @@ public bool ContainsKey(string key, string? sharedName = null) { if (_store.Contains(GetFullKey(key, sharedName))) return true; + if (LegacyFallbackSuppressed(key, sharedName)) + return false; return TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName).Any(_store.Contains); } @@ -58,11 +60,7 @@ public void Remove(string key, string? sharedName = null) if (_store.Contains(fullKey)) _store.Remove(fullKey); - foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) - { - if (_store.Contains(legacyKey)) - _store.Remove(legacyKey); - } + WriteTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); } } @@ -80,6 +78,8 @@ public void Clear(string? sharedName = null) foreach (var key in _store.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) _store.Remove(key); + + WriteTombstone(TizenStorageKeyEncoding.GetStoreTombstone(sharedName)); } } @@ -92,7 +92,9 @@ public void Set(string key, T value, string? sharedName = null) { SetCore(GetFullKey(key, sharedName), value); if (value is null) - RemoveLegacyKeys(key, sharedName); + WriteTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); + else + RemoveTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); } } @@ -107,6 +109,8 @@ public T Get(string key, T defaultValue, string? sharedName = null) if (_store.Contains(fullKey)) return GetCore(fullKey, defaultValue); + if (LegacyFallbackSuppressed(key, sharedName)) + return defaultValue; foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) { @@ -162,13 +166,20 @@ T GetCore(string fullKey, T defaultValue) return _store.Get(fullKey); } - void RemoveLegacyKeys(string key, string? sharedName) + bool LegacyFallbackSuppressed(string key, string? sharedName) => + _store.Contains(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)) || + _store.Contains(TizenStorageKeyEncoding.GetStoreTombstone(sharedName)); + + void WriteTombstone(string key) + { + if (!_store.Contains(key)) + _store.Set(key, true); + } + + void RemoveTombstone(string key) { - foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) - { - if (_store.Contains(legacyKey)) - _store.Remove(legacyKey); - } + if (_store.Contains(key)) + _store.Remove(key); } internal static string GetFullKey(string key, string? sharedName) => diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 90b7b004..3b3f29d2 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -3,6 +3,7 @@ using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Storage; +using TizenPreference = Tizen.Applications.Preference; using Tizen.Security.SecureRepository; namespace Microsoft.Maui.Platforms.Tizen.Essentials @@ -26,7 +27,9 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public sealed class TizenSecureStorage : ISecureStorage { + static readonly object Locker = new(); readonly ITizenSecureRepository _repository; + readonly ITizenSecureStorageTombstones _tombstones; /// /// Prefix identifying aliases owned by this API. @@ -41,13 +44,16 @@ public sealed class TizenSecureStorage : ISecureStorage /// Creates a secure-storage service backed by Tizen's secure repository. /// public TizenSecureStorage() - : this(TizenSecureRepository.Instance) + : this(TizenSecureRepository.Instance, TizenSecureStorageTombstones.Instance) { } - internal TizenSecureStorage(ITizenSecureRepository repository) + internal TizenSecureStorage( + ITizenSecureRepository repository, + ITizenSecureStorageTombstones? tombstones = null) { _repository = repository; + _tombstones = tombstones ?? new InMemorySecureStorageTombstones(); } /// @@ -55,48 +61,42 @@ internal TizenSecureStorage(ITizenSecureRepository repository) { ArgumentNullException.ThrowIfNull(key); - try + lock (Locker) { - // The second parameter is the data password, not a default value. - return Task.FromResult(Encoding.UTF8.GetString(_repository.Get(ToAlias(key)))); - } - catch (InvalidOperationException) - { - // The namespaced alias does not exist. Try the exact raw alias used by the in-box - // backend, then migrate it one-way before returning it. - } - catch - { - global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to load data."); - throw; - } + try + { + // The second parameter is the data password, not a default value. + return Task.FromResult(Encoding.UTF8.GetString(_repository.Get(ToAlias(key)))); + } + catch (InvalidOperationException) + { + // The namespaced alias does not exist. + } + catch + { + global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to load data."); + throw; + } - byte[] legacyValue; + if (_tombstones.Contains(key) || _tombstones.ContainsAll) + return Task.FromResult(null); - try - { - legacyValue = _repository.Get(key); - } - catch (InvalidOperationException) - { - return Task.FromResult(null); - } + byte[] legacyValue; - // Save before deleting so a migration failure cannot remove the only readable copy. - _repository.Save(ToAlias(key), legacyValue); + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } - try - { - _repository.RemoveAlias(key); - } - catch - { - // The namespaced copy is now authoritative. A stale legacy alias is safe to leave - // behind and can be cleaned up by a later explicit application migration. - global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove migrated legacy data."); - } + // Raw aliases are unowned and may belong to another component. Copy, never delete. + _repository.Save(ToAlias(key), legacyValue); - return Task.FromResult(Encoding.UTF8.GetString(legacyValue)); + return Task.FromResult(Encoding.UTF8.GetString(legacyValue)); + } } /// @@ -105,29 +105,29 @@ public Task SetAsync(string key, string value) ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(value); - var alias = ToAlias(key); - - try + lock (Locker) { try { - // DataManager.Save throws when the alias already exists, and Tizen offers no - // existence probe that does not throw, so remove unconditionally first. - _repository.RemoveAlias(alias); + var alias = ToAlias(key); + try + { + _repository.RemoveAlias(alias); + } + catch + { + // Expected when the alias did not exist. + } + + _repository.Save(alias, Encoding.UTF8.GetBytes(value)); + _tombstones.Remove(key); + return Task.CompletedTask; } catch { - // Expected when the alias did not exist. + global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to save data."); + throw; } - - _repository.Save(alias, Encoding.UTF8.GetBytes(value)); - - return Task.CompletedTask; - } - catch - { - global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to save data."); - throw; } } @@ -136,15 +136,21 @@ public bool Remove(string key) { ArgumentNullException.ThrowIfNull(key); - try + lock (Locker) { - _repository.RemoveAlias(ToAlias(key)); - return true; - } - catch - { - global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove data."); - return false; + var removed = false; + try + { + _repository.RemoveAlias(ToAlias(key)); + removed = true; + } + catch + { + // Missing namespaced data is expected when only an ambiguous raw alias exists. + } + + _tombstones.Add(key); + return removed; } } @@ -155,30 +161,34 @@ public bool Remove(string key) /// public void RemoveAll() { - IEnumerable aliases; - - try - { - aliases = _repository.GetAliases(); - } - catch + lock (Locker) { - global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "No saved data."); - return; - } - - foreach (var alias in aliases) - { - if (!IsOwnedAlias(alias)) - continue; + _tombstones.AddAll(); + IEnumerable aliases; try { - _repository.RemoveAlias(alias); + aliases = _repository.GetAliases(); } catch { - global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove data."); + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "No saved data."); + return; + } + + foreach (var alias in aliases) + { + if (!IsOwnedAlias(alias)) + continue; + + try + { + _repository.RemoveAlias(alias); + } + catch + { + global::Tizen.Log.Info(TizenPlatform.CurrentPackageLogTag, "Failed to remove data."); + } } } } @@ -215,6 +225,64 @@ internal static bool IsOwnedAlias(string alias) } } + internal interface ITizenSecureStorageTombstones + { + bool ContainsAll { get; } + + bool Contains(string key); + + void Add(string key); + + void Remove(string key); + + void AddAll(); + } + + sealed class TizenSecureStorageTombstones : ITizenSecureStorageTombstones + { + const string Prefix = "maui.tizen.securestorage.tombstone:v1:"; + const string AllKey = Prefix + "all"; + + public static TizenSecureStorageTombstones Instance { get; } = new(); + + TizenSecureStorageTombstones() + { + } + + public bool ContainsAll => TizenPreference.Contains(AllKey); + + public bool Contains(string key) => + TizenPreference.Contains(Prefix + "key:" + TizenStorageKeyEncoding.Encode(key)); + + public void Add(string key) => + TizenPreference.Set(Prefix + "key:" + TizenStorageKeyEncoding.Encode(key), true); + + public void Remove(string key) + { + var tombstone = Prefix + "key:" + TizenStorageKeyEncoding.Encode(key); + if (TizenPreference.Contains(tombstone)) + TizenPreference.Remove(tombstone); + } + + public void AddAll() => + TizenPreference.Set(AllKey, true); + } + + sealed class InMemorySecureStorageTombstones : ITizenSecureStorageTombstones + { + readonly HashSet _keys = new(StringComparer.Ordinal); + + public bool ContainsAll { get; private set; } + + public bool Contains(string key) => _keys.Contains(key); + + public void Add(string key) => _keys.Add(key); + + public void Remove(string key) => _keys.Remove(key); + + public void AddAll() => ContainsAll = true; + } + internal interface ITizenSecureRepository { byte[] Get(string alias); diff --git a/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs index 4c0e3b4f..fc264e3b 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs @@ -33,6 +33,8 @@ public static class TizenStorageKeyEncoding const string VersionPrefix = "maui.tizen.preferences:v2:"; const string DefaultStorePrefix = VersionPrefix + "d:"; const string NamedStorePrefix = VersionPrefix + "n:"; + const string KeyTombstonePrefix = VersionPrefix + "tk:"; + const string StoreTombstonePrefix = VersionPrefix + "ts:"; /// /// Encodes a single component so it can be joined with unambiguously. @@ -109,5 +111,21 @@ internal static IEnumerable GetLegacyKeys(string key, string? sharedName if (!string.Equals(raw, escaped, StringComparison.Ordinal)) yield return raw; } + + internal static string GetKeyTombstone(string key, string? sharedName) => + KeyTombstonePrefix + EncodeLogicalKey(key, sharedName); + + internal static string GetStoreTombstone(string? sharedName) => + StoreTombstonePrefix + EncodeStore(sharedName); + + static string EncodeLogicalKey(string key, string? sharedName) => + string.IsNullOrEmpty(sharedName) + ? "d:" + Encode(key) + : string.Concat("n:", Encode(sharedName), Separator.ToString(), Encode(key)); + + static string EncodeStore(string? sharedName) => + string.IsNullOrEmpty(sharedName) + ? "d" + : "n:" + Encode(sharedName); } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index bea001ef..6835fb2a 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -180,6 +180,75 @@ public void PreferencesPreferVersionedEntriesOverLegacyAliases() Assert.Equal("legacy-value", store["token"]); } + [Fact] + public void PreferencesRemoveTombstonePreventsAmbiguousLegacyResurrection() + { + var store = new FakePreferencesStore + { + ["a~b"] = "ambiguous-legacy-value", + }; + var preferences = new TizenPreferences(store); + + preferences.Remove("a~b"); + + Assert.Equal("missing", preferences.Get("a~b", "missing")); + Assert.Equal("ambiguous-legacy-value", store["a~b"]); + Assert.Equal( + "ambiguous-legacy-value", + new TizenPreferences(store).Get("b", "missing", "a")); + } + + [Fact] + public void PreferencesClearTombstonePreventsStoreLegacyResurrection() + { + var store = new FakePreferencesStore + { + ["legacy-default"] = "default-value", + ["shared~legacy"] = "named-value", + }; + var preferences = new TizenPreferences(store); + + preferences.Clear(); + + Assert.Equal("missing", preferences.Get("legacy-default", "missing")); + Assert.Equal("named-value", preferences.Get("legacy", "missing", "shared")); + Assert.Equal("default-value", store["legacy-default"]); + } + + [Fact] + public void PreferencesNewValueWinsAfterStoreClearTombstone() + { + var store = new FakePreferencesStore + { + ["token"] = "legacy-value", + }; + var preferences = new TizenPreferences(store); + + preferences.Clear(); + preferences.Set("token", "new-value"); + + Assert.Equal("new-value", preferences.Get("token", "missing")); + Assert.Equal("legacy-value", store["token"]); + } + + [Fact] + public async Task ConcurrentPreferencesMigrationCreatesOneVersionedCopy() + { + var store = new FakePreferencesStore + { + ["token"] = "legacy-value", + }; + var preferences = new TizenPreferences(store); + + var values = await Task.WhenAll( + Task.Run(() => preferences.Get("token", "missing")), + Task.Run(() => preferences.Get("token", "missing"))); + + Assert.Equal(["legacy-value", "legacy-value"], values); + Assert.Equal(1, store.GetSetCount(TizenPreferences.GetFullKey("token", null))); + Assert.Equal("legacy-value", store["token"]); + } + // ------------------------------------------------------------------------------------------- // SecureStorage alias namespacing. // ------------------------------------------------------------------------------------------- @@ -236,7 +305,7 @@ public async Task SecureStorageReadsAndMigratesAnExactLegacyAlias() var value = await storage.GetAsync("token"); Assert.Equal("legacy-value", value); - Assert.False(repository.Contains("token")); + Assert.Equal("legacy-value", repository["token"]); Assert.Equal("legacy-value", repository[TizenSecureStorage.ToAlias("token")]); Assert.Equal("leave-me", repository["unrelated"]); } @@ -290,6 +359,79 @@ public async Task SecureStorageMigrationFailureLeavesLegacyDataIntact() Assert.False(repository.Contains(TizenSecureStorage.ToAlias("token"))); } + [Fact] + public async Task SecureStorageRemoveTombstoneSuppressesLegacyFallback() + { + var repository = new FakeSecureRepository + { + ["token"] = "unowned-raw-value", + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.False(storage.Remove("token")); + + Assert.Null(await storage.GetAsync("token")); + Assert.Equal("unowned-raw-value", repository["token"]); + Assert.True(tombstones.Contains("token")); + } + + [Fact] + public async Task SecureStorageRemoveAllSuppressesAllLegacyFallback() + { + var repository = new FakeSecureRepository + { + ["legacy-token"] = "unowned-raw-value", + [TizenSecureStorage.ToAlias("owned")] = "owned-value", + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + storage.RemoveAll(); + + Assert.Null(await storage.GetAsync("legacy-token")); + Assert.Equal("unowned-raw-value", repository["legacy-token"]); + Assert.False(repository.Contains(TizenSecureStorage.ToAlias("owned"))); + Assert.True(tombstones.ContainsAll); + } + + [Fact] + public async Task SecureStorageSetWinsAfterRemoveTombstone() + { + var repository = new FakeSecureRepository + { + ["token"] = "unowned-raw-value", + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + storage.Remove("token"); + await storage.SetAsync("token", "new-value"); + + Assert.Equal("new-value", await storage.GetAsync("token")); + Assert.Equal("unowned-raw-value", repository["token"]); + Assert.False(tombstones.Contains("token")); + } + + [Fact] + public async Task ConcurrentSecureStorageMigrationCreatesOneOwnedCopy() + { + var repository = new FakeSecureRepository + { + ["token"] = "legacy-value", + }; + var storage = new TizenSecureStorage(repository, new FakeSecureStorageTombstones()); + + var values = await Task.WhenAll( + Task.Run(() => storage.GetAsync("token")), + Task.Run(() => storage.GetAsync("token"))); + + Assert.Equal(["legacy-value", "legacy-value"], values); + Assert.Equal(1, repository.SuccessfulSaves); + Assert.Equal("legacy-value", repository["token"]); + Assert.Equal("legacy-value", repository[TizenSecureStorage.ToAlias("token")]); + } + // ------------------------------------------------------------------------------------------- // TextToSpeech cancellation. // ------------------------------------------------------------------------------------------- @@ -545,50 +687,92 @@ public void SensorStartRollbackResetsEvenWhenCleanupFails() sealed class FakeSecureRepository : ITizenSecureRepository { readonly Dictionary _values = new(StringComparer.Ordinal); + readonly object _locker = new(); public Exception? SaveException { get; init; } + public int SuccessfulSaves { get; private set; } public string this[string alias] { - get => Encoding.UTF8.GetString(_values[alias]); - set => _values[alias] = Encoding.UTF8.GetBytes(value); + get + { + lock (_locker) + return Encoding.UTF8.GetString(_values[alias]); + } + set + { + lock (_locker) + _values[alias] = Encoding.UTF8.GetBytes(value); + } } public void Add(string alias, string value) => _values.Add(alias, Encoding.UTF8.GetBytes(value)); - public bool Contains(string alias) => - _values.ContainsKey(alias); + public bool Contains(string alias) + { + lock (_locker) + return _values.ContainsKey(alias); + } - public byte[] Get(string alias) => - _values.TryGetValue(alias, out var value) - ? value - : throw new InvalidOperationException("alias not found"); + public byte[] Get(string alias) + { + lock (_locker) + return _values.TryGetValue(alias, out var value) + ? value + : throw new InvalidOperationException("alias not found"); + } public void Save(string alias, byte[] value) { - if (SaveException is not null) - throw SaveException; + lock (_locker) + { + if (SaveException is not null) + throw SaveException; - if (_values.ContainsKey(alias)) - throw new InvalidOperationException("alias already exists"); + if (_values.ContainsKey(alias)) + throw new InvalidOperationException("alias already exists"); - _values.Add(alias, value); + _values.Add(alias, value); + SuccessfulSaves++; + } } public void RemoveAlias(string alias) { - if (!_values.Remove(alias)) - throw new InvalidOperationException("alias not found"); + lock (_locker) + { + if (!_values.Remove(alias)) + throw new InvalidOperationException("alias not found"); + } + } + + public IEnumerable GetAliases() + { + lock (_locker) + return _values.Keys.ToArray(); } + } + + sealed class FakeSecureStorageTombstones : ITizenSecureStorageTombstones + { + readonly HashSet _keys = new(StringComparer.Ordinal); - public IEnumerable GetAliases() => - _values.Keys.ToArray(); + public bool ContainsAll { get; private set; } + + public bool Contains(string key) => _keys.Contains(key); + + public void Add(string key) => _keys.Add(key); + + public void Remove(string key) => _keys.Remove(key); + + public void AddAll() => ContainsAll = true; } sealed class FakePreferencesStore : ITizenPreferencesStore { readonly Dictionary _values = new(StringComparer.Ordinal); + readonly Dictionary _setCounts = new(StringComparer.Ordinal); public IEnumerable Keys => _values.Keys.ToArray(); @@ -604,11 +788,17 @@ public bool Contains(string key) => public void Remove(string key) => _values.Remove(key); - public void Set(string key, T value) => + public void Set(string key, T value) + { _values[key] = value; + _setCounts[key] = GetSetCount(key) + 1; + } public T Get(string key) => (T)_values[key]!; + + public int GetSetCount(string key) => + _setCounts.TryGetValue(key, out var count) ? count : 0; } sealed class FakeContactRecord : IDisposable From d7e0bae6ea35c54c815f5faa57d645821695555e Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 09:35:22 -0400 Subject: [PATCH 10/21] Serialize storage and speech lifetimes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/migration.md | 4 +- docs/tizen-essentials-service-coverage.md | 2 +- eng/build-workload-free.sh | 2 +- .../Preferences/TizenPreferences.cs | 54 +++++-- .../SecureStorage/TizenSecureStorage.cs | 59 +++++-- .../TextToSpeech/TizenTextToSpeech.cs | 49 +++--- .../TizenServiceBehaviorTests.cs | 151 +++++++++++++++++- 7 files changed, 265 insertions(+), 56 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index df8cc251..504377ac 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -76,7 +76,9 @@ the legacy value intact. `Remove` and `RemoveAll` delete only namespaced aliases and write tombstones in the application preference store. Those tombstones suppress legacy fallback, so an unowned raw alias cannot resurrect a removed SecureStorage value. There is no safe way to distinguish an old SecureStorage -raw alias from certificates, keys, or another component's data in the shared repository. +raw alias from certificates, keys, or another component's data in the shared repository. Tombstones +are persistent and may accumulate: removing one while its shadowed raw alias still exists would +make deleted data readable again. ### Preferences data migration diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 82cd1e79..12fc5ab5 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (310 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (313 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 08f9a98b..924a6b33 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=310 + ESSENTIALS_TESTS_MINIMUM=313 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs index 0a09c8e4..5ae47c3e 100644 --- a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -17,7 +17,6 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public sealed class TizenPreferences : IPreferences { - static readonly object Locker = new(); readonly ITizenPreferencesStore _store; /// @@ -38,7 +37,7 @@ public bool ContainsKey(string key, string? sharedName = null) { ArgumentNullException.ThrowIfNull(key); - lock (Locker) + lock (_store.SyncRoot) { if (_store.Contains(GetFullKey(key, sharedName))) return true; @@ -54,7 +53,7 @@ public void Remove(string key, string? sharedName = null) { ArgumentNullException.ThrowIfNull(key); - lock (Locker) + lock (_store.SyncRoot) { var fullKey = GetFullKey(key, sharedName); if (_store.Contains(fullKey)) @@ -72,7 +71,7 @@ public void Remove(string key, string? sharedName = null) /// public void Clear(string? sharedName = null) { - lock (Locker) + lock (_store.SyncRoot) { var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix(sharedName ?? string.Empty); @@ -88,7 +87,7 @@ public void Set(string key, T value, string? sharedName = null) { ArgumentNullException.ThrowIfNull(key); - lock (Locker) + lock (_store.SyncRoot) { SetCore(GetFullKey(key, sharedName), value); if (value is null) @@ -103,7 +102,7 @@ public T Get(string key, T defaultValue, string? sharedName = null) { ArgumentNullException.ThrowIfNull(key); - lock (Locker) + lock (_store.SyncRoot) { var fullKey = GetFullKey(key, sharedName); @@ -188,6 +187,8 @@ internal static string GetFullKey(string key, string? sharedName) => internal interface ITizenPreferencesStore { + object SyncRoot { get; } + IEnumerable Keys { get; } bool Contains(string key); @@ -201,24 +202,47 @@ internal interface ITizenPreferencesStore sealed class TizenPreferencesStore : ITizenPreferencesStore { + readonly object _syncRoot = new(); + public static TizenPreferencesStore Instance { get; } = new(); TizenPreferencesStore() { } - public IEnumerable Keys => TizenPreference.Keys; + public object SyncRoot => _syncRoot; - public bool Contains(string key) => - TizenPreference.Contains(key); + public IEnumerable Keys + { + get + { + lock (SyncRoot) + return TizenPreference.Keys.ToArray(); + } + } - public void Remove(string key) => - TizenPreference.Remove(key); + public bool Contains(string key) + { + lock (SyncRoot) + return TizenPreference.Contains(key); + } - public void Set(string key, T value) => - TizenPreference.Set(key, value); + public void Remove(string key) + { + lock (SyncRoot) + TizenPreference.Remove(key); + } - public T Get(string key) => - TizenPreference.Get(key); + public void Set(string key, T value) + { + lock (SyncRoot) + TizenPreference.Set(key, value); + } + + public T Get(string key) + { + lock (SyncRoot) + return TizenPreference.Get(key); + } } } diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 3b3f29d2..79533793 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -3,7 +3,6 @@ using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Storage; -using TizenPreference = Tizen.Applications.Preference; using Tizen.Security.SecureRepository; namespace Microsoft.Maui.Platforms.Tizen.Essentials @@ -132,6 +131,11 @@ public Task SetAsync(string key, string value) } /// + /// + /// Removes only the namespaced alias owned by this implementation. A tombstone suppresses + /// fallback to a same-named legacy raw alias, which cannot be safely deleted because the + /// secure-repository alias space is shared with unrelated application components. + /// public bool Remove(string key) { ArgumentNullException.ThrowIfNull(key); @@ -157,7 +161,9 @@ public bool Remove(string key) /// /// /// Removes only the aliases this API owns. Other secure-repository entries belonging to the - /// application are left untouched. + /// application are left untouched. A persistent global tombstone suppresses fallback to + /// legacy raw aliases after the clear. Tombstones intentionally accumulate: they cannot be + /// garbage-collected while a shadowed raw alias exists because that would resurrect data. /// public void RemoveAll() { @@ -242,30 +248,55 @@ sealed class TizenSecureStorageTombstones : ITizenSecureStorageTombstones { const string Prefix = "maui.tizen.securestorage.tombstone:v1:"; const string AllKey = Prefix + "all"; + readonly ITizenPreferencesStore _store; - public static TizenSecureStorageTombstones Instance { get; } = new(); + public static TizenSecureStorageTombstones Instance { get; } = + new(TizenPreferencesStore.Instance); - TizenSecureStorageTombstones() + internal TizenSecureStorageTombstones(ITizenPreferencesStore store) { + _store = store; } - public bool ContainsAll => TizenPreference.Contains(AllKey); + public bool ContainsAll + { + get + { + lock (_store.SyncRoot) + return _store.Contains(AllKey); + } + } - public bool Contains(string key) => - TizenPreference.Contains(Prefix + "key:" + TizenStorageKeyEncoding.Encode(key)); + public bool Contains(string key) + { + lock (_store.SyncRoot) + return _store.Contains(GetKeyTombstone(key)); + } - public void Add(string key) => - TizenPreference.Set(Prefix + "key:" + TizenStorageKeyEncoding.Encode(key), true); + public void Add(string key) + { + lock (_store.SyncRoot) + _store.Set(GetKeyTombstone(key), true); + } public void Remove(string key) { - var tombstone = Prefix + "key:" + TizenStorageKeyEncoding.Encode(key); - if (TizenPreference.Contains(tombstone)) - TizenPreference.Remove(tombstone); + lock (_store.SyncRoot) + { + var tombstone = GetKeyTombstone(key); + if (_store.Contains(tombstone)) + _store.Remove(tombstone); + } + } + + public void AddAll() + { + lock (_store.SyncRoot) + _store.Set(AllKey, true); } - public void AddAll() => - TizenPreference.Set(AllKey, true); + static string GetKeyTombstone(string key) => + Prefix + "key:" + TizenStorageKeyEncoding.Encode(key); } sealed class InMemorySecureStorageTombstones : ITizenSecureStorageTombstones diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index ce9e0d83..c729241e 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -116,26 +116,19 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati cancelToken.ThrowIfCancellationRequested(); - var client = await InitializeAsync(cancelToken).ConfigureAwait(false); - - await _speakLock.WaitAsync(cancelToken).ConfigureAwait(false); - try - { - // Re-check after acquiring the lock. Initialization and queuing behind another - // utterance can both take arbitrarily long, and starting speech for a request that - // was cancelled while waiting is exactly the surprise a cancellation token exists to - // prevent. - cancelToken.ThrowIfCancellationRequested(); - + await RunWithCurrentClientAsync( + _speakLock, + cancelToken, + InitializeAsync, + async client => + { var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _utterance = utterance; - using var registration = cancelToken.Register(() => - CancelUtterance(utterance, cancelToken, () => InvalidateClient(client))); - try { - cancelToken.ThrowIfCancellationRequested(); + using var registration = cancelToken.Register(() => + CancelUtterance(utterance, cancelToken, () => InvalidateClient(client))); var (resolvedLanguage, voiceType) = ResolveVoice(client, language); client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); @@ -144,19 +137,39 @@ async Task SpeakCoreAsync(string text, string? language, float? rate, Cancellati cancelToken.ThrowIfCancellationRequested(); client.Play(); + + await utterance.Task.ConfigureAwait(false); } catch (Exception) when (cancelToken.IsCancellationRequested) { cancelToken.ThrowIfCancellationRequested(); throw; } + finally + { + if (ReferenceEquals(_utterance, utterance)) + _utterance = null; + } + }).ConfigureAwait(false); + } - await utterance.Task.ConfigureAwait(false); + internal static async Task RunWithCurrentClientAsync( + SemaphoreSlim speakLock, + CancellationToken cancelToken, + Func> initialize, + Func operation) + { + await speakLock.WaitAsync(cancelToken).ConfigureAwait(false); + try + { + cancelToken.ThrowIfCancellationRequested(); + var client = await initialize(cancelToken).ConfigureAwait(false); + cancelToken.ThrowIfCancellationRequested(); + await operation(client).ConfigureAwait(false); } finally { - _utterance = null; - _speakLock.Release(); + speakLock.Release(); } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 6835fb2a..cdd81db5 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -432,6 +432,35 @@ public async Task ConcurrentSecureStorageMigrationCreatesOneOwnedCopy() Assert.Equal("legacy-value", repository[TizenSecureStorage.ToAlias("token")]); } + [Fact] + public async Task PreferencesAndSecureStorageShareOneSynchronizedBackingStore() + { + var preferenceStore = new FakePreferencesStore + { + RequireSynchronization = true, + ["legacy-preference"] = "legacy-value", + }; + var preferences = new TizenPreferences(preferenceStore); + var repository = new FakeSecureRepository + { + ["secret"] = "unowned-raw-value", + }; + var secureStorage = new TizenSecureStorage( + repository, + new TizenSecureStorageTombstones(preferenceStore)); + var cancellationToken = TestContext.Current.CancellationToken; + + await Task.WhenAll( + Task.Run(() => preferences.Get("legacy-preference", "missing"), cancellationToken), + Task.Run(() => preferences.Clear(), cancellationToken), + Task.Run(() => secureStorage.Remove("secret"), cancellationToken), + Task.Run(() => secureStorage.SetAsync("secret", "new-value"), cancellationToken)); + + Assert.Equal(1, preferenceStore.MaximumConcurrentOperations); + Assert.Equal("unowned-raw-value", repository["secret"]); + Assert.Contains(await secureStorage.GetAsync("secret"), new string?[] { null, "new-value" }); + } + // ------------------------------------------------------------------------------------------- // TextToSpeech cancellation. // ------------------------------------------------------------------------------------------- @@ -501,6 +530,84 @@ public async Task TextToSpeechDisposalSettlesAllPendingTasks() await Assert.ThrowsAsync(() => utterance.Task); } + [Fact] + public async Task QueuedTextToSpeechReinitializesAfterActiveCancellation() + { + using var speakLock = new SemaphoreSlim(1, 1); + using var cancellation = new CancellationTokenSource(); + var activeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var activeCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var currentClient = "stale"; + string? queuedClient = null; + + var active = TizenTextToSpeech.RunWithCurrentClientAsync( + speakLock, + cancellation.Token, + _ => Task.FromResult(currentClient), + async _ => + { + activeStarted.SetResult(); + await activeCompletion.Task; + }); + + await activeStarted.Task; + var queued = TizenTextToSpeech.RunWithCurrentClientAsync( + speakLock, + CancellationToken.None, + _ => Task.FromResult(currentClient), + client => + { + queuedClient = client; + return Task.CompletedTask; + }); + + currentClient = "fresh"; + cancellation.Cancel(); + activeCompletion.SetCanceled(cancellation.Token); + + await Assert.ThrowsAnyAsync(() => active); + await queued; + Assert.Equal("fresh", queuedClient); + } + + [Fact] + public async Task QueuedTextToSpeechReinitializesAfterActiveNativeError() + { + using var speakLock = new SemaphoreSlim(1, 1); + var activeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var activeCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var currentClient = "stale"; + string? queuedClient = null; + + var active = TizenTextToSpeech.RunWithCurrentClientAsync( + speakLock, + CancellationToken.None, + _ => Task.FromResult(currentClient), + async _ => + { + activeStarted.SetResult(); + await activeCompletion.Task; + }); + + await activeStarted.Task; + var queued = TizenTextToSpeech.RunWithCurrentClientAsync( + speakLock, + CancellationToken.None, + _ => Task.FromResult(currentClient), + client => + { + queuedClient = client; + return Task.CompletedTask; + }); + + currentClient = "fresh"; + activeCompletion.SetException(new InvalidOperationException("native error")); + + await Assert.ThrowsAsync(() => active); + await queued; + Assert.Equal("fresh", queuedClient); + } + // ------------------------------------------------------------------------------------------- // Screenshot pixel-format handling. // ------------------------------------------------------------------------------------------- @@ -773,8 +880,13 @@ sealed class FakePreferencesStore : ITizenPreferencesStore { readonly Dictionary _values = new(StringComparer.Ordinal); readonly Dictionary _setCounts = new(StringComparer.Ordinal); + int _activeOperations; + + public object SyncRoot { get; } = new(); + public bool RequireSynchronization { get; init; } + public int MaximumConcurrentOperations { get; private set; } - public IEnumerable Keys => _values.Keys.ToArray(); + public IEnumerable Keys => Access(() => _values.Keys.ToArray()); public object? this[string key] { @@ -783,22 +895,49 @@ public object? this[string key] } public bool Contains(string key) => - _values.ContainsKey(key); + Access(() => _values.ContainsKey(key)); public void Remove(string key) => - _values.Remove(key); + Access(() => _values.Remove(key)); public void Set(string key, T value) { - _values[key] = value; - _setCounts[key] = GetSetCount(key) + 1; + Access(() => + { + _values[key] = value; + _setCounts[key] = GetSetCount(key) + 1; + }); } public T Get(string key) => - (T)_values[key]!; + Access(() => (T)_values[key]!); public int GetSetCount(string key) => _setCounts.TryGetValue(key, out var count) ? count : 0; + + T Access(Func action) + { + if (RequireSynchronization && !System.Threading.Monitor.IsEntered(SyncRoot)) + throw new InvalidOperationException("Preference access was not synchronized."); + + var active = Interlocked.Increment(ref _activeOperations); + MaximumConcurrentOperations = Math.Max(MaximumConcurrentOperations, active); + try + { + return action(); + } + finally + { + Interlocked.Decrement(ref _activeOperations); + } + } + + void Access(Action action) => + Access(() => + { + action(); + return true; + }); } sealed class FakeContactRecord : IDisposable From ce7aa8728a80ec11516dc5f12ad396ff2ef6e286 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 12:00:35 -0400 Subject: [PATCH 11/21] Harden secure storage and TTS lifetimes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: f10f5376-08fd-4221-8332-7c3b3865f0b2 --- docs/migration.md | 16 +- docs/tizen-essentials-service-coverage.md | 4 +- eng/build-workload-free.sh | 2 +- .../SecureStorage/TizenSecureStorage.cs | 120 +++-- .../TextToSpeech/TizenTextToSpeech.cs | 505 +++++++++++++----- .../TizenServiceBehaviorTests.cs | 203 ++++++- 6 files changed, 681 insertions(+), 169 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index 504377ac..c8af5eb9 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -64,17 +64,19 @@ working. ### SecureStorage data migration The standalone Essentials package stores secure values under -`maui.tizen.securestorage:`. The in-box Tizen backend stored the caller's raw key in -the application-wide secure-repository alias space. +`maui.tizen.securestorage:v2:`. The v2 encoding is injective and contains no +whitespace, padding, or separator characters rejected by Tizen's secure repository. Aliases are +never truncated or hashed to fit a native limit; Tizen's argument error is surfaced instead. -`GetAsync` performs a one-way, per-key compatibility migration: it reads the namespaced alias first; -only when that alias is absent does it read the exact legacy raw alias and save the value under the -namespaced alias. It never deletes the raw alias because the application-wide secure repository +`GetAsync` performs a one-way, per-key compatibility migration in this order: v2 alias, the first +standalone package's escaped namespaced alias, then the in-box backend's exact raw alias. A legacy +value is copied to v2. Raw aliases are never deleted because the application-wide secure repository cannot prove that alias is owned by SecureStorage. A migration save failure is surfaced and leaves the legacy value intact. -`Remove` and `RemoveAll` delete only namespaced aliases and write tombstones in the application -preference store. Those tombstones suppress legacy fallback, so an unowned raw alias cannot +`Remove` deletes both generations of owned namespaced alias, and `RemoveAll` deletes every alias +under the private ownership prefix. Both write tombstones in the application preference store. +Those tombstones suppress legacy fallback, so an unowned raw alias cannot resurrect a removed SecureStorage value. There is no safe way to distinguish an old SecureStorage raw alias from certificates, keys, or another component's data in the shared repository. Tombstones are persistent and may accumulate: removing one while its shadowed raw alias still exists would diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 12fc5ab5..ae4c9f1c 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -59,7 +59,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `IPhoneDialer` | `TizenPhoneDialer` | Implemented | Mobile | `tel:` AppControl, gated on the `contact` feature key. | | `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with an **escaped** `{sharedName}~{key}` prefix so distinct stores cannot collide. Default-store keys stay unprefixed for compatibility. | | `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders; native handles disposed, RGBX/BGRX treated as opaque, and a bounded wait for `Capture.Finished`. Also implements `IViewScreenshot`. | -| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. Aliases are stored under a private prefix, so `RemoveAll` deletes only entries this API created rather than every alias the app can see. | +| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. Versioned Base64url aliases are whitespace-free and private to this API; reads migrate earlier namespaced/raw aliases, while tombstones prevent removed raw values from resurfacing. | | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | | `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (313 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (327 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 924a6b33..d6c42060 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=313 + ESSENTIALS_TESTS_MINIMUM=327 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 79533793..be14d890 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -27,6 +27,7 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials public sealed class TizenSecureStorage : ISecureStorage { static readonly object Locker = new(); + const string AliasVersion = "v2:"; readonly ITizenSecureRepository _repository; readonly ITizenSecureStorageTombstones _tombstones; @@ -71,11 +72,6 @@ internal TizenSecureStorage( { // The namespaced alias does not exist. } - catch - { - global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to load data."); - throw; - } if (_tombstones.Contains(key) || _tombstones.ContainsAll) return Task.FromResult(null); @@ -84,14 +80,36 @@ internal TizenSecureStorage( try { - legacyValue = _repository.Get(key); + if (!CanUseLegacyNamespacedAlias(key)) + throw new InvalidOperationException(); + + legacyValue = _repository.Get(ToLegacyNamespacedAlias(key)); } catch (InvalidOperationException) { - return Task.FromResult(null); + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } + } + catch (ArgumentException) + { + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } } - // Raw aliases are unowned and may belong to another component. Copy, never delete. + // Legacy namespaced and raw aliases are copied into v2. Raw aliases are unowned and + // may belong to another component, so they are never deleted. _repository.Save(ToAlias(key), legacyValue); return Task.FromResult(Encoding.UTF8.GetString(legacyValue)); @@ -106,27 +124,14 @@ public Task SetAsync(string key, string value) lock (Locker) { - try - { - var alias = ToAlias(key); - try - { - _repository.RemoveAlias(alias); - } - catch - { - // Expected when the alias did not exist. - } - - _repository.Save(alias, Encoding.UTF8.GetBytes(value)); - _tombstones.Remove(key); - return Task.CompletedTask; - } - catch - { - global::Tizen.Log.Error(TizenPlatform.CurrentPackageLogTag, "Failed to save data."); - throw; - } + var alias = ToAlias(key); + RemoveOwnedAliasIfPresent(alias); + if (CanUseLegacyNamespacedAlias(key)) + RemoveOwnedAliasIfPresent(ToLegacyNamespacedAlias(key)); + + _repository.Save(alias, Encoding.UTF8.GetBytes(value)); + _tombstones.Remove(key); + return Task.CompletedTask; } } @@ -148,11 +153,24 @@ public bool Remove(string key) _repository.RemoveAlias(ToAlias(key)); removed = true; } - catch + catch (InvalidOperationException) { // Missing namespaced data is expected when only an ambiguous raw alias exists. } + try + { + if (CanUseLegacyNamespacedAlias(key)) + { + _repository.RemoveAlias(ToLegacyNamespacedAlias(key)); + removed = true; + } + } + catch (InvalidOperationException) + { + // Missing v1 namespaced data is expected. + } + _tombstones.Add(key); return removed; } @@ -204,9 +222,37 @@ public void RemoveAll() /// /// The caller's key. /// The namespaced alias. - internal static string ToAlias(string key) => + /// + /// Version 2 encodes the UTF-8 key as unpadded Base64url, producing an injective alias with + /// no whitespace or delimiters rejected by Tizen's secure repository. Aliases are never + /// truncated; native alias-length or format failures are surfaced to the caller. + /// + internal static string ToAlias(string key) + { + ArgumentNullException.ThrowIfNull(key); + + var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + + return AliasPrefix + AliasVersion + encoded; + } + + internal static string ToLegacyNamespacedAlias(string key) => AliasPrefix + TizenStorageKeyEncoding.Encode(key); + internal static bool CanUseLegacyNamespacedAlias(string key) + { + foreach (var character in key) + { + if (char.IsWhiteSpace(character)) + return false; + } + + return true; + } + /// /// Determines whether an alias was created by this API. /// @@ -229,6 +275,18 @@ internal static bool IsOwnedAlias(string alias) return separator >= 0 && alias.AsSpan(separator + 1).StartsWith(AliasPrefix, StringComparison.Ordinal); } + + void RemoveOwnedAliasIfPresent(string alias) + { + try + { + _repository.RemoveAlias(alias); + } + catch (InvalidOperationException) + { + // Expected when the owned alias did not exist. + } + } } internal interface ITizenSecureStorageTombstones diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index c729241e..57257845 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -24,8 +24,10 @@ public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable readonly SemaphoreSlim _speakLock = new(1, 1); readonly SemaphoreSlim _initializeLock = new(1, 1); - TtsClient? _client; - Task? _initialization; + ClientState? _clientState; + ClientState? _initializingState; + Task? _initialization; + ActiveUtterance? _activeUtterance; TaskCompletionSource? _readiness; TaskCompletionSource? _utterance; bool _disposed; @@ -58,15 +60,22 @@ public Task> GetLocalesAsync() => /// The distinct supported voice languages. public async Task> GetSupportedVoiceLanguagesAsync() { - var client = await InitializeAsync(CancellationToken.None).ConfigureAwait(false); - var languages = new List(); - foreach (var voice in client.GetSupportedVoices()) - { - if (!languages.Any(l => string.Equals(l, voice.Language, StringComparison.OrdinalIgnoreCase))) - languages.Add(voice.Language); - } + await RunWithCurrentClientAsync( + _speakLock, + CancellationToken.None, + InitializeAsync, + state => + { + foreach (var voice in state.Client.GetSupportedVoices()) + { + if (!languages.Any(l => string.Equals(l, voice.Language, StringComparison.OrdinalIgnoreCase))) + languages.Add(voice.Language); + } + + return Task.CompletedTask; + }).ConfigureAwait(false); return languages; } @@ -120,37 +129,49 @@ await RunWithCurrentClientAsync( _speakLock, cancelToken, InitializeAsync, - async client => + async state => { - var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _utterance = utterance; - - try - { - using var registration = cancelToken.Register(() => - CancelUtterance(utterance, cancelToken, () => InvalidateClient(client))); - - var (resolvedLanguage, voiceType) = ResolveVoice(client, language); - client.AddText(text, resolvedLanguage, (int)voiceType, ResolveRate(client, rate)); + var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + SetPendingUtterance(state, utterance); - // Clear any text queued by a cancellation racing AddText before playback starts. - cancelToken.ThrowIfCancellationRequested(); - - client.Play(); - - await utterance.Task.ConfigureAwait(false); - } - catch (Exception) when (cancelToken.IsCancellationRequested) - { - cancelToken.ThrowIfCancellationRequested(); - throw; - } - finally - { - if (ReferenceEquals(_utterance, utterance)) - _utterance = null; - } - }).ConfigureAwait(false); + try + { + using var registration = cancelToken.Register(() => + CancelClientState(state, utterance, cancelToken)); + cancelToken.ThrowIfCancellationRequested(); + + var (resolvedLanguage, voiceType) = ResolveVoice(state.Client, language); + var utteranceId = state.Client.AddText( + text, + resolvedLanguage, + (int)voiceType, + ResolveRate(state.Client, rate)); + + SetActiveUtterance(state, utteranceId, utterance); + + // A cancellation racing AddText retires this generation before playback. + cancelToken.ThrowIfCancellationRequested(); + + PlayOrRetire( + state.Client.Play, + () => + { + if (RetireClientState(state)) + TeardownClient(state, stop: true); + }); + + await utterance.Task.ConfigureAwait(false); + } + catch (Exception) when (cancelToken.IsCancellationRequested) + { + cancelToken.ThrowIfCancellationRequested(); + throw; + } + finally + { + ClearActiveUtterance(state, utterance); + } + }).ConfigureAwait(false); } internal static async Task RunWithCurrentClientAsync( @@ -178,7 +199,6 @@ internal static void CancelUtterance( CancellationToken cancelToken, Action stop) { - utterance.TrySetCanceled(cancelToken); try { stop(); @@ -187,6 +207,33 @@ internal static void CancelUtterance( { // Cancellation has already won the task contract. } + + utterance.TrySetCanceled(cancelToken); + } + + internal static void PlayOrRetire(Action play, Action retire) + { + try + { + play(); + } + catch + { + retire(); + throw; + } + } + + internal static bool MatchesUtterance(int expectedUtteranceId, int callbackUtteranceId) => + expectedUtteranceId == callbackUtteranceId; + + internal static bool RetireBeforeSettle(Func retire, Action settle) + { + if (!retire()) + return false; + + settle(); + return true; } static void StopQuietly(TtsClient client) @@ -245,137 +292,284 @@ static int ResolveRate(TtsClient client, float? rate) /// retries cleanly instead of awaiting a task that will never complete. /// /// - async Task InitializeAsync(CancellationToken cancelToken) + async Task InitializeAsync(CancellationToken cancelToken) { - ObjectDisposedException.ThrowIf(_disposed, this); - - if (_initialization is { } cached) - return await cached.WaitAsync(cancelToken).ConfigureAwait(false); - + ClientState? stateToPrepare = null; + Task initialization; await _initializeLock.WaitAsync(cancelToken).ConfigureAwait(false); try { ObjectDisposedException.ThrowIf(_disposed, this); - _initialization ??= PrepareAsync(); + if (_clientState is { Retired: false } current) + return current; + + if (_initialization is null) + { + stateToPrepare = new ClientState(new TtsClient()); + _initializingState = stateToPrepare; + _initialization = stateToPrepare.Initialization.Task; + _readiness = stateToPrepare.Readiness; + } + + initialization = _initialization; } finally { _initializeLock.Release(); } - try - { - return await _initialization.WaitAsync(cancelToken).ConfigureAwait(false); - } - catch (Exception) when (_initialization?.IsFaulted == true) - { - // Let the next caller retry rather than caching the failure forever. - await _initializeLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); - try - { - if (_initialization?.IsFaulted == true) - _initialization = null; - } - finally - { - _initializeLock.Release(); - } + if (stateToPrepare is not null) + Prepare(stateToPrepare); - throw; - } + return await initialization.WaitAsync(cancelToken).ConfigureAwait(false); } - Task PrepareAsync() + void Prepare(ClientState state) { - var client = new TtsClient(); - var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var cleanedUp = 0; - _readiness = ready; - - client.StateChanged += OnStateChanged; - client.UtteranceCompleted += OnUtteranceCompleted; - client.ErrorOccurred += OnErrorOccurred; + state.Client.StateChanged += OnStateChanged; + state.Client.UtteranceCompleted += OnUtteranceCompleted; + state.Client.ErrorOccurred += OnErrorOccurred; + state.Teardown = () => + { + state.Client.StateChanged -= OnStateChanged; + state.Client.UtteranceCompleted -= OnUtteranceCompleted; + state.Client.ErrorOccurred -= OnErrorOccurred; + state.Client.Dispose(); + }; try { - client.Prepare(); + state.Client.Prepare(); } - catch (Exception) + catch (Exception exception) { - CleanupClient(); + RetireClientState(state); + state.Readiness.TrySetException(exception); + state.Initialization.TrySetException(exception); + TeardownClient(state, stop: false); throw; } - _client = client; - - return AwaitReadyAsync(); - void OnStateChanged(object? sender, StateChangedEventArgs e) { if (e.Current == State.Ready) - ready.TrySetResult(true); + PublishReadyClient(state); } void OnUtteranceCompleted(object? sender, UtteranceEventArgs e) { - StopQuietly(client); - _utterance?.TrySetResult(true); + var utterance = GetMatchingActiveUtterance(state, e.UtteranceId); + if (utterance is null) + return; + + StopQuietly(state.Client); + utterance.Completion.TrySetResult(true); } void OnErrorOccurred(object? sender, ErrorOccurredEventArgs e) { var exception = new InvalidOperationException( $"Tizen text-to-speech failed ({e.ErrorValue}): {e.ErrorMessage}"); + ActiveUtterance? utterance = null; + + if (!RetireBeforeSettle( + () => TryRetireForNativeError(state, e.UtteranceId, out utterance), + () => + { + state.Readiness.TrySetException(exception); + state.Initialization.TrySetException(exception); + utterance?.Completion.TrySetException(exception); + })) + return; - FailPendingTasks(ready, _utterance, exception); - CleanupClient(); + DeferNativeTeardown( + action => MainThread.BeginInvokeOnMainThread(action), + () => TeardownClient(state, stop: false)); } + } - async Task AwaitReadyAsync() + void PublishReadyClient(ClientState state) + { + _initializeLock.Wait(); + try { - try - { - await ready.Task.ConfigureAwait(false); - return client; - } - catch (Exception) - { - CleanupClient(); - throw; - } + if (state.Retired || !ReferenceEquals(_initializingState, state) || _disposed) + return; + + _clientState = state; + _initializingState = null; + _readiness = null; + } + finally + { + _initializeLock.Release(); } - void CleanupClient() + state.Readiness.TrySetResult(true); + state.Initialization.TrySetResult(state); + } + + void SetActiveUtterance( + ClientState state, + int utteranceId, + TaskCompletionSource completion) + { + _initializeLock.Wait(); + try + { + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired before playback."); + + _activeUtterance = new ActiveUtterance(state, utteranceId, completion); + } + finally { - if (Interlocked.Exchange(ref cleanedUp, 1) != 0) - return; + _initializeLock.Release(); + } + } + + void SetPendingUtterance(ClientState state, TaskCompletionSource completion) + { + _initializeLock.Wait(); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired before playback."); - client.StateChanged -= OnStateChanged; - client.UtteranceCompleted -= OnUtteranceCompleted; - client.ErrorOccurred -= OnErrorOccurred; + _utterance = completion; + } + finally + { + _initializeLock.Release(); + } + } - if (ReferenceEquals(_client, client)) + ActiveUtterance? GetMatchingActiveUtterance(ClientState state, int utteranceId) + { + _initializeLock.Wait(); + try + { + return _activeUtterance is { } active && + ReferenceEquals(active.Client, state) && + MatchesUtterance(active.UtteranceId, utteranceId) + ? active + : null; + } + finally + { + _initializeLock.Release(); + } + } + + bool TryRetireForNativeError( + ClientState state, + int utteranceId, + out ActiveUtterance? utterance) + { + _initializeLock.Wait(); + try + { + utterance = _activeUtterance; + if (utterance is not null && + (!ReferenceEquals(utterance.Client, state) || + !MatchesUtterance(utterance.UtteranceId, utteranceId))) { - _client = null; - _initialization = null; + utterance = null; + return false; } - if (ReferenceEquals(_readiness, ready)) - _readiness = null; - client.Dispose(); + return RetireClientStateLocked(state); + } + finally + { + _initializeLock.Release(); } } - void InvalidateClient(TtsClient client) + void ClearActiveUtterance(ClientState state, TaskCompletionSource completion) { - if (ReferenceEquals(_client, client)) + _initializeLock.Wait(); + try { - _client = null; - _initialization = null; + if (_activeUtterance is { } active && + ReferenceEquals(active.Client, state) && + ReferenceEquals(active.Completion, completion)) + { + _activeUtterance = null; + } + + if (ReferenceEquals(_utterance, completion)) + _utterance = null; + } + finally + { + _initializeLock.Release(); } + } + + void CancelClientState( + ClientState state, + TaskCompletionSource utterance, + CancellationToken cancelToken) + { + CancelUtterance( + utterance, + cancelToken, + () => + { + if (RetireClientState(state)) + TeardownClient(state, stop: true); + }); + } - client.Dispose(); + bool RetireClientState(ClientState state) + { + _initializeLock.Wait(); + try + { + return RetireClientStateLocked(state); + } + finally + { + _initializeLock.Release(); + } + } + + bool RetireClientStateLocked(ClientState state) + { + if (state.Retired) + return false; + + state.Retired = true; + + if (ReferenceEquals(_clientState, state)) + _clientState = null; + if (ReferenceEquals(_initializingState, state)) + _initializingState = null; + if (ReferenceEquals(_initialization, state.Initialization.Task)) + _initialization = null; + if (ReferenceEquals(_readiness, state.Readiness)) + _readiness = null; + + return true; + } + + static void TeardownClient(ClientState state, bool stop) + { + if (Interlocked.Exchange(ref state.TeardownStarted, 1) != 0) + return; + + if (stop) + StopQuietly(state.Client); + + state.Teardown?.Invoke(); + } + + internal static void DeferNativeTeardown(Action dispatch, Action teardown) + { + ThreadPool.QueueUserWorkItem(_ => dispatch(teardown)); } internal static void FailPendingTasks( @@ -390,19 +584,84 @@ internal static void FailPendingTasks( /// public void Dispose() { - if (_disposed) - return; + ClientState? current; + ClientState? initializing; + TaskCompletionSource? readiness; + TaskCompletionSource? utterance; + + _initializeLock.Wait(); + try + { + if (_disposed) + return; + + _disposed = true; + current = _clientState; + initializing = _initializingState; + readiness = _readiness; + utterance = _utterance; + + if (current is not null) + RetireClientStateLocked(current); + if (initializing is not null && !ReferenceEquals(initializing, current)) + RetireClientStateLocked(initializing); + + _activeUtterance = null; + _utterance = null; + } + finally + { + _initializeLock.Release(); + } - _disposed = true; FailPendingTasks( - _readiness, - _utterance, + readiness, + utterance, new ObjectDisposedException(nameof(TizenTextToSpeech))); - _client?.Dispose(); - _client = null; - _initialization = null; - _readiness = null; + var disposedException = new ObjectDisposedException(nameof(TizenTextToSpeech)); + current?.Initialization.TrySetException(disposedException); + initializing?.Initialization.TrySetException(disposedException); + + _speakLock.Wait(); + try + { + if (current is not null) + TeardownClient(current, stop: true); + if (initializing is not null && !ReferenceEquals(initializing, current)) + TeardownClient(initializing, stop: true); + } + finally + { + _speakLock.Release(); + } + } + + sealed class ClientState + { + public ClientState(TtsClient client) + { + Client = client; + } + + public TtsClient Client { get; } + + public TaskCompletionSource Readiness { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Initialization { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Action? Teardown { get; set; } + + public bool Retired { get; set; } + + public int TeardownStarted; } + + sealed record ActiveUtterance( + ClientState Client, + int UtteranceId, + TaskCompletionSource Completion); } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index cdd81db5..8253f062 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -259,13 +259,30 @@ public void SecureStorageAliasesAreNamespaced() var alias = TizenSecureStorage.ToAlias("token"); Assert.StartsWith(TizenSecureStorage.AliasPrefix, alias, StringComparison.Ordinal); - Assert.EndsWith("token", alias, StringComparison.Ordinal); + Assert.StartsWith(TizenSecureStorage.AliasPrefix + "v2:", alias, StringComparison.Ordinal); + Assert.DoesNotContain(alias, char.IsWhiteSpace); } [Fact] public void SecureStorageAliasesCannotCollideWithEachOther() { - Assert.NotEqual(TizenSecureStorage.ToAlias("a~b"), TizenSecureStorage.ToAlias("a\\~b")); + string[] keys = ["a~b", "a\\~b", "a:b", "a b", "a\tb", "é", "e\u0301", "秘密"]; + + Assert.Equal(keys.Length, keys.Select(TizenSecureStorage.ToAlias).Distinct().Count()); + } + + [Theory] + [InlineData("api token")] + [InlineData("api\ttoken")] + [InlineData("ключ доступа")] + [InlineData("a:b~c\\d")] + public void SecureStorageAliasesAreWhitespaceFreeBase64Url(string key) + { + var encoded = TizenSecureStorage.ToAlias(key)[(TizenSecureStorage.AliasPrefix.Length + 3)..]; + + Assert.NotEmpty(encoded); + Assert.All(encoded, character => Assert.True( + char.IsAsciiLetterOrDigit(character) || character is '-' or '_')); } [Theory] @@ -324,6 +341,74 @@ public async Task SecureStoragePrefersTheNamespacedAliasOverLegacyData() Assert.Equal("legacy-value", repository["token"]); } + [Fact] + public async Task SecureStorageReadsAndMigratesThePreviousNamespacedAlias() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToLegacyNamespacedAlias("token")] = "v1-value", + ["token"] = "raw-value", + }; + var storage = new TizenSecureStorage(repository); + + Assert.Equal("v1-value", await storage.GetAsync("token")); + Assert.Equal("v1-value", repository[TizenSecureStorage.ToAlias("token")]); + Assert.Equal("raw-value", repository["token"]); + } + + [Fact] + public async Task SecureStorageNewAliasWinsOverAllLegacyAliases() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToAlias("token")] = "v2-value", + [TizenSecureStorage.ToLegacyNamespacedAlias("token")] = "v1-value", + ["token"] = "raw-value", + }; + + Assert.Equal("v2-value", await new TizenSecureStorage(repository).GetAsync("token")); + } + + [Fact] + public async Task SecureStorageWhitespaceKeyUsesOnlyNativeSafeAliases() + { + var repository = new FakeSecureRepository + { + RejectWhitespaceAliases = true, + }; + var storage = new TizenSecureStorage(repository); + + await storage.SetAsync("api token", "value"); + + Assert.Equal("value", await storage.GetAsync("api token")); + Assert.False(TizenSecureStorage.CanUseLegacyNamespacedAlias("api token")); + } + + [Fact] + public async Task SecureStorageDoesNotTruncateAliasesRejectedByTheNativeLimit() + { + var repository = new FakeSecureRepository + { + MaximumAliasLength = TizenSecureStorage.AliasPrefix.Length + 8, + }; + var storage = new TizenSecureStorage(repository); + + await Assert.ThrowsAsync(() => storage.SetAsync(new string('x', 64), "value")); + Assert.Empty(repository.GetAliases()); + } + + [Fact] + public void SecureStorageRemoveDeletesPreviousOwnedAlias() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToLegacyNamespacedAlias("token")] = "v1-value", + }; + + Assert.True(new TizenSecureStorage(repository).Remove("token")); + Assert.False(repository.Contains(TizenSecureStorage.ToLegacyNamespacedAlias("token"))); + } + [Fact] public void SecureStorageRemoveAllDeletesOnlyNamespacedAliases() { @@ -484,21 +569,112 @@ public async Task TextToSpeechInFlightCancellationUsesTheCallerToken() using var source = new CancellationTokenSource(); var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var stopped = false; - var cancellationWonBeforeStop = false; + var retiredBeforeCancellationSettled = false; TizenTextToSpeech.CancelUtterance(utterance, source.Token, () => { - cancellationWonBeforeStop = utterance.Task.IsCanceled; + retiredBeforeCancellationSettled = !utterance.Task.IsCompleted; stopped = true; }); var exception = await Assert.ThrowsAnyAsync(() => utterance.Task); Assert.True(stopped); - Assert.True(cancellationWonBeforeStop); + Assert.True(retiredBeforeCancellationSettled); Assert.Equal(source.Token, exception.CancellationToken); } + [Fact] + public void TextToSpeechPlayFailureRetiresBeforeRethrowing() + { + var retired = false; + + Assert.Throws(() => + TizenTextToSpeech.PlayOrRetire( + () => throw new InvalidOperationException("play failed"), + () => retired = true)); + + Assert.True(retired); + } + + [Fact] + public void TextToSpeechIgnoresStaleUtteranceCallbacks() + { + Assert.True(TizenTextToSpeech.MatchesUtterance(42, 42)); + Assert.False(TizenTextToSpeech.MatchesUtterance(42, 41)); + } + + [Fact] + public void TextToSpeechNativeErrorRetiresBeforeTaskSettlement() + { + var retired = false; + var settledAfterRetirement = false; + + Assert.True(TizenTextToSpeech.RetireBeforeSettle( + () => + { + retired = true; + return true; + }, + () => settledAfterRetirement = retired)); + + Assert.True(settledAfterRetirement); + } + + [Fact] + public async Task TextToSpeechNativeTeardownIsDeferred() + { + using var allowDispatch = new ManualResetEventSlim(); + var tornDown = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + TizenTextToSpeech.DeferNativeTeardown( + action => + { + allowDispatch.Wait(TestContext.Current.CancellationToken); + action(); + }, + () => tornDown.SetResult()); + + Assert.False(tornDown.Task.IsCompleted); + allowDispatch.Set(); + await tornDown.Task.WaitAsync(TestContext.Current.CancellationToken); + } + + [Fact] + public async Task TextToSpeechClientGuardSerializesVoiceQueriesAndSpeech() + { + using var clientLock = new SemaphoreSlim(1, 1); + var firstStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFirst = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondStarted = false; + + var first = TizenTextToSpeech.RunWithCurrentClientAsync( + clientLock, + CancellationToken.None, + _ => Task.FromResult("client"), + async _ => + { + firstStarted.SetResult(); + await releaseFirst.Task; + }); + + await firstStarted.Task; + var second = TizenTextToSpeech.RunWithCurrentClientAsync( + clientLock, + CancellationToken.None, + _ => Task.FromResult("client"), + _ => + { + secondStarted = true; + return Task.CompletedTask; + }); + + Assert.False(secondStarted); + releaseFirst.SetResult(); + await Task.WhenAll(first, second); + Assert.True(secondStarted); + } + [Fact] public async Task TextToSpeechAsyncErrorsFaultReadinessAndPlayback() { @@ -797,6 +973,8 @@ sealed class FakeSecureRepository : ITizenSecureRepository readonly object _locker = new(); public Exception? SaveException { get; init; } + public int? MaximumAliasLength { get; init; } + public bool RejectWhitespaceAliases { get; init; } public int SuccessfulSaves { get; private set; } public string this[string alias] @@ -825,15 +1003,20 @@ public bool Contains(string alias) public byte[] Get(string alias) { lock (_locker) + { + ValidateAlias(alias); return _values.TryGetValue(alias, out var value) ? value : throw new InvalidOperationException("alias not found"); + } } public void Save(string alias, byte[] value) { lock (_locker) { + ValidateAlias(alias); + if (SaveException is not null) throw SaveException; @@ -849,6 +1032,8 @@ public void RemoveAlias(string alias) { lock (_locker) { + ValidateAlias(alias); + if (!_values.Remove(alias)) throw new InvalidOperationException("alias not found"); } @@ -859,6 +1044,14 @@ public IEnumerable GetAliases() lock (_locker) return _values.Keys.ToArray(); } + + void ValidateAlias(string alias) + { + if (RejectWhitespaceAliases && alias.Any(char.IsWhiteSpace)) + throw new ArgumentException("alias contains whitespace", nameof(alias)); + if (MaximumAliasLength is { } maximum && alias.Length > maximum) + throw new ArgumentException("alias exceeds native limit", nameof(alias)); + } } sealed class FakeSecureStorageTombstones : ITizenSecureStorageTombstones From f6b416fcc75d7fa9a3fdd3f764a107852949a618 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 14:04:30 -0400 Subject: [PATCH 12/21] Enforce secure aliases and TTS dispatching Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: f10f5376-08fd-4221-8332-7c3b3865f0b2 --- docs/migration.md | 15 +- docs/tizen-essentials-service-coverage.md | 4 +- eng/build-workload-free.sh | 2 +- .../SecureStorage/TizenSecureStorage.cs | 20 +- .../TextToSpeech/TizenTextToSpeech.cs | 714 +++++++++--------- .../TizenServiceBehaviorTests.cs | 532 ++++++++++--- 6 files changed, 818 insertions(+), 469 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index c8af5eb9..c74acc20 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -64,15 +64,18 @@ working. ### SecureStorage data migration The standalone Essentials package stores secure values under -`maui.tizen.securestorage:v2:`. The v2 encoding is injective and contains no -whitespace, padding, or separator characters rejected by Tizen's secure repository. Aliases are -never truncated or hashed to fit a native limit; Tizen's argument error is surfaced instead. +`maui.tizen.securestorage:~v2~`. The escaped-version delimiter cannot collide +with the first standalone package's alias encoder. Strict UTF-8 makes the encoding injective and +rejects unpaired UTF-16 surrogates before any store mutation. The result contains no whitespace or +padding rejected by Tizen's secure repository. Aliases are never truncated or hashed to fit a +native limit; Tizen's argument error is surfaced instead. `GetAsync` performs a one-way, per-key compatibility migration in this order: v2 alias, the first standalone package's escaped namespaced alias, then the in-box backend's exact raw alias. A legacy -value is copied to v2. Raw aliases are never deleted because the application-wide secure repository -cannot prove that alias is owned by SecureStorage. A migration save failure is surfaced and leaves -the legacy value intact. +value is copied to v2. Invalid-format legacy probes, including whitespace raw aliases Tizen cannot +read, are treated as absent rather than as storage failures. Raw aliases are never deleted because +the application-wide secure repository cannot prove that alias is owned by SecureStorage. A +migration save failure is surfaced and leaves the legacy value intact. `Remove` deletes both generations of owned namespaced alias, and `RemoveAll` deletes every alias under the private ownership prefix. Both write tombstones in the application preference store. diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index ae4c9f1c..8d22b1ca 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -63,7 +63,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | | `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | -| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; initialization is serialized and cancellation re-checked before playback starts. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | +| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; every native client operation is serialized and dispatched to Tizen's Ecore/main loop, with generation-safe cancellation/error teardown. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | | `IVibration` | `TizenVibration` | Implemented | Mobile, Wearable | `Tizen.System.Vibrator`; requires the `haptic` privilege. | | `IWebAuthenticator` | `TizenWebAuthenticator` | Unsupported | – | Tizen has no callback URI registration that returns an external browser response to the app. | @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (327 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (332 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index d6c42060..2c7937fd 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=327 + ESSENTIALS_TESTS_MINIMUM=332 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index be14d890..851d1848 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -27,7 +27,8 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials public sealed class TizenSecureStorage : ISecureStorage { static readonly object Locker = new(); - const string AliasVersion = "v2:"; + static readonly UTF8Encoding StrictUtf8 = new(false, true); + const string AliasVersion = "~v2~"; readonly ITizenSecureRepository _repository; readonly ITizenSecureStorageTombstones _tombstones; @@ -95,6 +96,10 @@ internal TizenSecureStorage( { return Task.FromResult(null); } + catch (ArgumentException) + { + return Task.FromResult(null); + } } catch (ArgumentException) { @@ -106,6 +111,10 @@ internal TizenSecureStorage( { return Task.FromResult(null); } + catch (ArgumentException) + { + return Task.FromResult(null); + } } // Legacy namespaced and raw aliases are copied into v2. Raw aliases are unowned and @@ -223,15 +232,16 @@ public void RemoveAll() /// The caller's key. /// The namespaced alias. /// - /// Version 2 encodes the UTF-8 key as unpadded Base64url, producing an injective alias with - /// no whitespace or delimiters rejected by Tizen's secure repository. Aliases are never - /// truncated; native alias-length or format failures are surfaced to the caller. + /// Version 2 uses a ~v2~ discriminator that version 1's encoder can only emit escaped, + /// followed by strict UTF-8 encoded as unpadded Base64url. This makes aliases injective both + /// within and across versions. Ill-formed UTF-16 is rejected before repository mutation. + /// Aliases are never truncated; native alias-length or format failures are surfaced. /// internal static string ToAlias(string key) { ArgumentNullException.ThrowIfNull(key); - var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)) + var encoded = Convert.ToBase64String(StrictUtf8.GetBytes(key)) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index 57257845..93d269c8 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -13,16 +13,17 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// Tizen implementation of , backed by Tizen.Uix.Tts. /// /// - /// Tizen's TTS client exposes a speed range but no pitch or volume control, so - /// and are rejected rather - /// than silently ignored. + /// Tizen's TTS client is bound to the Ecore main loop. Construction, queries, playback and + /// teardown are therefore all marshalled through the MAUI main-thread dispatcher. /// public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable { const float RateMax = 2.0f; readonly SemaphoreSlim _speakLock = new(1, 1); - readonly SemaphoreSlim _initializeLock = new(1, 1); + readonly object _stateLock = new(); + readonly ITizenTextToSpeechDispatcher _dispatcher; + readonly ITizenTextToSpeechClientFactory _clientFactory; ClientState? _clientState; ClientState? _initializingState; @@ -32,20 +33,26 @@ public sealed class TizenTextToSpeech : ITextToSpeech, IDisposable TaskCompletionSource? _utterance; bool _disposed; + /// Creates a Tizen text-to-speech service. + public TizenTextToSpeech() + : this(TizenTextToSpeechDispatcher.Instance, TizenTextToSpeechClientFactory.Instance) + { + } + + internal TizenTextToSpeech( + ITizenTextToSpeechDispatcher dispatcher, + ITizenTextToSpeechClientFactory clientFactory) + { + _dispatcher = dispatcher; + _clientFactory = clientFactory; + } + /// /// Always thrown; see remarks. /// - /// - /// Blocked by a public API gap in Microsoft.Maui.Essentials: - /// Microsoft.Maui.Media.Locale has only an internal constructor, so a platform - /// backend outside the dotnet/maui assembly cannot construct the values this contract must - /// return. Returning an empty sequence instead would be indistinguishable from "this device - /// supports no voices", so this throws rather than reporting a success-shaped result. - /// - /// - /// Use to enumerate the languages Tizen - /// reports, and pass one of them to . - /// + /// Microsoft.Maui.Media.Locale has no public constructor in the currently published + /// Essentials package. Use and + /// until the public Locale API is packaged. /// public Task> GetLocalesAsync() => throw TizenEssentialsSupport.NotSupported( @@ -54,10 +61,7 @@ public Task> GetLocalesAsync() => "backend cannot create the Locale values this contract returns. " + $"Use {nameof(TizenTextToSpeech)}.{nameof(GetSupportedVoiceLanguagesAsync)} instead."); - /// - /// Enumerates the voice languages Tizen reports for the current device, for example en_US. - /// - /// The distinct supported voice languages. + /// Enumerates the voice languages Tizen reports for the current device. public async Task> GetSupportedVoiceLanguagesAsync() { var languages = new List(); @@ -66,39 +70,35 @@ await RunWithCurrentClientAsync( _speakLock, CancellationToken.None, InitializeAsync, - state => + async state => { - foreach (var voice in state.Client.GetSupportedVoices()) + var voices = await _dispatcher.InvokeAsync(state.Client.GetSupportedVoices).ConfigureAwait(false); + foreach (var voice in voices) { - if (!languages.Any(l => string.Equals(l, voice.Language, StringComparison.OrdinalIgnoreCase))) + if (!languages.Any(value => + string.Equals(value, voice.Language, StringComparison.OrdinalIgnoreCase))) + { languages.Add(voice.Language); + } } - - return Task.CompletedTask; }).ConfigureAwait(false); return languages; } - /// - /// Speaks the supplied text using an explicit Tizen voice language. - /// - /// The text to speak. - /// A language returned by . - /// The optional speech rate, in the same 0..2 range as . - /// A token used to stop playback. - /// A task that completes when the utterance finishes or is cancelled. - /// - /// Deliberately not named SpeakAsync. An overload taking a language string alongside - /// would make - /// SpeakAsync(text, null) ambiguous between a null and a null - /// language, and adds a second optional-parameter overload to the same name (RS0026). - /// - public Task SpeakWithVoiceAsync(string text, string language, float? rate = null, CancellationToken cancelToken = default) => + /// Speaks text using an explicit Tizen voice language. + public Task SpeakWithVoiceAsync( + string text, + string language, + float? rate = null, + CancellationToken cancelToken = default) => SpeakCoreAsync(text, language, rate, cancelToken); /// - public async Task SpeakAsync(string text, SpeechOptions? options = default, CancellationToken cancelToken = default) + public async Task SpeakAsync( + string text, + SpeechOptions? options = default, + CancellationToken cancelToken = default) { ArgumentNullException.ThrowIfNull(text); @@ -116,13 +116,17 @@ public async Task SpeakAsync(string text, SpeechOptions? options = default, Canc "Tizen's TTS client exposes no per-utterance volume control."); } - await SpeakCoreAsync(text, options?.Locale?.Language, options?.Rate, cancelToken).ConfigureAwait(false); + await SpeakCoreAsync(text, options?.Locale?.Language, options?.Rate, cancelToken) + .ConfigureAwait(false); } - async Task SpeakCoreAsync(string text, string? language, float? rate, CancellationToken cancelToken) + async Task SpeakCoreAsync( + string text, + string? language, + float? rate, + CancellationToken cancelToken) { ArgumentNullException.ThrowIfNull(text); - cancelToken.ThrowIfCancellationRequested(); await RunWithCurrentClientAsync( @@ -131,36 +135,41 @@ await RunWithCurrentClientAsync( InitializeAsync, async state => { - var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - SetPendingUtterance(state, utterance); + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + SetPendingUtterance(state, completion); try { - using var registration = cancelToken.Register(() => - CancelClientState(state, utterance, cancelToken)); + using var registration = cancelToken.Register( + () => CancelClientState(state, completion, cancelToken)); cancelToken.ThrowIfCancellationRequested(); - var (resolvedLanguage, voiceType) = ResolveVoice(state.Client, language); - var utteranceId = state.Client.AddText( - text, - resolvedLanguage, - (int)voiceType, - ResolveRate(state.Client, rate)); - - SetActiveUtterance(state, utteranceId, utterance); - - // A cancellation racing AddText retires this generation before playback. + var utteranceId = await _dispatcher.InvokeAsync(() => + { + var (resolvedLanguage, voiceType) = ResolveVoice(state.Client, language); + return state.Client.AddText( + text, + resolvedLanguage, + voiceType, + ResolveRate(state.Client, rate)); + }).ConfigureAwait(false); + + SetActiveUtterance(state, utteranceId, completion); cancelToken.ThrowIfCancellationRequested(); - PlayOrRetire( - state.Client.Play, - () => - { - if (RetireClientState(state)) - TeardownClient(state, stop: true); - }); - - await utterance.Task.ConfigureAwait(false); + try + { + await _dispatcher.InvokeAsync(state.Client.Play).ConfigureAwait(false); + } + catch + { + if (RetireClientState(state)) + DispatchTeardown(state, stop: true); + throw; + } + + await completion.Task.ConfigureAwait(false); } catch (Exception) when (cancelToken.IsCancellationRequested) { @@ -169,7 +178,7 @@ await RunWithCurrentClientAsync( } finally { - ClearActiveUtterance(state, utterance); + ClearActiveUtterance(state, completion); } }).ConfigureAwait(false); } @@ -194,110 +203,12 @@ internal static async Task RunWithCurrentClientAsync( } } - internal static void CancelUtterance( - TaskCompletionSource utterance, - CancellationToken cancelToken, - Action stop) - { - try - { - stop(); - } - catch (Exception) - { - // Cancellation has already won the task contract. - } - - utterance.TrySetCanceled(cancelToken); - } - - internal static void PlayOrRetire(Action play, Action retire) - { - try - { - play(); - } - catch - { - retire(); - throw; - } - } - - internal static bool MatchesUtterance(int expectedUtteranceId, int callbackUtteranceId) => - expectedUtteranceId == callbackUtteranceId; - - internal static bool RetireBeforeSettle(Func retire, Action settle) - { - if (!retire()) - return false; - - settle(); - return true; - } - - static void StopQuietly(TtsClient client) - { - try - { - client.Stop(); - } - catch (Exception) - { - // The client may already be idle; nothing actionable. - } - } - - static (string Language, Voice VoiceType) ResolveVoice(TtsClient client, string? requestedLanguage) - { - var language = "en_US"; - var voiceType = Voice.Auto; - - if (requestedLanguage is { } requested) - { - foreach (var voice in client.GetSupportedVoices()) - { - if (string.Equals(voice.Language, requested, StringComparison.OrdinalIgnoreCase)) - { - language = voice.Language; - voiceType = voice.VoiceType; - break; - } - } - } - - return (language, voiceType); - } - - static int ResolveRate(TtsClient client, float? rate) - { - if (rate is not { } value) - return 0; - - return (int)Math.Round(value / RateMax * client.GetSpeedRange().Max, MidpointRounding.AwayFromZero); - } - - /// - /// Prepares the native TTS client, at most once. - /// - /// - /// - /// Serialized behind a semaphore and cached as a single task. The previous implementation - /// checked two fields without a lock, so concurrent callers could each construct a - /// ; the loser's client was overwritten and leaked, still holding a - /// native handle and an unremovable StateChanged subscription. - /// - /// - /// A failed Prepare disposes the client and clears the cached task, so a later call - /// retries cleanly instead of awaiting a task that will never complete. - /// - /// async Task InitializeAsync(CancellationToken cancelToken) { - ClientState? stateToPrepare = null; - Task initialization; - await _initializeLock.WaitAsync(cancelToken).ConfigureAwait(false); - try + ClientState state; + var initialize = false; + + lock (_stateLock) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -306,192 +217,142 @@ async Task InitializeAsync(CancellationToken cancelToken) if (_initialization is null) { - stateToPrepare = new ClientState(new TtsClient()); - _initializingState = stateToPrepare; - _initialization = stateToPrepare.Initialization.Task; - _readiness = stateToPrepare.Readiness; + state = new ClientState(); + _initializingState = state; + _initialization = state.Initialization.Task; + _readiness = state.Readiness; + initialize = true; + } + else + { + state = _initializingState!; } - - initialization = _initialization; } - finally + + if (initialize) { - _initializeLock.Release(); + try + { + await _dispatcher.InvokeAsync(() => PrepareOnMainThread(state)).ConfigureAwait(false); + } + catch (Exception exception) + { + RetireClientState(state); + state.Readiness.TrySetException(exception); + state.Initialization.TrySetException(exception); + DispatchTeardown(state, stop: false); + } } - if (stateToPrepare is not null) - Prepare(stateToPrepare); - - return await initialization.WaitAsync(cancelToken).ConfigureAwait(false); + return await state.Initialization.Task.WaitAsync(cancelToken).ConfigureAwait(false); } - void Prepare(ClientState state) + void PrepareOnMainThread(ClientState state) { + state.Client = _clientFactory.Create(); state.Client.StateChanged += OnStateChanged; state.Client.UtteranceCompleted += OnUtteranceCompleted; state.Client.ErrorOccurred += OnErrorOccurred; - state.Teardown = () => - { - state.Client.StateChanged -= OnStateChanged; - state.Client.UtteranceCompleted -= OnUtteranceCompleted; - state.Client.ErrorOccurred -= OnErrorOccurred; - state.Client.Dispose(); - }; + state.Client.Prepare(); - try - { - state.Client.Prepare(); - } - catch (Exception exception) + void OnStateChanged(TizenTextToSpeechState current) { - RetireClientState(state); - state.Readiness.TrySetException(exception); - state.Initialization.TrySetException(exception); - TeardownClient(state, stop: false); - throw; - } + if (current != TizenTextToSpeechState.Ready) + return; - void OnStateChanged(object? sender, StateChangedEventArgs e) - { - if (e.Current == State.Ready) - PublishReadyClient(state); - } + lock (_stateLock) + { + if (state.Retired || _disposed || !ReferenceEquals(_initializingState, state)) + return; - void OnUtteranceCompleted(object? sender, UtteranceEventArgs e) - { - var utterance = GetMatchingActiveUtterance(state, e.UtteranceId); - if (utterance is null) - return; + _clientState = state; + _initializingState = null; + _readiness = null; + } - StopQuietly(state.Client); - utterance.Completion.TrySetResult(true); + state.Readiness.TrySetResult(true); + state.Initialization.TrySetResult(state); } - void OnErrorOccurred(object? sender, ErrorOccurredEventArgs e) + void OnUtteranceCompleted(int utteranceId) { - var exception = new InvalidOperationException( - $"Tizen text-to-speech failed ({e.ErrorValue}): {e.ErrorMessage}"); - ActiveUtterance? utterance = null; - - if (!RetireBeforeSettle( - () => TryRetireForNativeError(state, e.UtteranceId, out utterance), - () => + _dispatcher.Dispatch(() => + { + ActiveUtterance? utterance; + lock (_stateLock) { - state.Readiness.TrySetException(exception); - state.Initialization.TrySetException(exception); - utterance?.Completion.TrySetException(exception); - })) - return; - - DeferNativeTeardown( - action => MainThread.BeginInvokeOnMainThread(action), - () => TeardownClient(state, stop: false)); - } - } + utterance = _activeUtterance is { } active && + ReferenceEquals(active.Client, state) && + active.UtteranceId == utteranceId + ? active + : null; + } - void PublishReadyClient(ClientState state) - { - _initializeLock.Wait(); - try - { - if (state.Retired || !ReferenceEquals(_initializingState, state) || _disposed) - return; + if (utterance is null) + return; - _clientState = state; - _initializingState = null; - _readiness = null; + StopQuietly(state.Client); + utterance.Completion.TrySetResult(true); + }); } - finally + + void OnErrorOccurred(TizenTextToSpeechError error) { - _initializeLock.Release(); - } + ActiveUtterance? utterance; + lock (_stateLock) + { + utterance = _activeUtterance; + if (utterance is not null && + (!ReferenceEquals(utterance.Client, state) || + utterance.UtteranceId != error.UtteranceId)) + { + return; + } - state.Readiness.TrySetResult(true); - state.Initialization.TrySetResult(state); - } + if (!RetireClientStateLocked(state)) + return; + } - void SetActiveUtterance( - ClientState state, - int utteranceId, - TaskCompletionSource completion) - { - _initializeLock.Wait(); - try - { - if (state.Retired || !ReferenceEquals(_clientState, state)) - throw new InvalidOperationException("The Tizen text-to-speech client was retired before playback."); + var exception = new InvalidOperationException( + $"Tizen text-to-speech failed ({error.ErrorValue}): {error.ErrorMessage}"); + state.Readiness.TrySetException(exception); + state.Initialization.TrySetException(exception); + utterance?.Completion.TrySetException(exception); - _activeUtterance = new ActiveUtterance(state, utteranceId, completion); - } - finally - { - _initializeLock.Release(); + // Never destroy the native handle from inside the ErrorOccurred callback. + DispatchTeardown(state, stop: false); } } void SetPendingUtterance(ClientState state, TaskCompletionSource completion) { - _initializeLock.Wait(); - try + lock (_stateLock) { ObjectDisposedException.ThrowIf(_disposed, this); if (state.Retired || !ReferenceEquals(_clientState, state)) - throw new InvalidOperationException("The Tizen text-to-speech client was retired before playback."); + throw new InvalidOperationException("The Tizen text-to-speech client was retired."); _utterance = completion; } - finally - { - _initializeLock.Release(); - } - } - - ActiveUtterance? GetMatchingActiveUtterance(ClientState state, int utteranceId) - { - _initializeLock.Wait(); - try - { - return _activeUtterance is { } active && - ReferenceEquals(active.Client, state) && - MatchesUtterance(active.UtteranceId, utteranceId) - ? active - : null; - } - finally - { - _initializeLock.Release(); - } } - bool TryRetireForNativeError( + void SetActiveUtterance( ClientState state, int utteranceId, - out ActiveUtterance? utterance) + TaskCompletionSource completion) { - _initializeLock.Wait(); - try + lock (_stateLock) { - utterance = _activeUtterance; - if (utterance is not null && - (!ReferenceEquals(utterance.Client, state) || - !MatchesUtterance(utterance.UtteranceId, utteranceId))) - { - utterance = null; - return false; - } + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired."); - return RetireClientStateLocked(state); - } - finally - { - _initializeLock.Release(); + _activeUtterance = new ActiveUtterance(state, utteranceId, completion); } } void ClearActiveUtterance(ClientState state, TaskCompletionSource completion) { - _initializeLock.Wait(); - try + lock (_stateLock) { if (_activeUtterance is { } active && ReferenceEquals(active.Client, state) && @@ -503,38 +364,23 @@ void ClearActiveUtterance(ClientState state, TaskCompletionSource completi if (ReferenceEquals(_utterance, completion)) _utterance = null; } - finally - { - _initializeLock.Release(); - } } void CancelClientState( ClientState state, - TaskCompletionSource utterance, + TaskCompletionSource completion, CancellationToken cancelToken) { - CancelUtterance( - utterance, - cancelToken, - () => - { - if (RetireClientState(state)) - TeardownClient(state, stop: true); - }); + if (RetireClientState(state)) + DispatchTeardown(state, stop: true); + + completion.TrySetCanceled(cancelToken); } bool RetireClientState(ClientState state) { - _initializeLock.Wait(); - try - { + lock (_stateLock) return RetireClientStateLocked(state); - } - finally - { - _initializeLock.Release(); - } } bool RetireClientStateLocked(ClientState state) @@ -543,7 +389,6 @@ bool RetireClientStateLocked(ClientState state) return false; state.Retired = true; - if (ReferenceEquals(_clientState, state)) _clientState = null; if (ReferenceEquals(_initializingState, state)) @@ -552,24 +397,69 @@ bool RetireClientStateLocked(ClientState state) _initialization = null; if (ReferenceEquals(_readiness, state.Readiness)) _readiness = null; - return true; } - static void TeardownClient(ClientState state, bool stop) + void DispatchTeardown(ClientState state, bool stop) { - if (Interlocked.Exchange(ref state.TeardownStarted, 1) != 0) + if (Interlocked.Exchange(ref state.TeardownScheduled, 1) != 0) return; - if (stop) - StopQuietly(state.Client); + _dispatcher.Dispatch(() => + { + if (state.Client is null) + return; + + if (stop) + StopQuietly(state.Client); + + state.Client.Dispose(); + }); + } - state.Teardown?.Invoke(); + static void StopQuietly(ITizenTextToSpeechClient client) + { + try + { + client.Stop(); + } + catch (Exception) + { + // Stop is best effort after cancellation, failure, or completion. + } } - internal static void DeferNativeTeardown(Action dispatch, Action teardown) + static (string Language, int VoiceType) ResolveVoice( + ITizenTextToSpeechClient client, + string? requestedLanguage) { - ThreadPool.QueueUserWorkItem(_ => dispatch(teardown)); + var language = "en_US"; + var voiceType = (int)Voice.Auto; + + if (requestedLanguage is { } requested) + { + foreach (var voice in client.GetSupportedVoices()) + { + if (string.Equals(voice.Language, requested, StringComparison.OrdinalIgnoreCase)) + { + language = voice.Language; + voiceType = voice.VoiceType; + break; + } + } + } + + return (language, voiceType); + } + + static int ResolveRate(ITizenTextToSpeechClient client, float? rate) + { + if (rate is not { } value) + return 0; + + return (int)Math.Round( + value / RateMax * client.GetMaximumSpeed(), + MidpointRounding.AwayFromZero); } internal static void FailPendingTasks( @@ -589,8 +479,7 @@ public void Dispose() TaskCompletionSource? readiness; TaskCompletionSource? utterance; - _initializeLock.Wait(); - try + lock (_stateLock) { if (_disposed) return; @@ -609,42 +498,21 @@ public void Dispose() _activeUtterance = null; _utterance = null; } - finally - { - _initializeLock.Release(); - } - - FailPendingTasks( - readiness, - utterance, - new ObjectDisposedException(nameof(TizenTextToSpeech))); - var disposedException = new ObjectDisposedException(nameof(TizenTextToSpeech)); - current?.Initialization.TrySetException(disposedException); - initializing?.Initialization.TrySetException(disposedException); + var exception = new ObjectDisposedException(nameof(TizenTextToSpeech)); + FailPendingTasks(readiness, utterance, exception); + current?.Initialization.TrySetException(exception); + initializing?.Initialization.TrySetException(exception); - _speakLock.Wait(); - try - { - if (current is not null) - TeardownClient(current, stop: true); - if (initializing is not null && !ReferenceEquals(initializing, current)) - TeardownClient(initializing, stop: true); - } - finally - { - _speakLock.Release(); - } + if (current is not null) + DispatchTeardown(current, stop: true); + if (initializing is not null && !ReferenceEquals(initializing, current)) + DispatchTeardown(initializing, stop: true); } sealed class ClientState { - public ClientState(TtsClient client) - { - Client = client; - } - - public TtsClient Client { get; } + public ITizenTextToSpeechClient Client { get; set; } = null!; public TaskCompletionSource Readiness { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -652,11 +520,9 @@ public ClientState(TtsClient client) public TaskCompletionSource Initialization { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public Action? Teardown { get; set; } - public bool Retired { get; set; } - public int TeardownStarted; + public int TeardownScheduled; } sealed record ActiveUtterance( @@ -664,4 +530,112 @@ sealed record ActiveUtterance( int UtteranceId, TaskCompletionSource Completion); } + + internal enum TizenTextToSpeechState + { + Ready, + Other, + } + + internal sealed record TizenTextToSpeechVoice(string Language, int VoiceType); + + internal sealed record TizenTextToSpeechError( + int UtteranceId, + int ErrorValue, + string ErrorMessage); + + internal interface ITizenTextToSpeechDispatcher + { + Task InvokeAsync(Action action); + + Task InvokeAsync(Func action); + + void Dispatch(Action action); + } + + internal interface ITizenTextToSpeechClientFactory + { + ITizenTextToSpeechClient Create(); + } + + internal interface ITizenTextToSpeechClient : IDisposable + { + event Action? StateChanged; + + event Action? UtteranceCompleted; + + event Action? ErrorOccurred; + + void Prepare(); + + IReadOnlyList GetSupportedVoices(); + + int GetMaximumSpeed(); + + int AddText(string text, string language, int voiceType, int speed); + + void Play(); + + void Stop(); + } + + sealed class TizenTextToSpeechDispatcher : ITizenTextToSpeechDispatcher + { + public static TizenTextToSpeechDispatcher Instance { get; } = new(); + + public Task InvokeAsync(Action action) => MainThread.InvokeOnMainThreadAsync(action); + + public Task InvokeAsync(Func action) => MainThread.InvokeOnMainThreadAsync(action); + + public void Dispatch(Action action) => MainThread.BeginInvokeOnMainThread(action); + } + + sealed class TizenTextToSpeechClientFactory : ITizenTextToSpeechClientFactory + { + public static TizenTextToSpeechClientFactory Instance { get; } = new(); + + public ITizenTextToSpeechClient Create() => new TizenTextToSpeechClient(new TtsClient()); + } + + sealed class TizenTextToSpeechClient : ITizenTextToSpeechClient + { + readonly TtsClient _client; + + public TizenTextToSpeechClient(TtsClient client) + { + _client = client; + _client.StateChanged += (_, args) => + StateChanged?.Invoke( + args.Current == State.Ready + ? TizenTextToSpeechState.Ready + : TizenTextToSpeechState.Other); + _client.UtteranceCompleted += (_, args) => UtteranceCompleted?.Invoke(args.UtteranceId); + _client.ErrorOccurred += (_, args) => + ErrorOccurred?.Invoke(new(args.UtteranceId, (int)args.ErrorValue, args.ErrorMessage)); + } + + public event Action? StateChanged; + + public event Action? UtteranceCompleted; + + public event Action? ErrorOccurred; + + public void Prepare() => _client.Prepare(); + + public IReadOnlyList GetSupportedVoices() => + _client.GetSupportedVoices() + .Select(voice => new TizenTextToSpeechVoice(voice.Language, (int)voice.VoiceType)) + .ToArray(); + + public int GetMaximumSpeed() => _client.GetSpeedRange().Max; + + public int AddText(string text, string language, int voiceType, int speed) => + _client.AddText(text, language, voiceType, speed); + + public void Play() => _client.Play(); + + public void Stop() => _client.Stop(); + + public void Dispose() => _client.Dispose(); + } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 8253f062..2e05d0ef 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; @@ -259,7 +260,7 @@ public void SecureStorageAliasesAreNamespaced() var alias = TizenSecureStorage.ToAlias("token"); Assert.StartsWith(TizenSecureStorage.AliasPrefix, alias, StringComparison.Ordinal); - Assert.StartsWith(TizenSecureStorage.AliasPrefix + "v2:", alias, StringComparison.Ordinal); + Assert.StartsWith(TizenSecureStorage.AliasPrefix + "~v2~", alias, StringComparison.Ordinal); Assert.DoesNotContain(alias, char.IsWhiteSpace); } @@ -278,13 +279,92 @@ public void SecureStorageAliasesCannotCollideWithEachOther() [InlineData("a:b~c\\d")] public void SecureStorageAliasesAreWhitespaceFreeBase64Url(string key) { - var encoded = TizenSecureStorage.ToAlias(key)[(TizenSecureStorage.AliasPrefix.Length + 3)..]; + var encoded = TizenSecureStorage.ToAlias(key)[(TizenSecureStorage.AliasPrefix.Length + 4)..]; Assert.NotEmpty(encoded); Assert.All(encoded, character => Assert.True( char.IsAsciiLetterOrDigit(character) || character is '-' or '_')); } + [Fact] + public void SecureStorageAliasVersionsCannotCollideInEitherDirection() + { + string[] keys = + [ + "", + "token", + "~v2~dG9rZW4", + "v2:dG9rZW4", + "a~b", + "a\\~b", + "api token", + "秘密", + ]; + + foreach (var v2Key in keys) + { + foreach (var v1Key in keys) + { + Assert.NotEqual( + TizenSecureStorage.ToAlias(v2Key), + TizenSecureStorage.ToLegacyNamespacedAlias(v1Key)); + } + } + } + + [Fact] + public void SecureStorageAliasVersionNamespacesAreDisjointForGeneratedKeys() + { + var keys = Enumerable.Range(0, 4096) + .Select(value => (value % 4) switch + { + 0 => value.ToString(), + 1 => "~v2~" + value, + 2 => "key~" + (char)('a' + value % 26) + value, + _ => "ключ-" + value, + }) + .ToArray(); + var v2Aliases = keys.Select(TizenSecureStorage.ToAlias).ToHashSet(StringComparer.Ordinal); + var v1Aliases = keys.Select(TizenSecureStorage.ToLegacyNamespacedAlias).ToHashSet(StringComparer.Ordinal); + + Assert.Empty(v2Aliases.Intersect(v1Aliases)); + } + + [Fact] + public void SecureStorageAliasEncodingIsInjectiveAcrossUtf16CodeUnits() + { + var keys = Enumerable.Range(0, 0x10000) + .Where(value => value is < 0xD800 or > 0xDFFF) + .Select(value => new string((char)value, 1)) + .ToArray(); + + Assert.Equal(keys.Length, keys.Select(TizenSecureStorage.ToAlias).Distinct().Count()); + } + + [Fact] + public async Task SecureStorageRejectsIllFormedUtf16BeforeMutation() + { + string[] keys = + [ + new string((char)0xD800, 1), + new string((char)0xDC00, 1), + "prefix" + (char)0xD800 + "suffix", + ]; + + foreach (var key in keys) + { + var repository = new FakeSecureRepository(); + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + await Assert.ThrowsAsync(() => storage.SetAsync(key, "value")); + Assert.Throws(() => storage.Remove(key)); + await Assert.ThrowsAsync(() => storage.GetAsync(key)); + Assert.Empty(repository.GetAliases()); + Assert.False(tombstones.Contains(key)); + } + } + [Theory] [InlineData("maui.tizen.securestorage:token", true)] [InlineData("org.example.app maui.tizen.securestorage:token", true)] @@ -384,6 +464,20 @@ public async Task SecureStorageWhitespaceKeyUsesOnlyNativeSafeAliases() Assert.False(TizenSecureStorage.CanUseLegacyNamespacedAlias("api token")); } + [Fact] + public async Task SecureStorageInvalidRawLegacyAliasIsAbsentBeforeAnyWrite() + { + var repository = new FakeSecureRepository + { + RejectWhitespaceAliases = true, + }; + var storage = new TizenSecureStorage(repository); + + Assert.Null(await storage.GetAsync("api token")); + Assert.Empty(repository.GetAliases()); + Assert.Equal(0, repository.SuccessfulSaves); + } + [Fact] public async Task SecureStorageDoesNotTruncateAliasesRejectedByTheNativeLimit() { @@ -564,115 +658,153 @@ public async Task TextToSpeechPreCancellationUsesTheCallerToken() } [Fact] - public async Task TextToSpeechInFlightCancellationUsesTheCallerToken() + public async Task TextToSpeechRunsEveryNativeOperationOnTheDispatcherThread() { - using var source = new CancellationTokenSource(); - var utterance = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var stopped = false; - var retiredBeforeCancellationSettled = false; + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); - TizenTextToSpeech.CancelUtterance(utterance, source.Token, () => - { - retiredBeforeCancellationSettled = !utterance.Task.IsCompleted; - stopped = true; - }); + var speak = textToSpeech.SpeakAsync( + "hello", + cancelToken: TestContext.Current.CancellationToken); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + await client.CompleteAsync(client.LastUtteranceId); + await speak; - var exception = await Assert.ThrowsAnyAsync(() => utterance.Task); + var languages = await textToSpeech.GetSupportedVoiceLanguagesAsync(); + Assert.Equal(["en_US"], languages); - Assert.True(stopped); - Assert.True(retiredBeforeCancellationSettled); - Assert.Equal(source.Token, exception.CancellationToken); + textToSpeech.Dispose(); + await client.Disposed.Task; + Assert.Empty(client.WrongThreadOperations); } [Fact] - public void TextToSpeechPlayFailureRetiresBeforeRethrowing() + public async Task TextToSpeechCancellationRetiresBeforeSettlingAndTeardownRunsOnDispatcher() { - var retired = false; + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + using var cancellation = new CancellationTokenSource(); + + var speak = textToSpeech.SpeakAsync("cancel me", cancelToken: cancellation.Token); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + var queued = textToSpeech.SpeakAsync( + "fresh", + cancelToken: TestContext.Current.CancellationToken); + cancellation.Cancel(); - Assert.Throws(() => - TizenTextToSpeech.PlayOrRetire( - () => throw new InvalidOperationException("play failed"), - () => retired = true)); + var exception = await Assert.ThrowsAnyAsync(() => speak); + await client.Disposed.Task; + Assert.Equal(cancellation.Token, exception.CancellationToken); + Assert.True(client.StoppedBeforeDisposed); + Assert.Empty(client.WrongThreadOperations); - Assert.True(retired); + var freshClient = await factory.WaitForClientAsync(2); + Assert.NotSame(client, freshClient); + await freshClient.Played.Task; + await freshClient.CompleteAsync(freshClient.LastUtteranceId); + await queued; } [Fact] - public void TextToSpeechIgnoresStaleUtteranceCallbacks() + public async Task TextToSpeechNativeErrorDefersTeardownAndQueuedRequestUsesFreshClient() { - Assert.True(TizenTextToSpeech.MatchesUtterance(42, 42)); - Assert.False(TizenTextToSpeech.MatchesUtterance(42, 41)); + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var active = textToSpeech.SpeakAsync( + "active", + cancelToken: TestContext.Current.CancellationToken); + var firstClient = await factory.WaitForClientAsync(); + await firstClient.Played.Task; + var queued = textToSpeech.SpeakAsync( + "queued", + cancelToken: TestContext.Current.CancellationToken); + + await firstClient.FailAsync(firstClient.LastUtteranceId); + await Assert.ThrowsAsync(() => active); + await firstClient.Disposed.Task; + + var secondClient = await factory.WaitForClientAsync(2); + Assert.NotSame(firstClient, secondClient); + await secondClient.Played.Task; + await secondClient.CompleteAsync(secondClient.LastUtteranceId); + await queued; + Assert.False(firstClient.DisposedInsideCallback); + Assert.Empty(firstClient.WrongThreadOperations); + Assert.Empty(secondClient.WrongThreadOperations); } [Fact] - public void TextToSpeechNativeErrorRetiresBeforeTaskSettlement() + public async Task TextToSpeechPlayFailureRetiresClientBeforeRetry() { - var retired = false; - var settledAfterRetirement = false; - - Assert.True(TizenTextToSpeech.RetireBeforeSettle( - () => - { - retired = true; - return true; - }, - () => settledAfterRetirement = retired)); - - Assert.True(settledAfterRetirement); + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher) + { + FailFirstPlay = true, + }; + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + await Assert.ThrowsAsync(() => + textToSpeech.SpeakAsync( + "fails", + cancelToken: TestContext.Current.CancellationToken)); + var failedClient = await factory.WaitForClientAsync(); + await failedClient.Disposed.Task; + Assert.True(failedClient.StoppedBeforeDisposed); + + var retry = textToSpeech.SpeakAsync( + "retry", + cancelToken: TestContext.Current.CancellationToken); + var retryClient = await factory.WaitForClientAsync(2); + await retryClient.Played.Task; + await retryClient.CompleteAsync(retryClient.LastUtteranceId); + await retry; + Assert.NotSame(failedClient, retryClient); } [Fact] - public async Task TextToSpeechNativeTeardownIsDeferred() + public async Task TextToSpeechIgnoresOldUtteranceCompletion() { - using var allowDispatch = new ManualResetEventSlim(); - var tornDown = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - TizenTextToSpeech.DeferNativeTeardown( - action => - { - allowDispatch.Wait(TestContext.Current.CancellationToken); - action(); - }, - () => tornDown.SetResult()); - - Assert.False(tornDown.Task.IsCompleted); - allowDispatch.Set(); - await tornDown.Task.WaitAsync(TestContext.Current.CancellationToken); + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var speak = textToSpeech.SpeakAsync( + "current", + cancelToken: TestContext.Current.CancellationToken); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + await client.CompleteAsync(client.LastUtteranceId - 1); + Assert.False(speak.IsCompleted); + await client.CompleteAsync(client.LastUtteranceId); + await speak; } [Fact] - public async Task TextToSpeechClientGuardSerializesVoiceQueriesAndSpeech() + public async Task TextToSpeechVoiceQueryWaitsBehindActiveSpeech() { - using var clientLock = new SemaphoreSlim(1, 1); - var firstStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var releaseFirst = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var secondStarted = false; - - var first = TizenTextToSpeech.RunWithCurrentClientAsync( - clientLock, - CancellationToken.None, - _ => Task.FromResult("client"), - async _ => - { - firstStarted.SetResult(); - await releaseFirst.Task; - }); - - await firstStarted.Task; - var second = TizenTextToSpeech.RunWithCurrentClientAsync( - clientLock, - CancellationToken.None, - _ => Task.FromResult("client"), - _ => - { - secondStarted = true; - return Task.CompletedTask; - }); - - Assert.False(secondStarted); - releaseFirst.SetResult(); - await Task.WhenAll(first, second); - Assert.True(secondStarted); + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var speak = textToSpeech.SpeakAsync( + "active", + cancelToken: TestContext.Current.CancellationToken); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + var languages = textToSpeech.GetSupportedVoiceLanguagesAsync(); + + await Task.Delay(25, TestContext.Current.CancellationToken); + Assert.Equal(0, client.GetSupportedVoicesCalls); + await client.CompleteAsync(client.LastUtteranceId); + await speak; + Assert.Equal(["en_US"], await languages); + Assert.Equal(1, client.GetSupportedVoicesCalls); } [Fact] @@ -967,6 +1099,236 @@ public void SensorStartRollbackResetsEvenWhenCleanupFails() Assert.True(reset); } + sealed class FakeTextToSpeechDispatcher : ITizenTextToSpeechDispatcher, IDisposable + { + readonly BlockingCollection _work = []; + readonly Thread _thread; + readonly ManualResetEventSlim _started = new(); + + public FakeTextToSpeechDispatcher() + { + _thread = new Thread(Run) + { + IsBackground = true, + Name = "Fake Tizen Ecore thread", + }; + _thread.Start(); + _started.Wait(); + } + + public int ThreadId { get; private set; } + + public Task InvokeAsync(Action action) + { + if (Thread.CurrentThread.ManagedThreadId == ThreadId) + { + action(); + return Task.CompletedTask; + } + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _work.Add(() => + { + try + { + action(); + completion.SetResult(); + } + catch (Exception exception) + { + completion.SetException(exception); + } + }); + return completion.Task; + } + + public Task InvokeAsync(Func action) + { + if (Thread.CurrentThread.ManagedThreadId == ThreadId) + return Task.FromResult(action()); + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _work.Add(() => + { + try + { + completion.SetResult(action()); + } + catch (Exception exception) + { + completion.SetException(exception); + } + }); + return completion.Task; + } + + public void Dispatch(Action action) => _work.Add(action); + + public void Dispose() + { + _work.CompleteAdding(); + _thread.Join(); + _started.Dispose(); + _work.Dispose(); + } + + void Run() + { + ThreadId = Thread.CurrentThread.ManagedThreadId; + _started.Set(); + foreach (var action in _work.GetConsumingEnumerable()) + action(); + } + } + + sealed class FakeTextToSpeechClientFactory : ITizenTextToSpeechClientFactory + { + readonly FakeTextToSpeechDispatcher _dispatcher; + readonly List _clients = []; + + public FakeTextToSpeechClientFactory(FakeTextToSpeechDispatcher dispatcher) + { + _dispatcher = dispatcher; + } + + public bool FailFirstPlay { get; init; } + + public ITizenTextToSpeechClient Create() + { + Assert.Equal(_dispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); + var client = new FakeTextToSpeechClient( + _dispatcher, + throwOnPlay: FailFirstPlay && _clients.Count == 0); + lock (_clients) + _clients.Add(client); + return client; + } + + public async Task WaitForClientAsync(int count = 1) + { + while (true) + { + lock (_clients) + { + if (_clients.Count >= count) + return _clients[count - 1]; + } + + await Task.Delay(1, TestContext.Current.CancellationToken); + } + } + } + + sealed class FakeTextToSpeechClient : ITizenTextToSpeechClient + { + readonly FakeTextToSpeechDispatcher _dispatcher; + readonly bool _throwOnPlay; + bool _insideErrorCallback; + bool _stopped; + int _nextUtteranceId; + + public FakeTextToSpeechClient( + FakeTextToSpeechDispatcher dispatcher, + bool throwOnPlay) + { + _dispatcher = dispatcher; + _throwOnPlay = throwOnPlay; + } + + public event Action? StateChanged; + + public event Action? UtteranceCompleted; + + public event Action? ErrorOccurred; + + public ConcurrentQueue WrongThreadOperations { get; } = []; + + public TaskCompletionSource Played { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Disposed { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public int LastUtteranceId { get; private set; } + + public int GetSupportedVoicesCalls { get; private set; } + + public bool StoppedBeforeDisposed { get; private set; } + + public bool DisposedInsideCallback { get; private set; } + + public void Prepare() + { + AssertThread(nameof(Prepare)); + StateChanged?.Invoke(TizenTextToSpeechState.Ready); + } + + public IReadOnlyList GetSupportedVoices() + { + AssertThread(nameof(GetSupportedVoices)); + GetSupportedVoicesCalls++; + return [new("en_US", 0)]; + } + + public int GetMaximumSpeed() + { + AssertThread(nameof(GetMaximumSpeed)); + return 10; + } + + public int AddText(string text, string language, int voiceType, int speed) + { + AssertThread(nameof(AddText)); + LastUtteranceId = ++_nextUtteranceId; + return LastUtteranceId; + } + + public void Play() + { + AssertThread(nameof(Play)); + if (_throwOnPlay) + throw new InvalidOperationException("play failed"); + Played.TrySetResult(); + } + + public void Stop() + { + AssertThread(nameof(Stop)); + _stopped = true; + } + + public void Dispose() + { + AssertThread(nameof(Dispose)); + DisposedInsideCallback = _insideErrorCallback; + StoppedBeforeDisposed = _stopped; + Disposed.TrySetResult(); + } + + public Task CompleteAsync(int utteranceId) => + _dispatcher.InvokeAsync(() => UtteranceCompleted?.Invoke(utteranceId)); + + public Task FailAsync(int utteranceId) => + _dispatcher.InvokeAsync(() => + { + _insideErrorCallback = true; + try + { + ErrorOccurred?.Invoke(new(utteranceId, 1, "native failure")); + } + finally + { + _insideErrorCallback = false; + } + }); + + void AssertThread(string operation) + { + if (Thread.CurrentThread.ManagedThreadId != _dispatcher.ThreadId) + WrongThreadOperations.Enqueue(operation); + } + } + sealed class FakeSecureRepository : ITizenSecureRepository { readonly Dictionary _values = new(StringComparer.Ordinal); From 74ca0e46739787991711b052363319e96463c383 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 14:59:56 -0400 Subject: [PATCH 13/21] Close TTS dispatcher race windows Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: f10f5376-08fd-4221-8332-7c3b3865f0b2 --- docs/tizen-essentials-service-coverage.md | 4 +- eng/build-workload-free.sh | 2 +- .../TextToSpeech/TizenTextToSpeech.cs | 131 ++++++++++-- .../TizenServiceBehaviorTests.cs | 197 +++++++++++++++++- 4 files changed, 305 insertions(+), 29 deletions(-) diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 8d22b1ca..7a3795e8 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -63,7 +63,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | | `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | -| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; every native client operation is serialized and dispatched to Tizen's Ecore/main loop, with generation-safe cancellation/error teardown. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | +| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; every native client operation is serialized and dispatched to Tizen's Ecore/main loop. Cancellation/error retires the generation immediately, then force-posts native teardown so disposal cannot occur inside a callback. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | | `IVibration` | `TizenVibration` | Implemented | Mobile, Wearable | `Tizen.System.Vibrator`; requires the `haptic` privilege. | | `IWebAuthenticator` | `TizenWebAuthenticator` | Unsupported | – | Tizen has no callback URI registration that returns an external browser response to the app. | @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (332 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (337 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 2c7937fd..2480a8cd 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=332 + ESSENTIALS_TESTS_MINIMUM=337 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index 93d269c8..2bf2c17b 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -72,7 +72,11 @@ await RunWithCurrentClientAsync( InitializeAsync, async state => { - var voices = await _dispatcher.InvokeAsync(state.Client.GetSupportedVoices).ConfigureAwait(false); + var voices = await _dispatcher.InvokeAsync(() => + { + ThrowIfNativeCallInvalid(state, CancellationToken.None); + return state.Client!.GetSupportedVoices(); + }).ConfigureAwait(false); foreach (var voice in voices) { if (!languages.Any(value => @@ -147,12 +151,13 @@ await RunWithCurrentClientAsync( var utteranceId = await _dispatcher.InvokeAsync(() => { - var (resolvedLanguage, voiceType) = ResolveVoice(state.Client, language); - return state.Client.AddText( + ThrowIfNativeCallInvalid(state, cancelToken); + var (resolvedLanguage, voiceType) = ResolveVoice(state.Client!, language); + return state.Client!.AddText( text, resolvedLanguage, voiceType, - ResolveRate(state.Client, rate)); + ResolveRate(state.Client!, rate)); }).ConfigureAwait(false); SetActiveUtterance(state, utteranceId, completion); @@ -160,7 +165,11 @@ await RunWithCurrentClientAsync( try { - await _dispatcher.InvokeAsync(state.Client.Play).ConfigureAwait(false); + await _dispatcher.InvokeAsync(() => + { + ThrowIfNativeCallInvalid(state, cancelToken); + state.Client!.Play(); + }).ConfigureAwait(false); } catch { @@ -249,11 +258,48 @@ async Task InitializeAsync(CancellationToken cancelToken) void PrepareOnMainThread(ClientState state) { - state.Client = _clientFactory.Create(); - state.Client.StateChanged += OnStateChanged; - state.Client.UtteranceCompleted += OnUtteranceCompleted; - state.Client.ErrorOccurred += OnErrorOccurred; - state.Client.Prepare(); + lock (_stateLock) + { + if (state.Retired || _disposed || !ReferenceEquals(_initializingState, state)) + return; + } + + var client = _clientFactory.Create(); + var retireLateClient = false; + lock (_stateLock) + { + state.Client = client; + retireLateClient = + state.Retired || + _disposed || + !ReferenceEquals(_initializingState, state); + } + + if (retireLateClient) + { + DispatchTeardown(state, stop: true); + return; + } + + client.StateChanged += OnStateChanged; + client.UtteranceCompleted += OnUtteranceCompleted; + client.ErrorOccurred += OnErrorOccurred; + + lock (_stateLock) + { + retireLateClient = + state.Retired || + _disposed || + !ReferenceEquals(_initializingState, state); + } + + if (retireLateClient) + { + DispatchTeardown(state, stop: true); + return; + } + + client.Prepare(); void OnStateChanged(TizenTextToSpeechState current) { @@ -276,7 +322,7 @@ void OnStateChanged(TizenTextToSpeechState current) void OnUtteranceCompleted(int utteranceId) { - _dispatcher.Dispatch(() => + _dispatcher.Post(() => { ActiveUtterance? utterance; lock (_stateLock) @@ -291,7 +337,7 @@ void OnUtteranceCompleted(int utteranceId) if (utterance is null) return; - StopQuietly(state.Client); + StopQuietly(state.Client!); utterance.Completion.TrySetResult(true); }); } @@ -402,21 +448,50 @@ bool RetireClientStateLocked(ClientState state) void DispatchTeardown(ClientState state, bool stop) { - if (Interlocked.Exchange(ref state.TeardownScheduled, 1) != 0) - return; + lock (_stateLock) + { + state.TeardownRequested = true; + state.StopBeforeTeardown |= stop; + + if (state.Client is null || state.TeardownPosted) + return; - _dispatcher.Dispatch(() => + state.TeardownPosted = true; + } + + _dispatcher.Post(() => { - if (state.Client is null) + var client = state.Client; + if (client is null) return; - if (stop) - StopQuietly(state.Client); + if (state.StopBeforeTeardown) + StopQuietly(client); - state.Client.Dispose(); + try + { + client.Dispose(); + } + catch (Exception) + { + // Teardown is best effort and must not terminate the Ecore loop. + } }); } + void ThrowIfNativeCallInvalid(ClientState state, CancellationToken cancelToken) + { + cancelToken.ThrowIfCancellationRequested(); + + lock (_stateLock) + { + cancelToken.ThrowIfCancellationRequested(); + ObjectDisposedException.ThrowIf(_disposed, this); + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired."); + } + } + static void StopQuietly(ITizenTextToSpeechClient client) { try @@ -512,7 +587,7 @@ public void Dispose() sealed class ClientState { - public ITizenTextToSpeechClient Client { get; set; } = null!; + public ITizenTextToSpeechClient? Client { get; set; } public TaskCompletionSource Readiness { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -522,7 +597,11 @@ sealed class ClientState public bool Retired { get; set; } - public int TeardownScheduled; + public bool TeardownRequested { get; set; } + + public bool StopBeforeTeardown { get; set; } + + public bool TeardownPosted { get; set; } } sealed record ActiveUtterance( @@ -550,7 +629,7 @@ internal interface ITizenTextToSpeechDispatcher Task InvokeAsync(Func action); - void Dispatch(Action action); + void Post(Action action); } internal interface ITizenTextToSpeechClientFactory @@ -587,7 +666,13 @@ sealed class TizenTextToSpeechDispatcher : ITizenTextToSpeechDispatcher public Task InvokeAsync(Func action) => MainThread.InvokeOnMainThreadAsync(action); - public void Dispatch(Action action) => MainThread.BeginInvokeOnMainThread(action); + public void Post(Action action) => + MainThread.BeginInvokeOnMainThread(() => + { + var context = SynchronizationContext.Current ?? + throw new InvalidOperationException("The Tizen main loop has no synchronization context."); + context.Post(static state => ((Action)state!).Invoke(), action); + }); } sealed class TizenTextToSpeechClientFactory : ITizenTextToSpeechClientFactory diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 2e05d0ef..b1afba04 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -739,6 +739,110 @@ public async Task TextToSpeechNativeErrorDefersTeardownAndQueuedRequestUsesFresh Assert.Empty(secondClient.WrongThreadOperations); } + [Fact] + public async Task TextToSpeechErrorTeardownIsPostedWhenMainThreadDispatchWouldInline() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var speak = textToSpeech.SpeakAsync( + "active", + cancelToken: TestContext.Current.CancellationToken); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + await client.FailAsync(client.LastUtteranceId); + + await Assert.ThrowsAsync(() => speak); + await client.Disposed.Task; + Assert.False(client.DisposedInsideCallback); + } + + [Fact] + public async Task TextToSpeechDisposeBeforeQueuedConstructionDoesNotCreateClient() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var blocked = dispatcher.BlockNextAction(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var speak = textToSpeech.SpeakAsync( + "never constructed", + cancelToken: TestContext.Current.CancellationToken); + await blocked.Queued; + textToSpeech.Dispose(); + blocked.Release(); + + await Assert.ThrowsAsync(() => speak); + Assert.Equal(0, factory.ClientCount); + } + + [Fact] + public async Task TextToSpeechCancellationBeforeQueuedAddTextSkipsNativeCall() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + await textToSpeech.GetSupportedVoiceLanguagesAsync(); + var client = await factory.WaitForClientAsync(); + var blocked = dispatcher.BlockNextAction(); + using var cancellation = new CancellationTokenSource(); + + var speak = textToSpeech.SpeakAsync("cancelled", cancelToken: cancellation.Token); + await blocked.Queued; + cancellation.Cancel(); + blocked.Release(); + + await Assert.ThrowsAnyAsync(() => speak); + await client.Disposed.Task; + Assert.Equal(0, client.AddTextCalls); + Assert.Equal(0, client.PlayCalls); + } + + [Fact] + public async Task TextToSpeechCancellationBeforeQueuedPlaySkipsPlayback() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher) + { + BlockAfterAddText = true, + }; + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + using var cancellation = new CancellationTokenSource(); + + var speak = textToSpeech.SpeakAsync("cancelled", cancelToken: cancellation.Token); + var client = await factory.WaitForClientAsync(); + var blocked = await factory.WaitForBlockedActionAsync(); + await blocked.Queued; + cancellation.Cancel(); + blocked.Release(); + + await Assert.ThrowsAnyAsync(() => speak); + await client.Disposed.Task; + Assert.Equal(1, client.AddTextCalls); + Assert.Equal(0, client.PlayCalls); + Assert.True(client.StoppedBeforeDisposed); + } + + [Fact] + public async Task TextToSpeechDisposeFailureDoesNotStopDispatcherLoop() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher) + { + ThrowOnDispose = true, + }; + var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + await textToSpeech.GetSupportedVoiceLanguagesAsync(); + var client = await factory.WaitForClientAsync(); + + textToSpeech.Dispose(); + await client.DisposeAttempted.Task; + var dispatcherStillRunning = false; + await dispatcher.InvokeAsync(() => dispatcherStillRunning = true); + Assert.True(dispatcherStillRunning); + } + [Fact] public async Task TextToSpeechPlayFailureRetiresClientBeforeRetry() { @@ -1104,6 +1208,8 @@ sealed class FakeTextToSpeechDispatcher : ITizenTextToSpeechDispatcher, IDisposa readonly BlockingCollection _work = []; readonly Thread _thread; readonly ManualResetEventSlim _started = new(); + readonly object _blockLock = new(); + BlockedAction? _nextBlockedAction; public FakeTextToSpeechDispatcher() { @@ -1145,7 +1251,9 @@ public Task InvokeAsync(Action action) public Task InvokeAsync(Func action) { if (Thread.CurrentThread.ManagedThreadId == ThreadId) + { return Task.FromResult(action()); + } var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _work.Add(() => @@ -1162,7 +1270,19 @@ public Task InvokeAsync(Func action) return completion.Task; } - public void Dispatch(Action action) => _work.Add(action); + public void Post(Action action) => _work.Add(action); + + public BlockedAction BlockNextAction() + { + lock (_blockLock) + { + if (_nextBlockedAction is not null) + throw new InvalidOperationException("An action is already blocked."); + + _nextBlockedAction = new BlockedAction(); + return _nextBlockedAction; + } + } public void Dispose() { @@ -1177,7 +1297,37 @@ void Run() ThreadId = Thread.CurrentThread.ManagedThreadId; _started.Set(); foreach (var action in _work.GetConsumingEnumerable()) + { + BlockedAction? blocked; + lock (_blockLock) + { + blocked = _nextBlockedAction; + _nextBlockedAction = null; + } + + if (blocked is not null) + { + blocked.MarkQueued(); + blocked.Wait(); + } + action(); + } + } + + public sealed class BlockedAction + { + readonly TaskCompletionSource _queued = + new(TaskCreationOptions.RunContinuationsAsynchronously); + readonly ManualResetEventSlim _release = new(); + + public Task Queued => _queued.Task; + + public void Release() => _release.Set(); + + internal void MarkQueued() => _queued.TrySetResult(); + + internal void Wait() => _release.Wait(TestContext.Current.CancellationToken); } } @@ -1185,6 +1335,8 @@ sealed class FakeTextToSpeechClientFactory : ITizenTextToSpeechClientFactory { readonly FakeTextToSpeechDispatcher _dispatcher; readonly List _clients = []; + readonly TaskCompletionSource _blockedAction = + new(TaskCreationOptions.RunContinuationsAsynchronously); public FakeTextToSpeechClientFactory(FakeTextToSpeechDispatcher dispatcher) { @@ -1193,12 +1345,29 @@ public FakeTextToSpeechClientFactory(FakeTextToSpeechDispatcher dispatcher) public bool FailFirstPlay { get; init; } + public bool BlockAfterAddText { get; init; } + + public bool ThrowOnDispose { get; init; } + + public int ClientCount + { + get + { + lock (_clients) + return _clients.Count; + } + } + public ITizenTextToSpeechClient Create() { Assert.Equal(_dispatcher.ThreadId, Thread.CurrentThread.ManagedThreadId); var client = new FakeTextToSpeechClient( _dispatcher, - throwOnPlay: FailFirstPlay && _clients.Count == 0); + throwOnPlay: FailFirstPlay && _clients.Count == 0, + throwOnDispose: ThrowOnDispose, + onAddText: BlockAfterAddText + ? () => _blockedAction.TrySetResult(_dispatcher.BlockNextAction()) + : null); lock (_clients) _clients.Add(client); return client; @@ -1217,22 +1386,31 @@ public async Task WaitForClientAsync(int count = 1) await Task.Delay(1, TestContext.Current.CancellationToken); } } + + public Task WaitForBlockedActionAsync() => + _blockedAction.Task.WaitAsync(TestContext.Current.CancellationToken); } sealed class FakeTextToSpeechClient : ITizenTextToSpeechClient { readonly FakeTextToSpeechDispatcher _dispatcher; readonly bool _throwOnPlay; + readonly bool _throwOnDispose; + readonly Action? _onAddText; bool _insideErrorCallback; bool _stopped; int _nextUtteranceId; public FakeTextToSpeechClient( FakeTextToSpeechDispatcher dispatcher, - bool throwOnPlay) + bool throwOnPlay, + bool throwOnDispose, + Action? onAddText) { _dispatcher = dispatcher; _throwOnPlay = throwOnPlay; + _throwOnDispose = throwOnDispose; + _onAddText = onAddText; } public event Action? StateChanged; @@ -1249,6 +1427,9 @@ public FakeTextToSpeechClient( public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource DisposeAttempted { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public int LastUtteranceId { get; private set; } public int GetSupportedVoicesCalls { get; private set; } @@ -1257,6 +1438,10 @@ public FakeTextToSpeechClient( public bool DisposedInsideCallback { get; private set; } + public int AddTextCalls { get; private set; } + + public int PlayCalls { get; private set; } + public void Prepare() { AssertThread(nameof(Prepare)); @@ -1279,13 +1464,16 @@ public int GetMaximumSpeed() public int AddText(string text, string language, int voiceType, int speed) { AssertThread(nameof(AddText)); + AddTextCalls++; LastUtteranceId = ++_nextUtteranceId; + _onAddText?.Invoke(); return LastUtteranceId; } public void Play() { AssertThread(nameof(Play)); + PlayCalls++; if (_throwOnPlay) throw new InvalidOperationException("play failed"); Played.TrySetResult(); @@ -1302,6 +1490,9 @@ public void Dispose() AssertThread(nameof(Dispose)); DisposedInsideCallback = _insideErrorCallback; StoppedBeforeDisposed = _stopped; + DisposeAttempted.TrySetResult(); + if (_throwOnDispose) + throw new InvalidOperationException("dispose failed"); Disposed.TrySetResult(); } From 396de81b1b1fcf03c5e2bde0ad928424bbd1750d Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 17:47:29 -0400 Subject: [PATCH 14/21] Fix Tizen app control payloads Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: f10f5376-08fd-4221-8332-7c3b3865f0b2 --- docs/tizen-essentials-service-coverage.md | 8 +- eng/build-workload-free.sh | 2 +- src/Maui.Tizen.Essentials/Email/TizenEmail.cs | 26 +++-- .../Geolocation/TizenGeolocation.cs | 41 +++++++- .../Launcher/TizenLauncher.cs | 2 +- src/Maui.Tizen.Essentials/Map/TizenMap.cs | 19 +++- src/Maui.Tizen.Essentials/Share/TizenShare.cs | 40 ++++++-- .../TizenServiceBehaviorTests.cs | 96 +++++++++++++++++++ 8 files changed, 207 insertions(+), 27 deletions(-) diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 7a3795e8..4261d92a 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -41,12 +41,12 @@ Profile column values are the Tizen device profiles on which the service is usab | `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. `GetAllAsync` requests runtime `contact.read` consent and materialises the result before disposing the native cursor. | | `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | | `IDeviceInfo` | `TizenDeviceInfo` | Implemented | All | System / feature information keys. | -| `IEmail` | `TizenEmail` | Partial | Mobile | Attachments are rejected: the Tizen `compose` AppControl accepts no attachment payload. Gated on the `email` feature key. | +| `IEmail` | `TizenEmail` | Implemented | Mobile | Tizen `compose` AppControl, including enumerable attachment paths and a compatible MIME filter. Gated on the `email` feature key. | | `IFilePicker` | `TizenFilePicker` | Partial | All | Tizen's `pick` operation accepts one MIME filter, so only the first entry of `PickOptions.FileTypes` is applied. | | `IFileSystem` | `TizenFileSystem` | Implemented | All | Application `DirectoryInfo` data / cache / resource paths. | | `IFlashlight` | `TizenFlashlight` | Implemented | Mobile | `Tizen.System.Led`. Gated on `camera.back.flash`; requires the `led` privilege. | | `IGeocoding` | `TizenGeocoding` | Unsupported | – | `Tizen.Maps` (`MapService`) was deprecated in TizenFX API11 and **removed by API15**; there is no replacement. `MapServiceToken` is still accepted so a configured token cannot crash startup, but it is never used. | -| `IGeolocation` | `TizenGeolocation` | Partial | All | One-shot `GetLocationAsync` works. `StartListeningForegroundAsync` / `StopListeningForeground` throw. | +| `IGeolocation` | `TizenGeolocation` | Partial | All | One-shot `GetLocationAsync` works. `IsEnabled` checks the enabled state of supported GPS/WPS services, not only hardware presence. `StartListeningForegroundAsync` / `StopListeningForeground` throw. | | `IGyroscope` | `TizenGyroscope` | Implemented | All | `Tizen.Sensor.Gyroscope`. | | `IHapticFeedback` | `TizenHapticFeedback` | Implemented | Mobile, Wearable | `Tizen.System.Feedback`. Unsupported patterns throw instead of silently doing nothing. | | `ILauncher` | `TizenLauncher` | Implemented | All | AppControl launch requests with scheme-based operation selection. `CanOpenAsync`/`TryOpenAsync` query matched application ids, so `TryOpenAsync` returns `false` instead of throwing when nothing handles the URI. | @@ -61,7 +61,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders; native handles disposed, RGBX/BGRX treated as opaque, and a bounded wait for `Capture.Finished`. Also implements `IViewScreenshot`. | | `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. Versioned Base64url aliases are whitespace-free and private to this API; reads migrate earlier namespaced/raw aliases, while tombstones prevent removed raw values from resurfacing. | | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | -| `IShare` | `TizenShare` | Implemented | All | `share` / `share_text` AppControls. | +| `IShare` | `TizenShare` | Implemented | All | `share_text`, `share`, and `multi_share` AppControls; file paths are sent as one enumerable payload with a compatible MIME filter. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | | `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; every native client operation is serialized and dispatched to Tizen's Ecore/main loop. Cancellation/error retires the generation immediately, then force-posts native teardown so disposal cannot occur inside a callback. `GetLocalesAsync` throws (see API gaps below); use `GetSupportedVoiceLanguagesAsync` with `SpeakWithVoiceAsync`. `SpeechOptions.Pitch` / `Volume` are rejected. | | `IVibration` | `TizenVibration` | Implemented | Mobile, Wearable | `Tizen.System.Vibrator`; requires the `haptic` privilege. | @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (337 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (346 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 2480a8cd..23080452 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=337 + ESSENTIALS_TESTS_MINIMUM=346 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs index b1bcd17d..59606415 100644 --- a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs +++ b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs @@ -12,10 +12,7 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// /// Tizen implementation of , backed by the mailto: compose AppControl. /// - /// - /// Tizen's compose operation has no attachment slot, so - /// is rejected rather than silently dropped, and HTML bodies are sent as plain text. - /// + /// HTML bodies are sent as plain text. public sealed class TizenEmail : IEmail { /// @@ -38,11 +35,11 @@ public Task ComposeAsync(EmailMessage? message) if (message is not null) { - if (message.Attachments?.Count > 0) + var attachments = CreateAttachmentPayload(message.Attachments); + if (attachments.Paths.Count > 0) { - throw TizenEssentialsSupport.NotSupported( - $"{nameof(IEmail)}.{nameof(ComposeAsync)} with attachments", - "The Tizen 'compose' AppControl operation accepts no attachment payload."); + appControl.Mime = attachments.Mime; + appControl.ExtraData.Add(TizenAppControlData.Path, attachments.Paths); } if (message.Bcc?.Count > 0) @@ -62,6 +59,19 @@ public Task ComposeAsync(EmailMessage? message) return Task.CompletedTask; } + internal static TizenFilePayload CreateAttachmentPayload( + System.Collections.Generic.IEnumerable? attachments) + { + var validAttachments = (attachments ?? Enumerable.Empty()) + .Where(attachment => !string.IsNullOrEmpty(attachment?.FullPath)) + .ToArray(); + + return new( + TizenAppControlOperations.Compose, + TizenShare.ResolveMime(validAttachments.Select(attachment => attachment.ContentType)), + validAttachments.Select(attachment => attachment.FullPath).ToArray()); + } + /// /// Composes an email with the supplied subject, body and recipients. /// diff --git a/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs index f1011ddb..9d2fb6d9 100644 --- a/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs +++ b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs @@ -5,6 +5,7 @@ using Microsoft.Maui.Devices.Sensors; using TizenLocationChangedEventArgs = Tizen.Location.LocationChangedEventArgs; using TizenLocationType = Tizen.Location.LocationType; +using TizenLocatorHelper = Tizen.Location.LocatorHelper; using TizenLocator = Tizen.Location.Locator; namespace Microsoft.Maui.Platforms.Tizen.Essentials @@ -32,9 +33,10 @@ public sealed class TizenGeolocation : IGeolocation public bool IsListeningForeground => false; /// - public bool IsEnabled => - TizenSystemInformation.GetFeatureInfo("location.gps") || - TizenSystemInformation.GetFeatureInfo("location.wps"); + public bool IsEnabled => IsLocationEnabled( + () => TizenSystemInformation.GetFeatureInfo("location.gps"), + () => TizenSystemInformation.GetFeatureInfo("location.wps"), + TizenLocatorHelper.IsEnabledType); /// /// Never raised: continuous listening is unsupported on this backend. @@ -144,6 +146,39 @@ internal static TizenLocationType ResolveLocationType() }; } + internal static bool IsLocationEnabled( + Func hasGps, + Func hasWps, + Func isEnabled) + { + if (hasGps() && IsEnabled(TizenLocationType.Gps)) + return true; + if (hasWps() && IsEnabled(TizenLocationType.Wps)) + return true; + + return false; + + bool IsEnabled(TizenLocationType type) + { + try + { + return isEnabled(type); + } + catch (NotSupportedException) + { + return false; + } + catch (ArgumentException) + { + return false; + } + catch (InvalidOperationException) + { + return false; + } + } + } + internal static double KilometersPerHourToMetersPerSecond(double kilometersPerHour) => kilometersPerHour * 0.277778; } diff --git a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs index 314abf06..0c86e759 100644 --- a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs +++ b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs @@ -115,7 +115,7 @@ internal static string GetOperation(Uri uri) var absoluteUri = uri.AbsoluteUri; if (absoluteUri.StartsWith("geo:", StringComparison.OrdinalIgnoreCase)) - return TizenAppControlOperations.Pick; + return TizenAppControlOperations.View; if (absoluteUri.StartsWith("http", StringComparison.OrdinalIgnoreCase)) return TizenAppControlOperations.View; if (absoluteUri.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Maui.Tizen.Essentials/Map/TizenMap.cs b/src/Maui.Tizen.Essentials/Map/TizenMap.cs index 8990821b..913014a0 100644 --- a/src/Maui.Tizen.Essentials/Map/TizenMap.cs +++ b/src/Maui.Tizen.Essentials/Map/TizenMap.cs @@ -49,18 +49,27 @@ internal static TizenAppControl CreateAppControl(double latitude, double longitu internal static TizenAppControl CreateAppControl(Placemark placemark, MapLaunchOptions options) { - ArgumentNullException.ThrowIfNull(placemark); - ArgumentNullException.ThrowIfNull(options); + var request = CreatePlacemarkRequest(placemark, options); TizenPermissions.EnsureDeclared(); return new TizenAppControl { - Operation = TizenAppControlOperations.Pick, - Uri = $"geo:0,0?q={placemark.GetEscapedAddress()}", + Operation = request.Operation, + Uri = request.Uri, }; } + internal static TizenMapRequest CreatePlacemarkRequest(Placemark placemark, MapLaunchOptions options) + { + ArgumentNullException.ThrowIfNull(placemark); + ArgumentNullException.ThrowIfNull(options); + + return new( + TizenAppControlOperations.View, + $"geo:0,0?q={placemark.GetEscapedAddress()}"); + } + static Task Launch(TizenAppControl appControl) { TizenAppControl.SendLaunchRequest(appControl); @@ -76,5 +85,7 @@ static Task TryLaunch(TizenAppControl appControl) return Task.FromResult(canLaunch); } + + internal sealed record TizenMapRequest(string Operation, string Uri); } } diff --git a/src/Maui.Tizen.Essentials/Share/TizenShare.cs b/src/Maui.Tizen.Essentials/Share/TizenShare.cs index 629c9120..f137480e 100644 --- a/src/Maui.Tizen.Essentials/Share/TizenShare.cs +++ b/src/Maui.Tizen.Essentials/Share/TizenShare.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; @@ -56,23 +57,50 @@ public Task RequestAsync(ShareMultipleFilesRequest request) TizenPermissions.EnsureDeclared(); + var payload = CreateFilePayload(request.Files); var appControl = new TizenAppControl { - Operation = TizenAppControlOperations.Share, + Operation = payload.Operation, + Mime = payload.Mime, }; if (!string.IsNullOrEmpty(request.Title)) appControl.ExtraData.Add(TizenAppControlData.Title, request.Title); - foreach (var file in request.Files ?? Enumerable.Empty()) - { - if (!string.IsNullOrEmpty(file?.FullPath)) - appControl.ExtraData.Add(TizenAppControlData.Path, file.FullPath); - } + if (payload.Paths.Count > 0) + appControl.ExtraData.Add(TizenAppControlData.Path, payload.Paths); TizenAppControl.SendLaunchRequest(appControl); return Task.CompletedTask; } + + internal static TizenFilePayload CreateFilePayload(IEnumerable? files) + { + var validFiles = (files ?? Enumerable.Empty()) + .Where(file => !string.IsNullOrEmpty(file?.FullPath)) + .ToArray(); + var paths = validFiles.Select(file => file.FullPath).ToArray(); + + return new( + paths.Length > 1 ? TizenAppControlOperations.MultiShare : TizenAppControlOperations.Share, + ResolveMime(validFiles.Select(file => file.ContentType)), + paths); + } + + internal static string ResolveMime(IEnumerable contentTypes) + { + var types = contentTypes + .Where(type => !string.IsNullOrWhiteSpace(type)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + return types.Length == 1 ? types[0]! : TizenFileMimeTypes.All; + } } + + internal sealed record TizenFilePayload( + string Operation, + string Mime, + IReadOnlyList Paths); } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index b1afba04..8d3ee4d1 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -7,13 +7,17 @@ using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.ApplicationModel.Communication; +using Microsoft.Maui.ApplicationModel.DataTransfer; using Microsoft.Maui.Devices; +using Microsoft.Maui.Devices.Sensors; using Microsoft.Maui.Networking; using Microsoft.Maui.Platforms.Tizen.Essentials; using Xunit; using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; using TizenColorSpace = Tizen.Multimedia.ColorSpace; using TizenConnectionState = Tizen.Network.Connection.ConnectionState; +using TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenLocationType = Tizen.Location.LocationType; using TizenPixelFormat = Tizen.NUI.PixelFormat; namespace Maui.Tizen.Essentials.Tests; @@ -1203,6 +1207,98 @@ public void SensorStartRollbackResetsEvenWhenCleanupFails() Assert.True(reset); } + [Fact] + public void ShareFilePayloadHandlesZeroFiles() + { + var payload = TizenShare.CreateFilePayload([]); + + Assert.Equal(TizenAppControlOperations.Share, payload.Operation); + Assert.Equal(TizenFileMimeTypes.All, payload.Mime); + Assert.Empty(payload.Paths); + } + + [Fact] + public void ShareFilePayloadHandlesOneFile() + { + var payload = TizenShare.CreateFilePayload( + [new ShareFile("/tmp/photo.png", TizenFileMimeTypes.ImagePng)]); + + Assert.Equal(TizenAppControlOperations.Share, payload.Operation); + Assert.Equal(TizenFileMimeTypes.ImagePng, payload.Mime); + Assert.Equal(["/tmp/photo.png"], payload.Paths); + } + + [Fact] + public void ShareFilePayloadUsesMultiShareAndAllPathsOnce() + { + var payload = TizenShare.CreateFilePayload( + [ + new ShareFile("/tmp/photo.png", TizenFileMimeTypes.ImagePng), + new ShareFile("/tmp/document.pdf", TizenFileMimeTypes.Pdf), + ]); + + Assert.Equal(TizenAppControlOperations.MultiShare, payload.Operation); + Assert.Equal(TizenFileMimeTypes.All, payload.Mime); + Assert.Equal(["/tmp/photo.png", "/tmp/document.pdf"], payload.Paths); + } + + [Fact] + public void EmailAttachmentPayloadUsesEnumerablePathsAndCompatibleMime() + { + var payload = TizenEmail.CreateAttachmentPayload( + [ + new EmailAttachment("/tmp/first.png", TizenFileMimeTypes.ImagePng), + new EmailAttachment("/tmp/second.png", TizenFileMimeTypes.ImagePng), + ]); + + Assert.Equal(TizenAppControlOperations.Compose, payload.Operation); + Assert.Equal(TizenFileMimeTypes.ImagePng, payload.Mime); + Assert.Equal(["/tmp/first.png", "/tmp/second.png"], payload.Paths); + } + + [Fact] + public void MapPlacemarkUsesViewOperation() + { + var request = TizenMap.CreatePlacemarkRequest( + new Placemark { Locality = "Seattle", CountryName = "USA" }, + new MapLaunchOptions()); + + Assert.Equal(TizenAppControlOperations.View, request.Operation); + Assert.StartsWith("geo:0,0?q=", request.Uri, StringComparison.Ordinal); + } + + [Theory] + [InlineData("geo:47.6,-122.3")] + [InlineData("geo:0,0?q=Seattle")] + public void LauncherGeoUrisUseViewOperation(string uri) => + Assert.Equal(TizenAppControlOperations.View, TizenLauncher.GetOperation(new Uri(uri))); + + [Fact] + public void GeolocationIsEnabledRequiresAnEnabledSupportedService() + { + Assert.False(TizenGeolocation.IsLocationEnabled( + () => true, + () => true, + _ => false)); + Assert.True(TizenGeolocation.IsLocationEnabled( + () => true, + () => false, + type => type == TizenLocationType.Gps)); + Assert.True(TizenGeolocation.IsLocationEnabled( + () => false, + () => true, + type => type == TizenLocationType.Wps)); + } + + [Fact] + public void GeolocationIsEnabledIgnoresUnsupportedServiceQueries() + { + Assert.False(TizenGeolocation.IsLocationEnabled( + () => true, + () => false, + _ => throw new NotSupportedException())); + } + sealed class FakeTextToSpeechDispatcher : ITizenTextToSpeechDispatcher, IDisposable { readonly BlockingCollection _work = []; From 09e8b3323fd0cac4a6b0cecdbf63f617dc2ba5b6 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 19:08:29 -0400 Subject: [PATCH 15/21] Fix path-only Tizen file payloads Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: f10f5376-08fd-4221-8332-7c3b3865f0b2 --- docs/tizen-essentials-service-coverage.md | 2 +- eng/build-workload-free.sh | 2 +- src/Maui.Tizen.Essentials/Email/TizenEmail.cs | 2 +- src/Maui.Tizen.Essentials/Share/TizenShare.cs | 76 +++++++++++++++++-- .../TizenServiceBehaviorTests.cs | 31 +++++++- 5 files changed, 103 insertions(+), 10 deletions(-) diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 4261d92a..49a49f3c 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -76,7 +76,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (346 tests) | +| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (347 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 23080452..0a34b8ad 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -249,7 +249,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=346 + ESSENTIALS_TESTS_MINIMUM=347 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs index 59606415..0dc7cb7f 100644 --- a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs +++ b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs @@ -68,7 +68,7 @@ internal static TizenFilePayload CreateAttachmentPayload( return new( TizenAppControlOperations.Compose, - TizenShare.ResolveMime(validAttachments.Select(attachment => attachment.ContentType)), + TizenShare.ResolveMime(validAttachments), validAttachments.Select(attachment => attachment.FullPath).ToArray()); } diff --git a/src/Maui.Tizen.Essentials/Share/TizenShare.cs b/src/Maui.Tizen.Essentials/Share/TizenShare.cs index f137480e..ba6f2f1c 100644 --- a/src/Maui.Tizen.Essentials/Share/TizenShare.cs +++ b/src/Maui.Tizen.Essentials/Share/TizenShare.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.ApplicationModel.DataTransfer; +using Microsoft.Maui.Storage; using TizenAppControl = Tizen.Applications.AppControl; using TizenAppControlData = Tizen.Applications.AppControlData; using TizenAppControlOperations = Tizen.Applications.AppControlOperations; @@ -67,8 +69,10 @@ public Task RequestAsync(ShareMultipleFilesRequest request) if (!string.IsNullOrEmpty(request.Title)) appControl.ExtraData.Add(TizenAppControlData.Title, request.Title); - if (payload.Paths.Count > 0) - appControl.ExtraData.Add(TizenAppControlData.Path, payload.Paths); + AddPaths( + payload, + (key, value) => appControl.ExtraData.Add(key, value), + (key, values) => appControl.ExtraData.Add(key, values)); TizenAppControl.SendLaunchRequest(appControl); @@ -84,19 +88,81 @@ internal static TizenFilePayload CreateFilePayload(IEnumerable? files return new( paths.Length > 1 ? TizenAppControlOperations.MultiShare : TizenAppControlOperations.Share, - ResolveMime(validFiles.Select(file => file.ContentType)), + ResolveMime(validFiles), paths); } - internal static string ResolveMime(IEnumerable contentTypes) + internal static void AddPaths( + TizenFilePayload payload, + Action addSingle, + Action> addMultiple) { - var types = contentTypes + if (payload.Paths.Count == 1) + addSingle(TizenAppControlData.Path, payload.Paths[0]); + else if (payload.Paths.Count > 1) + addMultiple(TizenAppControlData.Path, payload.Paths); + } + + internal static string ResolveMime(IEnumerable files) + { + var types = files + .Select(ResolveMime) .Where(type => !string.IsNullOrWhiteSpace(type)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); return types.Length == 1 ? types[0]! : TizenFileMimeTypes.All; } + + static string? ResolveMime(FileBase file) + { + try + { + var contentType = file.ContentType; + if (!string.IsNullOrWhiteSpace(contentType)) + return contentType; + } + catch (NotImplementedException) + { + } + + var extension = Path.GetExtension(file.FullPath); + if (string.IsNullOrEmpty(extension)) + return null; + + try + { + var contentType = TizenFileSystem.GetContentType(extension); + if (!string.IsNullOrWhiteSpace(contentType)) + return contentType; + } + catch (ArgumentException) + { + } + catch (InvalidOperationException) + { + } + catch (NotSupportedException) + { + } + + return extension.ToLowerInvariant() switch + { + ".png" => TizenFileMimeTypes.ImagePng, + ".jpg" or ".jpeg" => TizenFileMimeTypes.ImageJpg, + ".pdf" => TizenFileMimeTypes.Pdf, + ".gif" => "image/gif", + ".webp" => "image/webp", + ".mp4" => "video/mp4", + ".mp3" => "audio/mpeg", + ".txt" => "text/plain", + ".html" or ".htm" => "text/html", + ".json" => "application/json", + ".xml" => "application/xml", + ".zip" => "application/zip", + _ => null, + }; + } } internal sealed record TizenFilePayload( diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index 8d3ee4d1..1bda70d3 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -1220,12 +1220,20 @@ public void ShareFilePayloadHandlesZeroFiles() [Fact] public void ShareFilePayloadHandlesOneFile() { - var payload = TizenShare.CreateFilePayload( - [new ShareFile("/tmp/photo.png", TizenFileMimeTypes.ImagePng)]); + var payload = TizenShare.CreateFilePayload([new ShareFile("/tmp/photo.png")]); + string? scalarPath = null; + IEnumerable? multiplePaths = null; + + TizenShare.AddPaths( + payload, + (_, path) => scalarPath = path, + (_, paths) => multiplePaths = paths); Assert.Equal(TizenAppControlOperations.Share, payload.Operation); Assert.Equal(TizenFileMimeTypes.ImagePng, payload.Mime); Assert.Equal(["/tmp/photo.png"], payload.Paths); + Assert.Equal("/tmp/photo.png", scalarPath); + Assert.Null(multiplePaths); } [Fact] @@ -1236,10 +1244,19 @@ public void ShareFilePayloadUsesMultiShareAndAllPathsOnce() new ShareFile("/tmp/photo.png", TizenFileMimeTypes.ImagePng), new ShareFile("/tmp/document.pdf", TizenFileMimeTypes.Pdf), ]); + string? scalarPath = null; + IEnumerable? multiplePaths = null; + + TizenShare.AddPaths( + payload, + (_, path) => scalarPath = path, + (_, paths) => multiplePaths = paths); Assert.Equal(TizenAppControlOperations.MultiShare, payload.Operation); Assert.Equal(TizenFileMimeTypes.All, payload.Mime); Assert.Equal(["/tmp/photo.png", "/tmp/document.pdf"], payload.Paths); + Assert.Null(scalarPath); + Assert.Equal(payload.Paths, multiplePaths); } [Fact] @@ -1256,6 +1273,16 @@ public void EmailAttachmentPayloadUsesEnumerablePathsAndCompatibleMime() Assert.Equal(["/tmp/first.png", "/tmp/second.png"], payload.Paths); } + [Fact] + public void EmailPathOnlyAttachmentResolvesMimeFromExtension() + { + var payload = TizenEmail.CreateAttachmentPayload( + [new EmailAttachment("/tmp/document.pdf")]); + + Assert.Equal(TizenFileMimeTypes.Pdf, payload.Mime); + Assert.Equal(["/tmp/document.pdf"], payload.Paths); + } + [Fact] public void MapPlacemarkUsesViewOperation() { From 85f6313a2295d6767bb5f257434e25f181f650e8 Mon Sep 17 00:00:00 2001 From: redth Date: Sat, 29 Aug 2026 15:24:42 -0400 Subject: [PATCH 16/21] Harden Tizen Essentials native contracts Close the reviewed build, API15, storage, dispatcher, callback, sensor, screenshot, AppControl, permission, and lifecycle blockers. Record the pinned MAUI FileResult and passkey response construction gaps as compile-backed release blockers, and expand locked mutation coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7a37339a-ace9-487d-b025-3262b9d414d9 --- docs/migration.md | 59 ++- docs/net11-status.md | 13 +- docs/tizen-essentials-service-coverage.md | 11 +- docs/validation/api15-guards.md | 16 +- docs/validation/blockers.md | 41 ++ eng/Maui.Tizen.Essentials.Sources.props | 2 + eng/build-workload-free.sh | 4 +- eng/targets/TizenPackage.props | 16 +- eng/tests/essentials-mutations.json | 298 ++++++++++++++ eng/tests/run-essentials-negative-controls.sh | 126 +++++- eng/validation/api15-contract.json | 13 +- .../essentials-external-blockers.json | 19 + .../Accelerometer/TizenAccelerometer.cs | 36 +- .../Accelerometer/TizenAccelerometerQueue.cs | 5 +- .../Barometer/TizenBarometer.cs | 17 +- .../Battery/TizenBattery.cs | 22 +- .../Browser/TizenBrowser.cs | 2 +- .../Clipboard/TizenClipboard.cs | 313 +++++++++++++- .../Compass/TizenCompass.cs | 17 +- .../Connectivity/TizenConnectivity.cs | 59 ++- .../Contacts/TizenContacts.cs | 52 +-- .../DeviceDisplay/TizenDeviceDisplay.cs | 15 +- .../FilePicker/TizenFilePicker.cs | 36 +- .../Gyroscope/TizenGyroscope.cs | 17 +- .../Launcher/TizenLauncher.cs | 44 +- .../Magnetometer/TizenMagnetometer.cs | 17 +- src/Maui.Tizen.Essentials/Map/TizenMap.cs | 2 +- .../Maui.Tizen.Essentials.csproj | 6 + .../MediaPicker/TizenMediaPicker.cs | 31 +- .../TizenOrientationSensor.cs | 17 +- .../Passkeys/TizenPasskeys.cs | 47 ++- .../Permissions/TizenPermissions.cs | 39 +- .../Platform/TizenAppControlReply.cs | 72 ++++ .../TizenNativeCallbackCoordinator.cs | 44 ++ .../Platform/TizenPlatform.cs | 18 +- .../Preferences/TizenPreferences.cs | 157 +++++++- .../PublicAPI/slice/PublicAPI.Unshipped.txt | 8 +- .../Screenshot/TizenScreenshot.cs | 381 ++++++++++++++---- .../SecureStorage/TizenSecureStorage.cs | 221 +++++++++- src/Maui.Tizen.Essentials/Share/TizenShare.cs | 2 +- .../TextToSpeech/TizenTextToSpeech.cs | 11 +- .../Types/TizenSensorBase.cs | 355 ++++++++++------ .../Maui.Tizen.Controls.RefPackCompile.csproj | 1 + .../Api15ReferencePackTests.cs | 49 +++ .../Api15SourceGuardTests.cs | 12 +- .../Maui.Tizen.Core.RefPackCompile.csproj | 1 + .../BuildConfigurationTests.cs | 36 +- ...aui.Tizen.Essentials.RefPackCompile.csproj | 5 +- .../FacadeAndMainThreadOwnershipTests.cs | 76 ---- .../ServiceCoverageMatrixTests.cs | 2 +- .../TizenAccelerometerQueueTests.cs | 33 ++ .../TizenAppControlReplyTests.cs | 130 ++++++ .../TizenClipboardCoordinatorTests.cs | 246 +++++++++++ .../TizenFileResultBlockerTests.cs | 76 ++++ .../TizenNativeCallbackCoordinatorTests.cs | 101 +++++ .../TizenPermissionsTests.cs | 33 ++ .../TizenScreenshotCoordinatorTests.cs | 238 +++++++++++ .../TizenSensorCoordinatorTests.cs | 168 ++++++++ .../TizenServiceBehaviorTests.cs | 343 +++++++++++++--- .../TizenUnsupportedCapabilityTests.cs | 29 +- .../Maui.Tizen.Sample.RefPackCompile.csproj | 1 + .../EssentialsSourceClosureTests.cs | 65 +++ .../MauiPublicApiBlockerTests.cs | 76 ++++ .../ReleaseReadinessTests.cs | 31 ++ .../CompiledSourceInventory.cs | 215 ++++++---- .../ReferencePackProbe.cs | 8 +- 66 files changed, 3953 insertions(+), 703 deletions(-) create mode 100644 eng/validation/essentials-external-blockers.json create mode 100644 src/Maui.Tizen.Essentials/Platform/TizenAppControlReply.cs create mode 100644 src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenAppControlReplyTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenFileResultBlockerTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenNativeCallbackCoordinatorTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenScreenshotCoordinatorTests.cs create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenSensorCoordinatorTests.cs create mode 100644 tests/Maui.Tizen.SourceTests/MauiPublicApiBlockerTests.cs diff --git a/docs/migration.md b/docs/migration.md index 8342c4a8..6f9e15a0 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -6,14 +6,16 @@ Extracting the .NET MAUI Tizen backend from `dotnet/maui` into this repository. | Phase | Scope | Status | |---|---|---| -| **0** | Freeze baselines; inventory and disposition manifests; API baselines | Contract landed; generated data in progress | +| **0** | Freeze baselines; inventory and disposition manifests; API baselines | **Complete** | | **1** | History-preserving import; repository scaffolding; docs; CI | **Complete** | -| 2 | Handler implementation (`Maui.Tizen.Core`, `Maui.Tizen.Controls`) | Not started | -| 3 | Essentials implementation | Not started | -| 4 | BlazorWebView, Maps, Build.Tasks, Templates | Not started | +| **2** | Handler implementation (`Maui.Tizen.Core`, `Maui.Tizen.Controls`) | **Core and Waves A/B/C merged** | +| **3** | Essentials implementation | **Implemented and host/API15 tested; two external MAUI API blockers remain** | +| 4 | BlazorWebView, Maps, Build.Tasks, Templates | Maps disposition complete (no API15 implementation); remaining packages in progress | | 5 | Device tests, samples, packaging and publishing | Not started | -Phases 2 onward are **blocked on an external dependency** — see below. +The Samsung workload blocks real Tizen-TFM builds, packaging and device execution. It does not +block implementation: host-executable coordinators, API15 ref-pack builds, source/convention +guards, mutation tests and the merged handler stack all run without it. ## The external gate @@ -45,11 +47,19 @@ The lane in `eng/build-workload-free.sh` (required in CI) genuinely exercises: - central package management and package source mapping - MSBuild conventions and the workload gate itself - consistency between `Directory.Build.props`, `global.json` and `eng/baselines.json` -- 20 repository invariant tests, built and executed on `net11.0` +- the complete Core/Waves host suites and Core/Controls/Sample/Essentials API15 ref-pack lanes +- the implemented Essentials DI, storage, permission, AppControl, dispatcher and lifecycle tests +- package/source/PublicAPI/analyzer closure checks and locked Essentials/Wave B/Wave C mutations +- migration tooling, package graph, consumer compile and repository invariant suites - integrity of the imported history and the import tooling -So when the workload does ship, the workload is the *only* thing that needs to start -working. +At this integration head the principal executable inventories are 1,248 Core/Waves tests, 406 +Essentials tests in both Debug and Release, and 578 source/closure/parity tests. The canonical +script also executes the repository, tooling, negative-control and hosted suites rather than +inferring their result from a successful build. + +Hosted validation also runs validation, build, convention, DevFlow and consumer suites. Device +behaviour, shipping packages and visual baselines remain explicitly gated rather than inferred. ### When the gate lifts @@ -65,8 +75,8 @@ The transition is automatic and fail-closed: 4. `eng/build-tizen.sh` restores, builds, and invokes Pack for every actual `net11.0-tizen11.0` product project. Any install, restore, build, or pack failure fails the workflow. -5. After that lane is green, regenerate API baselines against the real Tizen build and - begin Phase 2. +5. After that lane is green, regenerate API baselines against the real Tizen build and run the + device/profile/visual/package gates. ### SecureStorage data migration @@ -84,8 +94,13 @@ read, are treated as absent rather than as storage failures. Raw aliases are nev the application-wide secure repository cannot prove that alias is owned by SecureStorage. A migration save failure is surfaced and leaves the legacy value intact. -`Remove` deletes both generations of owned namespaced alias, and `RemoveAll` deletes every alias -under the private ownership prefix. Both write tombstones in the application preference store. +`SetAsync` stages the new bytes under a versioned transaction alias before removing either owned +generation. A failed commit restores the prior v1/v2 aliases; if restoration itself fails, the +staged bytes remain recoverable by the next read. Successful replacement removes duplicate v1 and +transaction aliases. `Remove` deletes both owned generations, and `RemoveAll` deletes unqualified +owned aliases plus qualified aliases whose owner exactly matches the current package id; a foreign +package using the same raw prefix is preserved. Both removal paths write tombstones in the +application preference store. Those tombstones suppress legacy fallback, so an unowned raw alias cannot resurrect a removed SecureStorage value. There is no safe way to distinguish an old SecureStorage raw alias from certificates, keys, or another component's data in the shared repository. Tombstones @@ -107,6 +122,12 @@ per-store `Clear` write v2 tombstones instead of deleting ambiguous aliases, so resurrect removed data or cross-delete another logical store. `Clear` removes only the selected store's unambiguous v2 entries and never performs a native global clear. +Tizen's native preference store supports only its documented primitive types. `long` and +`DateTime` therefore use invariant versioned strings, `DateTimeOffset` uses a tagged round-trip +string, and `float` is stored as `double` with a checked exact conversion on read. Compatibility +reads migrate the earlier unsupported direct representations when encountered in development or +legacy stores. + ### Target contract provenance The `tizen11.0` / API15 contract is **verified from Samsung workload PR #310**, not @@ -211,7 +232,7 @@ The 87 files that exist only at `9.0.120` break down as: | **Compatibility layer** | .NET MAUI 11 drops it. Audit each of the 70 files; `move` only what net11 Tizen handlers genuinely require, `exclude` the rest. Expected outcome: the package is deleted entirely. | | **Graphics** | `Microsoft.Maui.Graphics` is upstreamed from its own repository and carries one Tizen view here. Likely `keep-upstream` — contribute the view back rather than shipping a package. | | **Build.Tasks** | The imported Tizen tasks depend on shared Resizetizer types (`ILogger`, `ResizeImageInfo`, `ResizedImageInfo`) whose filenames contain no "tizen" and were therefore correctly excluded by the import filter. Either vendor them here, or ship these tasks inside `Microsoft.Maui.Resizetizer` upstream. **Also unresolved:** these tasks use SkiaSharp for splash/icon generation, so enabling them raises real runtime and native-asset packaging questions (which SkiaSharp native assets ship, and how they reach a Tizen build). That is deliberately *not* papered over in the foundation — it is part of enabling the project, not of scaffolding it. | -| **Documentation warnings** | `CS1591` is suppressed in `TizenPackage.props` while projects compile nothing. The inherited sources are not uniformly documented, so flipping a project to compile would otherwise fail on hundreds of missing-comment errors under warnings-as-errors. Remove the suppression per project as its documentation is completed. | +| **Documentation warnings** | Shipping Core, Controls and Essentials explicitly opt into XML documentation before importing `TizenPackage.props`; projects that still compile nothing retain the no-documentation default. `CS1591` remains suppressed until package-by-package documentation completion. | | **`Tizen.UIExtensions`** | Needs republishing to drop its .NET 6-era `Microsoft.Maui.Graphics` dependencies. No API surface change expected. | ## The import @@ -232,15 +253,17 @@ diffing the import commit alone. Full detail in [`../PROVENANCE.md`](../PROVENAN graph LR F["Phase 0-1
Foundation
done"] --> I["Inventory + API baselines"] F --> G{{"Samsung workload
external gate"}} - I --> H["Phase 2
Handlers"] - G --> H - G --> E["Phase 3
Essentials"] + I --> H["Phase 2
Handlers
merged"] + I --> E["Phase 3
Essentials
implemented"] + G --> D["Real Tizen build/device/package gates"] H --> X["Phase 4
BlazorWebView, Maps,
Build.Tasks, Templates"] E --> X - X --> P["Phase 5
Device tests, samples,
packaging"] + X --> D + D --> P["Phase 5
publish and transfer"] ``` -Inventory work can proceed now. Everything downstream of the gate cannot. +Implementation and hosted verification proceed now. Only Tizen workload, device and publishing +evidence remain downstream of the Samsung gate. ## See also diff --git a/docs/net11-status.md b/docs/net11-status.md index 9c4082bc..6a8ee189 100644 --- a/docs/net11-status.md +++ b/docs/net11-status.md @@ -1,7 +1,6 @@ # .NET 11 status: blockers and required MAUI API gaps -Status of the **core standalone backend vertical slice** (application, window, page, content view, -layout, label) in `src/Maui.Tizen.Core`. +Status of the merged standalone Core/Waves backend plus the implemented Essentials package. Baselines are frozen in [`eng/baselines.json`](../eng/baselines.json); package versions are centrally configurable in [`eng/Maui.props`](../eng/Maui.props). @@ -20,6 +19,10 @@ not compile identical sets - that would be impossible, since the platform source | `Maui.Tizen.Core.UnitTests` | portable + handler | test host | no | | `Maui.Tizen.Core.RefPackCompile` | portable + handler + platform | `Maui.Tizen.Core` | yes | | `Maui.Tizen.Sample.RefPackCompile` | sample only, references the above | `Maui.Tizen.Sample` | yes | +| `Maui.Tizen.Controls.RefPackCompile` | Controls, Waves A/B/C and navigation | `Maui.Tizen.Controls` | yes | +| `Maui.Tizen.Controls.ConsumerCompile` | consumer/catalog crossing the package boundary | consumer | yes | +| `Maui.Tizen.Essentials.RefPackCompile` | exact Essentials shipping closure against API15 | `Maui.Tizen.Essentials` | yes | +| `Maui.Tizen.Essentials.Tests` | host-executable storage/callback/lifecycle/DI behavior | test host | yes | | `Maui.Tizen.Core` (product) | portable + handler + platform | `Maui.Tizen.Core` | yes | Between them every owned source is compiled by at least one lane, and everything the product @@ -44,8 +47,10 @@ identical, so neither can drift from the other. | Lane | Command | What it proves | | --- | --- | --- | -| Unit tests | `dotnet test tests/Maui.Tizen.Core.UnitTests` | Mapper + command-mapper registration, DI/handler registration, hosting, dispatcher/timer/provider semantics, density conversion, layout z-index ordering, `IMauiContext` scoping. **417 tests at this head, all passing.** | -| Compile validation | `dotnet build tests/Maui.Tizen.Core.RefPackCompile` | Every Core `#if TIZEN` source - including `TizenMauiApplication`, the NUI view groups and all the ported platform extensions - type-checks against the **real** TizenFX reference assemblies from `Samsung.Tizen.Ref.API15` (`ref/net8.0`). The sample is compiled separately by `Maui.Tizen.Sample.RefPackCompile`. **Both build cleanly.** | +| Core/Waves tests | `dotnet test tests/Maui.Tizen.Core.UnitTests` | Mapper + command-mapper registration, concrete Controls startup, DI/handler registration, hosting, dispatcher/timer/provider semantics, density/layout, Wave A/B/C lifetimes and navigation. **1,248 tests at this head, all passing.** | +| Source/closure tests | `dotnet test tests/Maui.Tizen.SourceTests` | Source ownership, mapper parity, startup and package closures, compile-backed MAUI API blockers. **578 tests at this head, all passing.** | +| Essentials tests | execute `artifacts/bin/Maui.Tizen.Essentials.Tests//net11.0/Maui.Tizen.Essentials.Tests` | DI facade bridge, native-faithful Preferences/SecureStorage, Clipboard/TTS/sensor/screenshot/AppControl lifecycle coordinators, permissions and translation behavior. **406 tests pass in Debug and Release.** | +| Compile validation | build the four `*.RefPackCompile`/consumer projects | Core, Controls, Sample and Essentials shipping sources type-check against the **real** TizenFX reference assemblies from `Samsung.Tizen.Ref.API15` (`ref/net8.0`), with package-specific PublicAPI analyzers. **All build cleanly.** | | Product | `dotnet build src/Maui.Tizen.Core` | Fails with actionable `MAUITIZEN0001` from `Directory.Build.targets`. This is the intended behaviour. | Both lanes are wired into `eng/build-workload-free.sh`, so they run in the workload-free CI lane diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 384e3f03..a58c6faf 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -19,6 +19,7 @@ Support levels: | `Implemented` | The whole contract is backed by native Tizen APIs. | | `Partial` | Part of the contract is backed by native Tizen APIs. The remaining members throw `FeatureNotSupportedException` with an explicit reason. | | `Unsupported` | Tizen has no API that can satisfy the contract. Every member throws `FeatureNotSupportedException`. Nothing is faked. | +| `Blocked` | Tizen has the platform capability, but the pinned public MAUI contract lacks an external-backend construction/override seam. A compile-backed blocker is recorded. | Nothing in this backend returns a success-shaped fallback (an empty collection, `null`, or a completed `Task`) to stand in for a capability the platform does not have. @@ -37,14 +38,14 @@ Profile column values are the Tizen device profiles on which the service is usab | `IBarometer` | `TizenBarometer` | Implemented | All | `Tizen.Sensor.PressureSensor`. | | `IBattery` | `TizenBattery` | Partial | All | Power source read from Tizen's own reading (`None`/`Ac`/`Usb`/`Wireless`); state distinguishes `Full` and `NotCharging`. `EnergySaverStatus` / `EnergySaverStatusChanged` throw: Tizen exposes no application-visible power saving state. | | `IBrowser` | `TizenBrowser` | Partial | All | Always opens the system browser: Tizen has no in-app browser, so `BrowserLaunchMode` cannot be honoured. | -| `IClipboard` | `TizenClipboard` | Unsupported | – | Tizen scopes copy/paste to the focused NUI/EFL window selection buffer; there is no headless clipboard service. | +| `IClipboard` | `TizenClipboard` | Partial | All | `GetTextAsync`, `SetTextAsync`, and change notifications use public `Tizen.NUI.Clipboard` on the MAUI dispatcher. Synchronous `HasText` throws because API15 exposes reads only through an asynchronous callback; blocking the NUI loop would deadlock. | | `ICompass` | `TizenCompass` | Implemented | All | Azimuth from `Tizen.Sensor.OrientationSensor`. `applyLowPassFilter` has no extra effect (Tizen already fuses and filters). | | `IConnectivity` | `TizenConnectivity` | Implemented | All | `Tizen.Network.Connection`. `ConnectionProfiles` is queried synchronously per read, so it works without subscribing to `ConnectivityChanged`. Requires `network.get` + `internet`. | | `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. `GetAllAsync` requests runtime `contact.read` consent and materialises the result before disposing the native cursor. | | `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | | `IDeviceInfo` | `TizenDeviceInfo` | Implemented | All | System / feature information keys. | | `IEmail` | `TizenEmail` | Implemented | Mobile | Tizen `compose` AppControl, including enumerable attachment paths and a compatible MIME filter. Gated on the `email` feature key. | -| `IFilePicker` | `TizenFilePicker` | Partial | All | Tizen's `pick` operation accepts one MIME filter, so only the first entry of `PickOptions.FileTypes` is applied. | +| `IFilePicker` | `TizenFilePicker` | Blocked | All | Tizen's `pick` operation and MIME filtering work, but pinned MAUI `FileResult` has no public path-open override. Standard `OpenReadAsync` and direct `ShareFile(FileBase)` / `EmailAttachment(FileBase)` / `OpenFileRequest(FileBase)` flows fail in the neutral package. Explicit path+MIME reconstruction works but is not a compatible replacement. See validation blocker 9. | | `IFileSystem` | `TizenFileSystem` | Implemented | All | Application `DirectoryInfo` data / cache / resource paths. | | `IFlashlight` | `TizenFlashlight` | Implemented | Mobile | `Tizen.System.Led`. Gated on `camera.back.flash`; requires the `led` privilege. | | `IGeocoding` | `TizenGeocoding` | Unsupported | – | `Tizen.Maps` (`MapService`) was deprecated in TizenFX API11 and **removed by API15**; there is no replacement. `MapServiceToken` is still accepted so a configured token cannot crash startup, but it is never used. | @@ -54,9 +55,9 @@ Profile column values are the Tizen device profiles on which the service is usab | `ILauncher` | `TizenLauncher` | Implemented | All | AppControl launch requests with scheme-based operation selection. `CanOpenAsync`/`TryOpenAsync` query matched application ids, so `TryOpenAsync` returns `false` instead of throwing when nothing handles the URI. | | `IMagnetometer` | `TizenMagnetometer` | Implemented | All | `Tizen.Sensor.Magnetometer`. | | `IMap` | `TizenMap` | Partial | All | `geo:` AppControl. `MapLaunchOptions.NavigationMode` and the launch name cannot be honoured. | -| `IMediaPicker` | `TizenMediaPicker` | Implemented | Mobile | Picking delegates to `TizenFilePicker`; capture uses the `image_capture` / `video_capture` AppControls. | +| `IMediaPicker` | `TizenMediaPicker` | Blocked | Mobile | Pick/capture AppControls work, but their `FileResult` values have the same pinned-MAUI `OpenReadAsync` blocker as `IFilePicker`. | | `IOrientationSensor` | `TizenOrientationSensor` | Implemented | All | `Tizen.Sensor.RotationVectorSensor`. | -| `IPasskeys` | `TizenPasskeys` | Unsupported | – | Tizen ships FIDO UAF, not a WebAuthn / CTAP2 credential manager. `IsSupported` is `false`. | +| `IPasskeys` | `TizenPasskeys` | Blocked | All | API15 devices with `security.webauthn` publicly expose `Tizen.Security.WebAuthn.Authenticator`, including `SupportedAuthenticators`, MakeCredential/GetAssertion, and Cancel. Native ceremonies require the public `bluetooth` and `internet` privileges plus BLE and an available network transport. Pinned MAUI seals both response types and exposes no public constructor/factory, so the backend cannot return the native WebAuthn response without forbidden reflection. `IsSupported` remains `false` until that MAUI API exists. See validation blocker 10. | | `IPermissions` | `TizenPermissions` | Partial | All | Maps every built-in `Permissions.*` type to verified Tizen privileges, with privacy privileges resolved through `PrivacyPrivilegeManager`. `Permissions.Maps` and `Permissions.Reminders` have no Tizen equivalent and throw rather than reporting `Granted`. | | `IPhoneDialer` | `TizenPhoneDialer` | Implemented | Mobile | `tel:` AppControl, gated on the `contact` feature key. | | `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with an **escaped** `{sharedName}~{key}` prefix so distinct stores cannot collide. Default-store keys stay unprefixed for compatibility. | @@ -78,7 +79,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, permission privilege mapping, unsupported classification, ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (352 tests) | +| DI registration, facade/`MainThread` ownership, native-faithful storage, callback/lifecycle coordinators, permission privilege mapping, unsupported classification, and ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (406 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/docs/validation/api15-guards.md b/docs/validation/api15-guards.md index 066a345b..530bc104 100644 --- a/docs/validation/api15-guards.md +++ b/docs/validation/api15-guards.md @@ -30,11 +30,10 @@ repository carrying a workaround for a problem that no longer exists. The guard scans a file exactly when a project compiles it. -This matters because `src/Maui.Tizen.*` was imported verbatim from dotnet/maui and currently sets -`EnableDefaultCompileItems=false`, so those sources are `` and nothing compiles them. Scanning -them would produce hundreds of failures describing upstream history rather than anything this -repository has adopted, and the only way to get green would be to switch the guard off — which is -how guards die. +This matters because the raw import still shares directories with adopted code. Core, Controls and +Essentials keep default globbing disabled and instead compile explicit shared source manifests; the +guard resolves those manifests and scans their exact closures. Projects that still compile nothing +remain out of scope, so historical sources are not mistaken for shipping code. A project enters scope automatically the moment it opts into compiling, so the handler, Essentials and Blazor waves get covered as they land, with no change here. @@ -46,8 +45,9 @@ handles explicit ``, the default `**/*.cs` glob, and `EnableDefaultCompileItems` inherited from an imported props file, which is the mechanism `eng/targets/TizenPackage.props` actually uses. -Today that means 10 compiled files across the two diagnostics projects. It found a real violation -there: the DevFlow agent used `Window.Instance` in three places. +Today that includes the finalized Core/Waves, Controls navigation, implemented Essentials, and the +two diagnostics projects. The guard previously found a real violation in the DevFlow agent: +`Window.Instance` in three places. ## Why not just rely on the compiler? @@ -77,7 +77,7 @@ The ban is on `MapService`. `MapServiceToken` is explicitly **allowed**: | Member | Status | Why | |---|---|---| -| `IGeocoding` | unsupported | Built on `Tizen.Maps`, which no longer exists. No replacement API. Must not be registered in DI, and throws `PlatformNotSupportedException`. | +| `IGeocoding` / `IPlatformGeocoding` | registered unsupported service | Built on `Tizen.Maps`, which no longer exists. One `TizenGeocoding` singleton is registered for both contracts; operations throw `FeatureNotSupportedException`. | | `MapServiceToken` | accepted, no-op | App startup and the Essentials DI bridge set it during initialisation. Removing it turns a now-meaningless configuration call into a compile break for every consumer; throwing turns it into a startup crash. | The distinction is enforced by matching whole identifiers (`(?!\w)` after the symbol), so diff --git a/docs/validation/blockers.md b/docs/validation/blockers.md index 3a39c375..1624ba05 100644 --- a/docs/validation/blockers.md +++ b/docs/validation/blockers.md @@ -185,3 +185,44 @@ application under test, and a **release is blocked** rather than passing with th Running `run-hosted-validation.sh` on the self-hosted runner is explicitly *not* a substitute: the controller has no Tizen backend loaded, so those suites would skip there exactly as they do on any hosted runner. + +## 9. Pinned MAUI `FileResult` cannot open an external-backend path + +**Blocks:** merging the picker/media surface as fully supported. + +The pinned neutral `Microsoft.Maui.Essentials` package exposes public +`FileResult(string fullPath)` constructors, but `FileBase.OpenReadAsync()` delegates to the +assembly-internal virtual `PlatformOpenReadAsync()`. An external backend cannot override that +member, cannot construct its own `FileBase`, and cannot replace the instance method with an +extension method. The public `ShareFile(FileBase)`, `EmailAttachment(FileBase)`, and +`OpenFileRequest(string, FileBase)` constructors also clone through MAUI's internal +`PlatformInit`, so passing a picked `FileResult` directly fails on the neutral package. + +`MauiPublicApiBlockerTests.FileResultHasNoPublicPathOpenOverrideSeam` compiles an attempted +`FileResult` subclass against the pinned package and requires compiler error `CS0115`. +`TizenFileResultBlockerTests.NeutralFileResultCannotOpenAnExistingTizenPath` creates a real file +under the test output, constructs the public path-based `FileResult`, and proves the inherited +`OpenReadAsync` still fails. Explicit path-based reconstruction +(`ShareFile(path, mime)`, `EmailAttachment(path, mime)`, `ReadOnlyFile(path, mime)`) works and is +covered, but requiring callers to rebuild the object is not the standard FileBase flow. + +**Clears when:** MAUI makes `PlatformOpenReadAsync` protected, adds a public stream-factory +constructor, or publishes an equivalent supported external-platform seam. + +## 10. Pinned MAUI passkey responses cannot be constructed externally + +**Blocks:** implementing `IPasskeys`, despite API15 having native WebAuthn. + +`Samsung.Tizen.Ref.API15 15.0.0.19396` contains +`Tizen.Security.WebAuthn.Authenticator` with `SupportedAuthenticators`, `MakeCredential`, +`GetAssertion`, and `Cancel`. The native premise is therefore supported. The blocker is MAUI: +`PasskeyCreationResponse` and `PasskeyAssertionResponse` are sealed, and their JSON constructors +are internal with no public factory. + +`MauiPublicApiBlockerTests.PasskeyResponsesHaveNoPublicConstructionOrFactorySurface` reflects only +the public surface and compiles attempted construction against the pinned package, requiring +`CS1729`/`CS0122`. Production code does not use reflection or private access. + +**Clears when:** MAUI publishes supported factories that accept the WebAuthn registration and +assertion response JSON. Until then `TizenPasskeys.IsSupported` remains false rather than promising +an operation whose required result cannot be returned. diff --git a/eng/Maui.Tizen.Essentials.Sources.props b/eng/Maui.Tizen.Essentials.Sources.props index 69e9e577..2108a3e9 100644 --- a/eng/Maui.Tizen.Essentials.Sources.props +++ b/eng/Maui.Tizen.Essentials.Sources.props @@ -43,6 +43,8 @@ + + diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 4c9115af..3879774d 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -69,7 +69,7 @@ info "SDK" # malformed file there breaks both in confusing ways. # --------------------------------------------------------------------------- info "JSON validation" -for f in eng/baselines.json eng/manifests/*.json; do +for f in eng/baselines.json eng/manifests/*.json eng/validation/*.json; do [[ -e "$f" ]] || continue check "$f is well-formed JSON" python3 -c "import json,sys; json.load(open(sys.argv[1]))" "$f" done @@ -265,7 +265,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=352 + ESSENTIALS_TESTS_MINIMUM=406 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/eng/targets/TizenPackage.props b/eng/targets/TizenPackage.props index fe625ed5..e30def6b 100644 --- a/eng/targets/TizenPackage.props +++ b/eng/targets/TizenPackage.props @@ -7,7 +7,7 @@ @@ -80,7 +80,7 @@ $(MSBuildProjectName) $(MSBuildProjectName) - + false + true + $(DefineConstants);TIZEN_API15 + + diff --git a/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs index ae498dfe..d9bce58f 100644 --- a/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs +++ b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs @@ -77,8 +77,6 @@ static PickOptions CreatePickOptions(MediaPickerOptions? options, FilePickerFile TizenPermissions.EnsureDeclared(); await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var appControl = new TizenAppControl { Operation = photo ? TizenAppControlOperations.ImageCapture : TizenAppControlOperations.VideoCapture, @@ -89,21 +87,24 @@ static PickOptions CreatePickOptions(MediaPickerOptions? options, FilePickerFile if (!string.IsNullOrEmpty(appId)) appControl.ApplicationId = appId; - TizenAppControl.SendLaunchRequest(appControl, (request, reply, result) => - { - if (result == TizenAppControlReplyResult.Succeeded && - reply.ExtraData.TryGet(TizenAppControlData.Selected, out IEnumerable selected)) + return await TizenAppControlReply.RunAsync( + callback => TizenAppControl.SendLaunchRequest( + appControl, + TizenAppControlReply.NativeTimeoutMilliseconds, + (_, reply, result) => callback(reply, result)), + static (reply, result) => { - var file = selected?.FirstOrDefault(); - tcs.TrySetResult(string.IsNullOrEmpty(file) ? null : new FileResult(file)); - } - else - { - tcs.TrySetCanceled(); - } - }); + if (result != TizenAppControlReplyResult.Succeeded || + !reply.ExtraData.TryGet( + TizenAppControlData.Selected, + out IEnumerable selected)) + { + return null; + } - return await tcs.Task.ConfigureAwait(false); + var file = selected?.FirstOrDefault(); + return string.IsNullOrWhiteSpace(file) ? null : new FileResult(file); + }).ConfigureAwait(false); } } } diff --git a/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs index a74fc4b4..ea535a77 100644 --- a/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs +++ b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs @@ -23,12 +23,15 @@ public sealed class TizenOrientationSensor : TizenSensorBase - protected override void Subscribe(TizenRotationVectorSensor sensor) => sensor.DataUpdated += OnDataUpdated; - - /// - protected override void Unsubscribe(TizenRotationVectorSensor sensor) => sensor.DataUpdated -= OnDataUpdated; - - void OnDataUpdated(object? sender, global::Tizen.Sensor.RotationVectorSensorDataUpdatedEventArgs e) => - Raise(ReadingChanged, new OrientationSensorChangedEventArgs(new OrientationSensorData(e.X, e.Y, e.Z, e.W))); + protected override Action Subscribe(TizenRotationVectorSensor sensor, long generation) + { + EventHandler handler = + (sender, e) => Raise( + generation, + ReadingChanged, + new OrientationSensorChangedEventArgs(new OrientationSensorData(e.X, e.Y, e.Z, e.W))); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } } } diff --git a/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs index b3d9bfcc..42bfe805 100644 --- a/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs +++ b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs @@ -10,19 +10,52 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// Tizen implementation of . ///
/// - /// Tizen exposes FIDO UAF through Tizen.Account.FidoClient, which is a different protocol - /// from the WebAuthn / CTAP2 contract that models. There is no Tizen - /// credential manager that can produce a WebAuthn attestation or assertion, so - /// reports and both operations throw. + /// API15 exposes a public WebAuthn authenticator, but the pinned MAUI package exposes no public + /// constructor or factory for or + /// . The backend can translate the input JSON and receive + /// native WebAuthn bytes, but cannot return the sealed MAUI response types without reflection or + /// an internal API. Until MAUI publishes that response factory, the complete contract is + /// unavailable and must remain . /// public sealed class TizenPasskeys : IPasskeys { const string Reason = - "Tizen ships FIDO UAF (Tizen.Account.FidoClient) but no WebAuthn/CTAP2 credential " + - "manager that can satisfy the passkey creation and assertion contract."; + "Tizen API15 provides Tizen.Security.WebAuthn.Authenticator, but the pinned MAUI " + + "PasskeyCreationResponse and PasskeyAssertionResponse types are sealed and expose no " + + "public constructor or factory. Returning the native response would require forbidden " + + "reflection or an unavailable MAUI API."; /// - public bool IsSupported => false; + public bool IsSupported + { + get + { + // Probe the actual API15 feature/authenticator state so a future MAUI response + // factory can activate without replacing the native capability logic. + _ = IsNativeAuthenticatorAvailable(); + return false; + } + } + + internal static bool IsNativeAuthenticatorAvailable( + Func getFeature, + Func getAuthenticators) + { + try + { + return getFeature() && + getAuthenticators() != global::Tizen.Security.WebAuthn.AuthenticatorTransport.None; + } + catch (Exception) + { + return false; + } + } + + internal static bool IsNativeAuthenticatorAvailable() => + IsNativeAuthenticatorAvailable( + static () => TizenSystemInformation.GetFeatureInfo("security.webauthn"), + static () => global::Tizen.Security.WebAuthn.Authenticator.SupportedAuthenticators()); /// /// Always thrown. diff --git a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs index 99c920d2..520cc338 100644 --- a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs +++ b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs @@ -433,8 +433,21 @@ static async Task RequestPrivilegeAsync(string privilege) var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - void OnResponseFetched(object? sender, global::Tizen.Security.RequestResponseEventArgs e) => - tcs.TrySetResult(e.result == global::Tizen.Security.RequestResult.AllowForever); + void OnResponseFetched(object? sender, global::Tizen.Security.RequestResponseEventArgs e) + { + try + { + tcs.TrySetResult(InterpretRequestResponse( + privilege, + e.cause, + e.result, + e.privilege)); + } + catch (Exception exception) + { + tcs.TrySetException(exception); + } + } context.ResponseFetched += OnResponseFetched; @@ -448,5 +461,27 @@ void OnResponseFetched(object? sender, global::Tizen.Security.RequestResponseEve context.ResponseFetched -= OnResponseFetched; } } + + internal static bool InterpretRequestResponse( + string requestedPrivilege, + global::Tizen.Security.CallCause cause, + global::Tizen.Security.RequestResult result, + string responsePrivilege) + { + if (cause != global::Tizen.Security.CallCause.Answer) + { + throw new InvalidOperationException( + $"Tizen reported an error while requesting '{requestedPrivilege}'."); + } + + if (!string.Equals(requestedPrivilege, responsePrivilege, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"Tizen returned a permission answer for '{responsePrivilege}' while " + + $"'{requestedPrivilege}' was pending."); + } + + return result == global::Tizen.Security.RequestResult.AllowForever; + } } } diff --git a/src/Maui.Tizen.Essentials/Platform/TizenAppControlReply.cs b/src/Maui.Tizen.Essentials/Platform/TizenAppControlReply.cs new file mode 100644 index 00000000..979b30f5 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenAppControlReply.cs @@ -0,0 +1,72 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + internal static class TizenAppControlReply + { + public static TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30); + + public static async Task RunAsync( + Action> start, + Func parse, + CancellationToken cancellationToken = default, + Action>? unsubscribe = null, + TimeSpan? timeoutOverride = null) + { + ArgumentNullException.ThrowIfNull(start); + ArgumentNullException.ThrowIfNull(parse); + cancellationToken.ThrowIfCancellationRequested(); + + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + var settled = 0; + + void Complete(TReply reply, TResult result) + { + if (Interlocked.Exchange(ref settled, 1) != 0) + return; + + try + { + completion.TrySetResult(parse(reply, result)); + } + catch (Exception exception) + { + completion.TrySetException(exception); + } + } + + var effectiveTimeout = timeoutOverride ?? Timeout; + using var timeout = new CancellationTokenSource(effectiveTimeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + timeout.Token); + using var registration = linked.Token.Register(() => + { + if (Interlocked.Exchange(ref settled, 1) != 0) + return; + + if (cancellationToken.IsCancellationRequested) + completion.TrySetCanceled(cancellationToken); + else + completion.TrySetException( + new TimeoutException($"Tizen AppControl did not reply within {effectiveTimeout}.")); + }); + + try + { + start(Complete); + return await completion.Task.ConfigureAwait(false); + } + finally + { + unsubscribe?.Invoke(Complete); + } + } + + public static uint NativeTimeoutMilliseconds => + checked((uint)Math.Clamp(Math.Ceiling(Timeout.TotalMilliseconds), 1, uint.MaxValue)); + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs b/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs new file mode 100644 index 00000000..eff9dbcf --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs @@ -0,0 +1,44 @@ +using System; +using Microsoft.Maui.ApplicationModel; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + internal sealed class TizenNativeCallbackCoordinator + { + readonly ITizenNativeCallbackDispatcher _dispatcher; + + public TizenNativeCallbackCoordinator() + : this(TizenNativeCallbackDispatcher.Instance) + { + } + + internal TizenNativeCallbackCoordinator(ITizenNativeCallbackDispatcher dispatcher) + { + _dispatcher = dispatcher; + } + + public void Post(Func isCurrent, Action callback) + { + ArgumentNullException.ThrowIfNull(isCurrent); + ArgumentNullException.ThrowIfNull(callback); + + _dispatcher.Post(() => + { + if (isCurrent()) + callback(); + }); + } + } + + internal interface ITizenNativeCallbackDispatcher + { + void Post(Action action); + } + + sealed class TizenNativeCallbackDispatcher : ITizenNativeCallbackDispatcher + { + public static TizenNativeCallbackDispatcher Instance { get; } = new(); + + public void Post(Action action) => MainThread.BeginInvokeOnMainThread(action); + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs index a1eaa6ae..3c73ea8c 100644 --- a/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs +++ b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs @@ -18,6 +18,21 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public static class TizenPlatform { + internal static string? CurrentPackageId + { + get + { + try + { + return TizenApplication.Current.ApplicationInfo.PackageId; + } + catch + { + return null; + } + } + } + /// /// Gets a with information about the current application package. /// @@ -25,7 +40,8 @@ public static TizenPackage CurrentPackage { get { - var packageId = TizenApplication.Current.ApplicationInfo.PackageId; + var packageId = CurrentPackageId ?? + throw new InvalidOperationException("The current Tizen package id is unavailable."); return TizenPackageManager.GetPackage(packageId); } } diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs index 5ae47c3e..6da2ec00 100644 --- a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -17,6 +17,10 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// public sealed class TizenPreferences : IPreferences { + const string LongPrefix = "maui-pref:long:v1:"; + const string DateTimePrefix = "maui-pref:datetime:v1:"; + const string DateTimeOffsetPrefix = "maui-pref:datetimeoffset:v1:"; + readonly ITizenPreferencesStore _store; /// @@ -134,37 +138,172 @@ void SetCore(string fullKey, T value) _store.Remove(fullKey); break; case DateTime dateTime: - _store.Set(fullKey, dateTime.ToBinary()); + _store.Set( + fullKey, + DateTimePrefix + dateTime.ToBinary().ToString(CultureInfo.InvariantCulture)); break; case DateTimeOffset dateTimeOffset: - _store.Set(fullKey, dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); + _store.Set( + fullKey, + DateTimeOffsetPrefix + dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); break; - default: + case long longValue: + _store.Set(fullKey, LongPrefix + longValue.ToString(CultureInfo.InvariantCulture)); + break; + case float floatValue: + _store.Set(fullKey, (double)floatValue); + break; + case bool or int or double or string: _store.Set(fullKey, value); break; + default: + throw new ArgumentException( + $"Preferences does not support values of type '{typeof(T).FullName}'.", + nameof(value)); } } T GetCore(string fullKey, T defaultValue) { if (typeof(T) == typeof(DateTime)) - return (T)(object)DateTime.FromBinary(_store.Get(fullKey)); + { + if (TryGetString(fullKey, out var saved) && + saved.StartsWith(DateTimePrefix, StringComparison.Ordinal) && + long.TryParse( + saved.AsSpan(DateTimePrefix.Length), + NumberStyles.Integer, + CultureInfo.InvariantCulture, + out var binary)) + { + return (T)(object)DateTime.FromBinary(binary); + } + + // First standalone builds attempted to use a native-unsupported Int64 directly. + // Keep the read path so test/development stores can migrate that representation. + try + { + var legacy = DateTime.FromBinary(_store.Get(fullKey)); + SetCore(fullKey, legacy); + return (T)(object)legacy; + } + catch (Exception exception) when (exception is InvalidCastException or ArgumentException) + { + return defaultValue; + } + } if (typeof(T) == typeof(DateTimeOffset)) { - var saved = _store.Get(fullKey); - return DateTimeOffset.TryParse( + if (!TryGetString(fullKey, out var saved)) + return defaultValue; + + var versioned = saved.StartsWith(DateTimeOffsetPrefix, StringComparison.Ordinal); + if (versioned) + saved = saved[DateTimeOffsetPrefix.Length..]; + + if (!DateTimeOffset.TryParse( saved, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, - out var parsed) - ? (T)(object)parsed - : defaultValue; + out var parsed)) + { + return defaultValue; + } + + if (!versioned) + SetCore(fullKey, parsed); + return (T)(object)parsed; + } + + if (typeof(T) == typeof(long)) + { + if (TryGetString(fullKey, out var saved) && + saved.StartsWith(LongPrefix, StringComparison.Ordinal) && + long.TryParse( + saved.AsSpan(LongPrefix.Length), + NumberStyles.Integer, + CultureInfo.InvariantCulture, + out var value)) + { + return (T)(object)value; + } + + try + { + var legacy = _store.Get(fullKey); + SetCore(fullKey, legacy); + return (T)(object)legacy; + } + catch (Exception exception) when (exception is InvalidCastException or ArgumentException) + { + return defaultValue; + } + } + + if (typeof(T) == typeof(float)) + { + double saved; + try + { + saved = _store.Get(fullKey); + } + catch (Exception exception) when (exception is InvalidCastException or ArgumentException) + { + // Compatibility with the pre-fix in-memory/development representation. + try + { + var legacy = _store.Get(fullKey); + SetCore(fullKey, legacy); + return (T)(object)legacy; + } + catch (Exception fallback) when (fallback is InvalidCastException or ArgumentException) + { + return defaultValue; + } + } + + return (T)(object)ToSingleExact(saved); } return _store.Get(fullKey); } + bool TryGetString(string key, out string value) + { + try + { + value = _store.Get(key); + return true; + } + catch (Exception exception) when (exception is InvalidCastException or ArgumentException) + { + value = string.Empty; + return false; + } + } + + internal static float ToSingleExact(double value) + { + if (double.IsNaN(value)) + return float.NaN; + if (double.IsPositiveInfinity(value)) + return float.PositiveInfinity; + if (double.IsNegativeInfinity(value)) + return float.NegativeInfinity; + if (value > float.MaxValue || value < float.MinValue) + throw new OverflowException($"Stored preference value '{value}' is outside the Single range."); + + var converted = (float)value; + if ((double)converted != value) + { + throw new InvalidOperationException( + $"Stored preference value '{value.ToString("R", CultureInfo.InvariantCulture)}' " + + "cannot be represented exactly as Single."); + } + + return converted; + } + bool LegacyFallbackSuppressed(string key, string? sharedName) => _store.Contains(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)) || _store.Contains(TizenStorageKeyEncoding.GetStoreTombstone(sharedName)); diff --git a/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt index dc1844f9..8f64f7a6 100644 --- a/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt +++ b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt @@ -2,8 +2,7 @@ abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.IsSupported.get -> bool abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Sensor.get -> TSensor! abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.SensorName.get -> string! -abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Subscribe(TSensor! sensor) -> void -abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Unsubscribe(TSensor! sensor) -> void +abstract Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Subscribe(TSensor! sensor, long generation) -> System.Action! const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.All = "*/*" -> string! const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.ImageAll = "image/*" -> string! const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.ImageJpg = "image/jpeg" -> string! @@ -53,6 +52,7 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenBrowser.OpenAsync(System.Uri! uri Microsoft.Maui.Platforms.Tizen.Essentials.TizenBrowser.TizenBrowser() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.ClipboardContentChanged -> System.EventHandler! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.Dispose() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.GetTextAsync() -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.HasText.get -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.SetTextAsync(string? text) -> System.Threading.Tasks.Task! @@ -210,6 +210,7 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureAsync() -> Syst Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureAsync(Tizen.NUI.BaseComponents.View! view) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureAsync(Tizen.NUI.Window! window) -> System.Threading.Tasks.Task! Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureViewAsync(object! platformView) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.Dispose() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.IsCaptureSupported.get -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.TizenScreenshot() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotExtensions @@ -228,8 +229,9 @@ Microsoft.Maui.Platforms.Tizen.Essentials.TizenSemanticScreenReader Microsoft.Maui.Platforms.Tizen.Essentials.TizenSemanticScreenReader.Announce(string! text) -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenSemanticScreenReader.TizenSemanticScreenReader() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.IsCurrentGeneration(long generation) -> bool Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.IsMonitoring.get -> bool -Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Raise(System.EventHandler? handler, TArgs! args) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Raise(long generation, System.EventHandler? handler, TArgs! args) -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Start(Microsoft.Maui.Devices.Sensors.SensorSpeed sensorSpeed) -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.Stop() -> void Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.TizenSensorBase() -> void diff --git a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs index 9ac8f6a8..787cfa52 100644 --- a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs +++ b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs @@ -33,8 +33,13 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials /// neutral contract. /// /// - public sealed class TizenScreenshot : IScreenshot, IViewScreenshot + public sealed class TizenScreenshot : IScreenshot, IViewScreenshot, IDisposable { + readonly ITizenScreenshotDispatcher _dispatcher; + readonly ITizenScreenshotCaptureFactory _factory; + readonly CancellationTokenSource _disposeCancellation = new(); + int _disposed; + /// /// How long to wait for Capture.Finished before giving up. /// @@ -47,12 +52,29 @@ public sealed class TizenScreenshot : IScreenshot, IViewScreenshot /// public static TimeSpan CaptureTimeout { get; set; } = TimeSpan.FromSeconds(10); + /// Creates a screenshot service backed by NUI Capture. + public TizenScreenshot() + : this(TizenScreenshotDispatcher.Instance, TizenScreenshotCaptureFactory.Instance) + { + } + + internal TizenScreenshot( + ITizenScreenshotDispatcher dispatcher, + ITizenScreenshotCaptureFactory factory) + { + _dispatcher = dispatcher; + _factory = factory; + } + /// public bool IsCaptureSupported => true; /// - public Task CaptureAsync() => - CaptureAsync(TizenWindow.Default); + public async Task CaptureAsync() => + await CaptureCoreAsync( + _factory.CreateDefaultWindowCapture, + CancellationToken.None).ConfigureAwait(false) + ?? throw new InvalidOperationException("Tizen reported a failed window capture."); /// /// Captures a screenshot of the supplied NUI window. @@ -63,17 +85,9 @@ public async Task CaptureAsync(TizenWindow window) { ArgumentNullException.ThrowIfNull(window); - int width; - int height; - - // Size2D is a native handle, not a value type. - using (var size = window.WindowSize) - { - width = size.Width; - height = size.Height; - } - - return await CaptureCoreAsync(window.GetDefaultLayer(), width, height).ConfigureAwait(false) + return await CaptureCoreAsync( + () => _factory.CreateWindowCapture(window), + CancellationToken.None).ConfigureAwait(false) ?? throw new InvalidOperationException("Tizen reported a failed window capture."); } @@ -86,16 +100,9 @@ public async Task CaptureAsync(TizenWindow window) { ArgumentNullException.ThrowIfNull(view); - int width; - int height; - - using (var size = view.Size2D) - { - width = size.Width; - height = size.Height; - } - - return CaptureCoreAsync(view, width, height); + return CaptureCoreAsync( + () => _factory.CreateViewCapture(view), + CancellationToken.None); } /// @@ -110,65 +117,262 @@ public async Task CaptureAsync(TizenWindow window) async Task CaptureWindowAsync(TizenWindow window) => await CaptureAsync(window).ConfigureAwait(false); - static async Task CaptureCoreAsync(Container source, int width, int height) + internal async Task CaptureCoreAsync( + Func createSession, + CancellationToken cancellationToken, + TimeSpan? timeoutOverride = null) { - if (width <= 0 || height <= 0) - throw new InvalidOperationException("Cannot capture a screenshot of a zero-sized NUI container."); - + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + ITizenScreenshotCaptureSession? session = null; + void OnFinished(bool success) => tcs.TrySetResult(success); - // Capture.Start requires a writable destination path even when the pixel buffer is what - // we actually consume, so a cache-scoped scratch file is used and removed afterwards. - var scratchPath = System.IO.Path.Combine( - global::Tizen.Applications.Application.Current.DirectoryInfo.Cache, - $"maui-screenshot-{Guid.NewGuid():N}.png"); - - var capture = new Capture(); - - void OnFinished(object? sender, CaptureFinishedEventArgs e) => tcs.TrySetResult(e.Success); - - capture.Finished += OnFinished; + var effectiveTimeout = timeoutOverride ?? CaptureTimeout; + using var timeout = new CancellationTokenSource(effectiveTimeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + _disposeCancellation.Token, + timeout.Token); - try + void ThrowIfCanceled() { - using (var size = new TizenNUISize(width, height, 0)) - using (var background = Color.Transparent) + if (_disposeCancellation.IsCancellationRequested) + throw new ObjectDisposedException(nameof(TizenScreenshot)); + cancellationToken.ThrowIfCancellationRequested(); + if (timeout.IsCancellationRequested) { - capture.Start(source, size, scratchPath, background); + throw new TimeoutException( + $"Tizen did not raise Capture.Finished within {effectiveTimeout}."); } + } - var completed = await Task.WhenAny(tcs.Task, Task.Delay(CaptureTimeout)).ConfigureAwait(false); + using var registration = linked.Token.Register(() => + { + if (_disposeCancellation.IsCancellationRequested) + tcs.TrySetException(new ObjectDisposedException(nameof(TizenScreenshot))); + else if (cancellationToken.IsCancellationRequested) + tcs.TrySetCanceled(cancellationToken); + else + tcs.TrySetException( + new TimeoutException( + $"Tizen did not raise Capture.Finished within {effectiveTimeout}.")); + }); - if (completed != tcs.Task) + try + { + await _dispatcher.InvokeAsync(() => { - throw new TimeoutException( - $"Tizen did not raise Capture.Finished within {CaptureTimeout}. " + - "The capture was abandoned rather than waiting indefinitely."); - } + ThrowIfCanceled(); + session = createSession(); + session.Finished += OnFinished; + session.Start(); + }).ConfigureAwait(false); if (!await tcs.Task.ConfigureAwait(false)) return null; - using var buffer = capture.GetCapturedBuffer(); - - return buffer is null ? null : TizenScreenshotResult.FromPixelBuffer(buffer); + timeout.CancelAfter(Timeout.InfiniteTimeSpan); + var buffer = await _dispatcher.InvokeAsync(() => + { + ThrowIfCanceled(); + return session!.CopyBuffer(); + }).ConfigureAwait(false); + + // Once the managed bytes are copied, encoding and result construction no longer + // touch NUI and can continue off the dispatcher. + return buffer is null + ? null + : await Task.Run( + () => TizenScreenshotResult.FromCapturedBuffer(buffer), + CancellationToken.None).ConfigureAwait(false); } finally { - capture.Finished -= OnFinished; - capture.Dispose(); - - try + if (session is not null) { - if (File.Exists(scratchPath)) - File.Delete(scratchPath); - } - catch (Exception) - { - // A leftover scratch file in the cache directory is not worth failing a capture. + try + { + await _dispatcher.InvokeAsync(() => + { + session.Finished -= OnFinished; + session.Dispose(); + }).ConfigureAwait(false); + } + catch (Exception) when (linked.IsCancellationRequested) + { + // Cancellation/disposal has already settled the caller. Native cleanup is + // best effort when the app's dispatcher itself is shutting down. + } } } } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + _disposeCancellation.Cancel(); + } + } + + internal sealed record TizenCapturedPixels( + byte[] Pixels, + int Width, + int Height, + TizenColorSpace ColorSpace); + + internal sealed record TizenCapturedBuffer( + byte[] Buffer, + int Width, + int Height, + int Stride, + PixelFormat Format); + + internal interface ITizenScreenshotDispatcher + { + Task InvokeAsync(Action action); + + Task InvokeAsync(Func action); + } + + internal interface ITizenScreenshotCaptureFactory + { + ITizenScreenshotCaptureSession CreateDefaultWindowCapture(); + + ITizenScreenshotCaptureSession CreateWindowCapture(TizenWindow window); + + ITizenScreenshotCaptureSession CreateViewCapture(TizenView view); + } + + internal interface ITizenScreenshotCaptureSession : IDisposable + { + event Action? Finished; + + void Start(); + + TizenCapturedBuffer? CopyBuffer(); + } + + sealed class TizenScreenshotDispatcher : ITizenScreenshotDispatcher + { + public static TizenScreenshotDispatcher Instance { get; } = new(); + + public Task InvokeAsync(Action action) => + Microsoft.Maui.ApplicationModel.MainThread.InvokeOnMainThreadAsync(action); + + public Task InvokeAsync(Func action) => + Microsoft.Maui.ApplicationModel.MainThread.InvokeOnMainThreadAsync(action); + } + + sealed class TizenScreenshotCaptureFactory : ITizenScreenshotCaptureFactory + { + public static TizenScreenshotCaptureFactory Instance { get; } = new(); + + public ITizenScreenshotCaptureSession CreateDefaultWindowCapture() => + CreateWindowCapture(TizenWindow.Default); + + public ITizenScreenshotCaptureSession CreateWindowCapture(TizenWindow window) + { + using var size = window.WindowSize; + return new TizenScreenshotCaptureSession( + window.GetDefaultLayer(), + size.Width, + size.Height); + } + + public ITizenScreenshotCaptureSession CreateViewCapture(TizenView view) + { + using var size = view.Size2D; + return new TizenScreenshotCaptureSession(view, size.Width, size.Height); + } + } + + sealed class TizenScreenshotCaptureSession : ITizenScreenshotCaptureSession + { + readonly Container _source; + readonly int _width; + readonly int _height; + readonly string _scratchPath; + readonly Capture _capture = new(); + + public TizenScreenshotCaptureSession(Container source, int width, int height) + { + if (width <= 0 || height <= 0) + throw new InvalidOperationException("Cannot capture a screenshot of a zero-sized NUI container."); + + _source = source; + _width = width; + _height = height; + _scratchPath = System.IO.Path.Combine( + global::Tizen.Applications.Application.Current.DirectoryInfo.Cache, + $"maui-screenshot-{Guid.NewGuid():N}.png"); + _capture.Finished += OnFinished; + } + + public event Action? Finished; + + public void Start() + { + using var size = new TizenNUISize(_width, _height, 0); + using var background = Color.Transparent; + _capture.Start(_source, size, _scratchPath, background); + } + + public TizenCapturedBuffer? CopyBuffer() + { + using var buffer = _capture.GetCapturedBuffer(); + if (buffer is null) + return null; + + var width = checked((int)buffer.GetWidth()); + var height = checked((int)buffer.GetHeight()); + var format = buffer.GetPixelFormat(); + var bytesPerPixel = TizenScreenshotResult.BytesPerPixel(format); + var rowBytes = checked(width * bytesPerPixel); +#if TIZEN_API15 + var stride = checked((int)buffer.GetStrideBytes()); +#else + // The host verification package predates API15. Product and API15 lanes compile the + // branch above; strict coordinator tests provide padded rows without invoking NUI. + var stride = rowBytes; +#endif + if (stride < rowBytes) + throw new InvalidOperationException( + $"Tizen returned stride {stride} for a {rowBytes}-byte row."); + + var native = buffer.GetBuffer(); + if (native == IntPtr.Zero) + throw new InvalidOperationException("Tizen returned an empty capture buffer."); + + var padded = new byte[checked(stride * height)]; + Marshal.Copy(native, padded, 0, padded.Length); + + return new TizenCapturedBuffer( + padded, + width, + height, + stride, + format); + } + + public void Dispose() + { + _capture.Finished -= OnFinished; + _capture.Dispose(); + + try + { + if (File.Exists(_scratchPath)) + File.Delete(_scratchPath); + } + catch (Exception) + { + // Cache cleanup must not hide an otherwise successful capture. + } + } + + void OnFinished(object? sender, CaptureFinishedEventArgs e) => + Finished?.Invoke(e.Success); } /// @@ -193,21 +397,46 @@ public sealed class TizenScreenshotResult : IScreenshotResult /// public int Height { get; } - internal static TizenScreenshotResult FromPixelBuffer(PixelBuffer buffer) + internal static TizenScreenshotResult FromCapturedPixels(TizenCapturedPixels pixels) => + new( + pixels.Pixels, + pixels.Width, + pixels.Height, + pixels.ColorSpace); + + internal static TizenScreenshotResult FromCapturedBuffer(TizenCapturedBuffer buffer) => + FromCapturedPixels( + CopyRows( + buffer.Buffer, + buffer.Width, + buffer.Height, + buffer.Stride, + buffer.Format)); + + internal static TizenCapturedPixels CopyRows( + byte[] padded, + int width, + int height, + int stride, + PixelFormat format) { - var width = (int)buffer.GetWidth(); - var height = (int)buffer.GetHeight(); - var format = buffer.GetPixelFormat(); var colorSpace = MapColorSpace(format); - var stride = BytesPerPixel(format); - - var pixels = new byte[width * height * stride]; - var native = buffer.GetBuffer(); - - if (native == IntPtr.Zero) - throw new InvalidOperationException("Tizen returned an empty capture buffer."); - - Marshal.Copy(native, pixels, 0, pixels.Length); + var rowBytes = checked(width * BytesPerPixel(format)); + if (stride < rowBytes) + throw new ArgumentOutOfRangeException(nameof(stride)); + if (padded.Length < checked(stride * height)) + throw new ArgumentException("The source buffer is shorter than its declared stride.", nameof(padded)); + + var pixels = new byte[checked(rowBytes * height)]; + for (var row = 0; row < height; row++) + { + Buffer.BlockCopy( + padded, + row * stride, + pixels, + row * rowBytes, + rowBytes); + } // RGBX has no Tizen colour space, so the padding byte is promoted to an opaque alpha and // the buffer encoded as RGBA. Encoding it as RGBA without this step would treat whatever @@ -215,7 +444,7 @@ internal static TizenScreenshotResult FromPixelBuffer(PixelBuffer buffer) if (format == PixelFormat.RGB8888) MakeOpaque(pixels); - return new TizenScreenshotResult(pixels, width, height, colorSpace); + return new TizenCapturedPixels(pixels, width, height, colorSpace); } internal static void MakeOpaque(byte[] pixels) diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs index 851d1848..53edcbeb 100644 --- a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Storage; @@ -29,8 +30,10 @@ public sealed class TizenSecureStorage : ISecureStorage static readonly object Locker = new(); static readonly UTF8Encoding StrictUtf8 = new(false, true); const string AliasVersion = "~v2~"; + const string TransactionVersion = "~tx~"; readonly ITizenSecureRepository _repository; readonly ITizenSecureStorageTombstones _tombstones; + readonly Func _currentPackageId; /// /// Prefix identifying aliases owned by this API. @@ -45,16 +48,21 @@ public sealed class TizenSecureStorage : ISecureStorage /// Creates a secure-storage service backed by Tizen's secure repository. /// public TizenSecureStorage() - : this(TizenSecureRepository.Instance, TizenSecureStorageTombstones.Instance) + : this( + TizenSecureRepository.Instance, + TizenSecureStorageTombstones.Instance, + static () => TizenPlatform.CurrentPackageId) { } internal TizenSecureStorage( ITizenSecureRepository repository, - ITizenSecureStorageTombstones? tombstones = null) + ITizenSecureStorageTombstones? tombstones = null, + Func? currentPackageId = null) { _repository = repository; _tombstones = tombstones ?? new InMemorySecureStorageTombstones(); + _currentPackageId = currentPackageId ?? (static () => null); } /// @@ -64,6 +72,8 @@ internal TizenSecureStorage( lock (Locker) { + RecoverStagedValue(key); + try { // The second parameter is the data password, not a default value. @@ -78,13 +88,15 @@ internal TizenSecureStorage( return Task.FromResult(null); byte[] legacyValue; + string? migratedOwnedAlias = null; try { if (!CanUseLegacyNamespacedAlias(key)) throw new InvalidOperationException(); - legacyValue = _repository.Get(ToLegacyNamespacedAlias(key)); + migratedOwnedAlias = ToLegacyNamespacedAlias(key); + legacyValue = _repository.Get(migratedOwnedAlias); } catch (InvalidOperationException) { @@ -120,6 +132,18 @@ internal TizenSecureStorage( // Legacy namespaced and raw aliases are copied into v2. Raw aliases are unowned and // may belong to another component, so they are never deleted. _repository.Save(ToAlias(key), legacyValue); + if (migratedOwnedAlias is not null) + { + try + { + _repository.RemoveAlias(migratedOwnedAlias); + } + catch (Exception) + { + // The v2 copy is committed and wins. A duplicate v1 alias is harmless and + // can be cleaned by the next Set/Remove without failing this read. + } + } return Task.FromResult(Encoding.UTF8.GetString(legacyValue)); } @@ -134,11 +158,11 @@ public Task SetAsync(string key, string value) lock (Locker) { var alias = ToAlias(key); - RemoveOwnedAliasIfPresent(alias); - if (CanUseLegacyNamespacedAlias(key)) - RemoveOwnedAliasIfPresent(ToLegacyNamespacedAlias(key)); - - _repository.Save(alias, Encoding.UTF8.GetBytes(value)); + RecoverStagedValue(key); + ReplaceOwnedAliases( + key, + alias, + Encoding.UTF8.GetBytes(value)); _tombstones.Remove(key); return Task.CompletedTask; } @@ -180,6 +204,7 @@ public bool Remove(string key) // Missing v1 namespaced data is expected. } + RemoveStagedAliases(key); _tombstones.Add(key); return removed; } @@ -209,9 +234,10 @@ public void RemoveAll() return; } + var currentPackageId = _currentPackageId(); foreach (var alias in aliases) { - if (!IsOwnedAlias(alias)) + if (!IsOwnedAlias(alias, currentPackageId)) continue; try @@ -269,10 +295,11 @@ internal static bool CanUseLegacyNamespacedAlias(string key) /// The raw key manager alias. /// when the alias is owned by this API. /// - /// Tizen may return aliases qualified with the owning package id (pkgid alias), so a - /// trailing match is accepted as well as an exact prefix match. + /// Tizen may return aliases qualified with the owning package id (pkgid alias). + /// Qualified aliases are accepted only when that owner exactly equals the current package; + /// another package can use the same raw prefix without transferring ownership. /// - internal static bool IsOwnedAlias(string alias) + internal static bool IsOwnedAlias(string alias, string? currentPackageId = null) { if (string.IsNullOrEmpty(alias)) return false; @@ -280,12 +307,178 @@ internal static bool IsOwnedAlias(string alias) if (alias.StartsWith(AliasPrefix, StringComparison.Ordinal)) return true; - var separator = alias.LastIndexOf(' '); + var separator = alias.IndexOf(' '); + if (separator <= 0 || separator == alias.Length - 1) + return false; - return separator >= 0 && + return !string.IsNullOrEmpty(currentPackageId) && + alias.AsSpan(0, separator).Equals(currentPackageId, StringComparison.Ordinal) && alias.AsSpan(separator + 1).StartsWith(AliasPrefix, StringComparison.Ordinal); } + void ReplaceOwnedAliases(string key, string alias, byte[] value) + { + var legacyAlias = CanUseLegacyNamespacedAlias(key) + ? ToLegacyNamespacedAlias(key) + : null; + var hadCurrent = TryGet(alias, out var previousCurrent); + byte[]? previousLegacy = null; + var hadLegacy = legacyAlias is not null && TryGet(legacyAlias, out previousLegacy); + var stagedAlias = GetTransactionPrefix(key) + Guid.NewGuid().ToString("N"); + + // Stage first. If this fails, every prior alias is untouched. + _repository.Save(stagedAlias, value); + + try + { + RemoveOwnedAliasIfPresent(alias); + if (legacyAlias is not null) + RemoveOwnedAliasIfPresent(legacyAlias); + + _repository.Save(alias, value); + } + catch (Exception commitFailure) + { + var restoreFailures = new List(); + Restore(alias, hadCurrent, previousCurrent, restoreFailures); + if (legacyAlias is not null) + Restore(legacyAlias, hadLegacy, previousLegacy, restoreFailures); + + if (restoreFailures.Count == 0) + { + RemoveOwnedAliasIfPresent(stagedAlias); + throw; + } + + // The staged new value is deliberately retained when restoration fails. Its + // versioned key lets the next read recover rather than silently lose both values. + throw new AggregateException( + "SecureStorage replacement failed and one or more previous aliases could not be restored. " + + "The staged value was retained for recovery.", + new[] { commitFailure }.Concat(restoreFailures)); + } + + RemoveOwnedAliasIfPresent(stagedAlias); + } + + void RecoverStagedValue(string key) + { + var alias = ToAlias(key); + var staged = GetStagedAliases(key).ToList(); + if (staged.Count == 0) + return; + + if (!TryGet(alias, out _)) + { + // Multiple staged aliases can only result from interrupted retries. The repository's + // enumeration order is not a commit order, so fail closed rather than choosing one. + if (staged.Count != 1) + throw new InvalidOperationException( + $"Multiple interrupted SecureStorage replacements exist for '{key}'."); + + _repository.Save(alias, _repository.Get(staged[0])); + } + + foreach (var stagedAlias in staged) + RemoveOwnedAliasIfPresent(stagedAlias); + } + + void RemoveStagedAliases(string key) + { + foreach (var alias in GetStagedAliases(key)) + RemoveOwnedAliasIfPresent(alias); + } + + IEnumerable GetStagedAliases(string key) + { + IEnumerable aliases; + try + { + aliases = _repository.GetAliases(); + } + catch + { + yield break; + } + + var prefix = GetTransactionPrefix(key); + var currentPackageId = _currentPackageId(); + foreach (var qualifiedAlias in aliases) + { + if (!TryGetOwnedRawAlias(qualifiedAlias, currentPackageId, out var rawAlias)) + continue; + if (rawAlias.StartsWith(prefix, StringComparison.Ordinal)) + yield return qualifiedAlias; + } + } + + static bool TryGetOwnedRawAlias( + string alias, + string? currentPackageId, + out string rawAlias) + { + if (alias.StartsWith(AliasPrefix, StringComparison.Ordinal)) + { + rawAlias = alias; + return true; + } + + var separator = alias.IndexOf(' '); + if (separator > 0 && + !string.IsNullOrEmpty(currentPackageId) && + alias.AsSpan(0, separator).Equals(currentPackageId, StringComparison.Ordinal) && + alias.AsSpan(separator + 1).StartsWith(AliasPrefix, StringComparison.Ordinal)) + { + rawAlias = alias[(separator + 1)..]; + return true; + } + + rawAlias = string.Empty; + return false; + } + + static string GetTransactionPrefix(string key) => + AliasPrefix + TransactionVersion + + Convert.ToBase64String(StrictUtf8.GetBytes(key)) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_') + + "~"; + + bool TryGet(string alias, out byte[] value) + { + try + { + value = _repository.Get(alias); + return true; + } + catch (InvalidOperationException) + { + value = []; + return false; + } + } + + void Restore( + string alias, + bool existed, + byte[]? value, + ICollection failures) + { + if (!existed || value is null) + return; + + try + { + if (!TryGet(alias, out _)) + _repository.Save(alias, value); + } + catch (Exception exception) + { + failures.Add(exception); + } + } + void RemoveOwnedAliasIfPresent(string alias) { try diff --git a/src/Maui.Tizen.Essentials/Share/TizenShare.cs b/src/Maui.Tizen.Essentials/Share/TizenShare.cs index ba6f2f1c..bd354595 100644 --- a/src/Maui.Tizen.Essentials/Share/TizenShare.cs +++ b/src/Maui.Tizen.Essentials/Share/TizenShare.cs @@ -114,7 +114,7 @@ internal static string ResolveMime(IEnumerable files) return types.Length == 1 ? types[0]! : TizenFileMimeTypes.All; } - static string? ResolveMime(FileBase file) + internal static string? ResolveMime(FileBase file) { try { diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs index 2bf2c17b..160455b3 100644 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -157,7 +157,7 @@ await RunWithCurrentClientAsync( text, resolvedLanguage, voiceType, - ResolveRate(state.Client!, rate)); + ResolveRate(state, rate)); }).ConfigureAwait(false); SetActiveUtterance(state, utteranceId, completion); @@ -299,6 +299,9 @@ void PrepareOnMainThread(ClientState state) return; } + // Tizen only permits GetSpeedRange while the new client is in Created. Cache it before + // Prepare transitions the client, then apply the caller's rate after Ready. + state.MaximumSpeed = client.GetMaximumSpeed(); client.Prepare(); void OnStateChanged(TizenTextToSpeechState current) @@ -527,13 +530,13 @@ static void StopQuietly(ITizenTextToSpeechClient client) return (language, voiceType); } - static int ResolveRate(ITizenTextToSpeechClient client, float? rate) + static int ResolveRate(ClientState state, float? rate) { if (rate is not { } value) return 0; return (int)Math.Round( - value / RateMax * client.GetMaximumSpeed(), + value / RateMax * state.MaximumSpeed, MidpointRounding.AwayFromZero); } @@ -602,6 +605,8 @@ sealed class ClientState public bool StopBeforeTeardown { get; set; } public bool TeardownPosted { get; set; } + + public int MaximumSpeed { get; set; } } sealed record ActiveUtterance( diff --git a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs index b1c4b894..b725f9dc 100644 --- a/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs +++ b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs @@ -1,4 +1,7 @@ using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Devices.Sensors; using TizenSensor = Tizen.Sensor.Sensor; @@ -6,213 +9,301 @@ namespace Microsoft.Maui.Platforms.Tizen.Essentials { /// - /// Shared start/stop bookkeeping for the Tizen sensor implementations. + /// Shared generation and ref-counted native lifetime for a Tizen sensor implementation. /// - /// The native Tizen sensor type. - /// - /// - /// dotnet/maui expressed this logic once per sensor in the *.shared.cs half of a partial - /// class. Since this backend ships independently named classes, the common behaviour lives here - /// instead of being copied into each implementation. - /// - /// - /// Start and Stop are transactional. A native failure part way through leaves no subscription - /// behind and no state claiming the sensor is monitoring when it is not: an earlier version - /// restored but left DataUpdated attached if - /// sensor.Start() threw, so the next Start would double-subscribe and every reading was - /// then raised twice. - /// - /// public abstract class TizenSensorBase where TSensor : TizenSensor { - readonly object _locker = new(); + static readonly TizenSensorLifetimeCoordinator Lifetime = new(); + readonly TizenSensorGenerationGate _generation = new(); + readonly object _operationLock = new(); + readonly TizenNativeCallbackCoordinator _callbacks = new(); - /// - /// Gets a value indicating whether readings should be marshalled to the main thread. - /// - protected bool UseSyncContext { get; private set; } + /// Gets whether readings should be marshalled to the main thread. + protected bool UseSyncContext => _generation.UseSyncContext; - /// - /// Gets a value indicating whether the sensor is currently being monitored. - /// - public bool IsMonitoring { get; private set; } + /// Gets whether this wrapper is currently monitoring. + public bool IsMonitoring => _generation.IsMonitoring; - /// - /// Gets a value indicating whether this device provides the sensor. - /// + /// Gets whether this device provides the sensor. public abstract bool IsSupported { get; } - /// - /// Gets the display name used in diagnostics and exception messages. - /// + /// Gets the display name used in diagnostics. protected abstract string SensorName { get; } - /// - /// Gets the shared native sensor instance. - /// + /// Gets the shared native sensor instance. protected abstract TSensor Sensor { get; } - /// Attaches the native data-updated handler. - /// The native sensor. - protected abstract void Subscribe(TSensor sensor); - - /// Detaches the native data-updated handler. - /// The native sensor. - protected abstract void Unsubscribe(TSensor sensor); - /// - /// Called after the sensor has started, so derived types can reset per-session state. + /// Subscribes a generation-specific native callback and returns its exact unsubscribe action. /// + protected abstract Action Subscribe(TSensor sensor, long generation); + + /// Resets per-wrapper state after a successful start. protected virtual void OnStarted() { } - /// - /// Called after the sensor has stopped, so derived types can release per-session state. - /// + /// Releases per-wrapper state after stop or failed start. protected virtual void OnStopped() { } - /// - /// Starts monitoring the sensor. - /// - /// The requested reporting speed. - /// The device has no such sensor. - /// Monitoring is already in progress. + /// Starts monitoring. public void Start(SensorSpeed sensorSpeed) { if (!IsSupported) throw TizenEssentialsSupport.NotSupported($"{SensorName}.Start", $"This device has no {SensorName} sensor."); - - lock (_locker) + lock (_operationLock) { - if (IsMonitoring) - throw new InvalidOperationException($"{SensorName} has already been started."); - - var sensor = Sensor; - var subscribed = false; - var started = false; + var generation = _generation.BeginStart( + sensorSpeed is SensorSpeed.Default or SensorSpeed.UI, + SensorName); try { - sensor.Interval = sensorSpeed.ToPlatform(); - - Subscribe(sensor); - subscribed = true; - - sensor.Start(); - started = true; - - OnStarted(); - - UseSyncContext = sensorSpeed is SensorSpeed.Default or SensorSpeed.UI; - IsMonitoring = true; + Lifetime.Start( + this, + Sensor, + sensorSpeed.ToPlatform(), + static (sensor, interval) => sensor.Interval = interval, + sensor => Subscribe(sensor, generation), + static sensor => sensor.Start(), + static sensor => sensor.Stop(), + static sensor => TizenSensors.ResetDefaultSensor(sensor), + OnStarted); } catch { - RollbackFailedStart( - started, - subscribed, - () => sensor.Stop(), - () => Unsubscribe(sensor), - () => TizenSensors.ResetDefaultSensor(sensor)); + _generation.Invalidate(); + OnStopped(); throw; } } } - internal static void RollbackFailedStart( - bool started, - bool subscribed, - Action stop, - Action unsubscribe, - Action reset) + /// Stops monitoring. + public void Stop() { - if (subscribed) - TryRollback(unsubscribe); - - if (started) - TryRollback(stop); + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{SensorName}.Stop", $"This device has no {SensorName} sensor."); + lock (_operationLock) + { + if (!_generation.Invalidate()) + return; - TryRollback(reset); + Lifetime.Stop( + this, + static sensor => sensor.Stop(), + static sensor => TizenSensors.ResetDefaultSensor(sensor), + static (sensor, interval) => sensor.Interval = interval, + OnStopped); + } } - static void TryRollback(Action action) + /// Returns whether a native callback belongs to the active start generation. + protected bool IsCurrentGeneration(long generation) => + _generation.IsCurrent(generation); + + /// Raises a reading only while its start generation is still active. + protected void Raise( + long generation, + EventHandler? handler, + TArgs args) + where TArgs : EventArgs { - try + if (handler is null || !IsCurrentGeneration(generation)) + return; + + if (UseSyncContext) { - action(); + _callbacks.Post( + () => IsCurrentGeneration(generation), + () => handler.Invoke(this, args)); } - catch (Exception) + else if (IsCurrentGeneration(generation)) { - // Preserve the failure that caused the rollback. + handler.Invoke(this, args); } } + } - /// - /// Stops monitoring the sensor. - /// - /// The device has no such sensor. - public void Stop() + internal sealed class TizenSensorGenerationGate + { + long _generation; + int _monitoring; + int _useSyncContext; + + public bool IsMonitoring => Volatile.Read(ref _monitoring) != 0; + + public bool UseSyncContext => Volatile.Read(ref _useSyncContext) != 0; + + public long BeginStart(bool useSyncContext, string sensorName) { - if (!IsSupported) - throw TizenEssentialsSupport.NotSupported($"{SensorName}.Stop", $"This device has no {SensorName} sensor."); + if (Interlocked.CompareExchange(ref _monitoring, 1, 0) != 0) + throw new InvalidOperationException($"{sensorName} has already been started."); - lock (_locker) + Volatile.Write(ref _useSyncContext, useSyncContext ? 1 : 0); + return Interlocked.Increment(ref _generation); + } + + public bool Invalidate() + { + if (Interlocked.Exchange(ref _monitoring, 0) == 0) + return false; + + Interlocked.Increment(ref _generation); + return true; + } + + public bool IsCurrent(long generation) => + IsMonitoring && Volatile.Read(ref _generation) == generation; + } + + internal sealed class TizenSensorLifetimeCoordinator + where TSensor : class + { + readonly object _locker = new(); + readonly Dictionary _registrations = + new(ReferenceEqualityComparer.Instance); + TSensor? _sensor; + + public int ActiveCount + { + get { - if (!IsMonitoring) - return; + lock (_locker) + return _registrations.Count; + } + } - var sensor = Sensor; + public void Start( + object owner, + TSensor sensor, + uint interval, + Action setInterval, + Func subscribe, + Action start, + Action stop, + Action reset, + Action started) + { + lock (_locker) + { + if (_registrations.ContainsKey(owner)) + throw new InvalidOperationException("This sensor wrapper has already started."); - // Unsubscribe first: once the handler is detached no further readings can be - // delivered, so even if Stop() throws the sensor is no longer raising events. - Unsubscribe(sensor); + _sensor ??= sensor; + var first = _registrations.Count == 0; + Action? unsubscribe = null; + var registered = false; + var nativeStartAttempted = false; try { - sensor.Stop(); + unsubscribe = subscribe(_sensor); + _registrations.Add(owner, new(interval, unsubscribe)); + registered = true; + ApplyFastestInterval(_sensor, setInterval); + + if (first) + { + nativeStartAttempted = true; + start(_sensor); + } + + started(); } catch { - // The native sensor is still running, so restore the subscription to keep the - // object's state and the platform's state consistent. - try + if (registered) + _registrations.Remove(owner); + TryCleanup(unsubscribe); + if (first && nativeStartAttempted) + TryCleanup(() => stop(_sensor)); + + if (_registrations.Count == 0) { - Subscribe(sensor); + TryCleanup(() => reset(_sensor)); + _sensor = null; } - catch + else { - // Nothing further can be done; surface the original failure. + TryCleanup(() => ApplyFastestInterval(_sensor, setInterval)); } throw; } - - IsMonitoring = false; } + } + + public void Stop( + object owner, + Action stop, + Action reset, + Action setInterval, + Action stopped) + { + lock (_locker) + { + if (!_registrations.Remove(owner, out var registration) || _sensor is null) + return; + + var failures = new List(); + TryCleanup(registration.Unsubscribe, failures); - OnStopped(); + if (_registrations.Count == 0) + { + TryCleanup(() => stop(_sensor), failures); + TryCleanup(() => reset(_sensor), failures); + _sensor = null; + } + else + { + TryCleanup(() => ApplyFastestInterval(_sensor, setInterval), failures); + } + + TryCleanup(stopped, failures); + + if (failures.Count == 1) + throw failures[0]; + if (failures.Count > 1) + throw new AggregateException("Sensor teardown failed.", failures); + } } - /// - /// Raises a reading changed event, honouring the requested sensor speed. - /// - /// The event argument type. - /// The event handler to invoke. - /// The event arguments. - protected void Raise(EventHandler? handler, TArgs args) - where TArgs : EventArgs + void ApplyFastestInterval(TSensor sensor, Action setInterval) { - if (handler is null) + if (_registrations.Count == 0) return; - if (UseSyncContext) - MainThread.BeginInvokeOnMainThread(() => handler.Invoke(this, args)); - else - handler.Invoke(this, args); + setInterval(sensor, _registrations.Values.Min(registration => registration.Interval)); + } + + static void TryCleanup(Action? action) + { + try + { + action?.Invoke(); + } + catch (Exception) + { + // Preserve the failure that triggered rollback. + } + } + + static void TryCleanup(Action action, ICollection failures) + { + try + { + action(); + } + catch (Exception exception) + { + failures.Add(exception); + } } + + sealed record Registration(uint Interval, Action Unsubscribe); } } diff --git a/tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj b/tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj index dce534fd..7ad29fd5 100644 --- a/tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj +++ b/tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj @@ -17,6 +17,7 @@ + $(MSBuildAllProjects);$(RepositoryRoot)eng/targets/TizenPackage.props $(DotNetTfm) false diff --git a/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs b/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs index f6cb4ea0..86ef7cbb 100644 --- a/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs +++ b/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs @@ -148,4 +148,53 @@ public async Task WindowInstance_DeprecationMessageStillNamesDefault() window.ObsoleteMembers["Instance"], StringComparison.OrdinalIgnoreCase); } + + [Theory] + [InlineData("Tizen.NUI.dll", "Tizen.NUI.Clipboard")] + [InlineData("Tizen.Security.WebAuthn.dll", "Tizen.Security.WebAuthn.Authenticator")] + public async Task EssentialsApi15Capabilities_ArePresent( + string assemblyName, + string typeName) + { + var directory = await AcquireOrSkipAsync().ConfigureAwait(true); + var assembly = ReferencePackProbe.FindAssembly(directory, assemblyName); + + Assert.True(assembly is not null, $"'{assemblyName}' is not in the API15 reference pack."); + Assert.NotNull(ReferencePackProbe.ReadTypeMembers(assembly!, typeName)); + } + + [Fact] + public async Task ScreenshotStrideAndClipboardTextMethods_ArePublicInApi15() + { + var directory = await AcquireOrSkipAsync().ConfigureAwait(true); + var nui = ReferencePackProbe.FindAssembly(directory, "Tizen.NUI.dll"); + Assert.NotNull(nui); + + var pixelBuffer = ReferencePackProbe.ReadTypeMembers(nui!, "Tizen.NUI.PixelBuffer"); + var clipboard = ReferencePackProbe.ReadTypeMembers(nui!, "Tizen.NUI.Clipboard"); + + Assert.NotNull(pixelBuffer); + Assert.NotNull(clipboard); + Assert.True(pixelBuffer!.HasMethod("GetStrideBytes")); + Assert.True(clipboard!.HasMethod("SetData")); + Assert.True(clipboard.HasMethod("GetData")); + } + + [Fact] + public async Task WebAuthnAuthenticator_HasTheRequiredApi15Operations() + { + var directory = await AcquireOrSkipAsync().ConfigureAwait(true); + var assembly = ReferencePackProbe.FindAssembly(directory, "Tizen.Security.WebAuthn.dll"); + Assert.NotNull(assembly); + + var authenticator = ReferencePackProbe.ReadTypeMembers( + assembly!, + "Tizen.Security.WebAuthn.Authenticator"); + Assert.NotNull(authenticator); + + Assert.True(authenticator!.HasMethod("SupportedAuthenticators")); + Assert.True(authenticator.HasMethod("MakeCredential")); + Assert.True(authenticator.HasMethod("GetAssertion")); + Assert.True(authenticator.HasMethod("Cancel")); + } } diff --git a/tests/Maui.Tizen.Conventions.Tests/Api15SourceGuardTests.cs b/tests/Maui.Tizen.Conventions.Tests/Api15SourceGuardTests.cs index 82abcaea..957fc2c7 100644 --- a/tests/Maui.Tizen.Conventions.Tests/Api15SourceGuardTests.cs +++ b/tests/Maui.Tizen.Conventions.Tests/Api15SourceGuardTests.cs @@ -357,11 +357,13 @@ public void Geocoding_IsRecordedAsUnsupportedOnApi15() Assert.Equal("unsupported", geocoding.Status); - // Not merely degraded: the platform API it was built on no longer exists, so it must not be - // registered and must fail loudly rather than returning empty results that look like "no - // match found". - Assert.True(geocoding.DoNotRegisterInDi); - Assert.Contains("PlatformNotSupportedException", geocoding.Behaviour, StringComparison.Ordinal); + // The unsupported implementation is still registered so DI and the static facade resolve + // consistently. Operations fail loudly rather than returning an empty "no match" result. + Assert.False(geocoding.DoNotRegisterInDi); + Assert.Contains("IGeocoding", geocoding.Behaviour, StringComparison.Ordinal); + Assert.Contains("IPlatformGeocoding", geocoding.Behaviour, StringComparison.Ordinal); + Assert.Contains("FeatureNotSupportedException", geocoding.Behaviour, StringComparison.Ordinal); + Assert.Contains("MapServiceToken", geocoding.Behaviour, StringComparison.Ordinal); Assert.Contains("Tizen.Maps", geocoding.Reason, StringComparison.Ordinal); } diff --git a/tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj b/tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj index 6dda5e8a..e987d942 100644 --- a/tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj +++ b/tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj @@ -33,6 +33,7 @@ + $(MSBuildAllProjects);$(RepositoryRoot)eng/targets/TizenPackage.props $(DotNetTfm) false diff --git a/tests/Maui.Tizen.Core.UnitTests/BuildConfigurationTests.cs b/tests/Maui.Tizen.Core.UnitTests/BuildConfigurationTests.cs index f810837f..44b73d34 100644 --- a/tests/Maui.Tizen.Core.UnitTests/BuildConfigurationTests.cs +++ b/tests/Maui.Tizen.Core.UnitTests/BuildConfigurationTests.cs @@ -2,6 +2,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; +using System.Xml.Linq; using Xunit; namespace Microsoft.Maui.Platforms.Tizen.UnitTests @@ -96,6 +97,7 @@ public void TheIconIsCopiedToTheOutputForPackaging() [Theory] [InlineData(Core)] [InlineData(Controls)] + [InlineData("src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj")] public void ShippingAssembliesGenerateDocumentation(string project) { // The heuristic keyed off EnableDefaultCompileItems, which these two turn OFF - not @@ -107,13 +109,13 @@ public void ShippingAssembliesGenerateDocumentation(string project) } [Fact] - public void ProjectsThatCompileNothingDoNotGenerateDocumentation() + public void AnUnportedProjectThatCompilesNothingDoesNotGenerateDocumentation() { // The other half: the default must still hold for the un-ported projects, or the build // fills with CS1591 for assemblies that have no API at all. Assert.Equal( "false", - MSBuildEvaluation.GetProperty("src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj", "GenerateDocumentationFile")); + MSBuildEvaluation.GetProperty("src/Maui.Tizen.BlazorWebView/Maui.Tizen.BlazorWebView.csproj", "GenerateDocumentationFile")); } [Fact] @@ -159,17 +161,41 @@ public void TheAnalyzerAssetSetMatchesBetweenProductAndVerificationLanes() Assert.True(productAssets.Success, "The shared analyzer reference was not found."); Assert.Contains("buildtransitive", productAssets.Groups[1].Value, StringComparison.Ordinal); + var expectedAssets = productAssets.Groups[1].Value; foreach (var lane in new[] { "tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj", "tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj", + "tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj", }) { - var text = File.ReadAllText(Path.Combine(RepositoryRoot, lane)); - - Assert.Contains("buildtransitive", text, StringComparison.Ordinal); + var document = XDocument.Load(Path.Combine(RepositoryRoot, lane)); + var reference = Assert.Single( + document.Descendants("PackageReference"), + element => element.Attribute("Include")?.Value == + "Microsoft.CodeAnalysis.PublicApiAnalyzers"); + var actualAssets = + reference.Attribute("IncludeAssets")?.Value ?? + reference.Element("IncludeAssets")?.Value; + + Assert.Equal(expectedAssets, actualAssets); } } + + [Theory] + [InlineData("tests/Maui.Tizen.Core.RefPackCompile/Maui.Tizen.Core.RefPackCompile.csproj")] + [InlineData("tests/Maui.Tizen.Controls.RefPackCompile/Maui.Tizen.Controls.RefPackCompile.csproj")] + [InlineData("tests/Maui.Tizen.Sample.RefPackCompile/Maui.Tizen.Sample.RefPackCompile.csproj")] + [InlineData("tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj")] + public void RefPackLanesRebuildWhenSharedShippingPropertiesChange(string project) + { + var text = File.ReadAllText(Path.Combine(RepositoryRoot, project)); + + Assert.Contains( + "$(RepositoryRoot)eng/targets/TizenPackage.props", + text, + StringComparison.Ordinal); + } } } diff --git a/tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj b/tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj index 00a666de..1385fbcc 100644 --- a/tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj +++ b/tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj @@ -27,6 +27,7 @@ + $(MSBuildAllProjects);$(RepositoryRoot)eng/targets/TizenPackage.props $(DotNetTfm) false @@ -42,7 +43,7 @@ $(NoWarn);CS1591;NU1701 false - $(DefineConstants);TIZEN + $(DefineConstants);TIZEN;TIZEN_API15 @@ -63,7 +64,7 @@ surface with no workload, so it is the only place the baseline can actually be checked today. Without it, an API drift would sit undetected until the workload ships. --> - + + + diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs index ceb5386c..8b25c679 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs @@ -346,7 +346,11 @@ public void StartChangeNotifications(Action changed) if (RaiseOnStart) changed(); if (FailStartNotifications) + { + _dataSelected = null; + StopNotificationsCalls++; throw new InvalidOperationException("secondary selection failed"); + } } public void StopChangeNotifications() diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs index b52238f2..f7de146a 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs @@ -17,12 +17,12 @@ public void NativeStartRunsWithoutHoldingTheStateLock() var started = false; coordinator = new( this, - () => + publish => { - coordinator!.Publish(EventArgs.Empty); + publish(EventArgs.Empty); started = true; + return static () => { }; }, - static () => { }, new TizenNativeCallbackCoordinator(dispatcher)); coordinator.Add(static (_, _) => { }); @@ -34,26 +34,45 @@ public void NativeStartRunsWithoutHoldingTheStateLock() public async Task StaleQueuedEventNeverReachesReplacementSubscriber() { using var dispatcher = new StrictCallbackDispatcher(blockFirst: true); - var coordinator = new TizenEventSubscriptionCoordinator( - this, - static () => { }, - static () => { }, - new TizenNativeCallbackCoordinator(dispatcher)); var oldCalls = 0; var replacementCalls = 0; + Action? currentNative = null; + var retained = new List>(); EventHandler old = (_, _) => oldCalls++; - EventHandler replacement = (_, _) => replacementCalls++; + var replacementDelivered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler replacement = (_, _) => + { + replacementCalls++; + replacementDelivered.TrySetResult(); + }; + var coordinator = new TizenEventSubscriptionCoordinator( + this, + publish => + { + currentNative = publish; + retained.Add(publish); + return () => currentNative = null; + }, + new TizenNativeCallbackCoordinator(dispatcher)); coordinator.Add(old); - coordinator.Publish(EventArgs.Empty); + var oldNative = Assert.Single(retained); + oldNative(EventArgs.Empty); await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); coordinator.Remove(old); coordinator.Add(replacement); + Assert.NotSame(oldNative, currentNative); + oldNative(EventArgs.Empty); dispatcher.Release(); await dispatcher.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); Assert.Equal(0, oldCalls); Assert.Equal(0, replacementCalls); + + currentNative!(EventArgs.Empty); + await replacementDelivered.Task.WaitAsync(TestContext.Current.CancellationToken); + Assert.Equal(1, replacementCalls); } [Fact] @@ -64,13 +83,21 @@ public void FailedFirstSubscriptionRollsBackAndCanBeRetried() var fail = true; var coordinator = new TizenEventSubscriptionCoordinator( this, - () => + publish => { - native = true; - if (fail) - throw new InvalidOperationException("subscribe failed"); + try + { + native = true; + if (fail) + throw new InvalidOperationException("subscribe failed"); + return () => native = false; + } + catch + { + native = false; + throw; + } }, - () => native = false, new TizenNativeCallbackCoordinator(dispatcher)); EventHandler handler = static (_, _) => { }; @@ -88,14 +115,19 @@ public async Task DisposeInvalidatesAQueuedEventAndStopsNativeListening() using var dispatcher = new StrictCallbackDispatcher(blockFirst: true); var native = false; var calls = 0; + Action? nativeCallback = null; var coordinator = new TizenEventSubscriptionCoordinator( this, - () => native = true, - () => native = false, + publish => + { + native = true; + nativeCallback = publish; + return () => native = false; + }, new TizenNativeCallbackCoordinator(dispatcher)); - coordinator.Add((_, _) => calls++); - coordinator.Publish(EventArgs.Empty); + coordinator.Add((_, _) => calls++); + nativeCallback!(EventArgs.Empty); await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); coordinator.Dispose(); dispatcher.Release(); diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs index b58ca838..a0c2b393 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -635,6 +635,38 @@ public void SecureStorageRemoveAllDeletesOnlyNamespacedAliases() Assert.Equal("leave-me", repository["unrelated"]); } + [Fact] + public void SecureRepositoryNormalizesOnlyDocumentedNoAliasArgumentException() + { + Assert.Empty(new TizenSecureRepository( + static () => throw new ArgumentException("there's no alias to get")).GetAliases()); + + var genuine = Assert.Throws(() => + new TizenSecureRepository( + static () => throw new ArgumentException("invalid repository argument", "alias")) + .GetAliases()); + Assert.Equal("alias", genuine.ParamName); + + Assert.Throws(() => + new TizenSecureRepository( + static () => throw new InvalidOperationException("repository failed")) + .GetAliases()); + } + + [Fact] + public async Task SecureStorageEmptyRepositorySupportsFirstReadWriteRemoveAndRemoveAll() + { + var repository = new FakeSecureRepository(); + var storage = new TizenSecureStorage(repository); + + Assert.Null(await storage.GetAsync("token")); + await storage.SetAsync("token", "value"); + Assert.Equal("value", await storage.GetAsync("token")); + Assert.True(storage.Remove("token")); + Assert.Null(await storage.GetAsync("token")); + storage.RemoveAll(); + } + [Fact] public void SecureStorageRemoveAllPreservesQualifiedForeignPackageAliases() { From 6cd5c108cdd26efe0a6330d13bef0e33ed1f0612 Mon Sep 17 00:00:00 2001 From: redth Date: Sat, 29 Aug 2026 18:06:37 -0400 Subject: [PATCH 20/21] Remove cached-only API15 documentation dependency Keep the hosted convention proof on the publicly restorable Samsung API15 reference pack and rely on native-faithful unit coverage for the documented empty-alias sentinel. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7a37339a-ace9-487d-b025-3262b9d414d9 --- .../Api15ReferencePackTests.cs | 26 +++++-------------- .../Maui.Tizen.Conventions.Tests.csproj | 2 -- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs b/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs index fb0d9a40..3f0946d0 100644 --- a/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs +++ b/tests/Maui.Tizen.Conventions.Tests/Api15ReferencePackTests.cs @@ -215,7 +215,7 @@ public async Task ClipboardSecondarySelectionLifecycle_IsPublicInApi15() } [Fact] - public async Task SecureRepositoryDocumentsArgumentExceptionAsTheEmptyAliasSentinel() + public async Task SecureRepositoryGetAliases_IsPublicInApi15() { var directory = await AcquireOrSkipAsync().ConfigureAwait(true); var assembly = ReferencePackProbe.FindAssembly( @@ -223,24 +223,10 @@ public async Task SecureRepositoryDocumentsArgumentExceptionAsTheEmptyAliasSenti "Tizen.Security.SecureRepository.dll"); Assert.NotNull(assembly); - var pack = RepositoryBaselines.Target.ReferencePack; - var xml = Path.Combine( - PackageDependencyProbe.GlobalPackagesFolder, - "tizen.net.api15", - pack.Version.ToLowerInvariant(), - "ref", - "net8.0", - "Tizen.Security.SecureRepository.xml"); - Assert.True(File.Exists(xml), $"Missing API15 documentation file '{xml}'."); - var documentation = File.ReadAllText(xml); - - Assert.Contains( - """""", - documentation, - StringComparison.Ordinal); - Assert.Contains( - """Thrown when there's no alias to get.""", - documentation, - StringComparison.Ordinal); + var dataManager = ReferencePackProbe.ReadTypeMembers( + assembly!, + "Tizen.Security.SecureRepository.DataManager"); + Assert.NotNull(dataManager); + Assert.True(dataManager!.HasMethod("GetAliases")); } } diff --git a/tests/Maui.Tizen.Conventions.Tests/Maui.Tizen.Conventions.Tests.csproj b/tests/Maui.Tizen.Conventions.Tests/Maui.Tizen.Conventions.Tests.csproj index 784b2e71..3d4aebff 100644 --- a/tests/Maui.Tizen.Conventions.Tests/Maui.Tizen.Conventions.Tests.csproj +++ b/tests/Maui.Tizen.Conventions.Tests/Maui.Tizen.Conventions.Tests.csproj @@ -14,8 +14,6 @@ the EXPECTED key sets can be read on a hosted runner; only the Tizen side needs a device. --> - - From 8d40456264afc715cc003b11e5840ec0088c53a0 Mon Sep 17 00:00:00 2001 From: redth Date: Sat, 29 Aug 2026 18:52:43 -0400 Subject: [PATCH 21/21] Bind native events to subscription generations Give each clipboard native relay its exact DataSelected delegate and move device display state updates behind generation-validated commits. Add retained-callback tests and locked mutations while preserving secure storage and external release gates. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7a37339a-ace9-487d-b025-3262b9d414d9 --- docs/migration.md | 4 +- docs/net11-status.md | 4 +- docs/tizen-essentials-service-coverage.md | 6 +- eng/build-workload-free.sh | 2 +- eng/tests/essentials-mutations.json | 41 +++++++-- .../Battery/TizenBattery.cs | 4 +- .../Clipboard/TizenClipboard.cs | 37 ++++---- .../Connectivity/TizenConnectivity.cs | 4 +- .../DeviceDisplay/TizenDeviceDisplay.cs | 88 ++++++++++++------- .../TizenEventSubscriptionCoordinator.cs | 65 ++++++++++---- .../TizenClipboardCoordinatorTests.cs | 40 ++++++++- .../TizenDeviceDisplayGenerationTests.cs | 85 ++++++++++++++++++ .../TizenEventSubscriptionCoordinatorTests.cs | 45 ++++++---- .../EssentialsSourceClosureTests.cs | 24 +++++ 14 files changed, 344 insertions(+), 105 deletions(-) create mode 100644 tests/Maui.Tizen.Essentials.Tests/TizenDeviceDisplayGenerationTests.cs diff --git a/docs/migration.md b/docs/migration.md index a0f13017..2fabba7d 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -53,8 +53,8 @@ The lane in `eng/build-workload-free.sh` (required in CI) genuinely exercises: - migration tooling, package graph, consumer compile and repository invariant suites - integrity of the imported history and the import tooling -At this integration head the principal executable inventories are 1,248 Core/Waves tests, 447 -Essentials tests in both Debug and Release, and 578 source/closure/parity tests. The canonical +At this integration head the principal executable inventories are 1,248 Core/Waves tests, 449 +Essentials tests in both Debug and Release, and 579 source/closure/parity tests. The canonical script also executes the repository, tooling, negative-control and hosted suites rather than inferring their result from a successful build. diff --git a/docs/net11-status.md b/docs/net11-status.md index 2bad2a6a..5777e265 100644 --- a/docs/net11-status.md +++ b/docs/net11-status.md @@ -48,8 +48,8 @@ identical, so neither can drift from the other. | Lane | Command | What it proves | | --- | --- | --- | | Core/Waves tests | `dotnet test tests/Maui.Tizen.Core.UnitTests` | Mapper + command-mapper registration, concrete Controls startup, DI/handler registration, hosting, dispatcher/timer/provider semantics, density/layout, Wave A/B/C lifetimes and navigation. **1,248 tests at this head, all passing.** | -| Source/closure tests | `dotnet test tests/Maui.Tizen.SourceTests` | Source ownership, mapper parity, startup and package closures, compile-backed MAUI API blockers. **578 tests at this head, all passing.** | -| Essentials tests | execute `artifacts/bin/Maui.Tizen.Essentials.Tests//net11.0/Maui.Tizen.Essentials.Tests` | DI facade bridge, native-faithful Preferences/SecureStorage, Clipboard/TTS/sensor/screenshot/AppControl lifecycle coordinators, permissions and translation behavior. **447 tests pass in Debug and Release.** | +| Source/closure tests | `dotnet test tests/Maui.Tizen.SourceTests` | Source ownership, mapper parity, startup and package closures, compile-backed MAUI API blockers. **579 tests at this head, all passing.** | +| Essentials tests | execute `artifacts/bin/Maui.Tizen.Essentials.Tests//net11.0/Maui.Tizen.Essentials.Tests` | DI facade bridge, native-faithful Preferences/SecureStorage, Clipboard/TTS/sensor/screenshot/AppControl lifecycle coordinators, permissions and translation behavior. **449 tests pass in Debug and Release.** | | Compile validation | build the four `*.RefPackCompile`/consumer projects | Core, Controls, Sample and Essentials shipping sources type-check against the **real** TizenFX reference assemblies from `Samsung.Tizen.Ref.API15` (`ref/net8.0`), with package-specific PublicAPI analyzers. **All build cleanly.** | | Product | `dotnet build src/Maui.Tizen.Core` | Fails with actionable `MAUITIZEN0001` from `Directory.Build.targets`. This is the intended behaviour. | diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md index 8bcd9a20..a50ae458 100644 --- a/docs/tizen-essentials-service-coverage.md +++ b/docs/tizen-essentials-service-coverage.md @@ -42,7 +42,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `ICompass` | `TizenCompass` | Implemented | All | Azimuth from `Tizen.Sensor.OrientationSensor`. `applyLowPassFilter` has no extra effect (Tizen already fuses and filters). | | `IConnectivity` | `TizenConnectivity` | Implemented | All | `Tizen.Network.Connection`. `ConnectionProfiles` is queried synchronously per read. Event subscription is transactional and generation-scoped so partial startup and stale queued callbacks cannot leak into replacement subscribers. Requires `network.get` + `internet`. | | `IContacts` | `TizenContacts` | Implemented | Mobile | `Tizen.Pims.Contacts`. `GetAllAsync` requests runtime `contact.read` consent and materialises the result before disposing the native cursor. | -| `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | +| `IDeviceDisplay` | `TizenDeviceDisplay` | Implemented | All | Screen metrics from feature keys; generation validation atomically commits orientation state and its event so retained old native callbacks cannot mutate replacement state. `KeepScreenOn` uses `device_power_request_lock` and requires the `display` privilege. | | `IDeviceInfo` | `TizenDeviceInfo` | Implemented | All | System / feature information keys. | | `IEmail` | `TizenEmail` | Implemented | Mobile | Tizen `compose` AppControl, including enumerable attachment paths and a compatible MIME filter. Gated on the `email` feature key. | | `IFilePicker` | `TizenFilePicker` | Blocked | All | Tizen's `pick` operation and MIME filtering work, but pinned MAUI `FileResult` has no public path-open override. Standard `OpenReadAsync` and direct `ShareFile(FileBase)` / `EmailAttachment(FileBase)` / `OpenFileRequest(FileBase)` flows fail in the neutral package. Explicit path+MIME reconstruction works but is not a compatible replacement. See validation blocker 9. | @@ -62,7 +62,7 @@ Profile column values are the Tizen device profiles on which the service is usab | `IPhoneDialer` | `TizenPhoneDialer` | Implemented | Mobile | `tel:` AppControl, gated on the `contact` feature key. | | `IPreferences` | `TizenPreferences` | Implemented | All | `Tizen.Applications.Preference`; shared names are emulated with an **escaped** `{sharedName}~{key}` prefix so distinct stores cannot collide. Default-store keys stay unprefixed for compatibility. | | `IScreenshot` | `TizenScreenshot` | Implemented | All | `Tizen.NUI.Capture` plus `Tizen.Multimedia.Util` encoders. One atomic terminal arbitrates Finished/timeout/cancellation/disposal; all NUI work and cleanup stays on the dispatcher, zero stride means tightly packed, and padded rows are copied without padding. Also implements `IViewScreenshot`. | -| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. Deletion intent is tombstoned before native removal, so undeleted current/staged/v1/v2 aliases remain unreadable after a fault; unexpected enumeration/deletion failures are surfaced. A later committed Set explicitly supersedes the tombstone. | +| `ISecureStorage` | `TizenSecureStorage` | Implemented | All | Tizen key manager. API15's documented parameterless `ArgumentException` for “no aliases” is normalized to empty; parameter-bearing and non-argument repository failures propagate. Deletion intent is tombstoned before native removal, so undeleted current/staged/v1/v2 aliases remain unreadable after a fault. | | `ISemanticScreenReader` | `TizenSemanticScreenReader` | Implemented | All | `Tizen.NUI.Accessibility`. | | `IShare` | `TizenShare` | Implemented | All | `share_text`, `share`, and `multi_share` AppControls; file paths are sent as one enumerable payload with a compatible MIME filter. | | `ISms` | `TizenSms` | Implemented | Mobile | `sms:` compose AppControl, gated on `network.telephony.sms`. | @@ -79,7 +79,7 @@ Profile column values are the Tizen device profiles on which the service is usab | Sources type-check against the **API15 reference pack** the product targets | Verified, by `tests/Maui.Tizen.Essentials.RefPackCompile` | | The declared public API surface matches `PublicAPI/slice/PublicAPI.Unshipped.txt` | Verified, by the PublicAPI analyzer in that same lane | | Sources compile against loadable Tizen implementation assemblies | Verified, by `src/Maui.Tizen.Essentials.HostVerification` | -| DI registration, facade/`MainThread` ownership, native-faithful storage, callback/lifecycle coordinators, permission privilege mapping, unsupported classification, and ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (447 tests) | +| DI registration, facade/`MainThread` ownership, native-faithful storage, callback/lifecycle coordinators, permission privilege mapping, unsupported classification, and ported translation logic | Verified, by `tests/Maui.Tizen.Essentials.Tests` (449 tests) | | `src/Maui.Tizen.Essentials` builds for `net11.0-tizen11.0` | **Blocked.** Fails with `MAUITIZEN0001`: the Samsung workload manifest `samsung.net.sdk.tizen.manifest-11.0.100` is unpublished. Nobody can build this TFM anywhere yet. | | Any behaviour that P/Invokes into Tizen (sensors, AppControl, key manager, NUI capture, TTS, geocoding, ...) | **Blocked.** Requires a Tizen device or emulator, which in turn requires the workload. | diff --git a/eng/build-workload-free.sh b/eng/build-workload-free.sh index 2ec0b86c..96f7296a 100755 --- a/eng/build-workload-free.sh +++ b/eng/build-workload-free.sh @@ -266,7 +266,7 @@ if [[ $BUILD_OK -eq 1 ]]; then # runner, because console rendering is not a stable contract. A report file is. # # Raise this when adding tests; never lower it to make a run go green. - ESSENTIALS_TESTS_MINIMUM=447 + ESSENTIALS_TESTS_MINIMUM=449 check "essentials tests" "$ESSENTIALS_TESTS" \ --report-xunit-junit --report-xunit-junit-filename results.xml \ diff --git a/eng/tests/essentials-mutations.json b/eng/tests/essentials-mutations.json index 6e9df3c9..df6aecbb 100644 --- a/eng/tests/essentials-mutations.json +++ b/eng/tests/essentials-mutations.json @@ -406,12 +406,12 @@ "expected": "StaleQueuedEventNeverReachesReplacementSubscriber", "replacements": [ { - "search": "_generation == generation &&\n\t\t\t\t\t\t\t_handlers is not null", - "replace": "_generation >= generation &&\n\t\t\t\t\t\t\t_handlers is not null" + "search": "return !_disposed && _generation == generation && _handlers is not null;", + "replace": "return !_disposed && _generation >= generation && _handlers is not null;" }, { - "search": "handlers = _generation == generation ? _handlers : null;", - "replace": "handlers = _generation >= generation ? _handlers : null;" + "search": "if (_disposed || _generation != generation || _handlers is null)\n\t\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\targs = createArgs();", + "replace": "if (_disposed || _generation < generation || _handlers is null)\n\t\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\targs = createArgs();" } ] }, @@ -537,15 +537,42 @@ ] }, { - "id": "event-native-delegate-relabeled-to-current-generation", + "id": "event-publisher-drops-captured-generation", "file": "src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs", "project": "tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj", "filter": "FullyQualifiedName~StaleQueuedEventNeverReachesReplacementSubscriber", "expected": "StaleQueuedEventNeverReachesReplacementSubscriber", "replacements": [ { - "search": "unsubscribe = _start(args => Publish(generation, args));", - "replace": "unsubscribe = _start(args => Publish(_generation, args));" + "search": "_owner.Publish(_generation, args);", + "replace": "_owner.Publish(_generation + 1, args);" + } + ] + }, + { + "id": "clipboard-native-relay-uses-mutable-current-handler", + "file": "src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs", + "project": "tests/Maui.Tizen.SourceTests/Maui.Tizen.SourceTests.csproj", + "mode": "source", + "filter": "FullyQualifiedName~ClipboardNativeRelayUsesTheExactGenerationHandler", + "expected": "ClipboardNativeRelayUsesTheExactGenerationHandler", + "replacements": [ + { + "search": "dataSelectedHandler = (_, _) => changed();", + "replace": "dataSelectedHandler = OnDataSelected;" + } + ] + }, + { + "id": "device-display-mutates-state-before-generation-commit", + "file": "src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs", + "project": "tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj", + "filter": "FullyQualifiedName~RetainedAndQueuedOldNativeCallbacksCannotMutateReplacementState", + "expected": "RetainedAndQueuedOldNativeCallbacksCannotMutateReplacementState", + "replacements": [ + { + "search": "generation.Commit(() =>\n\t\t\t\t{\n\t\t\t\t\tvar metrics = _native.GetMetrics();\n\t\t\t\t\tvar natural = GetNaturalOrientation(metrics.Width, metrics.Height);\n\t\t\t\t\t(_displayRotation, _displayOrientation) = MapOrientation(deviceOrientation, natural);\n\t\t\t\t\treturn new DisplayInfoChangedEventArgs(MainDisplayInfo);\n\t\t\t\t});", + "replace": "var metrics = _native.GetMetrics();\n\t\t\t\tvar natural = GetNaturalOrientation(metrics.Width, metrics.Height);\n\t\t\t\t(_displayRotation, _displayOrientation) = MapOrientation(deviceOrientation, natural);\n\t\t\t\tgeneration.Publish(new DisplayInfoChangedEventArgs(MainDisplayInfo));" } ] } diff --git a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs index 8b6a02a3..965f0493 100644 --- a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs +++ b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs @@ -90,14 +90,14 @@ public event EventHandler EnergySaverStatusCh remove => throw TizenEssentialsSupport.NotSupported($"{nameof(IBattery)}.{nameof(EnergySaverStatusChanged)}", EnergySaverReason); } - Action StartListeners(Action publish) + Action StartListeners(TizenEventGeneration generation) { var percent = false; var charging = false; void OnChanged(object? sender, object e) { var args = new BatteryInfoChangedEventArgs(ChargeLevel, State, PowerSource); - publish(args); + generation.Publish(args); } try diff --git a/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs index 3ac22847..4a1fafeb 100644 --- a/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs +++ b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs @@ -38,9 +38,9 @@ internal TizenClipboard( _native = native; _events = new( this, - publish => + generation => { - Action nativeCallback = () => publish(EventArgs.Empty); + Action nativeCallback = () => generation.Publish(EventArgs.Empty); _dispatcher.Invoke(() => _native.StartChangeNotifications(nativeCallback)); return () => _dispatcher.Invoke(_native.StopChangeNotifications); }, @@ -231,7 +231,7 @@ sealed class TizenClipboardNative : ITizenClipboardNative global::Tizen.NUI.Clipboard? _clipboard; global::Tizen.NUI.WindowSystem.Shell.TizenShell? _shell; global::Tizen.NUI.WindowSystem.Shell.KVMService? _kvm; - Action? _changed; + EventHandler? _dataSelectedHandler; public static TizenClipboardNative Instance { get; } = new(); @@ -249,6 +249,7 @@ public void StartChangeNotifications(Action changed) global::Tizen.NUI.WindowSystem.Shell.TizenShell? shell = null; global::Tizen.NUI.WindowSystem.Shell.KVMService? kvm = null; + EventHandler? dataSelectedHandler = null; var selected = false; var subscribed = false; try @@ -259,19 +260,20 @@ public void StartChangeNotifications(Action changed) global::Tizen.NUI.Window.Default); kvm.SetSecondarySelection(); selected = true; - Clipboard.DataSelected += OnDataSelected; + dataSelectedHandler = (_, _) => changed(); + Clipboard.DataSelected += dataSelectedHandler; subscribed = true; _shell = shell; _kvm = kvm; - _changed = changed; + _dataSelectedHandler = dataSelectedHandler; } catch { - if (subscribed) + if (subscribed && dataSelectedHandler is not null) { try { - Clipboard.DataSelected -= OnDataSelected; + Clipboard.DataSelected -= dataSelectedHandler; } catch (Exception) { @@ -307,17 +309,20 @@ public void StartChangeNotifications(Action changed) public void StopChangeNotifications() { - if (_kvm is null && _changed is null) + if (_kvm is null && _dataSelectedHandler is null) return; var failures = new List(); - try + if (_dataSelectedHandler is not null) { - Clipboard.DataSelected -= OnDataSelected; - } - catch (Exception exception) - { - failures.Add(exception); + try + { + Clipboard.DataSelected -= _dataSelectedHandler; + } + catch (Exception exception) + { + failures.Add(exception); + } } try @@ -347,7 +352,7 @@ public void StopChangeNotifications() failures.Add(exception); } - _changed = null; + _dataSelectedHandler = null; _kvm = null; _shell = null; @@ -364,7 +369,5 @@ public void GetText(Action callback) => MimeType, (success, clipEvent) => callback(success, success ? clipEvent.Data : null)); - void OnDataSelected(object? sender, global::Tizen.NUI.ClipboardDataSelectedEventArgs e) => - _changed?.Invoke(); } } diff --git a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs index 8fa4faeb..60c7fd83 100644 --- a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs +++ b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs @@ -131,7 +131,7 @@ public event EventHandler ConnectivityChanged remove => _events.Remove(value); } - Action StartListeners(Action publish) + Action StartListeners(TizenEventGeneration generation) { TizenPermissions.EnsureDeclared(); @@ -140,7 +140,7 @@ Action StartListeners(Action publish) var args = new ConnectivityChangedEventArgs( GetNetworkAccess(static () => TizenConnectionManager.CurrentConnection.Type), GetConnectionProfiles()); - publish(args); + generation.Publish(args); }; StartTransactional( diff --git a/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs index f6842720..c12872c4 100644 --- a/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs +++ b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs @@ -31,25 +31,22 @@ public sealed partial class TizenDeviceDisplay : IDeviceDisplay, IDisposable const int PowerLockDisplay = 1; readonly TizenEventSubscriptionCoordinator _events; + readonly ITizenDeviceDisplayNative _native; bool _keepScreenOn; DisplayRotation _displayRotation = DisplayRotation.Rotation0; DisplayOrientation _displayOrientation = DisplayOrientation.Unknown; - static TizenCoreApplication? CoreApplication => TizenApplication.Current as TizenCoreApplication; - - static int DisplayWidth => TizenSystemInformation.GetFeatureInfo("screen.width"); - - static int DisplayHeight => TizenSystemInformation.GetFeatureInfo("screen.height"); - - static int DisplayDpi => - TizenSystemInformation.CurrentProfile == TizenDeviceProfile.TV - ? 72 - : TizenSystemInformation.GetFeatureInfo("screen.dpi"); - /// Creates the Tizen display service. - public TizenDeviceDisplay() + public TizenDeviceDisplay() : this(TizenDeviceDisplayNative.Instance) { - _events = new(this, StartListeners); + } + + internal TizenDeviceDisplay( + ITizenDeviceDisplayNative native, + TizenNativeCallbackCoordinator? callbacks = null) + { + _native = native; + _events = new(this, StartListeners, callbacks); } /// @@ -78,15 +75,14 @@ public DisplayInfo MainDisplayInfo { get { - var width = DisplayWidth; - var height = DisplayHeight; + var metrics = _native.GetMetrics(); return new DisplayInfo( - width: width, - height: height, - density: DisplayDpi / BaseLogicalDpi, + width: metrics.Width, + height: metrics.Height, + density: metrics.Dpi / BaseLogicalDpi, orientation: _displayOrientation == DisplayOrientation.Unknown - ? GetNaturalOrientation(width, height) + ? GetNaturalOrientation(metrics.Width, metrics.Height) : _displayOrientation, rotation: _displayRotation); } @@ -99,19 +95,18 @@ public event EventHandler MainDisplayInfoChanged remove => _events.Remove(value); } - Action StartListeners(Action publish) + Action StartListeners(TizenEventGeneration generation) { - if (CoreApplication is not { } app) - return static () => { }; - - EventHandler handler = (_, e) => + return _native.Subscribe(deviceOrientation => { - var natural = GetNaturalOrientation(DisplayWidth, DisplayHeight); - (_displayRotation, _displayOrientation) = MapOrientation(e.DeviceOrientation, natural); - publish(new DisplayInfoChangedEventArgs(MainDisplayInfo)); - }; - app.DeviceOrientationChanged += handler; - return () => app.DeviceOrientationChanged -= handler; + generation.Commit(() => + { + var metrics = _native.GetMetrics(); + var natural = GetNaturalOrientation(metrics.Width, metrics.Height); + (_displayRotation, _displayOrientation) = MapOrientation(deviceOrientation, natural); + return new DisplayInfoChangedEventArgs(MainDisplayInfo); + }); + }); } static DisplayOrientation GetNaturalOrientation(int width, int height) => @@ -138,4 +133,37 @@ internal static (DisplayRotation Rotation, DisplayOrientation Orientation) MapOr /// public void Dispose() => _events.Dispose(); } + + internal readonly record struct TizenDisplayMetrics(int Width, int Height, int Dpi); + + internal interface ITizenDeviceDisplayNative + { + TizenDisplayMetrics GetMetrics(); + + Action Subscribe(Action callback); + } + + sealed class TizenDeviceDisplayNative : ITizenDeviceDisplayNative + { + public static TizenDeviceDisplayNative Instance { get; } = new(); + + public TizenDisplayMetrics GetMetrics() => + new( + TizenSystemInformation.GetFeatureInfo("screen.width"), + TizenSystemInformation.GetFeatureInfo("screen.height"), + TizenSystemInformation.CurrentProfile == TizenDeviceProfile.TV + ? 72 + : TizenSystemInformation.GetFeatureInfo("screen.dpi")); + + public Action Subscribe(Action callback) + { + if (TizenApplication.Current is not TizenCoreApplication app) + return static () => { }; + + EventHandler handler = + (_, e) => callback(e.DeviceOrientation); + app.DeviceOrientationChanged += handler; + return () => app.DeviceOrientationChanged -= handler; + } + } } diff --git a/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs b/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs index 23d9e81b..d1d0e782 100644 --- a/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs +++ b/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs @@ -8,7 +8,7 @@ internal sealed class TizenEventSubscriptionCoordinator : IDisposabl readonly object _stateLock = new(); readonly object _transitionLock = new(); readonly object _sender; - readonly Func, Action> _start; + readonly Func, Action> _start; readonly TizenNativeCallbackCoordinator _callbacks; EventHandler? _handlers; Action? _unsubscribe; @@ -17,7 +17,7 @@ internal sealed class TizenEventSubscriptionCoordinator : IDisposabl public TizenEventSubscriptionCoordinator( object sender, - Func, Action> start, + Func, Action> start, TizenNativeCallbackCoordinator? callbacks = null) { _sender = sender; @@ -49,7 +49,7 @@ public void Add(EventHandler? handler) { // This delegate is unique to this subscription generation. A native source that // retains it after unsubscribe cannot be relabelled as a later generation. - unsubscribe = _start(args => Publish(generation, args)); + unsubscribe = _start(new(this, generation)); lock (_stateLock) { if (_disposed || _generation != generation || _handlers is null) @@ -103,33 +103,39 @@ public void Remove(EventHandler? handler) } } - public void Publish(long generation, TEventArgs args) + internal void Publish(long generation, TEventArgs args) => + Commit(generation, () => args); + + internal void Commit(long generation, Func createArgs) { - lock (_stateLock) - { - if (_disposed || _generation != generation || _handlers is null) - return; - } + ArgumentNullException.ThrowIfNull(createArgs); + if (!IsCurrent(generation)) + return; _callbacks.Post( + () => IsCurrent(generation), () => { + EventHandler? handlers; + TEventArgs args; lock (_stateLock) { - return !_disposed && - _generation == generation && - _handlers is not null; + if (_disposed || _generation != generation || _handlers is null) + return; + + args = createArgs(); + handlers = _handlers; } - }, - () => - { - EventHandler? handlers; - lock (_stateLock) - handlers = _generation == generation ? _handlers : null; - handlers?.Invoke(_sender, args); + handlers.Invoke(_sender, args); }); } + bool IsCurrent(long generation) + { + lock (_stateLock) + return !_disposed && _generation == generation && _handlers is not null; + } + public void Dispose() { lock (_transitionLock) @@ -151,4 +157,25 @@ public void Dispose() } } } + + internal readonly struct TizenEventGeneration + where TEventArgs : EventArgs + { + readonly TizenEventSubscriptionCoordinator _owner; + readonly long _generation; + + public TizenEventGeneration( + TizenEventSubscriptionCoordinator owner, + long generation) + { + _owner = owner; + _generation = generation; + } + + public void Publish(TEventArgs args) => + _owner.Publish(_generation, args); + + public void Commit(Func createArgs) => + _owner.Commit(_generation, createArgs); + } } diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs index 8b25c679..8f5da69f 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs @@ -180,6 +180,33 @@ public async Task QueuedOldNotificationDoesNotReachReplacementSubscriber() Assert.Equal(0, replacementCalls); } + [Fact] + public async Task RetainedOldNativeEventDelegateCannotReachReplacementSubscriber() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + var oldCalls = 0; + var replacementCalls = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler old = (_, _) => oldCalls++; + EventHandler replacement = (_, _) => replacementCalls.TrySetResult(); + + clipboard.ClipboardContentChanged += old; + var oldNative = Assert.Single(native.RetainedDataSelectedHandlers); + clipboard.ClipboardContentChanged -= old; + clipboard.ClipboardContentChanged += replacement; + Assert.NotSame(oldNative, native.CurrentDataSelectedHandler); + + await native.RaiseRetainedAsync(0); + await Task.Delay(25, TestContext.Current.CancellationToken); + Assert.Equal(0, oldCalls); + Assert.False(replacementCalls.Task.IsCompleted); + + await native.RaiseChangedAsync(); + await replacementCalls.Task.WaitAsync(TestContext.Current.CancellationToken); + } + sealed class StrictDispatcher : ITizenClipboardDispatcher, IDisposable { readonly BlockingCollection _work = []; @@ -330,6 +357,10 @@ public FakeClipboardNative(StrictDispatcher dispatcher) public int ChangeSubscriberCount => _dataSelected?.GetInvocationList().Length ?? 0; + public List RetainedDataSelectedHandlers { get; } = []; + + public Action? CurrentDataSelectedHandler => _dataSelected; + public int StartNotificationsCalls { get; private set; } public int StopNotificationsCalls { get; private set; } @@ -342,9 +373,11 @@ public void StartChangeNotifications(Action changed) { AssertThread("start notifications"); StartNotificationsCalls++; - _dataSelected = changed; + Action dataSelected = () => changed(); + _dataSelected = dataSelected; + RetainedDataSelectedHandlers.Add(dataSelected); if (RaiseOnStart) - changed(); + dataSelected(); if (FailStartNotifications) { _dataSelected = null; @@ -383,6 +416,9 @@ public Task CompleteReadAsync(bool success, string? text) => public Task RaiseChangedAsync() => _dispatcher.InvokeAsync(() => _dataSelected?.Invoke()); + public Task RaiseRetainedAsync(int index) => + _dispatcher.InvokeAsync(() => RetainedDataSelectedHandlers[index]()); + void AssertThread(string operation) { if (Thread.CurrentThread.ManagedThreadId != _dispatcher.ThreadId) diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenDeviceDisplayGenerationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenDeviceDisplayGenerationTests.cs new file mode 100644 index 00000000..6bb99693 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenDeviceDisplayGenerationTests.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using Microsoft.Maui.Devices; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; +using TizenDeviceOrientation = Tizen.Applications.DeviceOrientation; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenDeviceDisplayGenerationTests +{ + [Fact] + public void RetainedAndQueuedOldNativeCallbacksCannotMutateReplacementState() + { + var dispatcher = new ManualCallbackDispatcher(); + var native = new FakeDeviceDisplayNative(); + using var display = new TizenDeviceDisplay( + native, + new TizenNativeCallbackCoordinator(dispatcher)); + var firstCalls = 0; + var replacementCalls = 0; + EventHandler first = (_, _) => firstCalls++; + EventHandler replacement = (_, _) => replacementCalls++; + + display.MainDisplayInfoChanged += first; + var oldNative = Assert.Single(native.RetainedCallbacks); + oldNative(TizenDeviceOrientation.Orientation_90); + + display.MainDisplayInfoChanged -= first; + display.MainDisplayInfoChanged += replacement; + var currentNative = native.CurrentCallback; + Assert.NotNull(currentNative); + Assert.NotSame(oldNative, currentNative); + + // Retained callback after replacement is rejected immediately. The callback queued before + // replacement is rejected again when the deferred dispatcher action executes. + oldNative(TizenDeviceOrientation.Orientation_180); + dispatcher.RunAll(); + + Assert.Equal(0, firstCalls); + Assert.Equal(0, replacementCalls); + Assert.Equal(DisplayRotation.Rotation0, display.MainDisplayInfo.Rotation); + Assert.Equal(DisplayOrientation.Portrait, display.MainDisplayInfo.Orientation); + + currentNative!(TizenDeviceOrientation.Orientation_90); + dispatcher.RunAll(); + + Assert.Equal(1, replacementCalls); + Assert.Equal(DisplayRotation.Rotation90, display.MainDisplayInfo.Rotation); + Assert.Equal(DisplayOrientation.Landscape, display.MainDisplayInfo.Orientation); + } + + sealed class ManualCallbackDispatcher : ITizenNativeCallbackDispatcher + { + readonly Queue _work = []; + + public void PostDeferred(Action action) => _work.Enqueue(action); + + public void RunAll() + { + while (_work.TryDequeue(out var action)) + action(); + } + } + + sealed class FakeDeviceDisplayNative : ITizenDeviceDisplayNative + { + public List> RetainedCallbacks { get; } = []; + + public Action? CurrentCallback { get; private set; } + + public TizenDisplayMetrics GetMetrics() => new(100, 200, 160); + + public Action Subscribe(Action callback) + { + CurrentCallback = callback; + RetainedCallbacks.Add(callback); + return () => + { + if (ReferenceEquals(CurrentCallback, callback)) + CurrentCallback = null; + }; + } + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs index f7de146a..f544f38f 100644 --- a/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs +++ b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs @@ -17,9 +17,9 @@ public void NativeStartRunsWithoutHoldingTheStateLock() var started = false; coordinator = new( this, - publish => + generation => { - publish(EventArgs.Empty); + generation.Publish(EventArgs.Empty); started = true; return static () => { }; }, @@ -36,8 +36,8 @@ public async Task StaleQueuedEventNeverReachesReplacementSubscriber() using var dispatcher = new StrictCallbackDispatcher(blockFirst: true); var oldCalls = 0; var replacementCalls = 0; - Action? currentNative = null; - var retained = new List>(); + Action? currentNative = null; + var retained = new List(); EventHandler old = (_, _) => oldCalls++; var replacementDelivered = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously); @@ -48,30 +48,39 @@ public async Task StaleQueuedEventNeverReachesReplacementSubscriber() }; var coordinator = new TizenEventSubscriptionCoordinator( this, - publish => + generation => { - currentNative = publish; - retained.Add(publish); - return () => currentNative = null; + Action native = () => generation.Publish(EventArgs.Empty); + currentNative = native; + retained.Add(native); + return () => + { + if (ReferenceEquals(currentNative, native)) + currentNative = null; + }; }, new TizenNativeCallbackCoordinator(dispatcher)); coordinator.Add(old); var oldNative = Assert.Single(retained); - oldNative(EventArgs.Empty); - await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + oldNative(); + await dispatcher.Queued.Task.WaitAsync( + TimeSpan.FromMilliseconds(250), + TestContext.Current.CancellationToken); coordinator.Remove(old); coordinator.Add(replacement); Assert.NotSame(oldNative, currentNative); - oldNative(EventArgs.Empty); + oldNative(); dispatcher.Release(); await dispatcher.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); Assert.Equal(0, oldCalls); Assert.Equal(0, replacementCalls); - currentNative!(EventArgs.Empty); - await replacementDelivered.Task.WaitAsync(TestContext.Current.CancellationToken); + currentNative!(); + await replacementDelivered.Task.WaitAsync( + TimeSpan.FromMilliseconds(250), + TestContext.Current.CancellationToken); Assert.Equal(1, replacementCalls); } @@ -83,7 +92,7 @@ public void FailedFirstSubscriptionRollsBackAndCanBeRetried() var fail = true; var coordinator = new TizenEventSubscriptionCoordinator( this, - publish => + generation => { try { @@ -115,19 +124,19 @@ public async Task DisposeInvalidatesAQueuedEventAndStopsNativeListening() using var dispatcher = new StrictCallbackDispatcher(blockFirst: true); var native = false; var calls = 0; - Action? nativeCallback = null; + Action? nativeCallback = null; var coordinator = new TizenEventSubscriptionCoordinator( this, - publish => + generation => { native = true; - nativeCallback = publish; + nativeCallback = () => generation.Publish(EventArgs.Empty); return () => native = false; }, new TizenNativeCallbackCoordinator(dispatcher)); coordinator.Add((_, _) => calls++); coordinator.Add((_, _) => calls++); - nativeCallback!(EventArgs.Empty); + nativeCallback!(); await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); coordinator.Dispose(); dispatcher.Release(); diff --git a/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs b/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs index 6b76a736..07fed4c9 100644 --- a/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs +++ b/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs @@ -110,6 +110,30 @@ public void EssentialsRegistrationReplacesRatherThanShadowsPlatformServices() StringComparison.Ordinal); } + [Fact] + public void ClipboardNativeRelayUsesTheExactGenerationHandler() + { + var source = File.ReadAllText(RepoPaths.Combine( + "src", + "Maui.Tizen.Essentials", + "Clipboard", + "TizenClipboard.cs")); + + Assert.DoesNotContain("Action? _changed", source, StringComparison.Ordinal); + Assert.Contains( + "dataSelectedHandler = (_, _) => changed();", + source, + StringComparison.Ordinal); + Assert.Contains( + "Clipboard.DataSelected += dataSelectedHandler;", + source, + StringComparison.Ordinal); + Assert.Contains( + "Clipboard.DataSelected -= _dataSelectedHandler;", + source, + StringComparison.Ordinal); + } + [Fact] public void MigrationDocumentationRecordsMergedHandlersAndImplementedEssentials() {