cranpose-capabilities 0.9.20

Declare platform services, permissions and hardware for Cranpose apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#![doc = include_str!("../README.md")]

use std::{
    collections::BTreeSet,
    env,
    ffi::OsString,
    fmt::Write as _,
    fs,
    path::{Path, PathBuf},
};

/// Something an application uses that the device has to allow.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Service {
    /// The camera.
    Camera,
    /// Reading the photo library.
    PhotoLibrary,
    /// Writing to the photo library.
    PhotoLibraryAdd,
    /// The microphone.
    Microphone,
    /// Where the device is.
    Location,
    /// Notifications the person sees.
    Notifications,
    /// Work that carries on with the application off screen.
    Background,
    /// Media playback that carries on with the application off screen.
    Media,
    /// Purchases through the platform store.
    Billing,
    /// A window drawn above other applications.
    Overlay,
    /// The vibrator.
    Haptics,
    /// Handing a downloaded package to the system installer.
    Update,
    /// The network, and whether the device is on one.
    Network,
    /// The wearer's heart rate, from the device's own sensor.
    HeartRate,
    /// Recording that can start from the background, kept possible by a
    /// standby the application starts from its screen.
    MicrophoneStandby,
    /// Messages and streams to the same application on the paired phone or
    /// watch.
    Wearable,
}

impl Service {
    /// The name this service carries in the build's own files.
    pub const fn name(self) -> &'static str {
        match self {
            Service::Camera => "camera",
            Service::PhotoLibrary => "photo-library",
            Service::PhotoLibraryAdd => "photo-library-add",
            Service::Microphone => "microphone",
            Service::Location => "location",
            Service::Notifications => "notifications",
            Service::Background => "background",
            Service::Media => "media",
            Service::Billing => "billing",
            Service::Overlay => "overlay",
            Service::Haptics => "haptics",
            Service::Update => "update",
            Service::Network => "network",
            Service::HeartRate => "heart-rate",
            Service::MicrophoneStandby => "microphone-standby",
            Service::Wearable => "wearable",
        }
    }

    /// The Android permissions this service needs.
    ///
    /// Both photo library services are empty here: Android reads and writes
    /// photos through the system picker, which asks the person for one file
    /// and needs no permission from the application.
    pub const fn android_permissions(self) -> &'static [&'static str] {
        match self {
            Service::Camera => &["android.permission.CAMERA"],
            Service::PhotoLibrary => &[],
            Service::PhotoLibraryAdd => &[],
            Service::Microphone => &["android.permission.RECORD_AUDIO"],
            Service::Location => &["android.permission.ACCESS_COARSE_LOCATION"],
            Service::Notifications => &["android.permission.POST_NOTIFICATIONS"],
            Service::Background => &[
                "android.permission.FOREGROUND_SERVICE",
                "android.permission.FOREGROUND_SERVICE_DATA_SYNC",
            ],
            Service::Media => &[
                "android.permission.FOREGROUND_SERVICE",
                "android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK",
            ],
            Service::Billing => &["com.android.vending.BILLING"],
            Service::Overlay => &["android.permission.SYSTEM_ALERT_WINDOW"],
            Service::Haptics => &["android.permission.VIBRATE"],
            Service::Update => &["android.permission.REQUEST_INSTALL_PACKAGES"],
            Service::Network => &[
                "android.permission.INTERNET",
                "android.permission.ACCESS_NETWORK_STATE",
            ],
            // Android 16 split the body sensors into the health
            // permissions; older releases read the same sensor under
            // BODY_SENSORS, which `android_permissions_up_to` carries.
            Service::HeartRate => &["android.permission.health.READ_HEART_RATE"],
            Service::MicrophoneStandby => &[
                "android.permission.FOREGROUND_SERVICE",
                "android.permission.FOREGROUND_SERVICE_MICROPHONE",
                "android.permission.RECORD_AUDIO",
            ],
            // The Data Layer runs through Google Play services and asks for
            // nothing.
            Service::Wearable => &[],
        }
    }

    /// The Android permissions this service needs only up to an API level,
    /// with that level: what a platform release replaced, declared with
    /// `android:maxSdkVersion` so a newer device is never asked for it.
    pub const fn android_permissions_up_to(self) -> &'static [(&'static str, u32)] {
        match self {
            Service::HeartRate => &[("android.permission.BODY_SENSORS", 35)],
            _ => &[],
        }
    }

    /// The key an Apple platform reads the sentence from.
    pub const fn apple_key(self) -> Option<&'static str> {
        match self {
            Service::Camera => Some("NSCameraUsageDescription"),
            Service::PhotoLibrary => Some("NSPhotoLibraryUsageDescription"),
            Service::PhotoLibraryAdd => Some("NSPhotoLibraryAddUsageDescription"),
            Service::Microphone => Some("NSMicrophoneUsageDescription"),
            Service::Location => Some("NSLocationWhenInUseUsageDescription"),
            Service::HeartRate => Some("NSHealthShareUsageDescription"),
            _ => None,
        }
    }

    /// Whether this service takes a sentence to show the person.
    pub const fn takes_reason(self) -> bool {
        self.apple_key().is_some()
    }
}

/// One service an application uses, with the sentence it shows if it needs one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Use {
    service: Service,
    reason: Option<&'static str>,
}

impl Use {
    /// The camera, with what the person is told before it opens.
    pub const fn camera(reason: &'static str) -> Self {
        Self {
            service: Service::Camera,
            reason: Some(reason),
        }
    }

    /// Reading the photo library, with what the person is told.
    pub const fn photo_library(reason: &'static str) -> Self {
        Self {
            service: Service::PhotoLibrary,
            reason: Some(reason),
        }
    }

    /// Writing to the photo library, with what the person is told.
    pub const fn photo_library_add(reason: &'static str) -> Self {
        Self {
            service: Service::PhotoLibraryAdd,
            reason: Some(reason),
        }
    }

    /// The microphone, with what the person is told.
    pub const fn microphone(reason: &'static str) -> Self {
        Self {
            service: Service::Microphone,
            reason: Some(reason),
        }
    }

    /// Where the device is, with what the person is told.
    pub const fn location(reason: &'static str) -> Self {
        Self {
            service: Service::Location,
            reason: Some(reason),
        }
    }

    /// Notifications the person sees.
    pub const fn notifications() -> Self {
        Self {
            service: Service::Notifications,
            reason: None,
        }
    }

    /// Work that carries on with the application off screen.
    pub const fn background() -> Self {
        Self {
            service: Service::Background,
            reason: None,
        }
    }

    /// Media playback that carries on with the application off screen.
    pub const fn media() -> Self {
        Self {
            service: Service::Media,
            reason: None,
        }
    }

    /// Purchases through the platform store.
    pub const fn billing() -> Self {
        Self {
            service: Service::Billing,
            reason: None,
        }
    }

    /// A window drawn above other applications.
    pub const fn overlay() -> Self {
        Self {
            service: Service::Overlay,
            reason: None,
        }
    }

    /// The vibrator.
    pub const fn haptics() -> Self {
        Self {
            service: Service::Haptics,
            reason: None,
        }
    }

    /// Recording that can start from the background; see
    /// `cranpose_services::hold_microphone_standby`.
    pub const fn microphone_standby() -> Self {
        Self {
            service: Service::MicrophoneStandby,
            reason: None,
        }
    }

    /// Messages and streams to the same application on the paired phone or
    /// watch; see `cranpose_services::wearable`.
    pub const fn wearable() -> Self {
        Self {
            service: Service::Wearable,
            reason: None,
        }
    }

    /// Handing a downloaded package to the system installer.
    pub const fn update() -> Self {
        Self {
            service: Service::Update,
            reason: None,
        }
    }

    /// The network, and whether the device is on one.
    pub const fn network() -> Self {
        Self {
            service: Service::Network,
            reason: None,
        }
    }

    /// The wearer's heart rate, with what the person is told before the
    /// sensor is read. Declaring it is the only way an application's build
    /// asks for the permission; reading it still takes an explicit request
    /// at run time.
    pub const fn heart_rate(reason: &'static str) -> Self {
        Self {
            service: Service::HeartRate,
            reason: Some(reason),
        }
    }

    /// Which service this is.
    pub const fn service(self) -> Service {
        self.service
    }

    /// The sentence the person is shown, for the services that have one.
    pub const fn reason(self) -> Option<&'static str> {
        self.reason
    }
}

/// Hardware an application cannot run without.
///
/// Every other feature stays optional, so the application reaches devices
/// that lack the hardware and asks the framework at run time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Demand {
    /// A camera.
    Camera,
    /// A microphone.
    Microphone,
    /// A watch.
    Watch,
    /// Telephony.
    Telephony,
    /// Bluetooth.
    Bluetooth,
    /// Near-field communication.
    Nfc,
    /// Wi-Fi.
    Wifi,
    /// Location hardware.
    Location,
}

impl Demand {
    /// The Android feature name this demand becomes.
    pub const fn android_feature(self) -> &'static str {
        match self {
            Demand::Camera => "android.hardware.camera",
            Demand::Microphone => "android.hardware.microphone",
            Demand::Watch => "android.hardware.type.watch",
            Demand::Telephony => "android.hardware.telephony",
            Demand::Bluetooth => "android.hardware.bluetooth",
            Demand::Nfc => "android.hardware.nfc",
            Demand::Wifi => "android.hardware.wifi",
            Demand::Location => "android.hardware.location",
        }
    }

    /// The name this demand carries in the build's own files.
    pub const fn name(self) -> &'static str {
        self.android_feature()
    }
}

/// Everything one application asks of a device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Capabilities<'a> {
    /// The services the application uses.
    pub uses: &'a [Use],
    /// The hardware the application cannot run without.
    pub demands: &'a [Demand],
    /// The media types of the files the application opens, such as
    /// `"audio/*"` or `"application/pdf"`: the platform then offers it for
    /// those files, in a share sheet and in "Open with", and hands what the
    /// person picks to `cranpose_services::incoming_share`.
    pub opens: &'a [&'a str],
}

impl Capabilities<'_> {
    /// An application that asks for nothing.
    pub const NONE: Capabilities<'static> = Capabilities {
        uses: &[],
        demands: &[],
        opens: &[],
    };

    /// Whether the application declared this service.
    pub fn has(&self, service: Service) -> bool {
        self.uses.iter().any(|entry| entry.service == service)
    }

    /// The sentence declared for a service, if it has one.
    pub fn reason_for(&self, service: Service) -> Option<&'static str> {
        self.uses
            .iter()
            .find(|entry| entry.service == service)
            .and_then(|entry| entry.reason())
    }
}

/// What a build script declares, before [`Declaration::emit`] writes it out.
#[must_use = "a declaration reaches the platform builds only through emit()"]
#[derive(Clone, Copy, Debug)]
pub struct Declaration<'a> {
    capabilities: Capabilities<'a>,
}

/// Starts a declaration with the services an application uses.
pub const fn declare(uses: &[Use]) -> Declaration<'_> {
    Declaration {
        capabilities: Capabilities {
            uses,
            demands: &[],
            opens: &[],
        },
    }
}

impl<'a> Declaration<'a> {
    /// Adds the hardware the application cannot run without.
    pub const fn demanding(self, demands: &'a [Demand]) -> Declaration<'a> {
        Declaration {
            capabilities: Capabilities {
                demands,
                ..self.capabilities
            },
        }
    }

    /// Adds the media types of the files the application opens, such as
    /// `"audio/*"`, so the platform offers it for them.
    pub const fn opening(self, opens: &'a [&'a str]) -> Declaration<'a> {
        Declaration {
            capabilities: Capabilities {
                opens,
                ..self.capabilities
            },
        }
    }

    /// Writes the declaration where the application and every platform build
    /// reads it.
    ///
    /// Call this from a build script. It panics when the files cannot be
    /// written, which is what a build script does with a failure.
    pub fn emit(self) {
        let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set for a build script"));
        let package = env::var("CARGO_PKG_NAME").expect("CARGO_PKG_NAME is set for a build script");
        write_file(
            &out.join("cranpose_capabilities.rs"),
            &rust_source(&self.capabilities),
        );

        let crate_dir = PathBuf::from(
            env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set for a build script"),
        );
        let shared = shared_dir(&crate_dir, env::var_os(CAPABILITIES_DIR));
        fs::create_dir_all(&shared).expect("the shared capabilities directory");
        let outputs = shared_outputs(&shared, &package);
        let contents = [
            json(&self.capabilities),
            android_manifest(&self.capabilities),
            apple_usage(&self.capabilities),
        ];
        for (path, text) in outputs.iter().zip(contents.iter()) {
            write_file(path, text);
        }
        println!("cargo::rerun-if-changed=build.rs");
        println!("cargo::rerun-if-env-changed={CAPABILITIES_DIR}");
        for directive in rerun_directives(&outputs) {
            println!("{directive}");
        }
    }
}

/// The files [`Declaration::emit`] writes outside `OUT_DIR`.
///
/// They go where every platform build reads them, which is also where anything
/// that reclaims build artifacts can remove them.
fn shared_outputs(shared: &Path, package: &str) -> [PathBuf; 3] {
    [
        shared.join(format!("{package}-capabilities.json")),
        shared.join(format!("{package}-permissions.xml")),
        shared.join(format!("{package}-usage.plist")),
    ]
}

/// Tells cargo that these files are this build script's outputs.
///
/// Cargo does not know what a build script writes outside `OUT_DIR`, and a
/// path named to `rerun-if-changed` counts as changed when it is missing. So
/// naming them is what makes a deleted declaration come back: without it,
/// cargo reads an unchanged `build.rs`, skips the script, and the tree keeps
/// building without the permissions XML that carries SYSTEM_ALERT_WINDOW and
/// VIBRATE into the merged Android manifest. The Android release APK then
/// fails `cranposeReleaseManifestCheck` on every run in that workspace,
/// because nothing will ever write the file again.
fn rerun_directives(outputs: &[PathBuf]) -> Vec<String> {
    outputs
        .iter()
        .map(|path| format!("cargo::rerun-if-changed={}", path.display()))
        .collect()
}

fn write_file(path: &Path, text: &str) {
    if fs::read(path).is_ok_and(|contents| contents == text.as_bytes()) {
        return;
    }
    fs::write(path, text).unwrap_or_else(|error| panic!("writing {}: {error}", path.display()));
}

/// Names the directory the declaration is written into.
///
/// A platform build sets it, because the build knows the tree it drives. A
/// plain `cargo build` does not, and the declaration then goes to
/// `<workspace>/target/cranpose`.
const CAPABILITIES_DIR: &str = "CRANPOSE_CAPABILITIES_DIR";

/// Where the declaration goes: the directory the build named, or the one under
/// the workspace this crate belongs to.
fn shared_dir(crate_dir: &Path, named: Option<OsString>) -> PathBuf {
    match named.filter(|value| !value.is_empty()) {
        Some(value) => PathBuf::from(value),
        None => workspace_root(crate_dir).join("target").join("cranpose"),
    }
}

/// The workspace this crate belongs to, found from its own directory.
///
/// The platform builds read the declaration from `<workspace>/target/cranpose`,
/// and they know the workspace because they already resolved this crate's
/// source there. The directory Cargo happens to build into is not that place:
/// it moves with `CARGO_TARGET_DIR`, and continuous integration sets it.
fn workspace_root(crate_dir: &Path) -> PathBuf {
    found_workspace(crate_dir, &|path| {
        fs::read_to_string(path.join("Cargo.toml"))
            .is_ok_and(|manifest| manifest.contains("[workspace]"))
    })
}

fn found_workspace(crate_dir: &Path, holds_workspace: &dyn Fn(&Path) -> bool) -> PathBuf {
    // The outermost workspace, so a crate inside a workspace that is itself
    // vendored into another one still answers with the tree the build drives.
    crate_dir
        .ancestors()
        .filter(|path| holds_workspace(path))
        .last()
        .map_or_else(|| crate_dir.to_path_buf(), Path::to_path_buf)
}

/// The Rust the application includes, so it reads the same declaration the
/// platform builds do.
fn rust_source(capabilities: &Capabilities<'_>) -> String {
    let mut text = String::from(
        "pub const CAPABILITIES: cranpose_capabilities::Capabilities =\n    \
         cranpose_capabilities::Capabilities {\n        uses: &[\n",
    );
    for entry in capabilities.uses {
        let call = constructor(entry);
        let _ = writeln!(text, "            cranpose_capabilities::Use::{call},");
    }
    text.push_str("        ],\n        demands: &[\n");
    for demand in capabilities.demands {
        let _ = writeln!(
            text,
            "            cranpose_capabilities::Demand::{demand:?},"
        );
    }
    text.push_str("        ],\n        opens: &[\n");
    for media_type in capabilities.opens {
        let _ = writeln!(text, "            \"{}\",", escape(media_type));
    }
    text.push_str("        ],\n    };\n");
    text
}

/// The call that rebuilds one entry, which is the service's own name with the
/// dashes a Rust function cannot carry turned back into underscores.
fn constructor(entry: &Use) -> String {
    let name = entry.service.name().replace('-', "_");
    match entry.reason {
        Some(reason) => format!("{name}(\"{}\")", escape(reason)),
        None => format!("{name}()"),
    }
}

fn escape(text: &str) -> String {
    text.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The declaration as the platform builds read it.
pub fn json(capabilities: &Capabilities<'_>) -> String {
    let mut text = String::from("{\n  \"services\": [\n");
    for (at, entry) in capabilities.uses.iter().enumerate() {
        let comma = if at + 1 == capabilities.uses.len() {
            ""
        } else {
            ","
        };
        let reason = match entry.reason {
            Some(reason) => format!("\"{}\"", escape_json(reason)),
            None => String::from("null"),
        };
        let _ = writeln!(
            text,
            "    {{ \"name\": \"{}\", \"reason\": {reason} }}{comma}",
            entry.service.name()
        );
    }
    text.push_str("  ],\n  \"permissions\": [\n");
    let permissions = android_permissions(capabilities);
    for (at, permission) in permissions.iter().enumerate() {
        let comma = if at + 1 == permissions.len() { "" } else { "," };
        let _ = writeln!(text, "    \"{permission}\"{comma}");
    }
    text.push_str("  ],\n  \"permissionsUpTo\": [\n");
    let capped = android_permissions_up_to(capabilities);
    for (at, (permission, level)) in capped.iter().enumerate() {
        let comma = if at + 1 == capped.len() { "" } else { "," };
        let _ = writeln!(
            text,
            "    {{ \"name\": \"{permission}\", \"maxSdk\": {level} }}{comma}"
        );
    }
    text.push_str("  ],\n  \"demands\": [\n");
    for (at, demand) in capabilities.demands.iter().enumerate() {
        let comma = if at + 1 == capabilities.demands.len() {
            ""
        } else {
            ","
        };
        let _ = writeln!(text, "    \"{}\"{comma}", demand.android_feature());
    }
    text.push_str("  ],\n  \"opens\": [\n");
    for (at, media_type) in capabilities.opens.iter().enumerate() {
        let comma = if at + 1 == capabilities.opens.len() {
            ""
        } else {
            ","
        };
        let _ = writeln!(text, "    \"{}\"{comma}", escape_json(media_type));
    }
    text.push_str("  ]\n}\n");
    text
}

fn escape_json(text: &str) -> String {
    escape(text).replace('\n', "\\n")
}

/// Every Android permission the declared services need, in order and without
/// repeats.
pub fn android_permissions(capabilities: &Capabilities<'_>) -> Vec<&'static str> {
    let mut named = BTreeSet::new();
    for entry in capabilities.uses {
        for permission in entry.service.android_permissions() {
            named.insert(*permission);
        }
    }
    named.into_iter().collect()
}

/// The permissions the declaration needs only up to an API level, each with
/// that level, without repeats and leaving out any the newer list already
/// names.
pub fn android_permissions_up_to(capabilities: &Capabilities<'_>) -> Vec<(&'static str, u32)> {
    let plain = android_permissions(capabilities);
    let mut named = std::collections::BTreeMap::new();
    for entry in capabilities.uses {
        for (permission, level) in entry.service.android_permissions_up_to() {
            if !plain.contains(permission) {
                named.insert(*permission, *level);
            }
        }
    }
    named.into_iter().collect()
}

/// The Android manifest fragment the declaration becomes.
pub fn android_manifest(capabilities: &Capabilities<'_>) -> String {
    let mut text = String::from(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
         <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n",
    );
    for permission in android_permissions(capabilities) {
        let _ = writeln!(
            text,
            "    <uses-permission android:name=\"{permission}\" />"
        );
    }
    for (permission, level) in android_permissions_up_to(capabilities) {
        let _ = writeln!(
            text,
            "    <uses-permission android:name=\"{permission}\" android:maxSdkVersion=\"{level}\" />"
        );
    }
    for demand in capabilities.demands {
        let _ = writeln!(
            text,
            "    <uses-feature android:name=\"{}\" android:required=\"true\" />",
            demand.android_feature()
        );
    }
    if !capabilities.opens.is_empty() {
        text.push_str(&android_opening_activity(capabilities.opens));
    }
    text.push_str("</manifest>\n");
    text
}

/// The activity entry that offers the application for `opens`: sending a file
/// to it and opening one with it.
fn android_opening_activity(opens: &[&str]) -> String {
    let mut text = String::from(
        "    <application>\n        \
         <activity android:name=\"dev.cranpose.android.CranposeActivity\">\n",
    );
    for actions in [
        &[
            "android.intent.action.SEND",
            "android.intent.action.SEND_MULTIPLE",
        ][..],
        &["android.intent.action.VIEW"][..],
    ] {
        text.push_str("            <intent-filter>\n");
        for action in actions {
            let _ = writeln!(text, "                <action android:name=\"{action}\" />");
        }
        text.push_str(
            "                <category android:name=\"android.intent.category.DEFAULT\" />\n",
        );
        for media_type in opens {
            let _ = writeln!(
                text,
                "                <data android:mimeType=\"{}\" />",
                escape_xml(media_type)
            );
        }
        text.push_str("            </intent-filter>\n");
    }
    text.push_str("        </activity>\n    </application>\n");
    text
}

/// The Apple usage descriptions the declaration becomes, as a property list
/// to merge into an `Info.plist`.
///
/// It is a property list of its own, so an Apple build merges it with one
/// line and no tool beyond the ones macOS ships:
///
/// ```text
/// /usr/libexec/PlistBuddy -c "Merge target/cranpose/my-app-usage.plist" MyApp.app/Info.plist
/// ```
pub fn apple_usage(capabilities: &Capabilities<'_>) -> String {
    let mut text = String::from(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \
         \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n<dict>\n",
    );
    for entry in capabilities.uses {
        let (Some(key), Some(reason)) = (entry.service.apple_key(), entry.reason) else {
            continue;
        };
        let _ = writeln!(text, "\t<key>{key}</key>");
        let _ = writeln!(text, "\t<string>{}</string>", escape_xml(reason));
    }
    text.push_str("</dict>\n</plist>\n");
    text
}

fn escape_xml(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

#[cfg(test)]
#[path = "tests/capabilities_tests.rs"]
mod tests;