#![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},
};
fn connect(backend: impl LiveActivityBackend) -> Result<LiveActivity> {
LiveActivity::builder()
.backend(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()
}
fn over(event: &Event) -> Option<&str> {
match event {
Event::State(change)
if matches!(
change.state,
ActivityState::Ended | ActivityState::Dismissed
) =>
{
Some(&change.activity_id)
}
_ => None,
}
}
async fn progress_and_timer(live: &LiveActivity) -> Result<()> {
let order = live
.start(StartInput::progress(
"order:42",
"Order 42",
"Preparing",
0.1,
))
.await?;
live.update(UpdateInput::progress(
&order.id,
1,
"Order 42",
"On the way",
0.6,
))
.await?;
live.end(EndInput::new(&order.id)).await?;
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(())
}
async fn layout(live: &LiveActivity) -> Result<String> {
let layout = Layout {
lock_screen: vstack([
text(Bound::key("title")),
progress("done"),
button("track", text("Track")),
]),
island: None,
background: None,
keyline: None,
url: None,
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?;
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)
}
async fn links_accessibility_and_motion(live: &LiveActivity) -> Result<()> {
let layout = Layout {
lock_screen: vstack([
progress("done").accessibility(
Accessibility::new()
.label("Delivery progress")
.value(Bound::key("percent")),
),
text(Bound::key("address")).sensitive(),
text("At the door")
.when("arrived")
.transition(Transition::MoveTop),
link("myapp://delivery/9/map", text("Map")),
]),
island: None,
background: None,
keyline: None,
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?;
println!("left out: {:?}", record.degraded_features);
Ok(())
}
async fn toggle_and_staleness(live: &LiveActivity, stale_at: u64) -> Result<()> {
let layout = Layout {
lock_screen: vstack([
text(Bound::key("eta")).unless_stale(),
text("No signal").when_stale(),
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?;
println!("left out: {:?}", record.degraded_features);
Ok(())
}
fn asked_to_mute(event: &Event) -> Option<bool> {
match event {
Event::Action(tap) if tap.action_id == "mute" => tap.on,
_ => None,
}
}
async fn start_options_and_sounds(
live: &LiveActivity,
start: LayoutStartInput,
at: u64,
) -> Result<()> {
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?;
assert_eq!(record.state, ActivityState::Pending);
live.end_layout(LayoutEndInput::immediate(&record.id))
.await?;
let mut transient = start;
transient.ios = Some(IosOptions::new(true));
live.start_layout(transient).await?;
Ok(())
}
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);
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(())
}
async fn android_content(live: &LiveActivity, id: &str) -> Result<()> {
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);
let segments = if segmented {
vec![segment(60, Some(0xFF00_7F00)), segment(40, None)]
} else {
vec![segment(100, None)]
};
snapshot.android = Some(AndroidContent::new(
"Delivery 7",
"2 stops away",
AndroidPresentation {
short_critical_text: Some("8 min".into()),
..AndroidPresentation::new(PresentationStyle::Progress(ProgressStyle::new(
60, segments,
)))
},
));
live.update_layout(LayoutUpdateInput::new(id, snapshot))
.await?;
Ok(())
}
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::new(
"Delivery 7",
"At the door in 4 minutes",
AndroidPresentation {
open_url: offered.links.then(|| "myapp://delivery/7".into()),
actions: if offered.links {
vec![NotificationAction {
open_url: Some("myapp://delivery/7/map".into()),
..NotificationAction::new("map", "Map")
}]
} else {
Vec::new()
},
chronometer: offered
.chronometer
.then(|| TimerStyle::new(Timer::new(ends_at - 240_000, ends_at), true)),
public_version: offered
.public_version
.then(|| PublicVersion::new("Delivery", "On the way")),
sub_text: offered.branding.then(|| "Mochi Express".into()),
wear_ongoing_activity: false,
..AndroidPresentation::new(PresentationStyle::Standard)
},
));
live.update_layout(LayoutUpdateInput::new(id, snapshot))
.await?;
Ok(())
}
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::new("Delivery", "On the way"));
if offered.foreground_placement {
options.placement = Some(AndroidPlacement::Foreground);
}
if offered.wear_ongoing_activity {
options = options.with_wear_ongoing_activity(false);
}
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 {
color,
..ProgressSegment::new(length)
}
}
async fn image(live: &LiveActivity, png: &[u8]) -> Result<()> {
live.write_image("badge.png", png).await
}
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(())
}
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 {
live.request_permissions(PermissionKind::Notifications)
.await?;
}
Ok(())
}
#[allow(dead_code)]
fn when_to_ask_again<D: Driver + 'static>(backend: &LiveUpdateBackend<D>) -> Result<()> {
match backend.next_check()? {
NextCheck::Now => {
backend.pump_events()?;
}
NextCheck::Soon => {}
NextCheck::At(_time) => {}
NextCheck::Never => {}
_ => {}
}
Ok(())
}
async fn end_and_sync(live: &LiveActivity, id: &str) -> Result<()> {
live.end_layout(LayoutEndInput::new(id)).await?;
live.sync_events().await
}
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(())
}
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())?;
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)
);
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(())
})
}