liveactivity 0.7.6

Framework-neutral Live Activities: one interface over ActivityKit, Android Live Updates and other backends
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
//! Every feature of the crate as one function, in the order of the README, whose examples are these.
//!
//! The functions run on any backend. `main` runs them on a backend without a platform, which has the progress and
//! timer activities and their taps; what needs a platform answers its error code, which `main` prints.
//!
//! ```sh
//! cargo run -p liveactivity --example features --features testkit
//! ```

#![deny(clippy::unwrap_used, clippy::expect_used)]

use liveactivity::{
    Accessibility, ActivityState, Alert, AndroidContent, AndroidOptions, AndroidPlacement,
    AndroidPresentation, AndroidVisibility, Bound, EndInput, EndPolicy, Event, FeatureSupport,
    IosOptions, Layout, LayoutEndInput, LayoutPush, LayoutSnapshot, LayoutStartInput,
    LayoutUpdateInput, LiveActivity, LiveActivityBackend, NotificationAction, PermissionKind,
    PermissionState, PresentationStyle, ProgressSegment, ProgressStyle, PublicVersion, Result,
    ScheduledStart, StartInput, TimerStyle, Transition, UpdateInput,
    activitykit::{
        layout::{button, hstack, link, progress, symbol, text, toggle, vstack},
        values,
    },
    android::LiveUpdateBackend,
    liveupdate::{Driver, NextCheck, Timer},
};

/// Connect. One builder: the application names where events go, and whatever is not named is the default.
fn connect(backend: impl LiveActivityBackend) -> Result<LiveActivity> {
    LiveActivity::builder()
        .backend(backend) // leave this out for the platform's own backend
        .event_sink(|event: Event| {
            if let Some(id) = over(&event) {
                println!("{id} is over");
            }
            if let Some(on) = asked_to_mute(&event) {
                println!("asked to mute: {on}");
            }
            match event {
                Event::Action(tap) => println!("tapped {} on {}", tap.action_id, tap.activity_id),
                Event::State(change) => println!("{} is {:?}", change.activity_id, change.state),
                Event::PushToken(token) => println!("send {} to the server", token.token),
                _ => {}
            }
        })
        .build()
}

/// Events: an activity is over when a state event says that it ended or that the person dismissed it. This is
/// the id of the activity that `event` says is over.
fn over(event: &Event) -> Option<&str> {
    match event {
        Event::State(change)
            if matches!(
                change.state,
                ActivityState::Ended | ActivityState::Dismissed
            ) =>
        {
            Some(&change.activity_id)
        }
        _ => None,
    }
}

/// Progress and timer activities: a title, a status, and a progress from 0 to 1 or a countdown.
async fn progress_and_timer(live: &LiveActivity) -> Result<()> {
    let order = live
        .start(StartInput::progress(
            "order:42",
            "Order 42",
            "Preparing",
            0.1,
        ))
        .await?;
    // An update sends the whole content again, under a higher revision.
    live.update(UpdateInput::progress(
        &order.id,
        1,
        "Order 42",
        "On the way",
        0.6,
    ))
    .await?;
    live.end(EndInput::new(&order.id)).await?;

    // A countdown between two times, in epoch milliseconds.
    let (started_at, ends_at) = (1_800_000_000_000, 1_800_000_180_000);
    let tea = live
        .start(StartInput::timer(
            "tea:1", "Tea", "Steeping", started_at, ends_at,
        ))
        .await?;
    live.end(EndInput::immediate(&tea.id)).await?;
    Ok(())
}

/// A layout of the application's own: a tree of nodes, fixed at start, and values that updates replace.
async fn layout(live: &LiveActivity) -> Result<String> {
    let layout = Layout {
        lock_screen: vstack([
            text(Bound::key("title")),
            progress("done"),
            // A button: its tap reaches the event sink as `Event::Action`.
            button("track", text("Track")),
        ]),
        island: None,
        background: None,
        keyline: None,
        url: None,
        // What a paired Apple Watch and CarPlay show, when the widget extension draws the small family: a glance,
        // without buttons. Android has no place for it and names `layout.small`.
        small: Some(hstack([
            symbol("shippingbox.fill"),
            text(Bound::key("title")),
        ])),
    };
    let values = values! { "title" => "Delivery 7", "done" => 0.4 }.into_inner();
    let start = LayoutStartInput::new("delivery:7", layout, LayoutSnapshot::new(0, values));
    let record = live.start_layout(start).await?;

    // Every value again, under a higher revision.
    let values = values! { "title" => "Delivery 7", "done" => 0.9 }.into_inner();
    let update = LayoutUpdateInput::new(&record.id, LayoutSnapshot::new(1, values));
    live.update_layout(update).await?;
    Ok(record.id)
}

/// Links, accessibility, motion and privacy: members of the layout, which iOS draws. On Android the notification
/// and its actions open the URLs, a label is the text of what a notification cannot draw, and the record names
/// what was left out.
async fn links_accessibility_and_motion(live: &LiveActivity) -> Result<()> {
    let layout = Layout {
        lock_screen: vstack([
            // What VoiceOver reads of a node that has no text of its own.
            progress("done").accessibility(
                Accessibility::new()
                    .label("Delivery progress")
                    .value(Bound::key("percent")),
            ),
            // Hidden on a locked device, when the person asked for that.
            text(Bound::key("address")).sensitive(),
            // Shown while `arrived` is true, and how it comes and goes.
            text("At the door")
                .when("arrived")
                .transition(Transition::MoveTop),
            // A tap on the label opens the application with this URL.
            link("myapp://delivery/9/map", text("Map")),
        ]),
        island: None,
        background: None,
        keyline: None,
        // A tap anywhere else on the activity.
        url: Some("myapp://delivery/9".into()),
        small: None,
    };
    let values = values! {
        "done" => 0.4, "percent" => "40 percent", "address" => "12 Hill Street", "arrived" => false,
    }
    .into_inner();
    let start = LayoutStartInput::new("delivery:9", layout, LayoutSnapshot::new(0, values));
    let record = live.start_layout(start).await?;
    // On Android the links open too, and the record names layout.transition.
    println!("left out: {:?}", record.degraded_features);
    Ok(())
}

/// A toggle, and nodes that follow staleness. iOS draws a switch, and once the stale date has passed it draws the
/// stale nodes, without the application running. Android shows the toggle as an action whose title has a check
/// mark while it is on, draws the content as it is while fresh, and tells the sink that the activity is stale.
async fn toggle_and_staleness(live: &LiveActivity, stale_at: u64) -> Result<()> {
    let layout = Layout {
        lock_screen: vstack([
            // Drawn while the content is fresh, and the other in its place once its stale date has passed.
            text(Bound::key("eta")).unless_stale(),
            text("No signal").when_stale(),
            // A switch that shows `muted`. A tap asks for the other state and changes nothing itself.
            toggle("mute", "muted", text("Mute")),
        ]),
        island: None,
        background: None,
        keyline: None,
        url: None,
        small: None,
    };
    let values = values! { "eta" => "6 min", "muted" => false }.into_inner();
    let mut snapshot = LayoutSnapshot::new(0, values);
    snapshot.stale_at = Some(stale_at);
    let start = LayoutStartInput::new("ride:7", layout, snapshot);
    let record = live.start_layout(start).await?;
    // On Android the record names layout.ifStale.
    println!("left out: {:?}", record.degraded_features);
    Ok(())
}

/// What a sink reads of a tap on that toggle: the state the person asked for. The application sends an update
/// with that value, or does not when it refuses the change.
fn asked_to_mute(event: &Event) -> Option<bool> {
    match event {
        Event::Action(tap) if tap.action_id == "mute" => tap.on,
        _ => None,
    }
}

/// A start at a later time, with the alert the system shows then and its sound, and a transient activity. Android
/// takes a scheduled start where liveupdate's library begins one, keeps nothing of the iOS options, and names an
/// alert's sound.
async fn start_options_and_sounds(
    live: &LiveActivity,
    start: LayoutStartInput,
    at: u64,
) -> Result<()> {
    // A sound of the application's bundle. Without one the system plays its own.
    let alert = Alert::new("Your ride", "It starts now").with_sound("chime.aiff");
    let mut later = start.clone();
    later.scheduled = Some(ScheduledStart::new(at, alert));
    let record = live.start_layout(later).await?;
    // Until its time the activity is pending: it holds its key, takes no update, and can be ended.
    assert_eq!(record.state, ActivityState::Pending);
    live.end_layout(LayoutEndInput::immediate(&record.id))
        .await?;

    // An activity that the system ends when the person locks the device or leaves the application (iOS 18).
    let mut transient = start;
    transient.ios = Some(IosOptions::new(true));
    live.start_layout(transient).await?;
    Ok(())
}

/// An alert with an update, and a relevance. iOS lights up and shows the alert. Android alerts again with the
/// notification where the device offers that; elsewhere it updates silently and names `alert` in the record's
/// `degraded_features`.
async fn alert_and_relevance(live: &LiveActivity, id: &str) -> Result<()> {
    let values = values! { "title" => "Delivery 7", "done" => 1.0 }.into_inner();
    let mut snapshot = LayoutSnapshot::new(2, values);
    // Which of the application's activities the Dynamic Island shows first.
    snapshot.relevance = Some(90.0);
    let mut update = LayoutUpdateInput::new(id, snapshot);
    update.alert = Some(Alert::new("Delivery arrived", "Your parcel is at the door"));
    let record = live.update_layout(update).await?;
    if record.degraded_features.iter().any(|left| left == "alert") {
        println!("this platform updated without the alert");
    }
    Ok(())
}

/// An Android content: what the notification shows, in Android's own terms, instead of the projection of the
/// layout. iOS ignores it.
async fn android_content(live: &LiveActivity, id: &str) -> Result<()> {
    // Which notification styles the device draws: absent where there is no Android content.
    let styles = live.capabilities().await?.android_presentation;
    let segmented = styles.is_some_and(|styles| styles.progress_style);
    let values = values! { "title" => "Delivery 7", "done" => 0.6 }.into_inner();
    let mut snapshot = LayoutSnapshot::new(3, values);
    snapshot.android = Some(AndroidContent {
        title: "Delivery 7".into(),
        status: "2 stops away".into(),
        presentation: AndroidPresentation {
            // The text of the status chip, at most 7 characters.
            short_critical_text: Some("8 min".into()),
            ..AndroidPresentation::new(PresentationStyle::Progress(ProgressStyle {
                progress: 60,
                indeterminate: false,
                styled_by_progress: true,
                segments: if segmented {
                    vec![segment(60, Some(0xFF00_7F00)), segment(40, None)]
                } else {
                    vec![segment(100, None)]
                },
                points: Vec::new(),
                start_icon: None,
                end_icon: None,
                tracker_icon: None,
            }))
        },
    });
    live.update_layout(LayoutUpdateInput::new(id, snapshot))
        .await?;
    Ok(())
}

/// What else an Android content can say: a URL the notification opens, an action that opens one, a clock in the
/// header, what a secure lock screen shows, and the application's own look. Each is behind a capability.
async fn android_links_and_extras(live: &LiveActivity, id: &str, ends_at: u64) -> Result<()> {
    let capabilities = live.capabilities().await?;
    let offered = capabilities.android_presentation.unwrap_or_default();
    let values = values! { "title" => "Delivery 7", "done" => 0.8 }.into_inner();
    let mut snapshot = LayoutSnapshot::new(4, values);
    snapshot.android = Some(AndroidContent {
        title: "Delivery 7".into(),
        status: "At the door in 4 minutes".into(),
        presentation: AndroidPresentation {
            // A tap on the notification opens this URL in the application.
            open_url: offered.links.then(|| "myapp://delivery/7".into()),
            // An action that opens a URL sends no tap.
            actions: if offered.links {
                vec![NotificationAction {
                    open_url: Some("myapp://delivery/7/map".into()),
                    ..NotificationAction::new("map", "Map")
                }]
            } else {
                Vec::new()
            },
            // A countdown in the header, beside the style.
            chronometer: offered.chronometer.then(|| TimerStyle {
                timer: Timer {
                    started_at: ends_at - 240_000,
                    ends_at,
                },
                counts_down: true,
            }),
            // What a secure lock screen shows of an activity that started as private.
            public_version: offered.public_version.then(|| PublicVersion {
                title: "Delivery".into(),
                status: "On the way".into(),
            }),
            sub_text: offered.branding.then(|| "Mochi Express".into()),
            ..AndroidPresentation::new(PresentationStyle::Standard)
        },
    });
    live.update_layout(LayoutUpdateInput::new(id, snapshot))
        .await?;
    Ok(())
}

/// Android options: what only Android reads of a start. A public version is what a secure lock screen shows in
/// place of the content of a private activity. The foreground placement makes the notification the one that a
/// foreground service of the application holds.
async fn android_options(live: &LiveActivity, mut start: LayoutStartInput) -> Result<()> {
    let capabilities = live.capabilities().await?;
    let offered = capabilities.android_presentation.unwrap_or_default();
    let mut options = AndroidOptions::new(AndroidVisibility::Private);
    options.public_version = Some(PublicVersion {
        title: "Delivery".into(),
        status: "On the way".into(),
    });
    if offered.foreground_placement {
        options.placement = Some(AndroidPlacement::Foreground);
    }
    start.android = Some(options);
    let record = live.start_layout(start).await?;
    if record
        .degraded_features
        .iter()
        .any(|left| left == "publicVersion")
    {
        println!("this device shows no public version");
    }
    Ok(())
}

fn segment(length: u32, color: Option<u32>) -> ProgressSegment {
    ProgressSegment {
        length,
        id: None,
        color,
        semantic_style: None,
    }
}

/// An image: write the PNG first, then show it with an image node whose source is `{ "file": name }`.
async fn image(live: &LiveActivity, png: &[u8]) -> Result<()> {
    live.write_image("badge.png", png).await
}

/// Pushes (iOS): a start asks for a token, the sink gets it as `Event::PushToken`, and `push_tokens` answers what
/// came before the sink listened. A server sends the payloads that `activitykit::push::Payload` builds.
async fn pushes(live: &LiveActivity, mut start: LayoutStartInput) -> Result<()> {
    start.push = Some(LayoutPush::Token);
    live.start_layout(start).await?;
    for held in live.push_tokens().await?.activities {
        println!("{} has the token {}", held.activity_id, held.token);
    }
    Ok(())
}

/// What the device can do and what the person allows.
async fn capabilities_and_permissions(live: &LiveActivity) -> Result<()> {
    let capabilities = live.capabilities().await?;
    if capabilities.layout != FeatureSupport::Supported {
        println!(
            "{}: progress and timer activities only",
            capabilities.platform
        );
    }
    let permissions = live.permissions().await?;
    if permissions.notifications == PermissionState::Prompt {
        // Android shows the system's dialog through the host; iOS has a switch in Settings and no dialog.
        live.request_permissions(PermissionKind::Notifications)
            .await?;
    }
    Ok(())
}

/// Events on Android: nobody tells the application that a stale time has come, and the backend runs no timer. A
/// host that has a thread and the default Android backend asks it when to ask again.
#[allow(dead_code)]
fn when_to_ask_again<D: Driver + 'static>(backend: &LiveUpdateBackend<D>) -> Result<()> {
    match backend.next_check()? {
        // A state is due: hand it over.
        NextCheck::Now => {
            backend.pump_events()?;
        }
        // Android has not shown a post yet: shortly, a little later each time, a few times.
        NextCheck::Soon => {}
        // The earliest stale time ahead, in epoch milliseconds.
        NextCheck::At(_time) => {}
        // Nothing until the next call, signal or resume.
        NextCheck::Never => {}
    }
    Ok(())
}

/// Ending a layout activity, and the events Android stored while the application did not run.
async fn end_and_sync(live: &LiveActivity, id: &str) -> Result<()> {
    live.end_layout(LayoutEndInput::new(id)).await?;
    // Call this when the application starts and resumes. On iOS it does nothing.
    live.sync_events().await
}

/// An end that keeps the last content on screen until a time, with a final snapshot. iOS keeps it for at most
/// four hours. Android keeps it where the device offers that, and answers `UNSUPPORTED_FEATURE` elsewhere.
async fn end_with_a_last_content(live: &LiveActivity, id: &str, until: u64) -> Result<()> {
    let values = values! { "title" => "Delivered", "done" => 1.0 }.into_inner();
    let mut end = LayoutEndInput::new(id);
    end.policy = EndPolicy::After { at: until };
    end.snapshot = Some(LayoutSnapshot::new(5, values));
    live.end_layout(end).await?;
    Ok(())
}

/// The error code of a call, or `ok`.
fn code<T>(result: Result<T>) -> String {
    result.map_or_else(|error| error.code, |_| "ok".to_owned())
}

fn main() -> Result<()> {
    let memory = std::sync::Arc::new(liveactivity::testkit::MemoryBackend::new());
    let live = connect(memory.clone())?;
    // Where no executor runs, `wait` blocks for the answer; on the main thread of an iOS app it answers an error
    // at once instead, because the answer comes from that thread.
    liveactivity::wait(async {
        println!(
            "progress and timer: {}",
            code(progress_and_timer(&live).await)
        );
        let order = live
            .start(StartInput::progress(
                "order:43",
                "Order 43",
                "Preparing",
                0.2,
            ))
            .await?;
        memory.tap(&order.id, "track")?;
        println!(
            "capabilities: {}",
            code(capabilities_and_permissions(&live).await)
        );

        // The rest needs a platform that draws layouts: here each answers its error code.
        println!("layout: {}", code(layout(&live).await));
        println!(
            "links, accessibility and motion: {}",
            code(links_accessibility_and_motion(&live).await)
        );
        println!(
            "toggle and staleness: {}",
            code(toggle_and_staleness(&live, 1_800_000_240_000).await)
        );
        println!(
            "alert and relevance: {}",
            code(alert_and_relevance(&live, "id").await)
        );
        println!(
            "android content: {}",
            code(android_content(&live, "id").await)
        );
        let in_four_minutes = 1_800_000_240_000;
        println!(
            "android links and extras: {}",
            code(android_links_and_extras(&live, "id", in_four_minutes).await)
        );
        println!("image: {}", code(image(&live, b"not a png").await));
        let start = LayoutStartInput::new(
            "delivery:8",
            Layout {
                lock_screen: text("Delivery 8"),
                island: None,
                background: None,
                keyline: None,
                url: None,
                small: None,
            },
            LayoutSnapshot::new(0, Default::default()),
        );
        println!(
            "android options: {}",
            code(android_options(&live, start.clone()).await)
        );
        println!(
            "start options and sounds: {}",
            code(start_options_and_sounds(&live, start.clone(), 1_800_000_240_000).await)
        );
        println!("pushes: {}", code(pushes(&live, start).await));
        println!("end and sync: {}", code(end_and_sync(&live, "id").await));
        println!(
            "end with a last content: {}",
            code(end_with_a_last_content(&live, "id", in_four_minutes).await)
        );
        Ok(())
    })
}