diff --git a/Directory.Packages.props b/Directory.Packages.props index 149d7fba..a2a8d491 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -64,6 +64,15 @@ API surface change is expected from that republish. --> + + + @@ -87,6 +96,11 @@ + + + + + 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 d68def0d..5777e265 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. **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. | Both lanes are wired into `eng/build-workload-free.sh`, so they run in the workload-free CI lane @@ -58,6 +63,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. + --- ### G11. The public `IImageSourcePaint` contract has not shipped yet diff --git a/docs/tizen-essentials-service-coverage.md b/docs/tizen-essentials-service-coverage.md new file mode 100644 index 00000000..a50ae458 --- /dev/null +++ b/docs/tizen-essentials-service-coverage.md @@ -0,0 +1,154 @@ +# 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**. + +Registration is the whole integration surface: the production +`UseMauiAppTizenControls()` path calls `AddTizenEssentials(MauiAppBuilder)`, which replaces +MAUI's neutral defaults with every Tizen service below. Applications can replace an individual +service after configuring the backend. .NET 11 MAUI bridges those DI registrations onto the +static Essentials facades during `MauiApp` initialization (dotnet/maui#36657, first available +publicly in `11.0.0-preview.7.26418.3`). This package therefore performs no `SetDefault` +reflection, and ships no `MainThread` platform hook: main-thread marshalling is bridged from the +registered `IDispatcher`. + +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. | +| `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. + +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`. Shared native sensor lifetime is ref-counted across wrappers; generation checks reject stale callbacks. Shake detection purges every expired sample, requires four current samples, and uses the exact 75% threshold. | +| `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 | 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` | Partial | All | `GetTextAsync` and `SetTextAsync` use public `Tizen.NUI.Clipboard` on the MAUI dispatcher. First/last change subscribers own a dispatcher-bound API15 `KVMService` secondary-selection lifetime, and generation checks reject stale queued events. Synchronous `HasText` throws because API15 exposes reads only through an asynchronous callback. | +| `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; 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. | +| `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. `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. | +| `IMagnetometer` | `TizenMagnetometer` | Implemented | All | `Tizen.Sensor.Magnetometer`. | +| `IMap` | `TizenMap` | Partial | All | `geo:` AppControl. `MapLaunchOptions.NavigationMode` and the launch name cannot be honoured. | +| `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` | 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. Runtime requests are bounded, exactly once, unsubscribed on every terminal path, and accept only `Answer` for the matching privilege. `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. | +| `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. 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`. | +| `ITextToSpeech` | `TizenTextToSpeech` | Partial | All | Speech works; Min/Normal/Max speed is cached in Created before Prepare, and MAUI's 0.1–2.0 rate is mapped piecewise around Normal. Every native operation is serialized on the Ecore/main loop; cancellation/error retires the generation before posted teardown. `GetLocalesAsync` remains blocked by MAUI's closed `Locale` constructor. | +| `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. | + + + +## What is verified, and what is not + +| | 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/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` (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. | + +The two verification lanes are complementary. `RefPackCompile` type-checks against +`Samsung.Tizen.Ref.API15`, the exact surface `net11.0-tizen11.0` will bind to, but reference +assemblies have no method bodies and can never be executed. `HostVerification` compiles against +the Tizen.NET implementation assemblies, which can be loaded, which is what lets the tests run. +Neither packs or publishes anything, so neither can be mistaken for a shippable neutral build. + +That split earns its keep: the API15 lane is what caught the removal of `Tizen.Maps`. The +implementation-assembly lane alone (Tizen.NET, API13) still compiles the old geocoding code +happily, and would have shipped an implementation binding to an assembly the target platform no +longer has. + +The blocked rows are gates, not gaps in this work, and they are reported rather than papered +over. + +## 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. | + +## 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 | +| --- | --- | --- | +| `Tizen.Maps` / `MapService` | **Removed** (deprecated API11, gone by API15) | Geocoding has no implementation. Reclassified `Unsupported`; see the matrix above. | +| `Tizen.Security.PrivacyPrivilegeManager` | Deprecated at API11, still present at API15 | Runtime privilege checks still work. Tizen ships no replacement, so this backend keeps using it behind a scoped `#pragma`, as dotnet/maui did. | +| `Tizen.NUI.Window.Instance` | Deprecated at API12 in favour of `Window.Default` | Screenshot capture uses `Window.Default`. | + +## 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` (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`. | +| `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/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 new file mode 100644 index 00000000..f73ca53a --- /dev/null +++ b/eng/Maui.Tizen.Essentials.Sources.props @@ -0,0 +1,67 @@ + + + + + + $(MSBuildThisFileDirectory)../src/Maui.Tizen.Essentials/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 6cdf676e..96f7296a 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 @@ -109,6 +109,8 @@ check "normalize script is syntactically valid" bash -n eng/import/normalize-lay check "Tizen workload gate script is syntactically valid" bash -n eng/ci/tizen-workload-gate.sh check "real Tizen lane script is syntactically valid" bash -n eng/build-tizen.sh check "Tizen workload transition tests are syntactically valid" bash -n eng/tests/test-ci-tizen-workload-gate.sh +check "Essentials mutation runner is syntactically valid" bash -n eng/tests/run-essentials-negative-controls.sh +check "Essentials mutation lock tests are syntactically valid" bash -n eng/tests/test-essentials-mutation-lock.sh check "Wave C mutation runner is syntactically valid" bash -n eng/tests/run-wave-c-negative-controls.sh # --------------------------------------------------------------------------- @@ -119,6 +121,7 @@ check "Wave C mutation runner is syntactically valid" bash -n eng/tests/run-wave info "Workload-independent projects" WORKLOAD_FREE_PROJECTS=( "src/Maui.Tizen.Build.Tasks/Maui.Tizen.Build.Tasks.csproj" + "src/Maui.Tizen.Essentials.HostVerification/Maui.Tizen.Essentials.HostVerification.csproj" "tests/UnitTests/Maui.Tizen.UnitTests.csproj" # Verification lanes for the ported backend slice. Neither is a Tizen artifact: @@ -152,6 +155,18 @@ WORKLOAD_FREE_PROJECTS=( "tests/Maui.Tizen.Core.UnitTests/Maui.Tizen.Core.UnitTests.csproj" "tests/Maui.Tizen.SourceTests/Maui.Tizen.SourceTests.csproj" + # Essentials verification lanes, mirroring the pair above: + # + # Maui.Tizen.Essentials.RefPackCompile type-checks the ported Essentials sources against the + # REAL API15 reference assemblies the product will bind + # to. Compile-only and unpackable. This is the lane that + # caught Tizen.Maps being removed from API15. + # + # Maui.Tizen.Essentials.Tests executes DI/facade/permission/translation tests against + # the loadable Tizen.NET assemblies via + # src/Maui.Tizen.Essentials.HostVerification. + "tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj" + "tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj" # Foundation-owned probes. "eng/tests/PublicApiOptIn/PublicApiOptIn.csproj" "eng/tests/PackReadmeProbe/PackReadmeProbe.csproj" @@ -226,8 +241,43 @@ info "Repository invariant tests" if [[ $BUILD_OK -eq 1 ]]; then check "unit tests" "$DOTNET" test tests/UnitTests/Maui.Tizen.UnitTests.csproj --no-build -c Release check "backend slice tests" "$DOTNET" test tests/Maui.Tizen.Core.UnitTests/Maui.Tizen.Core.UnitTests.csproj --no-build -c Release + # Essentials behaviour tests, run against the workload-free host verification harness + # (src/Maui.Tizen.Essentials.HostVerification), which compiles the same sources the Tizen + # package will. Anything that P/Invokes into Tizen is out of their reach and is classified + # in docs/tizen-essentials-service-coverage.md rather than faked into a green test. + # + # The self-executing Microsoft.Testing.Platform binary is run directly. `dotnet test` would + # 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" + ESSENTIALS_RESULTS="$REPO_ROOT/artifacts/test-results/essentials" + + # 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 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=449 + + 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" check "Wave B source tests" "$DOTNET" test tests/Maui.Tizen.SourceTests/Maui.Tizen.SourceTests.csproj --no-build -c Release check "migration tooling tests" "$DOTNET" test tests/Migration.Tooling.Tests/Migration.Tooling.Tests.csproj --no-build -c Release + check "Essentials negative controls" "$REPO_ROOT/eng/tests/run-essentials-negative-controls.sh" + check "Essentials mutation lock behavior" "$REPO_ROOT/eng/tests/test-essentials-mutation-lock.sh" check "Wave B negative controls" env DOTNET="$DOTNET" "$REPO_ROOT/eng/tests/run-wave-b-negative-controls.sh" check "Wave B mutation runner behavior" "$REPO_ROOT/eng/tests/test-wave-b-mutation-runner.sh" check "Wave C negative controls" "$REPO_ROOT/eng/tests/run-wave-c-negative-controls.sh" 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 + + + + + $(DotNetTfm) + false + false + Maui.Tizen.Essentials.HostVerification + Microsoft.Maui.Platforms.Tizen.Essentials + false + false + true + true + + $(DefineConstants);TIZEN + + + + + + + + + + + + + + + + + + + diff --git a/src/Maui.Tizen.Essentials/Accelerometer/Accelerometer.tizen.cs b/src/Maui.Tizen.Essentials/Accelerometer/Accelerometer.tizen.cs deleted file mode 100644 index 7ec85b84..00000000 --- a/src/Maui.Tizen.Essentials/Accelerometer/Accelerometer.tizen.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenAccelerometer = Tizen.Sensor.Accelerometer; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class AccelerometerImplementation - { - internal static TizenAccelerometer DefaultSensor => - (TizenAccelerometer)PlatformUtils.GetDefaultSensor(SensorType.Accelerometer); - - public bool IsSupported => - TizenAccelerometer.IsSupported; - - void PlatformStart(SensorSpeed sensorSpeed) - { - DefaultSensor.Interval = sensorSpeed.ToPlatform(); - DefaultSensor.DataUpdated += DataUpdated; - DefaultSensor.Start(); - } - - void PlatformStop() - { - DefaultSensor.DataUpdated -= DataUpdated; - DefaultSensor.Stop(); - } - - void DataUpdated(object sender, AccelerometerDataUpdatedEventArgs e) - { - OnChanged(new AccelerometerData(e.X, e.Y, e.Z)); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs new file mode 100644 index 00000000..57d0ebab --- /dev/null +++ b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometer.cs @@ -0,0 +1,120 @@ +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. + /// + /// + /// 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(); + readonly object _queueLocker = new(); + readonly TizenNativeCallbackCoordinator _callbacks = new(); + + /// + public event EventHandler? ReadingChanged; + + /// + public event EventHandler? ShakeDetected; + + /// + public override bool IsSupported => TizenAccelerometerSensor.IsSupported; + + /// + protected override string SensorName => nameof(IAccelerometer); + + /// + protected override TizenAccelerometerSensor Sensor => + (TizenAccelerometerSensor)TizenSensors.GetDefaultSensor(TizenSensorType.Accelerometer); + + /// + protected override Action Subscribe(TizenAccelerometerSensor sensor, long generation) + { + EventHandler handler = + (sender, e) => OnDataUpdated(generation, e); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } + + /// + /// + /// 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(); + + /// + protected override void OnStopped() => ClearShakeWindow(); + + void ClearShakeWindow() + { + lock (_queueLocker) + _queue.Clear(); + } + + void OnDataUpdated(long generation, global::Tizen.Sensor.AccelerometerDataUpdatedEventArgs e) + { + if (!IsCurrentGeneration(generation)) + return; + + var reading = new AccelerometerData(e.X, e.Y, e.Z); + + Raise(generation, ReadingChanged, new AccelerometerChangedEventArgs(reading)); + + if (ShakeDetected is not null && IsCurrentGeneration(generation)) + ProcessShakeEvent(generation, reading.Acceleration); + } + + void ProcessShakeEvent(long generation, Vector3 acceleration) + { + var now = TizenAccelerometerQueue.ToNanoseconds(DateTime.UtcNow); + + var x = acceleration.X * Gravity; + var y = acceleration.Y * Gravity; + var z = acceleration.Z * Gravity; + + 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 (shaking) + _queue.Clear(); + } + + if (!shaking || !IsCurrentGeneration(generation)) + return; + + var handler = ShakeDetected; + + if (handler is null) + return; + + if (UseSyncContext) + _callbacks.Post( + () => IsCurrentGeneration(generation), + () => handler.Invoke(this, EventArgs.Empty)); + else + { + if (IsCurrentGeneration(generation)) + handler.Invoke(this, EventArgs.Empty); + } + } + } +} diff --git a/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs new file mode 100644 index 00000000..ef41ee44 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Accelerometer/TizenAccelerometerQueue.cs @@ -0,0 +1,82 @@ +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 count >= MinQueueSize && + newest - oldest >= MinWindowSizeNanoseconds && + _acceleratingCount * 4 >= count * 3; + } + } + + long NewestTimestamp + { + get + { + var newest = 0L; + foreach (var sample in _samples) + newest = sample.Timestamp; + return newest; + } + } + + void Purge(long cutoff) + { + while (_samples.Count > 0 && 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/AppActions.netstandard.tvos.watchos.macos.tizen.cs b/src/Maui.Tizen.Essentials/AppActions/AppActions.netstandard.tvos.watchos.macos.tizen.cs deleted file mode 100755 index 07ff21ea..00000000 --- a/src/Maui.Tizen.Essentials/AppActions/AppActions.netstandard.tvos.watchos.macos.tizen.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Microsoft.Maui.ApplicationModel -{ - partial class AppActionsImplementation : IAppActions - { - public bool IsSupported => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task> GetAsync() => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task SetAsync(IEnumerable actions) => - throw ExceptionUtils.NotSupportedOrImplementedException; - -#pragma warning disable CS0067 // The event is never used - public event EventHandler AppActionActivated; -#pragma warning restore CS0067 // The event is never used - } -} 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/AppInfo.tizen.cs b/src/Maui.Tizen.Essentials/AppInfo/AppInfo.tizen.cs deleted file mode 100644 index 6285fac1..00000000 --- a/src/Maui.Tizen.Essentials/AppInfo/AppInfo.tizen.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Globalization; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel -{ - class AppInfoImplementation : IAppInfo - { - public string PackageName => GetDefaultPackageName(); - - internal static string GetDefaultPackageName() => - Application.Current.ApplicationInfo.PackageId; - - public string Name - => Application.Current.ApplicationInfo.Label; - - public System.Version Version => Utils.ParseVersion(VersionString); - - public string VersionString - => Platform.CurrentPackage.Version; - - public string BuildString - => Version.Build.ToString(CultureInfo.InvariantCulture); - - public void ShowSettingsUI() - { - Permissions.EnsureDeclared(); - AppControl.SendLaunchRequest(new AppControl() { Operation = AppControlOperations.Setting }); - } - - public AppTheme RequestedTheme - => AppTheme.Unspecified; - - public AppPackagingModel PackagingModel => AppPackagingModel.Packaged; - - public LayoutDirection RequestedLayoutDirection - => LayoutDirection.LeftToRight; - } -} 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/Barometer.tizen.cs b/src/Maui.Tizen.Essentials/Barometer/Barometer.tizen.cs deleted file mode 100644 index 3add4eb3..00000000 --- a/src/Maui.Tizen.Essentials/Barometer/Barometer.tizen.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenBarometerSensor = Tizen.Sensor.PressureSensor; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class BarometerImplementation : IBarometer - { - public bool IsSupported - => TizenBarometerSensor.IsSupported; - - TizenBarometerSensor DefaultSensor - => (TizenBarometerSensor)PlatformUtils.GetDefaultSensor(SensorType.Barometer); - - TizenBarometerSensor sensor = null; - - void PlatformStart(SensorSpeed sensorSpeed) - { - sensor = DefaultSensor; - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += DataUpdated; - sensor.Start(); - } - - void DataUpdated(object sender, PressureSensorDataUpdatedEventArgs e) - => RaiseReadingChanged(new BarometerData(e.Pressure)); - - void PlatformStop() - { - sensor.DataUpdated -= DataUpdated; - sensor.Stop(); - sensor = null; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs b/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs new file mode 100644 index 00000000..c791150a --- /dev/null +++ b/src/Maui.Tizen.Essentials/Barometer/TizenBarometer.cs @@ -0,0 +1,37 @@ +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 Action Subscribe(TizenPressureSensor sensor, long generation) + { + EventHandler handler = + (sender, e) => Raise( + generation, + ReadingChanged, + new BarometerChangedEventArgs(new BarometerData(e.Pressure))); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Battery/Battery.tizen.cs b/src/Maui.Tizen.Essentials/Battery/Battery.tizen.cs deleted file mode 100755 index 6aee8be5..00000000 --- a/src/Maui.Tizen.Essentials/Battery/Battery.tizen.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using Microsoft.Maui.ApplicationModel; -using TizenBattery = Tizen.System.Battery; - -namespace Microsoft.Maui.Devices -{ - partial class BatteryImplementation : IBattery - { - void OnChanged(object sender, object e) - => MainThread.BeginInvokeOnMainThread(OnBatteryInfoChanged); - - void StartBatteryListeners() - { - TizenBattery.PercentChanged += OnChanged; - TizenBattery.ChargingStateChanged += OnChanged; - TizenBattery.LevelChanged += OnChanged; - } - - void StopBatteryListeners() - { - TizenBattery.PercentChanged -= OnChanged; - TizenBattery.ChargingStateChanged -= OnChanged; - TizenBattery.LevelChanged -= OnChanged; - } - - public double ChargeLevel - { - get - { - return (double)TizenBattery.Percent / 100; - } - } - - public BatteryState State - { - get - { - if (TizenBattery.IsCharging) - return BatteryState.Charging; - return BatteryState.Discharging; - } - } - - public BatteryPowerSource PowerSource - { - get - { - if (TizenBattery.IsCharging) - return BatteryPowerSource.Usb; - return BatteryPowerSource.Battery; - } - } - - void StartEnergySaverListeners() - => throw new FeatureNotSupportedException("This API is not currently supported on Tizen."); - - void StopEnergySaverListeners() - => throw new FeatureNotSupportedException("This API is not currently supported on Tizen."); - - public EnergySaverStatus EnergySaverStatus - => throw new FeatureNotSupportedException("This API is not currently supported on Tizen."); - } -} diff --git a/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs new file mode 100644 index 00000000..965f0493 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Battery/TizenBattery.cs @@ -0,0 +1,131 @@ +using System; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices; +using TizenBatteryInfo = Tizen.System.Battery; +using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.System.Battery. + /// + /// + /// 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. + /// + public sealed class TizenBattery : IBattery, IDisposable + { + const string EnergySaverReason = + "Tizen exposes no application-visible power saving mode state."; + + readonly TizenEventSubscriptionCoordinator _events; + + /// Creates the Tizen battery service. + public TizenBattery() + { + _events = new(this, StartListeners); + } + + /// + 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 => + MapState(TizenBatteryInfo.IsCharging, TizenBatteryInfo.Percent, TizenBatteryInfo.PowerSource); + + /// + /// 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. + public EnergySaverStatus EnergySaverStatus => + throw TizenEssentialsSupport.NotSupported($"{nameof(IBattery)}.{nameof(EnergySaverStatus)}", EnergySaverReason); + + /// + public event EventHandler? BatteryInfoChanged + { + add => _events.Add(value); + remove => _events.Remove(value); + } + + /// + /// 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); + } + + Action StartListeners(TizenEventGeneration generation) + { + var percent = false; + var charging = false; + void OnChanged(object? sender, object e) + { + var args = new BatteryInfoChangedEventArgs(ChargeLevel, State, PowerSource); + generation.Publish(args); + } + + try + { + TizenBatteryInfo.PercentChanged += OnChanged; + percent = true; + TizenBatteryInfo.ChargingStateChanged += OnChanged; + charging = true; + TizenBatteryInfo.LevelChanged += OnChanged; + } + catch + { + if (charging) + TizenBatteryInfo.ChargingStateChanged -= OnChanged; + if (percent) + TizenBatteryInfo.PercentChanged -= OnChanged; + throw; + } + + return () => + { + TizenBatteryInfo.PercentChanged -= OnChanged; + TizenBatteryInfo.ChargingStateChanged -= OnChanged; + TizenBatteryInfo.LevelChanged -= OnChanged; + }; + } + + /// + public void Dispose() => _events.Dispose(); + } +} diff --git a/src/Maui.Tizen.Essentials/Browser/Browser.tizen.cs b/src/Maui.Tizen.Essentials/Browser/Browser.tizen.cs deleted file mode 100755 index df8d64b4..00000000 --- a/src/Maui.Tizen.Essentials/Browser/Browser.tizen.cs +++ /dev/null @@ -1,32 +0,0 @@ -#nullable enable -using System; -using System.Linq; -using System.Threading.Tasks; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel -{ - partial class BrowserImplementation : IBrowser - { - public Task OpenAsync(Uri uri, BrowserLaunchOptions launchMode) - { - if (uri == null) - throw new ArgumentNullException(nameof(uri)); - - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.View, - Uri = uri.AbsoluteUri - }; - - var hasMatches = AppControl.GetMatchedApplicationIds(appControl).Any(); - - if (hasMatches) - AppControl.SendLaunchRequest(appControl); - - return Task.FromResult(hasMatches); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs b/src/Maui.Tizen.Essentials/Browser/TizenBrowser.cs new file mode 100644 index 00000000..1ee7ce21 --- /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 = TizenLauncher.HasHandler(appControl); + + if (hasMatches) + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(hasMatches); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Clipboard/Clipboard.netstandard.tvos.watchos.tizen.cs b/src/Maui.Tizen.Essentials/Clipboard/Clipboard.netstandard.tvos.watchos.tizen.cs deleted file mode 100644 index be583c4f..00000000 --- a/src/Maui.Tizen.Essentials/Clipboard/Clipboard.netstandard.tvos.watchos.tizen.cs +++ /dev/null @@ -1,23 +0,0 @@ -#nullable enable -using System.Threading.Tasks; - -namespace Microsoft.Maui.ApplicationModel.DataTransfer -{ - partial class ClipboardImplementation : IClipboard - { - public Task SetTextAsync(string? text) - => throw ExceptionUtils.NotSupportedOrImplementedException; - - public bool HasText - => throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task GetTextAsync() - => throw ExceptionUtils.NotSupportedOrImplementedException; - - void StartClipboardListeners() - => throw ExceptionUtils.NotSupportedOrImplementedException; - - void StopClipboardListeners() - => throw ExceptionUtils.NotSupportedOrImplementedException; - } -} diff --git a/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs new file mode 100644 index 00000000..4a1fafeb --- /dev/null +++ b/src/Maui.Tizen.Essentials/Clipboard/TizenClipboard.cs @@ -0,0 +1,373 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.DataTransfer; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by + /// . + /// + public sealed class TizenClipboard : IClipboard, IDisposable + { + readonly object _locker = new(); + readonly ITizenClipboardDispatcher _dispatcher; + readonly ITizenClipboardNative _native; + readonly TizenEventSubscriptionCoordinator _events; + readonly Dictionary> _pending = []; + long _nextRequest; + bool _disposed; + + /// Maximum time to wait for Tizen's one-shot clipboard callback. + internal static TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(10); + + /// Creates a clipboard service using the NUI singleton. + public TizenClipboard() + : this(TizenClipboardDispatcher.Instance, TizenClipboardNative.Instance) + { + } + + internal TizenClipboard( + ITizenClipboardDispatcher dispatcher, + ITizenClipboardNative native) + { + _dispatcher = dispatcher; + _native = native; + _events = new( + this, + generation => + { + Action nativeCallback = () => generation.Publish(EventArgs.Empty); + _dispatcher.Invoke(() => _native.StartChangeNotifications(nativeCallback)); + return () => _dispatcher.Invoke(_native.StopChangeNotifications); + }, + new TizenNativeCallbackCoordinator(dispatcher)); + } + + /// + /// + /// NUI exposes text reads only as an asynchronous callback. Blocking the NUI thread to + /// implement this synchronous property would deadlock the callback, so this member alone is + /// unsupported; and are implemented. + /// + public bool HasText => + throw TizenEssentialsSupport.NotSupported( + $"{nameof(IClipboard)}.{nameof(HasText)}", + "Tizen.NUI.Clipboard exposes reads only through an asynchronous callback; the " + + "synchronous HasText contract cannot be implemented without blocking the NUI loop."); + + /// + public event EventHandler ClipboardContentChanged + { + add => _events.Add(value); + remove => _events.Remove(value); + } + + /// + public Task GetTextAsync() => GetTextAsync(CancellationToken.None); + + internal async Task GetTextAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + TaskCompletionSource completion; + long request; + lock (_locker) + { + ObjectDisposedException.ThrowIf(_disposed, this); + request = ++_nextRequest; + completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + _pending.Add(request, completion); + } + + using var timeout = new CancellationTokenSource(RequestTimeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + timeout.Token); + using var registration = linked.Token.Register(() => + { + TaskCompletionSource? pending; + lock (_locker) + { + if (!_pending.Remove(request, out pending)) + return; + } + + if (cancellationToken.IsCancellationRequested) + pending.TrySetCanceled(cancellationToken); + else + pending.TrySetException( + new TimeoutException( + $"Tizen did not return clipboard text within {RequestTimeout}.")); + }); + + try + { + await _dispatcher.InvokeAsync(() => + { + lock (_locker) + { + if (_disposed || !_pending.ContainsKey(request)) + return; + } + + _native.GetText((success, text) => CompleteRequest(request, success, text)); + }) + .ConfigureAwait(false); + } + catch + { + lock (_locker) + _pending.Remove(request); + throw; + } + + return await completion.Task.ConfigureAwait(false); + } + + /// + public async Task SetTextAsync(string? text) + { + lock (_locker) + ObjectDisposedException.ThrowIf(_disposed, this); + + var accepted = await _dispatcher.InvokeAsync(() => + { + lock (_locker) + ObjectDisposedException.ThrowIf(_disposed, this); + return _native.SetText(text ?? string.Empty); + }).ConfigureAwait(false); + + if (!accepted) + throw new InvalidOperationException("Tizen rejected the clipboard text request."); + } + + void CompleteRequest(long request, bool success, string? text) + { + TaskCompletionSource? completion; + lock (_locker) + { + if (!_pending.Remove(request, out completion)) + return; + } + + if (success) + completion.TrySetResult(text); + else + completion.TrySetResult(null); + } + + /// + public void Dispose() + { + List> pending; + lock (_locker) + { + if (_disposed) + return; + + _disposed = true; + pending = [.. _pending.Values]; + _pending.Clear(); + } + + foreach (var completion in pending) + completion.TrySetException(new ObjectDisposedException(nameof(TizenClipboard))); + + _events.Dispose(); + } + } + + internal interface ITizenClipboardDispatcher : ITizenNativeCallbackDispatcher + { + void Invoke(Action action); + + Task InvokeAsync(Action action); + + Task InvokeAsync(Func action); + + } + + internal interface ITizenClipboardNative + { + void StartChangeNotifications(Action changed); + + void StopChangeNotifications(); + + bool SetText(string text); + + void GetText(Action callback); + } + + sealed class TizenClipboardDispatcher : ITizenClipboardDispatcher + { + public static TizenClipboardDispatcher Instance { get; } = new(); + + public void Invoke(Action action) + { + if (MainThread.IsMainThread) + action(); + else + MainThread.InvokeOnMainThreadAsync(action).GetAwaiter().GetResult(); + } + + public Task InvokeAsync(Action action) => MainThread.InvokeOnMainThreadAsync(action); + + public Task InvokeAsync(Func action) => MainThread.InvokeOnMainThreadAsync(action); + + public void PostDeferred(Action action) => + TizenNativeCallbackDispatcher.PostDeferred( + MainThread.BeginInvokeOnMainThread, + static () => SynchronizationContext.Current, + action); + } + + sealed class TizenClipboardNative : ITizenClipboardNative + { + const string MimeType = "text/plain;charset=utf-8"; + global::Tizen.NUI.Clipboard? _clipboard; + global::Tizen.NUI.WindowSystem.Shell.TizenShell? _shell; + global::Tizen.NUI.WindowSystem.Shell.KVMService? _kvm; + EventHandler? _dataSelectedHandler; + + public static TizenClipboardNative Instance { get; } = new(); + + TizenClipboardNative() + { + } + + global::Tizen.NUI.Clipboard Clipboard => + _clipboard ??= global::Tizen.NUI.Clipboard.Instance; + + public void StartChangeNotifications(Action changed) + { + if (_kvm is not null) + throw new InvalidOperationException("Clipboard change notifications are already active."); + + 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 + { + shell = new global::Tizen.NUI.WindowSystem.Shell.TizenShell(); + kvm = new global::Tizen.NUI.WindowSystem.Shell.KVMService( + shell, + global::Tizen.NUI.Window.Default); + kvm.SetSecondarySelection(); + selected = true; + dataSelectedHandler = (_, _) => changed(); + Clipboard.DataSelected += dataSelectedHandler; + subscribed = true; + _shell = shell; + _kvm = kvm; + _dataSelectedHandler = dataSelectedHandler; + } + catch + { + if (subscribed && dataSelectedHandler is not null) + { + try + { + Clipboard.DataSelected -= dataSelectedHandler; + } + catch (Exception) + { + } + } + if (selected) + { + try + { + kvm?.UnsetSecondarySelection(); + } + catch (Exception) + { + } + } + try + { + kvm?.Dispose(); + } + catch (Exception) + { + } + try + { + shell?.Dispose(); + } + catch (Exception) + { + } + throw; + } + } + + public void StopChangeNotifications() + { + if (_kvm is null && _dataSelectedHandler is null) + return; + + var failures = new List(); + if (_dataSelectedHandler is not null) + { + try + { + Clipboard.DataSelected -= _dataSelectedHandler; + } + catch (Exception exception) + { + failures.Add(exception); + } + } + + try + { + _kvm?.UnsetSecondarySelection(); + } + catch (Exception exception) + { + failures.Add(exception); + } + + try + { + _kvm?.Dispose(); + } + catch (Exception exception) + { + failures.Add(exception); + } + + try + { + _shell?.Dispose(); + } + catch (Exception exception) + { + failures.Add(exception); + } + + _dataSelectedHandler = null; + _kvm = null; + _shell = null; + + if (failures.Count == 1) + throw failures[0]; + if (failures.Count > 1) + throw new AggregateException("Clipboard change notification teardown failed.", failures); + } + + public bool SetText(string text) => Clipboard.SetData(MimeType, text); + + public void GetText(Action callback) => + Clipboard.GetData( + MimeType, + (success, clipEvent) => callback(success, success ? clipEvent.Data : null)); + + } +} diff --git a/src/Maui.Tizen.Essentials/Compass/Compass.tizen.cs b/src/Maui.Tizen.Essentials/Compass/Compass.tizen.cs deleted file mode 100644 index dd388547..00000000 --- a/src/Maui.Tizen.Essentials/Compass/Compass.tizen.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenCompass = Tizen.Sensor.OrientationSensor; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class CompassImplementation : ICompass - { - static TizenCompass DefaultSensor => - (TizenCompass)PlatformUtils.GetDefaultSensor(SensorType.Compass); - - bool PlatformIsSupported => - TizenCompass.IsSupported; - - TizenCompass sensor; - - void PlatformStart(SensorSpeed sensorSpeed, bool applyLowPassFilter) - { - sensor = DefaultSensor; - - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += DataUpdated; - sensor.Start(); - } - - void PlatformStop() - { - sensor.DataUpdated -= DataUpdated; - sensor.Stop(); - sensor = null; - } - - void DataUpdated(object sender, OrientationSensorDataUpdatedEventArgs e) - { - RaiseReadingChanged(new CompassData(e.Azimuth)); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs b/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs new file mode 100644 index 00000000..79162fc7 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Compass/TizenCompass.cs @@ -0,0 +1,49 @@ +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 Action Subscribe(TizenOrientationSensorNative sensor, long generation) + { + EventHandler handler = + (sender, e) => Raise( + generation, + ReadingChanged, + new CompassChangedEventArgs(new CompassData(e.Azimuth))); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } + } +} diff --git a/src/Maui.Tizen.Essentials/Connectivity/Connectivity.tizen.cs b/src/Maui.Tizen.Essentials/Connectivity/Connectivity.tizen.cs deleted file mode 100644 index 39947484..00000000 --- a/src/Maui.Tizen.Essentials/Connectivity/Connectivity.tizen.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections.Generic; -using Microsoft.Maui.ApplicationModel; -using Tizen.Network.Connection; - -namespace Microsoft.Maui.Networking -{ - partial class ConnectivityImplementation : IConnectivity - { - IList profiles = new List(); - - void OnChanged(object sender, object e) - { - GetProfileListAsync(); - } - - async void GetProfileListAsync() - { - var list = await ConnectionProfileManager.GetProfileListAsync(ProfileListType.Connected); - profiles.Clear(); - foreach (var result in list) - { - switch (result.Type) - { - case ConnectionProfileType.Bt: - profiles.Add(ConnectionProfile.Bluetooth); - break; - - case ConnectionProfileType.Cellular: - profiles.Add(ConnectionProfile.Cellular); - break; - - case ConnectionProfileType.Ethernet: - profiles.Add(ConnectionProfile.Ethernet); - break; - - case ConnectionProfileType.WiFi: - profiles.Add(ConnectionProfile.WiFi); - break; - } - } - OnConnectivityChanged(); - } - - public NetworkAccess NetworkAccess - { - get - { - Permissions.EnsureDeclared(); - var currentAccess = ConnectionManager.CurrentConnection; - switch (currentAccess.Type) - { - case ConnectionType.WiFi: - case ConnectionType.Cellular: - case ConnectionType.Ethernet: - return NetworkAccess.Internet; - default: - return NetworkAccess.None; - } - } - } - - public IEnumerable ConnectionProfiles - { - get - { - return profiles; - } - } - - void StartListeners() - { - Permissions.EnsureDeclared(); - ConnectionManager.ConnectionTypeChanged += OnChanged; - GetProfileListAsync(); - } - - void StopListeners() - { - ConnectionManager.ConnectionTypeChanged -= OnChanged; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs new file mode 100644 index 00000000..60c7fd83 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Connectivity/TizenConnectivity.cs @@ -0,0 +1,177 @@ +using System; +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 TizenConnectionState = Tizen.Network.Connection.ConnectionState; +using TizenConnectionType = Tizen.Network.Connection.ConnectionType; +using TizenConnectionTypeEventArgs = Tizen.Network.Connection.ConnectionTypeEventArgs; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of , backed by Tizen.Network.Connection. + /// + public sealed class TizenConnectivity : IConnectivity, IDisposable + { + readonly TizenEventSubscriptionCoordinator _events; + + /// Creates the Tizen connectivity service. + public TizenConnectivity() + { + _events = new(this, StartListeners); + } + + /// + public NetworkAccess NetworkAccess + { + get + { + TizenPermissions.EnsureDeclared(); + + return GetNetworkAccess(static () => TizenConnectionManager.CurrentConnection.Type); + } + } + + /// + /// + /// 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 + { + TizenPermissions.EnsureDeclared(); + + return GetConnectionProfiles(); + } + } + + 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); + + TryAddProfile(profiles, ConnectionProfile.WiFi, isWiFiConnected); + TryAddProfile(profiles, ConnectionProfile.Cellular, isCellularConnected); + TryAddProfile(profiles, ConnectionProfile.Ethernet, isEthernetConnected); + TryAddProfile(profiles, ConnectionProfile.Bluetooth, isBluetoothConnected); + + return profiles; + } + + 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; + } + } + + 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) => + 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 + { + add => _events.Add(value); + remove => _events.Remove(value); + } + + Action StartListeners(TizenEventGeneration generation) + { + TizenPermissions.EnsureDeclared(); + + EventHandler handler = (_, _) => + { + var args = new ConnectivityChangedEventArgs( + GetNetworkAccess(static () => TizenConnectionManager.CurrentConnection.Type), + GetConnectionProfiles()); + generation.Publish(args); + }; + + StartTransactional( + () => TizenConnectionManager.ConnectionTypeChanged += handler, + () => TizenConnectionManager.ConnectionTypeChanged -= handler); + + return () => TizenConnectionManager.ConnectionTypeChanged -= handler; + } + + internal static void StartTransactional(Action subscribe, Action unsubscribe) + { + try + { + subscribe(); + } + catch + { + try + { + unsubscribe(); + } + catch (Exception) + { + // Preserve the subscription failure. + } + + throw; + } + } + + /// + public void Dispose() => _events.Dispose(); + } +} diff --git a/src/Maui.Tizen.Essentials/Contacts/Contacts.tizen.cs b/src/Maui.Tizen.Essentials/Contacts/Contacts.tizen.cs deleted file mode 100644 index df3722c3..00000000 --- a/src/Maui.Tizen.Essentials/Contacts/Contacts.tizen.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Tizen.Applications; -using Tizen.Pims.Contacts; -using TizenContact = Tizen.Pims.Contacts.ContactsViews.Contact; -using TizenEmail = Tizen.Pims.Contacts.ContactsViews.Email; -using TizenName = Tizen.Pims.Contacts.ContactsViews.Name; -using TizenNumber = Tizen.Pims.Contacts.ContactsViews.Number; - -namespace Microsoft.Maui.ApplicationModel.Communication -{ - class ContactsImplementation : IContacts - { - static ContactsManager manager = new ContactsManager(); - - public async Task PickContactAsync() - { - Permissions.EnsureDeclared(); - Permissions.EnsureDeclared(); - await Permissions.EnsureGrantedAsync(); - - var tcs = new TaskCompletionSource(); - - var appControl = new AppControl(); - appControl.Operation = AppControlOperations.Pick; - appControl.ExtraData.Add(AppControlData.SectionMode, "single"); - appControl.LaunchMode = AppControlLaunchMode.Single; - appControl.Mime = "application/vnd.tizen.contact"; - - AppControl.SendLaunchRequest(appControl, (request, reply, result) => - { - Contact contact = null; - - if (result == AppControlReplyResult.Succeeded) - { - var contactId = reply.ExtraData.Get>(AppControlData.Selected)?.FirstOrDefault(); - - if (int.TryParse(contactId, out var contactInt)) - { - var record = manager.Database.Get(TizenContact.Uri, contactInt); - if (record != null) - contact = ToContact(record); - } - } - tcs.TrySetResult(contact); - }); - - return await tcs.Task; - } - - public Task> GetAllAsync(CancellationToken cancellationToken) - { - var contactsList = manager.Database.GetAll(TizenContact.Uri, 0, 0); - - return Task.FromResult(GetEnumerable()); - - IEnumerable GetEnumerable() - { - for (var i = 0; i < contactsList?.Count; i++) - { - yield return ToContact(contactsList.GetCurrentRecord()); - - contactsList.MoveNext(); - } - } - } - - static Contact ToContact(ContactsRecord contactsRecord) - { - var record = contactsRecord.GetChildRecord(TizenContact.Name, 0); - - var phones = new List(); - var phonesCount = contactsRecord.GetChildRecordCount(TizenContact.Number); - for (var i = 0; i < phonesCount; i++) - { - var nameRecord = contactsRecord.GetChildRecord(TizenContact.Number, i); - var number = nameRecord.Get(TizenNumber.NumberData); - - phones.Add(new ContactPhone(number)); - } - - var emails = new List(); - var emailCount = contactsRecord.GetChildRecordCount(TizenContact.Email); - for (var i = 0; i < emailCount; i++) - { - var emailRecord = contactsRecord.GetChildRecord(TizenContact.Email, i); - var addr = emailRecord.Get(TizenEmail.Address); - - emails.Add(new ContactEmail(addr)); - } - - return new Contact( - (record?.Get(TizenName.ContactId))?.ToString(), - record?.Get(TizenName.Prefix), - record?.Get(TizenName.First), - record?.Get(TizenName.Addition), - record?.Get(TizenName.Last), - record?.Get(TizenName.Suffix), - phones, - emails); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs new file mode 100644 index 00000000..50ba248f --- /dev/null +++ b/src/Maui.Tizen.Essentials/Contacts/TizenContacts.cs @@ -0,0 +1,138 @@ +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 appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Pick, + LaunchMode = TizenAppControlLaunchMode.Single, + Mime = "application/vnd.tizen.contact", + }; + appControl.ExtraData.Add(TizenAppControlData.SectionMode, "single"); + + return await TizenAppControlReply.RunAsync( + callback => TizenAppControl.SendLaunchRequest( + appControl, + TizenAppControlReply.NativeTimeoutMilliseconds, + (_, reply, result) => callback(reply, result)), + static (reply, result) => + { + if (result != TizenAppControlReplyResult.Succeeded || + !reply.ExtraData.TryGet( + TizenAppControlData.Selected, + out IEnumerable selected) || + !int.TryParse(selected?.FirstOrDefault(), out var id)) + { + return null; + } + + using var record = Manager.Value.Database.Get(TizenContact.Uri, id); + return record is null ? null : ToContact(record); + }).ConfigureAwait(false); + } + + /// + /// + /// + /// 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) + { + await TizenPermissions.EnsureGrantedAsync().ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + var contacts = new List(); + + using var contactsList = Manager.Value.Database.GetAll(TizenContact.Uri, 0, 0); + + if (contactsList is null) + return contacts; + + for (var i = 0; i < contactsList.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + using var record = contactsList.GetCurrentRecord(); + if (record is not null) + contacts.Add(ToContact(record)); + + contactsList.MoveNext(); + } + + return contacts; + } + + static Contact ToContact(ContactsRecord contactsRecord) + { + 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++) + { + using 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++) + { + using 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/DeviceDisplay.tizen.cs b/src/Maui.Tizen.Essentials/DeviceDisplay/DeviceDisplay.tizen.cs deleted file mode 100644 index b3f9741e..00000000 --- a/src/Maui.Tizen.Essentials/DeviceDisplay/DeviceDisplay.tizen.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using Microsoft.Maui.ApplicationModel; -using Tizen.Applications; - -namespace Microsoft.Maui.Devices -{ - partial class DeviceDisplayImplementation - { - [DllImport("libcapi-system-device.so.0", EntryPoint = "device_power_request_lock")] - static extern void RequestKeepScreenOn(int type = 1, int timeout = 0); - - [DllImport("libcapi-system-device.so.0", EntryPoint = "device_power_release_lock")] - static extern void ReleaseKeepScreenOn(int type = 1); - - static CoreApplication CoreApplication => Application.Current as CoreApplication; - static int displayWidth = PlatformUtils.GetFeatureInfo("screen.width"); - static int displayHeight = PlatformUtils.GetFeatureInfo("screen.height"); - static int displayDpi = DeviceInfo.Idiom == DeviceIdiom.TV ? 72 : PlatformUtils.GetFeatureInfo("screen.dpi"); - DisplayOrientation displayOrientation; - DisplayRotation displayRotation = DisplayRotation.Rotation0; - - bool keepScreenOn = false; - - protected override bool GetKeepScreenOn() => keepScreenOn; - - protected override void SetKeepScreenOn(bool keepScreenOn) - { - if (keepScreenOn) - RequestKeepScreenOn(); - else - ReleaseKeepScreenOn(); - this.keepScreenOn = keepScreenOn; - } - - protected override DisplayInfo GetMainDisplayInfo() - { - return new DisplayInfo( - width: displayWidth, - height: displayHeight, - density: displayDpi / DeviceDisplay.BaseLogicalDpi, - orientation: GetNaturalDisplayOrientation(), - rotation: displayRotation - ); - } - - protected override void StartScreenMetricsListeners() - { - if (CoreApplication != null) - { - CoreApplication.DeviceOrientationChanged += OnRotationChanged; - } - } - - protected override void StopScreenMetricsListeners() - { - if (CoreApplication != null) - { - CoreApplication.DeviceOrientationChanged -= OnRotationChanged; - } - } - - DisplayOrientation GetNaturalDisplayOrientation() - { - if (displayHeight >= displayWidth) - { - return DisplayOrientation.Portrait; - } - else - { - return DisplayOrientation.Landscape; - } - } - - void OnRotationChanged(object s, DeviceOrientationEventArgs e) - { - switch (e.DeviceOrientation) - { - case DeviceOrientation.Orientation_0: - displayRotation = DisplayRotation.Rotation0; - displayOrientation = GetNaturalDisplayOrientation(); - break; - case DeviceOrientation.Orientation_90: - displayRotation = DisplayRotation.Rotation90; - displayOrientation = GetNaturalDisplayOrientation() == DisplayOrientation.Portrait ? DisplayOrientation.Landscape : DisplayOrientation.Portrait; - break; - case DeviceOrientation.Orientation_180: - displayRotation = DisplayRotation.Rotation180; - displayOrientation = GetNaturalDisplayOrientation(); - break; - case DeviceOrientation.Orientation_270: - displayRotation = DisplayRotation.Rotation270; - displayOrientation = GetNaturalDisplayOrientation() == DisplayOrientation.Portrait ? DisplayOrientation.Landscape : DisplayOrientation.Portrait; - break; - default: - displayRotation = DisplayRotation.Unknown; - displayOrientation = DisplayOrientation.Unknown; - break; - } - OnMainDisplayInfoChanged(); - } - } -} diff --git a/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs new file mode 100644 index 00000000..c12872c4 --- /dev/null +++ b/src/Maui.Tizen.Essentials/DeviceDisplay/TizenDeviceDisplay.cs @@ -0,0 +1,169 @@ +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, IDisposable + { + // 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 TizenEventSubscriptionCoordinator _events; + readonly ITizenDeviceDisplayNative _native; + bool _keepScreenOn; + DisplayRotation _displayRotation = DisplayRotation.Rotation0; + DisplayOrientation _displayOrientation = DisplayOrientation.Unknown; + + /// Creates the Tizen display service. + public TizenDeviceDisplay() : this(TizenDeviceDisplayNative.Instance) + { + } + + internal TizenDeviceDisplay( + ITizenDeviceDisplayNative native, + TizenNativeCallbackCoordinator? callbacks = null) + { + _native = native; + _events = new(this, StartListeners, callbacks); + } + + /// + 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 metrics = _native.GetMetrics(); + + return new DisplayInfo( + width: metrics.Width, + height: metrics.Height, + density: metrics.Dpi / BaseLogicalDpi, + orientation: _displayOrientation == DisplayOrientation.Unknown + ? GetNaturalOrientation(metrics.Width, metrics.Height) + : _displayOrientation, + rotation: _displayRotation); + } + } + + /// + public event EventHandler MainDisplayInfoChanged + { + add => _events.Add(value); + remove => _events.Remove(value); + } + + Action StartListeners(TizenEventGeneration generation) + { + return _native.Subscribe(deviceOrientation => + { + 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) => + 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), + }; + } + + /// + 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/DeviceInfo/DeviceInfo.tizen.cs b/src/Maui.Tizen.Essentials/DeviceInfo/DeviceInfo.tizen.cs deleted file mode 100644 index d96c927e..00000000 --- a/src/Maui.Tizen.Essentials/DeviceInfo/DeviceInfo.tizen.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using Microsoft.Maui.ApplicationModel; - -namespace Microsoft.Maui.Devices -{ - class DeviceInfoImplementation : IDeviceInfo - { - public string Model => PlatformUtils.GetSystemInfo("model_name"); - - public string Manufacturer => PlatformUtils.GetSystemInfo("manufacturer"); - - public string Name => PlatformUtils.GetSystemInfo("device_name"); - - public string VersionString => PlatformUtils.GetFeatureInfo("platform.version"); - - public Version Version => Utils.ParseVersion(VersionString); - - public DevicePlatform Platform => DevicePlatform.Tizen; - - public DeviceIdiom Idiom - { - get - { - var profile = PlatformUtils.GetFeatureInfo("profile")?.ToUpperInvariant(); - - if (profile == null) - return DeviceIdiom.Unknown; - - if (profile.StartsWith("M")) - return DeviceIdiom.Phone; - else if (profile.StartsWith("W")) - return DeviceIdiom.Watch; - else if (profile.StartsWith("T")) - return DeviceIdiom.TV; - else - return DeviceIdiom.Unknown; - } - } - - public DeviceType DeviceType - { - get - { - var arch = PlatformUtils.GetFeatureInfo("platform.core.cpu.arch"); - var armv7 = PlatformUtils.GetFeatureInfo("platform.core.cpu.arch.armv7"); - var x86 = PlatformUtils.GetFeatureInfo("platform.core.cpu.arch.x86"); - - if (arch != null && arch.Equals("armv7", StringComparison.Ordinal) && armv7 && !x86) - return DeviceType.Physical; - else if (arch != null && arch.Equals("x86", StringComparison.Ordinal) && !armv7 && x86) - return DeviceType.Virtual; - else - return DeviceType.Unknown; - } - } - } -} 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/Email.tizen.cs b/src/Maui.Tizen.Essentials/Email/Email.tizen.cs deleted file mode 100644 index 0b0bb976..00000000 --- a/src/Maui.Tizen.Essentials/Email/Email.tizen.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel.Communication -{ - partial class EmailImplementation : IEmail - { - public bool IsComposeSupported - => PlatformUtils.GetFeatureInfo("email"); - - Task PlatformComposeAsync(EmailMessage message) - { - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.Compose, - Uri = "mailto:", - }; - - if (message.Bcc?.Count > 0) - appControl.ExtraData.Add(AppControlData.Bcc, message.Bcc); - if (!string.IsNullOrEmpty(message.Body)) - appControl.ExtraData.Add(AppControlData.Text, message.Body); - if (message.Cc?.Count > 0) - appControl.ExtraData.Add(AppControlData.Cc, message.Cc); - if (!string.IsNullOrEmpty(message.Subject)) - appControl.ExtraData.Add(AppControlData.Subject, message.Subject); - if (message.To?.Count > 0) - appControl.ExtraData.Add(AppControlData.To, message.To); - - AppControl.SendLaunchRequest(appControl); - - return Task.CompletedTask; - } - - public Task ComposeAsync(string subject, string body, params string[] to) - => ComposeAsync( - new EmailMessage - { - Subject = subject, - Body = body, - To = to.ToList() - }); - - public Task ComposeAsync() - => ComposeAsync(null); - } -} diff --git a/src/Maui.Tizen.Essentials/Email/TizenEmail.cs b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs new file mode 100644 index 00000000..0dc7cb7f --- /dev/null +++ b/src/Maui.Tizen.Essentials/Email/TizenEmail.cs @@ -0,0 +1,96 @@ +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. + /// + /// 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) + { + var attachments = CreateAttachmentPayload(message.Attachments); + if (attachments.Paths.Count > 0) + { + appControl.Mime = attachments.Mime; + appControl.ExtraData.Add(TizenAppControlData.Path, attachments.Paths); + } + + 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; + } + + 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), + validAttachments.Select(attachment => attachment.FullPath).ToArray()); + } + + /// + /// 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/FilePicker.tizen.cs b/src/Maui.Tizen.Essentials/FilePicker/FilePicker.tizen.cs deleted file mode 100644 index a96aa2e4..00000000 --- a/src/Maui.Tizen.Essentials/FilePicker/FilePicker.tizen.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Microsoft.Maui.Devices; -using Tizen; -using Tizen.Applications; - -namespace Microsoft.Maui.Storage -{ - partial class FilePickerImplementation : IFilePicker - { - async Task> PlatformPickAsync(PickOptions options, bool allowMultiple = false) - { - Permissions.EnsureDeclared(); - await Permissions.EnsureGrantedAsync(); - - var tcs = new TaskCompletionSource>(); - - var appControl = new AppControl(); - appControl.Operation = AppControlOperations.Pick; - appControl.ExtraData.Add(AppControlData.SectionMode, allowMultiple ? "multiple" : "single"); - appControl.LaunchMode = AppControlLaunchMode.Single; - - var fileType = options?.FileTypes?.Value?.FirstOrDefault(); - appControl.Mime = fileType ?? FileMimeTypes.All; - - var fileResults = new List(); - - AppControl.SendLaunchRequest(appControl, (request, reply, result) => - { - if (result == AppControlReplyResult.Succeeded) - { - if (reply.ExtraData.Any()) - { - var selectedFiles = reply.ExtraData.Get>(AppControlData.Selected).ToList(); - fileResults.AddRange(selectedFiles.Select(f => new FileResult(f))); - } - } - - tcs.TrySetResult(fileResults); - }); - - return await tcs.Task; - } - } - - public partial class FilePickerFileType - { - static FilePickerFileType PlatformImageFileType() => - new FilePickerFileType(new Dictionary> - { - { DevicePlatform.Tizen, new[] { FileMimeTypes.ImageAll } }, - }); - - static FilePickerFileType PlatformPngFileType() => - new FilePickerFileType(new Dictionary> - { - { DevicePlatform.Tizen, new[] { FileMimeTypes.ImagePng } } - }); - - static FilePickerFileType PlatformJpegFileType() => - new FilePickerFileType(new Dictionary> - { - { DevicePlatform.Tizen, new[] { FileMimeTypes.ImageJpg } } - }); - - static FilePickerFileType PlatformVideoFileType() => - new FilePickerFileType(new Dictionary> - { - { DevicePlatform.Tizen, new[] { FileMimeTypes.VideoAll } } - }); - - static FilePickerFileType PlatformPdfFileType() => - new FilePickerFileType(new Dictionary> - { - { DevicePlatform.Tizen, new[] { FileMimeTypes.Pdf } } - }); - } -} diff --git a/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs b/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs new file mode 100644 index 00000000..c97a3954 --- /dev/null +++ b/src/Maui.Tizen.Essentials/FilePicker/TizenFilePicker.cs @@ -0,0 +1,105 @@ +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 appControl = new TizenAppControl + { + Operation = TizenAppControlOperations.Pick, + LaunchMode = TizenAppControlLaunchMode.Single, + Mime = ResolveMimeType(options), + }; + appControl.ExtraData.Add(TizenAppControlData.SectionMode, allowMultiple ? "multiple" : "single"); + + return await TizenAppControlReply.RunAsync>( + callback => TizenAppControl.SendLaunchRequest( + appControl, + TizenAppControlReply.NativeTimeoutMilliseconds, + (_, reply, result) => callback(reply, result)), + static (reply, result) => + { + if (result != TizenAppControlReplyResult.Succeeded || + !reply.ExtraData.TryGet( + TizenAppControlData.Selected, + out IEnumerable selected) || + selected is null) + { + return []; + } + + return selected + .Where(static path => !string.IsNullOrWhiteSpace(path)) + .Select(static path => new FileResult(path)) + .ToArray(); + }).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/FileSystem.tizen.cs b/src/Maui.Tizen.Essentials/FileSystem/FileSystem.tizen.cs deleted file mode 100644 index 5d96213e..00000000 --- a/src/Maui.Tizen.Essentials/FileSystem/FileSystem.tizen.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.Applications; - -namespace Microsoft.Maui.Storage -{ - partial class FileSystemImplementation : IFileSystem - { - string PlatformCacheDirectory - => Application.Current.DirectoryInfo.Cache; - - string PlatformAppDataDirectory - => Application.Current.DirectoryInfo.Data; - - Task PlatformOpenAppPackageFileAsync(string filename) - { - var file = PlatformGetFullAppPackageFilePath(filename); - return Task.FromResult((Stream)File.OpenRead(file)); - } - - Task PlatformAppPackageFileExistsAsync(string filename) - { - var file = PlatformGetFullAppPackageFilePath(filename); - return Task.FromResult(File.Exists(file)); - } - - static string PlatformGetFullAppPackageFilePath(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentNullException(nameof(filename)); - - filename = NormalizePath(filename); - - return Path.Combine(Application.Current.DirectoryInfo.Resource, filename); - } - - static string NormalizePath(string filename) => - filename.Replace('\\', Path.DirectorySeparatorChar); - } - - public partial class FileBase - { - string PlatformGetContentType(string extension) - { - extension = extension.TrimStart('.'); - return Tizen.Content.MimeType.MimeUtil.GetMimeType(extension); - } - - void PlatformInit(FileBase file) - { - } - - internal virtual async Task PlatformOpenReadAsync() - { - await Permissions.RequestAsync(); - - var stream = File.Open(FullPath, FileMode.Open, FileAccess.Read); - return Task.FromResult(stream).Result; - } - } -} 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/Flashlight.tizen.cs b/src/Maui.Tizen.Essentials/Flashlight/Flashlight.tizen.cs deleted file mode 100644 index fbc6614d..00000000 --- a/src/Maui.Tizen.Essentials/Flashlight/Flashlight.tizen.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.System; - -namespace Microsoft.Maui.Devices -{ - class FlashlightImplementation : IFlashlight - { - internal static bool IsSupported - => PlatformUtils.GetFeatureInfo("camera.back.flash"); - - /// - /// Checks if the flashlight is available and can be turned on or off. - /// - /// when the flashlight is available, or when not - public Task IsSupportedAsync() => Task.FromResult(IsSupported); - - public Task TurnOnAsync() - { - return SwitchFlashlight(true); - } - - public Task TurnOffAsync() - { - return SwitchFlashlight(false); - } - - Task SwitchFlashlight(bool switchOn) - { - Permissions.EnsureDeclared(); - return Task.Run(() => - { - if (!IsSupported) - throw new FeatureNotSupportedException(); - - if (switchOn) - Led.Brightness = Led.MaxBrightness; - else - Led.Brightness = 0; - }); - } - } -} 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/Geocoding.tizen.cs b/src/Maui.Tizen.Essentials/Geocoding/Geocoding.tizen.cs deleted file mode 100644 index 9020f1c2..00000000 --- a/src/Maui.Tizen.Essentials/Geocoding/Geocoding.tizen.cs +++ /dev/null @@ -1,64 +0,0 @@ -#pragma warning disable CS0618 // Type or member is obsolete -#nullable enable -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; - -namespace Microsoft.Maui.Devices.Sensors -{ - class GeocodingImplementation : IPlatformGeocoding - { - public string? MapServiceToken { get; set; } - - public async Task> GetPlacemarksAsync(double latitude, double longitude) - { - ValidateMapServiceToken(); - - Permissions.EnsureDeclared(); - - var map = await PlatformUtils.GetMapServiceAsync(MapServiceToken); - var request = map.CreateReverseGeocodeRequest(latitude, longitude); - - var list = new List(); - foreach (var address in await request.GetResponseAsync()) - { - list.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 list; - } - - public async Task> GetLocationsAsync(string address) - { - ValidateMapServiceToken(); - - Permissions.EnsureDeclared(); - - var map = await PlatformUtils.GetMapServiceAsync(MapServiceToken); - var request = map.CreateGeocodeRequest(address); - var list = new List(); - foreach (var position in await request.GetResponseAsync()) - list.Add(new Location(position.Latitude, position.Longitude)); - return list; - } - - void ValidateMapServiceToken() - { - if (string.IsNullOrWhiteSpace(MapServiceToken) && string.IsNullOrWhiteSpace(MapServiceToken)) - throw new ArgumentNullException(nameof(MapServiceToken), "Please set the map service token to be able to use this API."); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs b/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs new file mode 100644 index 00000000..6ebb3f15 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Geocoding/TizenGeocoding.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Tizen implementation of . + /// + /// + /// + /// Unsupported on the targeted Tizen surface. The in-box dotnet/maui Tizen backend + /// implemented geocoding with Tizen.Maps (the HERE-backed MapService). That API + /// was deprecated in TizenFX API11 and removed entirely by API15, which is the + /// reference pack this repository targets: Samsung.Tizen.Ref.API15 ships no + /// Tizen.Maps.dll. Tizen offers no replacement geocoding service, so there is nothing + /// left to call. + /// + /// + /// Both operations therefore throw rather than + /// returning an empty result set, which a caller could not distinguish from "this address + /// matched nothing". + /// + /// + /// deliberately does not throw. The .NET 11 Essentials DI + /// bridge reads and writes it during MauiApp initialization when an app calls + /// ConfigureEssentials(e => e.UseMapServiceToken(...)); throwing there would turn a + /// configuration line into a startup crash. The token is accepted and simply never used. + /// + /// + public sealed class TizenGeocoding : IPlatformGeocoding + { + const string Reason = + "Tizen.Maps (MapService) was deprecated in TizenFX API11 and removed by API15, and " + + "Tizen ships no replacement geocoding service. Register a cross-platform geocoding " + + "client as IGeocoding instead."; + + /// + /// + /// Accepted and retained so that a configured map service token does not fail application + /// startup, but never used: there is no Tizen map service left to authenticate against. + /// + public string? MapServiceToken { get; set; } + + /// + /// Always thrown. + public Task> GetPlacemarksAsync(double latitude, double longitude) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IGeocoding)}.{nameof(GetPlacemarksAsync)}", Reason); + + /// + /// Always thrown. + public Task> GetLocationsAsync(string address) => + throw TizenEssentialsSupport.NotSupported($"{nameof(IGeocoding)}.{nameof(GetLocationsAsync)}", Reason); + } +} diff --git a/src/Maui.Tizen.Essentials/Geolocation/Geolocation.tizen.cs b/src/Maui.Tizen.Essentials/Geolocation/Geolocation.tizen.cs deleted file mode 100644 index ae20d783..00000000 --- a/src/Maui.Tizen.Essentials/Geolocation/Geolocation.tizen.cs +++ /dev/null @@ -1,82 +0,0 @@ -#nullable enable -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.Location; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class GeolocationImplementation : IGeolocation - { - Location lastKnownLocation = new Location(); - - public bool IsListeningForeground { get => false; } - - public bool IsEnabled { get => false; } - - public Task GetLastKnownLocationAsync() => Task.FromResult(lastKnownLocation); - - public async Task GetLocationAsync(GeolocationRequest request, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(request); - - await Permissions.EnsureGrantedAsync(); - - Locator? service = null; - var gps = PlatformUtils.GetFeatureInfo("location.gps"); - var wps = PlatformUtils.GetFeatureInfo("location.wps"); - if (gps) - { - if (wps) - service = new Locator(LocationType.Hybrid); - else - service = new Locator(LocationType.Gps); - } - else - { - if (wps) - service = new Locator(LocationType.Wps); - else - service = new Locator(LocationType.Passive); - } - - var tcs = new TaskCompletionSource(); - - cancellationToken = Utils.TimeoutToken(cancellationToken, request.Timeout); - cancellationToken.Register(() => - { - service?.Stop(); - tcs.TrySetResult(false); - }); - - double KmToMetersPerSecond(double km) => km * 0.277778; - service.LocationChanged += (s, e) => - { - if (e.Location != null) - { - lastKnownLocation.Accuracy = e.Location.Accuracy; - lastKnownLocation.Altitude = e.Location.Altitude; - lastKnownLocation.Course = e.Location.Direction; - lastKnownLocation.Latitude = e.Location.Latitude; - lastKnownLocation.Longitude = e.Location.Longitude; - lastKnownLocation.Speed = KmToMetersPerSecond(e.Location.Speed); - lastKnownLocation.Timestamp = e.Location.Timestamp; - } - service?.Stop(); - tcs.TrySetResult(true); - }; - service.Start(); - - await tcs.Task; - - return lastKnownLocation; - } - - public Task StartListeningForegroundAsync(GeolocationListeningRequest request) => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public void StopListeningForeground() => - throw ExceptionUtils.NotSupportedOrImplementedException; - } -} diff --git a/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs new file mode 100644 index 00000000..9d2fb6d9 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Geolocation/TizenGeolocation.cs @@ -0,0 +1,185 @@ +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 TizenLocatorHelper = Tizen.Location.LocatorHelper; +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 => IsLocationEnabled( + () => TizenSystemInformation.GetFeatureInfo("location.gps"), + () => TizenSystemInformation.GetFeatureInfo("location.wps"), + TizenLocatorHelper.IsEnabledType); + + /// + /// 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 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/Gyroscope/Gyroscope.tizen.cs b/src/Maui.Tizen.Essentials/Gyroscope/Gyroscope.tizen.cs deleted file mode 100644 index 980b56c8..00000000 --- a/src/Maui.Tizen.Essentials/Gyroscope/Gyroscope.tizen.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenGyroscope = Tizen.Sensor.Gyroscope; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class GyroscopeImplementation : IGyroscope - { - static TizenGyroscope DefaultSensor => - (TizenGyroscope)PlatformUtils.GetDefaultSensor(SensorType.Gyroscope); - - bool PlatformIsSupported => - TizenGyroscope.IsSupported; - - TizenGyroscope sensor; - - void PlatformStart(SensorSpeed sensorSpeed) - { - sensor = DefaultSensor; - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += DataUpdated; - sensor.Start(); - } - - void PlatformStop() - { - sensor.DataUpdated -= DataUpdated; - sensor.Stop(); - sensor = null; - } - - void DataUpdated(object sender, GyroscopeDataUpdatedEventArgs e) - { - RaiseReadingChanged(new GyroscopeData(e.X, e.Y, e.Z)); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs b/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs new file mode 100644 index 00000000..84d2c1c3 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Gyroscope/TizenGyroscope.cs @@ -0,0 +1,37 @@ +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 Action Subscribe(TizenGyroscopeSensor sensor, long generation) + { + EventHandler handler = + (sender, e) => Raise( + generation, + ReadingChanged, + new GyroscopeChangedEventArgs(new GyroscopeData(e.X, e.Y, e.Z))); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } + } +} diff --git a/src/Maui.Tizen.Essentials/HapticFeedback/HapticFeedback.tizen.cs b/src/Maui.Tizen.Essentials/HapticFeedback/HapticFeedback.tizen.cs deleted file mode 100644 index 81057e07..00000000 --- a/src/Maui.Tizen.Essentials/HapticFeedback/HapticFeedback.tizen.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Diagnostics; -using Microsoft.Maui.ApplicationModel; -using Tizen.System; - -namespace Microsoft.Maui.Devices -{ - partial class HapticFeedbackImplementation : IHapticFeedback - { - public bool IsSupported => true; - - public void Perform(HapticFeedbackType type) - { - Permissions.EnsureDeclared(); - try - { - var feedback = new Feedback(); - var pattern = ConvertType(type); - if (feedback.IsSupportedPattern(FeedbackType.Vibration, pattern)) - feedback.Play(FeedbackType.Vibration, pattern); - } - catch (Exception ex) - { - Debug.WriteLine($"HapticFeedback Exception: {ex.Message}"); - } - } - - static string ConvertType(HapticFeedbackType type) => - type switch - { - HapticFeedbackType.LongPress => "Hold", - _ => "Tap" - }; - } -} 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..efe0b6b2 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Hosting/TizenEssentialsMauiAppBuilderExtensions.cs @@ -0,0 +1,159 @@ +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 platform service replaces MAUI's neutral registration. This is required when the + /// method is reached from UseMauiAppTizenControls, because UseMauiApp has + /// already registered the neutral Essentials defaults. An application can replace an + /// individual implementation after configuring the Tizen backend. + /// + /// + /// 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); + + // 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; + } + + /// + /// 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 + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Communication + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Data transfer + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Storage + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Device + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Sensors + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Location + ReplaceSingleton(services); + services.Replace(ServiceDescriptor.Singleton( + static sp => sp.GetRequiredService())); + services.Replace(ServiceDescriptor.Singleton( + static sp => sp.GetRequiredService())); + ReplaceSingleton(services); + + // Networking + ReplaceSingleton(services); + + // Media + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + // Accessibility + ReplaceSingleton(services); + + // Authentication + ReplaceSingleton(services); + ReplaceSingleton(services); + ReplaceSingleton(services); + + return services; + } + + static void ReplaceSingleton(IServiceCollection services) + where TService : class + where TImplementation : class, TService => + services.Replace(ServiceDescriptor.Singleton()); + } +} diff --git a/src/Maui.Tizen.Essentials/Launcher/Launcher.tizen.cs b/src/Maui.Tizen.Essentials/Launcher/Launcher.tizen.cs deleted file mode 100644 index ac34d43d..00000000 --- a/src/Maui.Tizen.Essentials/Launcher/Launcher.tizen.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.Maui.Storage; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel -{ - partial class LauncherImplementation - { - Task PlatformCanOpenAsync(Uri uri) - => Task.FromResult(uri.IsWellFormedOriginalString()); - - Task PlatformOpenAsync(Uri uri) - { - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.ShareText, - Uri = uri.AbsoluteUri - }; - - if (uri.AbsoluteUri.StartsWith("geo:")) - appControl.Operation = AppControlOperations.Pick; - else if (uri.AbsoluteUri.StartsWith("http")) - appControl.Operation = AppControlOperations.View; - else if (uri.AbsoluteUri.StartsWith("mailto:")) - appControl.Operation = AppControlOperations.Compose; - else if (uri.AbsoluteUri.StartsWith("sms:")) - appControl.Operation = AppControlOperations.Compose; - else if (uri.AbsoluteUri.StartsWith("tel:")) - appControl.Operation = AppControlOperations.Dial; - - AppControl.SendLaunchRequest(appControl); - - return Task.FromResult(true); - } - - Task PlatformOpenAsync(OpenFileRequest request) - { - if (string.IsNullOrEmpty(request.File.FullPath)) - throw new ArgumentNullException(nameof(request.File.FullPath)); - - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.View, - Mime = FileMimeTypes.All, - Uri = "file://" + request.File.FullPath, - }; - - AppControl.SendLaunchRequest(appControl); - - return Task.FromResult(true); - } - - async Task PlatformTryOpenAsync(Uri uri) - { - var canOpen = await PlatformCanOpenAsync(uri); - - if (canOpen) - await PlatformOpenAsync(uri); - - return canOpen; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs new file mode 100644 index 00000000..201baa75 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Launcher/TizenLauncher.cs @@ -0,0 +1,153 @@ +using System; +using System.Linq; +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 + { + /// + /// + /// 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); + + if (!uri.IsAbsoluteUri || !uri.IsWellFormedOriginalString()) + return Task.FromResult(false); + + return Task.FromResult(HasHandler(CreateAppControl(uri))); + } + + /// + public Task OpenAsync(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + TizenPermissions.EnsureDeclared(); + + TizenAppControl.SendLaunchRequest(CreateAppControl(uri)); + + return Task.FromResult(true); + } + + /// + public Task OpenAsync(OpenFileRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + TizenPermissions.EnsureDeclared(); + + var appControl = CreateOpenFileAppControl(request); + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(true); + } + + internal static TizenAppControl CreateOpenFileAppControl(OpenFileRequest request) + { + var payload = CreateOpenFilePayload(request); + + return new TizenAppControl + { + Operation = payload.Operation, + Mime = payload.Mime, + Uri = payload.Uri, + }; + } + + internal static TizenOpenFilePayload CreateOpenFilePayload(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)); + + return new( + TizenAppControlOperations.View, + TizenShare.ResolveMime(request.File) ?? TizenFileMimeTypes.All, + "file://" + request.File.FullPath); + } + + /// + /// + /// Returns when nothing on the device handles the URI, rather than + /// letting the launch attempt throw. + /// + public Task TryOpenAsync(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); + + if (!uri.IsAbsoluteUri || !uri.IsWellFormedOriginalString()) + return Task.FromResult(false); + + TizenPermissions.EnsureDeclared(); + + var appControl = CreateAppControl(uri); + + if (!HasHandler(appControl)) + return Task.FromResult(false); + + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(true); + } + + static TizenAppControl CreateAppControl(Uri uri) => + new() + { + Operation = GetOperation(uri), + Uri = uri.AbsoluteUri, + }; + + internal static bool HasHandler(TizenAppControl appControl) => + HasHandler(() => TizenAppControl.GetMatchedApplicationIds(appControl)); + + internal static bool HasHandler(Func?> getMatches) + { + try + { + return getMatches()?.Any() == true; + } + 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; + } + } + + internal static string GetOperation(Uri uri) + { + var absoluteUri = uri.AbsoluteUri; + + if (absoluteUri.StartsWith("geo:", StringComparison.OrdinalIgnoreCase)) + return TizenAppControlOperations.View; + 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.View; + } + + internal sealed record TizenOpenFilePayload(string Operation, string Mime, string Uri); + } +} diff --git a/src/Maui.Tizen.Essentials/Magnetometer/Magnetometer.tizen.cs b/src/Maui.Tizen.Essentials/Magnetometer/Magnetometer.tizen.cs deleted file mode 100644 index 2bf6c44c..00000000 --- a/src/Maui.Tizen.Essentials/Magnetometer/Magnetometer.tizen.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenMagnetometer = Tizen.Sensor.Magnetometer; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class MagnetometerImplementation : IMagnetometer - { - static TizenMagnetometer DefaultSensor => - (TizenMagnetometer)PlatformUtils.GetDefaultSensor(SensorType.Magnetometer); - - bool PlatformIsSupported => - TizenMagnetometer.IsSupported; - - TizenMagnetometer sensor; - - void PlatformStart(SensorSpeed sensorSpeed) - { - sensor = DefaultSensor; - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += DataUpdated; - sensor.Start(); - } - - void PlatformStop() - { - sensor.DataUpdated -= DataUpdated; - sensor.Stop(); - sensor = null; - } - - void DataUpdated(object sender, MagnetometerDataUpdatedEventArgs e) - { - RaiseReadingChanged(new MagnetometerData(e.X, e.Y, e.Z)); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs b/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs new file mode 100644 index 00000000..1f93f989 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Magnetometer/TizenMagnetometer.cs @@ -0,0 +1,37 @@ +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 Action Subscribe(TizenMagnetometerSensor sensor, long generation) + { + EventHandler handler = + (sender, e) => Raise( + generation, + ReadingChanged, + new MagnetometerChangedEventArgs(new MagnetometerData(e.X, e.Y, e.Z))); + sensor.DataUpdated += handler; + return () => sensor.DataUpdated -= handler; + } + } +} diff --git a/src/Maui.Tizen.Essentials/MainThread/MainThread.tizen.cs b/src/Maui.Tizen.Essentials/MainThread/MainThread.tizen.cs deleted file mode 100644 index 99eb7576..00000000 --- a/src/Maui.Tizen.Essentials/MainThread/MainThread.tizen.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using ElmSharp; - -namespace Microsoft.Maui.ApplicationModel -{ - public static partial class MainThread - { - static void PlatformBeginInvokeOnMainThread(Action action) - { - if (PlatformIsMainThread) - action(); - else - EcoreMainloop.PostAndWakeUp(action); - } - - static bool PlatformIsMainThread - => EcoreMainloop.IsMainThread; - } -} diff --git a/src/Maui.Tizen.Essentials/Map/Map.tizen.cs b/src/Maui.Tizen.Essentials/Map/Map.tizen.cs deleted file mode 100644 index 50807dfe..00000000 --- a/src/Maui.Tizen.Essentials/Map/Map.tizen.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Maui.Devices.Sensors; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel -{ - class MapImplementation : IMap - { - public Task OpenAsync(double latitude, double longitude, MapLaunchOptions options) - { - var appControl = GetAppControlData(latitude, longitude, options); - return Launch(appControl); - } - - public Task OpenAsync(Placemark placemark, MapLaunchOptions options) - { - var appControl = GetAppControlData(placemark, options); - return Launch(appControl); - } - - public Task TryOpenAsync(double latitude, double longitude, MapLaunchOptions options) - { - var appControl = GetAppControlData(latitude, longitude, options); - return TryLaunch(appControl); - } - - public Task TryOpenAsync(Placemark placemark, MapLaunchOptions options) - { - var appControl = GetAppControlData(placemark, options); - return TryLaunch(appControl); - } - - internal static AppControl GetAppControlData(double latitude, double longitude, MapLaunchOptions options) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); - - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.View, - Uri = "geo:", - }; - - appControl.Uri += $"{latitude.ToString(CultureInfo.InvariantCulture)},{longitude.ToString(CultureInfo.InvariantCulture)}"; - - return appControl; - } - - internal static AppControl GetAppControlData(Placemark placemark, MapLaunchOptions options) - { - if (placemark == null) - throw new ArgumentNullException(nameof(placemark)); - - if (options == null) - throw new ArgumentNullException(nameof(options)); - - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.Pick, - Uri = "geo:", - }; - - appControl.Uri += $"0,0?q={placemark.GetEscapedAddress()}"; - return appControl; - } - - internal static Task Launch(AppControl appControl) - { - AppControl.SendLaunchRequest(appControl); - - return Task.CompletedTask; - } - - internal static Task TryLaunch(AppControl appControl) - { - var canLaunch = AppControl.GetMatchedApplicationIds(appControl).Any(); - - if (canLaunch) - { - Launch(appControl); - } - - return Task.FromResult(canLaunch); - } - } -} diff --git a/src/Maui.Tizen.Essentials/Map/TizenMap.cs b/src/Maui.Tizen.Essentials/Map/TizenMap.cs new file mode 100644 index 00000000..8d8352d7 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Map/TizenMap.cs @@ -0,0 +1,91 @@ +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) + { + var request = CreatePlacemarkRequest(placemark, options); + + TizenPermissions.EnsureDeclared(); + + return new TizenAppControl + { + 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); + return Task.CompletedTask; + } + + static Task TryLaunch(TizenAppControl appControl) + { + var canLaunch = TizenLauncher.HasHandler(appControl); + + if (canLaunch) + TizenAppControl.SendLaunchRequest(appControl); + + return Task.FromResult(canLaunch); + } + + internal sealed record TizenMapRequest(string Operation, string Uri); + } +} diff --git a/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj b/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj index df2e5adb..6965657d 100644 --- a/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj +++ b/src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj @@ -1,12 +1,47 @@ + + + true + $(DefineConstants);TIZEN_API15 + + + - Microsoft.Maui.ApplicationModel + Microsoft.Maui.Platforms.Tizen.Essentials Tizen platform implementation for .NET MAUI Essentials: sensors, device info, connectivity, storage, media, and application model APIs. + + + false + true + true + true + + + true + + + + + + + + + + + + true + + + + + + + + + + + diff --git a/src/Maui.Tizen.Essentials/MediaPicker/MediaPicker.tizen.cs b/src/Maui.Tizen.Essentials/MediaPicker/MediaPicker.tizen.cs deleted file mode 100644 index 3f0d2c41..00000000 --- a/src/Maui.Tizen.Essentials/MediaPicker/MediaPicker.tizen.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Microsoft.Maui.Storage; -using Tizen.Applications; - -namespace Microsoft.Maui.Media -{ - partial class MediaPickerImplementation : IMediaPicker - { - public bool IsCaptureSupported - => true; - - public async Task PickPhotoAsync(MediaPickerOptions options) - => await FilePicker.PickAsync(new PickOptions - { - PickerTitle = options?.Title, - FileTypes = FilePickerFileType.Images - }); - - public Task CapturePhotoAsync(MediaPickerOptions options) - => MediaAsync(options, true); - - public async Task PickVideoAsync(MediaPickerOptions options) - => await FilePicker.PickAsync(new PickOptions - { - PickerTitle = options?.Title, - FileTypes = FilePickerFileType.Videos - }); - - public Task CaptureVideoAsync(MediaPickerOptions options) - => MediaAsync(options, false); - - public async Task MediaAsync(MediaPickerOptions options, bool photo) - { - Permissions.EnsureDeclared(); - - await Permissions.EnsureGrantedAsync(); - - var tcs = new TaskCompletionSource(); - - var appControl = new AppControl(); - appControl.Operation = photo ? AppControlOperations.ImageCapture : AppControlOperations.VideoCapture; - appControl.LaunchMode = AppControlLaunchMode.Group; - - var appId = AppControl.GetMatchedApplicationIds(appControl)?.FirstOrDefault(); - - if (!string.IsNullOrEmpty(appId)) - appControl.ApplicationId = appId; - - AppControl.SendLaunchRequest(appControl, (request, reply, result) => - { - if (result == AppControlReplyResult.Succeeded && reply.ExtraData.Any()) - { - var file = reply.ExtraData.Get>(AppControlData.Selected)?.FirstOrDefault(); - tcs.TrySetResult(new FileResult(file)); - } - else - { - tcs.TrySetCanceled(); - } - }); - - return await tcs.Task; - } - } -} diff --git a/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs new file mode 100644 index 00000000..d9bce58f --- /dev/null +++ b/src/Maui.Tizen.Essentials/MediaPicker/TizenMediaPicker.cs @@ -0,0 +1,110 @@ +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 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; + + return await TizenAppControlReply.RunAsync( + callback => TizenAppControl.SendLaunchRequest( + appControl, + TizenAppControlReply.NativeTimeoutMilliseconds, + (_, reply, result) => callback(reply, result)), + static (reply, result) => + { + if (result != TizenAppControlReplyResult.Succeeded || + !reply.ExtraData.TryGet( + TizenAppControlData.Selected, + out IEnumerable selected)) + { + return null; + } + + var file = selected?.FirstOrDefault(); + return string.IsNullOrWhiteSpace(file) ? null : new FileResult(file); + }).ConfigureAwait(false); + } + } +} diff --git a/src/Maui.Tizen.Essentials/OrientationSensor/OrientationSensor.tizen.cs b/src/Maui.Tizen.Essentials/OrientationSensor/OrientationSensor.tizen.cs deleted file mode 100644 index 1c75de99..00000000 --- a/src/Maui.Tizen.Essentials/OrientationSensor/OrientationSensor.tizen.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Sensor; -using TizenRotationVectorSensor = Tizen.Sensor.RotationVectorSensor; - -namespace Microsoft.Maui.Devices.Sensors -{ - partial class OrientationSensorImplementation : IOrientationSensor - { - static TizenRotationVectorSensor DefaultSensor - => (TizenRotationVectorSensor)PlatformUtils.GetDefaultSensor(SensorType.OrientationSensor); - - bool PlatformIsSupported - => TizenRotationVectorSensor.IsSupported; - - TizenRotationVectorSensor sensor; - - void PlatformStart(SensorSpeed sensorSpeed) - { - sensor = DefaultSensor; - - sensor.Interval = sensorSpeed.ToPlatform(); - sensor.DataUpdated += DataUpdated; - sensor.Start(); - } - - void PlatformStop() - { - sensor.DataUpdated -= DataUpdated; - sensor.Stop(); - sensor = null; - } - - void DataUpdated(object sender, RotationVectorSensorDataUpdatedEventArgs e) - { - RaiseReadingChanged(new OrientationSensorData(e.X, e.Y, e.Z, e.W)); - } - } -} diff --git a/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs new file mode 100644 index 00000000..ea535a77 --- /dev/null +++ b/src/Maui.Tizen.Essentials/OrientationSensor/TizenOrientationSensor.cs @@ -0,0 +1,37 @@ +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 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/Passkeys.netstandard.tvos.tizen.cs b/src/Maui.Tizen.Essentials/Passkeys/Passkeys.netstandard.tvos.tizen.cs deleted file mode 100644 index 3348d880..00000000 --- a/src/Maui.Tizen.Essentials/Passkeys/Passkeys.netstandard.tvos.tizen.cs +++ /dev/null @@ -1,17 +0,0 @@ -#nullable enable -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; - -namespace Microsoft.Maui.Authentication; - -partial class PasskeysImplementation : IPasskeys -{ - public bool IsSupported => false; - - public Task CreateAsync(PasskeyCreationOptions options, CancellationToken cancellationToken = default) - => throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task AssertAsync(PasskeyRequestOptions options, CancellationToken cancellationToken = default) - => throw ExceptionUtils.NotSupportedOrImplementedException; -} diff --git a/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs new file mode 100644 index 00000000..42bfe805 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Passkeys/TizenPasskeys.cs @@ -0,0 +1,70 @@ +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 . + /// + /// + /// 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 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 + { + 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. + 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/Permissions.tizen.cs b/src/Maui.Tizen.Essentials/Permissions/Permissions.tizen.cs deleted file mode 100644 index de00d195..00000000 --- a/src/Maui.Tizen.Essentials/Permissions/Permissions.tizen.cs +++ /dev/null @@ -1,255 +0,0 @@ -#pragma warning disable CS0618 // Type or member is obsolete -using System.Linq; -using System.Threading.Tasks; -using Tizen.Security; - -namespace Microsoft.Maui.ApplicationModel -{ - public static partial class Permissions - { - /// - /// Checks if the key specified in is declared in the application's tizen-manifest.xml file. - /// - /// The key to check for declaration in the tizen-manifest.xml file. - /// when the key is declared, otherwise . - public static bool IsPrivilegeDeclared(string tizenPrivilege) - { - var tizenPrivileges = tizenPrivilege; - - if (tizenPrivileges == null || !tizenPrivileges.Any()) - return false; - - var package = Platform.CurrentPackage; - - if (!package.Privileges.Contains(tizenPrivilege)) - return false; - - return true; - } - - /// - public abstract partial class BasePlatformPermission : BasePermission - { - /// - /// Gets the required entries that need to be present in the application's tizen-manifest.xml file for this permission. - /// - public virtual (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges { get; } - - /// - public override Task CheckStatusAsync() - => CheckPrivilegeAsync(false); - - /// - public override Task RequestAsync() - => CheckPrivilegeAsync(true); - - async Task CheckPrivilegeAsync(bool ask) - { - if (RequiredPrivileges == null || !RequiredPrivileges.Any()) - return PermissionStatus.Granted; - - EnsureDeclared(); - - var tizenPrivileges = RequiredPrivileges.Where(p => p.isRuntime); - - foreach (var (tizenPrivilege, isRuntime) in tizenPrivileges) - { - var checkResult = PrivacyPrivilegeManager.CheckPermission(tizenPrivilege); - if (checkResult == CheckResult.Ask) - { - if (ask) - { - var tcs = new TaskCompletionSource(); - PrivacyPrivilegeManager.GetResponseContext(tizenPrivilege) - .TryGetTarget(out var context); - void OnResponseFetched(object sender, RequestResponseEventArgs e) - { - tcs.TrySetResult(e.result == RequestResult.AllowForever); - } - context.ResponseFetched += OnResponseFetched; - PrivacyPrivilegeManager.RequestPermission(tizenPrivilege); - var result = await tcs.Task; - context.ResponseFetched -= OnResponseFetched; - if (result) - continue; - } - return PermissionStatus.Denied; - } - else if (checkResult == CheckResult.Deny) - { - return PermissionStatus.Denied; - } - } - return PermissionStatus.Granted; - } - - /// - public override void EnsureDeclared() - { - if (RequiredPrivileges == null) - return; - - foreach (var (tizenPrivilege, isRuntime) in RequiredPrivileges) - { - if (!IsPrivilegeDeclared(tizenPrivilege)) - throw new PermissionException($"You need to declare the privilege: `{tizenPrivilege}` in your tizen-manifest.xml"); - } - } - - /// - public override bool ShouldShowRationale() => false; - } - - public partial class Battery : BasePlatformPermission - { - } - - public partial class Bluetooth : BasePlatformPermission - { - } - - public partial class CalendarRead : BasePlatformPermission - { - } - - public partial class CalendarWrite : BasePlatformPermission - { - } - - public partial class Camera : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/camera", false) }; - } - - public partial class ContactsRead : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/contact.read", true) }; - } - - public partial class ContactsWrite : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/contact.write", true) }; - } - - public partial class Flashlight : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/led", false) }; - } - - public partial class LaunchApp : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/appmanager.launch", false) }; - } - - public partial class LocationWhenInUse : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/location", true) }; - } - - public partial class LocationAlways : LocationWhenInUse - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/location", true) }; - } - - public partial class Maps : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] - { - ("http://tizen.org/privilege/internet", false), - ("http://tizen.org/privilege/mapservice", false), - ("http://tizen.org/privilege/network.get", false) - }; - } - - public partial class Media : BasePlatformPermission - { - } - - public partial class Microphone : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/recorder", false) }; - } - - public partial class NearbyWifiDevices : BasePlatformPermission - { - } - - public partial class NetworkState : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] - { - ("http://tizen.org/privilege/internet", false), - ("http://tizen.org/privilege/network.get", false) - }; - } - - public partial class Phone : BasePlatformPermission - { - } - - public partial class Photos : BasePlatformPermission - { - } - - public partial class PostNotifications : BasePlatformPermission - { - } - - public partial class Reminders : BasePlatformPermission - { - } - - public partial class Sensors : BasePlatformPermission - { - } - - public partial class Sms : BasePlatformPermission - { - } - - public partial class Speech : BasePlatformPermission - { - } - - public partial class StorageRead : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/mediastorage", true) }; - } - - public partial class StorageWrite : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/mediastorage", true) }; - } - - public partial class Vibrate : BasePlatformPermission - { - /// - public override (string tizenPrivilege, bool isRuntime)[] RequiredPrivileges => - new[] { ("http://tizen.org/privilege/haptic", false) }; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Permissions/TizenPermissionRequestCoordinator.cs b/src/Maui.Tizen.Essentials/Permissions/TizenPermissionRequestCoordinator.cs new file mode 100644 index 00000000..dacb868a --- /dev/null +++ b/src/Maui.Tizen.Essentials/Permissions/TizenPermissionRequestCoordinator.cs @@ -0,0 +1,86 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + internal readonly record struct TizenPermissionResponse( + global::Tizen.Security.CallCause Cause, + global::Tizen.Security.RequestResult Result, + string Privilege); + + internal interface ITizenPermissionRequestSource + { + event Action? Response; + + void Request(); + } + + internal static class TizenPermissionRequestCoordinator + { + public static TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30); + + public static async Task RunAsync( + string privilege, + ITizenPermissionRequestSource source, + CancellationToken cancellationToken = default, + TimeSpan? timeoutOverride = null) + { + ArgumentException.ThrowIfNullOrEmpty(privilege); + ArgumentNullException.ThrowIfNull(source); + cancellationToken.ThrowIfCancellationRequested(); + + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + var settled = 0; + + void OnResponse(TizenPermissionResponse response) + { + if (Interlocked.Exchange(ref settled, 1) != 0) + return; + + try + { + completion.TrySetResult(TizenPermissions.InterpretRequestResponse( + privilege, + response.Cause, + response.Result, + response.Privilege)); + } + 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 did not answer the '{privilege}' permission request within {effectiveTimeout}.")); + }); + + try + { + source.Response += OnResponse; + source.Request(); + return await completion.Task.ConfigureAwait(false); + } + finally + { + source.Response -= OnResponse; + } + } + } +} diff --git a/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs new file mode 100644 index 00000000..b16c8ed5 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Permissions/TizenPermissions.cs @@ -0,0 +1,502 @@ +// 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); + + /// + /// 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. + /// + /// + /// 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 KnownPermissions = + new Dictionary + { + // --------------------------------------------------------------------------- + // 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), + 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.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), + 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."), + }; + + /// + 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 (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 TryGetKnownMapping(Type permissionType, out TizenPermissionMapping mapping) + { + for (var type = permissionType; type is not null; type = type.BaseType) + { + if (KnownPermissions.TryGetValue(type, out mapping)) + return true; + } + + mapping = default; + 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 (!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."); + } + } + + /// + /// 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; + + return await TizenPermissionRequestCoordinator.RunAsync( + privilege, + new TizenPermissionRequestSource(privilege, context)).ConfigureAwait(false); + } + + 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; + } + +#pragma warning disable CS0618 // API15 retains this deprecated API without a replacement. + sealed class TizenPermissionRequestSource : ITizenPermissionRequestSource + { + readonly string _privilege; + readonly global::Tizen.Security.PrivacyPrivilegeManager.ResponseContext _context; + Action? _response; + + public TizenPermissionRequestSource( + string privilege, + global::Tizen.Security.PrivacyPrivilegeManager.ResponseContext context) + { + _privilege = privilege; + _context = context; + } + + public event Action? Response + { + add + { + if (_response is null) + _context.ResponseFetched += OnResponseFetched; + _response += value; + } + remove + { + _response -= value; + if (_response is null) + _context.ResponseFetched -= OnResponseFetched; + } + } + + public void Request() => + TizenPrivacyPrivilegeManager.RequestPermission(_privilege); + + void OnResponseFetched( + object? sender, + global::Tizen.Security.RequestResponseEventArgs e) => + _response?.Invoke(new(e.cause, e.result, e.privilege)); + } +#pragma warning restore CS0618 + } +} diff --git a/src/Maui.Tizen.Essentials/PhoneDialer/PhoneDialer.tizen.cs b/src/Maui.Tizen.Essentials/PhoneDialer/PhoneDialer.tizen.cs deleted file mode 100644 index e4d06f25..00000000 --- a/src/Maui.Tizen.Essentials/PhoneDialer/PhoneDialer.tizen.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.Maui.ApplicationModel; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel.Communication -{ - partial class PhoneDialerImplementation : IPhoneDialer - { - public bool IsSupported - => PlatformUtils.GetFeatureInfo("contact"); - - public void Open(string number) - { - ValidateOpen(number); - - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.Dial, - Uri = "tel:", - }; - - if (!string.IsNullOrEmpty(number)) - appControl.Uri += number; - - AppControl.SendLaunchRequest(appControl); - } - } -} 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/PlatformUtils.tizen.cs b/src/Maui.Tizen.Essentials/Platform/PlatformUtils.tizen.cs deleted file mode 100644 index fa490519..00000000 --- a/src/Maui.Tizen.Essentials/Platform/PlatformUtils.tizen.cs +++ /dev/null @@ -1,95 +0,0 @@ -#pragma warning disable CS0618 // Type or member is obsolete -using System.Threading.Tasks; -using Tizen.Applications; -using Tizen.Maps; -using Tizen.Sensor; -using Tizen.System; -using TizenAccelerometer = Tizen.Sensor.Accelerometer; -using TizenBarometer = Tizen.Sensor.PressureSensor; -using TizenCompass = Tizen.Sensor.OrientationSensor; -using TizenGyroscope = Tizen.Sensor.Gyroscope; -using TizenMagnetometer = Tizen.Sensor.Magnetometer; -using TizenOrientationSensor = Tizen.Sensor.RotationVectorSensor; - -namespace Microsoft.Maui.ApplicationModel -{ - static class PlatformUtils - { - static TizenAccelerometer accelerometer = null; - static TizenBarometer barometer = null; - static TizenCompass compass = null; - static TizenGyroscope gyroscope = null; - static TizenMagnetometer magnetometer = null; - static TizenOrientationSensor orientationSensor = null; - static MapService mapService = null; - - internal static string GetSystemInfo(string item) => GetSystemInfo(item); - - internal static T GetSystemInfo(string item) - { - Information.TryGetValue($"http://tizen.org/system/{item}", out var value); - return value; - } - - internal static string GetFeatureInfo(string item) => GetFeatureInfo(item); - - internal static T GetFeatureInfo(string item) - { - Information.TryGetValue($"http://tizen.org/feature/{item}", out var value); - return value; - } - - internal static Sensor GetDefaultSensor(SensorType type) - { - switch (type) - { - case SensorType.Accelerometer: - if (PlatformUtils.accelerometer == null) - PlatformUtils.accelerometer = new TizenAccelerometer(); - return PlatformUtils.accelerometer; - case SensorType.Barometer: - if (PlatformUtils.barometer == null) - PlatformUtils.barometer = new TizenBarometer(); - return PlatformUtils.barometer; - case SensorType.Compass: - if (PlatformUtils.compass == null) - PlatformUtils.compass = new TizenCompass(); - return PlatformUtils.compass; - case SensorType.Gyroscope: - if (PlatformUtils.gyroscope == null) - PlatformUtils.gyroscope = new TizenGyroscope(); - return PlatformUtils.gyroscope; - case SensorType.Magnetometer: - if (PlatformUtils.magnetometer == null) - PlatformUtils.magnetometer = new TizenMagnetometer(); - return PlatformUtils.magnetometer; - case SensorType.OrientationSensor: - if (PlatformUtils.orientationSensor == null) - PlatformUtils.orientationSensor = new TizenOrientationSensor(); - return PlatformUtils.orientationSensor; - default: - return null; - } - } - - internal static async Task GetMapServiceAsync(string key) - { - if (mapService == null) - { - mapService = new MapService("HERE", key); - await mapService.RequestUserConsent(); - } - return mapService; - } - } - - enum SensorType - { - Accelerometer, - Barometer, - Compass, - Gyroscope, - Magnetometer, - OrientationSensor - } -} 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/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/TizenEventSubscriptionCoordinator.cs b/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs new file mode 100644 index 00000000..d1d0e782 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenEventSubscriptionCoordinator.cs @@ -0,0 +1,181 @@ +using System; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + internal sealed class TizenEventSubscriptionCoordinator : IDisposable + where TEventArgs : EventArgs + { + readonly object _stateLock = new(); + readonly object _transitionLock = new(); + readonly object _sender; + readonly Func, Action> _start; + readonly TizenNativeCallbackCoordinator _callbacks; + EventHandler? _handlers; + Action? _unsubscribe; + long _generation; + bool _disposed; + + public TizenEventSubscriptionCoordinator( + object sender, + Func, Action> start, + TizenNativeCallbackCoordinator? callbacks = null) + { + _sender = sender; + _start = start; + _callbacks = callbacks ?? new TizenNativeCallbackCoordinator(); + } + + public void Add(EventHandler? handler) + { + if (handler is null) + return; + + lock (_transitionLock) + { + long generation; + lock (_stateLock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var start = _handlers is null; + _handlers += handler; + if (!start) + return; + + generation = ++_generation; + } + + Action? unsubscribe = null; + try + { + // 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(new(this, generation)); + lock (_stateLock) + { + if (_disposed || _generation != generation || _handlers is null) + throw new ObjectDisposedException(nameof(TizenEventSubscriptionCoordinator)); + _unsubscribe = unsubscribe; + } + } + catch + { + lock (_stateLock) + { + _handlers -= handler; + _generation++; + _unsubscribe = null; + } + + try + { + unsubscribe?.Invoke(); + } + catch (Exception) + { + // Preserve the startup failure while rolling back a partial subscription. + } + + throw; + } + } + } + + public void Remove(EventHandler? handler) + { + if (handler is null) + return; + + lock (_transitionLock) + { + Action? unsubscribe = null; + lock (_stateLock) + { + _handlers -= handler; + if (_handlers is null && _unsubscribe is not null) + { + _generation++; + unsubscribe = _unsubscribe; + _unsubscribe = null; + } + } + + unsubscribe?.Invoke(); + } + } + + internal void Publish(long generation, TEventArgs args) => + Commit(generation, () => args); + + internal void Commit(long generation, Func createArgs) + { + ArgumentNullException.ThrowIfNull(createArgs); + if (!IsCurrent(generation)) + return; + + _callbacks.Post( + () => IsCurrent(generation), + () => + { + EventHandler? handlers; + TEventArgs args; + lock (_stateLock) + { + if (_disposed || _generation != generation || _handlers is null) + return; + + args = createArgs(); + handlers = _handlers; + } + handlers.Invoke(_sender, args); + }); + } + + bool IsCurrent(long generation) + { + lock (_stateLock) + return !_disposed && _generation == generation && _handlers is not null; + } + + public void Dispose() + { + lock (_transitionLock) + { + Action? unsubscribe; + lock (_stateLock) + { + if (_disposed) + return; + + _disposed = true; + _generation++; + _handlers = null; + unsubscribe = _unsubscribe; + _unsubscribe = null; + } + + unsubscribe?.Invoke(); + } + } + } + + 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/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs b/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs new file mode 100644 index 00000000..0085e6fc --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenNativeCallbackCoordinator.cs @@ -0,0 +1,63 @@ +using System; +using System.Threading; +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.PostDeferred(() => + { + if (isCurrent()) + callback(); + }); + } + } + + internal interface ITizenNativeCallbackDispatcher + { + void PostDeferred(Action action); + } + + sealed class TizenNativeCallbackDispatcher : ITizenNativeCallbackDispatcher + { + public static TizenNativeCallbackDispatcher Instance { get; } = new(); + + public void PostDeferred(Action action) => + PostDeferred( + MainThread.BeginInvokeOnMainThread, + static () => SynchronizationContext.Current, + action); + + internal static void PostDeferred( + Action beginInvoke, + Func getContext, + Action action) + { + beginInvoke(() => + { + var context = getContext() ?? + throw new InvalidOperationException( + "The Tizen main loop has no synchronization context."); + context.Post(static state => ((Action)state!).Invoke(), action); + }); + } + } +} diff --git a/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs new file mode 100644 index 00000000..3c73ea8c --- /dev/null +++ b/src/Maui.Tizen.Essentials/Platform/TizenPlatform.cs @@ -0,0 +1,96 @@ +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 + { + internal static string? CurrentPackageId + { + get + { + try + { + return TizenApplication.Current.ApplicationInfo.PackageId; + } + catch + { + return null; + } + } + } + + /// + /// Gets a with information about the current application package. + /// + public static TizenPackage CurrentPackage + { + get + { + var packageId = CurrentPackageId ?? + throw new InvalidOperationException("The current Tizen package id is unavailable."); + 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/Preferences.tizen.cs b/src/Maui.Tizen.Essentials/Preferences/Preferences.tizen.cs deleted file mode 100644 index a1873241..00000000 --- a/src/Maui.Tizen.Essentials/Preferences/Preferences.tizen.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.Linq; -using Tizen.Applications; - -namespace Microsoft.Maui.Storage -{ - class PreferencesImplementation : IPreferences - { - const string separator = "~"; - - static readonly object locker = new object(); - - public bool ContainsKey(string key, string sharedName) - { - lock (locker) - { - return Preference.Contains(GetFullKey(key, sharedName)); - } - } - - public void Remove(string key, string sharedName) - { - lock (locker) - { - var fullKey = GetFullKey(key, sharedName); - if (Preference.Contains(fullKey)) - Preference.Remove(fullKey); - } - } - - public void Clear(string sharedName) - { - lock (locker) - { - if (string.IsNullOrEmpty(sharedName)) - { - Preference.RemoveAll(); - } - else - { - var keys = Preference.Keys.Where(key => key.StartsWith($"{sharedName}{separator}")).ToList(); - foreach (var key in keys) - Preference.Remove(key); - } - } - } - - public void Set(string key, T value, string sharedName) - { - Preferences.CheckIsSupportedType(); - - lock (locker) - { - var fullKey = GetFullKey(key, sharedName); - if (value == null) - Preference.Remove(fullKey); - else if (value is DateTime dt) - { - Preference.Set(fullKey, dt.ToBinary()); - } - else if (value is DateTimeOffset dto) - { - Preference.Set(fullKey, dto.ToString("O")); - } - else - Preference.Set(fullKey, value); - } - } - - public T Get(string key, T defaultValue, string sharedName) - { - lock (locker) - { - var value = defaultValue; - var fullKey = GetFullKey(key, sharedName); - if (Preference.Contains(fullKey)) - { - switch (defaultValue) - { - case int i: - case bool b: - case long l: - case double d: - case float f: - case string s: - value = Preference.Get(fullKey); - break; - case DateTime dt: - var encodedValue = Preference.Get(fullKey); - value = (T)(object)DateTime.FromBinary(encodedValue); - break; - case DateTimeOffset dt: - var savedDateTimeOffset = Preference.Get(fullKey); - if (DateTimeOffset.TryParse(savedDateTimeOffset, out var dateTimeOffset)) - { - value = (T)(object)dateTimeOffset; - } - break; - default: - // the case when the string is null - if (typeof(T) == typeof(string)) - value = (T)(object)Preference.Get(fullKey); - break; - } - } - return value; - } - } - - static string GetFullKey(string key, string sharedName = null) - { - if (string.IsNullOrEmpty(sharedName)) - return key; - return $"{sharedName}{separator}{key}"; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs new file mode 100644 index 00000000..6da2ec00 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Preferences/TizenPreferences.cs @@ -0,0 +1,387 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +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 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 LongPrefix = "maui-pref:long:v1:"; + const string DateTimePrefix = "maui-pref:datetime:v1:"; + const string DateTimeOffsetPrefix = "maui-pref:datetimeoffset:v1:"; + + 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) + { + ArgumentNullException.ThrowIfNull(key); + + lock (_store.SyncRoot) + { + if (_store.Contains(GetFullKey(key, sharedName))) + return true; + if (LegacyFallbackSuppressed(key, sharedName)) + return false; + + return TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName).Any(_store.Contains); + } + } + + /// + public void Remove(string key, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (_store.SyncRoot) + { + var fullKey = GetFullKey(key, sharedName); + if (_store.Contains(fullKey)) + _store.Remove(fullKey); + + WriteTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); + } + } + + /// + /// + /// 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 (_store.SyncRoot) + { + var prefix = TizenStorageKeyEncoding.GetSharedNamePrefix(sharedName ?? string.Empty); + + foreach (var key in _store.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + _store.Remove(key); + + WriteTombstone(TizenStorageKeyEncoding.GetStoreTombstone(sharedName)); + } + } + + /// + public void Set(string key, T value, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (_store.SyncRoot) + { + SetCore(GetFullKey(key, sharedName), value); + if (value is null) + WriteTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); + else + RemoveTombstone(TizenStorageKeyEncoding.GetKeyTombstone(key, sharedName)); + } + } + + /// + public T Get(string key, T defaultValue, string? sharedName = null) + { + ArgumentNullException.ThrowIfNull(key); + + lock (_store.SyncRoot) + { + var fullKey = GetFullKey(key, sharedName); + + if (_store.Contains(fullKey)) + return GetCore(fullKey, defaultValue); + if (LegacyFallbackSuppressed(key, sharedName)) + return defaultValue; + + foreach (var legacyKey in TizenStorageKeyEncoding.GetLegacyKeys(key, sharedName)) + { + if (!_store.Contains(legacyKey)) + continue; + + var value = GetCore(legacyKey, defaultValue); + SetCore(fullKey, value); + return value; + } + + 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, + DateTimePrefix + dateTime.ToBinary().ToString(CultureInfo.InvariantCulture)); + break; + case DateTimeOffset dateTimeOffset: + _store.Set( + fullKey, + DateTimeOffsetPrefix + dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)); + break; + 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)) + { + 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)) + { + 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)) + { + 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)); + + void WriteTombstone(string key) + { + if (!_store.Contains(key)) + _store.Set(key, true); + } + + void RemoveTombstone(string key) + { + if (_store.Contains(key)) + _store.Remove(key); + } + + internal static string GetFullKey(string key, string? sharedName) => + TizenStorageKeyEncoding.GetFullKey(key, sharedName); + } + + internal interface ITizenPreferencesStore + { + object SyncRoot { get; } + + 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 + { + readonly object _syncRoot = new(); + + public static TizenPreferencesStore Instance { get; } = new(); + + TizenPreferencesStore() + { + } + + public object SyncRoot => _syncRoot; + + public IEnumerable Keys + { + get + { + lock (SyncRoot) + return TizenPreference.Keys.ToArray(); + } + } + + public bool Contains(string key) + { + lock (SyncRoot) + return TizenPreference.Contains(key); + } + + public void Remove(string key) + { + lock (SyncRoot) + TizenPreference.Remove(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/PublicAPI/slice/PublicAPI.Shipped.txt b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Shipped.txt new file mode 100644 index 00000000..7dc5c581 --- /dev/null +++ b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt new file mode 100644 index 00000000..1d16d63e --- /dev/null +++ b/src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt @@ -0,0 +1,331 @@ +#nullable enable +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, 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! +const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.ImagePng = "image/png" -> string! +const Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes.Pdf = "application/pdf" -> string! +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.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.ShakeDetected -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAccelerometer.TizenAccelerometer() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.AppActionActivated -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.GetAsync() -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.IsSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.SetAsync(System.Collections.Generic.IEnumerable! actions) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppActions.TizenAppActions() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.BuildString.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.Name.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.PackageName.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.PackagingModel.get -> Microsoft.Maui.ApplicationModel.AppPackagingModel +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.RequestedLayoutDirection.get -> Microsoft.Maui.ApplicationModel.LayoutDirection +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.RequestedTheme.get -> Microsoft.Maui.ApplicationModel.AppTheme +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.ShowSettingsUI() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.TizenAppInfo() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.Version.get -> System.Version! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppInfo.VersionString.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppleSignInAuthenticator +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppleSignInAuthenticator.AuthenticateAsync(Microsoft.Maui.Authentication.AppleSignInAuthenticator.Options? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenAppleSignInAuthenticator.TizenAppleSignInAuthenticator() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBarometer +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBarometer.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBarometer.TizenBarometer() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.TizenBasePlatformPermission() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.BatteryInfoChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.ChargeLevel.get -> double +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.Dispose() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.EnergySaverStatus.get -> Microsoft.Maui.Devices.EnergySaverStatus +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.EnergySaverStatusChanged -> System.EventHandler! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.PowerSource.get -> Microsoft.Maui.Devices.BatteryPowerSource +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.State.get -> Microsoft.Maui.Devices.BatteryState +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBattery.TizenBattery() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBrowser +Microsoft.Maui.Platforms.Tizen.Essentials.TizenBrowser.OpenAsync(System.Uri! uri, Microsoft.Maui.ApplicationModel.BrowserLaunchOptions! options) -> System.Threading.Tasks.Task! +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! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenClipboard.TizenClipboard() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass +Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass.Start(Microsoft.Maui.Devices.Sensors.SensorSpeed sensorSpeed) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass.Start(Microsoft.Maui.Devices.Sensors.SensorSpeed sensorSpeed, bool applyLowPassFilter) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass.TizenCompass() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity.ConnectionProfiles.get -> System.Collections.Generic.IEnumerable! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity.ConnectivityChanged -> System.EventHandler! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity.Dispose() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity.NetworkAccess.get -> Microsoft.Maui.Networking.NetworkAccess +Microsoft.Maui.Platforms.Tizen.Essentials.TizenConnectivity.TizenConnectivity() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenContacts +Microsoft.Maui.Platforms.Tizen.Essentials.TizenContacts.GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenContacts.PickContactAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenContacts.TizenContacts() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.Dispose() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.KeepScreenOn.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.KeepScreenOn.set -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.MainDisplayInfo.get -> Microsoft.Maui.Devices.DisplayInfo +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.MainDisplayInfoChanged -> System.EventHandler! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceDisplay.TizenDeviceDisplay() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.DeviceType.get -> Microsoft.Maui.Devices.DeviceType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Idiom.get -> Microsoft.Maui.Devices.DeviceIdiom +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Manufacturer.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Model.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Name.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Platform.get -> Microsoft.Maui.Devices.DevicePlatform +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.TizenDeviceInfo() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.Version.get -> System.Version! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceInfo.VersionString.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile.Common = 4 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile.Mobile = 1 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile.TV = 3 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile.Unknown = 0 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile.Wearable = 2 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail.ComposeAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail.ComposeAsync(Microsoft.Maui.ApplicationModel.Communication.EmailMessage? message) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail.ComposeAsync(string! subject, string! body, params string![]! to) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail.IsComposeSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEmail.TizenEmail() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenEssentialsSupport +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileMimeTypes +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.PickAsync(Microsoft.Maui.Storage.PickOptions? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.PickMultipleAsync(Microsoft.Maui.Storage.PickOptions? options = null) -> System.Threading.Tasks.Task?>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.TizenFilePicker() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.AppDataDirectory.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.AppPackageFileExistsAsync(string! filename) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.CacheDirectory.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.OpenAppPackageFileAsync(string! filename) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFileSystem.TizenFileSystem() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFlashlight +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFlashlight.IsSupportedAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFlashlight.TizenFlashlight() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFlashlight.TurnOffAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenFlashlight.TurnOnAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding.GetLocationsAsync(string! address) -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding.GetPlacemarksAsync(double latitude, double longitude) -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding.MapServiceToken.get -> string? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding.MapServiceToken.set -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeocoding.TizenGeocoding() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.GetLastKnownLocationAsync() -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.GetLocationAsync(Microsoft.Maui.Devices.Sensors.GeolocationRequest! request, System.Threading.CancellationToken cancelToken) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.IsEnabled.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.IsListeningForeground.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.ListeningFailed -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.LocationChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.StartListeningForegroundAsync(Microsoft.Maui.Devices.Sensors.GeolocationListeningRequest! request) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.StopListeningForeground() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGeolocation.TizenGeolocation() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGyroscope +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGyroscope.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenGyroscope.TizenGyroscope() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenHapticFeedback +Microsoft.Maui.Platforms.Tizen.Essentials.TizenHapticFeedback.IsSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenHapticFeedback.Perform(Microsoft.Maui.Devices.HapticFeedbackType type) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenHapticFeedback.TizenHapticFeedback() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher.CanOpenAsync(System.Uri! uri) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher.OpenAsync(Microsoft.Maui.ApplicationModel.OpenFileRequest! request) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher.OpenAsync(System.Uri! uri) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher.TizenLauncher() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenLauncher.TryOpenAsync(System.Uri! uri) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMagnetometer +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMagnetometer.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMagnetometer.TizenMagnetometer() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap.OpenAsync(double latitude, double longitude, Microsoft.Maui.ApplicationModel.MapLaunchOptions! options) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap.OpenAsync(Microsoft.Maui.Devices.Sensors.Placemark! placemark, Microsoft.Maui.ApplicationModel.MapLaunchOptions! options) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap.TizenMap() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap.TryOpenAsync(double latitude, double longitude, Microsoft.Maui.ApplicationModel.MapLaunchOptions! options) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMap.TryOpenAsync(Microsoft.Maui.Devices.Sensors.Placemark! placemark, Microsoft.Maui.ApplicationModel.MapLaunchOptions! options) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.CapturePhotoAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.CaptureVideoAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.IsCaptureSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.PickPhotoAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.PickPhotosAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.PickVideoAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.PickVideosAsync(Microsoft.Maui.Media.MediaPickerOptions? options = null) -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenMediaPicker.TizenMediaPicker() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenOrientationSensor +Microsoft.Maui.Platforms.Tizen.Essentials.TizenOrientationSensor.ReadingChanged -> System.EventHandler? +Microsoft.Maui.Platforms.Tizen.Essentials.TizenOrientationSensor.TizenOrientationSensor() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPasskeys.AssertAsync(Microsoft.Maui.Authentication.PasskeyRequestOptions! options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +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! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.ShouldShowRationale() -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.TizenPermissions() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPhoneDialer +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPhoneDialer.IsSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPhoneDialer.Open(string! number) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPhoneDialer.TizenPhoneDialer() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPlacemarkExtensions +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPlatform +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.Clear(string? sharedName = null) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.ContainsKey(string! key, string? sharedName = null) -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.Get(string! key, T defaultValue, string? sharedName = null) -> T +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.Remove(string! key, string? sharedName = null) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.Set(string! key, T value, string? sharedName = null) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPreferences.TizenPreferences() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.IsRuntime.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.IsRuntime.init -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.Privilege.get -> string! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.Privilege.init -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.TizenPrivilege() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenPrivilege.TizenPrivilege(string! Privilege, bool IsRuntime) -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshot.CaptureAsync() -> System.Threading.Tasks.Task! +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 +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotResult +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotResult.CopyToAsync(System.IO.Stream! destination, Microsoft.Maui.Media.ScreenshotFormat format = Microsoft.Maui.Media.ScreenshotFormat.Png, int quality = 100) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotResult.Height.get -> int +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotResult.OpenReadAsync(Microsoft.Maui.Media.ScreenshotFormat format = Microsoft.Maui.Media.ScreenshotFormat.Png, int quality = 100) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenScreenshotResult.Width.get -> int +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage.GetAsync(string! key) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage.Remove(string! key) -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage.RemoveAll() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage.SetAsync(string! key, string! value) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSecureStorage.TizenSecureStorage() -> void +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(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 +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorBase.UseSyncContext.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensors +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorSpeedExtensions +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.Accelerometer = 0 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.Barometer = 1 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.Compass = 2 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.Gyroscope = 3 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.Magnetometer = 4 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType.OrientationSensor = 5 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSensorType +Microsoft.Maui.Platforms.Tizen.Essentials.TizenShare +Microsoft.Maui.Platforms.Tizen.Essentials.TizenShare.RequestAsync(Microsoft.Maui.ApplicationModel.DataTransfer.ShareFileRequest! request) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenShare.RequestAsync(Microsoft.Maui.ApplicationModel.DataTransfer.ShareMultipleFilesRequest! request) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenShare.RequestAsync(Microsoft.Maui.ApplicationModel.DataTransfer.ShareTextRequest! request) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenShare.TizenShare() -> void +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 +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel.Unsupported = 2 -> Microsoft.Maui.Platforms.Tizen.Essentials.TizenSupportLevel +Microsoft.Maui.Platforms.Tizen.Essentials.TizenSystemInformation +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.Dispose() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.GetLocalesAsync() -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.GetSupportedVoiceLanguagesAsync() -> System.Threading.Tasks.Task!>! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.SpeakAsync(string! text, Microsoft.Maui.Media.SpeechOptions? options = null, System.Threading.CancellationToken cancelToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.SpeakWithVoiceAsync(string! text, string! language, float? rate = null, System.Threading.CancellationToken cancelToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Microsoft.Maui.Platforms.Tizen.Essentials.TizenTextToSpeech.TizenTextToSpeech() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration.Cancel() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration.IsSupported.get -> bool +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration.TizenVibration() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration.Vibrate() -> void +Microsoft.Maui.Platforms.Tizen.Essentials.TizenVibration.Vibrate(System.TimeSpan duration) -> void +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 +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.RequestAsync() -> System.Threading.Tasks.Task! +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenBasePlatformPermission.ShouldShowRationale() -> bool +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenCompass.IsSupported.get -> bool +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenGyroscope.IsSupported.get -> bool +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenMagnetometer.IsSupported.get -> bool +override Microsoft.Maui.Platforms.Tizen.Essentials.TizenOrientationSensor.IsSupported.get -> bool +static Microsoft.Maui.Hosting.TizenEssentialsMauiAppBuilderExtensions.AddTizenEssentials(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Microsoft.Maui.Hosting.TizenEssentialsMauiAppBuilderExtensions.AddTizenEssentials(this Microsoft.Maui.Hosting.MauiAppBuilder! builder) -> Microsoft.Maui.Hosting.MauiAppBuilder! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenEssentialsSupport.NotSupported(string! capability, string! reason) -> Microsoft.Maui.ApplicationModel.FeatureNotSupportedException! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenEssentialsSupport.NotSupportedOnProfile(string! capability, params Microsoft.Maui.Platforms.Tizen.Essentials.TizenDeviceProfile[]! supportedProfiles) -> Microsoft.Maui.ApplicationModel.FeatureNotSupportedException! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.CreateFileType(params string![]! mimeTypes) -> Microsoft.Maui.Storage.FilePickerFileType! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.ImageFileType.get -> Microsoft.Maui.Storage.FilePickerFileType! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.JpegFileType.get -> Microsoft.Maui.Storage.FilePickerFileType! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.PdfFileType.get -> Microsoft.Maui.Storage.FilePickerFileType! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenFilePicker.PngFileType.get -> Microsoft.Maui.Storage.FilePickerFileType! +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! +static Microsoft.Maui.Platforms.Tizen.Essentials.TizenPermissions.IsPrivilegeDeclared(string! tizenPrivilege) -> bool +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/PublicAPI/slice/README.md b/src/Maui.Tizen.Essentials/PublicAPI/slice/README.md new file mode 100644 index 00000000..19adecb3 --- /dev/null +++ b/src/Maui.Tizen.Essentials/PublicAPI/slice/README.md @@ -0,0 +1,42 @@ +# PublicAPI baselines for the ported Tizen Essentials backend + +These files are this project's real API contract. They **replace** dotnet/maui's inherited +baselines under `../net-tizen/` for analyzer purposes, following the same convention as +`src/Maui.Tizen.Core/PublicAPI/slice/`. + +## Why the swap is necessary + +The inherited `../net-tizen/` baselines describe the whole of upstream's +`Microsoft.Maui.Essentials` assembly - the `Microsoft.Maui.ApplicationModel.*`, +`Microsoft.Maui.Devices.*` and `Microsoft.Maui.Storage.*` public surface. This assembly exports +none of that: it exports `Microsoft.Maui.Platforms.Tizen.Essentials.*` plus one +`Microsoft.Maui.Hosting` extensions class, and consumes the rest from the published +`Microsoft.Maui.Essentials` package. + +Attaching the inherited files would fail the build twice over: **RS0017** for each of the 1,318 +inherited entries that does not exist here, and **RS0016** for every type this assembly actually +does export. + +The inherited files stay on disk untouched. They are the imported provenance record of what +upstream shipped for `net-tizen`, and the API-comparison tooling in `eng/api-baselines/` reads +them. They are simply detached from the analyzer for this project. + +## How these were generated + +Not by hand - by the analyzer's own code fix, applied to the real compiled assembly: + +```bash +dotnet format analyzers tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj \ + --diagnostics RS0016 --severity warn +``` + +`tests/Maui.Tizen.Essentials.RefPackCompile` compiles the exact product sources against the real +`Samsung.Tizen.Ref.API15` reference assemblies, so every entry is the genuine emitted surface +rather than a transcription no build could verify. + +That lane is also where the baseline is currently *enforced*: `src/Maui.Tizen.Essentials` cannot be +built at all until Samsung publishes the .NET 11 workload (`MAUITIZEN0001`), so without it the +contract would sit unchecked until that day. Verified by negative test - adding an undeclared +public member fails the lane with RS0016 under CI semantics. + +`PublicAPI.Shipped.txt` is empty because nothing has shipped from this repository yet. diff --git a/src/Maui.Tizen.Essentials/Screenshot/Screenshot.tizen.cs b/src/Maui.Tizen.Essentials/Screenshot/Screenshot.tizen.cs deleted file mode 100644 index 1bc31dc5..00000000 --- a/src/Maui.Tizen.Essentials/Screenshot/Screenshot.tizen.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using NView = Tizen.NUI.BaseComponents.View; -using Window = Tizen.NUI.Window; - -namespace Microsoft.Maui.Media -{ - // TODO: Need to impl - partial class ScreenshotImplementation : IPlatformScreenshot, IScreenshot, IViewScreenshot - { - public bool IsCaptureSupported => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task CaptureAsync() => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task CaptureAsync(Window window) => - throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task CaptureAsync(NView view) => - throw ExceptionUtils.NotSupportedOrImplementedException; - -#nullable enable annotations - public Task CaptureViewAsync(object platformView) => - platformView is NView view ? CaptureAsync(view)! : Task.FromResult(null); -#nullable restore - } - - partial class ScreenshotResult - { - ScreenshotResult() - { - } - - Task PlatformOpenReadAsync(ScreenshotFormat format, int quality) => - throw ExceptionUtils.NotSupportedOrImplementedException; - - Task PlatformCopyToAsync(Stream destination, ScreenshotFormat format, int quality) => - throw ExceptionUtils.NotSupportedOrImplementedException; - - Task PlatformToPixelBufferAsync() => - throw ExceptionUtils.NotSupportedOrImplementedException; - } -} diff --git a/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs new file mode 100644 index 00000000..766d13ec --- /dev/null +++ b/src/Maui.Tizen.Essentials/Screenshot/TizenScreenshot.cs @@ -0,0 +1,628 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +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 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, IDisposable + { + readonly ITizenScreenshotDispatcher _dispatcher; + readonly ITizenScreenshotCaptureFactory _factory; + readonly CancellationTokenSource _disposeCancellation = new(); + int _disposed; + + /// + /// 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); + + /// 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 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. + /// + /// The window to capture. + /// The captured screenshot. + public async Task CaptureAsync(TizenWindow window) + { + ArgumentNullException.ThrowIfNull(window); + + return await CaptureCoreAsync( + () => _factory.CreateWindowCapture(window), + CancellationToken.None).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); + + return CaptureCoreAsync( + () => _factory.CreateViewCapture(view), + CancellationToken.None); + } + + /// + 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); + + internal async Task CaptureCoreAsync( + Func createSession, + CancellationToken cancellationToken, + TimeSpan? timeoutOverride = null) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + var terminal = new TizenScreenshotTerminalCoordinator(); + ITizenScreenshotCaptureSession? session = null; + void OnFinished(bool success) => + terminal.TryComplete( + success + ? TizenScreenshotTerminal.NativeSucceeded + : TizenScreenshotTerminal.NativeFailed); + + var effectiveTimeout = timeoutOverride ?? CaptureTimeout; + using var timeout = new CancellationTokenSource(effectiveTimeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + _disposeCancellation.Token, + timeout.Token); + + using var registration = linked.Token.Register(() => + { + if (_disposeCancellation.IsCancellationRequested) + terminal.TryComplete(TizenScreenshotTerminal.Disposed); + else if (cancellationToken.IsCancellationRequested) + terminal.TryComplete(TizenScreenshotTerminal.Canceled); + else + terminal.TryComplete(TizenScreenshotTerminal.TimedOut); + }); + + try + { + await _dispatcher.InvokeAsync(() => + { + if (!terminal.IsPending) + return; + + session = createSession(); + session.Finished += OnFinished; + if (terminal.IsPending) + session.Start(); + }).ConfigureAwait(false); + + var outcome = await terminal.Completion.ConfigureAwait(false); + switch (outcome) + { + case TizenScreenshotTerminal.NativeFailed: + return null; + case TizenScreenshotTerminal.Canceled: + throw new OperationCanceledException(cancellationToken); + case TizenScreenshotTerminal.Disposed: + throw new ObjectDisposedException(nameof(TizenScreenshot)); + case TizenScreenshotTerminal.TimedOut: + throw new TimeoutException( + $"Tizen did not raise Capture.Finished within {effectiveTimeout}."); + case TizenScreenshotTerminal.NativeSucceeded: + break; + default: + throw new InvalidOperationException($"Unexpected screenshot terminal state '{outcome}'."); + } + + // Native success owns the one terminal slot. A timeout/cancellation/disposal callback + // racing while the dispatcher copies the buffer cannot replace that outcome. + timeout.CancelAfter(Timeout.InfiniteTimeSpan); + var buffer = await _dispatcher.InvokeAsync(() => + { + 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 + { + if (session is not null) + { + 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 enum TizenScreenshotTerminal + { + Pending, + NativeSucceeded, + NativeFailed, + TimedOut, + Canceled, + Disposed, + } + + internal sealed class TizenScreenshotTerminalCoordinator + { + readonly TaskCompletionSource _completion = + new(TaskCreationOptions.RunContinuationsAsynchronously); + int _terminal; + + public bool IsPending => Volatile.Read(ref _terminal) == 0; + + public Task Completion => _completion.Task; + + public bool TryComplete(TizenScreenshotTerminal terminal) + { + if (terminal == TizenScreenshotTerminal.Pending) + throw new ArgumentOutOfRangeException(nameof(terminal)); + if (Interlocked.CompareExchange(ref _terminal, (int)terminal, 0) != 0) + return false; + + _completion.TrySetResult(terminal); + return true; + } + } + + 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 == 0) + stride = rowBytes; + 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); + } + + /// + /// 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 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 colorSpace = MapColorSpace(format); + var rowBytes = checked(width * BytesPerPixel(format)); + if (stride == 0) + stride = rowBytes; + 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 + // the driver left in the padding byte as transparency. + if (format == PixelFormat.RGB8888) + MakeOpaque(pixels); + + return new TizenCapturedPixels(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) + { + 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."); + } + } + + /// + /// 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 => 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( + $"{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/SecureStorage.tizen.cs b/src/Maui.Tizen.Essentials/SecureStorage/SecureStorage.tizen.cs deleted file mode 100644 index bcfa387e..00000000 --- a/src/Maui.Tizen.Essentials/SecureStorage/SecureStorage.tizen.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Text; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.Security.SecureRepository; - -namespace Microsoft.Maui.Storage -{ - partial class SecureStorageImplementation : ISecureStorage - { - Task PlatformGetAsync(string key) - { - try - { - // The null parameter here is not the default value as you might expect, but - // a password - return Task.FromResult(Encoding.UTF8.GetString(DataManager.Get(key, null))); - } - catch (System.InvalidOperationException) - { - // The DataManager.Get call throws an exception if key does not exist. Not logging - // anything since this is an expected and normal situation (if the key did not exist). - return Task.FromResult(null); - } - catch - { - Tizen.Log.Error(Platform.CurrentPackage.Label, "Failed to load data."); - throw; - } - } - - Task PlatformSetAsync(string key, string data) - { - try - { - try - { - // Remove the key in case it already exists, otherwise DataManager.Save will throw an exception. - // There is no way to check if a key exists without throwing an exception, so there is - // no point in checking whether the key exists prior to attempting to remove it. - DataManager.RemoveAlias(key); - } - catch - { - // Not logging anything since this is an expected and normal situation (if the key did not exist). - } - - DataManager.Save(key, Encoding.UTF8.GetBytes(data), new Policy()); - - return Task.CompletedTask; - } - catch - { - Tizen.Log.Error(Platform.CurrentPackage.Label, "Failed to save data."); - throw; - } - } - - void PlatformRemoveAll() - { - try - { - foreach (var key in DataManager.GetAliases()) - { - DataManager.RemoveAlias(key); - } - } - catch - { - Tizen.Log.Info(Platform.CurrentPackage.Label, "No save data."); - } - } - - bool PlatformRemove(string key) - { - try - { - DataManager.RemoveAlias(key); - return true; - } - catch - { - Tizen.Log.Info(Platform.CurrentPackage.Label, "Failed to remove data."); - return false; - } - } - } -} diff --git a/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs new file mode 100644 index 00000000..98dff07b --- /dev/null +++ b/src/Maui.Tizen.Essentials/SecureStorage/TizenSecureStorage.cs @@ -0,0 +1,660 @@ +using System; +using System.Collections.Generic; +using System.Linq; +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). + /// + /// + /// + /// 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 + { + 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. + /// + /// + /// 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:"; + + /// + /// Creates a secure-storage service backed by Tizen's secure repository. + /// + public TizenSecureStorage() + : this( + TizenSecureRepository.Instance, + TizenSecureStorageTombstones.Instance, + static () => TizenPlatform.CurrentPackageId) + { + } + + internal TizenSecureStorage( + ITizenSecureRepository repository, + ITizenSecureStorageTombstones? tombstones = null, + Func? currentPackageId = null) + { + _repository = repository; + _tombstones = tombstones ?? new InMemorySecureStorageTombstones(); + _currentPackageId = currentPackageId ?? (static () => null); + } + + /// + public Task GetAsync(string key) + { + ArgumentNullException.ThrowIfNull(key); + + lock (Locker) + { + if (_tombstones.Contains(key)) + return Task.FromResult(null); + + RecoverStagedValue(key); + + 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. + } + + byte[] legacyValue; + string? migratedOwnedAlias = null; + + try + { + if (!CanUseLegacyNamespacedAlias(key)) + throw new InvalidOperationException(); + + migratedOwnedAlias = ToLegacyNamespacedAlias(key); + legacyValue = _repository.Get(migratedOwnedAlias); + } + catch (InvalidOperationException) + { + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } + catch (ArgumentException) + { + return Task.FromResult(null); + } + } + catch (ArgumentException) + { + try + { + legacyValue = _repository.Get(key); + } + catch (InvalidOperationException) + { + return Task.FromResult(null); + } + catch (ArgumentException) + { + return Task.FromResult(null); + } + } + + // 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)); + } + } + + /// + public Task SetAsync(string key, string value) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + + lock (Locker) + { + var alias = ToAlias(key); + RecoverStagedValue(key); + ReplaceOwnedAliases( + key, + alias, + Encoding.UTF8.GetBytes(value)); + _tombstones.Remove(key); + return Task.CompletedTask; + } + } + + /// + /// + /// 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); + + lock (Locker) + { + var currentAlias = ToAlias(key); + // Commit deletion intent before touching repository aliases. Even if a native + // deletion fails, subsequent reads cannot expose the old current/staged value. + _tombstones.Add(key); + var removed = false; + var failures = new List(); + removed |= RemoveForDeletion(currentAlias, failures); + if (CanUseLegacyNamespacedAlias(key)) + removed |= RemoveForDeletion(ToLegacyNamespacedAlias(key), failures); + + foreach (var stagedAlias in GetStagedAliases(key).ToList()) + removed |= RemoveForDeletion(stagedAlias, failures); + + ThrowDeletionFailures(failures); + return removed; + } + } + + /// + /// + /// Removes only the aliases this API owns. Other secure-repository entries belonging to the + /// 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() + { + lock (Locker) + { + _tombstones.AddAll(); + + var aliases = _repository.GetAliases().ToList(); + + var currentPackageId = _currentPackageId(); + var failures = new List(); + foreach (var alias in aliases) + { + if (!IsOwnedAlias(alias, currentPackageId)) + continue; + + RemoveForDeletion(alias, failures); + } + + ThrowDeletionFailures(failures); + } + } + + /// + /// Maps a caller key onto the private alias actually stored in the key manager. + /// + /// The caller's key. + /// The namespaced alias. + /// + /// 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(StrictUtf8.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. + /// + /// 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). + /// 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, string? currentPackageId = null) + { + if (string.IsNullOrEmpty(alias)) + return false; + + if (alias.StartsWith(AliasPrefix, StringComparison.Ordinal)) + return true; + + var separator = alias.IndexOf(' '); + if (separator <= 0 || separator == alias.Length - 1) + return false; + + 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); + } + + IEnumerable GetStagedAliases(string key) + { + var prefix = GetTransactionPrefix(key); + var currentPackageId = _currentPackageId(); + foreach (var qualifiedAlias in _repository.GetAliases()) + { + 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 + { + _repository.RemoveAlias(alias); + } + catch (InvalidOperationException) + { + // Expected when the owned alias did not exist. + } + } + + bool RemoveForDeletion(string alias, ICollection failures) + { + try + { + _repository.RemoveAlias(alias); + return true; + } + catch (InvalidOperationException) + { + // Missing aliases are expected during idempotent removal. + return false; + } + catch (Exception exception) + { + failures.Add(exception); + return false; + } + } + + static void ThrowDeletionFailures(IReadOnlyCollection failures) + { + if (failures.Count == 1) + throw failures.First(); + if (failures.Count > 1) + throw new AggregateException("One or more SecureStorage aliases could not be removed.", failures); + } + } + + 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"; + const string LivePrefix = Prefix + "live:"; + readonly ITizenPreferencesStore _store; + + public static TizenSecureStorageTombstones Instance { get; } = + new(TizenPreferencesStore.Instance); + + internal TizenSecureStorageTombstones(ITizenPreferencesStore store) + { + _store = store; + } + + public bool ContainsAll + { + get + { + lock (_store.SyncRoot) + return _store.Contains(AllKey); + } + } + + public bool Contains(string key) + { + lock (_store.SyncRoot) + { + if (_store.Contains(GetKeyTombstone(key))) + return true; + + return _store.Contains(AllKey) && !_store.Contains(GetLiveMarker(key)); + } + } + + public void Add(string key) + { + lock (_store.SyncRoot) + { + var live = GetLiveMarker(key); + if (_store.Contains(live)) + _store.Remove(live); + _store.Set(GetKeyTombstone(key), true); + } + } + + public void Remove(string key) + { + lock (_store.SyncRoot) + { + var tombstone = GetKeyTombstone(key); + if (_store.Contains(tombstone)) + _store.Remove(tombstone); + + var live = GetLiveMarker(key); + if (_store.Contains(AllKey)) + _store.Set(live, true); + else if (_store.Contains(live)) + _store.Remove(live); + } + } + + public void AddAll() + { + lock (_store.SyncRoot) + { + _store.Set(AllKey, true); + foreach (var key in _store.Keys + .Where(key => key.StartsWith(LivePrefix, StringComparison.Ordinal)) + .ToList()) + { + _store.Remove(key); + } + } + } + + static string GetKeyTombstone(string key) => + Prefix + "key:" + TizenStorageKeyEncoding.Encode(key); + + static string GetLiveMarker(string key) => + LivePrefix + TizenStorageKeyEncoding.Encode(key); + } + + sealed class InMemorySecureStorageTombstones : ITizenSecureStorageTombstones + { + readonly HashSet _keys = new(StringComparer.Ordinal); + readonly HashSet _liveAfterAll = new(StringComparer.Ordinal); + + public bool ContainsAll { get; private set; } + + public bool Contains(string key) => + _keys.Contains(key) || (ContainsAll && !_liveAfterAll.Contains(key)); + + public void Add(string key) + { + _liveAfterAll.Remove(key); + _keys.Add(key); + } + + public void Remove(string key) + { + _keys.Remove(key); + if (ContainsAll) + _liveAfterAll.Add(key); + else + _liveAfterAll.Remove(key); + } + + public void AddAll() + { + ContainsAll = true; + _liveAfterAll.Clear(); + } + } + + internal interface ITizenSecureRepository + { + byte[] Get(string alias); + + void Save(string alias, byte[] value); + + void RemoveAlias(string alias); + + IEnumerable GetAliases(); + } + + sealed class TizenSecureRepository : ITizenSecureRepository + { + readonly Func> _getAliases; + + public static TizenSecureRepository Instance { get; } = + new(DataManager.GetAliases); + + internal TizenSecureRepository(Func> getAliases) + { + _getAliases = getAliases; + } + + 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() => + NormalizeAliases(_getAliases); + + internal static IReadOnlyList NormalizeAliases( + Func> getAliases) + { + try + { + return getAliases().ToArray(); + } + catch (ArgumentException exception) when (exception.ParamName is null) + { + // API15 documents ArgumentException from this parameterless call specifically as + // "there's no alias to get". An ArgumentException naming a parameter is not that + // sentinel and must propagate as a genuine repository failure. + return []; + } + } + } +} diff --git a/src/Maui.Tizen.Essentials/SemanticScreenReader/SemanticScreenReader.tizen.cs b/src/Maui.Tizen.Essentials/SemanticScreenReader/SemanticScreenReader.tizen.cs deleted file mode 100644 index 6a22ebb2..00000000 --- a/src/Maui.Tizen.Essentials/SemanticScreenReader/SemanticScreenReader.tizen.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Microsoft.Maui.Accessibility -{ - partial class SemanticScreenReaderImplementation : ISemanticScreenReader - { - public void Announce(string text) - { - Tizen.NUI.Accessibility.Accessibility.Say(text, true); - } - } -} 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/Share.tizen.cs b/src/Maui.Tizen.Essentials/Share/Share.tizen.cs deleted file mode 100644 index 0339307d..00000000 --- a/src/Maui.Tizen.Essentials/Share/Share.tizen.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Threading.Tasks; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel.DataTransfer -{ - partial class ShareImplementation : IShare - { - Task PlatformRequestAsync(ShareTextRequest request) - { - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.ShareText, - }; - - if (!string.IsNullOrEmpty(request.Text)) - appControl.ExtraData.Add(AppControlData.Text, request.Text); - if (!string.IsNullOrEmpty(request.Uri)) - appControl.ExtraData.Add(AppControlData.Url, request.Uri); - if (!string.IsNullOrEmpty(request.Subject)) - appControl.ExtraData.Add(AppControlData.Subject, request.Subject); - if (!string.IsNullOrEmpty(request.Title)) - appControl.ExtraData.Add(AppControlData.Title, request.Title); - - AppControl.SendLaunchRequest(appControl); - - return Task.CompletedTask; - } - - Task PlatformRequestAsync(ShareFileRequest request) => - PlatformRequestAsync((ShareMultipleFilesRequest)request); - - Task PlatformRequestAsync(ShareMultipleFilesRequest request) - { - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.Share, - }; - - if (!string.IsNullOrEmpty(request.Title)) - appControl.ExtraData.Add(AppControlData.Title, request.Title); - - foreach (var file in request.Files) - appControl.ExtraData.Add(AppControlData.Path, file.FullPath); - - AppControl.SendLaunchRequest(appControl); - - return Task.CompletedTask; - } - } -} diff --git a/src/Maui.Tizen.Essentials/Share/TizenShare.cs b/src/Maui.Tizen.Essentials/Share/TizenShare.cs new file mode 100644 index 00000000..bd354595 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Share/TizenShare.cs @@ -0,0 +1,172 @@ +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; + +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 payload = CreateFilePayload(request.Files); + var appControl = new TizenAppControl + { + Operation = payload.Operation, + Mime = payload.Mime, + }; + + if (!string.IsNullOrEmpty(request.Title)) + appControl.ExtraData.Add(TizenAppControlData.Title, request.Title); + + AddPaths( + payload, + (key, value) => appControl.ExtraData.Add(key, value), + (key, values) => appControl.ExtraData.Add(key, values)); + + 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), + paths); + } + + internal static void AddPaths( + TizenFilePayload payload, + Action addSingle, + Action> addMultiple) + { + 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; + } + + internal 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( + string Operation, + string Mime, + IReadOnlyList Paths); +} diff --git a/src/Maui.Tizen.Essentials/Sms/Sms.tizen.cs b/src/Maui.Tizen.Essentials/Sms/Sms.tizen.cs deleted file mode 100644 index 485f2075..00000000 --- a/src/Maui.Tizen.Essentials/Sms/Sms.tizen.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; -using Tizen.Applications; - -namespace Microsoft.Maui.ApplicationModel.Communication -{ - partial class SmsImplementation : ISms - { - public bool IsComposeSupported - => PlatformUtils.GetFeatureInfo("network.telephony.sms"); - - Task PlatformComposeAsync(SmsMessage message) - { - Permissions.EnsureDeclared(); - - var appControl = new AppControl - { - Operation = AppControlOperations.Compose, - Uri = "sms:", - }; - - if (!string.IsNullOrEmpty(message.Body)) - appControl.ExtraData.Add(AppControlData.Text, message.Body); - if (message.Recipients.Count > 0) - appControl.Uri += string.Join(" ", message.Recipients); - - AppControl.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/TextToSpeech.tizen.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TextToSpeech.tizen.cs deleted file mode 100644 index 686f87a9..00000000 --- a/src/Maui.Tizen.Essentials/TextToSpeech/TextToSpeech.tizen.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Tizen.Uix.Tts; - -namespace Microsoft.Maui.Media -{ - partial class TextToSpeechImplementation : ITextToSpeech - { - TtsClient tts = null; - TaskCompletionSource tcsInitialize = null; - TaskCompletionSource tcsUtterances = null; - - async Task PlatformSpeakAsync(string text, SpeechOptions options, CancellationToken cancelToken = default) - { - await Initialize(); - - if (tcsUtterances?.Task != null) - await tcsUtterances.Task; - - tcsUtterances = new TaskCompletionSource(); - - cancelToken.Register(() => - { - tts?.Stop(); - tcsUtterances?.TrySetResult(true); - }); - - var language = "en_US"; - var voiceType = Voice.Auto; - if (options?.Locale.Language != null) - { - foreach (var voice in tts.GetSupportedVoices()) - { - if (voice.Language == options.Locale.Language) - { - language = voice.Language; - voiceType = voice.VoiceType; - } - } - } - - var rate = 0; - if (options?.Rate.HasValue ?? false) - rate = (int)Math.Round(options.Rate.Value / RateMax * tts.GetSpeedRange().Max, MidpointRounding.AwayFromZero); - - tts.AddText(text, language, (int)voiceType, rate); - tts.Play(); - - await tcsUtterances.Task; - } - - async Task> PlatformGetLocalesAsync() - { - await Initialize(); - var list = new List(); - foreach (var voice in tts?.GetSupportedVoices()) - list.Add(new Locale(voice.Language, null, null, null)); - return list; - } - - Task Initialize() - { - if (tcsInitialize != null && tts != null) - return tcsInitialize.Task; - - tcsInitialize = new TaskCompletionSource(); - tts = new TtsClient(); - - tts.StateChanged += (s, e) => - { - if (e.Current == State.Ready) - tcsInitialize?.TrySetResult(true); - }; - - tts.UtteranceCompleted += (s, e) => - { - tts?.Stop(); - tcsUtterances?.TrySetResult(true); - }; - - tts.Prepare(); - return tcsInitialize.Task; - } - } -} diff --git a/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs new file mode 100644 index 00000000..16a6f533 --- /dev/null +++ b/src/Maui.Tizen.Essentials/TextToSpeech/TizenTextToSpeech.cs @@ -0,0 +1,755 @@ +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 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 RateMin = 0.1f; + const float RateNormal = 1.0f; + const float RateMax = 2.0f; + + readonly SemaphoreSlim _speakLock = new(1, 1); + readonly object _stateLock = new(); + readonly ITizenTextToSpeechDispatcher _dispatcher; + readonly ITizenTextToSpeechClientFactory _clientFactory; + + ClientState? _clientState; + ClientState? _initializingState; + Task? _initialization; + ActiveUtterance? _activeUtterance; + TaskCompletionSource? _readiness; + 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. + /// + /// 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( + $"{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. + public async Task> GetSupportedVoiceLanguagesAsync() + { + var languages = new List(); + + await RunWithCurrentClientAsync( + _speakLock, + CancellationToken.None, + InitializeAsync, + async state => + { + var voices = await _dispatcher.InvokeAsync(() => + { + ThrowIfNativeCallInvalid(state, CancellationToken.None); + return state.Client!.GetSupportedVoices(); + }).ConfigureAwait(false); + foreach (var voice in voices) + { + if (!languages.Any(value => + string.Equals(value, voice.Language, StringComparison.OrdinalIgnoreCase))) + { + languages.Add(voice.Language); + } + } + }).ConfigureAwait(false); + + return languages; + } + + /// 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) + { + 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); + cancelToken.ThrowIfCancellationRequested(); + + await RunWithCurrentClientAsync( + _speakLock, + cancelToken, + InitializeAsync, + async state => + { + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + SetPendingUtterance(state, completion); + + try + { + using var registration = cancelToken.Register( + () => CancelClientState(state, completion, cancelToken)); + cancelToken.ThrowIfCancellationRequested(); + + var utteranceId = await _dispatcher.InvokeAsync(() => + { + ThrowIfNativeCallInvalid(state, cancelToken); + var (resolvedLanguage, voiceType) = ResolveVoice(state.Client!, language); + return state.Client!.AddText( + text, + resolvedLanguage, + voiceType, + ResolveRate(state, rate)); + }).ConfigureAwait(false); + + SetActiveUtterance(state, utteranceId, completion); + cancelToken.ThrowIfCancellationRequested(); + + try + { + await _dispatcher.InvokeAsync(() => + { + ThrowIfNativeCallInvalid(state, cancelToken); + state.Client!.Play(); + }).ConfigureAwait(false); + } + catch + { + if (RetireClientState(state)) + DispatchTeardown(state, stop: true); + throw; + } + + await completion.Task.ConfigureAwait(false); + } + catch (Exception) when (cancelToken.IsCancellationRequested) + { + cancelToken.ThrowIfCancellationRequested(); + throw; + } + finally + { + ClearActiveUtterance(state, completion); + } + }).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 + { + speakLock.Release(); + } + } + + async Task InitializeAsync(CancellationToken cancelToken) + { + ClientState state; + var initialize = false; + + lock (_stateLock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (_clientState is { Retired: false } current) + return current; + + if (_initialization is null) + { + state = new ClientState(); + _initializingState = state; + _initialization = state.Initialization.Task; + _readiness = state.Readiness; + initialize = true; + } + else + { + state = _initializingState!; + } + } + + if (initialize) + { + 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); + } + } + + return await state.Initialization.Task.WaitAsync(cancelToken).ConfigureAwait(false); + } + + void PrepareOnMainThread(ClientState state) + { + 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; + } + + // 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.SpeedRange = client.GetSpeedRange(); + client.Prepare(); + + void OnStateChanged(TizenTextToSpeechState current) + { + if (current != TizenTextToSpeechState.Ready) + return; + + lock (_stateLock) + { + if (state.Retired || _disposed || !ReferenceEquals(_initializingState, state)) + return; + + _clientState = state; + _initializingState = null; + _readiness = null; + } + + state.Readiness.TrySetResult(true); + state.Initialization.TrySetResult(state); + } + + void OnUtteranceCompleted(int utteranceId) + { + _dispatcher.Post(() => + { + ActiveUtterance? utterance; + lock (_stateLock) + { + utterance = _activeUtterance is { } active && + ReferenceEquals(active.Client, state) && + active.UtteranceId == utteranceId + ? active + : null; + } + + if (utterance is null) + return; + + StopQuietly(state.Client!); + utterance.Completion.TrySetResult(true); + }); + } + + void OnErrorOccurred(TizenTextToSpeechError error) + { + ActiveUtterance? utterance; + lock (_stateLock) + { + utterance = _activeUtterance; + if (utterance is not null && + (!ReferenceEquals(utterance.Client, state) || + utterance.UtteranceId != error.UtteranceId)) + { + return; + } + + if (!RetireClientStateLocked(state)) + return; + } + + 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); + + // Never destroy the native handle from inside the ErrorOccurred callback. + DispatchTeardown(state, stop: false); + } + } + + void SetPendingUtterance(ClientState state, TaskCompletionSource completion) + { + lock (_stateLock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired."); + + _utterance = completion; + } + } + + void SetActiveUtterance( + ClientState state, + int utteranceId, + TaskCompletionSource completion) + { + lock (_stateLock) + { + if (state.Retired || !ReferenceEquals(_clientState, state)) + throw new InvalidOperationException("The Tizen text-to-speech client was retired."); + + _activeUtterance = new ActiveUtterance(state, utteranceId, completion); + } + } + + void ClearActiveUtterance(ClientState state, TaskCompletionSource completion) + { + lock (_stateLock) + { + if (_activeUtterance is { } active && + ReferenceEquals(active.Client, state) && + ReferenceEquals(active.Completion, completion)) + { + _activeUtterance = null; + } + + if (ReferenceEquals(_utterance, completion)) + _utterance = null; + } + } + + void CancelClientState( + ClientState state, + TaskCompletionSource completion, + CancellationToken cancelToken) + { + if (RetireClientState(state)) + DispatchTeardown(state, stop: true); + + completion.TrySetCanceled(cancelToken); + } + + bool RetireClientState(ClientState state) + { + lock (_stateLock) + return RetireClientStateLocked(state); + } + + 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; + } + + void DispatchTeardown(ClientState state, bool stop) + { + lock (_stateLock) + { + state.TeardownRequested = true; + state.StopBeforeTeardown |= stop; + + if (state.Client is null || state.TeardownPosted) + return; + + state.TeardownPosted = true; + } + + _dispatcher.Post(() => + { + var client = state.Client; + if (client is null) + return; + + if (state.StopBeforeTeardown) + StopQuietly(client); + + 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 + { + client.Stop(); + } + catch (Exception) + { + // Stop is best effort after cancellation, failure, or completion. + } + } + + static (string Language, int VoiceType) ResolveVoice( + ITizenTextToSpeechClient client, + string? requestedLanguage) + { + 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(ClientState state, float? rate) + => ResolveRate(state.SpeedRange, rate); + + internal static int ResolveRate(TizenTextToSpeechSpeedRange range, float? rate) + { + var value = rate ?? RateNormal; + if (value < RateMin || value > RateMax || float.IsNaN(value)) + throw new ArgumentOutOfRangeException( + nameof(rate), + value, + $"Speech rate must be between {RateMin} and {RateMax}."); + + var mapped = value <= RateNormal + ? range.Min + + ((value - RateMin) / (RateNormal - RateMin) * (range.Normal - range.Min)) + : range.Normal + + ((value - RateNormal) / (RateMax - RateNormal) * (range.Max - range.Normal)); + + return (int)Math.Round( + mapped, + MidpointRounding.AwayFromZero); + } + + internal static void FailPendingTasks( + TaskCompletionSource? readiness, + TaskCompletionSource? utterance, + Exception exception) + { + readiness?.TrySetException(exception); + utterance?.TrySetException(exception); + } + + /// + public void Dispose() + { + ClientState? current; + ClientState? initializing; + TaskCompletionSource? readiness; + TaskCompletionSource? utterance; + + lock (_stateLock) + { + 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; + } + + var exception = new ObjectDisposedException(nameof(TizenTextToSpeech)); + FailPendingTasks(readiness, utterance, exception); + current?.Initialization.TrySetException(exception); + initializing?.Initialization.TrySetException(exception); + + 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 ITizenTextToSpeechClient? Client { get; set; } + + public TaskCompletionSource Readiness { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Initialization { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool Retired { get; set; } + + public bool TeardownRequested { get; set; } + + public bool StopBeforeTeardown { get; set; } + + public bool TeardownPosted { get; set; } + + public TizenTextToSpeechSpeedRange SpeedRange { get; set; } + } + + sealed record ActiveUtterance( + ClientState Client, + int UtteranceId, + TaskCompletionSource Completion); + } + + internal enum TizenTextToSpeechState + { + Ready, + Other, + } + + internal sealed record TizenTextToSpeechVoice(string Language, int VoiceType); + + internal readonly record struct TizenTextToSpeechSpeedRange( + int Min, + int Normal, + int Max); + + internal sealed record TizenTextToSpeechError( + int UtteranceId, + int ErrorValue, + string ErrorMessage); + + internal interface ITizenTextToSpeechDispatcher + { + Task InvokeAsync(Action action); + + Task InvokeAsync(Func action); + + void Post(Action action); + } + + internal interface ITizenTextToSpeechClientFactory + { + ITizenTextToSpeechClient Create(); + } + + internal interface ITizenTextToSpeechClient : IDisposable + { + event Action? StateChanged; + + event Action? UtteranceCompleted; + + event Action? ErrorOccurred; + + void Prepare(); + + IReadOnlyList GetSupportedVoices(); + + TizenTextToSpeechSpeedRange GetSpeedRange(); + + 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 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 + { + 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 TizenTextToSpeechSpeedRange GetSpeedRange() + { + var range = _client.GetSpeedRange(); + return new(range.Min, range.Normal, range.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/src/Maui.Tizen.Essentials/Types/SensorSpeed.tizen.cs b/src/Maui.Tizen.Essentials/Types/SensorSpeed.tizen.cs deleted file mode 100644 index 10a7329b..00000000 --- a/src/Maui.Tizen.Essentials/Types/SensorSpeed.tizen.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Microsoft.Maui.Devices.Sensors -{ - internal static partial class SensorSpeedExtensions - { - internal static uint ToPlatform(this SensorSpeed sensorSpeed) - { - switch (sensorSpeed) - { - case SensorSpeed.Fastest: - return sensorIntervalFastest; - case SensorSpeed.Game: - return sensorIntervalGame; - case SensorSpeed.UI: - return sensorIntervalUI; - } - - return sensorIntervalDefault; - } - } -} 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..eb3d6227 --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenSensorBase.cs @@ -0,0 +1,317 @@ +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; + +namespace Microsoft.Maui.Platforms.Tizen.Essentials +{ + /// + /// Shared generation and ref-counted native lifetime for a Tizen sensor implementation. + /// + public abstract class TizenSensorBase + where TSensor : TizenSensor + { + static readonly TizenSensorLifetimeCoordinator Lifetime = new(); + readonly TizenSensorGenerationGate _generation = new(); + readonly object _operationLock = new(); + readonly TizenNativeCallbackCoordinator _callbacks = new(); + + /// Gets whether readings should be marshalled to the main thread. + protected bool UseSyncContext => _generation.UseSyncContext; + + /// Gets whether this wrapper is currently monitoring. + public bool IsMonitoring => _generation.IsMonitoring; + + /// Gets whether this device provides the sensor. + public abstract bool IsSupported { get; } + + /// Gets the display name used in diagnostics. + protected abstract string SensorName { get; } + + /// Gets the shared native sensor instance. + protected abstract TSensor Sensor { get; } + + /// + /// 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() + { + } + + /// Releases per-wrapper state after stop or failed start. + protected virtual void OnStopped() + { + } + + /// Starts monitoring. + public void Start(SensorSpeed sensorSpeed) + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{SensorName}.Start", $"This device has no {SensorName} sensor."); + lock (_operationLock) + { + var generation = _generation.BeginStart( + sensorSpeed is SensorSpeed.Default or SensorSpeed.UI, + SensorName); + + try + { + 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, + OnStopped); + } + catch + { + _generation.Invalidate(); + throw; + } + } + } + + /// Stops monitoring. + public void Stop() + { + if (!IsSupported) + throw TizenEssentialsSupport.NotSupported($"{SensorName}.Stop", $"This device has no {SensorName} sensor."); + lock (_operationLock) + { + if (!IsMonitoring) + return; + + Lifetime.Stop( + this, + () => _generation.Invalidate(), + static sensor => sensor.Stop(), + static sensor => TizenSensors.ResetDefaultSensor(sensor), + static (sensor, interval) => sensor.Interval = interval, + OnStopped); + } + } + + /// 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 + { + if (handler is null || !IsCurrentGeneration(generation)) + return; + + if (UseSyncContext) + { + _callbacks.Post( + () => IsCurrentGeneration(generation), + () => handler.Invoke(this, args)); + } + else if (IsCurrentGeneration(generation)) + { + handler.Invoke(this, args); + } + } + } + + 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 (Interlocked.CompareExchange(ref _monitoring, 1, 0) != 0) + throw new InvalidOperationException($"{sensorName} has already been started."); + + 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 + { + lock (_locker) + return _registrations.Count; + } + } + + public void Start( + object owner, + Func acquire, + uint interval, + Action setInterval, + Func subscribe, + Action start, + Action stop, + Action reset, + Action started, + Action stopped) + { + lock (_locker) + { + if (_registrations.ContainsKey(owner)) + throw new InvalidOperationException("This sensor wrapper has already started."); + + // Acquire while holding the same lock that clears the final cached sensor. A new + // owner can never capture the instance another thread is still stopping/resetting. + _sensor ??= acquire(); + var first = _registrations.Count == 0; + Action? unsubscribe = null; + var registered = false; + var nativeStartAttempted = false; + + try + { + unsubscribe = subscribe(_sensor); + _registrations.Add(owner, new(interval, unsubscribe)); + registered = true; + ApplyFastestInterval(_sensor, setInterval); + started(); + + if (first) + { + nativeStartAttempted = true; + start(_sensor); + } + + } + catch + { + if (registered) + _registrations.Remove(owner); + TryCleanup(unsubscribe); + if (first && nativeStartAttempted) + TryCleanup(() => stop(_sensor)); + + if (_registrations.Count == 0) + { + TryCleanup(() => reset(_sensor)); + _sensor = null; + } + else + { + TryCleanup(() => ApplyFastestInterval(_sensor, setInterval)); + } + + TryCleanup(stopped); + throw; + } + } + } + + public void Stop( + object owner, + Action invalidate, + Action stop, + Action reset, + Action setInterval, + Action stopped) + { + lock (_locker) + { + if (!_registrations.TryGetValue(owner, out var registration) || _sensor is null) + return; + + invalidate(); + _registrations.Remove(owner); + var failures = new List(); + TryCleanup(registration.Unsubscribe, failures); + + 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); + } + } + + void ApplyFastestInterval(TSensor sensor, Action setInterval) + { + if (_registrations.Count == 0) + return; + + 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/src/Maui.Tizen.Essentials/Types/TizenSensors.cs b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs new file mode 100644 index 00000000..c4db3ccb --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenSensors.cs @@ -0,0 +1,143 @@ +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 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. + /// + /// 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."), + }; + + 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; + } + } + } + } + + /// + /// 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/Types/TizenStorageKeyEncoding.cs b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs new file mode 100644 index 00000000..fc264e3b --- /dev/null +++ b/src/Maui.Tizen.Essentials/Types/TizenStorageKeyEncoding.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +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. + /// + /// + /// 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:"; + const string KeyTombstonePrefix = VersionPrefix + "tk:"; + const string StoreTombstonePrefix = VersionPrefix + "ts:"; + + /// + /// 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); + + if (string.IsNullOrEmpty(sharedName)) + return DefaultStorePrefix + Encode(key); + + return string.Concat(NamedStorePrefix, 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 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; + } + + 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/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/Vibration/Vibration.tizen.cs b/src/Maui.Tizen.Essentials/Vibration/Vibration.tizen.cs deleted file mode 100644 index 8bc524a5..00000000 --- a/src/Maui.Tizen.Essentials/Vibration/Vibration.tizen.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Linq; -using Microsoft.Maui.ApplicationModel; -using Tizen.System; - -namespace Microsoft.Maui.Devices -{ - partial class VibrationImplementation : IVibration - { - public bool IsSupported - => Vibrator.NumberOfVibrators > 0; - - void PlatformVibrate() - => Vibrate(TimeSpan.FromMilliseconds(500)); - - void PlatformVibrate(TimeSpan duration) - { - Permissions.EnsureDeclared(); - - Vibrator.Vibrators.FirstOrDefault()?.Vibrate((int)duration.TotalMilliseconds, 100); - } - - void PlatformCancel() - { - Permissions.EnsureDeclared(); - - Vibrator.Vibrators.FirstOrDefault()?.Stop(); - } - } -} diff --git a/src/Maui.Tizen.Essentials/WebAuthenticator/AppleSignInAuthenticator.netstandard.android.tvos.watchos.windows.tizen.macos.cs b/src/Maui.Tizen.Essentials/WebAuthenticator/AppleSignInAuthenticator.netstandard.android.tvos.watchos.windows.tizen.macos.cs deleted file mode 100644 index f0ade623..00000000 --- a/src/Maui.Tizen.Essentials/WebAuthenticator/AppleSignInAuthenticator.netstandard.android.tvos.watchos.windows.tizen.macos.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; - -namespace Microsoft.Maui.Authentication -{ - partial class AppleSignInAuthenticatorImplementation : IAppleSignInAuthenticator - { - public Task AuthenticateAsync(AppleSignInAuthenticator.Options options) => - throw ExceptionUtils.NotSupportedOrImplementedException; - } -} 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/src/Maui.Tizen.Essentials/WebAuthenticator/WebAuthenticator.netstandard.watchos.tizen.cs b/src/Maui.Tizen.Essentials/WebAuthenticator/WebAuthenticator.netstandard.watchos.tizen.cs deleted file mode 100644 index efc82d6a..00000000 --- a/src/Maui.Tizen.Essentials/WebAuthenticator/WebAuthenticator.netstandard.watchos.tizen.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Maui.ApplicationModel; - -namespace Microsoft.Maui.Authentication -{ - partial class WebAuthenticatorImplementation : IWebAuthenticator - { - public Task AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions) - => throw ExceptionUtils.NotSupportedOrImplementedException; - - public Task AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions, CancellationToken cancellationToken) - => throw ExceptionUtils.NotSupportedOrImplementedException; - } -} 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 4bd4e0f7..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 @@ -37,6 +38,7 @@ + + + + + + + $(MSBuildAllProjects);$(RepositoryRoot)eng/targets/TizenPackage.props + $(DotNetTfm) + false + + Maui.Tizen.Essentials + Microsoft.Maui.Platforms.Tizen.Essentials + + false + false + false + true + true + true + $(NoWarn);CS1591;NU1701 + + false + $(DefineConstants);TIZEN;TIZEN_API15 + + + + + + + + + + + + + + + + + + + + + + + + + + <_TizenRefPackDir>$(NuGetPackageRoot)$(TizenReferencePackId.ToLowerInvariant())/$(TizenReferencePackVersion)/ref/net8.0/ + + + + + + + + + + + diff --git a/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs new file mode 100644 index 00000000..c164c881 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/FacadeAndMainThreadOwnershipTests.cs @@ -0,0 +1,236 @@ +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. +/// +public class FacadeAndMainThreadOwnershipTests +{ + static readonly Assembly Backend = typeof(TizenAppInfo).Assembly; + + /// + /// The Essentials contracts MAUI actually bridges from DI onto their static facades, read out of + /// Microsoft.Maui.Hosting.EssentialsExtensions itself. + /// + /// + /// + /// 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() + { + 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 EveryRegisteredContractIsActuallyBridgedByMaui() + { + var bridged = MauiBridgedContracts.Value; + + var notBridged = TizenEssentialsRegistrationTests.ExpectedRegistrations.Keys + .Select(t => t.Name) + .Where(name => !bridged.Contains(name)) + .ToList(); + + Assert.Empty(notBridged); + } + + [Fact] + public void GeocodingIsBridgedEvenThoughItIsRegisteredThroughAFactory() => + Assert.Contains(nameof(IGeocoding), MauiBridgedContracts.Value); + + [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 = 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 = 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/FacadeBridgeIntegrationTests.cs b/tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs new file mode 100644 index 00000000..9dd1ca1b --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/FacadeBridgeIntegrationTests.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.DataTransfer; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Hosting; +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); + } + + [Theory] + [InlineData(typeof(IBattery), typeof(TizenBattery))] + [InlineData(typeof(ILauncher), typeof(TizenLauncher))] + [InlineData(typeof(IShare), typeof(TizenShare))] + [InlineData(typeof(IPreferences), typeof(TizenPreferences))] + [InlineData(typeof(ISecureStorage), typeof(TizenSecureStorage))] + public void TizenRegistrationReplacesMauiDefaultsWithoutShadowDescriptors( + Type serviceType, + Type expectedImplementation) + { + var builder = MauiApp.CreateBuilder(); + builder.UseMauiApp(); + + // This extra descriptor models a registration-order conflict in addition to MAUI's + // defaults. The backend must remove all predecessors and leave one authoritative service. + builder.Services.AddSingleton(serviceType, static _ => new object()); + builder.AddTizenEssentials(); + + var descriptor = Assert.Single(builder.Services, d => d.ServiceType == serviceType); + Assert.Equal(expectedImplementation, descriptor.ImplementationType); + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + } + + [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))); + } + + sealed class BridgeApplication : Application + { + } +} + +/// +/// 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/Maui.Tizen.Essentials.Tests.csproj b/tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj new file mode 100644 index 00000000..de85dda1 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/Maui.Tizen.Essentials.Tests.csproj @@ -0,0 +1,67 @@ + + + + + + $(DotNetTfm) + false + false + true + false + true + $(NoWarn);NETSDK1057 + + + Exe + true + + + + + + + + + + + + + + + + + + + + + <_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..a09b05fa --- /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", "Blocked"]; + + 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..61da0b9f --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenAccelerometerQueueTests.cs @@ -0,0 +1,139 @@ +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 IsNotShakingWithFewerThanFourSamples() + { + var queue = new TizenAccelerometerQueue(); + + queue.Add(0, accelerating: true); + queue.Add(300 * Millisecond, accelerating: true); + queue.Add(400 * Millisecond, accelerating: true); + + Assert.False(queue.IsShaking); + } + + [Theory] + [InlineData(4, 3, true)] + [InlineData(5, 3, false)] + [InlineData(5, 4, true)] + [InlineData(7, 5, false)] + [InlineData(7, 6, true)] + public void UsesExactThreeQuarterThreshold(int count, int accelerating, bool expected) + { + var queue = new TizenAccelerometerQueue(); + var interval = 300 * Millisecond / (count - 1); + + for (var index = 0; index < count; index++) + { + queue.Add( + index * interval, + accelerating: index < accelerating); + } + + Assert.Equal(expected, 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 PurgesEveryExpiredSampleAndUsesMinimumOnlyForDetection() + { + 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.False(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/TizenAppControlReplyTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenAppControlReplyTests.cs new file mode 100644 index 00000000..69e7f93d --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenAppControlReplyTests.cs @@ -0,0 +1,130 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenAppControlReplyTests +{ + [Fact] + public void ReplyWaitIsBounded() + { + Assert.True(TizenAppControlReply.Timeout > TimeSpan.Zero); + Assert.True(TizenAppControlReply.Timeout <= TimeSpan.FromMinutes(1)); + Assert.InRange(TizenAppControlReply.NativeTimeoutMilliseconds, 1u, 60_000u); + } + + [Fact] + public async Task ParseFailureFaultsAndUnsubscribes() + { + Action? callback = null; + var unsubscribed = 0; + var failure = new FormatException("malformed reply"); + + var operation = TizenAppControlReply.RunAsync( + handler => callback = handler, + (_, _) => throw failure, + TestContext.Current.CancellationToken, + handler => + { + if (callback == handler) + callback = null; + unsubscribed++; + }); + + callback!("reply", 0); + + Assert.Same(failure, await Assert.ThrowsAsync(() => operation)); + Assert.Equal(1, unsubscribed); + Assert.Null(callback); + } + + [Fact] + public async Task DuplicateAndLateRepliesAreIgnored() + { + Action? callback = null; + var parseCalls = 0; + + var operation = TizenAppControlReply.RunAsync( + handler => callback = handler, + (reply, _) => + { + parseCalls++; + return reply; + }, + TestContext.Current.CancellationToken); + + var nativeCallback = callback!; + nativeCallback("first", 0); + nativeCallback("duplicate", 0); + + Assert.Equal("first", await operation); + Assert.Equal(1, parseCalls); + } + + [Fact] + public async Task CancellationSettlesNeverReplyAndUnsubscribes() + { + using var cancellation = new CancellationTokenSource(); + Action? callback = null; + var unsubscribed = 0; + + var operation = TizenAppControlReply.RunAsync( + handler => callback = handler, + static (reply, _) => reply, + cancellation.Token, + handler => + { + if (callback == handler) + callback = null; + unsubscribed++; + }); + + cancellation.Cancel(); + + var exception = await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(cancellation.Token, exception.CancellationToken); + Assert.Equal(1, unsubscribed); + Assert.Null(callback); + } + + [Fact] + public async Task NeverReplyTimesOutAndUnsubscribes() + { + Action? callback = null; + var unsubscribed = 0; + + var operation = TizenAppControlReply.RunAsync( + handler => callback = handler, + static (reply, _) => reply, + cancellationToken: TestContext.Current.CancellationToken, + unsubscribe: handler => + { + if (callback == handler) + callback = null; + unsubscribed++; + }, + timeoutOverride: TimeSpan.FromMilliseconds(25)); + + await Assert.ThrowsAsync(() => operation); + Assert.Equal(1, unsubscribed); + Assert.Null(callback); + } + + [Fact] + public async Task SynchronousReplyIsHandledExactlyOnce() + { + var result = await TizenAppControlReply.RunAsync( + handler => + { + handler("inline", 0); + handler("duplicate", 0); + }, + static (reply, _) => reply, + TestContext.Current.CancellationToken); + + Assert.Equal("inline", result); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs new file mode 100644 index 00000000..8f5da69f --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenClipboardCoordinatorTests.cs @@ -0,0 +1,428 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenClipboardCoordinatorTests +{ + [Fact] + public async Task TextOperationsAndCallbacksStayOnTheDispatcher() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + + await clipboard.SetTextAsync("hello"); + var read = clipboard.GetTextAsync(TestContext.Current.CancellationToken); + await native.WaitForReadAsync(); + await native.CompleteReadAsync(success: true, "hello"); + + Assert.Equal("hello", await read); + Assert.Empty(native.WrongThreadOperations); + } + + [Fact] + public async Task CancellationSettlesOnceAndIgnoresALateCallback() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + using var cancellation = new CancellationTokenSource(); + + var read = clipboard.GetTextAsync(cancellation.Token); + await native.WaitForReadAsync(); + cancellation.Cancel(); + + var exception = await Assert.ThrowsAnyAsync(() => read); + Assert.Equal(cancellation.Token, exception.CancellationToken); + + await native.CompleteReadAsync(success: true, "late"); + Assert.True(read.IsCanceled); + Assert.Empty(native.WrongThreadOperations); + } + + [Fact] + public async Task CancellationBeforeQueuedNativeReadSkipsTheRequest() + { + using var dispatcher = new StrictDispatcher(blockFirst: true); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + using var cancellation = new CancellationTokenSource(); + + var read = clipboard.GetTextAsync(cancellation.Token); + await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + cancellation.Cancel(); + dispatcher.Release(); + + await Assert.ThrowsAnyAsync(() => read); + Assert.Equal(0, native.ReadCalls); + } + + [Fact] + public async Task DisposalBeforeQueuedNativeReadSettlesCallerAndSkipsTheRequest() + { + using var dispatcher = new StrictDispatcher(blockFirst: true); + var native = new FakeClipboardNative(dispatcher); + var clipboard = new TizenClipboard(dispatcher, native); + + var read = clipboard.GetTextAsync(TestContext.Current.CancellationToken); + await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + clipboard.Dispose(); + dispatcher.Release(); + + await Assert.ThrowsAsync(() => read); + Assert.Equal(0, native.ReadCalls); + } + + [Fact] + public async Task DisposalCancelsPendingReadAndUnsubscribesChangeEvent() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + var clipboard = new TizenClipboard(dispatcher, native); + var changed = 0; + clipboard.ClipboardContentChanged += (_, _) => changed++; + + var read = clipboard.GetTextAsync(TestContext.Current.CancellationToken); + await native.WaitForReadAsync(); + clipboard.Dispose(); + + await Assert.ThrowsAsync(() => read); + await native.RaiseChangedAsync(); + Assert.Equal(0, changed); + Assert.Equal(0, native.ChangeSubscriberCount); + Assert.Equal(1, native.StopNotificationsCalls); + Assert.Empty(native.WrongThreadOperations); + } + + [Fact] + public async Task ChangeNotificationIsPostedAndIgnoredAfterUnsubscribe() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler handler = (_, _) => changed.TrySetResult(); + + clipboard.ClipboardContentChanged += handler; + await native.RaiseChangedAsync(); + await changed.Task.WaitAsync( + TimeSpan.FromMilliseconds(250), + TestContext.Current.CancellationToken); + clipboard.ClipboardContentChanged -= handler; + + Assert.Equal(0, native.ChangeSubscriberCount); + Assert.Equal(1, native.StartNotificationsCalls); + Assert.Equal(1, native.StopNotificationsCalls); + Assert.Empty(native.WrongThreadOperations); + } + + [Fact] + public void FailedSecondarySelectionTransitionRollsBackSubscriber() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher) { FailStartNotifications = true }; + using var clipboard = new TizenClipboard(dispatcher, native); + EventHandler handler = static (_, _) => { }; + + Assert.Throws(() => + clipboard.ClipboardContentChanged += handler); + Assert.Equal(1, native.StartNotificationsCalls); + Assert.Equal(1, native.StopNotificationsCalls); + Assert.Equal(0, native.ChangeSubscriberCount); + + native.FailStartNotifications = false; + clipboard.ClipboardContentChanged += handler; + Assert.Equal(2, native.StartNotificationsCalls); + } + + [Fact] + public async Task SynchronousSecondarySelectionCallbackDoesNotDeadlockSubscription() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher) { RaiseOnStart = true }; + using var clipboard = new TizenClipboard(dispatcher, native); + EventHandler handler = static (_, _) => { }; + + var subscribe = Task.Run( + () => clipboard.ClipboardContentChanged += handler, + TestContext.Current.CancellationToken); + + await subscribe.WaitAsync(TestContext.Current.CancellationToken); + Assert.Equal(1, native.StartNotificationsCalls); + } + + [Fact] + public async Task QueuedOldNotificationDoesNotReachReplacementSubscriber() + { + using var dispatcher = new StrictDispatcher(); + var native = new FakeClipboardNative(dispatcher); + using var clipboard = new TizenClipboard(dispatcher, native); + var oldCalls = 0; + var replacementCalls = 0; + EventHandler old = (_, _) => oldCalls++; + EventHandler replacement = (_, _) => replacementCalls++; + + clipboard.ClipboardContentChanged += old; + var blocked = dispatcher.BlockNextDeferred(); + await native.RaiseChangedAsync(); + await blocked.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + clipboard.ClipboardContentChanged -= old; + clipboard.ClipboardContentChanged += replacement; + blocked.Release(); + await blocked.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); + + Assert.Equal(0, oldCalls); + 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 = []; + readonly ManualResetEventSlim _started = new(); + readonly ManualResetEventSlim _release = new(); + readonly Thread _thread; + readonly bool _blockFirst; + readonly object _deferredLock = new(); + BlockedDeferred? _nextDeferred; + int _actions; + + public StrictDispatcher(bool blockFirst = false) + { + _blockFirst = blockFirst; + _thread = new Thread(Run) { IsBackground = true }; + _thread.Start(); + _started.Wait(); + } + + public int ThreadId { get; private set; } + + public TaskCompletionSource Queued { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Invoke(Action action) => InvokeAsync(action).GetAwaiter().GetResult(); + + public Task InvokeAsync(Action action) => + InvokeAsync(() => + { + action(); + return true; + }); + + public Task InvokeAsync(Func action) + { + if (Thread.CurrentThread.ManagedThreadId == ThreadId) + return Task.FromResult(action()); + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _work.Add(() => + { + try + { + completion.TrySetResult(action()); + } + catch (Exception exception) + { + completion.TrySetException(exception); + } + }); + return completion.Task; + } + + public void PostDeferred(Action action) + { + BlockedDeferred? blocked; + lock (_deferredLock) + { + blocked = _nextDeferred; + _nextDeferred = null; + } + + if (blocked is not null) + { + blocked.SetRelease(() => _work.Add(() => + { + action(); + blocked.Drained.TrySetResult(); + })); + blocked.Queued.TrySetResult(); + return; + } + + _work.Add(action); + } + + public BlockedDeferred BlockNextDeferred() + { + lock (_deferredLock) + { + if (_nextDeferred is not null) + throw new InvalidOperationException("A deferred callback is already blocked."); + + return _nextDeferred = new BlockedDeferred(); + } + } + + public void Release() => _release.Set(); + + public void Dispose() + { + _work.CompleteAdding(); + _release.Set(); + _thread.Join(); + _release.Dispose(); + _started.Dispose(); + _work.Dispose(); + } + + void Run() + { + ThreadId = Thread.CurrentThread.ManagedThreadId; + _started.Set(); + foreach (var action in _work.GetConsumingEnumerable()) + { + if (_blockFirst && Interlocked.Increment(ref _actions) == 1) + { + Queued.TrySetResult(); + _release.Wait(); + } + action(); + } + } + + public sealed class BlockedDeferred + { + Action? _release; + + public TaskCompletionSource Queued { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Drained { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Release() => + Interlocked.Exchange(ref _release, null)?.Invoke(); + + internal void SetRelease(Action release) => _release = release; + } + } + + sealed class FakeClipboardNative : ITizenClipboardNative + { + readonly StrictDispatcher _dispatcher; + readonly TaskCompletionSource _readRequested = + new(TaskCreationOptions.RunContinuationsAsynchronously); + Action? _readCallback; + Action? _dataSelected; + + public FakeClipboardNative(StrictDispatcher dispatcher) + { + _dispatcher = dispatcher; + } + + public ConcurrentQueue WrongThreadOperations { get; } = []; + + public int ReadCalls { get; private set; } + + 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; } + + public bool FailStartNotifications { get; set; } + + public bool RaiseOnStart { get; set; } + + public void StartChangeNotifications(Action changed) + { + AssertThread("start notifications"); + StartNotificationsCalls++; + Action dataSelected = () => changed(); + _dataSelected = dataSelected; + RetainedDataSelectedHandlers.Add(dataSelected); + if (RaiseOnStart) + dataSelected(); + if (FailStartNotifications) + { + _dataSelected = null; + StopNotificationsCalls++; + throw new InvalidOperationException("secondary selection failed"); + } + } + + public void StopChangeNotifications() + { + AssertThread("stop notifications"); + StopNotificationsCalls++; + _dataSelected = null; + } + + public bool SetText(string text) + { + AssertThread(nameof(SetText)); + return true; + } + + public void GetText(Action callback) + { + AssertThread(nameof(GetText)); + ReadCalls++; + _readCallback = callback; + _readRequested.TrySetResult(); + } + + public Task WaitForReadAsync() => + _readRequested.Task.WaitAsync(TestContext.Current.CancellationToken); + + public Task CompleteReadAsync(bool success, string? text) => + _dispatcher.InvokeAsync(() => _readCallback?.Invoke(success, 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) + WrongThreadOperations.Enqueue(operation); + } + } +} 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/TizenEssentialsRegistrationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenEssentialsRegistrationTests.cs new file mode 100644 index 00000000..f2653cab --- /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 ReplacesAnEarlierRegistrationWithoutLeavingAShadowDescriptor(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.Equal(ExpectedRegistrations[serviceType], descriptor.ImplementationType); + Assert.Null(descriptor.ImplementationFactory); + } + + [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/TizenEventSubscriptionCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs new file mode 100644 index 00000000..f544f38f --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenEventSubscriptionCoordinatorTests.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenEventSubscriptionCoordinatorTests +{ + [Fact] + public void NativeStartRunsWithoutHoldingTheStateLock() + { + using var dispatcher = new StrictCallbackDispatcher(); + TizenEventSubscriptionCoordinator? coordinator = null; + var started = false; + coordinator = new( + this, + generation => + { + generation.Publish(EventArgs.Empty); + started = true; + return static () => { }; + }, + new TizenNativeCallbackCoordinator(dispatcher)); + + coordinator.Add(static (_, _) => { }); + + Assert.True(started); + } + + [Fact] + public async Task StaleQueuedEventNeverReachesReplacementSubscriber() + { + using var dispatcher = new StrictCallbackDispatcher(blockFirst: true); + var oldCalls = 0; + var replacementCalls = 0; + Action? currentNative = null; + var retained = new List(); + EventHandler old = (_, _) => oldCalls++; + var replacementDelivered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler replacement = (_, _) => + { + replacementCalls++; + replacementDelivered.TrySetResult(); + }; + var coordinator = new TizenEventSubscriptionCoordinator( + this, + generation => + { + 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(); + await dispatcher.Queued.Task.WaitAsync( + TimeSpan.FromMilliseconds(250), + TestContext.Current.CancellationToken); + coordinator.Remove(old); + coordinator.Add(replacement); + Assert.NotSame(oldNative, currentNative); + oldNative(); + dispatcher.Release(); + await dispatcher.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); + + Assert.Equal(0, oldCalls); + Assert.Equal(0, replacementCalls); + + currentNative!(); + await replacementDelivered.Task.WaitAsync( + TimeSpan.FromMilliseconds(250), + TestContext.Current.CancellationToken); + Assert.Equal(1, replacementCalls); + } + + [Fact] + public void FailedFirstSubscriptionRollsBackAndCanBeRetried() + { + using var dispatcher = new StrictCallbackDispatcher(); + var native = false; + var fail = true; + var coordinator = new TizenEventSubscriptionCoordinator( + this, + generation => + { + try + { + native = true; + if (fail) + throw new InvalidOperationException("subscribe failed"); + return () => native = false; + } + catch + { + native = false; + throw; + } + }, + new TizenNativeCallbackCoordinator(dispatcher)); + EventHandler handler = static (_, _) => { }; + + Assert.Throws(() => coordinator.Add(handler)); + Assert.False(native); + + fail = false; + coordinator.Add(handler); + Assert.True(native); + } + + [Fact] + 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, + generation => + { + native = true; + nativeCallback = () => generation.Publish(EventArgs.Empty); + return () => native = false; + }, + new TizenNativeCallbackCoordinator(dispatcher)); + coordinator.Add((_, _) => calls++); + coordinator.Add((_, _) => calls++); + nativeCallback!(); + await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + coordinator.Dispose(); + dispatcher.Release(); + await dispatcher.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); + + Assert.False(native); + Assert.Equal(0, calls); + } + + sealed class StrictCallbackDispatcher : ITizenNativeCallbackDispatcher, IDisposable + { + readonly BlockingCollection _work = []; + readonly ManualResetEventSlim _release = new(); + readonly Thread _thread; + readonly bool _blockFirst; + + public StrictCallbackDispatcher(bool blockFirst = false) + { + _blockFirst = blockFirst; + _thread = new Thread(Run) { IsBackground = true }; + _thread.Start(); + } + + public TaskCompletionSource Queued { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Drained { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void PostDeferred(Action action) => _work.Add(action); + + public void Release() => _release.Set(); + + public void Dispose() + { + _release.Set(); + _work.CompleteAdding(); + _thread.Join(); + _release.Dispose(); + _work.Dispose(); + } + + void Run() + { + foreach (var action in _work.GetConsumingEnumerable()) + { + Queued.TrySetResult(); + if (_blockFirst) + _release.Wait(); + action(); + Drained.TrySetResult(); + } + } + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenFileResultBlockerTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenFileResultBlockerTests.cs new file mode 100644 index 00000000..5d7354ef --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenFileResultBlockerTests.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.ApplicationModel.Communication; +using Microsoft.Maui.ApplicationModel.DataTransfer; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Microsoft.Maui.Storage; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenFileResultBlockerTests +{ + [Fact] + public async Task NeutralFileResultCannotOpenAnExistingTizenPath() + { + var directory = Path.Combine(AppContext.BaseDirectory, "file-result-blocker"); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "picked.txt"); + await File.WriteAllTextAsync(path, "picked", TestContext.Current.CancellationToken); + + try + { + var result = new FileResult(path, "text/plain"); + + Assert.Equal(path, result.FullPath); + Assert.Equal("text/plain", result.ContentType); + var exception = await Record.ExceptionAsync(() => result.OpenReadAsync()); + + Assert.NotNull(exception); + Assert.Equal("NotImplementedInReferenceAssemblyException", exception.GetType().Name); + } + finally + { + File.Delete(path); + Directory.Delete(directory); + } + } + + [Fact] + public void FileBaseWrapperFlowsAreBlockedButExplicitPathFallbackWorks() + { + var result = new FileResult("/data/media/photo.png", "image/png"); + + Assert.Equal( + "NotImplementedInReferenceAssemblyException", + Assert.ThrowsAny(() => new ShareFile(result)).GetType().Name); + Assert.Equal( + "NotImplementedInReferenceAssemblyException", + Assert.ThrowsAny(() => new EmailAttachment(result)).GetType().Name); + Assert.Equal( + "NotImplementedInReferenceAssemblyException", + Assert.ThrowsAny(() => new OpenFileRequest("Photo", result)).GetType().Name); + + var share = TizenShare.CreateFilePayload([new ShareFile(result.FullPath, "image/png")]); + var email = TizenEmail.CreateAttachmentPayload([new EmailAttachment(result.FullPath, "image/png")]); + var launch = TizenLauncher.CreateOpenFilePayload( + new OpenFileRequest("Photo", new ReadOnlyFile(result.FullPath, "image/png"))); + + Assert.Equal(["/data/media/photo.png"], share.Paths); + Assert.Equal(["/data/media/photo.png"], email.Paths); + Assert.Equal("image/png", share.Mime); + Assert.Equal("image/png", email.Mime); + Assert.Equal("image/png", launch.Mime); + Assert.Equal("file:///data/media/photo.png", launch.Uri); + + var pathOnlyLaunch = TizenLauncher.CreateOpenFilePayload( + new OpenFileRequest + { + Title = "Document", + File = new ReadOnlyFile("/data/media/document.pdf"), + }); + Assert.Equal("application/pdf", pathOnlyLaunch.Mime); + } +} 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/TizenNativeCallbackCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenNativeCallbackCoordinatorTests.cs new file mode 100644 index 00000000..eb1db484 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenNativeCallbackCoordinatorTests.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenNativeCallbackCoordinatorTests +{ + [Fact] + public async Task CallbackIsAsynchronouslyPostedToTheDispatcherThread() + { + using var dispatcher = new StrictDispatcher(); + var coordinator = new TizenNativeCallbackCoordinator(dispatcher); + var callbackThread = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + var returned = false; + + coordinator.Post( + static () => true, + () => callbackThread.TrySetResult(Thread.CurrentThread.ManagedThreadId)); + returned = true; + + Assert.True(returned); + Assert.Equal( + dispatcher.ThreadId, + await callbackThread.Task.WaitAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task QueuedCallbackRechecksGenerationOrSubscriptionState() + { + using var dispatcher = new StrictDispatcher(blockFirst: true); + var coordinator = new TizenNativeCallbackCoordinator(dispatcher); + var current = true; + var called = false; + + coordinator.Post(() => current, () => called = true); + await dispatcher.Queued.Task.WaitAsync(TestContext.Current.CancellationToken); + current = false; + dispatcher.Release(); + await dispatcher.Drained.Task.WaitAsync(TestContext.Current.CancellationToken); + + Assert.False(called); + } + + [Fact] + public void ProductionDispatcherAddsASecondHopWhenMainThreadDispatchIsInline() + { + var context = new QueuedSynchronizationContext(); + var called = false; + + TizenNativeCallbackDispatcher.PostDeferred( + beginInvoke: callback => callback(), + getContext: () => context, + action: () => called = true); + + Assert.False(called); + Assert.Equal(1, context.Pending); + context.RunOne(); + Assert.True(called); + } + + sealed class StrictDispatcher : ITizenNativeCallbackDispatcher, IDisposable + { + readonly BlockingCollection _work = []; + readonly ManualResetEventSlim _started = new(); + readonly ManualResetEventSlim _release = new(); + readonly Thread _thread; + readonly bool _blockFirst; + + public StrictDispatcher(bool blockFirst = false) + { + _blockFirst = blockFirst; + _thread = new Thread(Run) { IsBackground = true }; + _thread.Start(); + _started.Wait(); + } + + public int ThreadId { get; private set; } + + public TaskCompletionSource Queued { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Drained { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void PostDeferred(Action action) => _work.Add(action); + + public void Release() => _release.Set(); + + public void Dispose() + { + _release.Set(); + _work.CompleteAdding(); + _thread.Join(); + _release.Dispose(); + _started.Dispose(); + _work.Dispose(); + } + + void Run() + { + ThreadId = Thread.CurrentThread.ManagedThreadId; + _started.Set(); + foreach (var action in _work.GetConsumingEnumerable()) + { + Queued.TrySetResult(); + if (_blockFirst) + _release.Wait(); + action(); + Drained.TrySetResult(); + } + } + + } + + sealed class QueuedSynchronizationContext : SynchronizationContext + { + readonly Queue<(SendOrPostCallback Callback, object? State)> _work = []; + + public int Pending => _work.Count; + + public override void Post(SendOrPostCallback d, object? state) => + _work.Enqueue((d, state)); + + public void RunOne() + { + var (callback, state) = _work.Dequeue(); + callback(state); + } + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenPermissionRequestCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionRequestCoordinatorTests.cs new file mode 100644 index 00000000..3c4f1ec0 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionRequestCoordinatorTests.cs @@ -0,0 +1,131 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenPermissionRequestCoordinatorTests +{ + const string Privilege = "http://tizen.org/privilege/location"; + + [Fact] + public async Task SynchronousAnswerCompletesAndUnsubscribes() + { + var source = new FakePermissionRequestSource + { + OnRequest = self => self.Reply( + global::Tizen.Security.CallCause.Answer, + global::Tizen.Security.RequestResult.AllowForever, + Privilege), + }; + + Assert.True(await RunAsync(source, TestContext.Current.CancellationToken)); + Assert.Equal(0, source.SubscriberCount); + } + + [Fact] + public async Task NoResponseTimesOutAndUnsubscribes() + { + var source = new FakePermissionRequestSource(); + + await Assert.ThrowsAsync(() => + RunAsync( + source, + TestContext.Current.CancellationToken, + TimeSpan.FromMilliseconds(25))); + Assert.Equal(0, source.SubscriberCount); + } + + [Fact] + public async Task CallerCancellationUsesItsTokenAndUnsubscribes() + { + var source = new FakePermissionRequestSource(); + using var cancellation = new CancellationTokenSource(); + + var request = RunAsync(source, cancellation.Token); + cancellation.Cancel(); + + var exception = await Assert.ThrowsAnyAsync(() => request); + Assert.Equal(cancellation.Token, exception.CancellationToken); + Assert.Equal(0, source.SubscriberCount); + } + + [Fact] + public async Task DuplicateAndLateAnswersAreIgnored() + { + var source = new FakePermissionRequestSource(); + var request = RunAsync(source, TestContext.Current.CancellationToken); + + source.Reply( + global::Tizen.Security.CallCause.Answer, + global::Tizen.Security.RequestResult.AllowForever, + Privilege); + source.Reply( + global::Tizen.Security.CallCause.Answer, + global::Tizen.Security.RequestResult.DenyForever, + Privilege); + + var granted = await request; + Assert.True(granted); + Assert.Equal(0, source.SubscriberCount); + source.Reply( + global::Tizen.Security.CallCause.Answer, + global::Tizen.Security.RequestResult.DenyForever, + Privilege); + Assert.True(granted); + } + + [Theory] + [InlineData(global::Tizen.Security.CallCause.Error, Privilege)] + [InlineData(global::Tizen.Security.CallCause.Answer, "http://tizen.org/privilege/camera")] + public async Task ErrorOrMismatchedAnswerFailsClosed( + global::Tizen.Security.CallCause cause, + string responsePrivilege) + { + var source = new FakePermissionRequestSource(); + var request = RunAsync(source, TestContext.Current.CancellationToken); + + source.Reply( + cause, + global::Tizen.Security.RequestResult.AllowForever, + responsePrivilege); + + await Assert.ThrowsAsync(() => request); + Assert.Equal(0, source.SubscriberCount); + } + + static Task RunAsync( + FakePermissionRequestSource source, + CancellationToken cancellationToken, + TimeSpan? timeout = null) => + TizenPermissionRequestCoordinator.RunAsync( + Privilege, + source, + cancellationToken, + timeout ?? TimeSpan.FromSeconds(5)); + + sealed class FakePermissionRequestSource : ITizenPermissionRequestSource + { + Action? _response; + + public Action? OnRequest { get; init; } + + public int SubscriberCount => _response?.GetInvocationList().Length ?? 0; + + public event Action? Response + { + add => _response += value; + remove => _response -= value; + } + + public void Request() => OnRequest?.Invoke(this); + + public void Reply( + global::Tizen.Security.CallCause cause, + global::Tizen.Security.RequestResult result, + string privilege) => + _response?.Invoke(new(cause, result, privilege)); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs new file mode 100644 index 00000000..1a2f5477 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenPermissionsTests.cs @@ -0,0 +1,305 @@ +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 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.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() + { + // 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(); + + Assert.Empty(empty); + } + + [Fact] + public void OnlyBatteryIsClaimedUngatedAndItSaysWhy() + { + 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( + [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.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() + { + var mapping = Mapping(typeof(Permissions.NetworkState)); + + Assert.Equal( + new[] + { + "http://tizen.org/privilege/internet", + "http://tizen.org/privilege/network.get", + }, + mapping.Privileges.Select(p => p.Privilege).OrderBy(p => p, StringComparer.Ordinal)); + + Assert.All(mapping.Privileges, p => Assert.False(p.IsRuntime)); + } + + [Fact] + public void CoversEveryBuiltInMauiPermissionType() + { + var builtIn = BuiltInPermissions(); + + Assert.NotEmpty(builtIn); + + var unmapped = builtIn + .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() + { + 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.TryGetKnownMapping(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)); + + [Fact] + public void RejectsARequiresMappingWithNoPrivileges() => + Assert.Throws(static () => TizenPermissionMapping.Requires()); + + [Theory] + [InlineData(global::Tizen.Security.RequestResult.AllowForever, true)] + [InlineData(global::Tizen.Security.RequestResult.DenyForever, false)] + [InlineData(global::Tizen.Security.RequestResult.DenyOnce, false)] + public void PermissionAnswerInterpretsOnlyTheRequestedPrivilege( + global::Tizen.Security.RequestResult result, + bool expected) => + Assert.Equal( + expected, + TizenPermissions.InterpretRequestResponse( + "http://tizen.org/privilege/location", + global::Tizen.Security.CallCause.Answer, + result, + "http://tizen.org/privilege/location")); + + [Fact] + public void PermissionErrorCauseFailsInsteadOfInterpretingResult() => + Assert.Throws(() => + TizenPermissions.InterpretRequestResponse( + "http://tizen.org/privilege/location", + global::Tizen.Security.CallCause.Error, + global::Tizen.Security.RequestResult.AllowForever, + "http://tizen.org/privilege/location")); + + [Fact] + public void PermissionAnswerForAnotherPrivilegeFailsClosed() => + Assert.Throws(() => + TizenPermissions.InterpretRequestResponse( + "http://tizen.org/privilege/location", + global::Tizen.Security.CallCause.Answer, + global::Tizen.Security.RequestResult.AllowForever, + "http://tizen.org/privilege/camera")); + + sealed class DerivedCameraPermission : Permissions.Camera + { + } + + sealed class CustomPermission : TizenBasePlatformPermission + { + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenScreenshotCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenScreenshotCoordinatorTests.cs new file mode 100644 index 00000000..996dfe70 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenScreenshotCoordinatorTests.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; +using TizenPixelFormat = Tizen.NUI.PixelFormat; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenScreenshotCoordinatorTests +{ + [Fact] + public async Task EveryCaptureOperationRunsOnTheCapturedDispatcher() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher) + { + Buffer = new([1, 2, 3, 4], 1, 1, 4, TizenPixelFormat.RGBA8888), + }; + using var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + + var capture = screenshot.CaptureCoreAsync( + () => + { + session.AssertThread("create"); + return session; + }, + TestContext.Current.CancellationToken); + await session.Started.Task; + await session.CompleteAsync(success: true); + var result = await capture; + + Assert.NotNull(result); + Assert.Equal( + ["create", "subscribe", "start", "copy", "unsubscribe", "dispose"], + session.Operations); + Assert.Empty(session.WrongThreadOperations); + } + + [Fact] + public async Task FirstTerminalSignalWinsExactlyOnce() + { + var terminal = new TizenScreenshotTerminalCoordinator(); + + Assert.True(terminal.TryComplete(TizenScreenshotTerminal.NativeSucceeded)); + Assert.False(terminal.TryComplete(TizenScreenshotTerminal.TimedOut)); + Assert.False(terminal.TryComplete(TizenScreenshotTerminal.Canceled)); + Assert.Equal( + TizenScreenshotTerminal.NativeSucceeded, + await terminal.Completion); + } + + [Fact] + public async Task CancellationDisposesOnDispatcherAndIgnoresLateCompletion() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher); + using var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + using var cancellation = new CancellationTokenSource(); + + var capture = screenshot.CaptureCoreAsync( + () => session, + cancellation.Token); + await session.Started.Task; + cancellation.Cancel(); + + var exception = await Assert.ThrowsAnyAsync(() => capture); + Assert.Equal(cancellation.Token, exception.CancellationToken); + await session.Disposed.Task; + await session.CompleteAsync(success: true); + Assert.True(capture.IsCanceled); + Assert.Empty(session.WrongThreadOperations); + } + + [Fact] + public async Task TimeoutDisposesAndLateCallbackCannotResettle() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher); + using var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + + var capture = screenshot.CaptureCoreAsync( + () => session, + CancellationToken.None, + TimeSpan.FromMilliseconds(25)); + await session.Started.Task; + + await Assert.ThrowsAsync(() => capture); + await session.Disposed.Task; + await session.CompleteAsync(success: true); + Assert.True(capture.IsFaulted); + Assert.Empty(session.WrongThreadOperations); + } + + [Fact] + public async Task SuccessfulCompletionAtDeadlineOwnsTerminalWhileBufferCopyRuns() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher) + { + Buffer = new([1, 2, 3, 4], 1, 1, 4, TizenPixelFormat.RGBA8888), + BlockCopy = true, + }; + using var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + + var capture = screenshot.CaptureCoreAsync( + () => session, + CancellationToken.None, + TimeSpan.FromMilliseconds(40)); + await session.Started.Task; + await session.CompleteAsync(success: true); + await session.CopyEntered.Task.WaitAsync(TestContext.Current.CancellationToken); + await Task.Delay(80, TestContext.Current.CancellationToken); + session.ReleaseCopy(); + + Assert.NotNull(await capture); + Assert.Equal(1, session.CopyCalls); + Assert.Empty(session.WrongThreadOperations); + } + + [Fact] + public async Task DuplicateAndLateNativeCompletionCannotResettle() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher) + { + Buffer = new([1, 2, 3, 4], 1, 1, 4, TizenPixelFormat.RGBA8888), + }; + using var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + + var capture = screenshot.CaptureCoreAsync( + () => session, + TestContext.Current.CancellationToken); + await session.Started.Task; + await session.CompleteAsync(success: true); + await session.CompleteAsync(success: false); + + Assert.NotNull(await capture); + Assert.Equal(1, session.CopyCalls); + } + + [Fact] + public async Task DisposalWinsBeforeNativeCompletionAndCleansUpOnDispatcher() + { + using var dispatcher = new StrictScreenshotDispatcher(); + var session = new FakeCaptureSession(dispatcher); + var screenshot = new TizenScreenshot(dispatcher, new UnusedFactory()); + + var capture = screenshot.CaptureCoreAsync( + () => session, + TestContext.Current.CancellationToken); + await session.Started.Task; + screenshot.Dispose(); + + await Assert.ThrowsAsync(() => capture); + await session.Disposed.Task; + await session.CompleteAsync(success: true); + Assert.Empty(session.WrongThreadOperations); + } + + [Fact] + public void CopiesPaddedPixelRowsWithoutIncludingStrideBytes() + { + byte[] padded = + [ + 1, 2, 3, 4, 0xEE, 0xEE, 0xEE, 0xEE, + 5, 6, 7, 8, 0xDD, 0xDD, 0xDD, 0xDD, + ]; + + var captured = TizenScreenshotResult.CopyRows( + padded, + width: 1, + height: 2, + stride: 8, + format: TizenPixelFormat.RGBA8888); + + Assert.Equal([1, 2, 3, 4, 5, 6, 7, 8], captured.Pixels); + } + + [Fact] + public void TreatsZeroStrideAsTightlyPacked() + { + var captured = TizenScreenshotResult.CopyRows( + [1, 2, 3, 4, 5, 6, 7, 8], + width: 1, + height: 2, + stride: 0, + format: TizenPixelFormat.RGBA8888); + + Assert.Equal([1, 2, 3, 4, 5, 6, 7, 8], captured.Pixels); + } + + sealed class StrictScreenshotDispatcher : ITizenScreenshotDispatcher, IDisposable + { + readonly BlockingCollection _work = []; + readonly ManualResetEventSlim _started = new(); + readonly Thread _thread; + + public StrictScreenshotDispatcher() + { + _thread = new Thread(Run) { IsBackground = true }; + _thread.Start(); + _started.Wait(); + } + + public int ThreadId { get; private set; } + + public Task InvokeAsync(Action action) => + InvokeAsync(() => + { + action(); + return true; + }); + + public Task InvokeAsync(Func action) + { + if (Thread.CurrentThread.ManagedThreadId == ThreadId) + return Task.FromResult(action()); + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _work.Add(() => + { + try + { + completion.TrySetResult(action()); + } + catch (Exception exception) + { + completion.TrySetException(exception); + } + }); + return completion.Task; + } + + 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 FakeCaptureSession : ITizenScreenshotCaptureSession + { + readonly StrictScreenshotDispatcher _dispatcher; + Action? _finished; + readonly ManualResetEventSlim _releaseCopy = new(); + + public FakeCaptureSession(StrictScreenshotDispatcher dispatcher) + { + _dispatcher = dispatcher; + } + + public TizenCapturedBuffer? Buffer { get; init; } + + public bool BlockCopy { get; init; } + + public int CopyCalls { get; private set; } + + public ConcurrentQueue WrongThreadOperations { get; } = []; + + public List Operations { get; } = []; + + public TaskCompletionSource Started { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Disposed { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource CopyEntered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public event Action? Finished + { + add + { + AssertThread("subscribe"); + _finished += value; + } + remove + { + AssertThread("unsubscribe"); + _finished -= value; + } + } + + public void Start() + { + AssertThread("start"); + Started.TrySetResult(); + } + + public TizenCapturedBuffer? CopyBuffer() + { + AssertThread("copy"); + CopyCalls++; + CopyEntered.TrySetResult(); + if (BlockCopy) + _releaseCopy.Wait(TestContext.Current.CancellationToken); + return Buffer; + } + + public void Dispose() + { + AssertThread("dispose"); + _releaseCopy.Set(); + _releaseCopy.Dispose(); + Disposed.TrySetResult(); + } + + public Task CompleteAsync(bool success) => + _dispatcher.InvokeAsync(() => _finished?.Invoke(success)); + + public void ReleaseCopy() => _releaseCopy.Set(); + + public void AssertThread(string operation) + { + Operations.Add(operation); + if (Thread.CurrentThread.ManagedThreadId != _dispatcher.ThreadId) + WrongThreadOperations.Enqueue(operation); + } + } + + sealed class UnusedFactory : ITizenScreenshotCaptureFactory + { + public ITizenScreenshotCaptureSession CreateDefaultWindowCapture() => + throw new NotSupportedException(); + + public ITizenScreenshotCaptureSession CreateWindowCapture(global::Tizen.NUI.Window window) => + throw new NotSupportedException(); + + public ITizenScreenshotCaptureSession CreateViewCapture(global::Tizen.NUI.BaseComponents.View view) => + throw new NotSupportedException(); + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenSensorCoordinatorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenSensorCoordinatorTests.cs new file mode 100644 index 00000000..0818b3ce --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenSensorCoordinatorTests.cs @@ -0,0 +1,294 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Maui.Platforms.Tizen.Essentials; +using Xunit; + +namespace Maui.Tizen.Essentials.Tests; + +public class TizenSensorCoordinatorTests +{ + [Fact] + public void MultipleWrappersShareOneNativeLifetime() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var sensor = new FakeSensor(); + var first = new object(); + var second = new object(); + var firstSubscribed = false; + var secondSubscribed = false; + + Start(coordinator, first, sensor, 200, () => firstSubscribed = true, () => firstSubscribed = false); + Start(coordinator, second, sensor, 20, () => secondSubscribed = true, () => secondSubscribed = false); + + Assert.Equal(1, sensor.StartCalls); + Assert.Equal(20u, sensor.Interval); + Assert.True(firstSubscribed); + Assert.True(secondSubscribed); + + Stop(coordinator, first, sensor); + Assert.Equal(0, sensor.StopCalls); + Assert.False(firstSubscribed); + Assert.True(secondSubscribed); + + Stop(coordinator, second, sensor); + Assert.Equal(1, sensor.StopCalls); + Assert.Equal(1, sensor.ResetCalls); + Assert.False(secondSubscribed); + } + + [Fact] + public void FailedStartUnsubscribesStopsAndResetsBeforeAnotherStart() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var sensor = new FakeSensor { ThrowOnStart = true }; + var subscribed = false; + + Assert.Throws(() => + Start( + coordinator, + new object(), + sensor, + 60, + () => subscribed = true, + () => subscribed = false)); + + Assert.False(subscribed); + Assert.Equal(0, coordinator.ActiveCount); + Assert.Equal(1, sensor.StopCalls); + Assert.Equal(1, sensor.ResetCalls); + + sensor.ThrowOnStart = false; + Start(coordinator, new object(), sensor, 60, static () => { }, static () => { }); + Assert.Equal(2, sensor.StartCalls); + } + + [Fact] + public void FailedSecondOwnerDoesNotStopOrResetTheSharedSensor() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var sensor = new FakeSensor(); + var first = new object(); + + Start(coordinator, first, sensor, 60, static () => { }, static () => { }); + + Assert.Throws(() => + coordinator.Start( + new object(), + () => throw new InvalidOperationException("must reuse the cached sensor"), + 20, + static (native, value) => native.Interval = value, + static _ => throw new InvalidOperationException("subscribe failed"), + native => native.StartCalls++, + native => native.StopCalls++, + native => native.ResetCalls++, + static () => { }, + static () => { })); + + Assert.Equal(1, coordinator.ActiveCount); + Assert.Equal(1, sensor.StartCalls); + Assert.Equal(0, sensor.StopCalls); + Assert.Equal(0, sensor.ResetCalls); + Assert.Equal(60u, sensor.Interval); + } + + [Fact] + public void SessionStateIsInitializedBeforeNativeStart() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var sensor = new FakeSensor(); + var initialized = false; + + coordinator.Start( + new object(), + () => sensor, + 60, + static (native, value) => native.Interval = value, + static _ => static () => { }, + native => + { + Assert.True(initialized); + native.StartCalls++; + }, + native => native.StopCalls++, + native => native.ResetCalls++, + () => initialized = true, + () => initialized = false); + } + + [Fact] + public async Task StopCompletesSerializedCleanupBeforeANewStart() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var sensor = new FakeSensor(); + var first = new object(); + var second = new object(); + using var stopEntered = new ManualResetEventSlim(); + using var releaseStop = new ManualResetEventSlim(); + + Start(coordinator, first, sensor, 60, static () => { }, static () => { }); + var stop = Task.Run(() => + coordinator.Stop( + first, + static () => { }, + _ => + { + stopEntered.Set(); + releaseStop.Wait(TestContext.Current.CancellationToken); + sensor.StopCalls++; + }, + _ => sensor.ResetCalls++, + static (_, _) => { }, + static () => { }), + TestContext.Current.CancellationToken); + + stopEntered.Wait(TestContext.Current.CancellationToken); + var start = Task.Run( + () => Start(coordinator, second, sensor, 20, static () => { }, static () => { }), + TestContext.Current.CancellationToken); + await Task.Delay(25, TestContext.Current.CancellationToken); + Assert.False(start.IsCompleted); + + releaseStop.Set(); + await Task.WhenAll(stop, start); + Assert.Equal(2, sensor.StartCalls); + } + + [Fact] + public async Task LastOwnerStopFinishesBeforeNewSensorAcquisition() + { + var coordinator = new TizenSensorLifetimeCoordinator(); + var firstSensor = new FakeSensor(); + var secondSensor = new FakeSensor(); + var current = firstSensor; + var invalidated = false; + var first = new object(); + var second = new object(); + using var stopEntered = new ManualResetEventSlim(); + using var releaseStop = new ManualResetEventSlim(); + + coordinator.Start( + first, + () => current, + 60, + static (native, value) => native.Interval = value, + static _ => static () => { }, + native => native.StartCalls++, + native => native.StopCalls++, + native => native.ResetCalls++, + static () => { }, + static () => { }); + + var stop = Task.Run( + () => coordinator.Stop( + first, + () => invalidated = true, + _ => + { + Assert.True(invalidated); + stopEntered.Set(); + releaseStop.Wait(TestContext.Current.CancellationToken); + firstSensor.StopCalls++; + }, + _ => + { + firstSensor.ResetCalls++; + current = secondSensor; + }, + static (native, value) => native.Interval = value, + static () => { }), + TestContext.Current.CancellationToken); + stopEntered.Wait(TestContext.Current.CancellationToken); + + var start = Task.Run( + () => coordinator.Start( + second, + () => current, + 20, + static (native, value) => native.Interval = value, + static _ => static () => { }, + native => native.StartCalls++, + native => native.StopCalls++, + native => native.ResetCalls++, + static () => { }, + static () => { }), + TestContext.Current.CancellationToken); + + await Task.Delay(25, TestContext.Current.CancellationToken); + Assert.Equal(0, secondSensor.StartCalls); + releaseStop.Set(); + await Task.WhenAll(stop, start); + + Assert.Equal(1, firstSensor.StopCalls); + Assert.Equal(1, firstSensor.ResetCalls); + Assert.Equal(1, secondSensor.StartCalls); + } + + [Fact] + public void OldGenerationNeverBecomesCurrentAfterStopStart() + { + var gate = new TizenSensorGenerationGate(); + var first = gate.BeginStart(useSyncContext: true, "sensor"); + Assert.True(gate.IsCurrent(first)); + Assert.True(gate.Invalidate()); + Assert.False(gate.IsCurrent(first)); + + var second = gate.BeginStart(useSyncContext: false, "sensor"); + Assert.False(gate.IsCurrent(first)); + Assert.True(gate.IsCurrent(second)); + Assert.False(gate.UseSyncContext); + } + + static void Start( + TizenSensorLifetimeCoordinator coordinator, + object owner, + FakeSensor sensor, + uint interval, + Action subscribe, + Action unsubscribe) => + coordinator.Start( + owner, + () => sensor, + interval, + static (native, value) => native.Interval = value, + _ => + { + subscribe(); + return unsubscribe; + }, + native => + { + native.StartCalls++; + if (native.ThrowOnStart) + throw new InvalidOperationException("start failed"); + }, + native => native.StopCalls++, + native => native.ResetCalls++, + static () => { }, + static () => { }); + + static void Stop( + TizenSensorLifetimeCoordinator coordinator, + object owner, + FakeSensor sensor) => + coordinator.Stop( + owner, + static () => { }, + native => native.StopCalls++, + native => native.ResetCalls++, + static (native, value) => native.Interval = value, + static () => { }); + + sealed class FakeSensor + { + public uint Interval { get; set; } + + public int StartCalls { get; set; } + + public int StopCalls { get; set; } + + public int ResetCalls { get; set; } + + public bool ThrowOnStart { get; set; } + } +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs new file mode 100644 index 00000000..a0c2b393 --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenServiceBehaviorTests.cs @@ -0,0 +1,2243 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +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 TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenBatteryPowerSource = Tizen.System.BatteryPowerSource; +using TizenColorSpace = Tizen.Multimedia.ColorSpace; +using TizenConnectionState = Tizen.Network.Connection.ConnectionState; +using TizenLocationType = Tizen.Location.LocationType; +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 DefaultAndNamedStoreKeysCannotCollide() + { + 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] + 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); + } + + [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"]); + } + + [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"]); + } + + [Fact] + public void PreferencesEncodeLongAndDateTimeThroughNativeSupportedStrings() + { + var store = new FakePreferencesStore { RejectUnsupportedNativeTypes = true }; + var preferences = new TizenPreferences(store); + var dateTime = new DateTime(638901234567890123, DateTimeKind.Utc); + var offset = new DateTimeOffset(2026, 8, 29, 13, 46, 0, TimeSpan.FromHours(-4)); + + preferences.Set("long", long.MinValue); + preferences.Set("date", dateTime); + preferences.Set("offset", offset); + + Assert.IsType(store[TizenPreferences.GetFullKey("long", null)]); + Assert.IsType(store[TizenPreferences.GetFullKey("date", null)]); + Assert.IsType(store[TizenPreferences.GetFullKey("offset", null)]); + Assert.Equal(long.MinValue, preferences.Get("long", 0L)); + Assert.Equal(dateTime, preferences.Get("date", default(DateTime))); + Assert.Equal(offset, preferences.Get("offset", default(DateTimeOffset))); + } + + [Theory] + [InlineData(0.1f)] + [InlineData(float.MinValue)] + [InlineData(float.MaxValue)] + [InlineData(float.PositiveInfinity)] + [InlineData(float.NegativeInfinity)] + public void PreferencesRoundTripFloatThroughNativeDoubleExactly(float value) + { + var store = new FakePreferencesStore { RejectUnsupportedNativeTypes = true }; + var preferences = new TizenPreferences(store); + + preferences.Set("float", value); + + Assert.IsType(store[TizenPreferences.GetFullKey("float", null)]); + Assert.Equal(value, preferences.Get("float", 0f)); + } + + [Fact] + public void PreferencesRoundTripNaNThroughNativeDouble() + { + var store = new FakePreferencesStore { RejectUnsupportedNativeTypes = true }; + var preferences = new TizenPreferences(store); + + preferences.Set("float", float.NaN); + + Assert.True(float.IsNaN(preferences.Get("float", 0f))); + } + + [Fact] + public void PreferencesRejectCorruptLossyFloatRepresentation() + { + var store = new FakePreferencesStore + { + [TizenPreferences.GetFullKey("float", null)] = 0.1d, + }; + var preferences = new TizenPreferences(store); + + Assert.Throws(() => preferences.Get("float", 0f)); + } + + [Fact] + public void PreferencesReadLegacyUnsupportedRepresentationsAndMigrateThem() + { + var date = new DateTime(638901234567890123, DateTimeKind.Local); + var store = new FakePreferencesStore + { + ["legacy-long"] = long.MaxValue, + ["legacy-date"] = date.ToBinary(), + ["legacy-float"] = 1.25f, + }; + var preferences = new TizenPreferences(store); + + Assert.Equal(long.MaxValue, preferences.Get("legacy-long", 0L)); + Assert.Equal(date, preferences.Get("legacy-date", default(DateTime))); + Assert.Equal(1.25f, preferences.Get("legacy-float", 0f)); + + Assert.IsType(store[TizenPreferences.GetFullKey("legacy-long", null)]); + Assert.IsType(store[TizenPreferences.GetFullKey("legacy-date", null)]); + Assert.IsType(store[TizenPreferences.GetFullKey("legacy-float", null)]); + } + + [Fact] + public void PreferencesUpgradeUnsupportedValuesAlreadyStoredUnderVersionedKeys() + { + var longKey = TizenPreferences.GetFullKey("long", null); + var dateKey = TizenPreferences.GetFullKey("date", null); + var floatKey = TizenPreferences.GetFullKey("float", null); + var date = new DateTime(638901234567890123, DateTimeKind.Utc); + var store = new FakePreferencesStore + { + [longKey] = 42L, + [dateKey] = date.ToBinary(), + [floatKey] = 1.5f, + }; + var preferences = new TizenPreferences(store); + + Assert.Equal(42L, preferences.Get("long", 0L)); + Assert.Equal(date, preferences.Get("date", default(DateTime))); + Assert.Equal(1.5f, preferences.Get("float", 0f)); + Assert.IsType(store[longKey]); + Assert.IsType(store[dateKey]); + Assert.IsType(store[floatKey]); + } + + // ------------------------------------------------------------------------------------------- + // SecureStorage alias namespacing. + // ------------------------------------------------------------------------------------------- + + [Fact] + public void SecureStorageAliasesAreNamespaced() + { + var alias = TizenSecureStorage.ToAlias("token"); + + Assert.StartsWith(TizenSecureStorage.AliasPrefix, alias, StringComparison.Ordinal); + Assert.StartsWith(TizenSecureStorage.AliasPrefix + "~v2~", alias, StringComparison.Ordinal); + Assert.DoesNotContain(alias, char.IsWhiteSpace); + } + + [Fact] + public void SecureStorageAliasesCannotCollideWithEachOther() + { + 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 + 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", "org.example.app", true)] + [InlineData("org.example.app maui.tizen.securestorage:token", "org.example.app", true)] + [InlineData("org.other.app maui.tizen.securestorage:token", "org.example.app", false)] + [InlineData("org.example.app maui.tizen.securestorage:token", null, false)] + [InlineData("some.other.component:token", "org.example.app", false)] + [InlineData("maui.tizen.securestorageX", "org.example.app", false)] + [InlineData("", "org.example.app", false)] + public void RecognisesOnlyItsOwnSecureStorageAliases( + string alias, + string? currentPackageId, + bool owned) => + Assert.Equal(owned, TizenSecureStorage.IsOwnedAlias(alias, currentPackageId)); + + [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))); + } + + [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.Equal("legacy-value", repository["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 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.False(repository.Contains(TizenSecureStorage.ToLegacyNamespacedAlias("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 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() + { + 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() + { + 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 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() + { + var repository = new FakeSecureRepository + { + ["org.current.app " + TizenSecureStorage.ToAlias("mine")] = "delete-me", + ["org.foreign.app " + TizenSecureStorage.ToAlias("theirs")] = "keep-me", + }; + var storage = new TizenSecureStorage( + repository, + currentPackageId: static () => "org.current.app"); + + storage.RemoveAll(); + + Assert.False(repository.Contains("org.current.app " + TizenSecureStorage.ToAlias("mine"))); + Assert.Equal( + "keep-me", + repository["org.foreign.app " + TizenSecureStorage.ToAlias("theirs")]); + } + + [Fact] + public async Task SecureStorageReplacementRestoresV1AndV2WhenCommitFails() + { + var v2 = TizenSecureStorage.ToAlias("token"); + var v1 = TizenSecureStorage.ToLegacyNamespacedAlias("token"); + var repository = new FakeSecureRepository + { + [v2] = "old-v2", + [v1] = "old-v1", + }; + repository.FailSaveCalls.Add(2); + var storage = new TizenSecureStorage(repository); + + await Assert.ThrowsAsync(() => storage.SetAsync("token", "new")); + + Assert.Equal("old-v2", repository[v2]); + Assert.Equal("old-v1", repository[v1]); + Assert.DoesNotContain( + repository.GetAliases(), + alias => alias.StartsWith(TizenSecureStorage.AliasPrefix + "~tx~", StringComparison.Ordinal)); + } + + [Fact] + public async Task SecureStorageSuccessfulReplacementRemovesPreviousVersionDuplicate() + { + var v2 = TizenSecureStorage.ToAlias("token"); + var v1 = TizenSecureStorage.ToLegacyNamespacedAlias("token"); + var repository = new FakeSecureRepository + { + [v2] = "old-v2", + [v1] = "old-v1", + }; + var storage = new TizenSecureStorage(repository); + + await storage.SetAsync("token", "new"); + + Assert.Equal("new", repository[v2]); + Assert.False(repository.Contains(v1)); + Assert.Single(repository.GetAliases()); + } + + [Fact] + public async Task SecureStorageInterruptedReplacementRetainsAndRecoversStagedValue() + { + var v2 = TizenSecureStorage.ToAlias("token"); + var repository = new FakeSecureRepository + { + [v2] = "old", + }; + repository.FailSaveCalls.UnionWith([2, 3]); + var storage = new TizenSecureStorage(repository); + + await Assert.ThrowsAsync(() => storage.SetAsync("token", "new")); + Assert.Contains( + repository.GetAliases(), + alias => alias.StartsWith(TizenSecureStorage.AliasPrefix + "~tx~", StringComparison.Ordinal)); + + Assert.Equal("new", await storage.GetAsync("token")); + Assert.Equal("new", repository[v2]); + Assert.DoesNotContain( + repository.GetAliases(), + alias => alias.StartsWith(TizenSecureStorage.AliasPrefix + "~tx~", StringComparison.Ordinal)); + } + + [Fact] + public async Task SecureStorageRejectsAmbiguousDuplicateInterruptedReplacements() + { + var keyPrefix = TizenSecureStorage.AliasPrefix + "~tx~" + + Convert.ToBase64String(Encoding.UTF8.GetBytes("token")).TrimEnd('=') + "~"; + var repository = new FakeSecureRepository + { + [keyPrefix + "one"] = "first", + [keyPrefix + "two"] = "second", + }; + + var exception = await Assert.ThrowsAsync( + () => new TizenSecureStorage(repository).GetAsync("token")); + + Assert.Contains("Multiple interrupted", exception.Message, StringComparison.Ordinal); + Assert.Equal(2, repository.GetAliases().Count()); + } + + [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"))); + } + + [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 SecureStorageSetAfterRemoveAllSupersedesGlobalTombstone() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToAlias("token")] = "old-value", + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + storage.RemoveAll(); + Assert.Null(await storage.GetAsync("token")); + + await storage.SetAsync("token", "new-value"); + + Assert.Equal("new-value", await storage.GetAsync("token")); + Assert.True(tombstones.ContainsAll); + Assert.False(tombstones.Contains("token")); + } + + [Theory] + [InlineData("current")] + [InlineData("v1")] + [InlineData("staged")] + public async Task SecureStorageRemoveFailureIsSurfacedButTombstoneDominates(string failingAlias) + { + var current = TizenSecureStorage.ToAlias("token"); + var v1 = TizenSecureStorage.ToLegacyNamespacedAlias("token"); + var staged = TizenSecureStorage.AliasPrefix + "~tx~dG9rZW4~crash"; + var repository = new FakeSecureRepository + { + [current] = "current-value", + [v1] = "v1-value", + [staged] = "staged-value", + }; + repository.FailRemoveAliases.Add(failingAlias switch + { + "current" => current, + "v1" => v1, + _ => staged, + }); + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.ThrowsAny(() => storage.Remove("token")); + Assert.Null(await storage.GetAsync("token")); + Assert.True(tombstones.Contains("token")); + } + + [Fact] + public async Task SecureStorageRemoveSurfacesEnumerationFailureAndKeepsDeletionCommitted() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToAlias("token")] = "current-value", + GetAliasesException = new IOException("enumeration failed"), + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.Throws(() => storage.Remove("token")); + Assert.Null(await storage.GetAsync("token")); + } + + [Fact] + public async Task SecureStorageRemoveAllSurfacesEnumerationFailureAndSuppressesExistingData() + { + var repository = new FakeSecureRepository + { + [TizenSecureStorage.ToAlias("token")] = "current-value", + GetAliasesException = new IOException("enumeration failed"), + }; + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.Throws(storage.RemoveAll); + Assert.True(tombstones.ContainsAll); + Assert.Null(await storage.GetAsync("token")); + } + + [Fact] + public async Task SecureStorageRemoveAllSurfacesDeleteFailureAndSuppressesUndeletedAlias() + { + var alias = TizenSecureStorage.ToAlias("token"); + var repository = new FakeSecureRepository { [alias] = "current-value" }; + repository.FailRemoveAliases.Add(alias); + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.ThrowsAny(storage.RemoveAll); + Assert.True(repository.Contains(alias)); + Assert.Null(await storage.GetAsync("token")); + } + + [Fact] + public async Task SecureStorageDeletionTombstonePreventsCrashStagingRecovery() + { + var staged = TizenSecureStorage.AliasPrefix + "~tx~dG9rZW4~crash"; + var repository = new FakeSecureRepository { [staged] = "staged-old-value" }; + repository.FailRemoveAliases.Add(staged); + var tombstones = new FakeSecureStorageTombstones(); + var storage = new TizenSecureStorage(repository, tombstones); + + Assert.ThrowsAny(() => storage.Remove("token")); + Assert.Null(await storage.GetAsync("token")); + Assert.True(repository.Contains(staged)); + } + + [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")]); + } + + [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. + // ------------------------------------------------------------------------------------------- + + [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 TextToSpeechRunsEveryNativeOperationOnTheDispatcherThread() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + 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 languages = await textToSpeech.GetSupportedVoiceLanguagesAsync(); + Assert.Equal(["en_US"], languages); + + textToSpeech.Dispose(); + await client.Disposed.Task; + Assert.Empty(client.WrongThreadOperations); + } + + [Fact] + public async Task TextToSpeechCachesSpeedRangeBeforePrepareAndAppliesRateWhenReady() + { + using var dispatcher = new FakeTextToSpeechDispatcher(); + var factory = new FakeTextToSpeechClientFactory(dispatcher); + using var textToSpeech = new TizenTextToSpeech(dispatcher, factory); + + var speak = textToSpeech.SpeakAsync( + "rate", + new SpeechOptions { Rate = 1.0f }, + TestContext.Current.CancellationToken); + var client = await factory.WaitForClientAsync(); + await client.Played.Task; + + Assert.Equal(["GetSpeedRange", "Prepare", "AddText", "Play"], client.Operations.Take(4)); + Assert.Equal(0, client.LastSpeed); + + await client.CompleteAsync(client.LastUtteranceId); + await speak; + } + + [Theory] + [InlineData(0.1f, -10)] + [InlineData(0.55f, -5)] + [InlineData(1.0f, 0)] + [InlineData(1.5f, 10)] + [InlineData(2.0f, 20)] + public void TextToSpeechMapsMauiRatePiecewiseAcrossNativeRange(float rate, int expected) => + Assert.Equal( + expected, + TizenTextToSpeech.ResolveRate(new(-10, 0, 20), rate)); + + [Fact] + public void TextToSpeechUsesNativeNormalWhenRateIsNull() => + Assert.Equal( + 7, + TizenTextToSpeech.ResolveRate(new(-4, 7, 19), null)); + + [Theory] + [InlineData(0.09f)] + [InlineData(2.01f)] + public void TextToSpeechRejectsRatesOutsideMauiRange(float rate) => + Assert.Throws(() => + TizenTextToSpeech.ResolveRate(new(-10, 0, 20), rate)); + + [Fact] + public async Task TextToSpeechCancellationRetiresBeforeSettlingAndTeardownRunsOnDispatcher() + { + 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(); + + var exception = await Assert.ThrowsAnyAsync(() => speak); + await client.Disposed.Task; + Assert.Equal(cancellation.Token, exception.CancellationToken); + Assert.True(client.StoppedBeforeDisposed); + Assert.Empty(client.WrongThreadOperations); + + var freshClient = await factory.WaitForClientAsync(2); + Assert.NotSame(client, freshClient); + await freshClient.Played.Task; + await freshClient.CompleteAsync(freshClient.LastUtteranceId); + await queued; + } + + [Fact] + public async Task TextToSpeechNativeErrorDefersTeardownAndQueuedRequestUsesFreshClient() + { + 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 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() + { + 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 TextToSpeechIgnoresOldUtteranceCompletion() + { + 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 TextToSpeechVoiceQueryWaitsBehindActiveSpeech() + { + 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] + 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); + } + + [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. + // ------------------------------------------------------------------------------------------- + + [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)); + } + + [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 void ConnectivityRollsBackAPartialNativeSubscription() + { + var subscribed = false; + + Assert.Throws(() => + TizenConnectivity.StartTransactional( + () => + { + subscribed = true; + throw new InvalidOperationException("native add failed"); + }, + () => subscribed = false)); + + Assert.False(subscribed); + } + + [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")]); + 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] + public void ShareFilePayloadUsesMultiShareAndAllPathsOnce() + { + var payload = TizenShare.CreateFilePayload( + [ + 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] + 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 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() + { + 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 LauncherHandlerProbeTreatsNullAndExceptionsAsUnavailable() + { + Assert.False(TizenLauncher.HasHandler(static () => null)); + Assert.False(TizenLauncher.HasHandler( + static () => throw new InvalidOperationException("native lookup failed"))); + Assert.True(TizenLauncher.HasHandler(static () => ["org.example.handler"])); + } + + [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 = []; + readonly Thread _thread; + readonly ManualResetEventSlim _started = new(); + readonly object _blockLock = new(); + BlockedAction? _nextBlockedAction; + + 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 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() + { + _work.CompleteAdding(); + _thread.Join(); + _started.Dispose(); + _work.Dispose(); + } + + 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); + } + } + + sealed class FakeTextToSpeechClientFactory : ITizenTextToSpeechClientFactory + { + readonly FakeTextToSpeechDispatcher _dispatcher; + readonly List _clients = []; + readonly TaskCompletionSource _blockedAction = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public FakeTextToSpeechClientFactory(FakeTextToSpeechDispatcher dispatcher) + { + _dispatcher = 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, + throwOnDispose: ThrowOnDispose, + onAddText: BlockAfterAddText + ? () => _blockedAction.TrySetResult(_dispatcher.BlockNextAction()) + : null); + 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); + } + } + + 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; + bool _prepared; + int _nextUtteranceId; + + public FakeTextToSpeechClient( + FakeTextToSpeechDispatcher dispatcher, + bool throwOnPlay, + bool throwOnDispose, + Action? onAddText) + { + _dispatcher = dispatcher; + _throwOnPlay = throwOnPlay; + _throwOnDispose = throwOnDispose; + _onAddText = onAddText; + } + + 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 TaskCompletionSource DisposeAttempted { 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 int AddTextCalls { get; private set; } + + public int PlayCalls { get; private set; } + + public int LastSpeed { get; private set; } + + public List Operations { get; } = []; + + public void Prepare() + { + AssertThread(nameof(Prepare)); + Operations.Add(nameof(Prepare)); + _prepared = true; + StateChanged?.Invoke(TizenTextToSpeechState.Ready); + } + + public IReadOnlyList GetSupportedVoices() + { + AssertThread(nameof(GetSupportedVoices)); + GetSupportedVoicesCalls++; + return [new("en_US", 0)]; + } + + public TizenTextToSpeechSpeedRange GetSpeedRange() + { + AssertThread(nameof(GetSpeedRange)); + if (_prepared) + throw new InvalidOperationException("GetSpeedRange is only valid in Created."); + Operations.Add(nameof(GetSpeedRange)); + return new(-10, 0, 20); + } + + public int AddText(string text, string language, int voiceType, int speed) + { + AssertThread(nameof(AddText)); + if (!_prepared) + throw new InvalidOperationException("AddText requires Ready."); + Operations.Add(nameof(AddText)); + AddTextCalls++; + LastSpeed = speed; + LastUtteranceId = ++_nextUtteranceId; + _onAddText?.Invoke(); + return LastUtteranceId; + } + + public void Play() + { + AssertThread(nameof(Play)); + if (!_prepared) + throw new InvalidOperationException("Play requires Ready."); + Operations.Add(nameof(Play)); + PlayCalls++; + 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; + DisposeAttempted.TrySetResult(); + if (_throwOnDispose) + throw new InvalidOperationException("dispose failed"); + 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); + readonly object _locker = new(); + + public Exception? SaveException { get; init; } + public HashSet FailSaveCalls { get; } = []; + public HashSet FailRemoveAliases { get; } = new(StringComparer.Ordinal); + public Exception? GetAliasesException { get; init; } + public int? MaximumAliasLength { get; init; } + public bool RejectWhitespaceAliases { get; init; } + public int SuccessfulSaves { get; private set; } + public int SaveCalls { get; private set; } + + public string this[string alias] + { + 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) + { + lock (_locker) + return _values.ContainsKey(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); + SaveCalls++; + + if (FailSaveCalls.Contains(SaveCalls)) + throw new InvalidOperationException($"save failed at call {SaveCalls}"); + if (SaveException is not null) + throw SaveException; + + if (_values.ContainsKey(alias)) + throw new InvalidOperationException("alias already exists"); + + _values.Add(alias, value); + SuccessfulSaves++; + } + } + + public void RemoveAlias(string alias) + { + lock (_locker) + { + ValidateAlias(alias); + if (FailRemoveAliases.Contains(alias)) + throw new IOException($"remove failed for {alias}"); + + if (!_values.Remove(alias)) + throw new InvalidOperationException("alias not found"); + } + } + + public IEnumerable GetAliases() + { + lock (_locker) + { + if (GetAliasesException is not null) + throw GetAliasesException; + 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 + { + readonly HashSet _keys = new(StringComparer.Ordinal); + readonly HashSet _liveAfterAll = new(StringComparer.Ordinal); + + public bool ContainsAll { get; private set; } + + public bool Contains(string key) => + _keys.Contains(key) || (ContainsAll && !_liveAfterAll.Contains(key)); + + public void Add(string key) + { + _liveAfterAll.Remove(key); + _keys.Add(key); + } + + public void Remove(string key) + { + _keys.Remove(key); + if (ContainsAll) + _liveAfterAll.Add(key); + } + + public void AddAll() + { + ContainsAll = true; + _liveAfterAll.Clear(); + } + } + + 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 bool RejectUnsupportedNativeTypes { get; init; } + public int MaximumConcurrentOperations { get; private set; } + + public IEnumerable Keys => Access(() => _values.Keys.ToArray()); + + public object? this[string key] + { + get => _values[key]; + set => _values[key] = value; + } + + public bool Contains(string key) => + Access(() => _values.ContainsKey(key)); + + public void Remove(string key) => + Access(() => _values.Remove(key)); + + public void Set(string key, T value) + { + Access(() => + { + if (RejectUnsupportedNativeTypes && + value is not (bool or int or double or string)) + { + throw new ArgumentException( + $"Tizen preferences cannot store '{typeof(T).FullName}'."); + } + + _values[key] = value; + _setCounts[key] = GetSetCount(key) + 1; + }); + } + + public T Get(string 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; + }); + } + +} diff --git a/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs new file mode 100644 index 00000000..03ada23a --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenTranslationTests.cs @@ -0,0 +1,202 @@ +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 TizenAppControlOperations = Tizen.Applications.AppControlOperations; +using TizenConnectionType = Tizen.Network.Connection.ConnectionType; +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", "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)); + + [Theory] + [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)] + 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)] + [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..451b297d --- /dev/null +++ b/tests/Maui.Tizen.Essentials.Tests/TizenUnsupportedCapabilityTests.cs @@ -0,0 +1,216 @@ +using System; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Maui.ApplicationModel; +using Microsoft.Maui.Devices.Sensors; +using Microsoft.Maui.Media; +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 ClipboardReportsOnlyTheSynchronousHasTextGap() + { + Assert.Throws(() => _ = new TizenClipboard().HasText); + } + + [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); }); + } + + [Theory] + [InlineData(true, global::Tizen.Security.WebAuthn.AuthenticatorTransport.Internal, true)] + [InlineData(true, global::Tizen.Security.WebAuthn.AuthenticatorTransport.None, false)] + [InlineData(false, global::Tizen.Security.WebAuthn.AuthenticatorTransport.Internal, false)] + public void PasskeysDetectTheApi15NativeAuthenticator( + bool feature, + global::Tizen.Security.WebAuthn.AuthenticatorTransport authenticators, + bool expected) => + Assert.Equal( + expected, + TizenPasskeys.IsNativeAuthenticatorAvailable( + () => feature, + () => authenticators)); + + [Fact] + public void PasskeysTreatNativeProbeFailuresAsUnavailable() => + Assert.False( + TizenPasskeys.IsNativeAuthenticatorAvailable( + static () => true, + static () => throw new InvalidOperationException("native probe failed"))); + + [Fact] + public void WebAuthenticatorReportsUnsupported() + { + var authenticator = new TizenWebAuthenticator(); + + // The token-less overload is part of the contract under test, so it is called as declared. +#pragma warning disable xUnit1051 + Assert.Throws(() => { _ = authenticator.AuthenticateAsync(null!); }); +#pragma warning restore xUnit1051 + 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 GeocodingReportsUnsupportedBecauseTizenMapsWasRemoved() + { + var geocoding = new TizenGeocoding(); + + // Tizen.Maps was deprecated at API11 and removed by API15, so neither operation can be + // backed by anything. Returning an empty sequence would be indistinguishable from a + // genuine "no match". + var placemarks = Assert.Throws( + () => { _ = geocoding.GetPlacemarksAsync(0, 0); }); + Assert.Contains("Tizen.Maps", placemarks.Message, StringComparison.Ordinal); + + Assert.Throws(() => { _ = geocoding.GetLocationsAsync("nowhere"); }); + } + + [Fact] + public void GeocodingIsUnsupportedWithoutBeingHostileToTheHost() + { + // The contract is precise: the two operations Tizen cannot perform throw, and NOTHING else + // does. Construction, property access and disposal all happen during MauiApp startup and + // teardown, so a throw from any of them would turn an unsupported capability into an + // application that cannot start. + var geocoding = new TizenGeocoding(); + + var exception = Record.Exception(() => + { + geocoding.MapServiceToken = "token"; + _ = geocoding.MapServiceToken; + _ = ((IGeocoding)geocoding).GetType(); + }); + + Assert.Null(exception); + } + + [Fact] + public void GeocodingStillAcceptsAConfiguredMapServiceTokenWithoutThrowing() + { + // The .NET 11 Essentials DI bridge reads and writes IPlatformGeocoding.MapServiceToken + // during MauiApp initialization. Throwing here would turn a ConfigureEssentials line into + // a startup crash, so the token is accepted and simply never used. + var geocoding = new TizenGeocoding { MapServiceToken = "token" }; + + Assert.Equal("token", geocoding.MapServiceToken); + } + + [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); + } + + /// + /// 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() + { + 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); + } +} diff --git a/tests/Maui.Tizen.Sample.RefPackCompile/Maui.Tizen.Sample.RefPackCompile.csproj b/tests/Maui.Tizen.Sample.RefPackCompile/Maui.Tizen.Sample.RefPackCompile.csproj index 8738598d..66961ce8 100644 --- a/tests/Maui.Tizen.Sample.RefPackCompile/Maui.Tizen.Sample.RefPackCompile.csproj +++ b/tests/Maui.Tizen.Sample.RefPackCompile/Maui.Tizen.Sample.RefPackCompile.csproj @@ -25,6 +25,7 @@ + $(MSBuildAllProjects);$(RepositoryRoot)eng/targets/TizenPackage.props $(DotNetTfm) false Library diff --git a/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs b/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs new file mode 100644 index 00000000..07fed4c9 --- /dev/null +++ b/tests/Maui.Tizen.SourceTests/EssentialsSourceClosureTests.cs @@ -0,0 +1,214 @@ +using System.Text.Json; +using System.Xml.Linq; + +namespace Maui.Tizen.SourceTests; + +public class EssentialsSourceClosureTests +{ + [Fact] + public void SharedSourceClosureMatchesEveryShippingEssentialsSource() + { + var manifest = XDocument.Load(RepoPaths.Combine("eng", "Maui.Tizen.Essentials.Sources.props")); + + var declared = manifest + .Descendants("MauiTizenEssentialsCompile") + .Select(element => element.Attribute("Include")?.Value) + .Where(path => path is not null) + .Select(path => path!.Replace("$(MauiTizenEssentialsDir)", string.Empty, StringComparison.Ordinal)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + + var sourceRoot = RepoPaths.Combine("src", "Maui.Tizen.Essentials"); + var actual = Directory + .EnumerateFiles(sourceRoot, "*.cs", SearchOption.AllDirectories) + .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .Select(path => Path.GetRelativePath(sourceRoot, path).Replace(Path.DirectorySeparatorChar, '/')) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + + Assert.Equal(actual, declared); + Assert.Equal(declared.Length, declared.Distinct(StringComparer.Ordinal).Count()); + } + + [Theory] + [InlineData("src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj")] + [InlineData("src/Maui.Tizen.Essentials.HostVerification/Maui.Tizen.Essentials.HostVerification.csproj")] + [InlineData("tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj")] + public void EveryEssentialsLaneConsumesTheSharedSourceClosure(string projectPath) + { + var project = File.ReadAllText(RepoPaths.Combine(projectPath.Split('/'))); + + Assert.Contains("Maui.Tizen.Essentials.Sources.props", project, StringComparison.Ordinal); + Assert.Contains("@(MauiTizenEssentialsCompile)", project, StringComparison.Ordinal); + Assert.DoesNotContain("Maui.Tizen.Essentials/**/*.cs", project, StringComparison.Ordinal); + } + + [Theory] + [InlineData("src/Maui.Tizen.Essentials/Maui.Tizen.Essentials.csproj")] + [InlineData("tests/Maui.Tizen.Essentials.RefPackCompile/Maui.Tizen.Essentials.RefPackCompile.csproj")] + public void ProductAndApi15LaneUseThePackageSpecificPublicApiBaseline(string projectPath) + { + var project = File.ReadAllText(RepoPaths.Combine(projectPath.Split('/'))); + + Assert.Contains( + "src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Shipped.txt".Replace( + "src/Maui.Tizen.Essentials/", + projectPath.StartsWith("src/", StringComparison.Ordinal) + ? string.Empty + : "$(RepositoryRoot)src/Maui.Tizen.Essentials/", + StringComparison.Ordinal), + project, + StringComparison.Ordinal); + Assert.Contains( + "src/Maui.Tizen.Essentials/PublicAPI/slice/PublicAPI.Unshipped.txt".Replace( + "src/Maui.Tizen.Essentials/", + projectPath.StartsWith("src/", StringComparison.Ordinal) + ? string.Empty + : "$(RepositoryRoot)src/Maui.Tizen.Essentials/", + StringComparison.Ordinal), + project, + StringComparison.Ordinal); + Assert.DoesNotContain( + "AdditionalFiles Include=\"PublicAPI/net-tizen/PublicAPI.Shipped.txt", + project, + StringComparison.Ordinal); + } + + [Fact] + public void ControlsProductionCompositionIncludesEssentialsExactlyOnce() + { + var startup = File.ReadAllText(RepoPaths.Combine( + "src", + "Maui.Tizen.Controls", + "Hosting", + "TizenControlsMauiAppBuilderExtensions.cs")); + var project = File.ReadAllText(RepoPaths.Combine( + "src", + "Maui.Tizen.Controls", + "Maui.Tizen.Controls.csproj")); + + Assert.Equal(1, CountOccurrences(startup, "builder.AddTizenEssentials();")); + Assert.Equal(1, CountOccurrences( + project, + "")); + } + + [Fact] + public void EssentialsRegistrationReplacesRatherThanShadowsPlatformServices() + { + var registration = File.ReadAllText(RepoPaths.Combine( + "src", + "Maui.Tizen.Essentials", + "Hosting", + "TizenEssentialsMauiAppBuilderExtensions.cs")); + + Assert.DoesNotContain("services.TryAddSingleton(services);", + registration, + 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() + { + var migration = File.ReadAllText(RepoPaths.Combine("docs", "migration.md")); + + Assert.Contains("Core and Waves A/B/C merged", migration, StringComparison.Ordinal); + Assert.Contains("Implemented and host/API15 tested", migration, StringComparison.Ordinal); + Assert.DoesNotContain("| 2 | Handler implementation (`Maui.Tizen.Core`, `Maui.Tizen.Controls`) | Not started |", migration, StringComparison.Ordinal); + Assert.DoesNotContain("| 3 | Essentials implementation | Not started |", migration, StringComparison.Ordinal); + } + + [Fact] + public void ExactExternalMauiApiBlockersRemainMachineReadable() + { + using var document = JsonDocument.Parse(File.ReadAllText(RepoPaths.Combine( + "eng", + "validation", + "essentials-external-blockers.json"))); + var blockers = document.RootElement + .GetProperty("blockers") + .EnumerateArray() + .ToDictionary( + blocker => blocker.GetProperty("id").GetString()!, + blocker => blocker); + + Assert.Equal("active", blockers["maui-file-result-path-open"].GetProperty("status").GetString()); + Assert.Equal("active", blockers["maui-passkey-response-factory"].GetProperty("status").GetString()); + Assert.Contains( + "FileResult", + blockers["maui-file-result-path-open"].GetProperty("reason").GetString(), + StringComparison.Ordinal); + Assert.Contains( + "response", + blockers["maui-passkey-response-factory"].GetProperty("reason").GetString(), + StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Api15GeocodingContractMatchesTheRegisteredUnsupportedService() + { + using var document = JsonDocument.Parse(File.ReadAllText(RepoPaths.Combine( + "eng", + "validation", + "api15-contract.json"))); + var geocoding = document.RootElement + .GetProperty("unsupportedServices") + .EnumerateArray() + .Single(service => service.GetProperty("contract").GetString() == "IGeocoding"); + + Assert.False(geocoding.GetProperty("doNotRegisterInDi").GetBoolean()); + Assert.Contains( + "IPlatformGeocoding", + geocoding.GetProperty("behaviour").GetString(), + StringComparison.Ordinal); + Assert.Contains( + "FeatureNotSupportedException", + geocoding.GetProperty("behaviour").GetString(), + StringComparison.Ordinal); + Assert.Contains( + "MapServiceToken", + geocoding.GetProperty("behaviour").GetString(), + StringComparison.Ordinal); + } + + static int CountOccurrences(string text, string value) + { + var count = 0; + var index = 0; + + while ((index = text.IndexOf(value, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += value.Length; + } + + return count; + } +} diff --git a/tests/Maui.Tizen.SourceTests/MauiPublicApiBlockerTests.cs b/tests/Maui.Tizen.SourceTests/MauiPublicApiBlockerTests.cs new file mode 100644 index 00000000..0f58fdfd --- /dev/null +++ b/tests/Maui.Tizen.SourceTests/MauiPublicApiBlockerTests.cs @@ -0,0 +1,76 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.Maui.Authentication; +using Microsoft.Maui.Storage; + +namespace Maui.Tizen.SourceTests; + +public class MauiPublicApiBlockerTests +{ + [Fact] + public void PasskeyResponsesHaveNoPublicConstructionOrFactorySurface() + { + Assert.Empty(typeof(PasskeyCreationResponse).GetConstructors()); + Assert.Empty(typeof(PasskeyAssertionResponse).GetConstructors()); + Assert.True(typeof(PasskeyCreationResponse).IsSealed); + Assert.True(typeof(PasskeyAssertionResponse).IsSealed); + + var diagnostics = Compile( + """ + using Microsoft.Maui.Authentication; + class Probe + { + PasskeyCreationResponse Create(string json) => new(json); + PasskeyAssertionResponse Assert(string json) => new(json); + } + """); + + Assert.Contains(diagnostics, diagnostic => + diagnostic.Severity == DiagnosticSeverity.Error && + diagnostic.Id is "CS1729" or "CS0122"); + } + + [Fact] + public void FileResultHasNoPublicPathOpenOverrideSeam() + { + var platformOpen = typeof(FileBase).GetMethod( + "PlatformOpenReadAsync", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + + Assert.NotNull(platformOpen); + Assert.True(platformOpen!.IsAssembly); + + var diagnostics = Compile( + """ + using System.IO; + using System.Threading.Tasks; + using Microsoft.Maui.Storage; + class TizenFileResult : FileResult + { + public TizenFileResult(string path) : base(path) { } + internal override Task PlatformOpenReadAsync() => Task.FromResult(File.OpenRead(FullPath)); + } + """); + + Assert.Contains(diagnostics, diagnostic => + diagnostic.Severity == DiagnosticSeverity.Error && + diagnostic.Id == "CS0115"); + } + + static IReadOnlyList Compile(string source) + { + var trustedPlatformAssemblies = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")) + ?.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToList() ?? []; + trustedPlatformAssemblies.Add(MetadataReference.CreateFromFile(typeof(FileBase).Assembly.Location)); + + return CSharpCompilation + .Create( + "PublicApiProbe", + [CSharpSyntaxTree.ParseText(source)], + trustedPlatformAssemblies, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) + .GetDiagnostics(); + } +} diff --git a/tests/Maui.Tizen.Validation.Tests/ReleaseReadinessTests.cs b/tests/Maui.Tizen.Validation.Tests/ReleaseReadinessTests.cs index 66f09e42..ae7bc7c8 100644 --- a/tests/Maui.Tizen.Validation.Tests/ReleaseReadinessTests.cs +++ b/tests/Maui.Tizen.Validation.Tests/ReleaseReadinessTests.cs @@ -1,4 +1,5 @@ using System.Text.RegularExpressions; +using System.Text.Json; namespace Maui.Tizen.Validation.Tests; @@ -151,6 +152,36 @@ public void EveryRequiredProfileReportedADeviceResult() } } + [Fact] + public void NoActiveEssentialsExternalApiBlockers() + { + SkipUnlessRelease(); + + var path = Path.Combine( + RepoLayout.Root, + "eng", + "validation", + "essentials-external-blockers.json"); + Assert.True(File.Exists(path), $"Missing {RepoLayout.Relative(path)}."); + + using var document = JsonDocument.Parse(File.ReadAllText(path)); + var active = document.RootElement + .GetProperty("blockers") + .EnumerateArray() + .Where(blocker => + string.Equals( + blocker.GetProperty("status").GetString(), + "active", + StringComparison.OrdinalIgnoreCase)) + .Select(blocker => blocker.GetProperty("id").GetString()) + .ToList(); + + Assert.True( + active.Count == 0, + $"Essentials still has active public-API blockers: {string.Join(", ", active)}. " + + "See docs/validation/blockers.md."); + } + [Fact] public void ReleaseValidationFlagIsWiredIntoTheReleaseWorkflow() { diff --git a/tests/TestUtils/Maui.Tizen.TestUtils/CompiledSourceInventory.cs b/tests/TestUtils/Maui.Tizen.TestUtils/CompiledSourceInventory.cs index a6f33f5b..5a4c19b9 100644 --- a/tests/TestUtils/Maui.Tizen.TestUtils/CompiledSourceInventory.cs +++ b/tests/TestUtils/Maui.Tizen.TestUtils/CompiledSourceInventory.cs @@ -7,11 +7,10 @@ namespace Maui.Tizen.TestUtils; /// /// /// -/// This distinction is the whole point of the API15 source guards. The src/Maui.Tizen.* -/// sources were imported verbatim from dotnet/maui and are currently listed as <None> -/// with EnableDefaultCompileItems=false, so nothing compiles them. Scanning those files for -/// banned APIs 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 disable the guard. +/// This distinction is the whole point of the API15 source guards. The raw imports share +/// directories with adopted code. Core, Controls and Essentials keep default globbing disabled and +/// include explicit shared source manifests, while unported projects still compile nothing. +/// Scanning every file would report upstream history rather than the shipping closure. /// /// /// So the guard follows compilation: a file is in scope exactly when a project compiles it, and a @@ -45,24 +44,13 @@ public static CompiledSourceSet ForProject(string projectPath) ArgumentException.ThrowIfNullOrEmpty(projectPath); var projectDirectory = Path.GetDirectoryName(Path.GetFullPath(projectPath))!; - var document = XDocument.Load(projectPath); + var model = ProjectModel.Load(projectPath); + var defaultItemsEnabled = model.GetBooleanProperty("EnableDefaultCompileItems", defaultValue: true); - var defaultItemsEnabled = ResolveDefaultCompileItems(projectPath, document); - - var includes = new List(); - var removes = new List(); - - foreach (var item in document.Descendants().Where(e => e.Name.LocalName == "Compile")) - { - if (item.Attribute("Include")?.Value is { Length: > 0 } include) - includes.AddRange(SplitItemList(include)); - - if (item.Attribute("Update")?.Value is { Length: > 0 } update) - includes.AddRange(SplitItemList(update)); - - if (item.Attribute("Remove")?.Value is { Length: > 0 } remove) - removes.AddRange(SplitItemList(remove)); - } + var includes = model.GetItems("Compile", "Include") + .Concat(model.GetItems("Compile", "Update")) + .ToList(); + var removes = model.GetItems("Compile", "Remove").ToList(); var files = new SortedSet(StringComparer.Ordinal); @@ -91,54 +79,6 @@ public static CompiledSourceSet ForProject(string projectPath) public static IReadOnlyList ForAllProductProjects() => [.. EnumerateProductProjects().Select(ForProject)]; - /// - /// Resolves the effective EnableDefaultCompileItems. - /// - /// - /// The project's own value wins. Otherwise any props file it imports is consulted, which is how - /// eng/targets/TizenPackage.props turns default items off for the imported packages. - /// Absent both, the SDK default of applies. - /// - static bool ResolveDefaultCompileItems(string projectPath, XDocument document) - { - var own = ReadProperty(document, "EnableDefaultCompileItems"); - if (own is not null) - return IsTrue(own); - - var projectDirectory = Path.GetDirectoryName(Path.GetFullPath(projectPath))!; - - foreach (var import in document.Descendants().Where(e => e.Name.LocalName == "Import")) - { - var raw = import.Attribute("Project")?.Value; - if (string.IsNullOrEmpty(raw)) - continue; - - // Only $(MSBuildThisFileDirectory)-relative imports are resolvable without evaluation. - var relative = raw.Replace("$(MSBuildThisFileDirectory)", string.Empty, StringComparison.Ordinal); - var importPath = Path.GetFullPath(Path.Combine(projectDirectory, relative)); - - if (!File.Exists(importPath)) - continue; - - var imported = ReadProperty(XDocument.Load(importPath), "EnableDefaultCompileItems"); - if (imported is not null) - return IsTrue(imported); - } - - return true; - } - - static string? ReadProperty(XDocument document, string name) => - document.Descendants() - .Where(e => e.Name.LocalName == name && e.Parent?.Name.LocalName == "PropertyGroup") - .Select(e => e.Value.Trim()) - .LastOrDefault(); - - static bool IsTrue(string value) => string.Equals(value, "true", StringComparison.OrdinalIgnoreCase); - - static IEnumerable SplitItemList(string value) => - value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - static IEnumerable EnumerateSourceFiles(string directory) => Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories) .Where(p => !IsExcluded(p)); @@ -173,6 +113,141 @@ static bool IsExcluded(string path) var normalized = "/" + path.Replace('\\', '/').Trim('/') + "/"; return ExcludedDirectorySegments.Any(s => normalized.Contains(s, StringComparison.OrdinalIgnoreCase)); } + + sealed class ProjectModel + { + readonly Dictionary _properties = new(StringComparer.OrdinalIgnoreCase); + readonly Dictionary> _items = new(StringComparer.OrdinalIgnoreCase); + readonly HashSet _visited = new(StringComparer.OrdinalIgnoreCase); + + ProjectModel(string projectPath) + { + _properties["RepositoryRoot"] = RepoLayout.Root + Path.DirectorySeparatorChar; + Visit(Path.GetFullPath(projectPath)); + } + + public static ProjectModel Load(string projectPath) => new(projectPath); + + public bool GetBooleanProperty(string name, bool defaultValue) => + _properties.TryGetValue(name, out var value) + ? string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) + : defaultValue; + + public IEnumerable GetItems(string itemName, string attributeName) + { + if (!_items.TryGetValue(itemName, out var items)) + yield break; + + foreach (var item in items) + { + if (item.Attribute(attributeName)?.Value is not { Length: > 0 } value) + continue; + + foreach (var expanded in ExpandItemExpression(value)) + yield return expanded; + } + } + + void Visit(string path) + { + if (!File.Exists(path) || !_visited.Add(path)) + return; + + var directory = Path.GetDirectoryName(path)! + Path.DirectorySeparatorChar; + var document = XDocument.Load(path); + + foreach (var element in document.Root?.Elements() ?? []) + { + switch (element.Name.LocalName) + { + case "PropertyGroup": + foreach (var property in element.Elements()) + { + // The inventory cannot evaluate arbitrary MSBuild conditions. These + // source manifests only use "set when empty", for which retaining the + // first value is the faithful result. + if (property.Attribute("Condition") is not null && + _properties.ContainsKey(property.Name.LocalName)) + { + continue; + } + + _properties[property.Name.LocalName] = + ExpandProperties(property.Value.Trim(), directory); + } + break; + + case "Import": + if (element.Attribute("Project")?.Value is { Length: > 0 } import) + { + var importPath = ExpandProperties(import, directory); + if (!Path.IsPathRooted(importPath)) + importPath = Path.Combine(directory, importPath); + Visit(Path.GetFullPath(importPath)); + } + break; + + case "ItemGroup": + foreach (var item in element.Elements()) + { + var clone = new XElement(item); + foreach (var attribute in clone.Attributes().ToList()) + attribute.Value = ExpandProperties(attribute.Value, directory); + + if (!_items.TryGetValue(item.Name.LocalName, out var values)) + _items[item.Name.LocalName] = values = []; + values.Add(clone); + } + break; + } + } + } + + IEnumerable ExpandItemExpression(string value) + { + foreach (var component in value.Split( + ';', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (component.StartsWith("@(", StringComparison.Ordinal) && + component.EndsWith(')')) + { + var itemName = component[2..^1]; + foreach (var item in GetItems(itemName, "Include")) + yield return item; + } + else + { + yield return component; + } + } + } + + string ExpandProperties(string value, string currentDirectory) + { + var expanded = value.Replace( + "$(MSBuildThisFileDirectory)", + currentDirectory, + StringComparison.OrdinalIgnoreCase); + + for (var pass = 0; pass < 8; pass++) + { + var before = expanded; + foreach (var (name, propertyValue) in _properties) + { + expanded = expanded.Replace( + $"$({name})", + propertyValue, + StringComparison.OrdinalIgnoreCase); + } + + if (expanded == before) + break; + } + + return expanded; + } + } } /// diff --git a/tests/TestUtils/Maui.Tizen.TestUtils/ReferencePackProbe.cs b/tests/TestUtils/Maui.Tizen.TestUtils/ReferencePackProbe.cs index 3c4e63d9..a1efee50 100644 --- a/tests/TestUtils/Maui.Tizen.TestUtils/ReferencePackProbe.cs +++ b/tests/TestUtils/Maui.Tizen.TestUtils/ReferencePackProbe.cs @@ -142,6 +142,9 @@ [.. Directory continue; var properties = new List(); + var methods = type.GetMethods() + .Select(handle => reader.GetString(reader.GetMethodDefinition(handle).Name)) + .ToList(); var obsolete = new Dictionary(StringComparer.Ordinal); foreach (var propertyHandle in type.GetProperties()) @@ -154,7 +157,7 @@ [.. Directory obsolete[propertyName] = message; } - return new TypeMembers(fullName, properties, obsolete); + return new TypeMembers(fullName, properties, methods, obsolete); } return null; @@ -231,9 +234,12 @@ sealed class StringOnlyAttributeTypeProvider : ICustomAttributeTypeProvider Properties, + IReadOnlyList Methods, IReadOnlyDictionary ObsoleteMembers) { public bool HasProperty(string name) => Properties.Contains(name, StringComparer.Ordinal); + public bool HasMethod(string name) => Methods.Contains(name, StringComparer.Ordinal); + public bool IsObsolete(string name) => ObsoleteMembers.ContainsKey(name); }