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, and receiving the URL a deep link
4//! opened the app with - plus helpers for the deep-link metadata files iOS
5//! and Android expect a server to host.
6//!
7//! Every plugin sits behind a feature flag, so an app compiles in only what
8//! it uses. Platform coverage is not uniform; see the support matrix in the
9//! README. Where a plugin has no implementation for the current target it
10//! compiles to an inert no-op rather than failing to build, which keeps the
11//! same call sites working on web, desktop, and mobile.
12#![allow(non_snake_case)]
13#![warn(missing_docs)]
14#[cfg(all(
15    target_os = "android",
16    any(
17        feature = "auth",
18        feature = "camera-microphone",
19        feature = "clipboard",
20        feature = "deep-links",
21        feature = "external-url",
22        feature = "geolocation",
23        feature = "in-app-purchases",
24        feature = "storage"
25    )
26))]
27mod android_bridge;
28/// Both halves of deep linking: builders for the `apple-app-site-association`
29/// and `assetlinks.json` files that make universal links and App Links resolve
30/// to the app, and — behind the `deep-links` feature — the plugin that receives
31/// the URL once one does.
32#[cfg_attr(all(feature = "deep-links", target_os = "ios"), allow(missing_docs))]
33pub mod deep_links;
34/// The permission states plugins here report, in one place so an app can treat
35/// a refusal the same way whatever was refused.
36pub mod permissions;
37#[cfg(all(
38    feature = "deep-links",
39    any(
40        target_arch = "wasm32",
41        target_os = "android",
42        target_os = "ios",
43        target_os = "macos"
44    )
45))]
46#[allow(unused_imports)]
47pub use deep_links::DeepLinks;
48#[allow(unused_imports)]
49pub use permissions::PermissionState;
50cfg_if::cfg_if! {
51    if #[cfg(feature = "clipboard")] { mod clipboard;
52    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
53    #[allow(unused_imports)] pub use clipboard::Clipboard; }
54}
55cfg_if::cfg_if! {
56    if #[cfg(feature = "auth")] { mod auth;
57    #[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
58    #[allow(unused_imports)] pub use auth::Auth; }
59}
60cfg_if::cfg_if! {
61    if #[cfg(feature = "back-button")] { mod back_button;
62    #[allow(unused_imports)] pub use back_button::NATIVE_BACK_EVENT;
63    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
64    #[allow(unused_imports)] pub use back_button::BackButton; }
65}
66cfg_if::cfg_if! {
67    if #[cfg(feature = "camera-microphone")] { mod camera_microphone;
68    #[allow(unused_imports)] pub use camera_microphone::CapturePermissions;
69    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
70    #[allow(unused_imports)] pub use camera_microphone::CameraMicrophone; }
71}
72cfg_if::cfg_if! {
73    if #[cfg(feature = "external-url")] { mod external_url;
74    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
75    #[allow(unused_imports)] pub use external_url::ExternalUrl; }
76}
77cfg_if::cfg_if! {
78    if #[cfg(feature = "geolocation")] { mod geolocation;
79    #[allow(unused_imports)] pub use geolocation::{Coordinates, LocationState, PermissionStatus, Position, PositionOptions};
80    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
81    #[allow(unused_imports)] pub use geolocation::Geolocation; }
82}
83cfg_if::cfg_if! {
84    if #[cfg(feature = "in-app-purchases")] { mod in_app_purchases;
85    #[allow(unused_imports)] pub use in_app_purchases::{Entitlement, Product, ProductKind, PurchaseState, SubscriptionOffer, SubscriptionPeriod};
86    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
87    #[allow(unused_imports)] pub use in_app_purchases::InAppPurchases; }
88}
89cfg_if::cfg_if! {
90    if #[cfg(feature = "media")] { mod media;
91    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
92    #[allow(unused_imports)] pub use media::Media;
93    }
94}
95cfg_if::cfg_if! {
96    if #[cfg(feature = "storage")] { mod storage;
97    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
98    #[allow(unused_imports)] pub use storage::KeyValueStore; }
99}
100use dioxus::prelude::*;
101#[cfg(all(
102    any(
103        feature = "auth",
104        feature = "back-button",
105        feature = "camera-microphone",
106        feature = "clipboard",
107        feature = "deep-links",
108        feature = "external-url",
109        feature = "geolocation",
110        feature = "in-app-purchases",
111        feature = "media",
112        feature = "storage"
113    ),
114    any(
115        target_arch = "wasm32",
116        target_os = "android",
117        target_os = "ios",
118        target_os = "macos"
119    )
120))]
121use dioxus_signals::Signal;
122#[cfg(any(
123    target_arch = "wasm32",
124    target_os = "android",
125    target_os = "ios",
126    target_os = "macos"
127))]
128#[derive(Clone, Copy)]
129/// Reactive handles for every enabled native plugin.
130///
131/// Construct this directly with [`NativePlugins::new`] or install it in the
132/// Dioxus context with [`NativePluginsProvider`].
133pub struct NativePlugins {
134    #[cfg(all(
135        feature = "auth",
136        any(target_os = "android", target_os = "ios", target_os = "macos")
137    ))]
138    /// Native Apple or Google authentication, depending on the target.
139    pub auth: Signal<Auth>,
140    /// Available on every target: the non-Android builds are inert, so callers
141    /// need no cfg of their own.
142    #[cfg(feature = "back-button")]
143    pub back_button: Signal<BackButton>,
144    /// Available on every target: the web and macOS builds are inert, so
145    /// callers need no cfg of their own.
146    #[cfg(feature = "camera-microphone")]
147    pub camera_microphone: Signal<CameraMicrophone>,
148    #[cfg(feature = "clipboard")]
149    /// Clipboard copying and the platform share sheet.
150    pub clipboard: Signal<Clipboard>,
151    /// Available on every target: the web and macOS builds are inert, so
152    /// callers need no cfg of their own.
153    #[cfg(feature = "deep-links")]
154    pub deep_links: Signal<DeepLinks>,
155    #[cfg(all(
156        feature = "external-url",
157        any(
158            target_arch = "wasm32",
159            target_os = "android",
160            target_os = "ios",
161            target_os = "macos"
162        )
163    ))]
164    /// Opens a URL outside the app on supported targets.
165    pub external_url: Signal<ExternalUrl>,
166    /// Available on every target: the web and macOS builds are inert, so
167    /// callers need no cfg of their own.
168    #[cfg(feature = "geolocation")]
169    pub geolocation: Signal<Geolocation>,
170    /// Available on every target: the web and macOS builds are inert, so
171    /// callers need no cfg of their own.
172    #[cfg(feature = "in-app-purchases")]
173    pub in_app_purchases: Signal<InAppPurchases>,
174    #[cfg(feature = "media")]
175    /// Background media playback, orientation, and picture-in-picture support.
176    pub media: Signal<Media>,
177    /// Available on every target, but unlike the others the macOS build reports
178    /// an error rather than doing nothing: a store that silently discards is
179    /// worse than one that says it cannot help.
180    #[cfg(feature = "storage")]
181    pub storage: Signal<KeyValueStore>,
182}
183#[cfg(any(
184    target_arch = "wasm32",
185    target_os = "android",
186    target_os = "ios",
187    target_os = "macos"
188))]
189impl NativePlugins {
190    /// Creates reactive handles for every plugin enabled for this target.
191    pub fn new() -> Self {
192        Self {
193            #[cfg(all(
194                feature = "auth",
195                any(target_os = "android", target_os = "ios", target_os = "macos")
196            ))]
197            auth: Signal::new(Auth::new()),
198            #[cfg(feature = "back-button")]
199            back_button: Signal::new(BackButton::new()),
200            #[cfg(feature = "camera-microphone")]
201            camera_microphone: Signal::new(CameraMicrophone::new()),
202            #[cfg(feature = "clipboard")]
203            clipboard: Signal::new(Clipboard::new()),
204            #[cfg(feature = "deep-links")]
205            deep_links: Signal::new(DeepLinks::new()),
206            #[cfg(all(
207                feature = "external-url",
208                any(
209                    target_arch = "wasm32",
210                    target_os = "android",
211                    target_os = "ios",
212                    target_os = "macos"
213                )
214            ))]
215            external_url: Signal::new(ExternalUrl::new()),
216            #[cfg(feature = "geolocation")]
217            geolocation: Signal::new(Geolocation::new()),
218            #[cfg(feature = "in-app-purchases")]
219            in_app_purchases: Signal::new(InAppPurchases::new()),
220            #[cfg(feature = "media")]
221            media: Signal::new(Media::new()),
222            #[cfg(feature = "storage")]
223            storage: Signal::new(KeyValueStore::new()),
224        }
225    }
226}
227#[cfg(any(
228    target_arch = "wasm32",
229    target_os = "android",
230    target_os = "ios",
231    target_os = "macos"
232))]
233impl Default for NativePlugins {
234    fn default() -> Self {
235        Self::new()
236    }
237}
238#[component]
239pub fn NativePluginsProvider(children: Element) -> Element {
240    #[cfg(any(
241        target_arch = "wasm32",
242        target_os = "android",
243        target_os = "ios",
244        target_os = "macos"
245    ))]
246    use_context_provider(NativePlugins::default);
247    rsx! {
248        {children}
249    }
250}
251#[cfg(test)]
252mod tests {
253    fn production_source(source: &str) -> &str {
254        source
255            .split("#[cfg(test)]")
256            .next()
257            .expect("source should split before tests")
258    }
259    #[test]
260    fn back_button_interception_is_opt_in() {
261        let source = production_source(include_str!("back_button.rs"));
262        assert!(source.contains("intercepting: false"));
263        assert!(source.contains("pub fn set_intercepting"));
264        let kotlin = include_str!(
265            "android/back_button/src/main/kotlin/dev/dioxus/g3_native_plugins/back_button/BackButtonPlugin.kt",
266        );
267        assert!(kotlin.contains("g3nativeback"));
268        assert!(kotlin.contains("cancelable: true"));
269        assert!(kotlin.contains("evaluateJavascript(BACK_EVENT_SCRIPT"));
270        assert!(kotlin.contains("OnBackPressedCallback(false)"));
271        assert!(kotlin.contains("fun fallThroughFromRust()"));
272        assert!(kotlin.contains("current?.isEnabled = false"));
273        assert!(source.contains("pub fn fall_through"));
274        assert!(source.contains("pub const NATIVE_BACK_EVENT"));
275    }
276    #[test]
277    fn ios_back_button_raises_the_same_event_from_an_edge_swipe() {
278        let source = production_source(include_str!("back_button.rs"));
279        let swift = include_str!("ios/Sources/BackButtonPlugin.swift");
280        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
281        assert!(source.contains(
282            "pub fn setInterceptingFromRust(this: &BackButtonPlugin, intercepting: bool);",
283        ),);
284        assert!(source.contains("pub fn fallThroughFromRust(this: &BackButtonPlugin);"));
285        assert!(swift.contains("UIScreenEdgePanGestureRecognizer"));
286        assert!(swift.contains("created.edges = .left"));
287        // The same event contract as Android, so one web listener serves both.
288        assert!(swift.contains("g3nativeback"));
289        assert!(swift.contains("cancelable: true"));
290        assert!(swift.contains("webView.allowsBackForwardNavigationGestures = false"));
291        assert!(swift.contains("panGestureRecognizer.require(toFail: created)"));
292        assert!(swift.contains("created.isEnabled = false"));
293    }
294    #[test]
295    fn deep_links_are_collected_from_both_launch_paths() {
296        let source = production_source(include_str!("deep_links.rs"));
297        let kotlin = include_str!(
298            "android/deep_links/src/main/kotlin/dev/dioxus/g3_native_plugins/deep_links/DeepLinksPlugin.kt",
299        );
300        let swift = include_str!("ios/Sources/DeepLinksPlugin.swift");
301        assert!(
302            source.contains("pub fn takeLinkFromRust(this: &DeepLinksPlugin) -> Option<String>;"),
303        );
304        assert!(source.contains("pub fn take_link(&mut self) -> Result<Option<String>, String>"),);
305        // Public so an app can prepare ahead of the provider, which is what
306        // makes an iOS cold-start link catchable at all.
307        assert!(source.contains("pub fn new() -> Self"));
308        // Android: cold start from the launch Intent, read once; warm links
309        // through the listener, since onNewIntent cannot be overridden here.
310        assert!(kotlin.contains("Intent.ACTION_VIEW"));
311        assert!(kotlin.contains("enqueue(activity.intent)"));
312        assert!(kotlin.contains("launchIntentConsumed = true"));
313        assert!(kotlin.contains("addOnNewIntentListener"));
314        // Static, so a link is not stranded on a discarded plugin instance.
315        assert!(kotlin.contains("companion object"));
316        // iOS: cold start from the launch options, warm links from delegate
317        // methods added to the host's delegate class at runtime.
318        assert!(swift.contains("didFinishLaunchingNotification"));
319        assert!(swift.contains("LaunchOptionsKey.userActivityDictionary"));
320        assert!(swift.contains("class_addMethod"));
321        assert!(swift.contains("application(_:continue:restorationHandler:)"));
322        assert!(swift.contains("application(_:open:options:)"));
323        // A cold-start link is reported through both paths; only one survives.
324        assert!(swift.contains("duplicateWindow"));
325    }
326    #[test]
327    fn android_plugins_resolve_classes_through_the_app_loader() {
328        // Learned the hard way on a device: JNI's FindClass resolves against
329        // the calling thread's loader, and a thread attached from native code
330        // gets the system loader, which has never heard of the app's classes.
331        // The macro's generated bindings use FindClass, so every Android call
332        // here goes through the bridge instead, which asks the Activity.
333        let bridge = include_str!("android_bridge.rs");
334        assert!(bridge.contains("getClassLoader"));
335        assert!(bridge.contains("loadClass"));
336        for source in [
337            include_str!("auth.rs"),
338            include_str!("camera_microphone.rs"),
339            include_str!("clipboard.rs"),
340            include_str!("deep_links.rs"),
341            include_str!("external_url.rs"),
342            include_str!("geolocation.rs"),
343            include_str!("in_app_purchases.rs"),
344            include_str!("storage.rs"),
345        ] {
346            let production = production_source(source);
347            let android = production
348                .split("unsafe extern \"Kotlin\" {")
349                .nth(1)
350                .expect("each plugin declares a Kotlin block")
351                .split('}')
352                .next()
353                .expect("the Kotlin block should be closed");
354            // Only the type, so `dx` still builds the module. A function
355            // declared here would generate a FindClass binding and crash the
356            // moment a Dioxus effect called it.
357            assert!(
358                !android.contains("pub fn "),
359                "a Kotlin block still declares functions: {android}",
360            );
361            assert!(production.contains("crate::android_bridge::AndroidPlugin"));
362        }
363    }
364    #[test]
365    fn storage_encrypts_values_and_refuses_to_pretend_on_macos() {
366        let source = production_source(include_str!("storage.rs"));
367        let kotlin = include_str!(
368            "android/storage/src/main/kotlin/dev/dioxus/g3_native_plugins/storage/StoragePlugin.kt",
369        );
370        let swift = include_str!("ios/Sources/StoragePlugin.swift");
371        let gradle = include_str!("android/storage/build.gradle.kts");
372        assert!(source.contains("pub fn get(&mut self, key: &str)"));
373        assert!(source.contains("pub fn set(&mut self, key: &str, value: &str)"));
374        assert!(source.contains("pub fn keys(&mut self)"));
375        // A store that silently discards is worse than one that says it cannot
376        // help, so this plugin alone does not compile to an inert no-op.
377        assert!(source.contains("Secure storage is not implemented on macOS"));
378        // Android: Keystore-held AES-GCM, and no Tink dependency behind an
379        // unmaintained library to get it.
380        assert!(kotlin.contains("AndroidKeyStore"));
381        assert!(kotlin.contains("AES/GCM/NoPadding"));
382        // No dependency at all, so nothing to argue about. The comment in that
383        // file names security-crypto to explain why, hence matching on the
384        // declaration form rather than the word.
385        assert!(!gradle.contains("implementation("));
386        // The cipher picks the nonce: a reused GCM nonce leaks the plaintext.
387        assert!(kotlin.contains("val nonce = cipher.iv"));
388        // kotlin.error() throws, so a helper of that name would be a live trap.
389        assert!(!kotlin.contains(" error("));
390        assert!(kotlin.contains("errorJson("));
391        // iOS: keychain, readable in the background after one unlock.
392        assert!(swift.contains("kSecClassGenericPassword"));
393        assert!(swift.contains("kSecAttrAccessibleAfterFirstUnlock"));
394        // The keychain has no upsert; update first, then add.
395        assert!(swift.contains("SecItemUpdate"));
396        assert!(swift.contains("SecItemAdd"));
397        assert!(swift.contains("errSecItemNotFound"));
398    }
399    #[test]
400    fn camera_microphone_leaves_the_webview_permission_bridge_to_wry() {
401        let source = production_source(include_str!("camera_microphone.rs"));
402        let kotlin = include_str!(
403            "android/camera_microphone/src/main/kotlin/dev/dioxus/g3_native_plugins/camera_microphone/CameraMicrophonePlugin.kt",
404        );
405        let swift = include_str!("ios/Sources/CameraMicrophonePlugin.swift");
406        assert!(source.contains("pub fn check_permissions"));
407        assert!(source.contains("pub fn open_settings"));
408        assert!(source.contains("pub struct CapturePermissions"));
409        // wry already answers the WebView's own permission callbacks. Taking
410        // either delegate over would break its file chooser and JS dialogs, so
411        // neither native side may install one. The prose above each plugin says
412        // as much, so these look for the code, not the words.
413        assert!(!kotlin.contains("setWebChromeClient"));
414        assert!(!kotlin.contains("override fun onPermissionRequest"));
415        assert!(!swift.contains("uiDelegate ="));
416        assert!(!swift.contains("func webView("));
417        // What is left is the part the page cannot reach.
418        assert!(kotlin.contains("ACTION_APPLICATION_DETAILS_SETTINGS"));
419        assert!(kotlin.contains("shouldShowRequestPermissionRationale"));
420        assert!(swift.contains("openSettingsURLString"));
421        assert!(swift.contains("AVCaptureDevice.authorizationStatus"));
422        assert!(swift.contains("AVCaptureDevice.requestAccess"));
423        // A .playback session has no input, so a shared session needs moving.
424        assert!(swift.contains("playAndRecord"));
425        assert!(swift.contains("defaultToSpeaker"));
426    }
427    #[test]
428    fn permission_state_is_shared_rather_than_duplicated_per_plugin() {
429        // Both plugins glob-export at the crate root, so a second definition
430        // would collide there rather than merely repeating itself.
431        let permissions = include_str!("permissions.rs");
432        let geolocation = production_source(include_str!("geolocation.rs"));
433        let capture = production_source(include_str!("camera_microphone.rs"));
434        assert!(permissions.contains("pub enum PermissionState"));
435        assert!(!geolocation.contains("pub enum PermissionState"));
436        assert!(!capture.contains("pub enum PermissionState"));
437        assert!(geolocation.contains("use crate::permissions::PermissionState;"));
438        assert!(capture.contains("use crate::permissions::PermissionState;"));
439    }
440    #[test]
441    fn geolocation_starts_and_polls_rather_than_blocking() {
442        let source = production_source(include_str!("geolocation.rs"));
443        let kotlin = include_str!(
444            "android/geolocation/src/main/kotlin/dev/dioxus/g3_native_plugins/geolocation/GeolocationPlugin.kt",
445        );
446        let swift = include_str!("ios/Sources/GeolocationPlugin.swift");
447        let gradle = include_str!("android/geolocation/build.gradle.kts");
448        assert!(source.contains("pub fn start_position_request"));
449        assert!(
450            source.contains("pub fn poll_position(&mut self) -> Result<Option<Position>, String>"),
451        );
452        assert!(source.contains("pub fn check_permissions"));
453        assert!(source.contains("pub struct Position"));
454        assert!(source.contains("pub struct Coordinates"));
455        // The reference example blocks the caller on both platforms; this one
456        // must not, because the call arrives on a Dioxus effect thread.
457        assert!(!kotlin.contains("CountDownLatch"));
458        assert!(!swift.contains("DispatchSemaphore"));
459        assert!(!swift.contains("RunLoop.current.run"));
460        // A library does not get to force Play Services on its consumers, so
461        // no dependency may name the coordinate the fused provider ships under.
462        assert!(!gradle.contains("com.google.android.gms"));
463        assert!(!kotlin.contains("com.google.android.gms"));
464        assert!(kotlin.contains("LocationManager"));
465        assert!(kotlin.contains("requestLocationUpdates"));
466        assert!(kotlin.contains("prompt-with-rationale"));
467        assert!(swift.contains("CLLocationManagerDelegate"));
468        assert!(swift.contains("manager.requestLocation()"));
469        assert!(swift.contains("locationManagerDidChangeAuthorization"));
470        // Negative CoreLocation accuracies mean invalid, not precise.
471        assert!(swift.contains("location.verticalAccuracy >= 0"));
472    }
473    #[test]
474    fn in_app_purchases_start_and_poll_on_both_stores() {
475        let source = production_source(include_str!("in_app_purchases.rs"));
476        let kotlin = include_str!(
477            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/InAppPurchasesPlugin.kt",
478        );
479        let catalogue = include_str!(
480            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/Catalogue.kt",
481        );
482        let swift = include_str!("ios/Sources/InAppPurchasesPlugin.swift");
483        let store = include_str!("ios/Sources/StoreCatalogue.swift");
484        let gradle = include_str!("android/in_app_purchases/build.gradle.kts");
485        assert!(source.contains("pub fn start_purchase"));
486        assert!(source.contains("pub fn poll_entitlements"));
487        assert!(source.contains("pub fn finish(&mut self, transaction_id: &str, consume: bool)"),);
488        assert!(source.contains("Subscription"));
489        assert!(source.contains("pub struct SubscriptionOffer"));
490        assert!(source.contains("pub will_auto_renew: bool"));
491        // Play billing has no substitute, so it is a real dependency rather
492        // than compileOnly like the androidx ones elsewhere.
493        assert!(gradle.contains("com.android.billingclient:billing"));
494        assert!(gradle.contains("implementation("));
495        // A purchase left unacknowledged for three days is refunded by Play.
496        assert!(kotlin.contains("acknowledgePurchase"));
497        assert!(kotlin.contains("consumeAsync"));
498        assert!(kotlin.contains("needsFinishing"));
499        // Subscriptions cannot be bought without naming an offer token.
500        assert!(kotlin.contains("setOfferToken"));
501        assert!(kotlin.contains("queryPurchasesAsync"));
502        assert!(catalogue.contains("subscriptionOfferDetails"));
503        // StoreKit 2 is async Swift, which cannot cross the FFI boundary.
504        assert!(swift.contains("Transaction.updates"));
505        assert!(swift.contains("Transaction.currentEntitlements"));
506        assert!(swift.contains("Transaction.unfinished"));
507        assert!(swift.contains("AppStore.sync()"));
508        assert!(swift.contains("jwsRepresentation"));
509        assert!(swift.contains("renewal.willAutoRenew"));
510        assert!(store.contains("nonRenewable"));
511    }
512    #[test]
513    fn ios_media_plugin_owns_background_audio_and_lock_screen_controls() {
514        let source = production_source(include_str!("media.rs"));
515        let swift = include_str!("ios/Sources/MediaPlugin.swift");
516        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
517        assert!(source.contains(
518            "pub fn setPlaybackActiveFromRust(this: &MediaPlugin, playbackJson: String);",
519        ),);
520        assert!(swift.contains("AVAudioSession.sharedInstance().setCategory(.playback"));
521        assert!(swift.contains("MPNowPlayingInfoCenter"));
522        assert!(swift.contains("MPRemoteCommandCenter.shared()"));
523        assert!(swift.contains("beginReceivingRemoteControlEvents"));
524        assert!(swift.contains("notifyOthersOnDeactivation"));
525        assert!(swift.contains("webkitSetPresentationMode"));
526        assert!(swift.contains("requestGeometryUpdate"));
527        // Same duplicate-event guard as Android, for the same audible reason.
528        assert!(swift.contains("if !wasActive || titleChanged"));
529        assert!(swift.contains("__tawnyPlaybackIntent"));
530    }
531    #[test]
532    fn native_plugins_provider_owns_plugin_construction() {
533        let source = production_source(include_str!("lib.rs"));
534        let provider_start = source
535            .find("pub fn NativePluginsProvider(children: Element) -> Element")
536            .expect("provider component should be exported");
537        let provider_prefix = &source[..provider_start];
538        assert!(source.contains("pub struct NativePlugins"));
539        assert!(source.contains("pub fn NativePluginsProvider(children: Element) -> Element"),);
540        assert!(
541            !provider_prefix
542                .trim_end()
543                .ends_with("target_os = \"macos\"\n))]\n#[component]"),
544        );
545        assert!(source.contains("use_context_provider(NativePlugins::default)"));
546        assert!(source.contains("{children}"));
547        assert!(source.contains("pub auth: Signal<Auth>"));
548        assert!(source.contains("pub camera_microphone: Signal<CameraMicrophone>"));
549        assert!(source.contains("pub clipboard: Signal<Clipboard>"));
550        assert!(source.contains("pub deep_links: Signal<DeepLinks>"));
551        assert!(source.contains("pub external_url: Signal<ExternalUrl>"));
552        assert!(source.contains("pub geolocation: Signal<Geolocation>"));
553        assert!(source.contains("pub in_app_purchases: Signal<InAppPurchases>"));
554        assert!(source.contains("pub media: Signal<Media>"));
555        assert!(source.contains("pub storage: Signal<KeyValueStore>"));
556        assert!(source.contains("auth: Signal::new(Auth::new())"));
557        assert!(source.contains("camera_microphone: Signal::new(CameraMicrophone::new())"));
558        assert!(source.contains("clipboard: Signal::new(Clipboard::new())"));
559        assert!(source.contains("deep_links: Signal::new(DeepLinks::new())"));
560        assert!(source.contains("external_url: Signal::new(ExternalUrl::new())"));
561        assert!(source.contains("geolocation: Signal::new(Geolocation::new())"));
562        assert!(source.contains("in_app_purchases: Signal::new(InAppPurchases::new())"));
563        assert!(source.contains("media: Signal::new(Media::new())"));
564        assert!(source.contains("storage: Signal::new(KeyValueStore::new())"));
565        assert!(source.contains("impl Default for NativePlugins"));
566        assert!(source.contains("Self::new()"));
567    }
568    #[test]
569    fn ios_clipboard_plugin_supports_copy_and_scene_safe_share() {
570        let swift = include_str!("ios/Sources/ClipboardPlugin.swift");
571        let rust = include_str!("clipboard.rs");
572        assert!(rust.contains("pub fn copy_to_clipboard(&mut self, text: String)"));
573        assert!(rust.contains(
574            "pub fn copyToClipboardFromRust(this: &ClipboardPlugin, text: String) -> String;",
575        ),);
576        assert!(swift.contains("public func copyToClipboardFromRust(_ text: String) -> String",),);
577        assert!(swift.contains("UIPasteboard.general.string = text"));
578        assert!(swift.contains("NSLog(\"[ClipboardPlugin]"));
579        assert!(swift.contains("connectedScenes"));
580        assert!(swift.contains("popover.sourceView = vc.view"));
581        assert!(!swift.contains("keyWindow"));
582    }
583    #[test]
584    fn ios_plugins_share_one_swift_package_for_current_dx() {
585        let manifest = include_str!("ios/Package.swift");
586        let auth = include_str!("auth.rs");
587        let swift_auth = include_str!("ios/Sources/AuthPlugin.swift");
588        let clipboard = include_str!("clipboard.rs");
589        let external_url = include_str!("external_url.rs");
590        assert!(manifest.contains("name: \"DioxusNativePlugins\""));
591        assert!(manifest.contains(".library(name: \"AuthPlugin\""));
592        assert!(manifest.contains(".library(name: \"BackButtonPlugin\""));
593        assert!(manifest.contains(".library(name: \"CameraMicrophonePlugin\""));
594        assert!(manifest.contains(".library(name: \"ClipboardPlugin\""));
595        assert!(manifest.contains(".library(name: \"DeepLinksPlugin\""));
596        assert!(manifest.contains(".library(name: \"ExternalUrlPlugin\""));
597        assert!(manifest.contains(".library(name: \"GeolocationPlugin\""));
598        assert!(manifest.contains(".library(name: \"InAppPurchasesPlugin\""));
599        assert!(manifest.contains(".linkedFramework(\"StoreKit\")"));
600        assert!(manifest.contains(".linkedFramework(\"CoreLocation\")"));
601        assert!(manifest.contains(".library(name: \"MediaPlugin\""));
602        assert!(manifest.contains(".library(name: \"StoragePlugin\""));
603        assert!(manifest.contains(".linkedFramework(\"Security\")"));
604        assert!(manifest.contains(".linkedFramework(\"AuthenticationServices\")"));
605        assert!(manifest.contains(".linkedFramework(\"AVFoundation\")"));
606        assert!(manifest.contains(".linkedFramework(\"MediaPlayer\""));
607        assert!(manifest.contains(".linkedFramework(\"WebKit\")"));
608        assert!(auth.contains("#[manganis::ffi(\"src/ios\")]"));
609        assert!(
610            auth.contains("pub fn startAppleAuthFromRust(this: &AuthPlugin) -> Option<String>;",),
611        );
612        assert!(auth.contains("pub fn getAuthState(this: &AuthPlugin) -> Option<String>;"),);
613        assert!(!auth.contains("signOutFromRust"));
614        assert!(swift_auth.contains("ASAuthorizationAppleIDProvider"));
615        assert!(swift_auth.contains("public func getAuthState() -> String?"));
616        assert!(swift_auth.contains("identity_token"));
617        assert!(clipboard.contains("#[manganis::ffi(\"src/ios\")]"));
618        assert!(external_url.contains("#[manganis::ffi(\"src/ios\")]"));
619    }
620    #[test]
621    fn android_auth_plugin_exposes_google_sign_in() {
622        let auth = include_str!("auth.rs");
623        let kotlin_auth = include_str!(
624            "android/auth/src/main/kotlin/dev/dioxus/g3_native_plugins/auth/AuthPlugin.kt",
625        );
626        assert!(auth.contains("#[manganis::ffi(\"src/android/auth\")]"));
627        assert!(auth.contains("unsafe extern \"Kotlin\""));
628        let android = auth
629            .split("unsafe extern \"Kotlin\" {")
630            .nth(1)
631            .expect("auth declares its Kotlin module")
632            .split('}')
633            .next()
634            .expect("the Kotlin block should be closed");
635        assert!(!android.contains("pub fn "));
636        assert!(auth.contains("type AuthHandle = crate::android_bridge::AndroidPlugin"));
637        // The client id is the caller's, not the crate's. It names one Google
638        // Cloud project and is checked against an Android client registered
639        // there for the app's package and certificate, so a library carrying
640        // its own could only ever authenticate the app it shipped with.
641        assert!(auth.contains(
642            "pub fn start_google_auth(&mut self, server_client_id: &str) -> Result<(), String>",
643        ),);
644        assert!(
645            auth.contains("pub fn poll_auth_result(&mut self) -> Result<Option<String>, String>",)
646        );
647        assert!(auth.contains("pub fn is_auth_awaiting(&mut self) -> bool"));
648        assert!(kotlin_auth.contains("fun startGoogleAuthFromRust(serverClientId: String)"));
649        assert!(kotlin_auth.contains("fun getPendingResult(): String?"));
650        assert!(kotlin_auth.contains("fun getAuthState(): String"));
651        assert!(kotlin_auth.contains("setServerClientId(serverClientId)"));
652        assert!(!kotlin_auth.contains("apps.googleusercontent.com"));
653        assert!(!kotlin_auth.contains("CountDownLatch"));
654        assert!(!kotlin_auth.contains("TimeUnit"));
655        assert!(kotlin_auth.contains("GoogleIdTokenCredential.createFrom"));
656    }
657    #[test]
658    fn android_media_plugin_owns_mobile_playback_capabilities() {
659        let rust = include_str!("media.rs");
660        let kotlin = include_str!(
661            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/MediaPlugin.kt",
662        );
663        let service = include_str!(
664            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/PlaybackService.kt",
665        );
666        let manifest = include_str!("android/media/src/main/AndroidManifest.xml");
667        assert!(rust.contains("getClassLoader"));
668        assert!(rust.contains("enter_picture_in_picture"));
669        assert!(rust.contains("set_orientation"));
670        assert!(rust.contains("set_playback_active"));
671        assert!(kotlin.contains("enterPictureInPictureMode"));
672        assert!(kotlin.contains("setActions(pipActions())"));
673        assert!(kotlin.contains("COMMAND_REWIND"));
674        assert!(kotlin.contains("COMMAND_FORWARD"));
675        assert!(kotlin.contains("dataset.androidPip"));
676        assert!(kotlin.contains("tawnynativepictureinpicturechange"));
677        assert!(kotlin.contains("tawnynativeplaybackresume"));
678        assert!(kotlin.contains("Application.ActivityLifecycleCallbacks"));
679        assert!(kotlin.contains("if (!wasActive || titleChanged)"));
680        assert!(!kotlin.contains("setSourceRectHint"));
681        assert!(kotlin.contains("SCREEN_ORIENTATION_SENSOR_LANDSCAPE"));
682        assert!(kotlin.contains("--android-status-bar-inset"));
683        assert!(service.contains("startForeground"));
684        assert!(manifest.contains("android:supportsPictureInPicture=\"true\""));
685        assert!(manifest.contains("foregroundServiceType=\"mediaPlayback\""));
686    }
687    #[test]
688    fn plugin_wrapper_constructors_stay_crate_private_and_lazy() {
689        for (source, plugin_type, handle_type) in [
690            (
691                production_source(include_str!("auth.rs")),
692                "AuthPlugin",
693                "AuthHandle",
694            ),
695            (
696                production_source(include_str!("clipboard.rs")),
697                "ClipboardPlugin",
698                "ClipboardHandle",
699            ),
700            (
701                production_source(include_str!("external_url.rs")),
702                "ExternalUrlPlugin",
703                "ExternalUrlHandle",
704            ),
705        ] {
706            assert!(source.contains("pub(crate) fn new() -> Self"));
707            assert!(!source.contains("pub fn new() -> Self"));
708            assert!(source.contains(&format!("plugin: Option<{handle_type}>")));
709            assert!(source.contains("Self { plugin: None }"));
710            assert!(source.contains("self.plugin = Some("));
711            assert!(source.contains(&format!("{plugin_type}::new()")));
712            assert!(!source.contains(&format!("plugin: Result<{plugin_type}, String>")));
713        }
714    }
715}