use crate::layout::{Bindable, Element, ImageSource, Layout, LayoutSnapshot, Node, Value};
use std::collections::BTreeMap;
const PROGRESS_SCALE: u32 = 1000;
const MAX_TITLE: usize = 120;
const MAX_STATUS: usize = 240;
const MAX_ACTION_TITLE: usize = 64;
const MAX_ACTIONS: usize = liveupdate::MAX_ACTIONS;
const ON_MARK: &str = "✓ ";
pub(crate) struct Environment<'a> {
pub(crate) app_name: &'a str,
pub(crate) samsung_now_bar: bool,
pub(crate) image: &'a dyn Fn(&str) -> Option<String>,
pub(crate) public: bool,
pub(crate) links: bool,
pub(crate) chronometer: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Projection {
pub(crate) snapshot: liveupdate::Snapshot,
pub(crate) degraded: Vec<String>,
}
pub(crate) fn template(layout: &Layout) -> liveupdate::Template {
let mut texts = 0;
let mut timer = false;
let mut progress = false;
visit_all(
&layout.lock_screen,
false,
&mut |node, in_button| match &node.element {
Element::Progress { .. } => progress = true,
Element::TimerText { .. } => timer = true,
Element::Text { .. } if !in_button => texts += 1,
element if !in_button && !drawn(element) && worded(node) => texts += 1,
_ => {}
},
);
if progress {
liveupdate::Template::Progress
} else if timer {
liveupdate::Template::Timer
} else if texts >= 2 {
liveupdate::Template::BigText
} else {
liveupdate::Template::Standard
}
}
pub(crate) fn project(
layout: &Layout,
styled: bool,
snapshot: &LayoutSnapshot,
template: liveupdate::Template,
environment: &Environment<'_>,
) -> Projection {
let values = &snapshot.values;
let mut shown = Shown {
public: environment.public,
links: environment.links,
..Shown::default()
};
walk(&layout.lock_screen, values, &mut shown);
let chip = match (shown.progress, shown.timer) {
(Some(fraction), None) => Some(format!("{}%", (fraction * 100.0).round() as u32)),
_ => None,
};
let body = shown.texts.get(1).filter(|text| !blank(text)).cloned();
let title = shown.texts.first().filter(|text| !blank(text)).map_or_else(
|| cut(app_name(environment.app_name), MAX_TITLE),
|text| cut(text, MAX_TITLE),
);
let status = body
.clone()
.or_else(|| chip.clone())
.map_or_else(|| title.clone(), |text| cut(&text, MAX_STATUS));
let style = match template {
liveupdate::Template::Progress => {
liveupdate::PresentationStyle::Progress(progress_style(shown.progress))
}
liveupdate::Template::Timer => liveupdate::PresentationStyle::Timer(timer_style(
shown
.timer
.or_else(|| first_timer(&layout.lock_screen, values)),
)),
liveupdate::Template::BigText => {
liveupdate::PresentationStyle::BigText(liveupdate::BigTextStyle {
text: status.clone(),
summary: None,
})
}
_ => liveupdate::PresentationStyle::Standard,
};
let beside = environment.chronometer && matches!(template, liveupdate::Template::Progress);
let chronometer = shown
.timer
.filter(|_| beside)
.map(|timer| timer_style(Some(timer)));
let mut degraded = shown.degraded;
if shown.timer.is_some()
&& chronometer.is_none()
&& !matches!(template, liveupdate::Template::Timer)
{
note(&mut degraded, "timerText");
}
let open_url = layout
.url
.as_ref()
.filter(|_| environment.links)
.and_then(|url| address(url, values));
let large_icon = shown
.files
.first()
.and_then(|file| (environment.image)(file));
if shown.files.len() > 1 || (!shown.files.is_empty() && large_icon.is_none()) {
note(&mut degraded, "image");
}
let samsung_now_bar = environment
.samsung_now_bar
.then(|| liveupdate::SamsungNowBar {
primary: Some(title.clone()),
secondary: body
.clone()
.or_else(|| chip.clone())
.map(|text| cut(&text, MAX_STATUS)),
});
for part in [
(follows_staleness(&layout.lock_screen), "layout.ifStale"),
(layout.island.is_some(), "layout.island"),
(layout.small.is_some(), "layout.small"),
(styled, "layout.styles"),
(layout.background.is_some(), "layout.background"),
(layout.keyline.is_some(), "layout.keyline"),
(layout.url.is_some() && open_url.is_none(), "layout.url"),
] {
if part.0 {
degraded.push(part.1.to_owned());
}
}
Projection {
snapshot: liveupdate::Snapshot {
revision: snapshot.revision,
title,
status,
progress: None,
timer: None,
stale_at: snapshot.stale_at,
presentation: Some(liveupdate::AndroidPresentation {
short_critical_text: chip,
large_icon: large_icon.map(liveupdate::IconSource::AppFile),
actions: shown.actions,
samsung_now_bar,
chronometer,
open_url,
..liveupdate::AndroidPresentation::new(style)
}),
},
degraded,
}
}
pub(crate) fn asked_for(
layout: &Layout,
values: &BTreeMap<String, Value>,
action_id: &str,
) -> Option<bool> {
let mut shown = Shown::default();
walk(&layout.lock_screen, values, &mut shown);
let toggle = shown.toggles.iter().find(|(id, _)| id == action_id);
toggle.map(|(_, on)| !on)
}
#[derive(Default)]
struct Shown {
texts: Vec<String>,
actions: Vec<liveupdate::NotificationAction>,
toggles: Vec<(String, bool)>,
files: Vec<String>,
progress: Option<f64>,
timer: Option<(f64, f64, bool)>,
degraded: Vec<String>,
public: bool,
links: bool,
links_seen: usize,
}
fn walk(node: &Node, values: &BTreeMap<String, Value>, shown: &mut Shown) {
if !visible(node, values) {
shown.links_seen += links_in(node);
return;
}
if node.transition.is_some() {
note(&mut shown.degraded, "transition");
}
if node.privacy.is_some() && shown.public {
note(&mut shown.degraded, "privacy");
}
match &node.element {
Element::Vstack { children, .. }
| Element::Hstack { children, .. }
| Element::Zstack { children, .. } => {
children.iter().for_each(|child| walk(child, values, shown));
}
Element::Text { .. } => say(shown, text(node, values).unwrap_or_default()),
Element::Progress { bind, .. } if shown.progress.is_none() => {
shown.progress = Some(number(values.get(bind)).clamp(0.0, 1.0));
}
Element::TimerText {
start,
end,
counts_down,
} if shown.timer.is_none() => {
shown.timer = Some((
number(values.get(start)),
number(values.get(end)),
counts_down.unwrap_or(true),
));
}
Element::Image {
source: ImageSource::File { file },
..
} => shown.files.push(file.clone()),
Element::Button { action_id, child } => {
let (title, inside) = action_title(node, child, values, shown.public);
let action =
title.map(|title| liveupdate::NotificationAction::new(action_id.clone(), title));
act(shown, action, &inside, "button");
}
Element::Toggle {
action_id,
bind,
child,
} => {
let (label, inside) = action_title(node, child, values, shown.public);
let on = truthy(values.get(bind));
let mark = if on { ON_MARK } else { "" };
let action = label.map(|label| {
let title = cut(&format!("{mark}{label}"), MAX_ACTION_TITLE);
liveupdate::NotificationAction::new(action_id.clone(), title)
});
if act(shown, action, &inside, "toggle") {
shown.toggles.push((action_id.clone(), on));
}
}
Element::Link { url, child } => {
shown.links_seen += 1;
let id = format!("link:{}", shown.links_seen);
let (title, inside) = action_title(node, child, values, shown.public);
let url = Some(url)
.filter(|_| shown.links)
.and_then(|url| address(url, values));
let action = title
.zip(url)
.map(|(title, url)| liveupdate::NotificationAction {
open_url: Some(url),
..liveupdate::NotificationAction::new(id, title)
});
act(shown, action, &inside, "link");
}
element if drawn(element) => note(&mut shown.degraded, kind(element)),
element => match &node.accessibility {
Some(accessibility) if accessibility.hidden == Some(true) => {}
_ => match spoken(node, values) {
Some(words) => say(shown, words),
None => note(&mut shown.degraded, kind(element)),
},
},
}
}
fn say(shown: &mut Shown, words: String) {
match shown.texts.len() {
0 | 1 => shown.texts.push(words),
_ => note(&mut shown.degraded, "text"),
}
}
fn act(
shown: &mut Shown,
action: Option<liveupdate::NotificationAction>,
inside: &[&'static str],
kind: &str,
) -> bool {
let room = shown.actions.len() < MAX_ACTIONS;
match action {
Some(action) if room && shown.actions.iter().all(|other| other.id != action.id) => {
shown.actions.push(action);
inside
.iter()
.for_each(|kind| note(&mut shown.degraded, kind));
true
}
_ => {
note(&mut shown.degraded, kind);
false
}
}
}
fn action_title(
owner: &Node,
child: &Node,
values: &BTreeMap<String, Value>,
public: bool,
) -> (Option<String>, Vec<&'static str>) {
let mut first_text: Option<Option<String>> = None;
let mut worded_picture: Option<(usize, String)> = None;
let mut inside = Vec::new();
visit_shown(child, values, &mut |node| {
if node.transition.is_some() {
inside.push("transition");
}
if node.privacy.is_some() && public {
inside.push("privacy");
}
match &node.element {
Element::Vstack { .. } | Element::Hstack { .. } | Element::Zstack { .. } => {}
Element::Text { .. } if first_text.is_none() => {
first_text = Some(text(node, values).filter(|text| !blank(text)));
}
_ if node
.accessibility
.as_ref()
.is_some_and(|accessibility| accessibility.hidden == Some(true)) => {}
element => {
if worded_picture.is_none()
&& let Some(words) = spoken(node, values)
{
worded_picture = Some((inside.len(), words));
}
inside.push(kind(element));
}
}
});
let title = match (first_text.flatten(), worded_picture) {
(Some(text), _) => Some(text),
(None, Some((place, words))) => {
inside.remove(place);
Some(words)
}
(None, None) => spoken(owner, values),
};
(title.map(|title| cut(&title, MAX_ACTION_TITLE)), inside)
}
fn spoken(node: &Node, values: &BTreeMap<String, Value>) -> Option<String> {
let accessibility = node.accessibility.as_ref()?;
let words: Vec<String> = [&accessibility.label, &accessibility.value]
.into_iter()
.flatten()
.filter_map(|member| resolved(member, values))
.filter(|words| !blank(words))
.collect();
(!words.is_empty()).then(|| words.join(", "))
}
fn worded(node: &Node) -> bool {
node.accessibility.as_ref().is_some_and(|accessibility| {
accessibility.hidden != Some(true)
&& (accessibility.label.is_some() || accessibility.value.is_some())
})
}
fn drawn(element: &Element) -> bool {
matches!(
element,
Element::Vstack { .. }
| Element::Hstack { .. }
| Element::Zstack { .. }
| Element::Text { .. }
| Element::Progress { .. }
| Element::TimerText { .. }
| Element::Button { .. }
| Element::Toggle { .. }
| Element::Link { .. }
| Element::Image {
source: ImageSource::File { .. },
..
}
)
}
fn resolved(member: &Bindable<String>, values: &BTreeMap<String, Value>) -> Option<String> {
match member {
Bindable::Literal(text) => Some(text.clone()),
Bindable::Bound(bound) => values.get(&bound.bind).map(display),
}
}
fn address(url: &Bindable<String>, values: &BTreeMap<String, Value>) -> Option<String> {
let url = resolved(url, values)?;
let opened = liveupdate::AndroidPresentation {
open_url: Some(url.clone()),
..liveupdate::AndroidPresentation::new(liveupdate::PresentationStyle::Standard)
};
opened.validate().is_ok().then_some(url)
}
fn links_in(node: &Node) -> usize {
let mut links = 0;
visit_all(node, false, &mut |node, _| {
if matches!(node.element, Element::Link { .. }) {
links += 1;
}
});
links
}
pub(crate) fn could_use(layout: &Layout) -> (bool, bool) {
let (mut link, mut progress, mut timer) = (layout.url.is_some(), false, false);
visit_all(
&layout.lock_screen,
false,
&mut |node, _| match &node.element {
Element::Link { .. } => link = true,
Element::Progress { .. } => progress = true,
Element::TimerText { .. } => timer = true,
_ => {}
},
);
(link, progress && timer)
}
fn first_timer(node: &Node, values: &BTreeMap<String, Value>) -> Option<(f64, f64, bool)> {
let mut found = None;
visit_all(node, false, &mut |node, _| {
if let (
None,
Element::TimerText {
start,
end,
counts_down,
},
) = (&found, &node.element)
{
found = Some((
number(values.get(start)),
number(values.get(end)),
counts_down.unwrap_or(true),
));
}
});
found
}
fn progress_style(fraction: Option<f64>) -> liveupdate::ProgressStyle {
let fraction = fraction.unwrap_or(0.0);
liveupdate::ProgressStyle {
progress: (fraction * f64::from(PROGRESS_SCALE)).round() as u32,
indeterminate: false,
styled_by_progress: false,
segments: vec![liveupdate::ProgressSegment {
length: PROGRESS_SCALE,
id: None,
color: None,
semantic_style: None,
}],
points: Vec::new(),
start_icon: None,
end_icon: None,
tracker_icon: None,
}
}
fn timer_style(timer: Option<(f64, f64, bool)>) -> liveupdate::TimerStyle {
let (start, end, counts_down) = timer.unwrap_or((0.0, 0.0, true));
let started_at = millis(start);
let ends_at = millis(end)
.max(started_at.saturating_add(1))
.min(liveupdate::MAX_TIMESTAMP);
liveupdate::TimerStyle {
timer: liveupdate::Timer {
started_at: started_at.min(ends_at - 1),
ends_at,
},
counts_down,
}
}
fn millis(value: f64) -> u64 {
if value.is_finite() && value > 0.0 {
(value.floor() as u64).min(liveupdate::MAX_TIMESTAMP)
} else {
0
}
}
fn visible(node: &Node, values: &BTreeMap<String, Value>) -> bool {
!only_when_stale(node)
&& node.r#if.as_ref().is_none_or(|key| truthy(values.get(key)))
&& node
.unless
.as_ref()
.is_none_or(|key| !truthy(values.get(key)))
}
fn only_when_stale(node: &Node) -> bool {
node.if_stale == Some(true)
}
fn follows_staleness(node: &Node) -> bool {
node.if_stale.is_some()
|| match &node.element {
Element::Vstack { children, .. }
| Element::Hstack { children, .. }
| Element::Zstack { children, .. } => children.iter().any(follows_staleness),
Element::Button { child, .. }
| Element::Toggle { child, .. }
| Element::Link { child, .. } => follows_staleness(child),
_ => false,
}
}
fn truthy(value: Option<&Value>) -> bool {
match value {
Some(Value::Bool(value)) => *value,
Some(Value::Number(value)) => *value != 0.0 && !value.is_nan(),
Some(Value::Text(value)) => !value.is_empty(),
None => false,
}
}
fn number(value: Option<&Value>) -> f64 {
match value {
Some(Value::Number(value)) => *value,
_ => 0.0,
}
}
fn text(node: &Node, values: &BTreeMap<String, Value>) -> Option<String> {
match &node.element {
Element::Text {
value: Some(value), ..
} => Some(value.clone()),
Element::Text {
bind: Some(key), ..
} => values.get(key).map(display),
_ => None,
}
}
pub(crate) fn display(value: &Value) -> String {
match value {
Value::Text(text) => text.clone(),
Value::Bool(value) => value.to_string(),
Value::Number(value) => js_number(*value),
}
}
fn js_number(value: f64) -> String {
if value == 0.0 {
return "0".to_owned();
}
let magnitude = value.abs();
if (1e-6..1e21).contains(&magnitude) {
return value.to_string();
}
let written = format!("{value:e}");
match written.split_once('e') {
Some((mantissa, exponent)) if !exponent.starts_with('-') => {
format!("{mantissa}e+{exponent}")
}
_ => written,
}
}
fn blank(text: &str) -> bool {
text.chars().all(|character| {
matches!(
character as u32,
0x0009..=0x000D | 0x2000..=0x200A | 0x0020 | 0x00A0 | 0x1680 | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 | 0xFEFF
)
})
}
fn cut(text: &str, maximum: usize) -> String {
if text.chars().count() <= maximum {
return text.to_owned();
}
let mut cut: String = text.chars().take(maximum - 1).collect();
cut.push('…');
cut
}
fn app_name(name: &str) -> &str {
if blank(name) { "Live activity" } else { name }
}
fn note(degraded: &mut Vec<String>, kind: &str) {
let feature = format!("layout.{kind}");
if !degraded.contains(&feature) {
degraded.push(feature);
}
}
fn kind(element: &Element) -> &'static str {
match element {
Element::Vstack { .. } => "vstack",
Element::Hstack { .. } => "hstack",
Element::Zstack { .. } => "zstack",
Element::Spacer { .. } => "spacer",
Element::Divider { .. } => "divider",
Element::Text { .. } => "text",
Element::Symbol { .. } => "symbol",
Element::Image { .. } => "image",
Element::Path { .. } => "path",
Element::Progress { .. } => "progress",
Element::Gauge { .. } => "gauge",
Element::TimerText { .. } => "timerText",
Element::Button { .. } => "button",
Element::Link { .. } => "link",
Element::Toggle { .. } => "toggle",
Element::Custom { .. } => "custom",
}
}
fn visit_all(node: &Node, in_button: bool, visit: &mut impl FnMut(&Node, bool)) {
if only_when_stale(node) {
return;
}
visit(node, in_button);
match &node.element {
Element::Vstack { children, .. }
| Element::Hstack { children, .. }
| Element::Zstack { children, .. } => {
children
.iter()
.for_each(|child| visit_all(child, in_button, visit));
}
Element::Button { child, .. } | Element::Toggle { child, .. } => {
visit_all(child, true, visit);
}
_ => {}
}
}
fn visit_shown(node: &Node, values: &BTreeMap<String, Value>, visit: &mut impl FnMut(&Node)) {
if !visible(node, values) {
return;
}
visit(node);
match &node.element {
Element::Vstack { children, .. }
| Element::Hstack { children, .. }
| Element::Zstack { children, .. } => {
children
.iter()
.for_each(|child| visit_shown(child, values, visit));
}
Element::Button { child, .. } | Element::Toggle { child, .. } => {
visit_shown(child, values, visit);
}
_ => {}
}
}
#[cfg(test)]
#[path = "layout_tests.rs"]
mod tests;