diff --git a/Cargo.lock b/Cargo.lock index fc48085..c57ab2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,22 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "accesskit" version = "0.25.2" @@ -728,6 +744,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "crc32fast" version = "1.5.4" @@ -765,6 +790,7 @@ dependencies = [ "egui_kittest", "encoding_rs", "fancy-regex", + "fontdue", "regex", "resvg", "rfd", @@ -774,6 +800,7 @@ dependencies = [ "serde_json", "unicode-width", "walkdir", + "winit", ] [[package]] @@ -1221,6 +1248,16 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "fontdue" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" +dependencies = [ + "hashbrown 0.15.5", + "ttf-parser", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -1494,6 +1531,8 @@ version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.1.5", ] @@ -2331,6 +2370,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + [[package]] name = "parking" version = "2.2.1" @@ -2900,6 +2948,19 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3406,6 +3467,15 @@ dependencies = [ "petgraph", ] +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + [[package]] name = "type-map" version = "0.5.1" @@ -4197,6 +4267,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", + "sctk-adwaita", "smithay-client-toolkit 0.19.2", "smol_str", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 3157146..24d0e16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ resvg = { version = "0.45", default-features = false } rfd = { version = "0.17", default-features = false, features = ["xdg-portal", "pollster"] } walkdir = "2" alacritty_terminal = "0.26" +fontdue = "0.9" +winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita"] } [profile.release] opt-level = 3 diff --git a/README.md b/README.md index 30cdc3d..c02a301 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ at the centre of how it works.

- **Icons that morph between states**, and only where a button really has two: sun and moon, run and stop, `+` and `−` for staging, maximize and restore. One-shot actions like Save stay still. - **Jelly tabs** whose indicator edges are separate springs, so it stretches as it moves. +- **Your own top bar.** Settings > Toolbar puts any of the app's commands beside the `+` button, up to 8. - **One box for everything.** `Ctrl+Shift+P`: type for files, `>` commands, `:` line, `@` symbol, `!` run. ![The preview lens](docs/screenshots/03-preview-lens.png) @@ -42,7 +43,26 @@ hot exit (unsaved text survives a crash or quit), and language servers for compl definition and diagnostics when they're installed (`clangd`, `rust-analyzer`, `pylsp`, `gopls`, `typescript-language-server`, `bash-language-server`, `lua-language-server`). -Colours come from your Caelestia scheme or KDE accent, or a colour you pick, and follow live changes. +Colours follow your desktop (Caelestia's scheme or the KDE accent), or a colour you pick, and change live. + +## Discord + +Damson can show what you're editing on Discord: file, project, a language icon and time spent, or Idling +after five minutes. It speaks Discord's local socket directly. Settings > Discord has switches to hide the +file or project name. + +Discord takes the app name from the application ID, so you need your own: make an application named +Damson at [discord.com/developers/applications](https://discord.com/developers/applications) and paste +its Application ID into Settings. To get the small Damson icon, upload a PNG of `packaging/damson.svg` under Rich Presence +named `damson`. Language pictures load by URL from the +[zed-discord-presence](https://github.com/xhyrom/zed-discord-presence) project; none of its code is used +here (it's GPL-3). + +## Taskbar actions + +Right-clicking Damson in a launcher that reads desktop actions offers New Window, New File, Open Folder +and New Terminal. Windows opened this way stay out of your saved session, so their unsaved changes are +not recovered. ![Light mode](docs/screenshots/12-other-mode.png) diff --git a/assets/damson.svg b/assets/damson.svg index 154577c..87ad47f 100644 --- a/assets/damson.svg +++ b/assets/damson.svg @@ -1,6 +1,4 @@ - - - - + + diff --git a/docs/screenshots/01-editor.png b/docs/screenshots/01-editor.png index 1e77f52..c3cacb3 100644 Binary files a/docs/screenshots/01-editor.png and b/docs/screenshots/01-editor.png differ diff --git a/docs/screenshots/03-preview-lens.png b/docs/screenshots/03-preview-lens.png index 9e7e216..d87045a 100644 Binary files a/docs/screenshots/03-preview-lens.png and b/docs/screenshots/03-preview-lens.png differ diff --git a/install.sh b/install.sh index 87d7119..900ab7f 100755 --- a/install.sh +++ b/install.sh @@ -6,4 +6,5 @@ cargo build --release install -Dm755 target/release/damson "$HOME/.local/bin/damson" install -Dm644 packaging/damson.desktop "$HOME/.local/share/applications/damson.desktop" install -Dm644 packaging/damson.svg "$HOME/.local/share/icons/hicolor/scalable/apps/damson.svg" +update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true echo "Installed. Run: damson [file[:line]] [folder]" diff --git a/packaging/damson.desktop b/packaging/damson.desktop index b8b72db..72a44c3 100644 --- a/packaging/damson.desktop +++ b/packaging/damson.desktop @@ -9,3 +9,20 @@ Terminal=false Categories=Development;TextEditor;Utility; MimeType=text/plain;text/x-csrc;text/x-c++src;text/x-python;text/rust;text/x-shellscript;text/markdown;application/json;application/xml; StartupWMClass=damson +Actions=new-window;new-file;open-folder;terminal; + +[Desktop Action new-window] +Name=New Window +Exec=damson --new-window + +[Desktop Action new-file] +Name=New File +Exec=damson --new-file + +[Desktop Action open-folder] +Name=Open Folder +Exec=damson --open-folder + +[Desktop Action terminal] +Name=New Terminal +Exec=damson --terminal diff --git a/packaging/damson.svg b/packaging/damson.svg index 154577c..87ad47f 100644 --- a/packaging/damson.svg +++ b/packaging/damson.svg @@ -1,6 +1,4 @@ - - - - + + diff --git a/src/app.rs b/src/app.rs index ad176be..76601d9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,6 +1,7 @@ //! The application: state, layout and command handling. use crate::config::{config_dir, Settings}; +use crate::discord; use crate::git::{self, GitState}; use crate::lsp::{self, Client, CompletionItem, Diag, LspEvent}; use crate::motion::{self, spring, Preset}; @@ -18,7 +19,7 @@ use crate::ui::sidebar::Side; use crate::ui::terminal::Session; use crate::ui::morph::{self, Morph}; use crate::ui::{fonts, icons, status::FAB_W, widgets::*}; -use eframe::egui::{self, pos2, vec2, Align2, Color32, Id, Key, Modifiers, Pos2, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand}; +use eframe::egui::{self, pos2, vec2, Align2, Color32, Id, Key, Modifiers, Pos2, Rect, Sense, Stroke, Ui, ViewportCommand}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -102,6 +103,11 @@ pub struct App { pub side_state: Side, pub settings_open: bool, pub settings_tab: usize, + pub settings_scroll: [f32; 6], + pub settings_height: [f32; 6], + pub shell_open: bool, + pub shells: Vec, + pub toolbar_filter: String, pub logo_spin: f32, pub logo_clock: f32, pub theme_wave: Option<(Pos2, f64)>, @@ -113,6 +119,7 @@ pub struct App { pub term_open: bool, pub term_busy: bool, pub term_want_focus: bool, + pub term_target: Rect, pub term_height: f32, pub fab_rect: Rect, pub palette: Palette, @@ -136,6 +143,11 @@ pub struct App { pub caret_pos: Pos2, hover_copied: f64, smoke_frames: u64, + pub side_window: bool, + startup: Vec, + window_title: String, + presence: Sender, + presence_sent: Option<(String, bool, bool, bool)>, last_time: Option, last_poll: Instant, last_session: Instant, @@ -150,7 +162,8 @@ impl App { Self::build(&cc.egui_ctx, files) } - pub fn build(ctx: &egui::Context, files: Vec) -> App { + pub fn build(ctx: &egui::Context, args: Vec) -> App { + let (flags, files): (Vec, Vec) = args.into_iter().partition(|a| a.starts_with("--")); let s = Settings::load(); fonts::install(ctx, &s.mono_font); let (tx, rx) = channel(); @@ -159,15 +172,25 @@ impl App { let mut a = App { t, theme_stamp: 1, reg: Registry::scan(), docs: HashMap::new(), panes: vec![Pane::new(0)], focus_pane: 0, split_vertical: false, split: 0.5, next_id: 1, root: None, reveal: false, last_input: 0.0, side: 0, side_open: false, side_state: Side::default(), - settings_open: false, settings_tab: 0, logo_spin: 0.0, logo_clock: 0.0, theme_wave: None, git: GitState::default(), diags: HashMap::new(), - terms: vec![], term_cur: 0, next_term: 0, term_open: false, term_busy: false, term_want_focus: false, term_height: 300.0, fab_rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(FAB_W, 44.0)), + settings_open: false, settings_tab: 0, settings_scroll: [0.0; 6], settings_height: [0.0; 6], shell_open: false, shells: vec![], toolbar_filter: String::new(), logo_spin: 0.0, logo_clock: 0.0, theme_wave: None, git: GitState::default(), diags: HashMap::new(), + terms: vec![], term_cur: 0, next_term: 0, term_open: false, term_busy: false, term_want_focus: false, term_target: Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 300.0)), term_height: 300.0, fab_rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(FAB_W, 44.0)), palette: Palette::default(), find: Find::default(), menu: None, menu_seq: 0, dialog: None, toasts: vec![], toast_seq: 0, closed: vec![], - zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, + zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, side_window: false, startup: vec![], window_title: String::new(), presence: discord::spawn(), presence_sent: None, last_time: None, last_poll: Instant::now(), last_session: Instant::now(), last_git: Instant::now() - Duration::from_secs(60), last_stamp: theme::source_stamp(), saved_settings: s.clone(), s, quit_now: false, }; a.apply_style(ctx); - if a.s.restore_session && files.is_empty() { + // a window opened from a taskbar action is a side window: the main session stays as it was + a.side_window = !flags.is_empty(); + for f in &flags { + match f.as_str() { + "--new-file" => a.startup.push(Cmd::New), + "--open-folder" => a.startup.push(Cmd::OpenFolder), + "--terminal" => a.startup.push(Cmd::ToggleTerminal), + _ => {} + } + } + if a.s.restore_session && files.is_empty() && !a.side_window { a.restore_session(ctx); } for f in files { @@ -788,7 +811,8 @@ impl App { pub fn run(&mut self, ctx: &egui::Context, c: Cmd) { use Cmd::*; let prefs = Prefs { tab_width: self.s.tab_width, spaces: self.s.spaces, auto_close: self.s.auto_close }; - self.reveal = true; + // only commands that move or edit at the cursor scroll to it; view toggles leave you where you are + self.reveal = matches!(c, Undo | Redo | Cut | Paste | Comment | DuplicateLines | DeleteLines | MoveLinesUp | MoveLinesDown | JoinLines | Indent | Unindent | CursorAbove | CursorBelow | SelectNext); match c { New => { let id = self.next_id; @@ -1106,6 +1130,7 @@ impl App { self.last_poll = now; self.lsp_sync(); self.check_external(); + self.update_presence(ctx); let st = theme::source_stamp(); if st != self.last_stamp { self.last_stamp = st; @@ -1123,6 +1148,25 @@ impl App { } } + fn update_presence(&mut self, ctx: &egui::Context) { + let id = if self.s.discord { self.s.discord_id.trim().to_string() } else { String::new() }; + let _ = self.presence.send(discord::Update::Id(id)); + let idle = ctx.input(|i| i.time) - self.last_input > discord::IDLE_AFTER; + let name = self.cur_doc().map(|d| d.title()).unwrap_or_default(); + let key = (name.clone(), idle, self.s.discord_file, self.s.discord_project); + if self.presence_sent.as_ref() == Some(&key) { + return; + } + let project = self.root.as_ref().and_then(|r| r.file_name()).map(|n| n.to_string_lossy().into_owned()); + let activity = match self.cur_doc() { + _ if idle => discord::Activity::idle(), + Some(d) => discord::Activity::editing(self.s.discord_file.then_some(name.as_str()), project.as_deref().filter(|_| self.s.discord_project), &name, &d.language), + None => discord::Activity { state: Some("Getting started".to_string()), ..discord::Activity::idle() }, + }; + let _ = self.presence.send(discord::Update::Show(Some(activity))); + self.presence_sent = Some(key); + } + /// Picks up files changed by something else; unsaved ones are left alone with a note. fn check_external(&mut self) { let mut reload = vec![]; @@ -1148,6 +1192,9 @@ impl App { } pub fn save_session(&self) { + if self.side_window { + return; + } let dir = config_dir().join("recovery"); let _ = std::fs::create_dir_all(&dir); let mut keep = vec![]; @@ -1224,6 +1271,14 @@ impl App { self.last_time = Some(now); motion::begin_frame(dt, self.s.motion); self.background(&ctx); + for c in std::mem::take(&mut self.startup) { + self.run(&ctx, c); + } + let title = self.cur_doc().map_or("Damson".to_string(), |d| format!("{}{} — Damson", if d.buf.is_modified() { "• " } else { "" }, d.title())); + if title != self.window_title { + ctx.send_viewport_cmd(ViewportCommand::Title(title.clone())); + self.window_title = title; + } if ctx.memory(|m| m.focused()).is_none() && !self.palette.open && self.dialog.is_none() && !self.settings_open && !self.term_open { self.focus_editor(&ctx); } @@ -1281,13 +1336,11 @@ impl App { let ctx = ui.ctx().clone(); let t = self.t.clone(); let full = ui.max_rect(); - let maxed = ctx.input(|i| i.viewport().maximized.unwrap_or(false) || i.viewport().fullscreen.unwrap_or(false)); let p = ui.painter().clone(); - p.rect_filled(full, cr(if maxed { 0.0 } else { 18.0 }), t.surface); + p.rect_filled(full, cr(0.0), t.surface); let z = spring("zen", self.zen as u8 as f32, motion::DEFAULT); let zk = z.clamp(0.0, 1.0); - self.window_edges(ui, full, maxed); let rail_w = 78.0 * (1.0 - zk); if rail_w > 1.0 { @@ -1309,6 +1362,7 @@ impl App { let term_k = spring("term/k", self.term_open as u8 as f32, Preset { stiffness: 480.0, damping: 0.7 }); let reserved = (self.term_height + 8.0) * term_k.clamp(0.0, 1.0); + self.term_target = Rect::from_min_max(pos2(stage.left(), stage.bottom() - self.term_height), stage.max); let editors = Rect::from_min_max(stage.min, pos2(stage.right(), stage.bottom() - reserved)); let n = self.panes.len(); @@ -1334,12 +1388,8 @@ impl App { for (i, r) in rects.iter().enumerate() { let has_controls = (r.right() - full.right()).abs() < 30.0 && (r.top() - editors.top()).abs() < 1.0; let tab_h = 46.0 * (1.0 - zk); - let strip = Rect::from_min_max(r.min, pos2(r.right() - if has_controls { 118.0 } else { 0.0 }, r.top() + 44.0)); + let strip = Rect::from_min_max(r.min, pos2(r.right() - if has_controls { self.toolbar_width() } else { 0.0 }, r.top() + 44.0)); if tab_h > 8.0 { - // the strip's empty space moves the window; tabs are added after, so they sit on top - let bar = ui.interact(strip, ui.scope_id().with(("titlebar", i)), Sense::click_and_drag()); - if bar.drag_started() { ctx.send_viewport_cmd(ViewportCommand::StartDrag) } - if bar.double_clicked() { ctx.send_viewport_cmd(ViewportCommand::Maximized(!maxed)) } let mut sub = ui.new_child(egui::UiBuilder::new().max_rect(strip.translate(vec2(0.0, -46.0 * zk)))); self.tabstrip(&mut sub, i, strip.translate(vec2(0.0, -46.0 * zk))); } @@ -1353,7 +1403,7 @@ impl App { self.welcome(ui, card); continue; } - let mini_w = if self.s.preview { 92.0 } else { 0.0 }; + let mini_w = if self.s.preview { 112.0 } else { 0.0 }; let code = Rect::from_min_max(card.min, pos2(card.right() - mini_w - if mini_w > 0.0 { 8.0 } else { 0.0 }, card.bottom())); self.editor(ui, i, code.shrink2(vec2(0.0, 2.0))); if self.s.preview { @@ -1367,11 +1417,10 @@ impl App { } if let Some(c) = find_card { self.find_bar(ui, c) } - self.window_buttons(ui, full); + self.toolbar(ui, full); if term_k.abs() > 0.004 { - let target = Rect::from_min_max(pos2(stage.left(), stage.bottom() - self.term_height), stage.max); - self.terminal_card(ui, target, term_k); + self.terminal_card(ui, self.term_target, term_k); } if status_h > 2.0 { let r = Rect::from_min_max(pos2(body.left(), full.bottom() - 48.0 + 48.0 * zk), pos2(full.right() - 12.0, full.bottom() - 2.0 + 48.0 * zk)); @@ -1388,34 +1437,31 @@ impl App { pos2(code.left() + gutter + 6.0 + tb.caret[0].x - tb.scroll_x, code.top() + 8.0 + tb.caret[1].x - tb.scroll.x) } - fn window_edges(&mut self, ui: &mut Ui, full: Rect, maxed: bool) { - if maxed { return } + /// The icons at the top right: the ones chosen in Settings, then the menu logo at the end. + fn toolbar(&mut self, ui: &mut Ui, full: Rect) { + let t = self.t.clone(); let ctx = ui.ctx().clone(); - let m = 5.0; - let edges: [(Rect, ResizeDirection, egui::CursorIcon); 4] = [ - (Rect::from_min_max(full.left_top(), pos2(full.right(), full.top() + m)), ResizeDirection::North, egui::CursorIcon::ResizeVertical), - (Rect::from_min_max(pos2(full.left(), full.bottom() - m), full.right_bottom()), ResizeDirection::South, egui::CursorIcon::ResizeVertical), - (Rect::from_min_max(full.left_top(), pos2(full.left() + m, full.bottom())), ResizeDirection::West, egui::CursorIcon::ResizeHorizontal), - (Rect::from_min_max(pos2(full.right() - m, full.top()), full.right_bottom()), ResizeDirection::East, egui::CursorIcon::ResizeHorizontal), - ]; - for (i, (r, dir, cursor)) in edges.into_iter().enumerate() { - let resp = ui.interact(r, ui.scope_id().with(("edge", i)), Sense::drag()); - if resp.hovered() { ctx.set_cursor_icon(cursor) } - if resp.drag_started() { ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir)) } + let z = spring("zen", self.zen as u8 as f32, motion::DEFAULT).clamp(0.0, 1.0); + let y = full.top() + 30.0 - 60.0 * z; + let right = full.right() - 34.0; + let logo = pos2(right, y); + self.logo(ui, logo); + let all = crate::ui::commands::all(); + let picks: Vec<&crate::ui::commands::Entry> = self.s.toolbar.iter().filter_map(|l| all.iter().find(|e| e.label == l)).collect(); + let n = picks.len(); + for (i, e) in picks.iter().enumerate() { + let x = right - 44.0 - (n - 1 - i) as f32 * 38.0; + let key = format!("bar/{}", e.label); + let tip = if e.keys.is_empty() { e.label.to_string() } else { format!("{} ({})", e.label, e.keys) }; + let k = motion::spring_from(format!("{key}/in"), 0.4, 1.0, motion::DEFAULT); + if icon_btn(ui, &t, Rect::from_center_size(pos2(x, y), vec2(34.0, 34.0) * k), &key, e.ic, &tip, false).clicked() { + self.run(&ctx, e.cmd.clone()); + } } } - fn window_buttons(&mut self, ui: &mut Ui, full: Rect) { - let t = self.t.clone(); - let ctx = ui.ctx().clone(); - let y = full.top() + 30.0; - let x = full.right() - 30.0; - let z = spring("zen", self.zen as u8 as f32, motion::DEFAULT).clamp(0.0, 1.0); - let y = y - 60.0 * z; - let maxed = ctx.input(|i| i.viewport().maximized.unwrap_or(false)); - if icon_btn(ui, &t, Rect::from_center_size(pos2(x, y), vec2(32.0, 32.0)), "win/close", "close", "Close", false).clicked() { ctx.send_viewport_cmd(ViewportCommand::Close) } - if morph::button(ui, &t, Rect::from_center_size(pos2(x - 36.0, y), vec2(32.0, 32.0)), "win/max", Morph::MaxRestore, maxed, "Maximize", t.surface).clicked() { ctx.send_viewport_cmd(ViewportCommand::Maximized(!maxed)) } - if icon_btn(ui, &t, Rect::from_center_size(pos2(x - 72.0, y), vec2(32.0, 32.0)), "win/min", "minimize", "Minimize", false).clicked() { ctx.send_viewport_cmd(ViewportCommand::Minimized(true)) } + fn toolbar_width(&self) -> f32 { + 60.0 + self.s.toolbar.len() as f32 * 38.0 } fn toasts_ui(&mut self, ctx: &egui::Context) { @@ -1469,7 +1515,7 @@ impl eframe::App for App { } fn clear_color(&self, _: &egui::Visuals) -> [f32; 4] { - [0.0, 0.0, 0.0, 0.0] + self.t.surface.to_normalized_gamma_f32() } fn on_exit(&mut self, _: Option<&eframe::glow::Context>) { diff --git a/src/config.rs b/src/config.rs index 2a608f5..bc7cee5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,11 +4,13 @@ use serde::{Deserialize, Serialize}; use std::path::PathBuf; pub const APP_NAME: &str = "Damson"; +/// How many icons the top bar holds. +pub const TOOLBAR_MAX: usize = 8; #[derive(Serialize, Deserialize, Clone, PartialEq)] #[serde(default)] pub struct Settings { - pub color_source: String, // "auto", "caelestia", "kde", "custom" + pub color_source: String, // "auto" follows the desktop, or "custom" pub custom_color: String, pub mode: String, // "auto", "dark", "light" pub scheme: String, // "tonal", "vibrant", "expressive", "mono" @@ -29,6 +31,11 @@ pub struct Settings { pub shell: String, pub terminal_font: f32, pub lsp: bool, + pub toolbar: Vec, + pub discord: bool, + pub discord_id: String, + pub discord_file: bool, + pub discord_project: bool, pub recent: Vec, pub win: [f32; 2], } @@ -40,7 +47,8 @@ impl Default for Settings { motion: 2, font_size: 14.0, mono_font: String::new(), tab_width: 4, spaces: true, auto_close: true, word_wrap: false, line_numbers: true, show_whitespace: false, indent_guides: true, preview: true, lens: true, trim_on_save: false, restore_session: true, shell: String::new(), terminal_font: 13.0, - lsp: true, recent: vec![], win: [1400.0, 900.0], + lsp: true, toolbar: vec!["Save".into(), "Find".into(), "Command palette".into()], + discord: true, discord_id: String::new(), discord_file: true, discord_project: true, recent: vec![], win: [1400.0, 900.0], } } } @@ -51,7 +59,11 @@ pub fn config_dir() -> PathBuf { impl Settings { pub fn load() -> Settings { - std::fs::read(config_dir().join("settings.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() + let mut s: Settings = std::fs::read(config_dir().join("settings.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + if s.color_source != "custom" { + s.color_source = "auto".into(); + } + s } pub fn save(&self) { diff --git a/src/discord.rs b/src/discord.rs new file mode 100644 index 0000000..94da3fa --- /dev/null +++ b/src/discord.rs @@ -0,0 +1,273 @@ +//! Discord Rich Presence: tells Discord what's being edited, over its local socket. +//! +//! Shows the same things as the Zed presence extension (file, project, a language icon and time +//! spent). The text and language table here are Damson's own; the language pictures are the +//! extension's, which Discord fetches by URL. Which app name Discord shows comes from the +//! application id, so a "Damson" id has to be made in Discord's Developer Portal. + +use serde_json::{json, Value}; +use std::io::{Read, Write}; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::mpsc::{channel, RecvTimeoutError, Sender}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +pub const ICON_BASE: &str = "https://raw.githubusercontent.com/xhyrom/zed-discord-presence/main/assets/icons"; +/// Seconds without input before showing as idle. +pub const IDLE_AFTER: f64 = 300.0; + +/// Pictures that exist at `ICON_BASE`. +const ICONS: &str = " ahk android angular ansible applescript appveyor arduino asp assembly astro astroconfig autoit babel bat bazel bower brainfuck c c3 cargo circleci citrinescript clang clojure cmake cobol codeclimate coffee contenthook cosmo cpp crystal csharp csproj css cssmap cuda cython d dart debugging delphi denizen dlang docker edge editorconfig ejs elixir elm env erlang eslint firebase flowconfig fortran fsharp gamescript gatsbyjs gemfile git gleam glsl gml go godot gradle grain graphql groovy gruntfile gulp handlebars harbour hare haskell haxe heex heroku hjson hlsl holyc html http idle jar java javascript jest jinja js jsmap json jsx jule julia jupyter kivy kotlin laravel less lisp livescript log lua luau makefile manifest markdown markdownx marko matlab metal mojo moonscript nim nix nodemon npm objective-c ocaml odin onyx pascal pawn perl php ponylang postcss powershell prettier prisma processing pug purescript python qml r racket razor reasonml restructuredtext rscript ruby rust scala scss shell skript slint solidity sourcepawn sqf sql squirrel stylus svelte svg swift systemverilog tailwind terraform tex text toml travis ts tsmap tsx turbo twig typescript umm v vala vb vercel verilog verse viteconfig vitestconfig vue vueconfig wasm webpack xaml xml yaml yarn zig "; + +/// The picture for a file, from its name and Kate's language name. +pub fn icon_for(file: &str, language: &str) -> String { + let special = match file.to_ascii_lowercase().as_str() { + "cargo.toml" | "cargo.lock" => Some("cargo"), + "dockerfile" | "docker-compose.yml" | "docker-compose.yaml" | ".dockerignore" => Some("docker"), + "package.json" | "package-lock.json" => Some("npm"), + "makefile" | "gnumakefile" => Some("makefile"), + "cmakelists.txt" => Some("cmake"), + ".gitignore" | ".gitattributes" | ".gitmodules" => Some("git"), + ".env" => Some("env"), + ".editorconfig" => Some("editorconfig"), + "yarn.lock" => Some("yarn"), + "gemfile" => Some("gemfile"), + _ => None, + }; + if let Some(s) = special { + return s.to_string(); + } + let named = match language { + "C++" | "ISO C++" => "cpp", + "C#" => "csharp", + "Bash" | "Zsh" | "Fish" | "Tcsh" | "Ksh" => "shell", + "PHP (HTML)" | "PHP/PHP" => "php", + "LESSCSS" => "less", + "SCSS" => "scss", + "LaTeX" | "BibTeX" => "tex", + "R Script" => "r", + "D" => "dlang", + "Objective-C" | "Objective-C++" => "objective-c", + "Dockerfile" => "docker", + "TypeScript React (TSX)" => "tsx", + "JavaScript React (JSX)" => "jsx", + "SQL (PostgreSQL)" | "SQL (MySQL)" | "SQL (SQLite)" => "sql", + "Fortran (Free Format)" | "Fortran (Fixed Format)" => "fortran", + "GNU Assembler" | "Intel x86 (NASM)" => "assembly", + "PowerShell" => "powershell", + "reStructuredText" => "restructuredtext", + "Windows Batch" | "Batch" => "bat", + _ => "", + }; + if !named.is_empty() { + return named.to_string(); + } + let plain = language.to_lowercase(); + if ICONS.contains(&format!(" {plain} ")) { plain } else { "text".to_string() } +} + +#[derive(Clone, Debug, PartialEq, Default)] +pub struct Activity { + pub details: Option, + pub state: Option, + pub large_image: Option, + pub large_text: Option, + pub small_image: Option, + pub small_text: Option, +} + +impl Activity { + /// Editing a file. `file` and `project` are `None` when the user hides them. + pub fn editing(file: Option<&str>, project: Option<&str>, name_for_icon: &str, language: &str) -> Activity { + let lang = if language == "None" { "Plain text" } else { language }; + Activity { + state: Some(file.map_or_else(|| format!("Working on a {lang} file"), |f| format!("Working on {f}"))), + details: Some(project.map_or_else(|| "In Damson".to_string(), |p| format!("In {p}"))), + large_image: Some(format!("{ICON_BASE}/{}.png", icon_for(name_for_icon, language))), + large_text: Some(lang.to_string()), + small_image: Some("damson".to_string()), + small_text: Some("Damson".to_string()), + } + } + + pub fn idle() -> Activity { + Activity { + state: Some("Idling".to_string()), + details: Some("In Damson".to_string()), + large_image: Some("damson".to_string()), + large_text: Some("Damson".to_string()), + small_image: Some(format!("{ICON_BASE}/idle.png")), + small_text: Some("Idle".to_string()), + } + } + + fn json(&self, start: u64) -> Value { + let mut v = json!({"timestamps": {"start": start}, "assets": {}}); + if let Some(s) = &self.details { v["details"] = json!(s) } + if let Some(s) = &self.state { v["state"] = json!(s) } + for (k, s) in [("large_image", &self.large_image), ("large_text", &self.large_text), ("small_image", &self.small_image), ("small_text", &self.small_text)] { + if let Some(s) = s { v["assets"][k] = json!(s) } + } + v + } +} + +fn sockets() -> Vec { + if let Some(p) = std::env::var_os("DAMSON_DISCORD_SOCKET") { + return vec![PathBuf::from(p)]; + } + let base = dirs::runtime_dir().unwrap_or_else(|| PathBuf::from("/tmp")); + let mut v = vec![]; + for i in 0..10 { + let name = format!("discord-ipc-{i}"); + v.push(base.join(&name)); + v.push(base.join("app/com.discordapp.Discord").join(&name)); + v.push(base.join("snap.discord").join(&name)); + } + v +} + +fn write_frame(s: &mut UnixStream, op: u32, body: &Value) -> std::io::Result<()> { + let b = body.to_string(); + let mut out = Vec::with_capacity(b.len() + 8); + out.extend_from_slice(&op.to_le_bytes()); + out.extend_from_slice(&(b.len() as u32).to_le_bytes()); + out.extend_from_slice(b.as_bytes()); + s.write_all(&out) +} + +fn read_frame(s: &mut UnixStream) -> std::io::Result<(u32, Value)> { + let mut h = [0u8; 8]; + s.read_exact(&mut h)?; + let op = u32::from_le_bytes(h[..4].try_into().unwrap()); + let len = u32::from_le_bytes(h[4..].try_into().unwrap()) as usize; + let mut b = vec![0; len.min(1 << 20)]; + s.read_exact(&mut b)?; + Ok((op, serde_json::from_slice(&b).unwrap_or(Value::Null))) +} + +fn connect(id: &str) -> Option { + for p in sockets() { + let Ok(mut s) = UnixStream::connect(&p) else { continue }; + let _ = s.set_read_timeout(Some(Duration::from_secs(3))); + if write_frame(&mut s, 0, &json!({"v": 1, "client_id": id})).is_err() { + continue; + } + // op 1 is the READY reply; op 2 means Discord refused, for example a wrong id + if let Ok((1, _)) = read_frame(&mut s) { + return Some(s); + } + } + None +} + +fn send(s: &mut UnixStream, activity: &Option, start: u64, nonce: u64) -> std::io::Result<()> { + let args = json!({"pid": std::process::id(), "activity": activity.as_ref().map_or(Value::Null, |a| a.json(start))}); + write_frame(s, 1, &json!({"cmd": "SET_ACTIVITY", "args": args, "nonce": nonce.to_string()}))?; + read_frame(s).map(|_| ()) +} + +pub enum Update { + /// The application id; empty turns presence off. + Id(String), + Show(Option), +} + +/// Starts the worker. It connects when Discord appears and reconnects if Discord restarts. +pub fn spawn() -> Sender { + let (tx, rx) = channel(); + std::thread::spawn(move || { + let start = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let (mut id, mut wanted, mut sent): (String, Option, Option>) = (String::new(), None, None); + let mut conn: Option = None; + let mut nonce = 0; + loop { + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Update::Id(new)) => { + if new != id { + id = new; + conn = None; + sent = None; + } + } + Ok(Update::Show(a)) => wanted = a, + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return, + } + if id.is_empty() { + conn = None; + continue; + } + if conn.is_none() { + conn = connect(&id); + sent = None; + } + if let Some(s) = &mut conn { + // nothing to clear until something has been shown + if sent.as_ref() != Some(&wanted) && (wanted.is_some() || sent.is_some()) { + nonce += 1; + if send(s, &wanted, start, nonce).is_ok() { + sent = Some(wanted.clone()); + } else { + conn = None; + } + } + } + } + }); + tx +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::net::UnixListener; + + #[test] + fn icons_for_common_files_exist() { + for (f, l, want) in [("main.rs", "Rust", "rust"), ("a.py", "Python", "python"), ("Cargo.toml", "TOML", "cargo"), ("a.cpp", "C++", "cpp"), ("run.sh", "Bash", "shell"), ("a.go", "Go", "go"), ("a.md", "Markdown", "markdown"), ("a.xyz", "None", "text"), ("a.weird", "Some Odd Language", "text")] { + assert_eq!(icon_for(f, l), want); + assert!(ICONS.contains(&format!(" {want} ")), "{want}"); + } + } + + #[test] + fn hidden_names_stay_out_of_the_text() { + let a = Activity::editing(None, None, "secret.rs", "Rust"); + let j = a.json(1).to_string(); + assert!(!j.contains("secret"), "{j}"); + assert_eq!(a.state.as_deref(), Some("Working on a Rust file")); + } + + /// Talks to a stand-in for Discord, so nothing here reaches the real app. + #[test] + fn handshake_then_activity_over_the_socket() { + let dir = std::env::temp_dir().join(format!("damson-ipc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ipc"); + let l = UnixListener::bind(&path).unwrap(); + let server = std::thread::spawn(move || { + let (mut s, _) = l.accept().unwrap(); + let (op, hello) = read_frame(&mut s).unwrap(); + write_frame(&mut s, 1, &json!({"evt": "READY"})).unwrap(); + let (op2, set) = read_frame(&mut s).unwrap(); + write_frame(&mut s, 1, &json!({"cmd": "SET_ACTIVITY"})).unwrap(); + (op, hello, op2, set) + }); + std::env::set_var("DAMSON_DISCORD_SOCKET", &path); + let tx = spawn(); + tx.send(Update::Id("123".into())).unwrap(); + tx.send(Update::Show(Some(Activity::editing(Some("main.rs"), Some("Damson"), "main.rs", "Rust")))).unwrap(); + let (op, hello, op2, set) = server.join().unwrap(); + std::env::remove_var("DAMSON_DISCORD_SOCKET"); + assert_eq!((op, op2), (0, 1)); + assert_eq!(hello["client_id"], "123"); + assert_eq!(set["cmd"], "SET_ACTIVITY"); + let a = &set["args"]["activity"]; + assert_eq!(a["state"], "Working on main.rs"); + assert_eq!(a["details"], "In Damson"); + assert_eq!(a["assets"]["large_image"], format!("{ICON_BASE}/rust.png")); + assert_eq!(a["assets"]["small_text"], "Damson"); + std::fs::remove_dir_all(dir).ok(); + } +} diff --git a/src/lib.rs b/src/lib.rs index 8f3e0d7..6854d4e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod app; pub mod config; +pub mod discord; pub mod git; pub mod icondata; pub mod lsp; diff --git a/src/main.rs b/src/main.rs index 21768ed..dd386b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,15 +19,14 @@ fn app_icon() -> egui::IconData { } fn main() -> eframe::Result { - let files: Vec = std::env::args().skip(1).filter(|a| !a.starts_with("--")).collect(); + let files: Vec = std::env::args().skip(1).collect(); let [w, h] = config::Settings::load().win; let viewport = egui::ViewportBuilder::default() .with_title(config::APP_NAME) .with_app_id("damson") .with_inner_size([w.max(800.0), h.max(520.0)]) .with_min_inner_size([760.0, 480.0]) - .with_decorations(false) - .with_transparent(true) + .with_decorations(true) .with_icon(std::sync::Arc::new(app_icon())); let options = eframe::NativeOptions { viewport, multisampling: 4, ..Default::default() }; eframe::run_native(config::APP_NAME, options, Box::new(move |cc| Ok(Box::new(App::new(cc, files))))) diff --git a/src/theme.rs b/src/theme.rs index b0a1cbc..98aeff5 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -155,12 +155,8 @@ impl Theme { let cael = caelestia_seed(); let fallback = Color32::from_rgb(0x7f, 0x5f, 0xc4); let custom = hex(&s.custom_color); - let (seed, sys_dark) = match s.color_source.as_str() { - "custom" => (custom.unwrap_or(fallback), cael.map(|c| c.1).or(kde_dark)), - "kde" => (kde_seed.unwrap_or(fallback), kde_dark), - "caelestia" => (cael.map(|c| c.0).or(kde_seed).unwrap_or(fallback), cael.map(|c| c.1)), - _ => (cael.map(|c| c.0).or(kde_seed).unwrap_or(fallback), cael.map(|c| c.1).or(kde_dark)), - }; + let sys_dark = cael.map(|c| c.1).or(kde_dark); + let seed = if s.color_source == "custom" { custom.unwrap_or(fallback) } else { cael.map(|c| c.0).or(kde_seed).unwrap_or(fallback) }; let dark = match s.mode.as_str() { "dark" => true, "light" => false, _ => sys_dark.unwrap_or(true) }; Self::from_seed(seed, dark, &s.scheme) } diff --git a/src/ui/editor.rs b/src/ui/editor.rs index b6ac042..f4c36d1 100644 --- a/src/ui/editor.rs +++ b/src/ui/editor.rs @@ -19,7 +19,7 @@ const SCROLL: Preset = Preset { stiffness: 520.0, damping: 1.0 }; /// Visual rows, when wrapping or folding make them differ from lines. #[derive(Default)] pub struct Rows { - key: (u64, u64, usize, usize), + pub key: (u64, u64, usize, usize), /// (line, first char column) of each row; `None` means rows and lines are the same. map: Option>>, } @@ -237,7 +237,21 @@ impl App { doc.refresh_folds(tab_w); let p = &mut self.panes[pane]; let tb = &mut p.tabs[p.active]; + // a change of layout keeps the same line at the top, so wrap on and off lands where it was + let top = (tb.rows.key.2 != wrap).then(|| { + let row = (tb.scroll.target.max(0.0) / m.lh) as usize; + let (line, col) = tb.rows.row(row.min(tb.rows.count(doc).saturating_sub(1))); + (line.min(doc.buf.lines().saturating_sub(1)), col, tb.scroll.target - row as f32 * m.lh) + }); tb.rows.refresh(doc, wrap, tab_w); + if let Some((line, col, within)) = top { + let y = tb.rows.row_of(line, col) as f32 * m.lh + within; + let t = y.max(0.0); + tb.scroll.snap(t); + let (cl, cc) = doc.buf.pos(doc.buf.head()); + let row = tb.rows.row_of(cl, cc) as f32; + tb.caret = [Spring::new(tb.caret[0].x), Spring::new(row * m.lh)]; + } } self.pointer(ui, pane, doc_id, &resp, code, m); diff --git a/src/ui/fonts.rs b/src/ui/fonts.rs index e66fff3..4587020 100644 --- a/src/ui/fonts.rs +++ b/src/ui/fonts.rs @@ -2,11 +2,18 @@ use eframe::egui::{self, FontData, FontDefinitions, FontFamily, FontId}; use eframe::epaint::text::{FontTweak, VariationCoords}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; pub const MED: &str = "rubik-500"; pub const SEMI: &str = "rubik-600"; +static CODE_FONT: OnceLock> = OnceLock::new(); + +/// The code font for drawing the preview's tiny text; Rubik if none was found. +pub fn code_font_bytes() -> &'static [u8] { + CODE_FONT.get().map_or(include_bytes!("../../assets/Rubik.ttf"), |v| v.as_slice()) +} + fn fc_match(pattern: &str) -> Option<(String, String)> { let out = std::process::Command::new("fc-match").args(["-f", "%{file}\n%{family}", pattern]).output().ok()?; let txt = String::from_utf8_lossy(&out.stdout).to_string(); @@ -40,6 +47,7 @@ pub fn install(ctx: &egui::Context, mono: &str) { }) }); if let Some(bytes) = picked.and_then(|(f, _)| std::fs::read(f).ok()) { + let _ = CODE_FONT.set(bytes.clone()); defs.font_data.insert("code".into(), Arc::new(FontData::from_owned(bytes))); defs.families.get_mut(&FontFamily::Monospace).unwrap().insert(0, "code".into()); } diff --git a/src/ui/menu.rs b/src/ui/menu.rs index e5b3489..5141515 100644 --- a/src/ui/menu.rs +++ b/src/ui/menu.rs @@ -236,7 +236,7 @@ impl App { } } Dialog::ConfirmQuit => { - ui.painter().text(rect.left_top() + vec2(26.0, 72.0), Align2::LEFT_CENTER, "They stay saved as recovery copies for next time.", fonts::ui(14.0), t.on_variant); + ui.painter().text(rect.left_top() + vec2(26.0, 72.0), Align2::LEFT_CENTER, if self.side_window { "This window isn't part of your session, so they'll be lost." } else { "They stay saved as recovery copies for next time." }, fonts::ui(14.0), t.on_variant); if pill(ui, &t, primary, "dlg/ok", "", "Quit", Tone::Filled).clicked() { after = Some(Box::new(|app, ctx| { app.quit_now = true; ctx.send_viewport_cmd(egui::ViewportCommand::Close) })); close = true; diff --git a/src/ui/morph.rs b/src/ui/morph.rs index 648028c..0d05e27 100644 --- a/src/ui/morph.rs +++ b/src/ui/morph.rs @@ -4,7 +4,7 @@ use crate::motion::{self, spring}; use crate::theme::{mix, Theme}; -use eframe::egui::{self, epaint::PathShape, pos2, vec2, Color32, Painter, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2}; +use eframe::egui::{self, epaint::PathShape, vec2, Color32, Painter, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2}; use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, TAU}; #[derive(Clone, Copy, PartialEq, Debug)] @@ -138,16 +138,18 @@ pub fn paint(p: &Painter, c: Pos2, size: f32, kind: Morph, t: f32, col: Color32, } } Morph::Wrap => { - let (a, b) = (-8.0, 8.0); - let tail = lerp_p(pos2(b, 0.0), pos2(4.0, 5.0), k); - let bend = lerp_p(pos2(b - 1.0, 0.0), pos2(8.0, 2.5), k); - let head = lerp_p(pos2(b, 0.0), pos2(-1.0, 5.0), k); - let pts = [c + vec2(a, lerp_f(0.0, -4.0, k)) * u, c + vec2(4.0, lerp_f(0.0, -4.0, k)) * u, c + bend.to_vec2() * u, c + tail.to_vec2() * u, c + head.to_vec2() * u]; + // off: three plain lines. on: the middle one runs out, hooks back and points left + line(p, &[c + vec2(-8.0, -6.0) * u, c + vec2(8.0, -6.0) * u], w, col); + line(p, &[c + vec2(-8.0, 6.0) * u, c + vec2(lerp_f(8.0, -3.5, k), 6.0) * u], w, col); + let start = [(-8.0, 0.0), (2.0, 0.0), (5.0, 0.0), (7.0, 0.0), (8.0, 0.0)]; + let end = [(-8.0, 0.0), (5.0, 0.0), (8.5, 3.0), (5.0, 6.0), (0.5, 6.0)]; + let pts: Vec = (0..5).map(|i| c + vec2(lerp_f(start[i].0, end[i].0, k), lerp_f(start[i].1, end[i].1, k)) * u).collect(); line(p, &pts, w, col); - let dir = if k > 0.5 { -1.0 } else { 1.0 }; - let h = c + head.to_vec2() * u; - let s = (2.0 * (k - 0.5).abs()).clamp(0.2, 1.0) * 3.4 * u; - line(p, &[h + vec2(-dir * s, -s), h, h + vec2(-dir * s, s)], w, col); + if k > 0.02 { + let tip = pts[4]; + let s = 3.0 * u * k; + line(p, &[tip + vec2(s, -s), tip, tip + vec2(s, s)], w, col); + } } Morph::CopyCheck => { let f = 1.0 - k; @@ -191,6 +193,10 @@ pub fn button(ui: &mut Ui, t: &Theme, rect: Rect, key: &str, kind: Morph, on: bo let m = spring(format!("{key}/m"), on as u8 as f32, motion::DEFAULT); let c = super::widgets::scale_rect(rect, 1.0 - 0.1 * press); let radius = super::widgets::lerp(rect.height() / 2.0, rect.height() * 0.3, press.clamp(0.0, 1.0)); + // a button that stays on shows it + if kind == Morph::Wrap && m > 0.01 { + ui.painter().rect_filled(c, super::widgets::cr(radius), crate::theme::alpha(t.secondary_container, m.clamp(0.0, 1.0))); + } if hov > 0.01 { ui.painter().rect_filled(c, super::widgets::cr(radius), crate::theme::alpha(t.on_surface, 0.09 * hov)); } @@ -202,6 +208,7 @@ pub fn button(ui: &mut Ui, t: &Theme, rect: Rect, key: &str, kind: Morph, on: bo #[cfg(test)] mod tests { use super::*; + use eframe::egui::pos2; /// Every morph has to draw at both ends and past them, since springs overshoot. #[test] diff --git a/src/ui/preview.rs b/src/ui/preview.rs index e65efd4..a91cc7f 100644 --- a/src/ui/preview.rs +++ b/src/ui/preview.rs @@ -1,4 +1,4 @@ -//! The scrolling preview. A texture of the whole file sits on a rail beside the code. +//! The scrolling preview. A picture of the file, drawn in real glyphs, sits on a rail beside the code. //! //! Pressing the rail pops it out: it widens over the code, the lines near the pointer swell like a //! lens (the texture is drawn on a bent mesh), and a card of real, readable code bursts out beside @@ -8,53 +8,113 @@ use super::{fonts, widgets::*}; use crate::app::App; use crate::motion::{self, spring, Preset}; -use crate::text::Doc; -use crate::theme::{alpha, mix, Theme}; -use eframe::egui::{self, emath::TSTransform, pos2, vec2, Color32, ColorImage, Id, LayerId, Mesh, Order, Rect, Sense, TextureHandle, TextureOptions, Ui}; +use crate::theme::{alpha, mix}; +use eframe::egui::{self, emath::TSTransform, pos2, vec2, Color32, ColorImage, Id, LayerId, Mesh, Order, Rect, Sense, TextureFilter, TextureHandle, TextureOptions, TextureWrapMode, Ui}; +use ropey::Rope; +use std::collections::HashMap; +use std::sync::mpsc::{channel, Receiver}; +use std::sync::{Arc, Mutex, OnceLock}; -const ROW_PX: usize = 3; -const CHAR_PX: usize = 2; -const COLS: usize = 120; -const MAX_ROWS: usize = 4096; +const ROW_PX: usize = 8; +const CHAR_PX: usize = 4; +const GLYPH_PX: f32 = 7.2; +const BASELINE: i32 = 6; +const COLS: usize = 110; +/// Longer files get a window of lines around the view. +const MAX_ROWS: usize = 2040; const STRIPS: usize = 72; +/// Rail scale at rest and fully popped out, in points per line and per character. +const LINE_H: (f32, f32) = (3.4, 6.0); +const CHAR_W: (f32, f32) = (1.7, 3.0); +const OPTIONS: TextureOptions = TextureOptions { magnification: TextureFilter::Linear, minification: TextureFilter::Linear, wrap_mode: TextureWrapMode::ClampToEdge, mipmap_mode: Some(TextureFilter::Linear) }; + +type Key = (u64, u64, u32, usize); + +struct Built { + key: Key, + image: ColorImage, + rows: usize, +} #[derive(Default)] pub struct Mini { tex: Option, - key: (u64, u64, u32), + /// What's in `tex`. + shown: Option, + /// What the worker is drawing now. + pending: Option, + rx: Option>, built: f64, - /// Doc lines per texture row. - step: f32, + first: usize, rows: usize, } -fn build(doc: &Doc, reg: &crate::syntax::Registry, t: &Theme, tab: usize) -> (ColorImage, usize, f32) { - let lines = doc.buf.lines(); - let rows = lines.min(MAX_ROWS).max(1); - let step = lines as f32 / rows as f32; +impl Mini { + /// Is a picture of this document on the rail? + pub fn ready(&self, doc: u64) -> bool { + self.tex.is_some() && self.shown.is_some_and(|k| k.0 == doc) + } +} + +/// Everything the worker needs, so drawing never holds up a frame. +struct Job { + key: Key, + rope: Rope, + hl: Vec, + colors: Vec, + normal: Color32, + first: usize, + tab: usize, +} + +struct Glyph { + x: i32, + y: i32, + w: usize, + h: usize, + px: Vec, +} + +fn font() -> Option<&'static fontdue::Font> { + static F: OnceLock> = OnceLock::new(); + F.get_or_init(|| fontdue::Font::from_bytes(super::fonts::code_font_bytes(), fontdue::FontSettings::default()).ok()).as_ref() +} + +fn draw(job: Job) -> Built { + static GLYPHS: OnceLock>>> = OnceLock::new(); + let cache = GLYPHS.get_or_init(Default::default); + let rows = job.hl.len().max(1); let (w, h) = (COLS * CHAR_PX, rows * ROW_PX); let mut px = vec![Color32::TRANSPARENT; w * h]; - for r in 0..rows { - let line = (r as f32 * step) as usize; - let text = doc.buf.line_text(line); - let spans = doc.hl.get(line).map(|h| h.spans.clone()); + let font = font(); + for (r, hl) in job.hl.iter().enumerate() { let (mut x, mut byte, mut si) = (0usize, 0u32, 0usize); - for c in text.chars() { - let cells = super::editor::cell_width(c, x, tab); - if x >= COLS { break } + let spans = &hl.spans; + for c in job.rope.line(job.first + r).chars() { + if c == '\n' || c == '\r' || x >= COLS { break } + let cells = super::editor::cell_width(c, x, job.tab); if !c.is_whitespace() { - let mut col = t.syntax[0]; - if let Some(sp) = &spans { - while si < sp.len() && sp[si].end <= byte { si += 1 } - if let Some(s) = sp.get(si).filter(|s| s.start <= byte) { - if let Some(st) = reg.compiled.styles.get(s.style as usize) { col = t.syntax[st.base as usize] } - } - } - let col = alpha(col, 0.86); - for yy in 0..ROW_PX - 1 { - for xx in 0..CHAR_PX * cells { - let px_x = x * CHAR_PX + xx; - if px_x < w { px[(r * ROW_PX + yy) * w + px_x] = col } + while si < spans.len() && spans[si].end <= byte { si += 1 } + let col = spans.get(si).filter(|s| s.start <= byte).and_then(|s| job.colors.get(s.style as usize)).copied().unwrap_or(job.normal); + let g = font.map(|f| { + let mut m = cache.lock().unwrap(); + m.entry(c).or_insert_with(|| { + let (me, bits) = f.rasterize(c, GLYPH_PX); + Arc::new(Glyph { x: me.xmin, y: BASELINE - me.height as i32 - me.ymin, w: me.width, h: me.height, px: bits }) + }).clone() + }); + if let Some(g) = g { + for gy in 0..g.h { + let py = (r * ROW_PX) as i32 + g.y + gy as i32; + if py < 0 || py as usize >= h { continue } + for gx in 0..g.w { + let cov = g.px[gy * g.w + gx]; + let ox = (x * CHAR_PX) as i32 + g.x + gx as i32; + if cov > 24 && ox >= 0 && (ox as usize) < w { + // small text reads thin, so coverage gets a lift + px[py as usize * w + ox as usize] = alpha(col, (cov as f32 / 255.0 * 1.5).min(1.0)); + } + } } } } @@ -62,7 +122,7 @@ fn build(doc: &Doc, reg: &crate::syntax::Registry, t: &Theme, tab: usize) -> (Co byte += c.len_utf8() as u32; } } - (ColorImage::new([w, h], px), rows, step) + Built { key: job.key, image: ColorImage::new([w, h], px), rows } } /// Line ↔ rail position, including the lens bend around the pointer. @@ -106,25 +166,6 @@ impl App { let m = self.metrics(ui); let now = ui.input(|i| i.time); - // texture: rebuilt when colours or text change, but not more than a few times a second - { - let doc = &self.docs[&doc_id]; - let mini = &mut self.panes[pane].mini; - let key = (doc_id, doc.hl_version, self.theme_stamp); - if mini.key != key && (now - mini.built > 0.14 || mini.key.0 != doc_id || mini.tex.is_none()) { - let (img, rows, step) = build(doc, &self.reg, &t, self.s.tab_width); - match &mut mini.tex { - Some(h) if h.size() == img.size => h.set(img, TextureOptions::LINEAR), - _ => mini.tex = Some(ui.ctx().load_texture(format!("mini-{pane}"), img, TextureOptions::LINEAR)), - } - mini.key = key; - mini.built = now; - mini.rows = rows; - mini.step = step; - } - if mini.key != key { motion::keep_alive() } - } - let key = format!("mini/{pane}"); let id = ui.scope_id().with(&key); let active = self.panes[pane].dragging_mini; @@ -132,16 +173,59 @@ impl App { let hover_rail = ui.rect_contains_pointer(rail); let hov = spring(format!("{key}/hov"), hover_rail as u8 as f32, motion::EFFECT); - let visual = lerp(1.0, 2.4, pop.max(0.0)); + let visual = lerp(1.0, 2.3, pop.max(0.0)); let popped = pop.abs() > 0.004; let frame = Rect::from_min_max(pos2(rail.right() - rail.width() * visual - 2.0 * hov, rail.top()), rail.max); - let lh = lerp(2.0, 3.0, pop.clamp(0.0, 1.2)); + let lh = lerp(LINE_H.0, LINE_H.1, pop.clamp(0.0, 1.2)); let visible = m.lh * count as f32; let total_h = lh * count as f32; let max_scroll = (visible - rail.height()).max(1.0); let frac = (scroll / max_scroll).clamp(0.0, 1.0); let offset = if total_h > frame.height() { frac * (total_h - frame.height()) } else { 0.0 }; + // the picture: drawn by a worker, and only asked for again once the last one has landed + { + let mini = &mut self.panes[pane].mini; + if let Some(b) = mini.rx.as_ref().and_then(|r| r.try_recv().ok()) { + match &mut mini.tex { + Some(h) if h.size() == b.image.size => h.set(b.image, OPTIONS), + _ => mini.tex = Some(ui.ctx().load_texture(format!("mini-{pane}"), b.image, OPTIONS)), + } + mini.first = b.key.3; + mini.rows = b.rows; + mini.shown = Some(b.key); + mini.pending = None; + mini.rx = None; + } + // a long file keeps a window of lines around what the rail is showing + // (how tall a texture can be is up to the GPU) + let max_rows = (ui.input(|i| i.max_texture_side) / ROW_PX).min(MAX_ROWS); + let rail_top = ((offset / lh) as usize).min(count.saturating_sub(1)); + let rail_end = rail_top + (frame.height() / lh) as usize + 1; + let last_first = mini.pending.or(mini.shown).filter(|k| k.0 == doc_id).map_or(usize::MAX, |k| k.3); + let first = if count <= max_rows { 0 } + else if last_first != usize::MAX && rail_top >= last_first && rail_end <= last_first + max_rows { last_first } + else { rail_top.saturating_sub(max_rows / 8).min(count - max_rows) }; + let doc = &self.docs[&doc_id]; + let want: Key = (doc_id, doc.hl_version, self.theme_stamp, first); + let new_doc = mini.shown.is_none_or(|k| k.0 != doc_id || k.3 != first); + if mini.pending.is_none() && mini.shown != Some(want) && (new_doc || now - mini.built > 0.12) { + let end = (first + max_rows).min(doc.hl.len()); + let colors = self.reg.compiled.styles.iter().map(|s| t.syntax[s.base as usize]).collect(); + let job = Job { key: want, rope: doc.buf.rope.clone(), hl: doc.hl[first.min(end)..end].to_vec(), colors, normal: t.syntax[0], first, tab: self.s.tab_width }; + let (tx, rx) = channel(); + let ctx = ui.ctx().clone(); + std::thread::spawn(move || { + let _ = tx.send(draw(job)); + ctx.request_repaint(); + }); + mini.rx = Some(rx); + mini.pending = Some(want); + mini.built = now; + } + if mini.shown != Some(want) { motion::keep_alive() } + } + let ptr = ui.input(|i| i.pointer.interact_pos()); let center = spring(format!("{key}/cy"), ptr.map_or(0.0, |p| (p.y - frame.top()).clamp(0.0, frame.height())), Preset { stiffness: 900.0, damping: 0.8 }); let map = Map { top: frame.top(), height: frame.height(), lh, offset, bend: 0.74 * pop.clamp(0.0, 1.0), center }; @@ -160,14 +244,14 @@ impl App { // the bent texture let mini = &self.panes[pane].mini; - if let Some(tex) = &mini.tex { + if let Some(tex) = mini.tex.as_ref().filter(|_| mini.ready(doc_id)) { let mut mesh = Mesh::with_texture(tex.id()); let tint = alpha(Color32::WHITE, lerp(0.8, 1.0, pop.clamp(0.0, 1.0))); - let u_max = (inner.width() / (COLS as f32 * lerp(1.0, 1.7, pop.clamp(0.0, 1.0)))).min(1.0); + let u_max = (inner.width() / (COLS as f32 * lerp(CHAR_W.0, CHAR_W.1, pop.clamp(0.0, 1.0)))).min(1.0); for i in 0..=STRIPS { let y = inner.height() * i as f32 / STRIPS as f32; let line = map.line_at(y).clamp(0.0, count as f32); - let v = (line / mini.step.max(0.001) / mini.rows.max(1) as f32).clamp(0.0, 1.0); + let v = ((line - mini.first as f32) / mini.rows.max(1) as f32).clamp(0.0, 1.0); // nothing is drawn below the last line let fade = if line >= count as f32 { 0.0 } else { 1.0 }; let c = alpha(tint, fade * tint.a() as f32 / 255.0); diff --git a/src/ui/rail.rs b/src/ui/rail.rs index 5ed8e74..955c7dc 100644 --- a/src/ui/rail.rs +++ b/src/ui/rail.rs @@ -11,29 +11,32 @@ use eframe::egui::{pos2, vec2, Align2, Rect, Sense, Ui}; pub const SIDES: [(&str, &str, &str); 5] = [("Files", "folder", "folder_fill"), ("Search", "search", "search"), ("Outline", "account_tree", "account_tree_fill"), ("Git", "commit", "commit"), ("Problems", "error", "error_fill")]; impl App { - pub fn rail(&mut self, ui: &mut Ui, rect: Rect) { + /// The Damson bloom, which opens the main menu. + pub fn logo(&mut self, ui: &mut Ui, logo: eframe::egui::Pos2) { let t = self.t.clone(); - let logo = pos2(rect.center().x, rect.top() + 28.0); - let lr = Rect::from_center_size(logo, vec2(46.0, 46.0)); + let lr = Rect::from_center_size(logo, vec2(44.0, 44.0)); let resp = ui.interact(lr, ui.scope_id().with("logo"), Sense::click()).on_hover_text("Menu"); let (hov, press) = states("logo", &resp); - // the logo breathes between shapes and spins up under the pointer + // it breathes and spins up under the pointer if resp.hovered() { self.logo_clock += motion::dt(); motion::keep_alive(); } let spin = self.logo_clock * 0.5 + spring("logo/spin", self.logo_spin, motion::SLOW); let amount = 0.075 + 0.035 * (self.logo_clock * 1.6).sin() + 0.03 * hov; - blob(ui.painter(), logo, 20.0 * (1.0 - 0.1 * press), 7.0, amount, spin, t.primary_container); - icons::paint(ui.ctx(), ui.painter(), logo, 22.0, "code", t.on_primary_container); + blob(ui.painter(), logo, 19.0 * (1.0 - 0.1 * press), 7.0, amount, spin, t.primary_container); + icons::paint(ui.ctx(), ui.painter(), logo, 21.0, "code", t.on_primary_container); if resp.clicked() { self.logo_spin += 1.2; - self.app_menu(lr.right_top() + vec2(8.0, 0.0)); + self.app_menu(lr.left_bottom() + vec2(-200.0, 6.0)); } + } + pub fn rail(&mut self, ui: &mut Ui, rect: Rect) { + let t = self.t.clone(); let open = self.side_open.then_some(self.side); let h = 62.0; - let top = rect.top() + 72.0; + let top = rect.top() + 6.0; let pill_y = spring("rail/y", top + self.side as f32 * h, crate::motion::Preset { stiffness: 900.0, damping: 0.68 }); let on = spring("rail/on", open.is_some() as u8 as f32, motion::FAST); let problems = self.problem_count(); diff --git a/src/ui/settings.rs b/src/ui/settings.rs index 6f1891b..af13c35 100644 --- a/src/ui/settings.rs +++ b/src/ui/settings.rs @@ -1,12 +1,15 @@ //! Settings: a sheet that rises over the window, in the same card-and-rows look as Nacre's. +use super::morph::{self, Morph}; use super::{fonts, icons, widgets::*}; use crate::app::App; use crate::motion::{self, spring, spring_from}; -use crate::theme::{alpha, hex}; +use crate::config::TOOLBAR_MAX; +use crate::theme::{alpha, hex, mix}; +use std::collections::HashSet; use eframe::egui::{self, pos2, vec2, Align2, Area, Color32, Id, Key, Order, Rect, Sense, Ui}; -const SECTIONS: [(&str, &str); 4] = [("Appearance", "palette"), ("Editor", "edit"), ("Motion", "motion_mode"), ("Terminal", "terminal")]; +const SECTIONS: [(&str, &str); 6] = [("Appearance", "palette"), ("Editor", "edit"), ("Motion", "motion_mode"), ("Terminal", "terminal"), ("Toolbar", "tune"), ("Discord", "rocket_launch")]; const SEEDS: [&str; 8] = ["#7f5fc4", "#d0485e", "#d9782b", "#c8a020", "#3f9c6b", "#1f9aa8", "#2b7fd4", "#c656a8"]; impl App { @@ -51,17 +54,26 @@ impl App { let list = Rect::from_min_max(body.min + vec2(0.0, 48.0), body.max); let mut sub = ui.new_child(egui::UiBuilder::new().max_rect(list)); sub.set_clip_rect(list); - let mut y = list.top(); let tab = self.settings_tab; + if ui.rect_contains_pointer(list) { + self.settings_scroll[tab] -= wheel(ui).y; + } + let room = (self.settings_height[tab] - list.height()).max(0.0); + self.settings_scroll[tab] = self.settings_scroll[tab].clamp(0.0, room); + let scroll = spring(format!("set/scroll{tab}"), self.settings_scroll[tab], motion::Preset { stiffness: 520.0, damping: 1.0 }); let entered = spring_from(format!("set/tab{tab}"), 0.0, 1.0, motion::DEFAULT); - let off = (1.0 - entered) * 24.0; - y += off; + let start = list.top() - scroll + (1.0 - entered) * 24.0; + let mut y = start; match tab { 0 => self.appearance(&mut sub, list, &mut y), 1 => self.editor_settings(&mut sub, list, &mut y), 2 => self.motion_settings(&mut sub, list, &mut y), - _ => self.terminal_settings(&mut sub, list, &mut y), + 3 => self.terminal_settings(&mut sub, list, &mut y), + 4 => self.toolbar_settings(&mut sub, list, &mut y), + _ => self.discord_settings(&mut sub, list, &mut y), } + self.settings_height[tab] = y - start; + scroll_pill(ui.painter(), &t, list, scroll, self.settings_height[tab]); }); if ctx.input(|i| i.key_pressed(Key::Escape)) { self.settings_open = false } if self.s != before { @@ -124,7 +136,7 @@ impl App { let mode = self.s.mode.clone(); if let Some(v) = self.choice(ui, list, y, "set/mode", "Theme", "Follows your desktop on Auto", &[("auto", "Auto"), ("light", "Light"), ("dark", "Dark")], &mode) { self.s.mode = v } let src = self.s.color_source.clone(); - if let Some(v) = self.choice(ui, list, y, "set/src", "Colours from", "Your desktop, or a colour you pick", &[("auto", "Desktop"), ("caelestia", "Caelestia"), ("kde", "KDE"), ("custom", "Custom")], &src) { self.s.color_source = v } + if let Some(v) = self.choice(ui, list, y, "set/src", "Colours from", "Your desktop, or a colour you pick", &[("auto", "Desktop"), ("custom", "Custom")], &src) { self.s.color_source = v } let sch = self.s.scheme.clone(); if let Some(v) = self.choice(ui, list, y, "set/sch", "Style", "How much colour the scheme uses", &[("tonal", "Tonal"), ("vibrant", "Vibrant"), ("expressive", "Expressive"), ("mono", "Mono")], &sch) { self.s.scheme = v } let r = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 74.0)); @@ -172,24 +184,144 @@ impl App { self.s.motion = v.parse().unwrap_or(2); } self.toggle(ui, list, y, "set/prev", "Scrolling preview", "The rail of code beside the editor", |s| &mut s.preview); - self.toggle(ui, list, y, "set/lens", "Preview lens", "A card of real code pops out while you drag the preview. Hold Shift to peek.", |s| &mut s.lens); + self.toggle(ui, list, y, "set/lens", "Preview lens", "A card of code pops out while you drag. Hold Shift to peek.", |s| &mut s.lens); } fn terminal_settings(&mut self, ui: &mut Ui, list: Rect, y: &mut f32) { let f = self.s.terminal_font; let d = self.stepper(ui, list, y, "set/tfont", "Text size", format!("{f:.0}")); self.s.terminal_font = (f + d as f32).clamp(8.0, 30.0); + self.shell_picker(ui, list, y); + } + + /// A dropdown of the shells installed here. It unfolds in place, inside the sheet. + fn shell_picker(&mut self, ui: &mut Ui, list: Rect, y: &mut f32) { + let t = self.t.clone(); + if self.shells.is_empty() { + self.shells = scan_shells(); + } + let current = if self.s.shell.is_empty() { "Login shell".to_string() } else { short_shell(&self.s.shell) }; + let r = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 62.0)); + let open = spring("set/shell", self.shell_open as u8 as f32, motion::DEFAULT).clamp(0.0, 1.1); + let rows: Vec<(String, String)> = std::iter::once(("Login shell".to_string(), String::new())).chain(self.shells.iter().map(|p| (short_shell(p), p.clone()))).collect(); + let list_h = rows.len() as f32 * 42.0 * open; + let whole = Rect::from_min_size(r.min, vec2(r.width(), 62.0 + list_h)); + self.card(ui, whole); + self.label(ui, r, "Shell", "New terminals start in this"); + let field = Rect::from_min_size(pos2(r.right() - 214.0, r.center().y - 19.0), vec2(200.0, 38.0)); + let resp = ui.interact(field, ui.scope_id().with("set/shellf"), Sense::click()); + let (hov, press) = states("set/shellf", &resp); + ui.painter().rect_filled(scale_rect(field, 1.0 - 0.03 * press), cr(14.0), mix(t.highest, t.on_surface, 0.06 * hov)); + ui.painter().text(field.left_center() + vec2(14.0, 0.0), Align2::LEFT_CENTER, current, fonts::med(13.0), t.on_surface); + morph::paint(ui.painter(), field.right_center() - vec2(20.0, 0.0), 16.0, Morph::Fold, 1.0 + open * 2.0, t.on_variant, t.highest); + if resp.clicked() { self.shell_open = !self.shell_open } + if open > 0.05 { + let p = ui.painter().with_clip_rect(whole.intersect(ui.clip_rect())); + for (i, (name, path)) in rows.iter().enumerate() { + let rr = Rect::from_min_size(pos2(r.left() + 8.0, r.bottom() + i as f32 * 42.0 * open), vec2(r.width() - 16.0, 40.0)); + let key = format!("set/shell{i}"); + let row = ui.interact(rr.intersect(whole), ui.scope_id().with(&key), Sense::click()); + let (hov, _) = states(&key, &row); + let on = self.s.shell == *path; + if on { p.rect_filled(rr, cr(14.0), t.secondary_container); } + else if hov > 0.01 { p.rect_filled(rr, cr(14.0), alpha(t.on_surface, 0.07 * hov)); } + let fg = if on { t.on_secondary_container } else { t.on_surface }; + p.text(rr.left_center() + vec2(14.0, 0.0), Align2::LEFT_CENTER, name, fonts::med(13.5), fg); + p.text(rr.right_center() - vec2(14.0, 0.0), Align2::RIGHT_CENTER, path, fonts::ui(12.0), t.on_variant); + if row.clicked() { + self.s.shell = path.clone(); + self.shell_open = false; + } + } + } + *y += 66.0 + list_h; + } + + /// Choose the icons at the top of the window, from everything the app can do. + fn toolbar_settings(&mut self, ui: &mut Ui, list: Rect, y: &mut f32) { + let t = self.t.clone(); + let used = self.s.toolbar.len(); let r = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 62.0)); self.card(ui, r); - self.label(ui, r, "Shell", "Empty uses your login shell"); + self.label(ui, r, "Icons beside the + button", &format!("{used} of {TOOLBAR_MAX} used")); + let reset = Rect::from_min_size(pos2(r.right() - 98.0, r.center().y - 17.0), vec2(84.0, 34.0)); + if pill(ui, &t, reset, "set/barclear", "", "Clear all", Tone::Tonal).clicked() { self.s.toolbar.clear() } + *y += 66.0; + let field = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 42.0)); + ui.painter().rect_filled(field, cr(18.0), t.high); + icons::paint(ui.ctx(), ui.painter(), field.left_center() + vec2(20.0, 0.0), 18.0, "search", t.on_variant); + ui.put(Rect::from_min_max(field.min + vec2(38.0, 10.0), field.max - vec2(12.0, 8.0)), egui::TextEdit::singleline(&mut self.toolbar_filter).frame(egui::Frame::NONE).hint_text("Search commands").font(fonts::ui(13.5)).text_color(t.on_surface)); + *y += 48.0; + let q = self.toolbar_filter.clone(); + for e in super::commands::all() { + if super::palette::fuzzy(&q, e.label).is_none() { continue } + let r = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 46.0)); + *y += 48.0; + if r.bottom() < list.top() || r.top() > list.bottom() { continue } + let on = self.s.toolbar.iter().any(|l| l == e.label); + ui.painter().rect_filled(r, cr(14.0), if on { t.highest } else { t.high }); + icons::paint(ui.ctx(), ui.painter(), r.left_center() + vec2(22.0, 0.0), 19.0, e.ic, t.on_variant); + ui.painter().text(r.left_center() + vec2(46.0, 0.0), Align2::LEFT_CENTER, e.label, fonts::med(13.5), t.on_surface); + let sw = Rect::from_center_size(r.right_center() - vec2(44.0, 0.0), vec2(60.0, 38.0)); + let full = !on && used >= TOOLBAR_MAX; + if switch(ui, &t, sw, &format!("set/bar/{}", e.label), on).clicked() { + if on { + self.s.toolbar.retain(|l| l != e.label); + } else if full { + self.toast("info", format!("The top bar holds {TOOLBAR_MAX} icons. Remove one first.")); + } else { + self.s.toolbar.push(e.label.to_string()); + } + } + } + } + + fn discord_settings(&mut self, ui: &mut Ui, list: Rect, y: &mut f32) { let t = self.t.clone(); + self.toggle(ui, list, y, "set/dc", "Show what I'm editing on Discord", "File, project, language icon and time spent", |s| &mut s.discord); + self.toggle(ui, list, y, "set/dcf", "Show the file name", "Off says only the language", |s| &mut s.discord_file); + self.toggle(ui, list, y, "set/dcp", "Show the project name", "", |s| &mut s.discord_project); + let r = Rect::from_min_size(pos2(list.left(), *y), vec2(list.width(), 62.0)); + self.card(ui, r); + let missing = self.s.discord_id.trim().is_empty(); + self.label(ui, r, "Application ID", if missing { "Needed before anything shows. See the note below." } else { "The name Discord shows comes from this" }); let field = Rect::from_min_size(pos2(r.right() - 234.0, r.center().y - 18.0), vec2(220.0, 36.0)); ui.painter().rect_filled(field, cr(14.0), t.highest); - ui.put(field.shrink2(vec2(12.0, 9.0)), egui::TextEdit::singleline(&mut self.s.shell).frame(egui::Frame::NONE).font(fonts::ui(13.0)).text_color(t.on_surface)); + ui.put(field.shrink2(vec2(12.0, 9.0)), egui::TextEdit::singleline(&mut self.s.discord_id).frame(egui::Frame::NONE).font(fonts::ui(13.0)).text_color(t.on_surface)); *y += 66.0; + for (i, line) in ["Make an application named Damson at discord.com/developers/applications,", "then paste its Application ID here. For the small Damson icon, upload", "packaging/damson.svg as a PNG under Rich Presence, named damson."].iter().enumerate() { + ui.painter().text(pos2(list.left() + 18.0, *y + 12.0 + i as f32 * 19.0), Align2::LEFT_CENTER, *line, fonts::ui(12.5), t.on_variant); + } + *y += 70.0; } } +fn short_shell(path: &str) -> String { + path.rsplit('/').next().unwrap_or(path).to_string() +} + +/// Installed shells, from /etc/shells and a look along PATH, one per name. +fn scan_shells() -> Vec { + const SKIP: [&str; 6] = ["rbash", "git-shell", "nologin", "false", "systemd-home-fallback-shell", "sh"]; + const KNOWN: [&str; 12] = ["bash", "fish", "zsh", "nu", "dash", "ksh", "mksh", "tcsh", "csh", "elvish", "xonsh", "pwsh"]; + let listed = std::fs::read_to_string("/etc/shells").unwrap_or_default(); + let mut paths: Vec = listed.lines().map(str::trim).filter(|l| l.starts_with('/')).map(str::to_string).collect(); + if let Some(p) = std::env::var_os("PATH") { + for dir in std::env::split_paths(&p) { + for k in KNOWN { + let f = dir.join(k); + if f.is_file() { paths.push(f.to_string_lossy().into_owned()) } + } + } + } + // /usr/bin before /bin, so the same shell isn't listed twice + paths.sort_by_key(|p| !p.starts_with("/usr/bin")); + let mut seen = HashSet::new(); + let mut out: Vec = paths.into_iter().filter(|p| std::path::Path::new(p).is_file()).filter(|p| { let n = short_shell(p); !SKIP.contains(&n.as_str()) && seen.insert(n) }).collect(); + out.sort_by_key(|p| short_shell(p)); + out +} + fn i_time(ui: &Ui) -> f64 { ui.input(|i| i.time) } diff --git a/src/ui/status.rs b/src/ui/status.rs index e926e14..99c04d7 100644 --- a/src/ui/status.rs +++ b/src/ui/status.rs @@ -59,7 +59,8 @@ impl App { if self.cur_doc().is_some() { let r = Rect::from_center_size(pos2(rect.right() - FAB_W - 26.0, rect.center().y), vec2(32.0, 32.0)); - let (wrap, tip) = (self.s.word_wrap, "Word wrap (F10)"); + let wrap = self.s.word_wrap; + let tip = if wrap { "Word wrap is on (F10)" } else { "Word wrap is off (F10)" }; if morph::button(ui, &t, r, "st/wrap", Morph::Wrap, wrap, tip, t.surface).clicked() { self.run(ui.ctx(), Cmd::ToggleWrap); } diff --git a/src/ui/terminal.rs b/src/ui/terminal.rs index b78ef4d..8e5c937 100644 --- a/src/ui/terminal.rs +++ b/src/ui/terminal.rs @@ -60,11 +60,15 @@ pub struct Session { pub running: bool, caret: [Spring; 2], id: u64, + /// A new size, and when it was first seen. + next_size: Option<((usize, usize), f64)>, + /// How many times the shell has been told of a new size. + pub resizes: u32, } impl Session { - pub fn spawn(ctx: &egui::Context, id: u64, cwd: Option, shell: &str) -> std::io::Result { - let size = Size { cols: 100, lines: 24 }; + pub fn spawn(ctx: &egui::Context, id: u64, cwd: Option, shell: &str, (cols, lines): (usize, usize)) -> std::io::Result { + let size = Size { cols, lines }; let (tx, rx) = channel(); let proxy = Proxy { tx, ctx: ctx.clone() }; let mut env = std::collections::HashMap::new(); @@ -73,14 +77,26 @@ impl Session { env.insert("TERM_PROGRAM".to_string(), "damson".to_string()); let shell = (!shell.is_empty()).then(|| tty::Shell::new(shell.to_string(), vec![])); let opts = tty::Options { shell, working_directory: cwd, drain_on_exit: false, env, ..Default::default() }; - let ws = WindowSize { num_lines: 24, num_cols: 100, cell_width: 8, cell_height: 18 }; + let ws = WindowSize { num_lines: lines as u16, num_cols: cols as u16, cell_width: 8, cell_height: 18 }; tty::setup_env(); let pty = tty::new(&opts, ws, id)?; let term = Arc::new(FairMutex::new(Term::new(Config::default(), &size, proxy.clone()))); let lp = EventLoop::new(term.clone(), proxy, pty, false, false).map_err(std::io::Error::other)?; let notifier = Notifier(lp.channel()); lp.spawn(); - Ok(Session { term, notifier, rx, size, cell: (8.0, 18.0), title: "Shell".into(), exited: false, running: false, caret: [Spring::new(0.0), Spring::new(0.0)], id }) + Ok(Session { term, notifier, rx, size, cell: (8.0, 18.0), title: "Shell".into(), exited: false, running: false, caret: [Spring::new(0.0), Spring::new(0.0)], id, next_size: None, resizes: 0 }) + } + + /// The visible screen as text, one string per row. + pub fn screen_text(&self) -> Vec { + let term = self.term.lock(); + let mut rows = vec![String::new(); self.size.lines]; + for c in term.renderable_content().display_iter { + if let Some(r) = usize::try_from(c.point.line.0).ok().and_then(|l| rows.get_mut(l)) { + r.push(c.c); + } + } + rows } pub fn write(&self, s: impl Into>) { @@ -114,10 +130,28 @@ impl Session { } } - fn resize(&mut self, cols: usize, lines: usize, cell: (f32, f32)) { + /// Every resize makes the shell redraw its prompt, so one only goes through once the size has + /// held still for a moment: dragging the card or a panel sends one, not dozens. + fn resize(&mut self, cols: usize, lines: usize, cell: (f32, f32), now: f64) { if cols == self.size.cols && lines == self.size.lines { + self.next_size = None; return; } + match self.next_size { + Some((s, since)) if s == (cols, lines) => { + if now - since < 0.18 { + motion::keep_alive(); + return; + } + } + _ => { + self.next_size = Some(((cols, lines), now)); + motion::keep_alive(); + return; + } + } + self.next_size = None; + self.resizes += 1; self.size = Size { cols, lines }; self.cell = cell; let _ = self.notifier.0.send(Msg::Resize(WindowSize { num_lines: lines as u16, num_cols: cols as u16, cell_width: cell.0 as u16, cell_height: cell.1 as u16 })); @@ -200,6 +234,16 @@ fn key_bytes(key: Key, md: Modifiers, app_cursor: bool) -> Option> { }) } +fn term_line(size: f32) -> f32 { + (size * 1.36).round() +} + +/// The text area of a terminal card. +fn term_body(card: Rect) -> Rect { + let inner = card.shrink(4.0); + Rect::from_min_max(pos2(inner.left() + 10.0, inner.top() + 38.0), pos2(inner.right() - 8.0, inner.bottom() - 6.0)) +} + impl App { pub fn term_focus_id(&self) -> egui::Id { egui::Id::unique("terminal-surface") @@ -208,7 +252,11 @@ impl App { pub fn new_terminal(&mut self, ctx: &egui::Context, cwd: Option) { let cwd = cwd.or_else(|| self.root.clone()).or_else(|| dirs::home_dir()); self.next_term += 1; - match Session::spawn(ctx, self.next_term, cwd, &self.s.shell) { + let font = fonts::mono(self.s.terminal_font); + let cw = ctx.fonts_mut(|f| f.glyph_width(&font, 'M')); + let body = term_body(self.term_target); + let size = (((body.width() / cw) as usize).max(10), ((body.height() / term_line(self.s.terminal_font)) as usize).max(3)); + match Session::spawn(ctx, self.next_term, cwd, &self.s.shell, size) { Ok(s) => { self.terms.push(s); self.term_cur = self.terms.len() - 1; @@ -247,8 +295,7 @@ impl App { return; } let vis = ((k - 0.35) / 0.65).clamp(0.0, 1.0); - let inner = rect.shrink(4.0); - let head = Rect::from_min_size(inner.min, vec2(inner.width(), 38.0)); + let head = Rect::from_min_size(rect.shrink(4.0).min, vec2(rect.width() - 8.0, 38.0)); // dragging the card's top edge sets its height let edge = Rect::from_center_size(pos2(rect.center().x, rect.top() + 1.0), vec2(rect.width() - 48.0, 10.0)); @@ -316,20 +363,21 @@ impl App { if self.terms.is_empty() { self.term_open = false } return; } - let body = Rect::from_min_max(pos2(inner.left() + 10.0, head.bottom()), pos2(inner.right() - 8.0, inner.bottom() - 6.0)); if !self.terms.is_empty() { - self.terminal_surface(ui, body, vis); + self.terminal_surface(ui, term_body(rect), term_body(target), vis); } } - fn terminal_surface(&mut self, ui: &mut Ui, body: Rect, vis: f32) { + /// `body` is where to draw this frame; `settled` is where the card is heading. The grid follows + /// `settled` only, so the morph never resizes the shell. + fn terminal_surface(&mut self, ui: &mut Ui, body: Rect, settled: Rect, vis: f32) { let t = self.t.clone(); let size = self.s.terminal_font; let font = fonts::mono(size); let cw = ui.fonts_mut(|f| f.glyph_width(&font, 'M')); - let lh = (size * 1.36).round(); - let cols = ((body.width() / cw) as usize).max(10); - let lines = ((body.height() / lh) as usize).max(3); + let lh = term_line(size); + let cols = ((settled.width() / cw) as usize).max(10); + let lines = ((settled.height() / lh) as usize).max(3); let id = self.term_focus_id(); let resp = ui.interact(body, id, Sense::click_and_drag()); if resp.hovered() { ui.ctx().set_cursor_icon(egui::CursorIcon::Text) } @@ -342,7 +390,8 @@ impl App { } let cur = self.term_cur; let session = &mut self.terms[cur]; - session.resize(cols, lines, (cw, lh)); + let now = ui.input(|i| i.time); + session.resize(cols, lines, (cw, lh), now); let cell_at = |p: Pos2, s: &Session| -> (Point, Side) { let x = ((p.x - body.left()) / cw).max(0.0); diff --git a/tests/shots.rs b/tests/shots.rs index 0e6681b..610d352 100644 --- a/tests/shots.rs +++ b/tests/shots.rs @@ -48,6 +48,7 @@ fn tour() { let mut h: H = Harness::builder().with_size(vec2(1400.0, 900.0)).wgpu().build_eframe(move |cc| App::new(cc, vec![file.clone()])); h.ctx.set_missing_glyph_policy(eframe::epaint::text::MissingGlyphPolicy::Tofu); settle(&mut h, 40); + assert!(h.state().panes[0].mini.ready(*h.state().docs.keys().next().unwrap()), "preview is up within a moment of opening"); assert_eq!(h.state().docs.len(), 1, "file opened"); assert_eq!(h.state().cur_doc().unwrap().language, "Rust"); shot(&mut h, &out, "01-editor"); @@ -61,20 +62,20 @@ fn tour() { settle(&mut h, 3); // grab the preview, drag, and catch it while popped out - let rail = pos2(1340.0, 300.0); + let rail = pos2(1330.0, 300.0); mv(&mut h, rail); press(&mut h, rail, true); settle(&mut h, 6); shot(&mut h, &out, "02-preview-popping"); for i in 0..24 { - mv(&mut h, pos2(1340.0, 300.0 + i as f32 * 12.0)); + mv(&mut h, pos2(1330.0, 300.0 + i as f32 * 12.0)); std::thread::sleep(std::time::Duration::from_millis(16)); } settle(&mut h, 24); assert!(h.state().panes[0].dragging_mini, "rail is being dragged"); assert!(h.state().panes[0].tabs[0].scroll.x > 100.0, "dragging scrolled the file"); shot(&mut h, &out, "03-preview-lens"); - press(&mut h, pos2(1340.0, 588.0), false); + press(&mut h, pos2(1330.0, 588.0), false); settle(&mut h, 40); assert!(!h.state().panes[0].dragging_mini); shot(&mut h, &out, "04-preview-released"); @@ -116,6 +117,17 @@ fn tour() { cmd(&mut h, Cmd::Settings); settle(&mut h, 20); shot(&mut h, &out, "11-settings"); + h.state_mut().settings_tab = 3; + h.state_mut().shell_open = true; + settle(&mut h, 30); + shot(&mut h, &out, "11b-shells"); + h.state_mut().settings_tab = 4; + settle(&mut h, 30); + shot(&mut h, &out, "11c-toolbar"); + h.state_mut().settings_tab = 5; + settle(&mut h, 30); + shot(&mut h, &out, "11d-discord"); + h.state_mut().settings_tab = 0; cmd(&mut h, Cmd::Settings); cmd(&mut h, Cmd::ToggleDark); @@ -198,3 +210,62 @@ fn keyboard_paths() { assert!(!h.state().term_open, "F4 hides it even with the terminal focused"); std::fs::remove_dir_all(dir).ok(); } + +/// Reopening the terminal must not make the shell print its prompt again. +#[test] +fn reopening_terminal_keeps_one_prompt() { + let dir = std::env::temp_dir().join(format!("damson-prompt-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::env::set_var("XDG_CONFIG_HOME", dir.join("config")); + let mut h: H = Harness::builder().with_size(vec2(1200.0, 800.0)).wgpu().build_eframe(|cc| App::new(cc, vec![])); + settle(&mut h, 6); + // the login shell here; bash doesn't show the problem + h.state_mut().s.shell = "/usr/bin/fish".into(); + let used = |h: &H| h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).count(); + key(&mut h, egui::Key::F4, Modifiers::NONE); + // let the shell finish starting, then toggle as a person would + for _ in 0..60 { settle(&mut h, 2) } + // real use has output above the prompt, and the morph squeezes the card to a few rows + for i in 0..3 { + h.state().terms[0].write(format!("echo line{i}\r")); + for _ in 0..12 { settle(&mut h, 2) } + } + let first = used(&h); + assert!(first >= 1, "shell printed a prompt"); + eprintln!("before: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).map(|r| r.trim_end().to_string()).collect::>()); + for _ in 0..3 { + key(&mut h, egui::Key::F4, Modifiers::NONE); + settle(&mut h, 40); + key(&mut h, egui::Key::F4, Modifiers::NONE); + settle(&mut h, 40); + } + for _ in 0..30 { settle(&mut h, 2) } + eprintln!("after: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).map(|r| r.trim_end().to_string()).collect::>()); + assert_eq!(h.state().terms[0].resizes, 0, "opening and closing never resizes the shell"); + assert_eq!(used(&h), first, "screen grew: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).collect::>()); + std::fs::remove_dir_all(dir).ok(); +} + +/// Toggling wrap with the cursor far away must not move the view, and toggling back returns. +#[test] +fn word_wrap_keeps_your_place() { + let dir = std::env::temp_dir().join(format!("damson-wrap-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::env::set_var("XDG_CONFIG_HOME", dir.join("config")); + let file = dir.join("t.txt"); + std::fs::write(&file, format!("{}\n", "a fairly long line of plain text that will wrap when the wrap is on and the width is narrow ".repeat(2)).repeat(400)).unwrap(); + let f = file.to_string_lossy().into_owned(); + let mut h: H = Harness::builder().with_size(vec2(1000.0, 700.0)).wgpu().build_eframe(move |cc| App::new(cc, vec![f.clone()])); + settle(&mut h, 10); + let lh = (h.state().s.font_size * 1.55).round(); + h.state_mut().panes[0].tabs[0].scroll.snap(lh * 200.0); + settle(&mut h, 6); + let line_at_top = |h: &H| { let t = &h.state().panes[0].tabs[0]; t.rows.row((t.scroll.x / lh) as usize).0 }; + assert_eq!(line_at_top(&h), 200); + cmd(&mut h, Cmd::ToggleWrap); + assert_eq!(line_at_top(&h), 200, "wrap on stays at the same line"); + cmd(&mut h, Cmd::ToggleWrap); + assert_eq!(line_at_top(&h), 200, "wrap off is back at the same line"); + assert!((h.state().panes[0].tabs[0].scroll.x - lh * 200.0).abs() < lh, "and the same position"); + std::fs::remove_dir_all(dir).ok(); +}