Real text in the preview, system title bar, toolbar, Discord presence
The preview draws real glyphs on a worker thread, within the GPU's texture limit. The window uses the system title bar; the top right holds up to 8 icons chosen in Settings, then the menu logo. Adds a shell picker, taskbar actions and Discord presence, and drops the Caelestia and KDE colour choices in favour of Desktop. Word wrap no longer moves the view. The terminal starts at its final size and the morph never resizes the shell. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
65defa1ae3
commit
c9905567a6
15 changed files with 977 additions and 174 deletions
134
src/app.rs
134
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<String>,
|
||||
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<Cmd>,
|
||||
window_title: String,
|
||||
presence: Sender<discord::Update>,
|
||||
presence_sent: Option<(String, bool, bool, bool)>,
|
||||
last_time: Option<Instant>,
|
||||
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<String>) -> App {
|
||||
pub fn build(ctx: &egui::Context, args: Vec<String>) -> App {
|
||||
let (flags, files): (Vec<String>, Vec<String>) = 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>) {
|
||||
|
|
|
|||
|
|
@ -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<String>,
|
||||
pub discord: bool,
|
||||
pub discord_id: String,
|
||||
pub discord_file: bool,
|
||||
pub discord_project: bool,
|
||||
pub recent: Vec<String>,
|
||||
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) {
|
||||
|
|
|
|||
273
src/discord.rs
Normal file
273
src/discord.rs
Normal file
|
|
@ -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<String>,
|
||||
pub state: Option<String>,
|
||||
pub large_image: Option<String>,
|
||||
pub large_text: Option<String>,
|
||||
pub small_image: Option<String>,
|
||||
pub small_text: Option<String>,
|
||||
}
|
||||
|
||||
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<PathBuf> {
|
||||
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<UnixStream> {
|
||||
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<Activity>, 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<Activity>),
|
||||
}
|
||||
|
||||
/// Starts the worker. It connects when Discord appears and reconnects if Discord restarts.
|
||||
pub fn spawn() -> Sender<Update> {
|
||||
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<Activity>, Option<Option<Activity>>) = (String::new(), None, None);
|
||||
let mut conn: Option<UnixStream> = 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
pub mod app;
|
||||
pub mod config;
|
||||
pub mod discord;
|
||||
pub mod git;
|
||||
pub mod icondata;
|
||||
pub mod lsp;
|
||||
|
|
|
|||
|
|
@ -19,15 +19,14 @@ fn app_icon() -> egui::IconData {
|
|||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let files: Vec<String> = std::env::args().skip(1).filter(|a| !a.starts_with("--")).collect();
|
||||
let files: Vec<String> = 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)))))
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Arc<Vec<(u32, u32)>>>,
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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<Vec<u8>> = 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());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<Pos2> = (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]
|
||||
|
|
|
|||
|
|
@ -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<TextureHandle>,
|
||||
key: (u64, u64, u32),
|
||||
/// What's in `tex`.
|
||||
shown: Option<Key>,
|
||||
/// What the worker is drawing now.
|
||||
pending: Option<Key>,
|
||||
rx: Option<Receiver<Built>>,
|
||||
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<crate::text::doc::LineHl>,
|
||||
colors: Vec<Color32>,
|
||||
normal: Color32,
|
||||
first: usize,
|
||||
tab: usize,
|
||||
}
|
||||
|
||||
struct Glyph {
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: usize,
|
||||
h: usize,
|
||||
px: Vec<u8>,
|
||||
}
|
||||
|
||||
fn font() -> Option<&'static fontdue::Font> {
|
||||
static F: OnceLock<Option<fontdue::Font>> = 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<Mutex<HashMap<char, Arc<Glyph>>>> = 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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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<String> {
|
||||
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<String> = 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<String> = 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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<PathBuf>, shell: &str) -> std::io::Result<Session> {
|
||||
let size = Size { cols: 100, lines: 24 };
|
||||
pub fn spawn(ctx: &egui::Context, id: u64, cwd: Option<PathBuf>, shell: &str, (cols, lines): (usize, usize)) -> std::io::Result<Session> {
|
||||
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<String> {
|
||||
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<Vec<u8>>) {
|
||||
|
|
@ -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<Vec<u8>> {
|
|||
})
|
||||
}
|
||||
|
||||
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<PathBuf>) {
|
||||
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);
|
||||
|
|
|
|||
Loading…
Reference in a new issue