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:
astar76 2026-11-06 17:41:56 -06:00
commit c9905567a6
25 changed files with 977 additions and 174 deletions

71
Cargo.lock generated
View file

@ -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",

View file

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

View file

@ -19,6 +19,7 @@ at the centre of how it works.</p>
- **Icons that morph between states**, and only where a button really has two: sun and moon, run and stop,
`+` and `−` for staging, maximize and restore. One-shot actions like Save stay still.
- **Jelly tabs** whose indicator edges are separate springs, so it stretches as it moves.
- **Your own top bar.** Settings > Toolbar puts any of the app's commands beside the `+` button, up to 8.
- **One box for everything.** `Ctrl+Shift+P`: type for files, `>` commands, `:` line, `@` symbol, `!` run.
![The preview lens](docs/screenshots/03-preview-lens.png)
@ -42,7 +43,26 @@ hot exit (unsaved text survives a crash or quit), and language servers for compl
definition and diagnostics when they're installed (`clangd`, `rust-analyzer`, `pylsp`, `gopls`,
`typescript-language-server`, `bash-language-server`, `lua-language-server`).
Colours come from your Caelestia scheme or KDE accent, or a colour you pick, and follow live changes.
Colours follow your desktop (Caelestia's scheme or the KDE accent), or a colour you pick, and change live.
## Discord
Damson can show what you're editing on Discord: file, project, a language icon and time spent, or Idling
after five minutes. It speaks Discord's local socket directly. Settings > Discord has switches to hide the
file or project name.
Discord takes the app name from the application ID, so you need your own: make an application named
Damson at [discord.com/developers/applications](https://discord.com/developers/applications) and paste
its Application ID into Settings. To get the small Damson icon, upload a PNG of `packaging/damson.svg` under Rich Presence
named `damson`. Language pictures load by URL from the
[zed-discord-presence](https://github.com/xhyrom/zed-discord-presence) project; none of its code is used
here (it's GPL-3).
## Taskbar actions
Right-clicking Damson in a launcher that reads desktop actions offers New Window, New File, Open Folder
and New Terminal. Windows opened this way stay out of your saved session, so their unsaved changes are
not recovered.
![Light mode](docs/screenshots/12-other-mode.png)

View file

@ -1,6 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8e6bd8"/><stop offset="1" stop-color="#4b2a86"/></linearGradient></defs>
<path fill="url(#g)" d="M128 38c20 0 32 14 52 18 20 5 34 22 34 46 0 20 8 30 8 50 0 42-44 76-94 76s-94-34-94-76c0-20 8-30 8-50 0-24 14-41 34-46 20-4 32-18 52-18z"/>
<path fill="#b9efc4" d="M128 42c6-16 22-26 44-26-2 20-16 34-44 34z"/>
<path fill="none" stroke="#fff" stroke-opacity=".92" stroke-linecap="round" stroke-linejoin="round" stroke-width="15" d="M102 112l-30 28 30 28M154 112l30 28-30 28"/>
<path fill="#5b3f6e" d="M239.0 128.0 L238.4 132.8 L236.6 137.5 L233.8 141.9 L230.2 146.0 L226.1 149.7 L221.8 153.1 L217.7 156.3 L214.1 159.3 L211.0 162.4 L208.7 165.6 L207.2 169.2 L206.4 173.2 L206.1 177.7 L206.1 182.7 L206.2 188.0 L206.1 193.5 L205.5 199.0 L204.2 204.2 L202.2 208.9 L199.2 212.9 L195.5 216.0 L191.1 218.1 L186.1 219.2 L180.8 219.4 L175.3 218.8 L169.9 217.8 L164.7 216.5 L159.8 215.3 L155.3 214.5 L151.1 214.3 L147.3 214.9 L143.6 216.3 L139.9 218.5 L136.2 221.3 L132.2 224.6 L128.0 228.0 L123.5 231.2 L118.7 233.9 L113.8 235.8 L108.8 236.7 L104.0 236.4 L99.4 234.9 L95.1 232.2 L91.4 228.6 L88.1 224.3 L85.3 219.5 L82.9 214.6 L80.8 209.8 L78.6 205.5 L76.4 201.7 L73.8 198.7 L70.7 196.3 L67.0 194.5 L62.8 193.2 L58.0 192.1 L52.9 191.1 L47.5 189.8 L42.3 188.0 L37.4 185.7 L33.1 182.8 L29.8 179.1 L27.4 174.9 L26.2 170.2 L26.1 165.1 L27.0 159.8 L28.7 154.6 L30.8 149.5 L33.2 144.7 L35.5 140.2 L37.4 135.9 L38.6 131.9 L39.0 128.0 L38.6 124.1 L37.4 120.1 L35.5 115.8 L33.2 111.3 L30.8 106.5 L28.7 101.4 L27.0 96.2 L26.1 90.9 L26.2 85.8 L27.4 81.1 L29.8 76.9 L33.1 73.2 L37.4 70.3 L42.3 68.0 L47.5 66.2 L52.9 64.9 L58.0 63.9 L62.8 62.8 L67.0 61.5 L70.7 59.7 L73.8 57.3 L76.4 54.3 L78.6 50.5 L80.7 46.2 L82.9 41.4 L85.3 36.5 L88.1 31.7 L91.4 27.4 L95.1 23.8 L99.4 21.1 L104.0 19.6 L108.8 19.3 L113.8 20.2 L118.7 22.1 L123.5 24.8 L128.0 28.0 L132.2 31.4 L136.2 34.7 L139.9 37.5 L143.6 39.7 L147.3 41.1 L151.1 41.7 L155.3 41.5 L159.8 40.7 L164.7 39.5 L169.9 38.2 L175.3 37.2 L180.8 36.6 L186.1 36.8 L191.1 37.9 L195.5 40.0 L199.2 43.1 L202.2 47.1 L204.2 51.8 L205.5 57.0 L206.1 62.5 L206.2 68.0 L206.1 73.3 L206.1 78.3 L206.4 82.8 L207.2 86.8 L208.7 90.4 L211.0 93.6 L214.1 96.7 L217.7 99.7 L221.8 102.9 L226.1 106.3 L230.2 110.0 L233.8 114.1 L236.6 118.5 L238.4 123.2 Z"/>
<path fill="none" stroke="#f3dcf8" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" d="M104 96l-34 32 34 32M152 96l34 32-34 32"/>
</svg>

Before

Width:  |  Height:  |  Size: 638 B

After

Width:  |  Height:  |  Size: 2 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

After

Width:  |  Height:  |  Size: 280 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 424 KiB

After

Width:  |  Height:  |  Size: 536 KiB

Before After
Before After

View file

@ -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]"

View file

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

View file

@ -1,6 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8e6bd8"/><stop offset="1" stop-color="#4b2a86"/></linearGradient></defs>
<path fill="url(#g)" d="M128 38c20 0 32 14 52 18 20 5 34 22 34 46 0 20 8 30 8 50 0 42-44 76-94 76s-94-34-94-76c0-20 8-30 8-50 0-24 14-41 34-46 20-4 32-18 52-18z"/>
<path fill="#b9efc4" d="M128 42c6-16 22-26 44-26-2 20-16 34-44 34z"/>
<path fill="none" stroke="#fff" stroke-opacity=".92" stroke-linecap="round" stroke-linejoin="round" stroke-width="15" d="M102 112l-30 28 30 28M154 112l30 28-30 28"/>
<path fill="#5b3f6e" d="M239.0 128.0 L238.4 132.8 L236.6 137.5 L233.8 141.9 L230.2 146.0 L226.1 149.7 L221.8 153.1 L217.7 156.3 L214.1 159.3 L211.0 162.4 L208.7 165.6 L207.2 169.2 L206.4 173.2 L206.1 177.7 L206.1 182.7 L206.2 188.0 L206.1 193.5 L205.5 199.0 L204.2 204.2 L202.2 208.9 L199.2 212.9 L195.5 216.0 L191.1 218.1 L186.1 219.2 L180.8 219.4 L175.3 218.8 L169.9 217.8 L164.7 216.5 L159.8 215.3 L155.3 214.5 L151.1 214.3 L147.3 214.9 L143.6 216.3 L139.9 218.5 L136.2 221.3 L132.2 224.6 L128.0 228.0 L123.5 231.2 L118.7 233.9 L113.8 235.8 L108.8 236.7 L104.0 236.4 L99.4 234.9 L95.1 232.2 L91.4 228.6 L88.1 224.3 L85.3 219.5 L82.9 214.6 L80.8 209.8 L78.6 205.5 L76.4 201.7 L73.8 198.7 L70.7 196.3 L67.0 194.5 L62.8 193.2 L58.0 192.1 L52.9 191.1 L47.5 189.8 L42.3 188.0 L37.4 185.7 L33.1 182.8 L29.8 179.1 L27.4 174.9 L26.2 170.2 L26.1 165.1 L27.0 159.8 L28.7 154.6 L30.8 149.5 L33.2 144.7 L35.5 140.2 L37.4 135.9 L38.6 131.9 L39.0 128.0 L38.6 124.1 L37.4 120.1 L35.5 115.8 L33.2 111.3 L30.8 106.5 L28.7 101.4 L27.0 96.2 L26.1 90.9 L26.2 85.8 L27.4 81.1 L29.8 76.9 L33.1 73.2 L37.4 70.3 L42.3 68.0 L47.5 66.2 L52.9 64.9 L58.0 63.9 L62.8 62.8 L67.0 61.5 L70.7 59.7 L73.8 57.3 L76.4 54.3 L78.6 50.5 L80.7 46.2 L82.9 41.4 L85.3 36.5 L88.1 31.7 L91.4 27.4 L95.1 23.8 L99.4 21.1 L104.0 19.6 L108.8 19.3 L113.8 20.2 L118.7 22.1 L123.5 24.8 L128.0 28.0 L132.2 31.4 L136.2 34.7 L139.9 37.5 L143.6 39.7 L147.3 41.1 L151.1 41.7 L155.3 41.5 L159.8 40.7 L164.7 39.5 L169.9 38.2 L175.3 37.2 L180.8 36.6 L186.1 36.8 L191.1 37.9 L195.5 40.0 L199.2 43.1 L202.2 47.1 L204.2 51.8 L205.5 57.0 L206.1 62.5 L206.2 68.0 L206.1 73.3 L206.1 78.3 L206.4 82.8 L207.2 86.8 L208.7 90.4 L211.0 93.6 L214.1 96.7 L217.7 99.7 L221.8 102.9 L226.1 106.3 L230.2 110.0 L233.8 114.1 L236.6 118.5 L238.4 123.2 Z"/>
<path fill="none" stroke="#f3dcf8" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" d="M104 96l-34 32 34 32M152 96l34 32-34 32"/>
</svg>

Before

Width:  |  Height:  |  Size: 638 B

After

Width:  |  Height:  |  Size: 2 KiB

Before After
Before After

View file

@ -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>) {

View file

@ -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
View 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();
}
}

View file

@ -1,5 +1,6 @@
pub mod app;
pub mod config;
pub mod discord;
pub mod git;
pub mod icondata;
pub mod lsp;

View file

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

View file

@ -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)
}

View file

@ -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);

View file

@ -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());
}

View file

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

View file

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

View file

@ -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);

Some files were not shown because too many files have changed in this diff Show more