Skip to main content

paperpaw_plugin_store/
lib.rs

1//! The plugin store: the plugins of a plugin library (paperpaw.org's by
2//! default) for this device, by group as the website shows them, with a
3//! search, each with a page to install, update or remove it (ADR 0023).
4//! Fonts are one more entry, which opens the fonts browser where it is
5//! installed.
6//!
7//! The list is read as it streams into an index kept on the storage, so
8//! it may be as long as it likes; a plugin's files go straight to the
9//! storage, one after another, each checked ([`paperpaw_sdk::install`]).
10//! Plugins with code are listed where PaperPaw loads them and a build
11//! fits; their code is checked whole and signed by its author (`trust`,
12//! ADR 0024). Built-in plugins are not listed, nor a plugin that would
13//! take the place of one: those come with the firmware.
14
15#![no_std]
16
17extern crate alloc;
18
19mod catalog;
20mod fetch;
21mod letters;
22mod list;
23mod needs;
24mod origin;
25mod page;
26mod queue;
27mod request;
28mod requires;
29mod revoked;
30mod room;
31mod rows;
32mod setup;
33mod shots;
34mod source;
35mod styles;
36mod trust;
37mod view;
38
39use alloc::borrow::Cow;
40use alloc::boxed::Box;
41
42use paperpaw_sdk::builtin::{events, groups, menus, params};
43use paperpaw_sdk::event::Event;
44use paperpaw_sdk::install::{Installer, Progress, Received};
45use paperpaw_sdk::replies::HttpReply;
46use paperpaw_sdk::setting::Setting;
47use paperpaw_sdk::{
48    Arg, Command, Commands, Env, FixedAction, FixedScreen, Id, Manifest, MenuEntry, Params, Plugin,
49    RegisterError, Registrar, SettingSpec,
50};
51use trust::Verdict;
52
53pub const PLUGIN: Id = Id::new_static("store");
54/// Opens the store.
55pub const OPEN: Id = Id::new_static("store.open");
56const LIST_SCREEN: Id = Id::new_static("store.list");
57const PAGE_SCREEN: Id = Id::new_static("store.plugin");
58const VIEW_SCREEN: Id = Id::new_static("store.view");
59const SOURCE_SCREEN: Id = Id::new_static("store.source");
60const SHOTS_SCREEN: Id = Id::new_static("store.shots");
61const FETCH_SCREEN: Id = Id::new_static("store.fetch");
62const LETTERS_SCREEN: Id = Id::new_static("store.letters");
63/// The fonts browser's list, offered as the entry *Fonts*.
64pub(crate) const FONTS: Id = Id::new_static("fonts-browser.open");
65/// Fonts with larger sizes, from the reading settings: the fonts browser,
66/// or its page here where it is not installed (a store plugin on lean
67/// firmware).
68pub const DISCOVER_FONTS: Id = Id::new_static("store.discover-fonts");
69/// The plugin manager's list of other places to get plugins.
70const MANAGER_MORE: Id = Id::new_static("plugin-manager.more");
71
72/// Where the list of plugins comes from.
73pub const CATALOG: Setting<paperpaw_sdk::setting::Text> = Setting::new("store.catalog");
74
75/// Whether the store lists community plugins too: published by their
76/// authors from GitHub, which nobody reviewed (off unless set).
77pub const COMMUNITY: Setting<bool> = Setting::new("store.community");
78
79/// The plugin library's address, for developers and libraries of one's
80/// own; and whether it lists community plugins, guarded: no other
81/// plugin's defaults, presets or commands switch it on.
82static SETTINGS: [SettingSpec; 2] = [
83    SettingSpec::text(
84        CATALOG.static_str(),
85        "store.setting.catalog",
86        catalog::OFFICIAL_LIST,
87        groups::DEVELOPER,
88    )
89    .description("store.setting.catalog.help"),
90    SettingSpec::switch(
91        COMMUNITY.static_str(),
92        "store.setting.community",
93        false,
94        groups::SYSTEM,
95    )
96    .description("store.setting.community.help")
97    .guarded(),
98];
99
100/// Whether the reader asked for community plugins too.
101pub(crate) fn community(env: &Env<'_>) -> bool {
102    env.settings().read(&COMMUNITY)
103}
104
105/// The answer to a file's download.
106const DOWNLOADED: Event<HttpReply> = Event::new("store.downloaded");
107
108/// Installs plugins; its job is kept in this plugin's folder.
109pub(crate) const INSTALLER: Installer = Installer::new(PLUGIN, DOWNLOADED);
110
111/// The plugin store.
112#[derive(Debug, Default)]
113pub struct Store;
114
115/// How it works, by language (see `Manifest::how`).
116static HOW: [(&str, &str); 2] = [
117    ("en", include_str!("../how/en.txt")),
118    ("de", include_str!("../how/de.txt")),
119];
120
121static ACTIONS: [FixedAction; 2] = [
122    FixedAction::new(OPEN, "store.title")
123        .handler(|_, _, out| out.push(Command::OpenScreen(LIST_SCREEN, Params::new()))),
124    FixedAction::new(DISCOVER_FONTS, "store.discover-fonts").handler(|env, _, out| {
125        if env.actions().contains(FONTS.as_str()) {
126            out.push(Command::run(FONTS));
127        } else {
128            let page = Params::new().with(params::ID, "fonts-browser");
129            out.push(Command::OpenScreen(PAGE_SCREEN, page));
130        }
131    }),
132];
133static ENTRIES: [MenuEntry; 3] = [
134    // With the tools, and in the plugin manager.
135    MenuEntry::new(menus::TOOLS, OPEN).order(90),
136    MenuEntry::new(MANAGER_MORE, OPEN).order(10),
137    // On the page of the text, below the font size, whose largest
138    // sizes are the font's.
139    MenuEntry::new(groups::READING_TEXT, DISCOVER_FONTS),
140];
141static ICONS: [(Id, &str); 2] = [(OPEN, "cloud-download"), (DISCOVER_FONTS, "typography")];
142
143static SCREENS: [FixedScreen; 7] = [
144    FixedScreen::new(PAGE_SCREEN, "store.title", |env, params| {
145        Box::new(page::PageScreen::new(env, params))
146    }),
147    FixedScreen::new(LETTERS_SCREEN, "store.letter", |env, params| {
148        Box::new(letters::LettersScreen::new(env, params))
149    }),
150    FixedScreen::new(VIEW_SCREEN, "store.title", |env, params| {
151        Box::new(view::ViewScreen::new(env, params))
152    }),
153    FixedScreen::new(SOURCE_SCREEN, "store.source", |env, params| {
154        Box::new(source::SourceScreen::new(env, params))
155    }),
156    FixedScreen::new(FETCH_SCREEN, "store.fetch.title", |env, params| {
157        Box::new(fetch::FetchScreen::new(env, params))
158    })
159    .instances(paperpaw_sdk::Instances::SINGLE),
160    FixedScreen::new(SHOTS_SCREEN, "store.shots", |env, params| {
161        Box::new(shots::ShotsScreen::new(env, params))
162    }),
163    FixedScreen::new(LIST_SCREEN, "store.title", |env, _| {
164        Box::new(list::ListScreen::new(env))
165    })
166    .instances(paperpaw_sdk::Instances::SINGLE),
167];
168
169impl Plugin for Store {
170    fn manifest(&self) -> Manifest {
171        Manifest::new(PLUGIN, "Plugin store", paperpaw_sdk::package_version!())
172            .description("Finds, installs, updates and removes plugins for this device.")
173            .how(&HOW)
174            .uses(paperpaw_sdk::Uses::NETWORK)
175    }
176
177    fn register(&self, r: &mut Registrar) -> Result<(), RegisterError> {
178        r.add_settings(&SETTINGS)?;
179        r.add_screens(&SCREENS)?;
180        r.add_actions(&ACTIONS)?;
181        r.add_menu_entries(&ENTRIES)?;
182        r.add_icons(&ICONS)?;
183        // Downloads go on while no screen of the store is open; one cut
184        // off by a restart is begun anew from the plugin's page.
185        r.on(DOWNLOADED, received)?;
186        r.on(queue::FETCHED, queue::fetched)?;
187        // The first-run setup's offer of the plugins most readers add.
188        setup::register(r)?;
189        // Plugins another plugin asks for (the reader's packs of letters).
190        request::register(r)?;
191        r.on(events::STARTED, |env, _, out| {
192            // A download cut off by the restart is begun anew from its
193            // page, or first when the queue goes on.
194            queue::interrupted(env);
195            INSTALLER.cancel(env.storage());
196            // The setup's plugins go on without the store being opened:
197            // the reader asked for them.
198            if queue::has_quiet(env) {
199                queue::next(env, out);
200            }
201            // The faces of Literata the firmware leaves out, fetched once.
202            styles::offer(env, out);
203        })?;
204        r.add_translations(Cow::Borrowed(include_str!("../i18n/en.ini")))?;
205        r.add_translations(Cow::Borrowed(include_str!("../i18n/de.ini")))?;
206        Ok(())
207    }
208}
209
210/// A file arrived (or did not): once all are here, the plugin installed
211/// if it may be (see [`trust`]), and said; then the next update waiting
212/// in the queue ([`queue`]) has its turn.
213fn received(env: &Env<'_>, reply: &HttpReply, out: &mut Commands) {
214    let mut said = paperpaw_sdk::Commands::new();
215    // Plugins put in quietly by the first-run setup ask for nothing more;
216    // those another plugin asked for may (a chain of requirements).
217    let quiet = queue::quiet(env) && !queue::requested(env);
218    let mut required = alloc::vec::Vec::new();
219    let installed = match INSTALLER.received(env, reply, out) {
220        Received::Complete(done) => {
221            // Read before it is put in its place.
222            let folder = INSTALLER.folder(env.storage()).unwrap_or_default();
223            required = requires::missing(env, &folder, &done.plugin);
224            (finish(env, &done, &mut said), done.name, done.plugin)
225        }
226        Received::Failed(job) => {
227            said.push(failed(env, &job.name));
228            (false, job.name, job.plugin)
229        }
230        Received::Next(_) | Received::Other => return,
231        _ => return,
232    };
233    // Plugins another plugin asked for: told to it, not said here.
234    if queue::requested(env) {
235        request::outcome(env, &installed.2, installed.0);
236        out.extend(
237            said.into_iter()
238                .filter(|c| !matches!(c, Command::Notify(_))),
239        );
240    // A quiet queue (the first-run setup's) says it all once, at its end:
241    // its notices wait, what installs goes on.
242    } else if queue::quiet(env) {
243        queue::note(env, &installed.1, installed.0);
244        out.extend(
245            said.into_iter()
246                .filter(|c| !matches!(c, Command::Notify(_))),
247        );
248    } else {
249        out.extend(said);
250    }
251    queue::next(env, out);
252    // What the plugin installed requires, and the device lacks, is offered.
253    if installed.0 && !quiet {
254        requires::offer(required, out);
255    }
256}
257
258/// Installs the plugin all of whose files are here, if it may be, and
259/// says so; whether it was installed.
260fn finish(env: &Env<'_>, done: &Progress, out: &mut Commands) -> bool {
261    let name = [("name", Arg::Str(&done.name))];
262    let folder = INSTALLER.folder(env.storage()).unwrap_or_default();
263    let (key, installed) = match trust::verdict(env, &done.plugin, &folder) {
264        Verdict::Install { code } => {
265            let before = env.plugins().get(&done.plugin).is_some();
266            if trust::install(env, code, out).is_none() {
267                INSTALLER.cancel(env.storage());
268                out.push(failed(env, &done.name));
269                return false;
270            }
271            let key = match (code.is_some(), before) {
272                (true, true) => "store.updated-code",
273                (true, false) => "store.installed-code",
274                (false, true) => "store.updated",
275                (false, false) => "store.installed",
276            };
277            (key, true)
278        }
279        Verdict::Refused(refusal) => {
280            INSTALLER.cancel(env.storage());
281            (trust::refusal_key(env, refusal), false)
282        }
283    };
284    out.push(Command::Notify(env.i18n().format(key, &name)));
285    installed
286}
287
288fn failed(env: &Env<'_>, name: &str) -> Command {
289    Command::Notify(
290        env.i18n()
291            .format("store.failed", &[("name", Arg::Str(name))]),
292    )
293}
294
295#[cfg(test)]
296mod tests {
297    use paperpaw_i18n::{Catalog, check};
298
299    #[test]
300    fn translations_are_complete() {
301        let en = Catalog::parse(include_str!("../i18n/en.ini")).unwrap();
302        let de = Catalog::parse(include_str!("../i18n/de.ini")).unwrap();
303        let issues = check::compare(&en, &de);
304        assert!(issues.is_empty(), "{issues:?}");
305    }
306}