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!(source.contains("pub fn start_purchase"));
560        assert!(source.contains("pub fn poll_entitlements"));
561        assert!(source.contains("pub fn start_external_content_link_token"));
562        assert!(source.contains("pub fn launch_external_content_link"));
563        assert!(
564            production_source(include_str!("lib.rs"))
565                .contains("pub use in_app_purchases::{Entitlement, ExternalContentLinkToken")
566        );
567        assert!(source.contains("pub fn finish(&mut self, transaction_id: &str, consume: bool)"),);
568        assert!(source.contains("Subscription"));
569        assert!(source.contains("pub struct SubscriptionOffer"));
570        assert!(source.contains("pub will_auto_renew: bool"));
571        // Play billing has no substitute, so it is a real dependency rather
572        // than compileOnly like the androidx ones elsewhere.
573        assert!(gradle.contains("com.android.billingclient:billing:8.2.1"));
574        assert!(gradle.contains("implementation("));
575        assert!(kotlin.contains("BillingProgram.EXTERNAL_CONTENT_LINK"));
576        assert!(kotlin.contains("createBillingProgramReportingDetailsAsync"));
577        assert!(kotlin.contains("launchExternalLink"));
578        // A purchase left unacknowledged for three days is refunded by Play.
579        assert!(kotlin.contains("acknowledgePurchase"));
580        assert!(kotlin.contains("consumeAsync"));
581        assert!(kotlin.contains("needsFinishing"));
582        // Subscriptions cannot be bought without naming an offer token.
583        assert!(kotlin.contains("setOfferToken"));
584        assert!(kotlin.contains("queryPurchasesAsync"));
585        assert!(catalogue.contains("subscriptionOfferDetails"));
586        // StoreKit 2 is async Swift, which cannot cross the FFI boundary.
587        assert!(swift.contains("Transaction.updates"));
588        assert!(swift.contains("Transaction.currentEntitlements"));
589        assert!(swift.contains("Transaction.unfinished"));
590        assert!(swift.contains("AppStore.sync()"));
591        assert!(swift.contains("jwsRepresentation"));
592        assert!(swift.contains("renewal.willAutoRenew"));
593        assert!(store.contains("nonRenewable"));
594    }
595    #[test]
596    fn ios_media_plugin_owns_background_audio_and_lock_screen_controls() {
597        let source = production_source(include_str!("media.rs"));
598        let swift = include_str!("ios/Sources/MediaPlugin.swift");
599        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
600        assert!(source.contains(
601            "pub fn setPlaybackActiveFromRust(this: &MediaPlugin, playbackJson: String);",
602        ),);
603        assert!(swift.contains("AVAudioSession.sharedInstance().setCategory(.playback"));
604        assert!(swift.contains("MPNowPlayingInfoCenter"));
605        assert!(swift.contains("MPRemoteCommandCenter.shared()"));
606        assert!(swift.contains("beginReceivingRemoteControlEvents"));
607        assert!(swift.contains("notifyOthersOnDeactivation"));
608        assert!(swift.contains("webkitSetPresentationMode"));
609        assert!(swift.contains("requestGeometryUpdate"));
610        // Same duplicate-event guard as Android, for the same audible reason.
611        assert!(swift.contains("if !wasActive || titleChanged"));
612        assert!(swift.contains("__tawnyPlaybackIntent"));
613    }
614    #[test]
615    fn native_plugins_provider_owns_plugin_construction() {
616        let source = production_source(include_str!("lib.rs"));
617        let provider_start = source
618            .find("pub fn NativePluginsProvider(children: Element) -> Element")
619            .expect("provider component should be exported");
620        let provider_prefix = &source[..provider_start];
621        assert!(source.contains("pub struct NativePlugins"));
622        assert!(source.contains("pub fn NativePluginsProvider(children: Element) -> Element"),);
623        assert!(
624            !provider_prefix
625                .trim_end()
626                .ends_with("target_os = \"macos\"\n))]\n#[component]"),
627        );
628        assert!(source.contains("use_context_provider(NativePlugins::default)"));
629        assert!(source.contains("{children}"));
630        assert!(source.contains("pub auth: Signal<Auth>"));
631        assert!(source.contains("pub camera_microphone: Signal<CameraMicrophone>"));
632        assert!(source.contains("pub clipboard: Signal<Clipboard>"));
633        assert!(source.contains("pub deep_links: Signal<DeepLinks>"));
634        assert!(source.contains("pub external_url: Signal<ExternalUrl>"));
635        assert!(source.contains("pub geolocation: Signal<Geolocation>"));
636        assert!(source.contains("pub in_app_purchases: Signal<InAppPurchases>"));
637        assert!(source.contains("pub media: Signal<Media>"));
638        assert!(source.contains("pub storage: Signal<KeyValueStore>"));
639        assert!(source.contains("auth: Signal::new(Auth::new())"));
640        assert!(source.contains("camera_microphone: Signal::new(CameraMicrophone::new())"));
641        assert!(source.contains("clipboard: Signal::new(Clipboard::new())"));
642        assert!(source.contains("deep_links: Signal::new(DeepLinks::new())"));
643        assert!(source.contains("external_url: Signal::new(ExternalUrl::new())"));
644        assert!(source.contains("geolocation: Signal::new(Geolocation::new())"));
645        assert!(source.contains("in_app_purchases: Signal::new(InAppPurchases::new())"));
646        assert!(source.contains("media: Signal::new(Media::new())"));
647        assert!(source.contains("storage: Signal::new(KeyValueStore::new())"));
648        assert!(source.contains("pub notifications: Signal<Notifications>"));
649        assert!(source.contains("pub push_notifications: Signal<PushNotifications>"));
650        assert!(source.contains("pub updater: Signal<Updater>"));
651        assert!(source.contains("notifications: Signal::new(Notifications::new())"));
652        assert!(source.contains("push_notifications: Signal::new(PushNotifications::new())"));
653        assert!(source.contains("updater: Signal::new(Updater::new())"));
654        assert!(source.contains("impl Default for NativePlugins"));
655        assert!(source.contains("Self::new()"));
656    }
657    #[test]
658    fn ios_clipboard_plugin_supports_copy_and_scene_safe_share() {
659        let swift = include_str!("ios/Sources/ClipboardPlugin.swift");
660        let rust = include_str!("clipboard.rs");
661        assert!(rust.contains("pub fn copy_to_clipboard(&mut self, text: String)"));
662        assert!(rust.contains(
663            "pub fn copyToClipboardFromRust(this: &ClipboardPlugin, text: String) -> String;",
664        ),);
665        assert!(swift.contains("public func copyToClipboardFromRust(_ text: String) -> String",),);
666        assert!(swift.contains("UIPasteboard.general.string = text"));
667        assert!(swift.contains("NSLog(\"[ClipboardPlugin]"));
668        assert!(swift.contains("connectedScenes"));
669        assert!(swift.contains("popover.sourceView = vc.view"));
670        assert!(!swift.contains("keyWindow"));
671    }
672    #[test]
673    fn ios_plugins_share_one_swift_package_for_current_dx() {
674        let manifest = include_str!("ios/Package.swift");
675        let auth = include_str!("auth.rs");
676        let swift_auth = include_str!("ios/Sources/AuthPlugin.swift");
677        let clipboard = include_str!("clipboard.rs");
678        let external_url = include_str!("external_url.rs");
679        assert!(manifest.contains("name: \"DioxusNativePlugins\""));
680        assert!(manifest.contains(".library(name: \"AuthPlugin\""));
681        assert!(manifest.contains(".library(name: \"BackButtonPlugin\""));
682        assert!(manifest.contains(".library(name: \"CameraMicrophonePlugin\""));
683        assert!(manifest.contains(".library(name: \"ClipboardPlugin\""));
684        assert!(manifest.contains(".library(name: \"DeepLinksPlugin\""));
685        assert!(manifest.contains(".library(name: \"ExternalUrlPlugin\""));
686        assert!(manifest.contains(".library(name: \"GeolocationPlugin\""));
687        assert!(manifest.contains(".library(name: \"InAppPurchasesPlugin\""));
688        assert!(manifest.contains(".linkedFramework(\"StoreKit\")"));
689        assert!(manifest.contains(".linkedFramework(\"CoreLocation\")"));
690        assert!(manifest.contains(".library(name: \"MediaPlugin\""));
691        assert!(manifest.contains(".library(name: \"StoragePlugin\""));
692        assert!(manifest.contains(".library(name: \"NotificationsPlugin\""));
693        assert!(manifest.contains(".library(name: \"PushNotificationsPlugin\""));
694        assert!(manifest.contains(".library(name: \"UpdaterPlugin\""));
695        assert!(manifest.contains(".linkedFramework(\"UserNotifications\")"));
696        assert!(manifest.contains(".linkedFramework(\"Security\")"));
697        assert!(manifest.contains(".linkedFramework(\"AuthenticationServices\")"));
698        assert!(manifest.contains(".linkedFramework(\"AVFoundation\")"));
699        assert!(manifest.contains(".linkedFramework(\"MediaPlayer\""));
700        assert!(manifest.contains(".linkedFramework(\"WebKit\")"));
701        assert!(auth.contains("#[manganis::ffi(\"src/ios\")]"));
702        assert!(
703            auth.contains("pub fn startAppleAuthFromRust(this: &AuthPlugin, requestJson: String) -> Option<String>;",),
704        );
705        assert!(auth.contains("pub fn getAuthState(this: &AuthPlugin) -> Option<String>;"),);
706        assert!(!auth.contains("signOutFromRust"));
707        assert!(swift_auth.contains("ASAuthorizationAppleIDProvider"));
708        assert!(swift_auth.contains("request.nonce = Self.sha256(authRequest.nonce)"));
709        assert!(swift_auth.contains("credential.authorizationCode"));
710        assert!(swift_auth.contains("\"authorization_code\""));
711        assert!(swift_auth.contains("public func getAuthState() -> String?"));
712        assert!(swift_auth.contains("identity_token"));
713        assert!(!swift_auth.contains("Email found:"));
714        assert!(!swift_auth.contains("Display name:"));
715        assert!(clipboard.contains("#[manganis::ffi(\"src/ios\")]"));
716        assert!(external_url.contains("#[manganis::ffi(\"src/ios\")]"));
717    }
718    #[test]
719    fn android_auth_plugin_exposes_google_sign_in() {
720        let auth = include_str!("auth.rs");
721        let kotlin_auth = include_str!(
722            "android/auth/src/main/kotlin/dev/dioxus/g3_native_plugins/auth/AuthPlugin.kt",
723        );
724        assert!(auth.contains("#[manganis::ffi(\"src/android/auth\")]"));
725        assert!(auth.contains("unsafe extern \"Kotlin\""));
726        let android = auth
727            .split("unsafe extern \"Kotlin\" {")
728            .nth(1)
729            .expect("auth declares its Kotlin module")
730            .split('}')
731            .next()
732            .expect("the Kotlin block should be closed");
733        assert!(!android.contains("pub fn "));
734        assert!(auth.contains("type AuthHandle = crate::android_bridge::AndroidPlugin"));
735        // The client id is the caller's, not the crate's. It names one Google
736        // Cloud project and is checked against an Android client registered
737        // there for the app's package and certificate, so a library carrying
738        // its own could only ever authenticate the app it shipped with.
739        assert!(auth.contains(
740            "pub fn start_google_auth(&mut self, server_client_id: &str) -> Result<(), String>",
741        ),);
742        assert!(
743            auth.contains("pub fn poll_auth_result(&mut self) -> Result<Option<String>, String>",)
744        );
745        assert!(auth.contains("pub fn is_auth_awaiting(&mut self) -> bool"));
746        assert!(kotlin_auth.contains("fun startGoogleAuthFromRust(serverClientId: String)"));
747        assert!(kotlin_auth.contains("fun getPendingResult(): String?"));
748        assert!(kotlin_auth.contains("fun getAuthState(): String"));
749        assert!(kotlin_auth.contains("setServerClientId(serverClientId)"));
750        assert!(!kotlin_auth.contains("apps.googleusercontent.com"));
751        assert!(!kotlin_auth.contains("CountDownLatch"));
752        assert!(!kotlin_auth.contains("TimeUnit"));
753        assert!(kotlin_auth.contains("GoogleIdTokenCredential.createFrom"));
754    }
755    #[test]
756    fn android_media_plugin_owns_mobile_playback_capabilities() {
757        let rust = include_str!("media.rs");
758        let kotlin = include_str!(
759            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/MediaPlugin.kt",
760        );
761        let service = include_str!(
762            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/PlaybackService.kt",
763        );
764        let manifest = include_str!("android/media/src/main/AndroidManifest.xml");
765        assert!(rust.contains("getClassLoader"));
766        assert!(rust.contains("enter_picture_in_picture"));
767        assert!(rust.contains("set_orientation"));
768        assert!(rust.contains("set_system_bars_hidden"));
769        assert!(rust.contains("set_playback_active"));
770        assert!(kotlin.contains("fun setSystemBarsHiddenFromRust(hidden: Boolean)"));
771        assert!(kotlin.contains("enterPictureInPictureMode"));
772        assert!(kotlin.contains("setActions(pipActions())"));
773        assert!(kotlin.contains("COMMAND_REWIND"));
774        assert!(kotlin.contains("COMMAND_FORWARD"));
775        assert!(kotlin.contains("dataset.androidPip"));
776        assert!(kotlin.contains("tawnynativepictureinpicturechange"));
777        assert!(kotlin.contains("tawnynativeplaybackresume"));
778        assert!(kotlin.contains("Application.ActivityLifecycleCallbacks"));
779        assert!(kotlin.contains("playing && !serviceForeground"));
780        assert!(rust.contains("clear_playback"));
781        assert!(kotlin.contains("fun clearPlaybackFromRust()"));
782        assert!(kotlin.contains("MediaSession(activity"));
783        assert!(kotlin.contains("setMediaSession(session.sessionToken)"));
784        assert!(kotlin.contains("OnWindowVisibilityChangeListener"));
785        assert!(service.contains("STOP_FOREGROUND_DETACH"));
786        assert!(manifest.contains("android:launchMode=\"singleTask\""));
787        assert!(!kotlin.contains("setSourceRectHint"));
788        assert!(kotlin.contains("SCREEN_ORIENTATION_SENSOR_LANDSCAPE"));
789        assert!(kotlin.contains("--android-status-bar-inset"));
790        assert!(service.contains("startForeground"));
791        assert!(manifest.contains("android:supportsPictureInPicture=\"true\""));
792        assert!(manifest.contains("foregroundServiceType=\"mediaPlayback\""));
793    }
794    #[test]
795    fn updater_trusts_nothing_before_the_signature_and_keeps_decisions_in_rust() {
796        let source = production_source(include_str!("updater.rs"));
797        let kotlin = include_str!(
798            "android/updater/src/main/kotlin/dev/dioxus/g3_native_plugins/updater/UpdaterPlugin.kt",
799        );
800        let swift = include_str!("ios/Sources/UpdaterPlugin.swift");
801        let gradle = include_str!("android/updater/build.gradle.kts");
802        // The manifest is verified before it is parsed, and its hashes carry
803        // that guarantee to every file.
804        let verified = source
805            .find("verify_signature(&config.pubkey")
806            .expect("the manifest signature is checked");
807        let parsed = source
808            .find("let manifest = parse_manifest(&bytes)?")
809            .unwrap();
810        assert!(verified < parsed);
811        assert!(source.contains("does not match the hash in the signed manifest"));
812        assert!(source.contains("minisign_verify::PublicKey"));
813        // Installed on trial, rolled back if never confirmed.
814        assert!(source.contains("pub fn notify_ready(&mut self)"));
815        assert!(source.contains("state.trial && state.trial_launches >= 1"));
816        // Downloads happen off the Dioxus thread.
817        assert!(source.contains("std::thread::Builder::new()"));
818        // The native sides only move bytes: no hashing or verification there.
819        assert!(!kotlin.contains("MessageDigest"));
820        assert!(!swift.contains("CryptoKit"));
821        assert!(kotlin.contains("noBackupFilesDir"));
822        assert!(swift.contains("isExcludedFromBackup = true"));
823        // A half-written file never sits where a finished one belongs.
824        assert!(kotlin.contains("partial.renameTo(destination)"));
825        assert!(!gradle.contains("implementation("));
826        assert!(!kotlin.contains(" error("));
827    }
828    #[test]
829    fn notifications_survive_reboots_without_claiming_exact_alarms() {
830        let source = production_source(include_str!("notifications.rs"));
831        let plugin = include_str!(
832            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationsPlugin.kt",
833        );
834        let store = include_str!(
835            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Store.kt",
836        );
837        let poster = include_str!(
838            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationPoster.kt",
839        );
840        let receivers = include_str!(
841            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Receivers.kt",
842        );
843        let manifest = include_str!("android/notifications/src/main/AndroidManifest.xml");
844        let gradle = include_str!("android/notifications/build.gradle.kts");
845        let swift = include_str!("ios/Sources/NotificationsPlugin.swift");
846        let relay = include_str!("ios/Sources/NotificationCenterRelay.swift");
847        assert!(
848            source.contains(
849                "pub fn take_event(&mut self) -> Result<Option<NotificationEvent>, String>"
850            )
851        );
852        assert!(source.contains("pub fn new() -> Self"));
853        // Android: alarms re-armed after a reboot, exact only when allowed,
854        // and the restricted permission left for the app to claim.
855        assert!(manifest.contains("android.permission.POST_NOTIFICATIONS"));
856        assert!(manifest.contains("android.intent.action.BOOT_COMPLETED"));
857        assert!(
858            !manifest.contains(
859                "uses-permission android:name=\"android.permission.SCHEDULE_EXACT_ALARM\""
860            )
861        );
862        assert!(manifest.contains("android:launchMode=\"singleTask\""));
863        assert!(store.contains("canScheduleExactAlarms()"));
864        assert!(receivers.contains("class BootReceiver"));
865        // Taps come back through both launch paths, like deep links.
866        assert!(plugin.contains("addOnNewIntentListener"));
867        assert!(plugin.contains("launchIntentConsumed = true"));
868        // PendingIntents differing only in extras collapse into one.
869        assert!(poster.contains("requestCode(notification.getInt(\"id\"), action)"));
870        // optString turns JSON null into the text "null".
871        assert!(poster.contains("stringOrNull(\"body\")"));
872        assert!(!gradle.contains("implementation("));
873        for kotlin in [plugin, store, poster, receivers] {
874            assert!(!kotlin.contains(" error("));
875        }
876        // iOS: one delegate for local and push, never displacing the host's.
877        assert!(relay.contains("UNPushNotificationTrigger"));
878        assert!(relay.contains("leaving it alone"));
879        assert!(swift.contains("UNTextInputNotificationAction"));
880        assert!(swift.contains("NotificationCenterRelay.install()"));
881    }
882    #[test]
883    fn push_keeps_firebase_out_of_local_only_apps() {
884        let source = production_source(include_str!("push_notifications.rs"));
885        let manifest = include_str!("../Cargo.toml");
886        let kotlin = include_str!(
887            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushNotificationsPlugin.kt",
888        );
889        let service = include_str!(
890            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushMessagingService.kt",
891        );
892        let android_manifest =
893            include_str!("android/push_notifications/src/main/AndroidManifest.xml");
894        let gradle = include_str!("android/push_notifications/build.gradle.kts");
895        let swift = include_str!("ios/Sources/PushNotificationsPlugin.swift");
896        assert!(manifest.contains("push-notifications = [\"notifications\"]"));
897        assert!(gradle.contains("com.google.firebase:firebase-messaging"));
898        assert!(source.contains("pub fn register(&mut self, firebase: Option<&FirebaseOptions>)"));
899        // A generated Gradle project cannot run the google-services plugin,
900        // so Firebase is initialized from values passed at run time.
901        assert!(kotlin.contains("FirebaseApp.initializeApp(context, options)"));
902        assert!(android_manifest.contains("com.google.firebase.MESSAGING_EVENT"));
903        assert!(service.contains("override fun onNewToken"));
904        // iOS: APNs answers the app delegate, which Dioxus's does not
905        // implement, so the hooks are added at runtime.
906        assert!(swift.contains("class_addMethod"));
907        assert!(swift.contains("didRegisterForRemoteNotificationsWithDeviceToken"));
908        assert!(swift.contains("registerForRemoteNotifications()"));
909    }
910    #[test]
911    fn plugin_wrapper_constructors_stay_crate_private_and_lazy() {
912        for (source, plugin_type, handle_type) in [
913            (
914                production_source(include_str!("auth.rs")),
915                "AuthPlugin",
916                "AuthHandle",
917            ),
918            (
919                production_source(include_str!("clipboard.rs")),
920                "ClipboardPlugin",
921                "ClipboardHandle",
922            ),
923            (
924                production_source(include_str!("external_url.rs")),
925                "ExternalUrlPlugin",
926                "ExternalUrlHandle",
927            ),
928        ] {
929            assert!(source.contains("pub(crate) fn new() -> Self"));
930            assert!(!source.contains("pub fn new() -> Self"));
931            assert!(source.contains(&format!("plugin: Option<{handle_type}>")));
932            assert!(source.contains("Self { plugin: None }"));
933            assert!(source.contains("self.plugin = Some("));
934            assert!(source.contains(&format!("{plugin_type}::new()")));
935            assert!(!source.contains(&format!("plugin: Result<{plugin_type}, String>")));
936        }
937    }
938}