//! The display server. It owns the screen and the input devices; each app //! gets a window, memory it draws into itself, and says which rectangle //! changed. The server copies just those rectangles to the screen, for the //! one app in front, and draws the status bar above it and the home bar //! below. Nothing runs while nothing changes: the loop waits for a message, //! input, or the next minute for the clock. When the screen turns (F12, as //! an orientation sensor would), it takes a framebuffer of the new size and //! gives every app a new window, which the app lays out afresh. #![no_std] #![no_main] extern crate alloc; use alloc::string::String; use alloc::vec::Vec; use pinnacle_gfx::{Canvas, Color, Rect}; use pinnacle_locale::{t, tf}; use pinnacle_rt::abi::InputEvent; use pinnacle_rt::{Channel, Memory, Process, Received, println}; use pinnacle_ui::access::{self, Preferences}; use pinnacle_ui::layout::{self, shell}; use pinnacle_ui::{protocol, theme}; use pinnacle_view::{IntoView, Screen as View, Signal, el, signal}; /// The Linux key code that turns the screen. const KEY_F12: u16 = 88; struct Client { /// The program it runs, when the server started it. program: String, channel: Channel, title: String, /// Where the window is mapped here too; `None` until the app says hello. window: Option, /// What ends it, when the server started it. process: Option, /// Its interface as the screen reader reads it, as it last sent it. tree: Vec, } struct Server { screen: Memory, width: i32, height: i32, clients: Vec, /// The client in front (the launcher is 0 once it connects). front: Option, /// A press that started on the home bar. home_press: bool, /// A press that started on the close button. close_press: bool, minute: u64, /// Programs the server started and not yet heard from: task id, name, /// and what ends it. started: Vec<(u64, String, Process)>, /// What an app copied last, for any app to paste. clipboard: String, /// The notification shown as a banner, until its time is up. banner: Option, /// A press that started on the banner. banner_press: bool, /// The notifications that came, the newest last, at most /// [`NOTICES_KEPT`]: for the list the status bar's button opens. notices: Vec, /// How many came since the list was last open. unseen: usize, /// Whether the list shows over the app area. listing: bool, /// A press that started on the list or its button: on what. list_press: Option, /// Wrong passwords on the lock screen in a row, and when it takes the /// next try (ms since boot). lock: Lock, /// The password screen, when it shows: nothing of the apps is drawn and /// no input reaches them until the password is typed. unlocking: Option, /// Whether the person's data is in an open vault: then the screen /// locks behind its password. vault_open: bool, /// When the last input came (ms since boot): the screen locks a while /// after it. last_input: u64, /// Connections to `system-confirm`: the agent's gatekeepers, through /// the terminal that started them. askers: Vec, /// The Bluetooth service's end for a paired keyboard's keys, given it /// as it started: what arrives here is a hand on a keyboard, as the /// kernel's input is. No other program holds a way in. bluetooth_keys: Option, /// The questions waiting, the first on show over everything: which /// asker, and what (`pinnacle_ui::confirm`). confirming: Vec<(usize, pinnacle_ui::confirm::Question)>, /// The question on show, built from a view, and the answer tapped. confirm_sheet: Option<(Sheet, Signal>)>, /// The list of notifications on show, built from a view, and what was /// tapped in it. list_sheet: Option<(Sheet, Signal>)>, /// The person's language, text size, contrast and screen reader. prefs: Preferences, reader: Reader, /// To the speech service, once it answered. speech: Option, /// The pointer a mouse or touchpad moves, where it is drawn, and the /// pixels under it. pointer: Option<(i32, i32)>, under: Vec, /// The battery, charger and lid, asked again each minute and when the /// kernel says one changed. power: pinnacle_rt::Power, } /// The screen reader's state: what has its focus, and the gesture under /// way. #[derive(Default)] struct Reader { /// The node with the focus, as it was when it took it. focused: Option, /// Where its ring is drawn, on the screen. ring: Option, /// A finger down: when (ms since boot) and where. down: Option<(u64, i32, i32)>, /// The finger moved on to explore what is under it. exploring: bool, /// A single tap waiting to be one, not the first of two: when it is /// one, and where it was. tap: Option<(u64, i32, i32)>, /// Alt is held: Alt+arrows move the focus, Alt+Enter acts. alt: bool, } /// What a node of the screen reader's list acts through. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Owner { /// The display server's own status and home bars. Chrome, /// The app in front, or a sheet over it. Below, } /// Two taps closer than this are a double tap; a single tap is taken as /// one once it has passed. const DOUBLE_TAP_MS: u64 = 400; /// A swipe: this far across, this quickly. const SWIPE_PX: i32 = 80; const SWIPE_MS: u64 = 500; /// A finger down longer than this before it moves explores what it /// passes over, rather than swiping. const EXPLORE_MS: u64 = 300; /// Linux key codes the reader takes with Alt held. const KEY_LEFTALT: u16 = 56; const KEY_ENTER: u16 = 28; const KEY_LEFT: u16 = 105; const KEY_RIGHT: u16 = 106; #[derive(Default)] struct Lock { failures: u32, wait_until: u64, } /// What the password screen is for. #[derive(Clone, Copy, PartialEq, Eq)] enum Mode { /// The first start: a new vault's password, typed twice. New, /// Each start: the password that opens the vault. Open, /// The screen locked: the same password unlocks it. Locked, } /// The password screen. One strong password opens the data at start and /// unlocks the screen; a fingerprint is to stand beside it where a device /// has a sensor. struct Unlocking { mode: Mode, /// A new password typed once, to be typed again. first: Option, /// What the field holds. entry: Signal, message: String, /// The screen, built from a view: what it says, and Enter typed. sheet: Option, words: Words, submit: Signal>, } impl Unlocking { fn new(mode: Mode) -> Unlocking { Unlocking { mode, first: None, entry: signal(String::new()), message: String::new(), sheet: None, words: Words { title: signal(String::new()), help: signal(String::new()), message: signal(String::new()), clock: signal(String::new()), }, submit: signal(None), } } } /// A password's shortest and longest. const PASSWORD_MIN: usize = 8; const PASSWORD_MAX: usize = 64; /// How long without input before the screen locks. const LOCK_AFTER_MS: u64 = 5 * 60_000; /// How long to wait after five wrong passwords in a row. const LOCKED_OUT_MS: u64 = 30_000; /// A notification on show. struct Banner { /// The app a tap on it opens. app: String, title: String, text: String, /// When it goes (ms since boot). until: u64, } /// How long a notification shows. const BANNER_MS: u64 = 4_000; /// A notification kept for the list, after its banner went. struct Notice { app: String, title: String, text: String, /// When it came, as the clock said ("14:05"). at: String, } /// How many notifications the list keeps; the oldest go first. const NOTICES_KEPT: usize = 50; /// Where the list is kept, so a restart finds it: in the data vault once it /// is open, else on the system disk, as the phone service keeps texts. A /// log of `pinnacle_records::log` written whole at each change: its first /// entry how many are unseen (u32), then a notification an entry, the oldest /// first, each its app, title and time a line and then its text. fn notices_file() -> &'static str { if pinnacle_rt::fs::disk("data").is_some() { "data:/display/notices" } else { "system:/settings/notices" } } impl Notice { fn encode(&self) -> Vec { alloc::format!("{}\n{}\n{}\n{}", self.app, self.title, self.at, self.text).into_bytes() } fn decode(body: &[u8]) -> Option { let body = core::str::from_utf8(body).ok()?; let mut lines = body.splitn(4, '\n'); Some(Notice { app: lines.next()?.into(), title: lines.next()?.into(), at: lines.next()?.into(), text: lines.next()?.into(), }) } } /// What a press on the list, or on the button that opens it, was on. #[derive(Clone, Copy, PartialEq, Eq)] enum ListTarget { Button, Clear, /// The list's row `i`, newest first. Row(usize), } /// How the server's own screens say where their controls are /// (`Screen::announce`), for `cargo xtask` to tap them: in screen pixels for /// the password and the question, which cover the screen, and in the app /// area's for the list of notifications, which covers only it. const ANNOUNCE: &str = "display: button "; /// A screen of the display server's own, built from a view: drawn into /// pixels of its own, then copied onto the screen at `area`, where nothing /// else draws while it shows. struct Sheet { view: View, pixels: Vec, area: Rect, } impl Sheet { fn new(area: Rect, page: pinnacle_view::View) -> Sheet { let mut view = View::new(area.width as u32, area.height as u32); view.mount(page); Sheet { view, pixels: alloc::vec![0; (area.width * area.height).max(0) as usize], area, } } /// Draws what changed (everything with `all`) onto `screen`, `width` /// pixels a row, and flushes it there. fn draw(&mut self, screen: &mut [u32], width: i32, all: bool) { let (w, h) = (self.area.width, self.area.height); let drawn = { let mut canvas = Canvas::new(&mut self.pixels, w as u32, h as u32); self.view.draw(&mut canvas, all) }; let Some(r) = drawn else { return }; let r = r.intersect(&Rect::new(0, 0, w, h)); for y in r.y..r.bottom() { let from = (y * w + r.x) as usize; let to = ((y + self.area.y) * width + r.x + self.area.x) as usize; screen[to..to + r.width as usize].copy_from_slice(&self.pixels[from..from + r.width as usize]); } flush(Rect::new(r.x + self.area.x, r.y + self.area.y, r.width, r.height)); } /// Input in screen pixels, to the view in its own. fn input(&mut self, event: &InputEvent) { let mut moved = *event; if matches!(event.kind, InputEvent::PRESS | InputEvent::MOVE) { moved.x -= self.area.x; moved.y -= self.area.y; } self.view.input(&moved); } fn announce(&mut self) { self.view.announce(ANNOUNCE); } } /// Takes what a signal holds, leaving it empty. fn take(s: &Signal>) -> Option { let v = s.get_untracked(); if v.is_some() { s.set(None); } v } /// What the password screen shows; the field's text is its own signal. #[derive(Clone)] struct Words { title: Signal, help: Signal, message: Signal, clock: Signal, } /// The password screen: the time when locked, what to do, the field (its /// text in dots), and what came of the last try; Enter submits. fn password_page( words: &Words, locked: bool, entry: &Signal, submit: &Signal>, ) -> pinnacle_view::View { let mut column = el("main").attr( "style", "max-width: 640px; margin: 0 auto; padding: 90px 18px 24px; display: flex; \ flex-direction: column; gap: 12px", ); if locked { column = column.child( el("div") .attr( "style", "font-size: 54px; color: var(--m-text-strong); margin-bottom: 36px", ) .child(words.clock.clone()), ); } let typed = entry.clone(); let submit = submit.clone(); column .child( el("h1") .attr("style", "font-size: 30px; margin: 0") .child(words.title.clone()), ) .child( el("p") .attr("style", "margin: 0; font-size: 12px; color: var(--m-text-dim)") .child(words.help.clone()), ) .child( el("input") .class("m-input") .attr("type", "password") .attr("data-name", "password") .attr("enterkeyhint", "go") .attr("style", "width: 100%; margin-top: 16px; border-radius: 999px") .prop("value", entry.clone()) .prop_bool("@focus", true) .on("input", move |e| { let v: String = e .value .clone() .unwrap_or_default() .chars() .take(PASSWORD_MAX) .collect(); typed.set(v); }) .on("keydown", move |e| { if e.key.as_deref() == Some("Enter") { submit.set(Some(())); e.prevent_default(); } }), ) .child( el("p") .attr("style", "margin: 0; color: var(--m-text-dim)") .child(words.message.clone()), ) .into_view() } /// The agent's question, over everything: which app asks, what, the /// detail, and Allow or Don't allow. fn confirm_page(q: &pinnacle_ui::confirm::Question, answer: &Signal>) -> pinnacle_view::View { let button = |label: &'static str, name: &'static str, variant: Option<&'static str>, yes: bool| { let answer = answer.clone(); el("button") .class("m-button") .attr("type", "button") .attr("data-variant", variant) .attr("data-name", name) .attr("style", "flex: 1") .on("click", move |_| answer.set(Some(yes))) .child(label) }; el("main") .attr( "style", "height: 100vh; max-width: 640px; margin: 0 auto; padding: 90px 18px 36px; \ display: flex; flex-direction: column; gap: 16px", ) .child( el("p") .attr("style", "margin: 0; font-size: 12px; color: var(--m-accent-text)") .child(tf("The agent, in {}", &[&theme::display_name(&q.app)])), ) .child( el("h1") .attr("style", "margin: 0; font-size: 30px") .child(q.question.clone()), ) .child( el("p") .attr( "style", "flex: 1; min-height: 0; overflow: hidden; margin: 0; font-size: 12px; \ color: var(--m-text-dim); white-space: pre-wrap", ) .child(q.detail.clone()), ) .child( el("div") .attr("style", "display: flex; gap: 12px") .child(button(t("Don't allow"), "deny", None, false)) .child(button(t("Allow"), "allow", Some("primary"), true)), ) .into_view() } /// The list of past notifications, over the app area: a heading, Clear, /// and a card each, the newest first. fn list_page(notices: &[Notice], tapped: &Signal>) -> pinnacle_view::View { let mut head = el("div") .attr("style", "display: flex; align-items: center; gap: 12px") .child( el("h1") .attr("style", "flex: 1; margin: 0; font-size: 21px") .child(t("Notifications")), ); if !notices.is_empty() { let tapped = tapped.clone(); head = head.child( el("button") .class("m-button") .attr("type", "button") .attr("data-name", "clear") .on("click", move |_| tapped.set(Some(ListTarget::Clear))) .child(t("Clear")), ); } let mut list = el("main") .attr( "style", "max-width: 640px; margin: 0 auto; padding: 24px 16px; display: flex; \ flex-direction: column; gap: 12px", ) .child(head); if notices.is_empty() { list = list.child( el("p") .attr("style", "margin: 0; color: var(--m-text-dim)") .child(t("No notifications")), ); } for (i, n) in notices.iter().rev().enumerate() { let tapped = tapped.clone(); let small = "font-size: 12px; color: var(--m-text-dim)"; list = list.child( el("button") .attr("type", "button") .attr("data-name", alloc::format!("notice-{i}")) .attr( "style", "display: flex; flex-direction: column; align-items: stretch; gap: 4px; \ padding: 14px 18px; border: 0; text-align: start; color: var(--m-text); \ background: var(--m-surface); border-radius: var(--m-radius-lg)", ) .on("click", move |_| tapped.set(Some(ListTarget::Row(i)))) .child( el("div") .attr( "style", "display: flex; justify-content: space-between; gap: 12px", ) .child(el("span").attr("style", small).child(theme::display_name(&n.app))) .child(el("span").attr("style", small).child(n.at.clone())), ) .child( el("span") .attr("style", "white-space: nowrap; overflow: hidden") .child(n.title.clone()), ) .child( el("span") .attr( "style", alloc::format!("{small}; white-space: nowrap; overflow: hidden"), ) .child(n.text.clone()), ), ); } list.into_view() } impl Server { fn app_rect(&self) -> Rect { shell::app_area(self.width, self.height) } fn canvas(&mut self) -> Canvas<'_> { let (w, h) = (self.width as u32, self.height as u32); Canvas::new(self.screen.pixels(), w, h) } /// Whether the app in front can be closed: one the server started, not /// the home screen. fn closable(&self) -> bool { self.front .map(|i| &self.clients[i]) .is_some_and(|c| c.process.is_some() && c.program != "launcher") } /// Ends the app in front. Its channel closes, and [`closed`](Self::closed) /// brings the home screen back. fn close_front(&mut self) { let Some(front) = self.front else { return }; let client = &self.clients[front]; if let Some(process) = &client.process && process.kill() { println!("display: closed {}", client.title); } } /// A notification (its app, title and text, a line each): a banner, /// unless its app is in front, which shows it its own way. fn notify(&mut self, body: &str) { let mut lines = body.splitn(3, '\n'); let (app, title, text) = ( lines.next().unwrap_or(""), lines.next().unwrap_or(""), lines.next().unwrap_or(""), ); if self.front.is_some_and(|f| self.clients[f].program == app) && !self.listing { println!("display: a notice for {app}, which is in front"); return; } if self.notices.len() == NOTICES_KEPT { self.notices.remove(0); } self.notices.push(Notice { app: app.into(), title: title.into(), text: text.into(), at: clock_text(), }); self.unseen += 1; self.keep_notices(); if self.covered() { println!("display: a notice for {app}, while locked: kept for the list"); return; } if self.listing { println!("display: notice from {app}: {title}, in the list"); self.draw_list(); return self.draw_status(); } self.dismiss_banner(); self.banner = Some(Banner { app: app.into(), title: title.into(), text: text.into(), until: pinnacle_rt::time() + BANNER_MS, }); self.draw_banner(); self.draw_status(); println!("display: notice from {app}: {title}"); } /// Opens the list of past notifications over the app area: they are /// seen now. fn open_list(&mut self) { self.banner = None; self.listing = true; self.unseen = 0; self.keep_notices(); self.draw_list(); self.draw_status(); println!("display: listed {} notices", self.notices.len()); } /// Writes the list where [`notices_file`] says, whole: one transaction, /// so a power cut leaves the list before or after. fn keep_notices(&self) { let path = notices_file(); if let Some(folder) = path.strip_suffix("/notices") { pinnacle_rt::fs::create_dir(folder); } let unseen = (self.unseen as u32).to_le_bytes(); let mut file = pinnacle_records::log::entry(&unseen, true); for notice in &self.notices { file.extend(pinnacle_records::log::entry(¬ice.encode(), false)); } if !pinnacle_rt::fs::write(path, &file) { println!("display: could not keep the notices in {path}"); } } /// The list as it was kept before this start, once the person's data is /// open: the bell shows at once, with how many were not seen. fn read_notices(&mut self) { let Some(file) = pinnacle_rt::fs::read(notices_file()) else { return; }; let Some(entries) = pinnacle_records::log::entries(&file) else { return; }; let Some((unseen, rest)) = entries.split_first() else { return; }; self.notices = rest.iter().filter_map(|e| Notice::decode(e)).collect(); let excess = self.notices.len().saturating_sub(NOTICES_KEPT); self.notices.drain(..excess); self.unseen = unseen .get(..4) .map_or(0, |u| u32::from_le_bytes(u.try_into().unwrap()) as usize) .min(self.notices.len()); println!( "display: {} notices kept from before, {} unseen", self.notices.len(), self.unseen ); self.draw_status(); } /// Closes the list, showing the app in front again. fn close_list(&mut self) { self.listing = false; self.list_sheet = None; match self.front { Some(front) => self.bring_to_front(front), None => { let area = self.app_rect(); self.canvas().fill_rect(area, theme::BACKGROUND); flush(area); self.draw_status(); } } } /// The list: a heading, Clear, and a card a notification, the newest /// first; more than fit scroll. Drawn by the display server, so no app /// sees another's notifications. fn draw_list(&mut self) { if self.covered() || !self.listing { self.list_sheet = None; return; } let tapped = signal(None); let mut sheet = Sheet::new(self.app_rect(), list_page(&self.notices, &tapped)); let width = self.width; sheet.draw(self.screen.pixels(), width, true); sheet.announce(); self.list_sheet = Some((sheet, tapped)); } /// A press on the button that opens the list, at (`x`, `y`) on the /// screen. fn list_target(&self, x: i32, y: i32) -> Option { (!self.notices.is_empty() && shell::notices(self.width).contains(x, y)).then_some(ListTarget::Button) } /// Input on the list, while it shows: to its view, and what was tapped /// in it acted on. fn list_input(&mut self, event: &InputEvent) { let Some((sheet, tapped)) = &mut self.list_sheet else { return; }; sheet.input(event); match take(tapped) { Some(target) => self.list_tapped(target), None => { let width = self.width; if let Some((sheet, _)) = &mut self.list_sheet { sheet.draw(self.screen.pixels(), width, false); } } } } fn list_tapped(&mut self, target: ListTarget) { match target { ListTarget::Button if self.listing => self.close_list(), ListTarget::Button => self.open_list(), ListTarget::Clear => { self.notices.clear(); self.keep_notices(); println!("display: notices cleared"); self.draw_list(); self.draw_status(); } ListTarget::Row(i) => { let app = self.notices[self.notices.len() - 1 - i].app.clone(); println!("display: opening {app} from the list"); self.close_list(); self.start(&app); } } } fn draw_banner(&mut self) { if self.covered() || self.listing { return; } let Some(banner) = &self.banner else { return }; let r = shell::banner(self.width); let full = Rect::new(0, 0, self.width, self.height); let (app, title, text) = ( theme::display_name(&banner.app), banner.title.clone(), banner.text.clone(), ); let mut canvas = self.canvas(); canvas.fill_rounded(r, theme::RADIUS, theme::SURFACE_PRESSED); let (small, body) = (theme::small(), theme::body()); canvas.text(small, r.x + 24, r.y + 32, &app, theme::TEXT_DIM); canvas.set_clip(Rect::new(r.x + 16, r.y, r.width - 32, r.height)); // a line's descenders kept canvas.text(body, r.x + 24, r.y + 64, &title, theme::TEXT); canvas.text(small, r.x + 24, r.y + 92, &text, theme::TEXT_DIM); canvas.set_clip(full); flush(r); } /// Takes the banner away, showing what was under it. fn dismiss_banner(&mut self) { if self.banner.take().is_none() { return; } let r = shell::banner(self.width); self.canvas().fill_rect(r, theme::BACKGROUND); let area = self.app_rect(); self.show(Rect::new(r.x, r.y - area.y, r.width, r.height)); } /// The front app drew `rect` (window coordinates) over the banner: /// the banner goes back on top. fn redraw_banner_over(&mut self, rect: Rect) { let area = self.app_rect(); let on_screen = Rect::new(rect.x, rect.y + area.y, rect.width, rect.height); if self.banner.is_some() && !on_screen.intersect(&shell::banner(self.width)).is_empty() { self.draw_banner(); } } /// Whether the password screen or a confirmation covers the apps. fn covered(&self) -> bool { self.unlocking.is_some() || self.confirming().is_some() } /// The agent's question on show: not while the screen is locked, which /// it waits behind (what is confirmed is confirmed by whoever unlocked). fn confirming(&self) -> Option<&pinnacle_ui::confirm::Question> { self.confirming .first() .filter(|_| self.unlocking.is_none()) .map(|(_, q)| q) } /// Draws the agent's question over everything: no app can draw on it /// or see it, and only a hand on the device answers it. fn draw_confirming(&mut self) { let Some(q) = self.confirming().cloned() else { self.confirm_sheet = None; return; }; let answer = signal(None); let mut sheet = Sheet::new( Rect::new(0, 0, self.width, self.height), confirm_page(&q, &answer), ); let width = self.width; sheet.draw(self.screen.pixels(), width, true); sheet.announce(); self.confirm_sheet = Some((sheet, answer)); } /// A question from asker `asker`: shown at once, or after those before it. fn confirm(&mut self, asker: usize, question: pinnacle_ui::confirm::Question) { println!("display: the agent asks: {}", question.question); self.confirming.push((asker, question)); if self.confirming.len() == 1 && self.unlocking.is_none() { self.banner = None; self.draw_confirming(); } } /// The person answered the question on show. fn answer_confirm(&mut self, allowed: bool) { let (asker, q) = self.confirming.remove(0); println!( "display: {} {}", if allowed { "allowed" } else { "not allowed" }, q.question ); let answer = if allowed { pinnacle_ui::confirm::YES } else { pinnacle_ui::confirm::NO }; self.askers[asker].send(answer, Vec::new()); if self.confirming().is_some() { return self.draw_confirming(); } self.canvas().fill(theme::BACKGROUND); self.draw_home_bar(); match self.front { Some(front) => self.bring_to_front(front), None => self.draw_status(), } } fn confirming_input(&mut self, event: InputEvent) { // Only a hand on the device answers: never input an agent made. if event.synthetic || !matches!(event.kind, InputEvent::PRESS | InputEvent::MOVE) { return; } let width = self.width; let Some((sheet, answer)) = &mut self.confirm_sheet else { return; }; sheet.input(&event); match take(answer) { Some(allowed) => { self.confirm_sheet = None; self.answer_confirm(allowed); } None => sheet.draw(self.screen.pixels(), width, false), } } /// An asker went: its questions go too, unanswered. fn asker_gone(&mut self, asker: usize) { self.askers.remove(asker); let shown = self.confirming.first().map(|(a, _)| *a); self.confirming.retain(|(a, _)| *a != asker); for (a, _) in &mut self.confirming { if *a > asker { *a -= 1; } } if shown == Some(asker) { if self.confirming().is_some() { self.draw_confirming(); } else if self.unlocking.is_none() { self.canvas().fill(theme::BACKGROUND); self.draw_home_bar(); match self.front { Some(front) => self.bring_to_front(front), None => self.draw_status(), } } } } /// The rest of the system, once the person's data can be read: the /// p2p, Bluetooth, phone and model services in the background, and the home /// screen. fn start_system(&mut self) { // The notifications of before, ahead of any new one from the // services started here. self.read_notices(); // The peer-to-peer service runs in the background, with no window. pinnacle_rt::spawn("p2p", 0, Vec::new()); // The Bluetooth service too: this device's host stack, for apps and // for contacts nearby, with a channel for a paired keyboard's keys // (argument 1: it is handle 1). let (keys, theirs) = Channel::pair(); if pinnacle_rt::spawn("bt", 1, alloc::vec![theirs.0]).is_some() { self.bluetooth_keys = Some(keys); } // And the phone service, for ordinary calls over the modem when a // contact cannot be reached peer to peer. pinnacle_rt::spawn("phone", 0, Vec::new()); // And the Wi-Fi service, which joins the networks kept again by // itself. pinnacle_rt::spawn("wifi", 0, Vec::new()); // The model service: it sends nothing until Settings → Agent turns // the agent on. pinnacle_rt::spawn("model", 0, Vec::new()); // The updates service: it looks for new versions of the apps now // and then, as Settings → Updates chose. pinnacle_rt::spawn("updates", 0, Vec::new()); // The sync service: the vault kept in step with the person's other // devices. pinnacle_rt::spawn("sync", 0, Vec::new()); self.start("launcher"); } fn draw_unlocking(&mut self) { let (width, height) = (self.width, self.height); let wait_until = self.lock.wait_until; let Some(unlocking) = &mut self.unlocking else { return; }; let now = pinnacle_rt::time(); let (title, help) = match (unlocking.mode, &unlocking.first) { (Mode::New, None) => ( t("Choose a password"), t( "It opens your data each time the device starts, and unlocks the screen. At least eight characters; nobody can recover it.", ), ), (Mode::New, Some(_)) => (t("The password again"), t("To be sure of it.")), (Mode::Open, _) => (t("Your data is locked"), t("Type your password to open it.")), (Mode::Locked, _) => (t("Locked"), t("Type your password to unlock.")), }; let message = if unlocking.mode == Mode::Locked && now < wait_until { tf( "Try again in {} s", &[&alloc::format!("{}", (wait_until - now).div_ceil(1000))], ) } else { unlocking.message.clone() }; let words = &unlocking.words; words.title.set(title.into()); words.help.set(help.into()); words.message.set(message); words.clock.set(clock_text()); // The screen is built once, and changes by its words; a new size // builds it again. let area = Rect::new(0, 0, width, height); let all = unlocking.sheet.as_ref().is_none_or(|s| s.area != area); if all { let page = password_page( &unlocking.words, unlocking.mode == Mode::Locked, &unlocking.entry, &unlocking.submit, ); unlocking.sheet = Some(Sheet::new(area, page)); } let sheet = unlocking.sheet.as_mut().expect("built"); sheet.draw(self.screen.pixels(), width, all); if all { sheet.announce(); } } fn unlocking_input(&mut self, event: InputEvent) { let Some(unlocking) = &mut self.unlocking else { return; }; let Some(sheet) = &mut unlocking.sheet else { return }; sheet.input(&event); if take(&unlocking.submit).is_some() { return self.submit_password(); } self.draw_unlocking(); } fn submit_password(&mut self) { let now = pinnacle_rt::time(); let unlocking = self.unlocking.as_mut().unwrap(); let entry = unlocking.entry.get_untracked(); unlocking.entry.set(String::new()); let mode = unlocking.mode; if mode == Mode::Locked && now < self.lock.wait_until { return self.draw_unlocking(); } if mode == Mode::New && unlocking.first.is_none() { if entry.chars().count() < PASSWORD_MIN { unlocking.message = t("At least eight characters, please").into(); } else { unlocking.first = Some(entry); unlocking.message.clear(); } return self.draw_unlocking(); } if mode == Mode::New && unlocking.first.as_deref() != Some(&entry) { unlocking.first = None; unlocking.message = t("The two differed: choose it again").into(); return self.draw_unlocking(); } unlocking.message = match mode { Mode::New => t("Making your vault…"), Mode::Open => t("Opening…"), Mode::Locked => t("Checking…"), } .into(); self.draw_unlocking(); // A moment: the password is stretched on purpose. let right = match mode { Mode::New => pinnacle_rt::vault::create(&entry), Mode::Open => pinnacle_rt::vault::open(&entry), Mode::Locked => pinnacle_rt::vault::check(&entry), }; if !right { let message = match mode { Mode::New => t("Could not make the vault"), _ => t("Wrong password"), }; println!("display: {}", message.to_lowercase()); if mode == Mode::Locked { self.lock.failures += 1; if self.lock.failures >= 5 { self.lock.wait_until = now + LOCKED_OUT_MS; } } self.unlocking.as_mut().unwrap().message = message.into(); return self.draw_unlocking(); } self.unlocking = None; self.lock = Lock::default(); self.canvas().fill(theme::BACKGROUND); self.draw_home_bar(); if mode == Mode::Locked && self.confirming().is_some() { println!("display: unlocked"); self.draw_confirming(); } else if mode == Mode::Locked { println!("display: unlocked"); match self.front { Some(front) => self.bring_to_front(front), None => self.draw_status(), } } else { println!("display: data opened"); self.vault_open = true; self.draw_status(); self.start_system(); } } /// Locks the screen behind the password, when the data is in a vault. fn lock(&mut self) { if !self.vault_open || self.unlocking.is_some() { return; } self.banner = None; self.unlocking = Some(Unlocking::new(Mode::Locked)); self.draw_unlocking(); println!("display: locked"); } fn draw_status(&mut self) { if self.covered() { return; } let width = self.width; let title = match self.front { _ if self.listing => String::from(t("Notifications")), Some(i) => String::from(pinnacle_locale::tr(&self.clients[i].title)), None => String::new(), }; let closable = self.closable(); let (kept, unseen, listing) = (!self.notices.is_empty(), self.unseen, self.listing); let battery = self .power .batteries .iter() .find(|b| b.state != "absent") .and_then(|b| Some((b.percent?, b.state == "charging"))); let clock = clock_text(); let mut canvas = self.canvas(); let bar = Rect::new(0, 0, width, shell::STATUS); let margin = layout::margin(width); canvas.fill_rect(bar, theme::BACKGROUND); let font = theme::body(); let baseline = (shell::STATUS + font.ascent - font.descent) / 2; let mut x = margin; if closable { let close = shell::close(width); canvas.fill_rounded(close, close.height / 2, theme::SURFACE); canvas.text_centered(font, close, "\u{d7}", theme::TEXT); x = close.right() + 12; } canvas.text(font, x, baseline, &title, theme::TEXT_DIM); // The notifications' button, once one came: a bell, and how many // came since the list was open, on the accent while there are any. if kept { let r = shell::notices(width); let fill = match () { _ if unseen > 0 => theme::ACCENT, _ if listing => theme::SURFACE_PRESSED, _ => theme::SURFACE, }; canvas.fill_rounded(r, r.height / 2, fill); let (cx, cy) = (r.x + 22, r.y + r.height / 2); canvas.fill_round_rect(Rect::new(cx - 8, cy - 10, 16, 16), [8, 8, 2, 2], theme::TEXT, 255); canvas.fill_rect(Rect::new(cx - 11, cy + 5, 22, 3), theme::TEXT); canvas.fill_circle(cx, cy + 10, 3, theme::TEXT); if unseen > 0 { let count = if unseen > 9 { String::from("9+") } else { alloc::format!("{unseen}") }; let count_box = Rect::new(r.x + 34, r.y, r.width - 38, r.height); canvas.text_centered(theme::small(), count_box, &count, theme::TEXT); } } let x = width - margin - font.measure(&clock); canvas.text(font, x, baseline, &clock, theme::TEXT); // The battery, left of the clock: how full, drawn and as a number; // a bolt while it charges, red when it is nearly empty. if let Some((percent, charging)) = battery { let small = theme::small(); let label = alloc::format!("{percent}%"); let label_x = x - 14 - small.measure(&label); canvas.text(small, label_x, baseline, &label, theme::TEXT_DIM); let (w, h) = (24, 12); let body = Rect::new(label_x - 8 - w - 3, (shell::STATUS - h) / 2, w, h); let low = percent <= 10 && !charging; let ink = if low { theme::BAD } else { theme::TEXT }; canvas.fill_rounded(body, 3, ink); canvas.fill_rounded( Rect::new(body.x + 2, body.y + 2, w - 4, h - 4), 2, theme::BACKGROUND, ); let fill = ((w - 6) * i32::from(percent) / 100).max(1); canvas.fill_rect(Rect::new(body.x + 3, body.y + 3, fill, h - 6), ink); canvas.fill_rect(Rect::new(body.right(), body.y + 3, 3, h - 6), ink); if charging { // A bolt across the body, in the bar's own colour around // it so it reads on any fill. let (cx, cy) = (body.x + w / 2, body.y + h / 2); for (dx, dy, bw, bh) in [(0, -5, 3, 6), (-3, -1, 6, 2), (-2, 0, 3, 6)] { canvas.fill_rect( Rect::new(cx + dx - 1, cy + dy - 1, bw + 2, bh + 2), theme::BACKGROUND, ); } for (dx, dy, bw, bh) in [(0, -5, 3, 6), (-3, -1, 6, 2), (-2, 0, 3, 6)] { canvas.fill_rect(Rect::new(cx + dx, cy + dy, bw, bh), theme::ACCENT); } } } flush(bar); self.pointer_over(bar); } fn draw_home_bar(&mut self) { if self.covered() { return; } let (width, height) = (self.width, self.height); let mut canvas = self.canvas(); canvas.fill_rect( Rect::new(0, height - shell::HOME_BAR, width, shell::HOME_BAR), theme::BACKGROUND, ); canvas.fill_rounded(shell::pill(width, height), 3, Color::rgb(0x9a, 0xa3, 0xaf)); flush(Rect::new(0, height - shell::HOME_BAR, width, shell::HOME_BAR)); self.pointer_over(Rect::new(0, height - shell::HOME_BAR, width, shell::HOME_BAR)); } /// Copies `rect` (window coordinates) of the front app's window to the /// screen. fn show(&mut self, rect: Rect) { if self.covered() || self.listing { return; } let area = self.app_rect(); let Some(front) = self.front else { return }; let Some(window) = self.clients[front].window else { return; }; let window_rect = Rect::new(0, 0, area.width, area.height); let r = rect.intersect(&window_rect); let source = window as *const u32; let width = self.width as usize; let target = self.screen.pixels(); for y in r.y..r.bottom() { let from = (y * area.width + r.x) as usize; let to = (y + area.y) as usize * width + r.x as usize; // SAFETY: inside the mapped window, `area` pixels a row. let row = unsafe { core::slice::from_raw_parts(source.add(from), r.width as usize) }; target[to..to + r.width as usize].copy_from_slice(row); } flush(Rect::new(r.x, r.y + area.y, r.width, r.height)); self.pointer_over(Rect::new(r.x, r.y + area.y, r.width, r.height)); if let Some(ring) = self.reader.ring && !ring .intersect(&Rect::new(r.x, r.y + area.y, r.width, r.height)) .is_empty() { self.draw_ring(); } } fn bring_to_front(&mut self, index: usize) { // An app coming forward closes the list. self.listing = false; if let Some(old) = self.front.filter(|&old| old != index) { self.clients[old] .channel .send(&pinnacle_ui::message(protocol::SHOWN, &[0]), Vec::new()); } self.front = Some(index); self.clients[index] .channel .send(&pinnacle_ui::message(protocol::SHOWN, &[1]), Vec::new()); let area = self.app_rect(); self.reader.ring = None; self.show(Rect::new(0, 0, area.width, area.height)); self.draw_banner(); self.draw_status(); if self.prefs.reader { self.reader.focused = None; let title = String::from(pinnacle_locale::tr(&self.clients[index].title)); self.speak(&title); } } /// Brings program `name` to the front, starting it if it is not running. fn start(&mut self, name: &str) { // One a service started (the p2p or phone service, Calls on a // ring) has no program name here: its title says which it is. let running = |c: &&Client| c.program == name || (c.program.is_empty() && c.title.eq_ignore_ascii_case(name)); if let Some(i) = self.clients.iter().position(|c| running(&c)) { return self.bring_to_front(i); } match pinnacle_rt::spawn_process(name, 0, Vec::new()) { Some((pid, process)) => self.started.push((pid, name.into(), process)), None => println!("display: no program {name}"), } } /// Gives client `index` a window the size of the app area, in place of /// the one it had, which goes back. fn send_window(&mut self, index: usize) { let area = self.app_rect(); let Some(memory) = Memory::new((area.width * area.height * 4) as usize) else { return; }; let Memory { handle, address, .. } = memory; let mut body = Vec::new(); body.extend_from_slice(&(area.width as u32).to_le_bytes()); body.extend_from_slice(&(area.height as u32).to_le_bytes()); let client = &mut self.clients[index]; client.channel.send( &pinnacle_ui::message(protocol::WINDOW, &body), alloc::vec![handle], ); // Still mapped here, though the handle went to the app, until the // app closes (`closed`) or gets another. if let Some(old) = client.window.replace(address) { pinnacle_rt::unmap(old); } } fn hello(&mut self, index: usize, title: &str) { self.clients[index].title = title.into(); // The preferences before the window, so the app's first frame is // in the person's language and size, and its tree goes with it // while the screen reader reads. let client = &self.clients[index].channel; client.send( &pinnacle_ui::message(protocol::PREFERENCES, &self.prefs.to_bytes()), Vec::new(), ); if self.prefs.reader { client.send(&pinnacle_ui::message(protocol::WANT_TREE, &[1]), Vec::new()); } self.send_window(index); self.bring_to_front(index); } /// Settings changed the preferences: read them again, tell every app, /// and draw the server's own parts in the new language. fn preferences_changed(&mut self) { let was = self.prefs; self.prefs = Preferences::read(); access::set(self.prefs); println!( "display: preferences: language {}, text {} %, contrast {}, reader {}", self.prefs.language.code(), self.prefs.text_size, if self.prefs.high_contrast { "high" } else { "normal" }, if self.prefs.reader { "on" } else { "off" } ); let body = self.prefs.to_bytes(); for c in &self.clients { c.channel .send(&pinnacle_ui::message(protocol::PREFERENCES, &body), Vec::new()); if was.reader != self.prefs.reader { c.channel.send( &pinnacle_ui::message(protocol::WANT_TREE, &[u8::from(self.prefs.reader)]), Vec::new(), ); } } if was.reader != self.prefs.reader { self.erase_ring(); self.reader = Reader::default(); for c in &mut self.clients { c.tree.clear(); } self.speak(if self.prefs.reader { t("Screen reader on") } else { t("Screen reader off") }); // Drawn again, so its tree comes. if let Some(front) = self.front { self.clients[front] .channel .send(&pinnacle_ui::message(protocol::SHOWN, &[1]), Vec::new()); } } self.draw_status(); } /// Says `text` aloud, through the speech service, and on the console. fn speak(&mut self, text: &str) { println!("reader: {text}"); if self.speech.is_none() { self.speech = pinnacle_rt::connect(pinnacle_ui::access::SPEECH); } if self.speech.is_none() { // Started the first time the reader speaks, and waited for a // moment: the first words are not lost. let started = pinnacle_rt::spawn("speech", 0, Vec::new()).is_some(); for _ in 0..if started { 50 } else { 0 } { pinnacle_rt::sleep(10); self.speech = pinnacle_rt::connect(pinnacle_ui::access::SPEECH); if self.speech.is_some() { break; } } } if let Some(speech) = &self.speech { let mut body = alloc::vec![self.prefs.language as u8]; body.extend_from_slice(text.as_bytes()); if !speech.send(&body, Vec::new()) { self.speech = None; } } } /// What the screen reader reads now, in screen pixels, in reading /// order: a sheet over everything when one shows; else the status bar, /// the app in front and the home bar. fn reader_nodes(&self) -> Vec<(access::Node, Owner)> { let sheet = |sheet: &Sheet| -> Vec<(access::Node, Owner)> { sheet .view .access_tree() .into_iter() .map(|mut n| { n.rect = Rect::new( n.rect.x + sheet.area.x, n.rect.y + sheet.area.y, n.rect.width, n.rect.height, ); (n, Owner::Below) }) .collect() }; if let Some(sheet_) = self.unlocking.as_ref().and_then(|u| u.sheet.as_ref()) { return sheet(sheet_); } if self.confirming().is_some() && let Some((sheet_, _)) = &self.confirm_sheet { return sheet(sheet_); } let node = |role, name: &str, rect| access::Node { role, name: String::from(name), value: String::new(), checked: None, disabled: false, rect, }; let mut out = Vec::new(); let width = self.width; let title_x = layout::margin(width); if self.closable() { out.push(( node(access::Role::Button, t("Close"), shell::close(width)), Owner::Chrome, )); } if let Some(front) = self.front.filter(|_| !self.listing) { let title = pinnacle_locale::tr(&self.clients[front].title); out.push(( node( access::Role::Heading, title, Rect::new(title_x, 0, width / 2, shell::STATUS), ), Owner::Chrome, )); } if !self.notices.is_empty() { let name = if self.unseen > 0 { tf("Notifications, {} new", &[&alloc::format!("{}", self.unseen)]) } else { String::from(t("Notifications")) }; out.push(( node(access::Role::Button, &name, shell::notices(width)), Owner::Chrome, )); } out.push(( node( access::Role::Text, &clock_text(), Rect::new(width - 120, 0, 120, shell::STATUS), ), Owner::Chrome, )); if self.listing { if let Some((sheet_, _)) = &self.list_sheet { out.extend(sheet(sheet_)); } } else if let Some(front) = self.front { let area = self.app_rect(); out.extend(self.clients[front].tree.iter().cloned().map(|mut n| { n.rect = Rect::new(n.rect.x, n.rect.y + area.y, n.rect.width, n.rect.height); (n, Owner::Below) })); } let home = Rect::new(0, self.height - shell::HOME_BAR, width, shell::HOME_BAR); out.push((node(access::Role::Button, t("Home"), home), Owner::Chrome)); out } /// Which of `nodes` is the focused one: the same node, else one of /// the same role and name (the app drew it again elsewhere). fn focus_index(&self, nodes: &[(access::Node, Owner)]) -> Option { let f = self.reader.focused.as_ref()?; nodes.iter().position(|(n, _)| n == f).or_else(|| { nodes .iter() .position(|(n, _)| n.role == f.role && n.name == f.name) }) } /// Gives `node` the focus: its ring drawn, its words said. fn focus(&mut self, node: access::Node) { if self.reader.focused.as_ref() == Some(&node) { return; } let words = node.speech(); self.erase_ring(); self.reader.focused = Some(node); self.draw_ring(); self.speak(&words); } /// The focus to what is under a finger at `x`, `y`. fn explore(&mut self, x: i32, y: i32) { let nodes = self.reader_nodes(); // The smallest node under the finger: a button in its row. let under = nodes .into_iter() .filter(|(n, _)| n.rect.contains(x, y)) .min_by_key(|(n, _)| n.rect.width as i64 * n.rect.height as i64); if let Some((node, _)) = under { self.focus(node); } } /// The focus to the next node (`by` 1) or the one before (-1). fn step(&mut self, by: isize) { let nodes = self.reader_nodes(); if nodes.is_empty() { return; } let next = match self.focus_index(&nodes) { Some(i) => i as isize + by, None if by > 0 => 0, None => nodes.len() as isize - 1, }; if next < 0 || next >= nodes.len() as isize { // The ends: said, and the focus stays. self.speak(if by > 0 { t("End") } else { t("Start") }); return; } let node = nodes[next as usize].0.clone(); self.focus(node); } /// What a double tap does: a press and a release at the focused /// node's centre, as a finger there would make them. They are the /// person's, so not marked synthetic. fn activate(&mut self) { let nodes = self.reader_nodes(); let Some(i) = self.focus_index(&nodes) else { self.speak(t("Nothing selected")); return; }; let (node, _) = &nodes[i]; if !node.role.actionable() { return; } let (x, y) = ( node.rect.x + node.rect.width / 2, node.rect.y + node.rect.height / 2, ); println!("reader: activating {}", node.name); for value in [1, 0] { self.dispatch(InputEvent { kind: InputEvent::PRESS, code: 0, value, x, y, synthetic: false, }); } } /// Input while the reader is on: a finger explores, a double tap acts, /// a swipe moves on; keys go to the app but for Alt and the arrows. fn reader_input(&mut self, event: InputEvent) { let now = pinnacle_rt::time(); match event.kind { InputEvent::KEY => { if event.code == KEY_LEFTALT { self.reader.alt = event.value != 0; return self.dispatch(event); } if self.reader.alt { let pressed = event.value != 0; match event.code { KEY_RIGHT if pressed => return self.step(1), KEY_LEFT if pressed => return self.step(-1), KEY_ENTER if pressed => return self.activate(), KEY_RIGHT | KEY_LEFT | KEY_ENTER => return, _ => {} } } self.dispatch(event) } InputEvent::PRESS if event.value != 0 => { self.reader.down = Some((now, event.x, event.y)); self.reader.exploring = false; } // A finger held and moved explores; a quick one is a swipe. InputEvent::MOVE => { if let Some((t0, x0, y0)) = self.reader.down && (self.reader.exploring || (event.x - x0).abs() + (event.y - y0).abs() > 24 && now - t0 > EXPLORE_MS) { self.reader.exploring = true; self.explore(event.x, event.y); } } InputEvent::PRESS => { let Some((t0, x0, y0)) = self.reader.down.take() else { return; }; let (dx, dy) = (event.x - x0, event.y - y0); let quick = now - t0 < SWIPE_MS; if quick && dx.abs() > SWIPE_PX && dx.abs() > 2 * dy.abs() { self.reader.tap = None; return self.step(if dx > 0 { 1 } else { -1 }); } if self.reader.exploring { return; } match self.reader.tap.take() { // The second of two: the focused node acts. Some((until, ..)) if now <= until => self.activate(), // The first, or one on its own: what it is is known // once no second follows. _ => self.reader.tap = Some((now + DOUBLE_TAP_MS, event.x, event.y)), } } _ => {} } } /// A single tap's time ran out with no second: it was one, and the /// focus goes to what it touched. fn tap_due(&mut self) { if let Some((until, x, y)) = self.reader.tap && pinnacle_rt::time() >= until { self.reader.tap = None; self.explore(x, y); } } /// The ring around the focused node, in the focus's gold. fn draw_ring(&mut self) { let nodes = self.reader_nodes(); let Some(i) = self.focus_index(&nodes) else { self.reader.ring = None; return; }; let r = nodes[i].0.rect; let ring = Rect::new(r.x - 3, r.y - 3, r.width + 6, r.height + 6).intersect(&Rect::new( 0, 0, self.width, self.height, )); let mut canvas = self.canvas(); canvas.stroke_round_rect(ring, [8; 4], [3; 4], Color::rgb(0xf0, 0xc4, 0x6a), 255); flush(ring); self.reader.ring = Some(ring); } /// Draws again what is under the ring, taking it away. fn erase_ring(&mut self) { let Some(ring) = self.reader.ring.take() else { return; }; if ring.y < shell::STATUS { self.draw_status(); } if ring.bottom() > self.height - shell::HOME_BAR { self.draw_home_bar(); } if let Some(u) = self.unlocking.as_mut() && let Some(sheet) = u.sheet.as_mut() { let width = self.width; sheet.draw(self.screen.pixels(), width, true); } else if let Some((sheet, _)) = self .confirm_sheet .as_mut() .filter(|_| !self.confirming.is_empty()) { let width = self.width; sheet.draw(self.screen.pixels(), width, true); } else if self.listing { if let Some((sheet, _)) = self.list_sheet.as_mut() { let width = self.width; sheet.draw(self.screen.pixels(), width, true); } } else { let area = self.app_rect(); self.show(Rect::new(ring.x, ring.y - area.y, ring.width, ring.height)); } } /// An app sent its tree: the reader reads it from now on, the ring /// following its node. fn tree(&mut self, client: usize, tree: Vec) { self.clients[client].tree = tree; if self.front == Some(client) && self.reader.ring.is_some() { self.erase_ring(); self.draw_ring(); } } /// The screen at a new size (a turn: width and height swapped): a new /// framebuffer, a new window for every app, everything drawn again. fn resize(&mut self, width: i32, height: i32) { let Some((screen, w, h)) = pinnacle_rt::framebuffer(Some((width as u32, height as u32))) else { return; }; if (w as i32, h as i32) == (self.width, self.height) { // The screen cannot have that size; nothing changed. screen.unmap(); return; } core::mem::replace(&mut self.screen, screen).unmap(); (self.width, self.height) = (w as i32, h as i32); println!("display: {w}x{h}"); self.canvas().fill(theme::BACKGROUND); flush(Rect::new(0, 0, self.width, self.height)); self.draw_home_bar(); for i in 0..self.clients.len() { if self.clients[i].window.is_some() { self.send_window(i); } } let listing = self.listing; if let Some(front) = self.front { self.bring_to_front(front); } // The list stays open, laid out for the new size. self.listing = listing; self.draw_list(); self.draw_status(); if self.unlocking.is_some() { self.draw_unlocking(); } } fn input(&mut self, event: InputEvent) { // The machine's power, not a hand: asked again, and the lid // closed locks the screen, as the time without input would. if event.kind == InputEvent::POWER { self.power = pinnacle_rt::power(); if event.code == InputEvent::LID { println!( "display: the lid {}", if event.value == 1 { "opened" } else { "closed" } ); if event.value == 0 { self.lock(); } } if event.code == InputEvent::CHARGER { println!( "display: the charger {}", if event.value == 1 { "in" } else { "out" } ); } self.draw_status(); return; } if self.prefs.reader && !matches!(event.kind, InputEvent::SCREEN) && !(event.kind == InputEvent::KEY && event.code == KEY_F12) { self.last_input = pinnacle_rt::time(); return self.reader_input(event); } self.dispatch(event) } /// Input as a hand gives it, to the server's own parts or the app in /// front. fn dispatch(&mut self, event: InputEvent) { // The screen's size changed (QEMU's window resized): lay out afresh. if event.kind == InputEvent::SCREEN { if (event.x, event.y) != (self.width, self.height) { self.resize(event.x, event.y); } return; } // F12 turns the screen, as a device's orientation sensor would. if event.kind == InputEvent::KEY && event.code == KEY_F12 { if event.value == 1 { self.resize(self.height, self.width); } return; } // A mouse's pointer is drawn where it is; a finger on the screen // needs none, and takes it away. if event.kind == InputEvent::MOVE && event.code == InputEvent::BY_MOUSE { self.move_pointer(event.x, event.y); } else if event.kind == InputEvent::MOVE && self.pointer.is_some() { self.hide_pointer(); } self.last_input = pinnacle_rt::time(); if self.unlocking.is_some() { return self.unlocking_input(event); } if self.confirming().is_some() { return self.confirming_input(event); } let area = self.app_rect(); let on_home_bar = event.y >= area.bottom(); let close = shell::close(self.width); let banner = shell::banner(self.width); let on_banner = self.banner.is_some() && banner.contains(event.x, event.y); if event.kind == InputEvent::PRESS { let target = self.list_target(event.x, event.y); if event.value == 1 && target.is_some() { self.list_press = target; return; } if event.value == 0 && let Some(pressed) = self.list_press.take() { if target == Some(pressed) { self.list_tapped(pressed); } return; } if self.list_press.is_some() { return; } } match event.kind { InputEvent::PRESS if event.value == 1 && on_banner => self.banner_press = true, InputEvent::PRESS if event.value == 0 && self.banner_press => { self.banner_press = false; if let Some(app) = self.banner.as_ref().filter(|_| on_banner).map(|b| b.app.clone()) { self.dismiss_banner(); println!("display: opening {app} from its notice"); self.start(&app); } } InputEvent::PRESS if event.value == 1 && on_home_bar => self.home_press = true, InputEvent::PRESS if event.value == 0 && self.home_press => { self.home_press = false; if on_home_bar && (self.front != Some(0) || self.listing) && !self.clients.is_empty() { self.bring_to_front(0); } } InputEvent::PRESS if event.value == 1 && self.closable() && close.contains(event.x, event.y) => { self.close_press = true; } InputEvent::PRESS if event.value == 0 && self.close_press => { self.close_press = false; if close.contains(event.x, event.y) { self.close_front(); } } _ if self.home_press || self.close_press || event.y < shell::STATUS && event.kind != InputEvent::KEY => {} // The list covers the app: nothing reaches it meanwhile. _ if self.listing => self.list_input(&event), _ => { let Some(front) = self.front else { return }; let mut moved = event; moved.y -= area.y; self.clients[front].channel.send( &pinnacle_ui::message(protocol::INPUT, &moved.to_bytes()), Vec::new(), ); } } } fn closed(&mut self, index: usize) { // The app's window goes back: the app's own mapping ended with it. if let Some(window) = self.clients.remove(index).window { pinnacle_rt::unmap(window); } self.front = match self.front { Some(f) if f == index => (!self.clients.is_empty()).then_some(0), Some(f) if f > index => Some(f - 1), other => other, }; if let Some(front) = self.front { self.bring_to_front(front); } } } /// The pointer a mouse or touchpad moves: an arrow, `#` its white and `o` /// its dark outline, its tip at the top left. const ARROW: [&str; 19] = [ "o ", "oo ", "o#o ", "o##o ", "o###o ", "o####o ", "o#####o ", "o######o ", "o#######o ", "o########o ", "o#########o ", "o######ooooo", "o###o##o ", "o##o o##o ", "o#o o##o ", "oo o##o ", "o o##o ", " o##o ", " oo ", ]; const ARROW_W: i32 = 12; const ARROW_H: i32 = 19; impl Server { /// Where the pointer is drawn, on the screen. fn pointer_rect(&self) -> Option { let (x, y) = self.pointer?; Some(Rect::new(x, y, ARROW_W, ARROW_H).intersect(&Rect::new(0, 0, self.width, self.height))) } /// `r` of the screen was just drawn: what the pointer covers of it is /// what lies under the pointer now, and the pointer goes back on top. fn pointer_over(&mut self, r: Rect) { let Some(p) = self.pointer_rect() else { return }; let both = p.intersect(&r); if both.is_empty() { return; } let (px, py) = self.pointer.unwrap(); let width = self.width as usize; let pixels = self.screen.pixels(); for y in both.y..both.bottom() { for x in both.x..both.right() { let at = y as usize * width + x as usize; self.under[((y - py) * ARROW_W + (x - px)) as usize] = pixels[at]; match ARROW[(y - py) as usize].as_bytes()[(x - px) as usize] { b'#' => pixels[at] = 0x00ff_ffff, b'o' => pixels[at] = 0x0010_1418, _ => {} } } } flush(both); } /// Puts back what is under the pointer and stops drawing it. fn hide_pointer(&mut self) { let Some(p) = self.pointer_rect() else { return }; let (px, py) = self.pointer.take().unwrap(); let width = self.width as usize; let pixels = self.screen.pixels(); for y in p.y..p.bottom() { for x in p.x..p.right() { pixels[y as usize * width + x as usize] = self.under[((y - py) * ARROW_W + (x - px)) as usize]; } } flush(p); } /// The pointer moved by hand to `x`, `y`. fn move_pointer(&mut self, x: i32, y: i32) { self.hide_pointer(); self.under = alloc::vec![0; (ARROW_W * ARROW_H) as usize]; self.pointer = Some((x, y)); let r = Rect::new(x, y, ARROW_W, ARROW_H); self.pointer_over(r); } } /// Tells the display a rectangle of the screen changed: behind a GPU only /// what is flushed reaches it; a plain framebuffer needs nothing. fn flush(r: Rect) { pinnacle_rt::flush_screen(r.x, r.y, r.width, r.height); } /// "14:05", local, or the time since boot while the time of day is unknown. fn clock_text() -> String { pinnacle_rt::locale::time_text() } #[unsafe(no_mangle)] fn main(_argument: u64) -> u64 { let (screen, width, height) = pinnacle_rt::framebuffer(None).expect("the display server got no screen"); let input = pinnacle_rt::input().expect("the display server got no input"); let service = pinnacle_rt::register("display").expect("could not register the display"); let confirm = pinnacle_rt::register(pinnacle_ui::confirm::SERVICE).expect("could not register the confirmation"); let mut server = Server { screen, width: width as i32, height: height as i32, clients: Vec::new(), front: None, home_press: false, close_press: false, minute: 0, started: Vec::new(), clipboard: String::new(), banner: None, banner_press: false, notices: Vec::new(), unseen: 0, listing: false, list_press: None, lock: Lock::default(), unlocking: None, vault_open: false, last_input: 0, askers: Vec::new(), bluetooth_keys: None, confirming: Vec::new(), confirm_sheet: None, list_sheet: None, prefs: Preferences::read(), reader: Reader::default(), speech: None, pointer: None, under: Vec::new(), power: pinnacle_rt::power(), }; access::set(server.prefs); // The volume Settings kept: the kernel's mixer starts at its own. if let Some(volume) = pinnacle_ui::sound::kept() && pinnacle_rt::audio::volume(Some(volume)).is_some() { println!("display: volume {volume} %"); } // And the screen's brightness, where it has one to set. if let Some(level) = pinnacle_ui::brightness::kept() && let Some(set) = pinnacle_rt::set_brightness(level) { println!("display: brightness {set} %"); } server.canvas().fill(theme::BACKGROUND); flush(Rect::new(0, 0, server.width, server.height)); server.draw_status(); server.draw_home_bar(); // The time service needs none of the person's data: the clock is set // from the network while the lock screen shows it. pinnacle_rt::spawn("time", 0, Vec::new()); // The person's data first, when it waits for its password; the rest // of the system once it is open. let mode = match pinnacle_rt::vault::state() { pinnacle_rt::vault::State::None => None, pinnacle_rt::vault::State::Blank => Some(Mode::New), pinnacle_rt::vault::State::Locked => Some(Mode::Open), }; match mode { None => server.start_system(), Some(mode) => { println!( "display: {}", if mode == Mode::New { "choose a password for your data" } else { "your data is locked" } ); server.unlocking = Some(Unlocking::new(mode)); server.draw_unlocking(); } } // A new system being tried has started well once its screen shows: it // is the one that runs from now on (`pinnacle_pkg::system`). if let Some(version) = pinnacle_ui::updates::confirm_start() { println!("display: system version {version} started well"); } let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE]; loop { let next_minute = (pinnacle_rt::time() / 60_000 + 1) * 60_000; let banner_ends = server.banner.as_ref().map(|b| b.until); // Open, the idle lock; locked out, the countdown, a second a time. let lock_due = if server.unlocking.is_some() { (server.lock.wait_until > pinnacle_rt::time()).then(|| pinnacle_rt::time() + 1000) } else { server.vault_open.then_some(server.last_input + LOCK_AFTER_MS) }; let tap_due = server.reader.tap.map(|(until, ..)| until); let deadline = [Some(next_minute), banner_ends, lock_due, tap_due] .into_iter() .flatten() .min() .unwrap(); let mut channels: Vec<&Channel> = alloc::vec![&service, &input, &confirm]; channels.extend(server.clients.iter().map(|c| &c.channel)); // The askers after the apps: an app's index does not move when one // comes or goes. let first_asker = channels.len(); channels.extend(server.askers.iter()); // A Bluetooth keyboard's keys last. let bluetooth_keys = channels.len(); channels.extend(server.bluetooth_keys.iter()); let received = pinnacle_rt::receive(&channels, &mut buffer, Some(deadline)); drop(channels); match received { Received::Timeout => { let now = pinnacle_rt::time(); if server.banner.as_ref().is_some_and(|b| now >= b.until) { server.dismiss_banner(); } server.tap_due(); if now >= next_minute { server.minute += 1; server.power = pinnacle_rt::power(); server.draw_status(); } if server.unlocking.is_some() { server.draw_unlocking(); } else if server.vault_open && now >= server.last_input + LOCK_AFTER_MS { server.lock(); } } Received::Message { index: 0, mut handles, .. } if !handles.is_empty() => { server.clients.push(Client { channel: Channel(handles.remove(0)), program: String::new(), title: String::new(), window: None, process: None, tree: Vec::new(), }); } Received::Message { index: 1, len, .. } => { if let Some(event) = InputEvent::from_bytes(&buffer[..len]) { server.input(event); } } Received::Message { index: 2, mut handles, .. } if !handles.is_empty() => { server.askers.push(Channel(handles.remove(0))); } // Keys only, as a hand on the keyboard: never a touch, and // never marked as an agent's. Received::Message { index, len, .. } if index == bluetooth_keys => { if let Some(event) = InputEvent::from_bytes(&buffer[..len]) && event.kind == InputEvent::KEY && !event.synthetic { server.input(event); } } Received::Closed { index } if index == bluetooth_keys => server.bluetooth_keys = None, Received::Message { index, len, .. } if index >= first_asker => { match pinnacle_ui::confirm::Question::decode(&buffer[..len]) { Some(question) => server.confirm(index - first_asker, question), None => { server.askers[index - first_asker].send(pinnacle_ui::confirm::NO, Vec::new()); } } } Received::Closed { index } if index >= first_asker => server.asker_gone(index - first_asker), Received::Message { index, len, .. } if index >= 3 && len >= 4 => { let client = index - 3; let body = &buffer[4..len]; match buffer[0] { protocol::HELLO if body.len() >= 8 => { let pid = u64::from_le_bytes(body[..8].try_into().unwrap()); let title = String::from(core::str::from_utf8(&body[8..]).unwrap_or("App")); if let Some(i) = server.started.iter().position(|(p, ..)| *p == pid) { let (_, program, process) = server.started.remove(i); server.clients[client].program = program; server.clients[client].process = Some(process); } server.hello(client, &title); println!("display: {title} connected"); } protocol::DAMAGE if server.front == Some(client) => { if let Some(rect) = pinnacle_ui::rect_from(body) { server.show(rect); server.redraw_banner_over(rect); } } protocol::TURN => server.resize(server.height, server.width), protocol::COPY => { server.clipboard = String::from_utf8_lossy(body).into_owned(); println!("display: copied {} bytes", server.clipboard.len()); } protocol::PASTE => { let reply = pinnacle_ui::message(protocol::CLIPBOARD, server.clipboard.as_bytes()); server.clients[client].channel.send(&reply, Vec::new()); } protocol::NOTIFY => server.notify(&String::from_utf8_lossy(body)), protocol::RUNNING => { let name = core::str::from_utf8(body).unwrap_or(""); let running = server.clients.iter().any(|c| c.program == name) || server.started.iter().any(|(_, program, _)| program == name); let reply = pinnacle_ui::message(protocol::RUNNING_IS, &[u8::from(running)]); server.clients[client].channel.send(&reply, Vec::new()); } protocol::LOCK => server.lock(), protocol::TREE => server.tree(client, access::decode(body)), protocol::PREFERENCES_CHANGED => server.preferences_changed(), protocol::LAUNCH => { let name = String::from(core::str::from_utf8(body).unwrap_or("")); server.start(&name); } _ => {} } } Received::Closed { index } if index >= 3 => server.closed(index - 3), _ => {} } } }