Skip to main content

g3_native_plugins/
lib.rs

1//! Dioxus wrappers around native platform capabilities: clipboard and share
2//! sheets, Apple and Google sign-in, opening external URLs, system back
3//! handling, background media playback, local and push notifications,
4//! over-the-air bundle updates, and receiving the URL a deep link opened the
5//! app with - plus helpers for the deep-link metadata files iOS and Android
6//! expect a server to host.
7//!
8//! Every plugin sits behind a feature flag, so an app compiles in only what
9//! it uses. Platform coverage is not uniform; see the support matrix in the
10//! README. Where a plugin has no implementation for the current target it
11//! compiles to an inert no-op rather than failing to build, which keeps the
12//! same call sites working on web, desktop, and mobile.
13#![allow(non_snake_case)]
14#![warn(missing_docs)]
15#[cfg(all(
16    target_os = "android",
17    any(
18        feature = "appearance",
19        feature = "auth",
20        feature = "camera-microphone",
21        feature = "clipboard",
22        feature = "deep-links",
23        feature = "external-url",
24        feature = "geolocation",
25        feature = "in-app-purchases",
26        feature = "notifications",
27        feature = "storage",
28        feature = "updater"
29    )
30))]
31mod android_bridge;
32/// Both halves of deep linking: builders for the `apple-app-site-association`
33/// and `assetlinks.json` files that make universal links and App Links resolve
34/// to the app, and — behind the `deep-links` feature — the plugin that receives
35/// the URL once one does.
36#[cfg_attr(all(feature = "deep-links", target_os = "ios"), allow(missing_docs))]
37pub mod deep_links;
38/// The permission states plugins here report, in one place so an app can treat
39/// a refusal the same way whatever was refused.
40pub mod permissions;
41#[cfg(all(
42    feature = "deep-links",
43    any(
44        target_arch = "wasm32",
45        target_os = "android",
46        target_os = "ios",
47        target_os = "macos"
48    )
49))]
50#[allow(unused_imports)]
51pub use deep_links::DeepLinks;
52#[allow(unused_imports)]
53pub use permissions::PermissionState;
54cfg_if::cfg_if! {
55    if #[cfg(feature = "clipboard")] { mod clipboard;
56    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
57    #[allow(unused_imports)] pub use clipboard::Clipboard; }
58}
59cfg_if::cfg_if! {
60    if #[cfg(feature = "appearance")] { mod appearance;
61    #[allow(unused_imports)] pub use appearance::SystemAppearance; }
62}
63cfg_if::cfg_if! {
64    if #[cfg(feature = "auth")] { mod auth;
65    #[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
66    #[allow(unused_imports)] pub use auth::Auth; }
67}
68cfg_if::cfg_if! {
69    if #[cfg(feature = "back-button")] { mod back_button;
70    #[allow(unused_imports)] pub use back_button::NATIVE_BACK_EVENT;
71    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
72    #[allow(unused_imports)] pub use back_button::BackButton; }
73}
74cfg_if::cfg_if! {
75    if #[cfg(feature = "camera-microphone")] { mod camera_microphone;
76    #[allow(unused_imports)] pub use camera_microphone::CapturePermissions;
77    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
78    #[allow(unused_imports)] pub use camera_microphone::CameraMicrophone; }
79}
80cfg_if::cfg_if! {
81    if #[cfg(feature = "external-url")] { mod external_url;
82    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
83    #[allow(unused_imports)] pub use external_url::ExternalUrl; }
84}
85cfg_if::cfg_if! {
86    if #[cfg(feature = "geolocation")] { mod geolocation;
87    #[allow(unused_imports)] pub use geolocation::{Coordinates, LocationState, PermissionStatus, Position, PositionOptions};
88    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
89    #[allow(unused_imports)] pub use geolocation::Geolocation; }
90}
91cfg_if::cfg_if! {
92    if #[cfg(feature = "in-app-purchases")] { mod in_app_purchases;
93    #[allow(unused_imports)] pub use in_app_purchases::{Entitlement, ExternalContentLinkToken, Product, ProductKind, PurchaseState, SubscriptionOffer, SubscriptionPeriod};
94    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
95    #[allow(unused_imports)] pub use in_app_purchases::InAppPurchases; }
96}
97cfg_if::cfg_if! {
98    if #[cfg(feature = "media")] { mod media;
99    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
100    #[allow(unused_imports)] pub use media::Media;
101    }
102}
103cfg_if::cfg_if! {
104    if #[cfg(feature = "notifications")] { mod notifications;
105    #[allow(unused_imports)] pub use notifications::{Action, ActionType, Channel, DeliveredNotification, Importance, Notification, NotificationEvent, PendingNotification, Schedule, ScheduleInterval, Visibility, TAP_ACTION};
106    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
107    #[allow(unused_imports)] pub use notifications::Notifications; }
108}
109cfg_if::cfg_if! {
110    if #[cfg(feature = "push-notifications")] { mod push_notifications;
111    #[allow(unused_imports)] pub use push_notifications::{FirebaseOptions, PushEvent, PushService, PushToken};
112    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
113    #[allow(unused_imports)] pub use push_notifications::PushNotifications; }
114}
115cfg_if::cfg_if! {
116    if #[cfg(feature = "storage")] { mod storage;
117    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
118    #[allow(unused_imports)] pub use storage::KeyValueStore; }
119}
120cfg_if::cfg_if! {
121    if #[cfg(feature = "updater")] { mod updater;
122    #[allow(unused_imports)] pub use updater::{bundle_content_type, DownloadProgress, Update, UpdaterConfig, UpdaterState};
123    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
124    #[allow(unused_imports)] pub use updater::Updater; }
125}
126use dioxus::prelude::*;
127#[cfg(all(
128    any(
129        feature = "appearance",
130        feature = "auth",
131        feature = "back-button",
132        feature = "camera-microphone",
133        feature = "clipboard",
134        feature = "deep-links",
135        feature = "external-url",
136        feature = "geolocation",
137        feature = "in-app-purchases",
138        feature = "media",
139        feature = "notifications",
140        feature = "storage",
141        feature = "updater"
142    ),
143    any(
144        target_arch = "wasm32",
145        target_os = "android",
146        target_os = "ios",
147        target_os = "macos"
148    )
149))]
150#[allow(unused_imports)]
151use dioxus_signals::Signal;
152#[cfg(any(
153    target_arch = "wasm32",
154    target_os = "android",
155    target_os = "ios",
156    target_os = "macos"
157))]
158#[derive(Clone, Copy)]
159/// Reactive handles for every enabled native plugin.
160///
161/// Construct this directly with [`NativePlugins::new`] or install it in the
162/// Dioxus context with [`NativePluginsProvider`].
163pub struct NativePlugins {
164    /// The system's dark-mode setting where the web view misreports it. On
165    /// every target: it answers `None` wherever the page can tell already.
166    #[cfg(feature = "appearance")]
167    pub appearance: Signal<SystemAppearance>,
168    #[cfg(all(
169        feature = "auth",
170        any(target_os = "android", target_os = "ios", target_os = "macos")
171    ))]
172    /// Native Apple or Google authentication, depending on the target.
173    pub auth: Signal<Auth>,
174    /// Available on every target: the non-Android builds are inert, so callers
175    /// need no cfg of their own.
176    #[cfg(feature = "back-button")]
177    pub back_button: Signal<BackButton>,
178    /// Available on every target: the web and macOS builds are inert, so
179    /// callers need no cfg of their own.
180    #[cfg(feature = "camera-microphone")]
181    pub camera_microphone: Signal<CameraMicrophone>,
182    #[cfg(feature = "clipboard")]
183    /// Clipboard copying and the platform share sheet.
184    pub clipboard: Signal<Clipboard>,
185    /// Available on every target: the web and macOS builds are inert, so
186    /// callers need no cfg of their own.
187    #[cfg(feature = "deep-links")]
188    pub deep_links: Signal<DeepLinks>,
189    #[cfg(all(
190        feature = "external-url",
191        any(
192            target_arch = "wasm32",
193            target_os = "android",
194            target_os = "ios",
195            target_os = "macos"
196        )
197    ))]
198    /// Opens a URL outside the app on supported targets.
199    pub external_url: Signal<ExternalUrl>,
200    /// Available on every target: the web and macOS builds are inert, so
201    /// callers need no cfg of their own.
202    #[cfg(feature = "geolocation")]
203    pub geolocation: Signal<Geolocation>,
204    /// Available on every target: the web and macOS builds are inert, so
205    /// callers need no cfg of their own.
206    #[cfg(feature = "in-app-purchases")]
207    pub in_app_purchases: Signal<InAppPurchases>,
208    #[cfg(feature = "media")]
209    /// Background media playback, orientation, and picture-in-picture support.
210    pub media: Signal<Media>,
211    /// Local notifications. Available on every target: the web and macOS
212    /// builds are inert, so callers need no cfg of their own.
213    #[cfg(feature = "notifications")]
214    pub notifications: Signal<Notifications>,
215    /// Remote push through APNs and FCM. Available on every target: the web
216    /// and macOS builds are inert, so callers need no cfg of their own.
217    #[cfg(feature = "push-notifications")]
218    pub push_notifications: Signal<PushNotifications>,
219    /// Available on every target, but unlike the others the macOS build reports
220    /// an error rather than doing nothing: a store that silently discards is
221    /// worse than one that says it cannot help.
222    #[cfg(feature = "storage")]
223    pub storage: Signal<KeyValueStore>,
224    /// Over-the-air bundle updates. Available on every target: the web and
225    /// macOS builds are inert, so callers need no cfg of their own.
226    #[cfg(feature = "updater")]
227    pub updater: Signal<Updater>,
228}
229#[cfg(any(
230    target_arch = "wasm32",
231    target_os = "android",
232    target_os = "ios",
233    target_os = "macos"
234))]
235impl NativePlugins {
236    /// Creates reactive handles for every plugin enabled for this target.
237    pub fn new() -> Self {
238        Self {
239            #[cfg(feature = "appearance")]
240            appearance: Signal::new(SystemAppearance::new()),
241            #[cfg(all(
242                feature = "auth",
243                any(target_os = "android", target_os = "ios", target_os = "macos")
244            ))]
245            auth: Signal::new(Auth::new()),
246            #[cfg(feature = "back-button")]
247            back_button: Signal::new(BackButton::new()),
248            #[cfg(feature = "camera-microphone")]
249            camera_microphone: Signal::new(CameraMicrophone::new()),
250            #[cfg(feature = "clipboard")]
251            clipboard: Signal::new(Clipboard::new()),
252            #[cfg(feature = "deep-links")]
253            deep_links: Signal::new(DeepLinks::new()),
254            #[cfg(all(
255                feature = "external-url",
256                any(
257                    target_arch = "wasm32",
258                    target_os = "android",
259                    target_os = "ios",
260                    target_os = "macos"
261                )
262            ))]
263            external_url: Signal::new(ExternalUrl::new()),
264            #[cfg(feature = "geolocation")]
265            geolocation: Signal::new(Geolocation::new()),
266            #[cfg(feature = "in-app-purchases")]
267            in_app_purchases: Signal::new(InAppPurchases::new()),
268            #[cfg(feature = "media")]
269            media: Signal::new(Media::new()),
270            #[cfg(feature = "notifications")]
271            notifications: Signal::new(Notifications::new()),
272            #[cfg(feature = "push-notifications")]
273            push_notifications: Signal::new(PushNotifications::new()),
274            #[cfg(feature = "storage")]
275            storage: Signal::new(KeyValueStore::new()),
276            #[cfg(feature = "updater")]
277            updater: Signal::new(Updater::new()),
278        }
279    }
280}
281#[cfg(any(
282    target_arch = "wasm32",
283    target_os = "android",
284    target_os = "ios",
285    target_os = "macos"
286))]
287impl Default for NativePlugins {
288    fn default() -> Self {
289        Self::new()
290    }
291}
292#[component]
293pub fn NativePluginsProvider(children: Element) -> Element {
294    #[cfg(any(
295        target_arch = "wasm32",
296        target_os = "android",
297        target_os = "ios",
298        target_os = "macos"
299    ))]
300    use_context_provider(NativePlugins::default);
301    rsx! {
302        {children}
303    }
304}
305#[cfg(test)]
306mod tests {
307    fn production_source(source: &str) -> &str {
308        source
309            .split("#[cfg(test)]")
310            .next()
311            .expect("source should split before tests")
312    }
313    #[test]
314    fn appearance_asks_the_system_not_the_activity_theme() {
315        let source = production_source(include_str!("appearance.rs"));
316        let kotlin = include_str!(
317            "android/appearance/src/main/kotlin/dev/dioxus/g3_native_plugins/appearance/AppearancePlugin.kt",
318        );
319        let gradle = include_str!("android/appearance/build.gradle.kts");
320        assert!(source.contains("#[manganis::ffi(\"src/android/appearance\")]"));
321        assert!(source.contains("call_string(\"isDarkFromRust\")"));
322        // The Activity's own configuration follows its (light) theme.
323        assert!(kotlin.contains("Resources.getSystem().configuration.uiMode"));
324        assert!(kotlin.contains("fun isDarkFromRust(): String"));
325        assert!(gradle.contains("namespace = \"dev.dioxus.g3_native_plugins.appearance\""));
326    }
327
328    #[test]
329    fn back_button_interception_is_opt_in() {
330        let source = production_source(include_str!("back_button.rs"));
331        assert!(source.contains("intercepting: false"));
332        assert!(source.contains("pub fn set_intercepting"));
333        let kotlin = include_str!(
334            "android/back_button/src/main/kotlin/dev/dioxus/g3_native_plugins/back_button/BackButtonPlugin.kt",
335        );
336        assert!(kotlin.contains("g3nativeback"));
337        assert!(kotlin.contains("cancelable: true"));
338        assert!(kotlin.contains("evaluateJavascript(BACK_EVENT_SCRIPT"));
339        assert!(kotlin.contains("OnBackPressedCallback(false)"));
340        assert!(kotlin.contains("fun fallThroughFromRust()"));
341        assert!(kotlin.contains("current?.isEnabled = false"));
342        assert!(source.contains("pub fn fall_through"));
343        assert!(source.contains("pub const NATIVE_BACK_EVENT"));
344    }
345    #[test]
346    fn ios_back_button_raises_the_same_event_from_an_edge_swipe() {
347        let source = production_source(include_str!("back_button.rs"));
348        let swift = include_str!("ios/Sources/BackButtonPlugin.swift");
349        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
350        assert!(source.contains(
351            "pub fn setInterceptingFromRust(this: &BackButtonPlugin, intercepting: bool);",
352        ),);
353        assert!(source.contains("pub fn fallThroughFromRust(this: &BackButtonPlugin);"));
354        assert!(swift.contains("UIScreenEdgePanGestureRecognizer"));
355        assert!(swift.contains("created.edges = .left"));
356        // The same event contract as Android, so one web listener serves both.
357        assert!(swift.contains("g3nativeback"));
358        assert!(swift.contains("cancelable: true"));
359        assert!(swift.contains("webView.allowsBackForwardNavigationGestures = false"));
360        assert!(swift.contains("panGestureRecognizer.require(toFail: created)"));
361        assert!(swift.contains("created.isEnabled = false"));
362    }
363    #[test]
364    fn deep_links_are_collected_from_both_launch_paths() {
365        let source = production_source(include_str!("deep_links.rs"));
366        let kotlin = include_str!(
367            "android/deep_links/src/main/kotlin/dev/dioxus/g3_native_plugins/deep_links/DeepLinksPlugin.kt",
368        );
369        let swift = include_str!("ios/Sources/DeepLinksPlugin.swift");
370        assert!(
371            source.contains("pub fn takeLinkFromRust(this: &DeepLinksPlugin) -> Option<String>;"),
372        );
373        assert!(source.contains("pub fn take_link(&mut self) -> Result<Option<String>, String>"),);
374        // Public so an app can prepare ahead of the provider, which is what
375        // makes an iOS cold-start link catchable at all.
376        assert!(source.contains("pub fn new() -> Self"));
377        // Android: cold start from the launch Intent, read once; warm links
378        // through the listener, since onNewIntent cannot be overridden here.
379        assert!(kotlin.contains("Intent.ACTION_VIEW"));
380        assert!(kotlin.contains("enqueue(activity.intent)"));
381        assert!(kotlin.contains("launchIntentConsumed = true"));
382        assert!(kotlin.contains("addOnNewIntentListener"));
383        // Static, so a link is not stranded on a discarded plugin instance.
384        assert!(kotlin.contains("companion object"));
385        // iOS: cold start from the launch options, warm links from delegate
386        // methods added to the host's delegate class at runtime.
387        assert!(swift.contains("didFinishLaunchingNotification"));
388        assert!(swift.contains("LaunchOptionsKey.userActivityDictionary"));
389        assert!(swift.contains("class_addMethod"));
390        assert!(swift.contains("application(_:continue:restorationHandler:)"));
391        assert!(swift.contains("application(_:open:options:)"));
392        // A cold-start link is reported through both paths; only one survives.
393        assert!(swift.contains("duplicateWindow"));
394    }
395    #[test]
396    fn android_plugins_resolve_classes_through_the_app_loader() {
397        // Learned the hard way on a device: JNI's FindClass resolves against
398        // the calling thread's loader, and a thread attached from native code
399        // gets the system loader, which has never heard of the app's classes.
400        // The macro's generated bindings use FindClass, so every Android call
401        // here goes through the bridge instead, which asks the Activity.
402        let bridge = include_str!("android_bridge.rs");
403        assert!(bridge.contains("getClassLoader"));
404        assert!(bridge.contains("loadClass"));
405        for source in [
406            include_str!("auth.rs"),
407            include_str!("camera_microphone.rs"),
408            include_str!("clipboard.rs"),
409            include_str!("deep_links.rs"),
410            include_str!("external_url.rs"),
411            include_str!("geolocation.rs"),
412            include_str!("in_app_purchases.rs"),
413            include_str!("notifications.rs"),
414            include_str!("push_notifications.rs"),
415            include_str!("storage.rs"),
416            include_str!("updater.rs"),
417        ] {
418            let production = production_source(source);
419            let android = production
420                .split("unsafe extern \"Kotlin\" {")
421                .nth(1)
422                .expect("each plugin declares a Kotlin block")
423                .split('}')
424                .next()
425                .expect("the Kotlin block should be closed");
426            // Only the type, so `dx` still builds the module. A function
427            // declared here would generate a FindClass binding and crash the
428            // moment a Dioxus effect called it.
429            assert!(
430                !android.contains("pub fn "),
431                "a Kotlin block still declares functions: {android}",
432            );
433            assert!(production.contains("crate::android_bridge::AndroidPlugin"));
434        }
435    }
436    #[test]
437    fn storage_encrypts_values_and_refuses_to_pretend_on_macos() {
438        let source = production_source(include_str!("storage.rs"));
439        let kotlin = include_str!(
440            "android/storage/src/main/kotlin/dev/dioxus/g3_native_plugins/storage/StoragePlugin.kt",
441        );
442        let swift = include_str!("ios/Sources/StoragePlugin.swift");
443        let gradle = include_str!("android/storage/build.gradle.kts");
444        assert!(source.contains("pub fn get(&mut self, key: &str)"));
445        assert!(source.contains("pub fn set(&mut self, key: &str, value: &str)"));
446        assert!(source.contains("pub fn keys(&mut self)"));
447        // Public so an app can read configuration before `dioxus::launch`.
448        assert!(source.contains("pub fn new() -> Self"));
449        // A store that silently discards is worse than one that says it cannot
450        // help, so this plugin alone does not compile to an inert no-op.
451        assert!(source.contains("Secure storage is not implemented on macOS"));
452        // Android: Keystore-held AES-GCM, and no Tink dependency behind an
453        // unmaintained library to get it.
454        assert!(kotlin.contains("AndroidKeyStore"));
455        assert!(kotlin.contains("AES/GCM/NoPadding"));
456        // No dependency at all, so nothing to argue about. The comment in that
457        // file names security-crypto to explain why, hence matching on the
458        // declaration form rather than the word.
459        assert!(!gradle.contains("implementation("));
460        // The cipher picks the nonce: a reused GCM nonce leaks the plaintext.
461        assert!(kotlin.contains("val nonce = cipher.iv"));
462        // kotlin.error() throws, so a helper of that name would be a live trap.
463        assert!(!kotlin.contains(" error("));
464        assert!(kotlin.contains("errorJson("));
465        // iOS: keychain, readable in the background after one unlock.
466        assert!(swift.contains("kSecClassGenericPassword"));
467        assert!(swift.contains("kSecAttrAccessibleAfterFirstUnlock"));
468        // The keychain has no upsert; update first, then add.
469        assert!(swift.contains("SecItemUpdate"));
470        assert!(swift.contains("SecItemAdd"));
471        assert!(swift.contains("errSecItemNotFound"));
472    }
473    #[test]
474    fn camera_microphone_leaves_the_webview_permission_bridge_to_wry() {
475        let source = production_source(include_str!("camera_microphone.rs"));
476        let kotlin = include_str!(
477            "android/camera_microphone/src/main/kotlin/dev/dioxus/g3_native_plugins/camera_microphone/CameraMicrophonePlugin.kt",
478        );
479        let swift = include_str!("ios/Sources/CameraMicrophonePlugin.swift");
480        assert!(source.contains("pub fn check_permissions"));
481        assert!(source.contains("pub fn open_settings"));
482        assert!(source.contains("pub struct CapturePermissions"));
483        // wry already answers the WebView's own permission callbacks. Taking
484        // either delegate over would break its file chooser and JS dialogs, so
485        // neither native side may install one. The prose above each plugin says
486        // as much, so these look for the code, not the words.
487        assert!(!kotlin.contains("setWebChromeClient"));
488        assert!(!kotlin.contains("override fun onPermissionRequest"));
489        assert!(!swift.contains("uiDelegate ="));
490        assert!(!swift.contains("func webView("));
491        // What is left is the part the page cannot reach.
492        assert!(kotlin.contains("ACTION_APPLICATION_DETAILS_SETTINGS"));
493        assert!(kotlin.contains("shouldShowRequestPermissionRationale"));
494        assert!(swift.contains("openSettingsURLString"));
495        assert!(swift.contains("AVCaptureDevice.authorizationStatus"));
496        assert!(swift.contains("AVCaptureDevice.requestAccess"));
497        // A .playback session has no input, so a shared session needs moving.
498        assert!(swift.contains("playAndRecord"));
499        assert!(swift.contains("defaultToSpeaker"));
500    }
501    #[test]
502    fn permission_state_is_shared_rather_than_duplicated_per_plugin() {
503        // Both plugins glob-export at the crate root, so a second definition
504        // would collide there rather than merely repeating itself.
505        let permissions = include_str!("permissions.rs");
506        let geolocation = production_source(include_str!("geolocation.rs"));
507        let capture = production_source(include_str!("camera_microphone.rs"));
508        assert!(permissions.contains("pub enum PermissionState"));
509        assert!(!geolocation.contains("pub enum PermissionState"));
510        assert!(!capture.contains("pub enum PermissionState"));
511        assert!(geolocation.contains("use crate::permissions::PermissionState;"));
512        assert!(capture.contains("use crate::permissions::PermissionState;"));
513    }
514    #[test]
515    fn geolocation_starts_and_polls_rather_than_blocking() {
516        let source = production_source(include_str!("geolocation.rs"));
517        let kotlin = include_str!(
518            "android/geolocation/src/main/kotlin/dev/dioxus/g3_native_plugins/geolocation/GeolocationPlugin.kt",
519        );
520        let swift = include_str!("ios/Sources/GeolocationPlugin.swift");
521        let gradle = include_str!("android/geolocation/build.gradle.kts");
522        assert!(source.contains("pub fn start_position_request"));
523        assert!(
524            source.contains("pub fn poll_position(&mut self) -> Result<Option<Position>, String>"),
525        );
526        assert!(source.contains("pub fn check_permissions"));
527        assert!(source.contains("pub struct Position"));
528        assert!(source.contains("pub struct Coordinates"));
529        // The reference example blocks the caller on both platforms; this one
530        // must not, because the call arrives on a Dioxus effect thread.
531        assert!(!kotlin.contains("CountDownLatch"));
532        assert!(!swift.contains("DispatchSemaphore"));
533        assert!(!swift.contains("RunLoop.current.run"));
534        // A library does not get to force Play Services on its consumers, so
535        // no dependency may name the coordinate the fused provider ships under.
536        assert!(!gradle.contains("com.google.android.gms"));
537        assert!(!kotlin.contains("com.google.android.gms"));
538        assert!(kotlin.contains("LocationManager"));
539        assert!(kotlin.contains("requestLocationUpdates"));
540        assert!(kotlin.contains("prompt-with-rationale"));
541        assert!(swift.contains("CLLocationManagerDelegate"));
542        assert!(swift.contains("manager.requestLocation()"));
543        assert!(swift.contains("locationManagerDidChangeAuthorization"));
544        // Negative CoreLocation accuracies mean invalid, not precise.
545        assert!(swift.contains("location.verticalAccuracy >= 0"));
546    }
547    #[test]
548    fn in_app_purchases_start_and_poll_on_both_stores() {
549        let source = production_source(include_str!("in_app_purchases.rs"));
550        let kotlin = include_str!(
551            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/InAppPurchasesPlugin.kt",
552        );
553        let catalogue = include_str!(
554            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/Catalogue.kt",
555        );
556        let swift = include_str!("ios/Sources/InAppPurchasesPlugin.swift");
557        let store = include_str!("ios/Sources/StoreCatalogue.swift");
558        let gradle = include_str!("android/in_app_purchases/build.gradle.kts");
559        assert!(!kotlin.contains("queryPurchasesAsync(params) { _,"));
560        assert!(!kotlin.contains("queryProductDetailsAsync(params) { _,"));
561        assert!(kotlin.contains("publish(Catalogue.error(errorMessage), isProducts = true)"));
562        assert!(kotlin.contains("else publishEntitlementsError(errorMessage)"));
563        assert!(kotlin.contains("known.putAll(details)"));
564        assert!(source.contains("pub fn start_purchase"));
565        assert!(source.contains("pub fn poll_entitlements"));
566        assert!(source.contains("pub fn start_external_content_link_token"));
567        assert!(source.contains("pub fn launch_external_content_link"));
568        assert!(
569            production_source(include_str!("lib.rs"))
570                .contains("pub use in_app_purchases::{Entitlement, ExternalContentLinkToken")
571        );
572        assert!(source.contains("pub fn finish(&mut self, transaction_id: &str, consume: bool)"),);
573        assert!(source.contains("Subscription"));
574        assert!(source.contains("pub struct SubscriptionOffer"));
575        assert!(source.contains("pub will_auto_renew: bool"));
576        // Play billing has no substitute, so it is a real dependency rather
577        // than compileOnly like the androidx ones elsewhere.
578        assert!(gradle.contains("com.android.billingclient:billing:8.2.1"));
579        assert!(gradle.contains("implementation("));
580        assert!(kotlin.contains("BillingProgram.EXTERNAL_CONTENT_LINK"));
581        assert!(kotlin.contains("createBillingProgramReportingDetailsAsync"));
582        assert!(kotlin.contains("launchExternalLink"));
583        // A purchase left unacknowledged for three days is refunded by Play.
584        assert!(kotlin.contains("acknowledgePurchase"));
585        assert!(kotlin.contains("consumeAsync"));
586        assert!(kotlin.contains("needsFinishing"));
587        // Subscriptions cannot be bought without naming an offer token.
588        assert!(kotlin.contains("setOfferToken"));
589        assert!(kotlin.contains("queryPurchasesAsync"));
590        assert!(catalogue.contains("subscriptionOfferDetails"));
591        // StoreKit 2 is async Swift, which cannot cross the FFI boundary.
592        assert!(swift.contains("Transaction.updates"));
593        assert!(swift.contains("Transaction.currentEntitlements"));
594        assert!(swift.contains("Transaction.unfinished"));
595        assert!(swift.contains("AppStore.sync()"));
596        assert!(swift.contains("jwsRepresentation"));
597        assert!(swift.contains("renewal.willAutoRenew"));
598        assert!(store.contains("nonRenewable"));
599    }
600    #[test]
601    fn ios_media_plugin_owns_background_audio_and_lock_screen_controls() {
602        let source = production_source(include_str!("media.rs"));
603        let swift = include_str!("ios/Sources/MediaPlugin.swift");
604        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
605        assert!(source.contains(
606            "pub fn setPlaybackActiveFromRust(this: &MediaPlugin, playbackJson: String);",
607        ),);
608        assert!(swift.contains("AVAudioSession.sharedInstance().setCategory(.playback"));
609        assert!(swift.contains("MPNowPlayingInfoCenter"));
610        assert!(swift.contains("MPRemoteCommandCenter.shared()"));
611        assert!(swift.contains("beginReceivingRemoteControlEvents"));
612        assert!(swift.contains("notifyOthersOnDeactivation"));
613        assert!(swift.contains("webkitSetPresentationMode"));
614        assert!(swift.contains("requestGeometryUpdate"));
615        // Same duplicate-event guard as Android, for the same audible reason.
616        assert!(swift.contains("if !wasActive || titleChanged"));
617        assert!(swift.contains("__tawnyPlaybackIntent"));
618    }
619    #[test]
620    fn native_plugins_provider_owns_plugin_construction() {
621        let source = production_source(include_str!("lib.rs"));
622        let provider_start = source
623            .find("pub fn NativePluginsProvider(children: Element) -> Element")
624            .expect("provider component should be exported");
625        let provider_prefix = &source[..provider_start];
626        assert!(source.contains("pub struct NativePlugins"));
627        assert!(source.contains("pub fn NativePluginsProvider(children: Element) -> Element"),);
628        assert!(
629            !provider_prefix
630                .trim_end()
631                .ends_with("target_os = \"macos\"\n))]\n#[component]"),
632        );
633        assert!(source.contains("use_context_provider(NativePlugins::default)"));
634        assert!(source.contains("{children}"));
635        assert!(source.contains("pub auth: Signal<Auth>"));
636        assert!(source.contains("pub camera_microphone: Signal<CameraMicrophone>"));
637        assert!(source.contains("pub clipboard: Signal<Clipboard>"));
638        assert!(source.contains("pub deep_links: Signal<DeepLinks>"));
639        assert!(source.contains("pub external_url: Signal<ExternalUrl>"));
640        assert!(source.contains("pub geolocation: Signal<Geolocation>"));
641        assert!(source.contains("pub in_app_purchases: Signal<InAppPurchases>"));
642        assert!(source.contains("pub media: Signal<Media>"));
643        assert!(source.contains("pub storage: Signal<KeyValueStore>"));
644        assert!(source.contains("auth: Signal::new(Auth::new())"));
645        assert!(source.contains("camera_microphone: Signal::new(CameraMicrophone::new())"));
646        assert!(source.contains("clipboard: Signal::new(Clipboard::new())"));
647        assert!(source.contains("deep_links: Signal::new(DeepLinks::new())"));
648        assert!(source.contains("external_url: Signal::new(ExternalUrl::new())"));
649        assert!(source.contains("geolocation: Signal::new(Geolocation::new())"));
650        assert!(source.contains("in_app_purchases: Signal::new(InAppPurchases::new())"));
651        assert!(source.contains("media: Signal::new(Media::new())"));
652        assert!(source.contains("storage: Signal::new(KeyValueStore::new())"));
653        assert!(source.contains("pub notifications: Signal<Notifications>"));
654        assert!(source.contains("pub push_notifications: Signal<PushNotifications>"));
655        assert!(source.contains("pub updater: Signal<Updater>"));
656        assert!(source.contains("notifications: Signal::new(Notifications::new())"));
657        assert!(source.contains("push_notifications: Signal::new(PushNotifications::new())"));
658        assert!(source.contains("updater: Signal::new(Updater::new())"));
659        assert!(source.contains("impl Default for NativePlugins"));
660        assert!(source.contains("Self::new()"));
661    }
662    #[test]
663    fn ios_clipboard_plugin_supports_copy_and_scene_safe_share() {
664        let swift = include_str!("ios/Sources/ClipboardPlugin.swift");
665        let rust = include_str!("clipboard.rs");
666        assert!(rust.contains("pub fn copy_to_clipboard(&mut self, text: String)"));
667        assert!(rust.contains(
668            "pub fn copyToClipboardFromRust(this: &ClipboardPlugin, text: String) -> String;",
669        ),);
670        assert!(swift.contains("public func copyToClipboardFromRust(_ text: String) -> String",),);
671        assert!(swift.contains("UIPasteboard.general.string = text"));
672        assert!(swift.contains("NSLog(\"[ClipboardPlugin]"));
673        assert!(swift.contains("connectedScenes"));
674        assert!(swift.contains("popover.sourceView = vc.view"));
675        assert!(!swift.contains("keyWindow"));
676    }
677    #[test]
678    fn ios_plugins_share_one_swift_package_for_current_dx() {
679        let manifest = include_str!("ios/Package.swift");
680        let auth = include_str!("auth.rs");
681        let swift_auth = include_str!("ios/Sources/AuthPlugin.swift");
682        let clipboard = include_str!("clipboard.rs");
683        let external_url = include_str!("external_url.rs");
684        assert!(manifest.contains("name: \"DioxusNativePlugins\""));
685        assert!(manifest.contains(".library(name: \"AuthPlugin\""));
686        assert!(manifest.contains(".library(name: \"BackButtonPlugin\""));
687        assert!(manifest.contains(".library(name: \"CameraMicrophonePlugin\""));
688        assert!(manifest.contains(".library(name: \"ClipboardPlugin\""));
689        assert!(manifest.contains(".library(name: \"DeepLinksPlugin\""));
690        assert!(manifest.contains(".library(name: \"ExternalUrlPlugin\""));
691        assert!(manifest.contains(".library(name: \"GeolocationPlugin\""));
692        assert!(manifest.contains(".library(name: \"InAppPurchasesPlugin\""));
693        assert!(manifest.contains(".linkedFramework(\"StoreKit\")"));
694        assert!(manifest.contains(".linkedFramework(\"CoreLocation\")"));
695        assert!(manifest.contains(".library(name: \"MediaPlugin\""));
696        assert!(manifest.contains(".library(name: \"StoragePlugin\""));
697        assert!(manifest.contains(".library(name: \"NotificationsPlugin\""));
698        assert!(manifest.contains(".library(name: \"PushNotificationsPlugin\""));
699        assert!(manifest.contains(".library(name: \"UpdaterPlugin\""));
700        assert!(manifest.contains(".linkedFramework(\"UserNotifications\")"));
701        assert!(manifest.contains(".linkedFramework(\"Security\")"));
702        assert!(manifest.contains(".linkedFramework(\"AuthenticationServices\")"));
703        assert!(manifest.contains(".linkedFramework(\"AVFoundation\")"));
704        assert!(manifest.contains(".linkedFramework(\"MediaPlayer\""));
705        assert!(manifest.contains(".linkedFramework(\"WebKit\")"));
706        assert!(auth.contains("#[manganis::ffi(\"src/ios\")]"));
707        assert!(
708            auth.contains("pub fn startAppleAuthFromRust(this: &AuthPlugin, requestJson: String) -> Option<String>;",),
709        );
710        assert!(auth.contains("pub fn getAuthState(this: &AuthPlugin) -> Option<String>;"),);
711        assert!(!auth.contains("signOutFromRust"));
712        assert!(swift_auth.contains("ASAuthorizationAppleIDProvider"));
713        assert!(swift_auth.contains("request.nonce = Self.sha256(authRequest.nonce)"));
714        assert!(swift_auth.contains("credential.authorizationCode"));
715        assert!(swift_auth.contains("\"authorization_code\""));
716        assert!(swift_auth.contains("public func getAuthState() -> String?"));
717        assert!(swift_auth.contains("identity_token"));
718        assert!(!swift_auth.contains("Email found:"));
719        assert!(!swift_auth.contains("Display name:"));
720        assert!(clipboard.contains("#[manganis::ffi(\"src/ios\")]"));
721        assert!(external_url.contains("#[manganis::ffi(\"src/ios\")]"));
722    }
723    #[test]
724    fn android_auth_plugin_exposes_google_sign_in() {
725        let auth = include_str!("auth.rs");
726        let kotlin_auth = include_str!(
727            "android/auth/src/main/kotlin/dev/dioxus/g3_native_plugins/auth/AuthPlugin.kt",
728        );
729        assert!(auth.contains("#[manganis::ffi(\"src/android/auth\")]"));
730        assert!(auth.contains("unsafe extern \"Kotlin\""));
731        let android = auth
732            .split("unsafe extern \"Kotlin\" {")
733            .nth(1)
734            .expect("auth declares its Kotlin module")
735            .split('}')
736            .next()
737            .expect("the Kotlin block should be closed");
738        assert!(!android.contains("pub fn "));
739        assert!(auth.contains("type AuthHandle = crate::android_bridge::AndroidPlugin"));
740        // The client id is the caller's, not the crate's. It names one Google
741        // Cloud project and is checked against an Android client registered
742        // there for the app's package and certificate, so a library carrying
743        // its own could only ever authenticate the app it shipped with.
744        assert!(auth.contains(
745            "pub fn start_google_auth(&mut self, server_client_id: &str) -> Result<(), String>",
746        ),);
747        assert!(
748            auth.contains("pub fn poll_auth_result(&mut self) -> Result<Option<String>, String>",)
749        );
750        assert!(auth.contains("pub fn is_auth_awaiting(&mut self) -> bool"));
751        assert!(kotlin_auth.contains("fun startGoogleAuthFromRust(serverClientId: String)"));
752        assert!(kotlin_auth.contains("fun getPendingResult(): String?"));
753        assert!(kotlin_auth.contains("fun getAuthState(): String"));
754        assert!(kotlin_auth.contains("setServerClientId(serverClientId)"));
755        assert!(!kotlin_auth.contains("apps.googleusercontent.com"));
756        assert!(!kotlin_auth.contains("CountDownLatch"));
757        assert!(!kotlin_auth.contains("TimeUnit"));
758        assert!(kotlin_auth.contains("GoogleIdTokenCredential.createFrom"));
759    }
760    #[test]
761    fn android_media_plugin_owns_mobile_playback_capabilities() {
762        let rust = include_str!("media.rs");
763        let kotlin = include_str!(
764            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/MediaPlugin.kt",
765        );
766        let service = include_str!(
767            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/PlaybackService.kt",
768        );
769        let manifest = include_str!("android/media/src/main/AndroidManifest.xml");
770        assert!(rust.contains("getClassLoader"));
771        assert!(rust.contains("enter_picture_in_picture"));
772        assert!(rust.contains("set_orientation"));
773        assert!(rust.contains("set_system_bars_hidden"));
774        assert!(rust.contains("set_playback_active"));
775        assert!(kotlin.contains("fun setSystemBarsHiddenFromRust(hidden: Boolean)"));
776        assert!(kotlin.contains("enterPictureInPictureMode"));
777        assert!(kotlin.contains("setActions(pipActions())"));
778        assert!(kotlin.contains("COMMAND_REWIND"));
779        assert!(kotlin.contains("COMMAND_FORWARD"));
780        assert!(kotlin.contains("dataset.androidPip"));
781        assert!(kotlin.contains("tawnynativepictureinpicturechange"));
782        assert!(kotlin.contains("tawnynativeplaybackresume"));
783        assert!(kotlin.contains("Application.ActivityLifecycleCallbacks"));
784        assert!(kotlin.contains("playing && !serviceForeground"));
785        assert!(rust.contains("clear_playback"));
786        assert!(kotlin.contains("fun clearPlaybackFromRust()"));
787        assert!(kotlin.contains("MediaSession(activity"));
788        assert!(kotlin.contains("setMediaSession(session.sessionToken)"));
789        assert!(kotlin.contains("OnWindowVisibilityChangeListener"));
790        assert!(service.contains("STOP_FOREGROUND_DETACH"));
791        assert!(manifest.contains("android:launchMode=\"singleTask\""));
792        assert!(!kotlin.contains("setSourceRectHint"));
793        assert!(kotlin.contains("SCREEN_ORIENTATION_SENSOR_LANDSCAPE"));
794        assert!(kotlin.contains("--android-status-bar-inset"));
795        assert!(service.contains("startForeground"));
796        assert!(manifest.contains("android:supportsPictureInPicture=\"true\""));
797        assert!(manifest.contains("foregroundServiceType=\"mediaPlayback\""));
798    }
799    #[test]
800    fn updater_trusts_nothing_before_the_signature_and_keeps_decisions_in_rust() {
801        let source = production_source(include_str!("updater.rs"));
802        let kotlin = include_str!(
803            "android/updater/src/main/kotlin/dev/dioxus/g3_native_plugins/updater/UpdaterPlugin.kt",
804        );
805        let swift = include_str!("ios/Sources/UpdaterPlugin.swift");
806        let gradle = include_str!("android/updater/build.gradle.kts");
807        // The manifest is verified before it is parsed, and its hashes carry
808        // that guarantee to every file.
809        let verified = source
810            .find("verify_signature(&config.pubkey")
811            .expect("the manifest signature is checked");
812        let parsed = source
813            .find("let manifest = parse_manifest(&bytes)?")
814            .unwrap();
815        assert!(verified < parsed);
816        assert!(source.contains("does not match the hash in the signed manifest"));
817        assert!(source.contains("minisign_verify::PublicKey"));
818        // Installed on trial, rolled back if never confirmed.
819        assert!(source.contains("pub fn notify_ready(&mut self)"));
820        assert!(source.contains("state.trial && state.trial_launches >= 1"));
821        // Downloads happen off the Dioxus thread.
822        assert!(source.contains("std::thread::Builder::new()"));
823        // The native sides only move bytes: no hashing or verification there.
824        assert!(!kotlin.contains("MessageDigest"));
825        assert!(!swift.contains("CryptoKit"));
826        assert!(kotlin.contains("noBackupFilesDir"));
827        assert!(swift.contains("isExcludedFromBackup = true"));
828        // A half-written file never sits where a finished one belongs.
829        assert!(kotlin.contains("partial.renameTo(destination)"));
830        assert!(!gradle.contains("implementation("));
831        assert!(!kotlin.contains(" error("));
832    }
833    #[test]
834    fn notifications_survive_reboots_without_claiming_exact_alarms() {
835        let source = production_source(include_str!("notifications.rs"));
836        let plugin = include_str!(
837            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationsPlugin.kt",
838        );
839        let store = include_str!(
840            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Store.kt",
841        );
842        let poster = include_str!(
843            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationPoster.kt",
844        );
845        let receivers = include_str!(
846            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Receivers.kt",
847        );
848        let manifest = include_str!("android/notifications/src/main/AndroidManifest.xml");
849        let gradle = include_str!("android/notifications/build.gradle.kts");
850        let swift = include_str!("ios/Sources/NotificationsPlugin.swift");
851        let relay = include_str!("ios/Sources/NotificationCenterRelay.swift");
852        assert!(
853            source.contains(
854                "pub fn take_event(&mut self) -> Result<Option<NotificationEvent>, String>"
855            )
856        );
857        assert!(source.contains("pub fn new() -> Self"));
858        // Android: alarms re-armed after a reboot, exact only when allowed,
859        // and the restricted permission left for the app to claim.
860        assert!(manifest.contains("android.permission.POST_NOTIFICATIONS"));
861        assert!(manifest.contains("android.intent.action.BOOT_COMPLETED"));
862        assert!(
863            !manifest.contains(
864                "uses-permission android:name=\"android.permission.SCHEDULE_EXACT_ALARM\""
865            )
866        );
867        assert!(manifest.contains("android:launchMode=\"singleTask\""));
868        assert!(store.contains("canScheduleExactAlarms()"));
869        assert!(receivers.contains("class BootReceiver"));
870        // Taps come back through both launch paths, like deep links.
871        assert!(plugin.contains("addOnNewIntentListener"));
872        assert!(plugin.contains("launchIntentConsumed = true"));
873        // PendingIntents differing only in extras collapse into one.
874        assert!(poster.contains("requestCode(notification.getInt(\"id\"), action)"));
875        // optString turns JSON null into the text "null".
876        assert!(poster.contains("stringOrNull(\"body\")"));
877        assert!(!gradle.contains("implementation("));
878        for kotlin in [plugin, store, poster, receivers] {
879            assert!(!kotlin.contains(" error("));
880        }
881        // iOS: one delegate for local and push, never displacing the host's.
882        assert!(relay.contains("UNPushNotificationTrigger"));
883        assert!(relay.contains("leaving it alone"));
884        assert!(swift.contains("UNTextInputNotificationAction"));
885        assert!(swift.contains("NotificationCenterRelay.install()"));
886    }
887    #[test]
888    fn push_keeps_firebase_out_of_local_only_apps() {
889        let source = production_source(include_str!("push_notifications.rs"));
890        let manifest = include_str!("../Cargo.toml");
891        let kotlin = include_str!(
892            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushNotificationsPlugin.kt",
893        );
894        let service = include_str!(
895            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushMessagingService.kt",
896        );
897        let android_manifest =
898            include_str!("android/push_notifications/src/main/AndroidManifest.xml");
899        let gradle = include_str!("android/push_notifications/build.gradle.kts");
900        let swift = include_str!("ios/Sources/PushNotificationsPlugin.swift");
901        assert!(manifest.contains("push-notifications = [\"notifications\"]"));
902        assert!(gradle.contains("com.google.firebase:firebase-messaging"));
903        assert!(source.contains("pub fn register(&mut self, firebase: Option<&FirebaseOptions>)"));
904        // A generated Gradle project cannot run the google-services plugin,
905        // so Firebase is initialized from values passed at run time.
906        assert!(kotlin.contains("FirebaseApp.initializeApp(context, options)"));
907        assert!(android_manifest.contains("com.google.firebase.MESSAGING_EVENT"));
908        assert!(service.contains("override fun onNewToken"));
909        // iOS: APNs answers the app delegate, which Dioxus's does not
910        // implement, so the hooks are added at runtime.
911        assert!(swift.contains("class_addMethod"));
912        assert!(swift.contains("didRegisterForRemoteNotificationsWithDeviceToken"));
913        assert!(swift.contains("registerForRemoteNotifications()"));
914    }
915    #[test]
916    fn plugin_wrapper_constructors_stay_crate_private_and_lazy() {
917        for (source, plugin_type, handle_type) in [
918            (
919                production_source(include_str!("auth.rs")),
920                "AuthPlugin",
921                "AuthHandle",
922            ),
923            (
924                production_source(include_str!("clipboard.rs")),
925                "ClipboardPlugin",
926                "ClipboardHandle",
927            ),
928            (
929                production_source(include_str!("external_url.rs")),
930                "ExternalUrlPlugin",
931                "ExternalUrlHandle",
932            ),
933        ] {
934            assert!(source.contains("pub(crate) fn new() -> Self"));
935            assert!(!source.contains("pub fn new() -> Self"));
936            assert!(source.contains(&format!("plugin: Option<{handle_type}>")));
937            assert!(source.contains("Self { plugin: None }"));
938            assert!(source.contains("self.plugin = Some("));
939            assert!(source.contains(&format!("{plugin_type}::new()")));
940            assert!(!source.contains(&format!("plugin: Result<{plugin_type}, String>")));
941        }
942    }
943}