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