garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/filer.rs

raw

//! Files: the person's folders, looked through by tapping. The first page
//! has the files and folders of their home (the data vault once it is open)
//! and each app's own folder, under the app's name; a folder opens with a
//! tap, a file too: its text, a picture (PNG, JPEG, GIF, WebP, told by its
//! first bytes and decoded by Wil) fitted to the pane, or that nothing here
//! opens it. An open
//! file is moved or copied into another folder (Move or Copy, then the
//! folder, then "Move here" or "Copy here"), renamed, or deleted once the
//! person says so a second time. A folder gets new folders in it, and one
//! the person made is renamed, or deleted with all in it after a second
//! tap; an app's own folder keeps its name, which its app looks for. What
//! the system keeps for itself (`p2p`: the device's identity, its messages
//! and contacts) is not shown: a tap must not lose who the device is.
//!
//! The file system has no renaming of its own: a rename is a copy under the
//! new name and the old one removed, a folder's a file at a time.
//!
//! It is a system program, as the Terminal is, because an app sees only its
//! own folder (`app:`); the file commands (`files.rs`) do the same by typing.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;

use pinnacle_gfx::{Canvas, Rect};
use pinnacle_locale::{fill, t, tf};
use pinnacle_media::picture::{self, Picture};
use pinnacle_rt::fs;
use pinnacle_ui::command::{copy_file, home, size, when};
use pinnacle_ui::layout::notes;
use pinnacle_ui::{App, Event, theme};
use pinnacle_view::{Clipboard, IntoView, Screen, Signal, View, el, signal};

/// The most of a file shown when it is opened.
const SHOW_MAX: usize = 64 * 1024;
/// In the home folder, kept by the system and not shown: the apps' folders
/// (shown under their apps' names instead) and the p2p service's.
const KEPT: [&str; 2] = ["apps", "p2p"];
/// The longest name the data disk keeps, in bytes.
const NAME_MAX: usize = 58;
/// The style of a bar above a page's rows: what is being moved, a name
/// being typed.
const BAR: &str = "display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 12px; \
                   border-radius: 12px; background: var(--m-surface)";
/// The style of a line of buttons, which wraps on a narrow window.
const ACTIONS: &str = "display: flex; flex-wrap: wrap; align-items: center; gap: 8px";

/// A file or folder on a page.
#[derive(Clone)]
struct Entry {
    path: String,
    /// What the row says: its name, or for an app's folder the app's title.
    label: String,
    folder: bool,
    size: u64,
    modified: u64,
}

/// A folder being looked at: where it is and what it is called.
#[derive(Clone)]
struct Place {
    path: String,
    label: String,
    /// An app's own folder, opened from the first page: its app finds it by
    /// its name, so it is not renamed or deleted here.
    app: bool,
}

/// Where the apps' own folders are: in the vault once it is open, else on
/// the system disk (as the kernel's `app_folder` has it).
fn apps_folder() -> &'static str {
    if fs::disk("data").is_some() {
        "data:/apps"
    } else {
        "system:/data"
    }
}

/// The first page is the person's home with the apps' folders in it; on the
/// system disk (no vault yet) only the apps' folders, since the rest there
/// is the system's.
fn home_is_theirs() -> bool {
    home() == "data:/"
}

fn join(folder: &str, name: &str) -> String {
    if folder.ends_with('/') {
        alloc::format!("{folder}{name}")
    } else {
        alloc::format!("{folder}/{name}")
    }
}

fn base(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path)
}

fn entry(path: String, label: String) -> Option<Entry> {
    let stat = fs::stat(&path)?;
    Some(Entry {
        path,
        label,
        folder: stat.directory,
        size: stat.size,
        modified: stat.modified,
    })
}

/// What is in `folder`: folders first, then files, each by name.
fn list(folder: &str, skip: &[&str]) -> Vec<Entry> {
    let mut entries: Vec<Entry> = fs::list(folder)
        .unwrap_or_default()
        .into_iter()
        .map(|name| String::from(name.trim_end_matches('/')))
        .filter(|name| !skip.contains(&name.as_str()))
        .filter_map(|name| entry(join(folder, &name), name))
        .collect();
    entries.sort_by(|a, b| (!a.folder, &a.label).cmp(&(!b.folder, &b.label)));
    entries
}

/// Each installed app's own folder, under the app's title, by title.
fn app_folders() -> Vec<Entry> {
    let mut folders: Vec<Entry> = list(apps_folder(), &[])
        .into_iter()
        .filter(|e| e.folder)
        .map(|mut e| {
            let manifest =
                fs::read_string(&alloc::format!("system:/apps/{}/manifest", e.label)).unwrap_or_default();
            e.label = fs::field(&manifest, "title")
                .map(String::from)
                .unwrap_or_else(|| theme::display_name(&e.label));
            e
        })
        .collect();
    folders.sort_by(|a, b| a.label.cmp(&b.label));
    folders
}

/// Why `name` cannot be a file's or folder's name, if it cannot.
fn bad_name(name: &str) -> Option<&'static str> {
    if name.is_empty() {
        Some(t("Type a name first"))
    } else if name.contains('/') || name.contains(':') || name == "." || name == ".." {
        Some(t("A name cannot have / or : in it, nor be . or .."))
    } else if name.len() > NAME_MAX {
        Some(t("That name is too long"))
    } else {
        None
    }
}

/// The folder `from` and all in it copied to `to`, which is not there yet.
/// What was made of `to` is removed again when a part could not be copied.
fn copy_folder(from: &str, to: &str) -> bool {
    fn walk(from: &str, to: &str) -> bool {
        fs::create_dir(to)
            && fs::list(from).unwrap_or_default().iter().all(|name| {
                let child = name.trim_end_matches('/');
                let (from, to) = (join(from, child), join(to, child));
                if name.ends_with('/') {
                    walk(&from, &to)
                } else {
                    copy_file(&from, &to).is_ok()
                }
            })
    }
    let copied = walk(from, to);
    if !copied {
        fs::remove(to);
    }
    copied
}

/// `from` (a file, or with `folder` a folder and all in it) named `name`
/// in `parent`, the folder it is in: copied under the new name, then the
/// old one removed. The new path, or what went wrong.
fn rename(from: &str, parent: &str, name: &str, folder: bool) -> Result<String, String> {
    let to = join(parent, name);
    if fs::exists(&to) {
        return Err(tf("There is a {} here already", &[name]));
    }
    let copied = if folder {
        copy_folder(from, &to)
    } else {
        copy_file(from, &to).is_ok()
    };
    if !copied {
        fs::remove(&to);
        return Err(tf("{} could not be renamed", &[base(from)]));
    }
    if !fs::remove(from) {
        return Err(tf("{} made, but {} could not be taken away", &[name, base(from)]));
    }
    Ok(to)
}

/// A name for a copy of `name` in `folder` that nothing there has yet: the
/// name itself, else "list copy.txt", "list copy 2.txt", and on.
fn free_name(folder: &str, name: &str) -> String {
    if !fs::exists(&join(folder, name)) {
        return name.into();
    }
    let (stem, ext) = match name.rfind('.') {
        Some(at) if at > 0 => (&name[..at], &name[at..]),
        _ => (name, ""),
    };
    let word = t("copy");
    (1u32..)
        .map(|n| match n {
            1 => alloc::format!("{stem} {word}{ext}"),
            n => alloc::format!("{stem} {word} {n}{ext}"),
        })
        .find(|candidate| !fs::exists(&join(folder, candidate)))
        .unwrap_or_default()
}

/// A page's rows: the folder's entries, and on the first page the apps'
/// folders after the person's own.
struct Page {
    own: Vec<Entry>,
    apps: Vec<Entry>,
}

fn page_of(place: &Place, first: bool) -> Page {
    if first {
        let own = if home_is_theirs() {
            list(&place.path, &KEPT)
        } else {
            Vec::new()
        };
        Page {
            own,
            apps: app_folders(),
        }
    } else {
        Page {
            own: list(&place.path, &[]),
            apps: Vec::new(),
        }
    }
}

/// An opened file, as shown.
enum Shown {
    Text(String, bool),
    Picture,
    /// Neither text nor a picture: nothing here opens it.
    Nothing,
    Unreadable,
}

fn show(e: &Entry) -> Shown {
    let Some(data) = fs::read_at(&e.path, 0, (e.size as usize).min(SHOW_MAX)) else {
        return Shown::Unreadable;
    };
    if picture::sniff(&data).is_some() {
        return Shown::Picture;
    }
    match core::str::from_utf8(&data) {
        Ok(text) if !text.contains('\0') => Shown::Text(text.into(), e.size as usize > SHOW_MAX),
        // Cut mid-character at the limit: what came before it.
        Err(err) if err.error_len().is_none() && e.size as usize > SHOW_MAX => {
            let text = core::str::from_utf8(&data[..err.valid_up_to()]).unwrap_or_default();
            Shown::Text(text.into(), true)
        }
        _ => Shown::Nothing,
    }
}

/// The opened picture, decoded once: which file it is (its path, size and
/// change), and the picture or why it could not be shown.
type Decoded = ((String, u64, u64), Result<Picture, ()>);

/// The picture in `e`, a file that starts like one.
fn decode(e: &Entry) -> Result<Picture, ()> {
    if e.size > picture::FILE_MAX {
        pinnacle_rt::println!("filer: {} is too large to show", e.path);
        return Err(());
    }
    let data = fs::read_at(&e.path, 0, e.size as usize).ok_or(())?;
    match Picture::decode(&data) {
        Ok(p) => {
            pinnacle_rt::println!("filer: showing {} {}x{}", e.path, p.width(), p.height());
            Ok(p)
        }
        Err(err) => {
            pinnacle_rt::println!("filer: {} could not be shown: {err}", e.path);
            Err(())
        }
    }
}

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tap {
    /// Row `n` of the page: the person's own entries, then the apps'.
    Row(usize),
    Back,
    Close,
    Move,
    Copy,
    /// Move or copy the file being carried into the folder looked at.
    Here,
    CancelMove,
    Delete,
    DeleteForGood,
    Keep,
    /// Open the file in Fien, the editor.
    Edit,
    Rename,
    NewFolder,
    RenameFolder,
    DeleteFolder,
    DeleteFolderForGood,
    /// The name typed is the one: Enter, or the button beside the field.
    NameDone,
    NameCancel,
}

/// What is done with the file being carried to another folder.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Carry {
    Move,
    Copy,
}

/// What a name is being typed for.
#[derive(Clone, PartialEq, Eq)]
enum Naming {
    NewFolder,
    /// The opened file, at this path.
    File(String),
    /// The folder looked at.
    Folder,
}

/// What a second tap is waited for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Confirm {
    File,
    Folder,
}

/// A button that puts `tap` in `tapped`, named for `cargo xtask`.
fn button(label: &str, name: &str, variant: &'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", String::from(name))
        .on("click", move |_| tapped.set(Some(tap)))
        .child(String::from(label))
        .into_view()
}

/// What a row says under its name: a folder's count, a file's size, and
/// when either changed.
fn about(e: &Entry) -> String {
    if e.folder {
        let count = match fs::list(&e.path).map_or(0, |l| l.len()) {
            0 => String::from(t("Folder, empty")),
            1 => String::from(t("Folder, 1 item")),
            n => tf("Folder, {} items", &[&alloc::format!("{n}")]),
        };
        let changed = when(e.modified);
        return if changed.is_empty() {
            count
        } else {
            alloc::format!("{count} · {changed}")
        };
    }
    match first_line(e) {
        Some(line) => alloc::format!("{line} · {}", facts(e)),
        None => facts(e),
    }
}

/// A file's size and when it changed.
fn facts(e: &Entry) -> String {
    let changed = when(e.modified);
    if changed.is_empty() {
        size(e.size)
    } else {
        alloc::format!("{} · {changed}", size(e.size))
    }
}

/// A text file's first line with something on it, cut short: what a note
/// or a list is about, where its name (a number, often) says nothing.
fn first_line(e: &Entry) -> Option<String> {
    const MOST: usize = 40;
    let head = fs::read_at(&e.path, 0, (e.size as usize).min(160))?;
    // A character cut at the end of what was read is left off.
    let text = match core::str::from_utf8(&head) {
        Ok(text) => text,
        Err(err) if err.error_len().is_none() => core::str::from_utf8(&head[..err.valid_up_to()]).ok()?,
        Err(_) => return None,
    };
    if text.contains('\0') {
        return None;
    }
    let line = text.lines().map(str::trim).find(|l| !l.is_empty())?;
    Some(match line.char_indices().nth(MOST) {
        Some((at, _)) => alloc::format!("{}…", &line[..at]),
        None => line.into(),
    })
}

fn row(e: &Entry, n: usize, current: bool, tapped: &Signal<Option<Tap>>) -> View {
    let tapped = tapped.clone();
    el("button")
        .class("m-list-item")
        .attr("type", "button")
        .attr("role", "listitem")
        .attr("data-name", alloc::format!("row {}", e.label))
        .attr("aria-current", current.then_some("true"))
        .attr("style", current.then_some("background: var(--m-pressed)"))
        .on("click", move |_| tapped.set(Some(Tap::Row(n))))
        .child(
            el("span")
                .class("m-list-item__body")
                .child(el("span").class("m-list-item__title").child(e.label.clone()))
                .child(el("span").class("m-list-item__sub").child(about(e))),
        )
        .into_view()
}

fn heading(text: &str) -> View {
    el("h2")
        .attr(
            "style",
            "font-size: 16px; margin: 12px 0 0; color: var(--m-text-dim); font-weight: 600",
        )
        .child(String::from(text))
        .into_view()
}

/// What the app holds between taps.
struct Model {
    /// The folders opened, the first page first.
    places: Vec<Place>,
    page: Page,
    /// The file opened: its row.
    open: Option<usize>,
    /// The file being moved or copied, while a folder for it is looked for.
    carrying: Option<(Entry, Carry)>,
    /// Delete was tapped once: the second tap deletes.
    confirm: Option<Confirm>,
    /// A name being typed, and what for.
    naming: Option<Naming>,
    name: Signal<String>,
    /// What the last action did, or why it could not.
    said: String,
    /// The opened file's picture, when it is one.
    picture: Option<Decoded>,
}

impl Model {
    /// Decodes the opened file's picture, when it is one not decoded yet
    /// (or changed since); lets go of the last one otherwise.
    fn decode_opened(&mut self) {
        let Some(e) = self.opened().filter(|e| matches!(show(e), Shown::Picture)) else {
            self.picture = None;
            return;
        };
        let key = (e.path.clone(), e.size, e.modified);
        if self.picture.as_ref().is_none_or(|(k, _)| *k != key) {
            // The last one let go of first: two photos need not fit at once.
            self.picture = None;
            self.picture = Some((key, decode(&e)));
        }
    }

    /// The opened picture, when it could be decoded.
    fn shown_picture(&self) -> Option<&Picture> {
        self.picture.as_ref().and_then(|(_, p)| p.as_ref().ok())
    }

    fn place(&self) -> &Place {
        self.places.last().expect("the first page")
    }

    fn first(&self) -> bool {
        self.places.len() == 1
    }

    /// What the folder looked at is called, in the person's language for
    /// the first page.
    fn place_label(&self) -> String {
        if self.first() {
            String::from(t("Files"))
        } else {
            self.place().label.clone()
        }
    }

    /// Whether new folders may be made in the folder looked at: not on the
    /// first page without a vault, which is the system disk's.
    fn may_make_here(&self) -> bool {
        !self.first() || home_is_theirs()
    }

    /// Whether the folder looked at may be renamed or deleted: one in a
    /// folder, not an app's own.
    fn may_change_folder(&self) -> bool {
        !self.first() && !self.place().app
    }

    fn rows(&self) -> impl Iterator<Item = &Entry> {
        self.page.own.iter().chain(self.page.apps.iter())
    }

    fn row(&self, n: usize) -> Option<&Entry> {
        self.rows().nth(n)
    }

    fn opened(&self) -> Option<Entry> {
        self.open.and_then(|n| self.row(n)).cloned()
    }

    fn reload(&mut self) {
        let first = self.first();
        self.page = page_of(self.place(), first);
    }

    /// The opened file's row again after a reload, found by its path.
    fn reopen(&mut self, path: Option<String>) {
        self.open = path.and_then(|p| self.rows().position(|e| e.path == p));
    }

    /// Whether the file being carried may go into the folder looked at: not
    /// on the first page without a vault, and when moved, not where it is.
    fn may_carry_here(&self) -> bool {
        let Some((e, carry)) = &self.carrying else {
            return false;
        };
        self.may_make_here() && (*carry == Carry::Copy || join(&self.place().path, base(&e.path)) != e.path)
    }

    fn carry_here(&mut self) {
        match self.carrying.take() {
            Some((e, Carry::Move)) => self.move_here(e),
            Some((e, Carry::Copy)) => self.copy_here(e),
            None => return,
        }
        // The folder it went into, with it in the list, rather than the file
        // again: on a phone that would hide where it went.
        self.open = None;
        self.reload();
    }

    fn move_here(&mut self, m: Entry) {
        let to = join(&self.place().path, base(&m.path));
        let name = base(&m.path);
        self.said = if fs::stat(&to).is_some() {
            let said = tf("There is a {} here already: choose another folder", &[name]);
            self.carrying = Some((m.clone(), Carry::Move));
            said
        } else {
            match copy_file(&m.path, &to) {
                Err(_) => {
                    fs::remove(&to);
                    tf("{} could not be moved here", &[name])
                }
                Ok(()) if !fs::remove(&m.path) => tf("{} copied here, but could not be taken away", &[name]),
                Ok(()) => {
                    pinnacle_rt::println!("filer: moved {} to {to}", m.path);
                    tf("{} moved here", &[name])
                }
            }
        };
    }

    fn copy_here(&mut self, e: Entry) {
        let folder = self.place().path.clone();
        let name = free_name(&folder, base(&e.path));
        let to = join(&folder, &name);
        self.said = match copy_file(&e.path, &to) {
            Err(_) => {
                fs::remove(&to);
                tf("{} could not be copied here", &[base(&e.path)])
            }
            Ok(()) => {
                pinnacle_rt::println!("filer: copied {} to {to}", e.path);
                tf("{} copied here", &[&name])
            }
        };
    }

    fn delete(&mut self) {
        let Some(e) = self.opened() else {
            return;
        };
        self.open = None;
        self.said = if fs::remove(&e.path) {
            pinnacle_rt::println!("filer: deleted {}", e.path);
            tf("{} deleted", &[&e.label])
        } else {
            tf("{} could not be deleted", &[&e.label])
        };
        self.reload();
    }

    /// The folder looked at removed, all in it too, and its parent shown.
    fn delete_folder(&mut self) {
        if !self.may_change_folder() {
            return;
        }
        let place = self.place().clone();
        self.open = None;
        self.said = if fs::remove(&place.path) {
            pinnacle_rt::println!("filer: deleted folder {}", place.path);
            self.places.pop();
            // A file carried from in it is gone with it.
            if self
                .carrying
                .as_ref()
                .is_some_and(|(e, _)| e.path.starts_with(&alloc::format!("{}/", place.path)))
            {
                self.carrying = None;
            }
            tf("Folder {} deleted", &[&place.label])
        } else {
            tf("Folder {} could not be deleted", &[&place.label])
        };
        self.reload();
    }

    /// Starts typing a name for `naming`, the field holding `name` at first.
    fn start_naming(&mut self, naming: Naming, name: &str) {
        self.said.clear();
        self.name.set(name.into());
        self.naming = Some(naming);
    }

    /// The name typed taken: the folder made, or the file or folder renamed.
    /// The field stays when the name will not do, with why.
    fn name_done(&mut self) {
        let Some(naming) = self.naming.clone() else {
            return;
        };
        let name = String::from(self.name.get_untracked().trim());
        if let Some(why) = bad_name(&name) {
            self.said = why.into();
            return;
        }
        let folder = self.place().path.clone();
        match naming {
            Naming::NewFolder => {
                let path = join(&folder, &name);
                self.said = if fs::exists(&path) {
                    tf("There is a {} here already", &[&name])
                } else if fs::create_dir(&path) {
                    pinnacle_rt::println!("filer: made folder {path}");
                    self.naming = None;
                    tf("Folder {} made", &[&name])
                } else {
                    tf("{} could not be made", &[&name])
                };
                self.reload();
            }
            Naming::File(path) if base(&path) == name => self.naming = None,
            Naming::File(path) => match rename(&path, &folder, &name, false) {
                Ok(to) => {
                    pinnacle_rt::println!("filer: renamed {path} to {to}");
                    self.naming = None;
                    self.said = tf("Renamed to {}", &[&name]);
                    self.reload();
                    self.reopen(Some(to));
                }
                Err(why) => {
                    self.said = why;
                    self.reload();
                }
            },
            Naming::Folder if base(&folder) == name => self.naming = None,
            Naming::Folder => {
                if !self.may_change_folder() {
                    return;
                }
                let parent = self.places[self.places.len() - 2].path.clone();
                match rename(&folder, &parent, &name, true) {
                    Ok(to) => {
                        pinnacle_rt::println!("filer: renamed folder {folder} to {to}");
                        // A file carried from in it is there under the new name.
                        if let Some((e, _)) = &mut self.carrying
                            && let Some(rest) = e.path.strip_prefix(&alloc::format!("{folder}/"))
                        {
                            e.path = join(&to, rest);
                        }
                        let place = self.places.last_mut().expect("the folder looked at");
                        place.path = to;
                        place.label = name.clone();
                        self.naming = None;
                        self.said = tf("Renamed to {}", &[&name]);
                    }
                    Err(why) => self.said = why,
                }
                self.reload();
            }
        }
    }

    fn tap(&mut self, tap: Tap) {
        if !matches!(tap, Tap::DeleteForGood | Tap::DeleteFolderForGood) {
            self.confirm = None;
        }
        if tap != Tap::NameDone {
            self.naming = None;
        }
        match tap {
            Tap::Row(n) => {
                let Some(e) = self.row(n).cloned() else { return };
                self.said.clear();
                if e.folder {
                    pinnacle_rt::println!("filer: opened folder {}", e.path);
                    self.places.push(Place {
                        path: e.path,
                        label: e.label,
                        // On the first page, the rows after the person's own.
                        app: self.first() && n >= self.page.own.len(),
                    });
                    self.open = None;
                    self.reload();
                } else if self.carrying.is_none() {
                    pinnacle_rt::println!("filer: opened {}", e.path);
                    self.open = Some(n);
                }
            }
            Tap::Back => {
                if self.places.len() > 1 {
                    self.places.pop();
                    self.open = None;
                    self.said.clear();
                    self.reload();
                }
            }
            Tap::Close => self.open = None,
            Tap::Move | Tap::Copy => {
                if let Some(e) = self.opened() {
                    self.open = None;
                    self.said.clear();
                    let carry = if tap == Tap::Move {
                        Carry::Move
                    } else {
                        Carry::Copy
                    };
                    self.carrying = Some((e, carry));
                }
            }
            Tap::Here => self.carry_here(),
            Tap::CancelMove => {
                self.carrying = None;
                self.said.clear();
            }
            Tap::Delete => self.confirm = Some(Confirm::File),
            Tap::DeleteForGood if self.confirm == Some(Confirm::File) => {
                self.confirm = None;
                self.delete();
            }
            Tap::DeleteFolder if self.may_change_folder() => self.confirm = Some(Confirm::Folder),
            Tap::DeleteFolderForGood if self.confirm == Some(Confirm::Folder) => {
                self.confirm = None;
                self.delete_folder();
            }
            Tap::Rename => {
                if let Some(e) = self.opened() {
                    let name = String::from(base(&e.path));
                    self.start_naming(Naming::File(e.path), &name);
                }
            }
            Tap::NewFolder if self.may_make_here() => self.start_naming(Naming::NewFolder, ""),
            Tap::RenameFolder if self.may_change_folder() => {
                let name = String::from(base(&self.place().path));
                self.start_naming(Naming::Folder, &name);
            }
            Tap::NameDone => self.name_done(),
            // The main loop hands it to Fien, which it may have to start.
            Tap::Edit => {}
            _ => {}
        }
    }
}

/// The field a name is typed in, with its button and Cancel: Enter takes
/// it too.
fn name_bar(m: &Model, tapped: &Signal<Option<Tap>>) -> View {
    let (prompt, done) = match m.naming {
        Some(Naming::NewFolder) => (t("Name of the new folder"), t("Make")),
        _ => (t("New name"), t("Rename")),
    };
    let (shown, set, enter) = (m.name.clone(), m.name.clone(), tapped.clone());
    el("div")
        .attr("style", BAR)
        .child(
            el("input")
                .class("m-input")
                .attr("data-name", "name")
                .attr("aria-label", prompt)
                .attr("placeholder", prompt)
                .attr("style", "flex: 1; min-width: 160px")
                .prop("value", move || shown.get_untracked())
                .prop_bool("@focus", true)
                .on("input", move |e| set.set(e.value.clone().unwrap_or_default()))
                .on("keydown", move |e| {
                    if e.key.as_deref() == Some("Enter") {
                        enter.set(Some(Tap::NameDone));
                        e.prevent_default();
                    }
                }),
        )
        .child(button(done, "name-done", "primary", Tap::NameDone, tapped))
        .child(button(
            t("Cancel"),
            "name-cancel",
            "ghost",
            Tap::NameCancel,
            tapped,
        ))
        .into_view()
}

/// The folder's page: its name with back, what may be done with it, what
/// is being moved or copied, then its rows.
fn list_pane(m: &Model, both: bool, tapped: &Signal<Option<Tap>>) -> View {
    let mut header = el("div").attr(
        "style",
        "display: flex; align-items: center; gap: 8px; margin-top: 16px",
    );
    if !m.first() {
        header = header.child(button("←", "back", "ghost", Tap::Back, tapped));
    }
    header = header.child(
        el("h1")
            .attr(
                "style",
                "flex: 1; min-width: 0; margin: 0; font-size: 30px; white-space: nowrap; overflow: hidden",
            )
            .child(m.place_label()),
    );
    let mut pane = el("section")
        .attr(
            "style",
            alloc::format!(
                "{}; overflow-y: auto; padding: 24px 16px; display: flex; flex-direction: column; gap: 12px",
                if both {
                    "width: 400px; flex: none"
                } else {
                    "flex: 1"
                }
            ),
        )
        .child(header);
    // What may be done with the folder looked at.
    if m.confirm == Some(Confirm::Folder) {
        let label = m.place().label.as_str();
        let ask = match m.page.own.len() {
            0 => tf("Delete the empty folder {} for good?", &[label]),
            1 => tf(
                "Delete the folder {} and the one thing in it, for good?",
                &[label],
            ),
            n => {
                let ask = t("Delete the folder {} and the {} things in it, for good?");
                fill(ask, &[label, &alloc::format!("{n}")])
            }
        };
        pane = pane.child(
            el("div")
                .attr("style", ACTIONS)
                .child(el("span").attr("style", "flex: 1; min-width: 160px").child(ask))
                .child(button(
                    t("Delete"),
                    "delete-folder-for-good",
                    "danger",
                    Tap::DeleteFolderForGood,
                    tapped,
                ))
                .child(button(t("Keep"), "keep", "ghost", Tap::Keep, tapped)),
        );
    } else if m.may_make_here() {
        let mut row = el("div").attr("style", ACTIONS).child(button(
            t("New folder"),
            "new-folder",
            "ghost",
            Tap::NewFolder,
            tapped,
        ));
        if m.may_change_folder() {
            row = row
                .child(button(
                    t("Rename"),
                    "rename-folder",
                    "ghost",
                    Tap::RenameFolder,
                    tapped,
                ))
                .child(button(
                    t("Delete folder"),
                    "delete-folder",
                    "ghost",
                    Tap::DeleteFolder,
                    tapped,
                ));
        }
        pane = pane.child(row);
    }
    if matches!(m.naming, Some(Naming::NewFolder | Naming::Folder)) {
        pane = pane.child(name_bar(m, tapped));
    }
    if let Some((carried, carry)) = &m.carrying {
        let what = match carry {
            Carry::Move => tf("Moving {}: open the folder it goes to", &[&carried.label]),
            Carry::Copy => tf("Copying {}: open the folder the copy goes to", &[&carried.label]),
        };
        let mut bar = el("div")
            .attr("style", BAR)
            .child(el("span").attr("style", "flex: 1; min-width: 160px").child(what));
        if m.may_carry_here() {
            let label = match carry {
                Carry::Move => t("Move here"),
                Carry::Copy => t("Copy here"),
            };
            let name = match carry {
                Carry::Move => "move-here",
                Carry::Copy => "copy-here",
            };
            bar = bar.child(button(label, name, "primary", Tap::Here, tapped));
        }
        pane = pane.child(bar.child(button(
            t("Cancel"),
            "cancel-move",
            "ghost",
            Tap::CancelMove,
            tapped,
        )));
    }
    if !m.said.is_empty() && !matches!(m.naming, Some(Naming::File(_))) {
        pane = pane.child(said(m));
    }
    let own = m.page.own.len();
    let rows = |entries: &[Entry], from: usize| {
        let mut list = el("div").class("m-list").attr("role", "list");
        for (i, e) in entries.iter().enumerate() {
            list = list.child(row(e, from + i, m.open == Some(from + i), tapped));
        }
        list
    };
    if m.first() {
        if home_is_theirs() {
            pane = pane.child(heading(t("Your files")));
            pane = if own == 0 {
                let empty = t("Nothing here yet: files moved here from an app's folder stay here");
                pane.child(
                    el("p")
                        .attr("style", "margin: 0; color: var(--m-text-dim)")
                        .child(empty),
                )
            } else {
                pane.child(rows(&m.page.own, 0))
            };
        }
        pane = pane
            .child(heading(t("Apps' folders")))
            .child(rows(&m.page.apps, own));
    } else if own == 0 {
        pane = pane.child(
            el("p")
                .attr("style", "margin: 0; color: var(--m-text-dim)")
                .child(t("This folder is empty")),
        );
    } else {
        pane = pane.child(rows(&m.page.own, 0));
    }
    pane.into_view()
}

/// What the last action did, or why it could not.
fn said(m: &Model) -> View {
    el("p")
        .attr("role", "status")
        .attr("style", "margin: 0; color: var(--m-text-dim)")
        .child(m.said.clone())
        .into_view()
}

/// The opened file: its name, what it is, what may be done with it, and
/// its text.
fn file_pane(m: &Model, e: &Entry, both: bool, tapped: &Signal<Option<Tap>>) -> View {
    let mut header = el("div").attr("style", "display: flex; align-items: center; gap: 8px");
    if !both {
        header = header.child(button("←", "close", "ghost", Tap::Close, tapped));
    }
    header = header.child(
        el("h2")
            .attr(
                "style",
                "flex: 1; min-width: 0; margin: 0; font-size: 21px; white-space: nowrap; overflow: hidden",
            )
            .child(e.label.clone()),
    );
    let shown = show(e);
    let mut buttons = el("div").attr("style", ACTIONS);
    if m.confirm == Some(Confirm::File) {
        buttons = buttons
            .child(
                el("span")
                    .attr("style", "flex: 1; min-width: 160px")
                    .child(tf("Delete {} for good?", &[&e.label])),
            )
            .child(button(
                t("Delete"),
                "delete-for-good",
                "danger",
                Tap::DeleteForGood,
                tapped,
            ))
            .child(button(t("Keep"), "keep", "ghost", Tap::Keep, tapped));
    } else {
        buttons = buttons
            .child(button(t("Move"), "move", "ghost", Tap::Move, tapped))
            .child(button(t("Copy"), "copy", "ghost", Tap::Copy, tapped))
            .child(button(t("Rename"), "rename", "ghost", Tap::Rename, tapped));
        if matches!(shown, Shown::Text(..)) {
            buttons = buttons.child(button(t("Edit"), "edit", "ghost", Tap::Edit, tapped));
        }
        buttons = buttons.child(button(t("Delete"), "delete", "ghost", Tap::Delete, tapped));
    }
    let body: View = match shown {
        Shown::Text(text, cut) => {
            let mut text = el("div")
                .attr(
                    "style",
                    "white-space: pre-wrap; padding: 12px; border-radius: 12px; background: var(--m-bg)",
                )
                .child(text);
            if cut {
                let shown = tf("… the first {} of {}", &[&size(SHOW_MAX as u64), &size(e.size)]);
                text = text.child(el("p").attr("style", "color: var(--m-text-dim)").child(shown));
            }
            text.into_view()
        }
        // Drawn by the app into the canvas's place (`draw`), fitted to it.
        Shown::Picture if m.shown_picture().is_some() => el("canvas")
            .attr("data-name", "picture")
            .attr("data-revision", e.path.clone())
            .attr("role", "img")
            .attr("aria-label", e.label.clone())
            .attr("style", "flex: 1; display: block; min-height: 240px")
            .into_view(),
        Shown::Picture => el("p")
            .attr("style", "color: var(--m-text-dim)")
            .child(t("It looks like a picture, but it could not be shown"))
            .into_view(),
        Shown::Nothing => el("p")
            .attr("style", "color: var(--m-text-dim)")
            .child(t("Nothing here opens this kind of file"))
            .into_view(),
        Shown::Unreadable => el("p")
            .attr("style", "color: var(--m-text-dim)")
            .child(t("It could not be read"))
            .into_view(),
    };
    let mut pane = el("section")
        .attr(
            "style",
            "flex: 1; min-width: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; \
             padding: 24px 16px; background: var(--m-surface)",
        )
        .child(header)
        .child(
            el("p")
                .attr("style", "margin: 0; color: var(--m-text-dim)")
                .child(tf("{} · in {}", &[&about_file(m, e), &m.place_label()])),
        )
        .child(buttons);
    let naming = matches!(m.naming, Some(Naming::File(_)));
    if naming {
        pane = pane.child(name_bar(m, tapped));
    }
    // Here when the list, which says it otherwise, is not shown beside.
    if !m.said.is_empty() && (naming || !both) {
        pane = pane.child(said(m));
    }
    pane.child(body).into_view()
}

/// What the opened file is: a picture's size in pixels first, then its
/// size and when it changed.
fn about_file(m: &Model, e: &Entry) -> String {
    match m.shown_picture() {
        Some(p) => alloc::format!("{} × {} · {}", p.width(), p.height(), facts(e)),
        None => facts(e),
    }
}

/// The folder and the opened file side by side on a wide window, one of
/// them on a narrow one.
fn page(m: &Model, both: bool, tapped: &Signal<Option<Tap>>) -> View {
    let open = m.open.and_then(|n| m.row(n));
    let mut root = el("div").attr("style", "display: flex; height: 100vh");
    if both || open.is_none() {
        root = root.child(list_pane(m, both, tapped));
    }
    match open {
        Some(e) => root = root.child(file_pane(m, e, both, tapped)),
        None if both => {
            root = root.child(
                el("section")
                    .attr(
                        "style",
                        "flex: 1; display: flex; align-items: center; justify-content: center; \
                         background: var(--m-surface); color: var(--m-text-dim)",
                    )
                    .child(match m.carrying {
                        Some((_, Carry::Move)) => t("Open the folder it goes to, then Move here"),
                        Some((_, Carry::Copy)) => t("Open the folder the copy goes to, then Copy here"),
                        None => t("Tap a file to open it"),
                    }),
            )
        }
        None => {}
    }
    root.into_view()
}

/// Draws the window (all of it, or what changed), the opened picture in its
/// canvas's place, fitted to it.
fn draw(screen: &mut Screen, canvas: &mut Canvas, all: bool, m: &mut Model) -> Option<Rect> {
    screen.draw_with(canvas, all, &mut |name, canvas, rect| {
        let Some((_, Ok(p))) = &mut m.picture else {
            return;
        };
        if name != "picture" || rect.width <= 0 || rect.height <= 0 {
            return;
        }
        let f = p.fit(rect.width as u32, rect.height as u32, theme::SURFACE.0);
        let (x, y) = (rect.x + f.x as i32, rect.y + f.y as i32);
        canvas.blit(&f.pixels, f.width as i32, f.height as i32, x, y);
    })
}

/// Opens `path` in Fien: starts it (or brings it to the front) and asks
/// its service for the file, waiting a little for a Fien just started.
fn edit_in_fien(app: &App, path: &str) {
    app.launch("fien");
    let deadline = pinnacle_rt::time() + 3_000;
    loop {
        if let Some(fien) = pinnacle_rt::connect(pinnacle_ui::fien::SERVICE) {
            let mut body = alloc::vec![pinnacle_ui::fien::OPEN];
            body.extend_from_slice(path.as_bytes());
            fien.send(&body, Vec::new());
            pinnacle_rt::println!("filer: editing {path}");
            return;
        }
        if pinnacle_rt::time() > deadline {
            pinnacle_rt::println!("filer: Fien did not start");
            return;
        }
        pinnacle_rt::sleep(50);
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Files");
    let first = Place {
        path: home().into(),
        label: "Files".into(),
        app: false,
    };
    let mut m = Model {
        page: page_of(&first, true),
        places: alloc::vec![first],
        open: None,
        carrying: None,
        confirm: None,
        naming: None,
        name: signal(String::new()),
        said: String::new(),
        picture: None,
    };
    let mut screen = Screen::new(app.width, app.height);
    let tapped: Signal<Option<Tap>> = signal(None);
    let mut redraw = true;
    pinnacle_rt::println!(
        "filer: {} files and folders, {} apps' folders",
        m.page.own.len(),
        m.page.apps.len()
    );
    loop {
        if redraw {
            screen.resize(app.width, app.height);
            screen.clear();
            m.decode_opened();
            screen.mount(page(&m, notes::two_panes(app.width as i32), &tapped));
            draw(&mut screen, &mut app.canvas(), true, &mut m);
            app.present_all();
            screen.announce("filer: button ");
            redraw = false;
        }
        match app.next_event(None) {
            // Back in front: what other apps or the terminal changed since.
            Event::Shown(true) => {
                let open = m.opened().map(|e| e.path);
                m.reload();
                m.reopen(open);
                redraw = true;
            }
            Event::Resized => redraw = true,
            Event::Preferences => {
                screen.restyle();
                redraw = true;
            }
            Event::Input(e) => {
                screen.input(&e);
                if screen.clipboard() == Some(Clipboard::Paste) {
                    app.paste();
                }
                let tap = tapped.get_untracked();
                if let Some(tap) = tap {
                    tapped.set(None);
                    if tap == Tap::Edit
                        && let Some(e) = m.opened()
                    {
                        edit_in_fien(&app, &e.path);
                    }
                    m.tap(tap);
                    redraw = true;
                }
            }
            Event::Clipboard(text) => {
                screen.paste(&text);
            }
            Event::Closed => return 0,
            _ => {}
        }
        if !redraw && let Some(area) = draw(&mut screen, &mut app.canvas(), false, &mut m) {
            app.present(area);
        }
    }
}