git clone https://garage44.eu/jeroen/pinnacle.git.. /programs/src/bin/store.rs
//! The Store: the apps its package sources offer over HTTP, each with
//! Install, Update or Open, its description and what it may do; an app
//! installed from them has Uninstall too, which asks once more and whether
//! its data goes with it. The apps installed that the sources no longer
//! offer (or all of them, with no network) are listed after, to be
//! uninstalled. The sources, the catalogs, installing and uninstalling are
//! `pinnacle_ui::store`'s, which the updates service shares; this is the
//! page.
#![no_std]
#![no_main]
extern crate alloc;
use alloc::string::String;
use pinnacle_gfx::Rect;
use pinnacle_locale::{fill, t, tf, tr};
use pinnacle_ui::icons::{self, Icons};
use pinnacle_ui::store::{
Action, Installed, Offer, action, catalog, data_folders, data_size, install, removable_apps, size,
uninstall,
};
use pinnacle_ui::{App, Event};
use pinnacle_view::{IntoView, Screen, Signal, View, el, signal};
/// What a tap asked for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tap {
/// The offer's own button: Install, Update or Open.
Offer(usize),
/// Uninstall, for the installed app at this place in the list of them:
/// the choice of what to do with its data comes next.
Uninstall(usize),
/// Uninstalled, its data removed with it.
RemoveData,
/// Uninstalled, its data kept.
KeepData,
Cancel,
}
/// What the page shows.
struct Shown<'a> {
offers: Option<&'a [Offer]>,
/// The apps installed from a package source, which may be uninstalled.
removable: &'a [Installed],
/// The offer being installed.
busy: Option<usize>,
/// What was installed or uninstalled, or how far an install is.
note: &'a str,
/// The installed app whose Uninstall was tapped.
asking: Option<usize>,
}
/// A button that puts `tap` in `tapped`, named for `cargo xtask`.
fn button(
label: &str,
name: String,
variant: Option<&'static str>,
tap: Tap,
tapped: &Signal<Option<Tap>>,
) -> View {
let tapped = tapped.clone();
el("button")
.class("m-button")
.attr("type", "button")
.attr("data-variant", variant)
.attr("data-name", name)
.on("click", move |_| tapped.set(Some(tap)))
.child(String::from(label))
.into_view()
}
/// A row of the list: the app's icon, its title, what is said of it, and
/// its buttons last.
fn app_row(name: &str, title: &str, lines: &[String], buttons: View) -> View {
let mut body = el("span")
.class("m-list-item__body")
.child(el("span").class("m-list-item__title").child(String::from(title)));
for line in lines.iter().filter(|l| !l.is_empty()) {
body = body.child(el("span").class("m-list-item__sub").child(line.clone()));
}
el("div")
.class("m-list-item")
.attr("role", "listitem")
.attr("style", "align-items: center; gap: 16px")
.child(
// Its icon, the same as on the home screen.
el("canvas")
.attr("data-name", icons::canvas_name(name, title))
.attr("style", "flex: none; width: 48px; height: 48px; display: block"),
)
.child(body)
.child(buttons)
.into_view()
}
/// The question Uninstall asks: whether the app's data goes with it, when
/// it has any.
fn question(app: &Installed, tapped: &Signal<Option<Tap>>) -> View {
let has_data = !data_folders(&app.name).is_empty();
let question = if has_data {
let ask =
t("Uninstall {}? Its data ({}) can go with it, or stay in Files for when you install it again.");
fill(ask, &[&app.title, &size(data_size(&app.name))])
} else {
tf("Uninstall {}? It keeps no data.", &[&app.title])
};
let mut bar = el("div")
.attr("role", "alertdialog")
.attr(
"style",
"display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 12px; \
border-radius: 12px; background: var(--m-surface)",
)
.child(el("span").attr("style", "flex: 1 1 100%").child(question));
bar = if has_data {
bar.child(button(
t("Uninstall and remove its data"),
"uninstall-remove-data".into(),
Some("danger"),
Tap::RemoveData,
tapped,
))
.child(button(
t("Uninstall, keep its data"),
"uninstall-keep-data".into(),
None,
Tap::KeepData,
tapped,
))
} else {
bar.child(button(
t("Uninstall"),
"uninstall-remove-data".into(),
Some("danger"),
Tap::RemoveData,
tapped,
))
};
bar.child(button(
t("Cancel"),
"uninstall-cancel".into(),
Some("ghost"),
Tap::Cancel,
tapped,
))
.into_view()
}
/// The page: the title, a line of news (what was installed, how far an
/// install is), the question Uninstall asks, a row for each app offered,
/// then the apps installed that no source offers now.
fn page(s: &Shown, tapped: &Signal<Option<Tap>>) -> View {
let mut main = el("main")
.attr(
"style",
"max-width: 760px; margin: 0 auto; padding: 24px 16px 32px; \
display: flex; flex-direction: column; gap: 12px",
)
.child(
el("h1")
.attr("style", "font-size: 30px; margin: 16px 0 0")
.child(t("Store")),
)
.child(
el("p")
.attr("role", "status")
.attr("style", "margin: 0; color: var(--m-text-dim)")
.child(String::from(s.note)),
);
if let Some(app) = s.asking.and_then(|j| s.removable.get(j)) {
main = main.child(question(app, tapped));
}
let uninstall_button = |name: &str| {
let j = s.removable.iter().position(|a| a.name == name)?;
let disabled = s.busy.is_some();
let tapped = tapped.clone();
Some(
el("button")
.class("m-button")
.attr("type", "button")
.attr("data-variant", "ghost")
.attr("data-name", alloc::format!("uninstall-{name}"))
.attr("disabled", disabled.then_some(""))
.on("click", move |_| tapped.set(Some(Tap::Uninstall(j))))
.child(t("Uninstall")),
)
};
match s.offers {
None => {
main = main.child(
el("p")
.attr(
"style",
"margin: 48px 0; text-align: center; color: var(--m-text-dim)",
)
.child(t("No package source: no network, or it does not answer")),
);
}
Some(offers) => {
let mut list = el("div").class("m-list").attr("role", "list");
for (i, offer) in offers.iter().enumerate() {
let (label, variant) = if s.busy == Some(i) {
(t("Installing…"), None)
} else {
match action(offer) {
Action::Open => (t("Open"), None),
Action::Update => (t("Update"), Some("primary")),
Action::Install => (t("Install"), Some("primary")),
}
};
let meta = fill(
t("Version {} · {} · {}"),
&[&offer.version, &size(offer.size), &offer.rights.describe()],
);
let tapped = tapped.clone();
let mut buttons = el("div")
.attr(
"style",
"flex: none; display: flex; flex-direction: column; gap: 8px",
)
.child(
el("button")
.class("m-button")
.attr("type", "button")
.attr("data-variant", variant)
.attr("data-name", alloc::format!("offer-{i}"))
.attr("disabled", (s.busy == Some(i)).then_some(""))
.on("click", move |_| tapped.set(Some(Tap::Offer(i))))
.child(label),
);
if action(offer) != Action::Install
&& let Some(b) = uninstall_button(&offer.name)
{
buttons = buttons.child(b);
}
list = list.child(app_row(
&offer.name,
&offer.title,
&[offer.description.clone(), meta],
buttons.into_view(),
));
}
main = main.child(list);
}
}
// What no source offers now: still installed, and only to be removed.
let offered = |name: &str| s.offers.is_some_and(|o| o.iter().any(|offer| offer.name == name));
let others: alloc::vec::Vec<&Installed> = s.removable.iter().filter(|a| !offered(&a.name)).collect();
if !others.is_empty() {
main = main.child(
el("h2")
.attr(
"style",
"font-size: 16px; margin: 12px 0 0; color: var(--m-text-dim); font-weight: 600",
)
.child(if s.offers.is_some() {
t("Installed, not offered now")
} else {
t("Installed from the Store")
}),
);
let mut list = el("div").class("m-list").attr("role", "list");
for app in others {
let Some(b) = uninstall_button(&app.name) else {
continue;
};
list = list.child(app_row(
&app.name,
&app.title,
&[app.description.clone(), tf("Version {}", &[&app.version])],
b.into_view(),
));
}
main = main.child(list);
}
main.into_view()
}
/// Mounts the page afresh and draws all of it.
fn show(app: &mut App, screen: &mut Screen, shown: &Shown, tapped: &Signal<Option<Tap>>, icons: &mut Icons) {
screen.resize(app.width, app.height);
screen.clear();
screen.mount(page(shown, tapped));
draw(screen, app, icons, true);
app.present_all();
screen.announce("store: button ");
}
/// Draws the screen, each app's icon into its canvas.
fn draw(screen: &mut Screen, app: &mut App, icons: &mut Icons, all: bool) -> Option<Rect> {
screen.draw_with(&mut app.canvas(), all, &mut |name, canvas, rect| {
icons.draw_canvas(canvas, rect, name)
})
}
/// Uninstalls `app`, its data too when `data`, unless it is running: its
/// files are not taken from under it. What happened, said.
fn uninstall_app(app: &Installed, data: bool) -> String {
let title = app.title.as_str();
// Without the display server to ask, it is taken to run.
let display = pinnacle_rt::connect("display");
if display
.as_ref()
.is_none_or(|d| pinnacle_ui::running(d, &app.name))
{
pinnacle_rt::println!("store: {title} is running: not uninstalled");
return tf("{} is open: close it first, then uninstall it", &[title]);
}
let had_data = !data_folders(&app.name).is_empty();
match uninstall(&app.name, data) {
Err(why) => {
pinnacle_rt::println!("store: {title} was not uninstalled: {why}");
tf("{} was not uninstalled: {}", &[title, tr(why)])
}
Ok(()) => {
let left = !data_folders(&app.name).is_empty();
pinnacle_rt::println!(
"store: {title} is uninstalled, {}",
match (had_data, data, left) {
(false, ..) => "it had no data",
(true, true, false) => "its data removed",
(true, true, true) => "its data not all removed",
(true, false, _) => "its data kept",
}
);
match (had_data, data, left) {
(false, ..) => tf("{} is uninstalled", &[title]),
(true, true, false) => tf("{} is uninstalled, and its data removed", &[title]),
(true, true, true) => fill(
t("{} is uninstalled, but not all its data could be removed: Files shows what is left"),
&[title],
),
(true, false, _) => fill(
t("{} is uninstalled; its data stays in Files, under Apps' folders"),
&[title],
),
}
}
}
}
/// What the Store says when it opens, by what the sources offer.
fn opening_note(offers: Option<&[Offer]>) -> String {
String::from(match offers {
Some([]) => t("The package sources offer nothing"),
Some(_) => t("From the package sources, over the network"),
None => "",
})
}
#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
let mut app = App::new("Store");
let mut screen = Screen::new(app.width, app.height);
let tapped: Signal<Option<Tap>> = signal(None);
let mut icons = Icons::new();
let mut offers = catalog();
let mut removable = removable_apps();
let mut note = opening_note(offers.as_deref());
let mut asking: Option<usize> = None;
macro_rules! shown {
($busy:expr, $note:expr) => {
Shown {
offers: offers.as_deref(),
removable: &removable,
busy: $busy,
note: $note,
asking,
}
};
}
show(&mut app, &mut screen, &shown!(None, ¬e), &tapped, &mut icons);
loop {
match app.next_event(None) {
Event::Shown(true) | Event::Resized => {
offers = catalog();
removable = removable_apps();
asking = None;
show(&mut app, &mut screen, &shown!(None, ¬e), &tapped, &mut icons);
}
Event::Preferences => {
screen.restyle();
show(&mut app, &mut screen, &shown!(None, ¬e), &tapped, &mut icons);
}
Event::Input(e) => {
screen.input(&e);
let Some(tap) = tapped.get_untracked() else {
if let Some(area) = draw(&mut screen, &mut app, &mut icons, false) {
app.present(area);
screen.announce("store: button ");
}
continue;
};
tapped.set(None);
match tap {
Tap::Uninstall(j) => asking = Some(j).filter(|&j| j < removable.len()),
Tap::Cancel => asking = None,
Tap::RemoveData | Tap::KeepData => {
if let Some(installed) = asking.take().and_then(|j| removable.get(j)) {
note = uninstall_app(installed, tap == Tap::RemoveData);
removable = removable_apps();
}
}
Tap::Offer(i) => {
asking = None;
let Some(list) = offers.as_deref() else { continue };
let Some(offer) = list.get(i) else { continue };
let action = action(offer);
if action == Action::Open {
app.launch(&offer.name);
continue;
}
// How far it is, shown at each whole percent.
let mut percent_shown = None;
let mut progress = |done: u64, total: u64| {
let percent = (done * 100).checked_div(total).unwrap_or(100);
if percent_shown != Some(percent) {
percent_shown = Some(percent);
let text = fill(
t("{}: {}% of {}"),
&[&offer.title, &alloc::format!("{percent}"), &size(total)],
);
let shown = Shown {
offers: Some(list),
removable: &removable,
busy: Some(i),
note: &text,
asking: None,
};
show(&mut app, &mut screen, &shown, &tapped, &mut icons);
}
};
let outcome = install(offer, &mut progress);
let title = offer.title.as_str();
// The log in English, for a demo to wait for; the page
// in the person's language.
let (log, said) = match (outcome, action == Action::Update) {
(Ok(()), true) => (
alloc::format!("{title} is updated to version {}", offer.version),
tf("{} is updated to version {}", &[title, &offer.version]),
),
(Ok(()), false) => (
alloc::format!("{title} is installed: it is on the home screen"),
tf("{} is installed: it is on the home screen", &[title]),
),
(Err(why), true) => (
alloc::format!("{title} was not updated: {why}"),
tf("{} was not updated: {}", &[title, tr(why)]),
),
(Err(why), false) => (
alloc::format!("{title} was not installed: {why}"),
tf("{} was not installed: {}", &[title, tr(why)]),
),
};
pinnacle_rt::println!("store: {log}");
note = said;
removable = removable_apps();
}
}
show(&mut app, &mut screen, &shown!(None, ¬e), &tapped, &mut icons);
}
Event::Closed => return 0,
_ => {}
}
}
}