garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/fien.rs

raw

//! Fien: write code. The editor of `jeroen/fien` (a rope, many cursors,
//! undo by edit, colouring for Rust and Frits, wrapping) in a window, its
//! interface drawn with Mithril through `pinnacle_view`. A system program,
//! as Files is: it edits the person's files, not only its own.
//!
//! - Its own folder is the apps' folder `fien` (Files shows it as Fien);
//!   the first start puts an example in each language there. Files opens
//!   any text file in it (Edit), through [`fien::SERVICE`].
//! - A Frits script is checked against the terminal's platform as typing
//!   pauses, and names complete as they are typed: what `frits run` in the
//!   terminal would say.
//! - Share offers the text to a contact, whose Fien edits it at the same
//!   time ([`fien::SHARED`], through the p2p service): each sees the
//!   other's typing and cursor.
//!
//! A file is saved with Save (or ctrl+S), when another is opened and when
//! the app is left.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;

use fien_core::crdt::{Id, Op};
use fien_core::{Editor, Language};
use fien_view::{Assist, Completion, Diagnostic, Fien, Metrics, Request};
use frits::Platform;
use pinnacle_rt::{Channel, fs};
use pinnacle_ui::fien;
use pinnacle_ui::p2p::{Client, Contact};
use pinnacle_ui::{App, Event};
use pinnacle_view::{Clipboard, IntoView, SCALE, Screen, Signal, View, el, signal};

const EXAMPLE_RUST: &str = "//! A first program.

fn main() {
    let names = [\"Frits\", \"Fien\"];
    for name in names {
        println!(\"Hello, {name}!\");
    }
}
";

const EXAMPLE_FRITS: &str = "script / Console

// Frits, Pinnacle's language: what it may touch on the first line,
// checked as you type.

on main() {
    let who = \"Fien\"
    Console.print(\"Hello from {who}!\")
}
";

/// The terminal's platform: what a script written here can use.
const PLATFORM: &str = include_str!("../../frits/terminal.frits");

/// How long after the last key a script is checked.
const CHECK_AFTER_MS: u64 = 600;

/// The apps' own folders: in the vault once it is open, else on the system
/// disk (as the kernel and Files have it).
fn own() -> String {
    let apps = if fs::disk("data").is_some() {
        "data:/apps"
    } else {
        "system:/data"
    };
    format!("{apps}/fien")
}

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

/// The files in Fien's folder, by name; the examples on the first start.
fn files() -> Vec<String> {
    let folder = own();
    let mut names: Vec<String> = fs::list(&folder)
        .unwrap_or_default()
        .into_iter()
        .filter(|n| !n.ends_with('/'))
        .collect();
    if names.is_empty() {
        fs::create_dir(folder.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
        fs::create_dir(&folder);
        fs::write(&format!("{folder}/main.rs"), EXAMPLE_RUST.as_bytes());
        fs::write(&format!("{folder}/hello.frits"), EXAMPLE_FRITS.as_bytes());
        names = alloc::vec!["hello.frits".into(), "main.rs".into()];
    }
    names.sort();
    names
}

/// The monospace face's measures at the editor's size, in the view's
/// logical pixels.
fn metrics() -> Metrics {
    let size = 14.0;
    let face = pinnacle_ui::theme::mono().face();
    let font = pinnacle_gfx::Font::new(face, size * SCALE);
    let ten = font.measure("0000000000") as f32;
    Metrics {
        size,
        line: 20.0,
        advance: ten / 10.0 / SCALE,
    }
}

/// Frits's checker and names, for the editor.
struct Frits {
    platform: Platform<()>,
}

const KEYWORDS: [&str; 20] = [
    "fn", "let", "var", "if", "else", "while", "for", "in", "match", "return", "break", "continue", "enum",
    "type", "on", "true", "false", "keep", "import", "test",
];

impl Assist for Frits {
    fn check(&self, text: &str) -> Vec<Diagnostic> {
        match self.platform.compile(text) {
            Ok(_) => Vec::new(),
            Err(errors) => errors
                .into_iter()
                .map(|e| Diagnostic {
                    line: e.line.saturating_sub(1) as usize,
                    message: e.msg,
                })
                .collect(),
        }
    }

    fn complete(&self, owner: &str, _prefix: &str) -> Vec<Completion> {
        let decl = &self.platform.decl;
        let item = |label: &str, detail: String| Completion {
            label: label.into(),
            detail,
        };
        if let Some(ns) = owner.strip_suffix('.') {
            let fns = decl
                .fns
                .iter()
                .filter(|f| f.namespace == ns)
                .map(|f| item(&f.name, frits::guide::signature(f)));
            let consts = decl
                .consts
                .iter()
                .filter(|c| c.namespace == ns)
                .map(|c| item(&c.name, String::from("constant")));
            return fns.chain(consts).collect();
        }
        let mut out: Vec<Completion> = KEYWORDS.iter().map(|k| item(k, "keyword".into())).collect();
        for ns in decl.effects.iter().chain(&decl.modules) {
            out.push(item(ns, "effect or module".into()));
        }
        for (e, _) in &decl.events {
            out.push(item(e, "event".into()));
        }
        out
    }
}

/// The text open: a file, or one a contact shares (no file until saved).
struct Open {
    fien: Fien,
    /// Where it is saved.
    path: String,
}

impl Open {
    fn file(path: &str) -> Open {
        let text = fs::read(path)
            .and_then(|b| String::from_utf8(b).ok())
            .unwrap_or_default();
        pinnacle_rt::println!("fien: opened {}", base(path));
        Open::with(Fien::new(&text, base(path), metrics(), true), path.into())
    }

    fn with(fien: Fien, path: String) -> Open {
        if Language::for_path(&path) == Language::Frits
            && let Ok(platform) = Platform::new(PLATFORM)
        {
            fien.set_assist(Box::new(Frits { platform }));
        }
        Open { fien, path }
    }

    fn save(&self) {
        if !self.fien.editor().is_dirty() {
            return;
        }
        if fs::write(&self.path, self.fien.text().as_bytes()) {
            self.fien.saved();
            pinnacle_rt::println!("fien: saved {}", base(&self.path));
        } else {
            pinnacle_rt::println!("fien: could not save {}", base(&self.path));
        }
    }
}

/// A text edited with a contact: the channel to their Fien, through the p2p
/// service.
struct Link {
    channel: Channel,
    /// Who: the contact's name (sharing) or the sharer's device's (joined).
    who: String,
    /// Their cursor, as the name of the character before it.
    cursor: Option<Option<Id>>,
    /// Joining: the text's names so far, its name and the sharer's; `None`
    /// once whole.
    joining: Option<(Vec<u8>, String)>,
    /// The editor's version last sent.
    sent: u64,
}

impl Link {
    fn send(&self, kind: u8, body: &[u8]) {
        let mut m = alloc::vec![kind];
        m.extend_from_slice(body);
        self.channel.send(&m, Vec::new());
    }
}

/// What a tap on Fien's own pages asked for.
#[derive(Clone, PartialEq)]
enum Tap {
    Open(String),
    New(&'static str),
    ShareWith(usize),
    Cancel,
}

fn row(label: String, name: String, tap: Tap, tapped: &Signal<Option<Tap>>) -> View {
    let t = tapped.clone();
    el("button")
        .class("m-list-item")
        .attr("data-name", name)
        .attr("style", "width: 100%; text-align: left")
        .on("click", move |_| t.set(Some(tap.clone())))
        .child(
            el("span")
                .class("m-list-item__body")
                .child(el("span").class("m-list-item__title").child(label)),
        )
        .into_view()
}

fn page(title: &str, rows: Vec<View>, below: View) -> View {
    el("main")
        .attr(
            "style",
            "max-width: 640px; margin: 0 auto; padding: 24px 16px; display: flex; \
             flex-direction: column; gap: 12px",
        )
        .child(
            el("h1")
                .attr("style", "font-size: 28px; margin: 0")
                .child(String::from(title)),
        )
        .child(
            el("section")
                .class("m-section")
                .child(el("div").class("m-list").attr("role", "list").child(rows)),
        )
        .child(below)
        .into_view()
}

/// Fien's files, and a new file of either language.
fn files_page(names: &[String], tapped: &Signal<Option<Tap>>) -> View {
    let rows = names
        .iter()
        .map(|n| row(n.clone(), format!("file {n}"), Tap::Open(n.clone()), tapped))
        .collect();
    let new = |label: &'static str, ext: &'static str| {
        let t = tapped.clone();
        el("button")
            .class("m-button")
            .attr("data-name", format!("new {ext}"))
            .on("click", move |_| t.set(Some(Tap::New(ext))))
            .child(label)
    };
    let below = el("div")
        .attr("style", "display: flex; gap: 8px")
        .child(new("New Rust file", "rs"))
        .child(new("New Frits file", "frits"))
        .into_view();
    page("Fien", rows, below)
}

/// The contacts to share the open text with.
fn share_page(name: &str, contacts: &[Contact], tapped: &Signal<Option<Tap>>) -> View {
    let rows = contacts
        .iter()
        .enumerate()
        .map(|(i, c)| {
            row(
                c.name.clone(),
                format!("contact {}", c.name),
                Tap::ShareWith(i),
                tapped,
            )
        })
        .collect();
    let t = tapped.clone();
    let below = el("div")
        .attr("style", "display: flex; flex-direction: column; gap: 8px")
        .child(
            el("p")
                .attr("style", "margin: 0; color: var(--m-text-dim)")
                .child(if contacts.is_empty() {
                    "No contacts yet: add one in Contacts."
                } else {
                    "Their Fien must be open, and their device must offer its services to you \
                     (Settings, Remote access)."
                }),
        )
        .child(
            el("button")
                .class("m-button")
                .attr("data-name", "cancel")
                .on("click", move |_| t.set(Some(Tap::Cancel)))
                .child("Cancel"),
        )
        .into_view();
    page(&format!("Share {name} with"), rows, below)
}

/// This device's name, as its card has it.
fn device_name() -> String {
    fs::read("system:/settings/name")
        .and_then(|b| String::from_utf8(b).ok())
        .map(|n| String::from(n.trim()))
        .filter(|n| !n.is_empty())
        .unwrap_or_else(|| "Pinnacle".into())
}

fn random_u32() -> u32 {
    let mut b = [0u8; 4];
    pinnacle_rt::random(&mut b);
    u32::from_le_bytes(b).max(1)
}

/// Where the screen is.
enum Mode {
    Editing,
    Files,
    Sharing(Vec<Contact>),
}

struct App2 {
    app: App,
    screen: Screen,
    tapped: Signal<Option<Tap>>,
    open: Option<Open>,
    mode: Mode,
    link: Option<Link>,
    remount: bool,
    check_at: Option<u64>,
}

impl App2 {
    fn mount(&mut self) {
        self.screen.resize(self.app.width, self.app.height);
        self.screen.clear();
        match (&self.mode, &self.open) {
            (Mode::Editing, Some(o)) => self.screen.mount(o.fien.view()),
            (Mode::Sharing(contacts), Some(o)) => {
                self.screen
                    .mount(share_page(&o.fien.name(), contacts, &self.tapped))
            }
            _ => self.screen.mount(files_page(&files(), &self.tapped)),
        }
        self.remount = false;
        self.draw(true);
    }

    /// Draws what changed, then lets the editor read the text area's size
    /// and draws again if that moved anything.
    fn draw(&mut self, all: bool) {
        let first = self.screen.draw(&mut self.app.canvas(), all);
        let second = match (&self.mode, &self.open) {
            (Mode::Editing, Some(o)) => {
                o.fien.sync(self.screen.ui());
                self.screen.draw(&mut self.app.canvas(), false)
            }
            _ => None,
        };
        if all {
            self.app.present_all();
            self.screen.announce("fien: button ");
            return;
        }
        let area = match (first, second) {
            (Some(a), Some(b)) => Some(a.union(&b)),
            (a, b) => a.or(b),
        };
        if let Some(area) = area {
            self.app.present(area);
        }
    }

    /// Opens a file, the one open saved and any sharing stopped first.
    fn open_file(&mut self, path: &str) {
        self.leave();
        self.open = Some(Open::file(path));
        self.mode = Mode::Editing;
        self.check_at = Some(pinnacle_rt::time());
        self.remount = true;
    }

    fn leave(&mut self) {
        if let Some(o) = &self.open {
            o.save();
        }
        if self.link.take().is_some() {
            pinnacle_rt::println!("fien: stopped sharing");
        }
    }

    /// Offers the open text to a contact.
    fn share(&mut self, contact: &Contact) {
        let Some(o) = &self.open else { return };
        let Some(channel) = pinnacle_ui::p2p::remote_service(&contact.key, fien::SHARED) else {
            pinnacle_rt::println!("fien: the p2p service is not running");
            return;
        };
        let snapshot = o.fien.edit(|e| e.share(random_u32()));
        let link = Link {
            channel,
            who: contact.name.clone(),
            cursor: None,
            joining: None,
            sent: 0,
        };
        let me = device_name();
        let mut hello = alloc::vec![me.len().min(255) as u8];
        hello.extend_from_slice(&me.as_bytes()[..me.len().min(255)]);
        hello.extend_from_slice(o.fien.name().as_bytes());
        link.send(fien::HELLO, &hello);
        for part in snapshot.chunks(fien::PART_BYTES) {
            link.send(fien::PART, part);
        }
        link.send(fien::END, &[]);
        pinnacle_rt::println!("fien: shared {} with {}", o.fien.name(), contact.name);
        self.link = Some(link);
    }

    /// A message on the shared text's channel.
    fn linked(&mut self, m: &[u8]) {
        let Some(link) = &mut self.link else { return };
        let (Some(&kind), body) = (m.first(), &m[1.min(m.len())..]) else {
            return;
        };
        match kind {
            fien::HELLO if body.len() > 1 => {
                let n = body[0] as usize;
                let who = String::from_utf8_lossy(&body[1..(1 + n).min(body.len())]).into_owned();
                let name = String::from_utf8_lossy(&body[(1 + n).min(body.len())..]).into_owned();
                link.who = who;
                link.joining = Some((Vec::new(), name));
            }
            fien::PART => {
                if let Some((names, _)) = &mut link.joining {
                    names.extend_from_slice(body);
                }
            }
            fien::END => {
                let Some((names, name)) = link.joining.take() else {
                    return;
                };
                let language = Language::for_path(&name);
                let Some(editor) = Editor::join(&names, random_u32(), language) else {
                    pinnacle_rt::println!("fien: a shared text that did not read");
                    self.link = None;
                    return;
                };
                pinnacle_rt::println!("fien: joined {name} from {}", link.who);
                // Saved, when it is, into Fien's folder under its name.
                let path = format!("{}/{name}", own());
                let fien = Fien::with_editor(editor, &name, metrics(), true);
                if let Some(o) = &self.open {
                    o.save();
                }
                self.open = Some(Open::with(fien, path));
                self.mode = Mode::Editing;
                self.check_at = Some(pinnacle_rt::time());
                self.remount = true;
            }
            fien::OP => {
                if let (Some(op), Some(o)) = (Op::decode(body), &self.open) {
                    o.fien.edit(|e| e.receive(op));
                    self.check_at = Some(pinnacle_rt::time() + CHECK_AFTER_MS);
                }
            }
            fien::CURSOR => {
                link.cursor = Some(match body {
                    [1, rest @ ..] if rest.len() >= 8 => Some(Id {
                        replica: u32::from_le_bytes(rest[..4].try_into().unwrap()),
                        clock: u32::from_le_bytes(rest[4..8].try_into().unwrap()),
                    }),
                    _ => None,
                });
            }
            _ => {}
        }
        self.show_peer();
    }

    /// Sends what changed here, and shows where the other's cursor is now.
    fn sync_link(&mut self) {
        let (Some(link), Some(o)) = (&mut self.link, &self.open) else {
            return;
        };
        if link.joining.is_some() || !o.fien.editor().is_shared() {
            return;
        }
        let version = o.fien.editor().version();
        if version == link.sent {
            return;
        }
        link.sent = version;
        let (ops, cursor) = o.fien.edit(|e| {
            let ops = e.take_ops();
            let head = e.primary().head;
            (ops, e.anchor_of(head).flatten())
        });
        link.sent = o.fien.editor().version();
        for op in &ops {
            link.send(fien::OP, &op.encode());
        }
        let mut c = Vec::new();
        if let Some(id) = cursor {
            c.push(1);
            c.extend_from_slice(&id.replica.to_le_bytes());
            c.extend_from_slice(&id.clock.to_le_bytes());
        } else {
            c.push(0);
        }
        link.send(fien::CURSOR, &c);
        self.show_peer();
    }

    fn show_peer(&self) {
        let Some(o) = &self.open else { return };
        let peers = match &self.link {
            Some(Link {
                cursor: Some(anchor),
                who,
                ..
            }) => {
                let at = o.fien.editor().place_of(*anchor);
                alloc::vec![(who.clone(), at)]
            }
            _ => Vec::new(),
        };
        o.fien.set_peers(peers);
    }

    /// What the editor asked of the host.
    fn requests(&mut self) {
        let Some(o) = &self.open else { return };
        let fien = o.fien.clone();
        for request in fien.requests() {
            match request {
                Request::Copy(text) => self.app.copy(&text),
                Request::Paste => self.app.paste(),
                Request::Save => {
                    if let Some(o) = &self.open {
                        o.save();
                    }
                }
                Request::Files => {
                    self.leave();
                    self.mode = Mode::Files;
                    self.remount = true;
                }
                Request::Share => {
                    if self.link.take().is_some() {
                        fien.edit(Editor::unshare);
                        fien.set_peers(Vec::new());
                        pinnacle_rt::println!("fien: stopped sharing");
                    } else {
                        let contacts =
                            Client::connect(2000).map_or_else(Vec::new, |c| c.contacts(&mut Vec::new()));
                        self.mode = Mode::Sharing(contacts);
                        self.remount = true;
                    }
                }
            }
        }
    }

    fn tap(&mut self, tap: Tap) {
        match tap {
            Tap::Open(name) => self.open_file(&format!("{}/{name}", own())),
            Tap::New(ext) => {
                let names = files();
                let name = (1..)
                    .map(|i| format!("new-{i}.{ext}"))
                    .find(|n| !names.contains(n))
                    .expect("a free name");
                let path = format!("{}/{name}", own());
                fs::write(&path, b"");
                self.open_file(&path);
            }
            Tap::ShareWith(i) => {
                if let Mode::Sharing(contacts) = &self.mode
                    && let Some(c) = contacts.get(i).cloned()
                {
                    self.share(&c);
                }
                self.mode = Mode::Editing;
                self.remount = true;
            }
            Tap::Cancel => {
                self.mode = Mode::Editing;
                self.remount = true;
            }
        }
    }
}

/// Takes what a signal holds, leaving it empty.
fn take<T: Clone + 'static>(s: &Signal<Option<T>>) -> Option<T> {
    let v = s.get_untracked();
    if v.is_some() {
        s.set(None);
    }
    v
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let app = App::new("Fien");
    let opens = pinnacle_rt::register(fien::SERVICE);
    let shares = pinnacle_rt::register(fien::SHARED);
    let screen = Screen::new(app.width, app.height);
    let names = files();
    let first = if names.iter().any(|n| n == "main.rs") {
        "main.rs"
    } else {
        names[0].as_str()
    };
    let mut s = App2 {
        app,
        screen,
        tapped: signal(None),
        open: Some(Open::file(&format!("{}/{first}", own()))),
        mode: Mode::Editing,
        link: None,
        remount: true,
        check_at: None,
    };
    // Programs asking for a file, connected and not yet heard.
    let mut askers: Vec<Channel> = Vec::new();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    loop {
        if s.remount {
            s.mount();
        }
        // The channels waited on: the two services, the askers, the link.
        let mut waited: Vec<&Channel> = Vec::new();
        let services = [opens.as_ref(), shares.as_ref()];
        for c in services.into_iter().flatten() {
            waited.push(c);
        }
        let first_asker = waited.len();
        waited.extend(askers.iter());
        let link_at = waited.len();
        if let Some(l) = &s.link {
            waited.push(&l.channel);
        }
        let opens_at = opens.as_ref().map(|_| 0);
        let shares_at = shares.as_ref().map(|_| opens_at.map_or(0, |_| 1));
        let event = s.app.wait(&waited, &mut buffer, s.check_at);
        drop(waited);
        match event {
            Event::Timeout => {
                s.check_at = None;
                if let Some(o) = &s.open
                    && o.fien.needs_check()
                {
                    let n = o.fien.check();
                    pinnacle_rt::println!("fien: {n} problems");
                }
            }
            Event::Shown(true) | Event::Resized => s.remount = true,
            Event::Shown(false) => {
                if let Some(o) = &s.open {
                    o.save();
                }
            }
            Event::Input(e) => {
                s.screen.input(&e);
                match s.screen.clipboard() {
                    Some(Clipboard::Paste) => s.app.paste(),
                    Some(Clipboard::Copy) => {
                        if let Some(o) = &s.open {
                            s.app.copy(&o.fien.editor().copy());
                        }
                    }
                    None => {}
                }
                if let Some(o) = &s.open
                    && o.fien.needs_check()
                {
                    s.check_at = Some(pinnacle_rt::time() + CHECK_AFTER_MS);
                }
            }
            Event::Clipboard(text) => {
                if let Some(o) = &s.open {
                    o.fien.paste(&text);
                }
            }
            // A new connection to a service: its channel the handle.
            Event::Channel {
                index, mut handles, ..
            } if Some(index) == opens_at || Some(index) == shares_at => {
                let Some(h) = handles.pop() else { continue };
                if Some(index) == opens_at {
                    askers.push(Channel(h));
                } else if s.link.is_none() {
                    s.link = Some(Link {
                        channel: Channel(h),
                        who: String::new(),
                        cursor: None,
                        joining: None,
                        sent: 0,
                    });
                }
            }
            Event::Channel { index, len, .. } if index >= first_asker && index < link_at => {
                let asker = askers.remove(index - first_asker);
                if buffer.first() == Some(&fien::OPEN) {
                    let path = String::from_utf8_lossy(&buffer[1..len]).into_owned();
                    s.open_file(&path);
                }
                drop(asker);
            }
            Event::Channel { index, len, .. } if index == link_at => {
                let m = buffer[..len].to_vec();
                s.linked(&m);
            }
            Event::ChannelClosed { index } if index >= first_asker && index < link_at => {
                askers.remove(index - first_asker);
            }
            Event::ChannelClosed { index } if index == link_at => {
                s.link = None;
                if let Some(o) = &s.open {
                    o.fien.edit(Editor::unshare);
                    o.fien.set_peers(Vec::new());
                }
                pinnacle_rt::println!("fien: sharing ended");
            }
            Event::Closed => {
                s.leave();
                return 0;
            }
            _ => {}
        }
        s.requests();
        if let Some(tap) = take(&s.tapped) {
            s.tap(tap);
        }
        s.sync_link();
        if !s.remount {
            s.draw(false);
        }
    }
}