use super::{
convert as android_liveupdate,
layout::{self as android_layout, Environment},
};
use crate::{
ActionEvent, Backend, EndPolicy, Error, LayoutActivityRecord, LayoutEndInput, LayoutSnapshot,
LayoutStartInput, LayoutUpdateInput, Result, Visibility,
layout::{AndroidVisibility, Element, Node},
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs, io::Read, path::PathBuf, sync::Mutex};
const MAX_ICON_SIDE: u32 = 1024;
const MAX_ICON_BYTES: u64 = 1_048_576;
const PENDING: &str = "pending:";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Entry {
pub(crate) origin: LayoutStartInput,
pub(crate) snapshot: LayoutSnapshot,
pub(crate) degraded: Vec<String>,
}
pub(crate) type Entries = BTreeMap<String, Entry>;
pub(crate) trait Store: Send + Sync {
fn load(&self) -> Result<Entries>;
fn save(&self, entries: &Entries) -> Result<()>;
}
pub(crate) struct FileStore {
pub(crate) path: PathBuf,
}
impl Store for FileStore {
fn load(&self) -> Result<Entries> {
match fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|_| Error::native()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Entries::new()),
Err(_) => Err(Error::native()),
}
}
fn save(&self, entries: &Entries) -> Result<()> {
let bytes = serde_json::to_vec(entries).map_err(|_| Error::native())?;
let written = self.path.with_extension("json.new");
if let Some(folder) = self.path.parent() {
fs::create_dir_all(folder).map_err(|_| Error::native())?;
}
fs::write(&written, bytes)
.and_then(|()| fs::rename(&written, &self.path))
.map_err(|_| Error::native())
}
}
pub(crate) struct Settings {
pub(crate) app_name: String,
pub(crate) samsung_now_bar: bool,
pub(crate) files: Option<PathBuf>,
pub(crate) image_folder: String,
}
pub(crate) struct Layouts<D: liveupdate::Driver, S: Store> {
settings: Settings,
store: S,
lock: Mutex<()>,
_driver: std::marker::PhantomData<D>,
}
impl<D: liveupdate::Driver, S: Store> Layouts<D, S> {
pub(crate) fn new(settings: Settings, store: S) -> Self {
Self {
settings,
store,
lock: Mutex::new(()),
_driver: std::marker::PhantomData,
}
}
pub(crate) fn start(
&self,
updates: &liveupdate::LiveUpdate<D>,
input: LayoutStartInput,
) -> Result<LayoutActivityRecord> {
let input = LayoutStartInput {
push: None,
..input
};
let _guard = self.lock.lock().map_err(|_| Error::native())?;
let (mut entries, records) = self.reconciled(updates)?;
let conflicting = records
.iter()
.filter(|record| running(record))
.any(|record| {
entries.get(&record.id).is_some_and(|entry| {
entry.origin.activity_key == input.activity_key && entry.origin != input
})
});
if conflicting {
return Err(Error::new(
"CONFLICT",
"a running activity of this key started with another request",
));
}
let template = android_layout::template(&input.layout);
let projection = self.project(&input, &input.snapshot, template);
let request = liveupdate::StartRequest {
activity_key: input.activity_key.clone(),
schema_version: 2,
template,
fallback: android_liveupdate::fallback(input.fallback),
visibility: visibility(&input),
snapshot: projection.snapshot,
};
let pending = format!("{PENDING}{}", input.activity_key);
let entry = Entry {
origin: input.clone(),
snapshot: input.snapshot.clone(),
degraded: projection.degraded,
};
entries.insert(pending.clone(), entry.clone());
self.store.save(&entries)?;
let record = updates.start(request).map_err(android_liveupdate::error)?;
entries.remove(&pending);
let entry = entries.entry(record.id.clone()).or_insert(entry).clone();
self.store.save(&entries)?;
Ok(layout_record(&record, &entry))
}
pub(crate) fn update(
&self,
updates: &liveupdate::LiveUpdate<D>,
input: LayoutUpdateInput,
) -> Result<LayoutActivityRecord> {
let _guard = self.lock.lock().map_err(|_| Error::native())?;
let (mut entries, records) = self.reconciled(updates)?;
let record = self.replace(updates, &mut entries, &records, &input.id, input.snapshot)?;
let entry = entries.get(&input.id).ok_or_else(not_found)?;
Ok(layout_record(&record, entry))
}
pub(crate) fn end(
&self,
updates: &liveupdate::LiveUpdate<D>,
input: LayoutEndInput,
) -> Result<LayoutActivityRecord> {
let _guard = self.lock.lock().map_err(|_| Error::native())?;
let (mut entries, records) = self.reconciled(updates)?;
if !entries.contains_key(&input.id) {
return Err(not_found());
}
if let EndPolicy::After { .. } = input.policy {
return Err(Error::new(
"UNSUPPORTED_FEATURE",
"Android does not support delayed activity dismissal",
));
}
if let Some(snapshot) = input.snapshot {
self.replace(updates, &mut entries, &records, &input.id, snapshot)?;
}
let record = updates
.end(&input.id, android_liveupdate::end_policy(input.policy))
.map_err(android_liveupdate::error)?;
let entry = entries.get(&input.id).ok_or_else(not_found)?;
Ok(layout_record(&record, entry))
}
pub(crate) fn list(
&self,
updates: &liveupdate::LiveUpdate<D>,
) -> Result<Vec<LayoutActivityRecord>> {
let _guard = self.lock.lock().map_err(|_| Error::native())?;
let (entries, records) = self.reconciled(updates)?;
Ok(records
.iter()
.filter_map(|record| {
entries
.get(&record.id)
.map(|entry| layout_record(record, entry))
})
.collect())
}
pub(crate) fn taps(&self, updates: &liveupdate::LiveUpdate<D>) -> Result<Vec<ActionEvent>> {
let _guard = self.lock.lock().map_err(|_| Error::native())?;
let entries = self.store.load().unwrap_or_default();
let batch = updates.events().map_err(android_liveupdate::error)?;
Ok(batch
.events
.into_iter()
.filter_map(|event| match event.kind {
liveupdate::EventKind::Action { action_id } => {
let entry = entries.get(&event.activity_id);
if entry.is_some_and(|entry| {
!declares(&entry.origin.layout.lock_screen, &action_id)
}) {
return None;
}
Some(ActionEvent {
action_id,
activity_key: entry.map(|entry| entry.origin.activity_key.clone()),
activity_id: event.activity_id,
})
}
_ => None,
})
.collect())
}
fn replace(
&self,
updates: &liveupdate::LiveUpdate<D>,
entries: &mut Entries,
records: &[liveupdate::ActivityRecord],
id: &str,
snapshot: LayoutSnapshot,
) -> Result<liveupdate::ActivityRecord> {
let entry = entries.get(id).ok_or_else(not_found)?;
entry.origin.validate_update(&LayoutUpdateInput {
id: id.to_owned(),
snapshot: snapshot.clone(),
})?;
let current = records
.iter()
.find(|record| record.id == id && running(record))
.ok_or_else(not_found)?;
if snapshot.revision < entry.snapshot.revision {
return Err(Error::new(
"STALE_REVISION",
"the revision is below the accepted one",
));
}
if snapshot.revision == entry.snapshot.revision {
return if snapshot == entry.snapshot {
Ok(current.clone())
} else {
Err(Error::new(
"CONFLICT",
"the accepted revision has other values",
))
};
}
let projection = self.project(&entry.origin, &snapshot, current.template);
let record = updates
.update(id, projection.snapshot)
.map_err(android_liveupdate::error)?;
let entry = Entry {
origin: entry.origin.clone(),
snapshot,
degraded: projection.degraded,
};
entries.insert(id.to_owned(), entry);
self.store.save(entries)?;
Ok(record)
}
fn reconciled(
&self,
updates: &liveupdate::LiveUpdate<D>,
) -> Result<(Entries, Vec<liveupdate::ActivityRecord>)> {
let records: Vec<_> = updates
.list()
.map_err(android_liveupdate::error)?
.into_iter()
.filter(|record| record.schema_version == 2)
.collect();
let stored = self.store.load()?;
let entries: Entries = records
.iter()
.filter_map(|record| {
let pending = || {
running(record)
.then(|| stored.get(&format!("{PENDING}{}", record.activity_key)))
.flatten()
};
stored
.get(&record.id)
.or_else(pending)
.map(|entry| (record.id.clone(), entry.clone()))
})
.collect();
if entries != stored {
self.store.save(&entries)?;
}
Ok((entries, records))
}
fn project(
&self,
input: &LayoutStartInput,
snapshot: &LayoutSnapshot,
template: liveupdate::Template,
) -> android_layout::Projection {
let image = |name: &str| self.image(name);
let environment = Environment {
app_name: &self.settings.app_name,
samsung_now_bar: self.settings.samsung_now_bar,
image: &image,
};
android_layout::project(
&input.layout,
input.styles.is_some(),
snapshot,
template,
&environment,
)
}
fn image(&self, name: &str) -> Option<String> {
let folder = &self.settings.image_folder;
let path = self.settings.files.as_ref()?.join(folder).join(name);
let metadata = fs::metadata(&path).ok()?;
if !metadata.is_file() || metadata.len() > MAX_ICON_BYTES {
return None;
}
let (width, height) = png_size(&path)?;
(1..=MAX_ICON_SIDE).contains(&width).then_some(())?;
(1..=MAX_ICON_SIDE).contains(&height).then_some(())?;
Some(format!("{folder}/{name}"))
}
}
fn png_size(path: &std::path::Path) -> Option<(u32, u32)> {
let mut header = [0_u8; 24];
fs::File::open(path).ok()?.read_exact(&mut header).ok()?;
if header[..8] != *b"\x89PNG\r\n\x1a\n" || header[12..16] != *b"IHDR" {
return None;
}
let width = u32::from_be_bytes(header[16..20].try_into().ok()?);
let height = u32::from_be_bytes(header[20..24].try_into().ok()?);
Some((width, height))
}
fn declares(node: &Node, action_id: &str) -> bool {
match &node.element {
Element::Button {
action_id: id,
child,
} => id == action_id || declares(child, action_id),
Element::Vstack { children, .. }
| Element::Hstack { children, .. }
| Element::Zstack { children, .. } => {
children.iter().any(|child| declares(child, action_id))
}
_ => false,
}
}
fn running(record: &liveupdate::ActivityRecord) -> bool {
!matches!(
record.state,
liveupdate::ActivityState::Ended | liveupdate::ActivityState::Dismissed
)
}
fn visibility(input: &LayoutStartInput) -> liveupdate::Visibility {
match input.android.as_ref().map(|android| android.visibility) {
Some(AndroidVisibility::Public) => liveupdate::Visibility::Public,
Some(AndroidVisibility::Secret) => liveupdate::Visibility::Secret,
_ => liveupdate::Visibility::Private,
}
}
fn layout_record(record: &liveupdate::ActivityRecord, entry: &Entry) -> LayoutActivityRecord {
LayoutActivityRecord {
id: record.id.clone(),
activity_key: record.activity_key.clone(),
schema_version: 2,
snapshot: entry.snapshot.clone(),
backend: Backend::AndroidNotification,
state: android_liveupdate::activity_state(record.state),
visibility: Visibility::Unknown,
degraded_features: record
.degraded_features
.iter()
.chain(&entry.degraded)
.cloned()
.collect(),
promotion_requested: record.promotion_requested,
promotion_state: android_liveupdate::promotion_state(record.promotion_state),
}
}
fn not_found() -> Error {
Error::new("NOT_FOUND", "no layout activity has this id")
}
#[cfg(test)]
#[path = "layouts_tests.rs"]
mod tests;