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.

@@ -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.

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