Proper install script, and a clean Discord disconnect

install.sh now works like a usual source install: PREFIX and DESTDIR,
/usr/local by default with sudo for the copy only, --user, --uninstall
and --purge. It builds in a temporary folder that is removed however the
script ends, so target/ is left alone. Installs PNG icons up to 512,
AppStream data, the licence and the README, and removes an older copy in
~/.local that would hide the new one on PATH.

Quitting or switching presence off now clears the activity and closes
the connection, with a short limit so Discord can't delay quitting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-06 18:50:17 -06:00
commit 9cad187d56
7 changed files with 412 additions and 39 deletions

View file

@ -58,7 +58,7 @@ Colours follow your desktop (Caelestia's scheme or the KDE accent), or a colour
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.
file or project name. Quitting, or switching it off, clears the status and disconnects straight away.
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
@ -80,13 +80,32 @@ not recovered.
Vi mode, spell checking, snippets, reopening a file with a chosen encoding, and Kate's C++ plugins, which
can't load into a Rust app. Long lines are not virtualised. It runs one window per launch. Linux only for now.
## Build
## Install from source
You need Rust and a C compiler to build, and the `syntax-highlighting` package for code colours (no other
KDE parts). From a clone:
```bash
./install.sh # builds and installs to ~/.local
./install.sh
```
Needs Rust and the `syntax-highlighting` package. No other KDE parts are needed at runtime.
That builds in a temporary folder, installs to `/usr/local` (asking for sudo only to copy the files), and
deletes the build afterwards. A rebuild starts from scratch, so it takes a few minutes each time.
| Option | What it does |
|---|---|
| `--user` | Install to `~/.local`, with no sudo |
| `--prefix DIR` | Install under `DIR` |
| `--keep-build` | Build in `target/` and keep it, for quicker rebuilds |
| `--uninstall` | Remove it (add `--user` or `--prefix` if that's where it went) |
| `--uninstall --purge` | Also delete settings and recovery copies |
Installed files: the program in `bin/`, the launcher in `share/applications/`, icons in
`share/icons/hicolor/` (SVG, and PNGs from 16 to 512), AppStream data in `share/metainfo/`, and the licence and
README under `share/`. An older copy in `~/.local` is removed by a system install, because it comes first
on `PATH` and would hide the new one.
For packaging, `DESTDIR` is honoured: `DESTDIR=/path/to/pkg ./install.sh --prefix /usr`.
## Tests

View file

@ -1,10 +1,209 @@
#!/usr/bin/env bash
# Builds Damson and installs it for this user, in ~/.local.
# Builds Damson from source and installs it, like any Linux app built by hand.
# The build happens in a temporary folder that is deleted afterwards. Run with --help for options.
set -euo pipefail
cd "$(dirname "$0")"
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]"
usage() {
cat <<'EOF'
Usage: ./install.sh [options]
(no options) Build, then install system-wide to /usr/local (asks for sudo to copy)
--user Install for this user only, to ~/.local (no sudo)
--prefix DIR Install under DIR
--keep-build Build in target/ and keep it, which is faster when rebuilding
--uninstall Remove what this script installed (combine with --user or --prefix)
--purge With --uninstall, also delete settings and recovery copies
-h, --help Show this
Packagers: DESTDIR=/path/to/pkg ./install.sh --prefix /usr
EOF
}
die() { echo "error: $*" >&2; exit 1; }
say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
cd "$(dirname "$(readlink -f "$0")")"
[ -f Cargo.toml ] && [ -f packaging/damson.desktop ] || die "run this from a Damson source folder"
prefix=/usr/local
user_install=0 uninstall=0 purge=0 keep_build=0
while [ $# -gt 0 ]; do
case "$1" in
--user) user_install=1 ;;
--prefix) [ $# -ge 2 ] || die "--prefix needs a folder"; prefix=$2; shift ;;
--prefix=*) prefix=${1#--prefix=} ;;
--keep-build) keep_build=1 ;;
--uninstall) uninstall=1 ;;
--purge) purge=1 ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
shift
done
[ "$purge" = 0 ] || [ "$uninstall" = 1 ] || die "--purge only goes with --uninstall"
# Under sudo, the person is SUDO_USER: their toolchain builds it, and root only copies.
root=0 real_user=$(id -un) real_home=$HOME
if [ "$(id -u)" = 0 ]; then
root=1
if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ]; then
real_user=$SUDO_USER
real_home=$(getent passwd "$SUDO_USER" | cut -d: -f6)
fi
fi
if [ "$user_install" = 1 ]; then
[ "$root" = 0 ] || die "--user installs for one person, so run it without sudo"
prefix=$HOME/.local
fi
case "$prefix" in /*) ;; *) die "--prefix must be an absolute path" ;; esac
prefix=${prefix%/}
destdir=${DESTDIR:-}
destdir=${destdir%/}
target=$destdir$prefix
bindir=$prefix/bin
sizes="16 24 32 48 64 128 256 512"
# Every file this script installs, relative to the prefix.
installed_files() {
echo bin/damson
echo share/applications/damson.desktop
echo share/metainfo/damson.metainfo.xml
echo share/icons/hicolor/scalable/apps/damson.svg
for s in $sizes; do echo "share/icons/hicolor/${s}x$s/apps/damson.png"; done
echo share/licenses/damson/LICENSE
echo share/doc/damson/README.md
}
# sudo is used only for the copy, and only when the destination needs it.
writable_dir() {
local d=$1
while [ ! -e "$d" ]; do d=$(dirname "$d"); done
[ -w "$d" ]
}
as_owner=()
if [ "$root" = 0 ] && ! writable_dir "$target"; then
command -v sudo >/dev/null || die "$target needs root and sudo isn't installed. Try --user."
as_owner=(sudo)
fi
refresh_caches() {
[ -z "$destdir" ] || return 0
local share=$prefix/share
command -v update-desktop-database >/dev/null && "${as_owner[@]}" update-desktop-database -q "$share/applications" || true
if command -v gtk-update-icon-cache >/dev/null && [ -f "$share/icons/hicolor/index.theme" ]; then
"${as_owner[@]}" gtk-update-icon-cache -q -t -f "$share/icons/hicolor" || true
fi
}
remove_install() { # prefix on disk, sudo-or-empty
local base=$1; shift
local f
while read -r f; do "$@" rm -f "$base/$f"; done < <(installed_files)
"$@" rmdir --ignore-fail-on-non-empty "$base/share/licenses/damson" "$base/share/doc/damson" 2>/dev/null || true
}
if [ "$uninstall" = 1 ]; then
if [ ! -e "$target/bin/damson" ]; then
[ "$prefix" = "$real_home/.local" ] || [ ! -e "$real_home/.local/bin/damson" ] || say "There's a copy in ~/.local too: remove it with --user --uninstall"
die "Damson isn't installed in $prefix"
fi
say "Removing Damson from $prefix"
remove_install "$target" "${as_owner[@]}"
refresh_caches
if [ "$purge" = 1 ]; then
say "Deleting settings and recovery copies"
rm -rf "${XDG_CONFIG_HOME:-$real_home/.config}/damson"
else
echo "Settings are kept in ${XDG_CONFIG_HOME:-$real_home/.config}/damson (--purge deletes them)."
fi
say "Uninstalled"
exit 0
fi
# ---------------------------------------------------------------- build
as_builder() {
if [ "$root" = 1 ] && [ "$real_user" != root ]; then
sudo -u "$real_user" -H env PATH="$real_home/.cargo/bin:$PATH" "$@"
else
"$@"
fi
}
as_builder sh -c 'command -v cargo' >/dev/null || die "cargo not found. Install Rust (rustup or your distro's rust package) first."
as_builder sh -c 'command -v cc' >/dev/null || die "no C compiler found. Install gcc or clang first."
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
# anything left behind is removed however the script ends
work=
cleanup() { [ -z "$work" ] || rm -rf "$work"; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
cache=${XDG_CACHE_HOME:-$real_home/.cache}
as_builder mkdir -p "$cache"
work=$(as_builder mktemp -d "$cache/damson-build.XXXXXX")
if [ "$keep_build" = 1 ]; then
say "Building Damson $version (release) in target/"
as_builder cargo build --release --locked
binary=target/release/damson
else
say "Building Damson $version (release)"
as_builder env CARGO_TARGET_DIR="$work/target" cargo build --release --locked
binary=$work/target/release/damson
fi
[ -x "$binary" ] || die "the build didn't produce a binary"
# ---------------------------------------------------------------- stage
stage=$work/stage
as_builder mkdir -p "$stage"
for s in $sizes; do as_builder "$binary" --export-icon "$s" "$stage/$s.png"; done
if [ "$prefix" = /usr ] || [ "$prefix" = /usr/local ]; then
as_builder cp packaging/damson.desktop "$stage/damson.desktop"
else
# outside the standard folders, the launcher can't count on PATH finding it
as_builder sh -c "sed -e 's|^Exec=damson|Exec=$bindir/damson|' -e 's|^TryExec=damson|TryExec=$bindir/damson|' packaging/damson.desktop > '$stage/damson.desktop'"
fi
# ---------------------------------------------------------------- install
say "Installing to $target"
[ -z "${as_owner[*]:-}" ] || echo "Copying to $target needs root:"
put() { "${as_owner[@]}" install -Dm"$1" "$2" "$target/$3"; }
put 755 "$binary" bin/damson
put 644 "$stage/damson.desktop" share/applications/damson.desktop
put 644 packaging/damson.metainfo.xml share/metainfo/damson.metainfo.xml
put 644 packaging/damson.svg share/icons/hicolor/scalable/apps/damson.svg
for s in $sizes; do put 644 "$stage/$s.png" "share/icons/hicolor/${s}x$s/apps/damson.png"; done
put 644 LICENSE share/licenses/damson/LICENSE
put 644 README.md share/doc/damson/README.md
refresh_caches
# An older copy in ~/.local comes first on PATH and would hide this one.
old=$real_home/.local
if [ -z "$destdir" ] && [ "$prefix" != "$old" ] && [ -e "$old/bin/damson" ]; then
say "Removing the older copy in $old, which would hide this one"
remove_install "$old"
command -v update-desktop-database >/dev/null && update-desktop-database -q "$old/share/applications" || true
[ "$root" = 0 ] || chown -R "$real_user:" "$old/share/applications" 2>/dev/null || true
fi
say "Cleaning up"
cleanup
work=
# ---------------------------------------------------------------- notes
if [ -z "$destdir" ]; then
case ":$PATH:" in
*":$bindir:"*) ;;
*) [ "$root" = 1 ] || echo "Note: $bindir isn't on your PATH, so add it to run damson by name." ;;
esac
fi
if ! ls /usr/share/org.kde.syntax-highlighting/syntax*/rust.xml >/dev/null 2>&1; then
echo "Note: code colours need Kate's syntax definitions: install the syntax-highlighting package"
echo " (Arch: syntax-highlighting, Debian/Ubuntu: libkf6syntaxhighlighting6-data, Fedora: kf6-syntax-highlighting)."
fi
say "Installed Damson $version. Run: damson [file[:line]] [folder]"

View file

@ -4,9 +4,11 @@ Name=Damson
GenericName=Text Editor
Comment=A Material You code editor
Exec=damson %F
TryExec=damson
Icon=damson
Terminal=false
Categories=Development;TextEditor;Utility;
Categories=Development;TextEditor;
Keywords=code;editor;programming;kate;text;
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;

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>damson</id>
<name>Damson</name>
<summary>A Material You code editor</summary>
<metadata_license>MIT</metadata_license>
<project_license>MIT</project_license>
<description>
<p>Damson is a code editor with Material You colours and spring-driven motion. It reads Kate's syntax definitions, and has a pop-out scrolling preview, a built-in terminal, git tools and language server support.</p>
</description>
<launchable type="desktop-id">damson.desktop</launchable>
<categories>
<category>Development</category>
<category>TextEditor</category>
</categories>
<provides>
<binary>damson</binary>
</provides>
</component>

View file

@ -1582,6 +1582,7 @@ impl eframe::App for App {
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
self.save_session();
self.s.save();
discord::shut_down(&self.presence);
}
}

View file

@ -171,6 +171,30 @@ pub enum Update {
/// The application id; empty turns presence off.
Id(String),
Show(Option<Activity>),
/// Clear the status and disconnect, then say so on the channel.
Shutdown(Sender<()>),
}
/// Takes the status down and leaves properly, so Discord doesn't have to notice a dropped socket.
fn hang_up(conn: &mut Option<UnixStream>, nonce: &mut u64) {
if let Some(mut s) = conn.take() {
let _ = s.set_read_timeout(Some(Duration::from_millis(500)));
*nonce += 1;
let _ = send(&mut s, &None, 0, *nonce);
let _ = write_frame(&mut s, 2, &json!({}));
let _ = s.shutdown(std::net::Shutdown::Both);
}
}
/// How long quitting will wait for Discord to confirm.
const SHUTDOWN_WAIT: Duration = Duration::from_millis(900);
/// Clears the status before the app exits, waiting only briefly if Discord is slow.
pub fn shut_down(tx: &Sender<Update>) {
let (done, wait) = channel();
if tx.send(Update::Shutdown(done)).is_ok() {
let _ = wait.recv_timeout(SHUTDOWN_WAIT);
}
}
/// Starts the worker. It connects when Discord appears and reconnects if Discord restarts.
@ -185,17 +209,21 @@ pub fn spawn() -> Sender<Update> {
match rx.recv_timeout(Duration::from_secs(5)) {
Ok(Update::Id(new)) => {
if new != id {
hang_up(&mut conn, &mut nonce);
id = new;
conn = None;
sent = None;
}
}
Ok(Update::Show(a)) => wanted = a,
Ok(Update::Shutdown(done)) => {
hang_up(&mut conn, &mut nonce);
let _ = done.send(());
return;
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return,
}
if id.is_empty() {
conn = None;
continue;
}
if conn.is_none() {
@ -239,35 +267,125 @@ mod tests {
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.
/// The socket path is read from the environment, so these take turns.
static SOCKET: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// A stand-in for Discord, so nothing here reaches the real app. Records frames until the
/// client goes away, and answers like Discord does.
fn fake_discord(path: &std::path::Path) -> std::thread::JoinHandle<Vec<(u32, Value)>> {
let l = UnixListener::bind(path).unwrap();
std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
let mut got = vec![];
while let Ok((op, v)) = read_frame(&mut s) {
got.push((op, v));
if op != 2 {
write_frame(&mut s, 1, &json!({"evt": "OK"})).unwrap();
}
}
got
})
}
fn socket(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("damson-ipc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("DAMSON_DISCORD_SOCKET", dir.join("ipc"));
dir.join("ipc")
}
fn editing() -> Update {
Update::Show(Some(Activity::editing(Some("main.rs"), Some("Damson"), "main.rs", "Rust")))
}
fn shown(frames: &[(u32, Value)], i: usize) -> Value {
assert_eq!(frames[i].1["cmd"], "SET_ACTIVITY");
frames[i].1["args"]["activity"].clone()
}
#[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 _turn = SOCKET.lock().unwrap();
let server = fake_discord(&socket("hello"));
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"];
tx.send(editing()).unwrap();
shut_down(&tx);
let f = server.join().unwrap();
assert_eq!((f[0].0, f[1].0), (0, 1));
assert_eq!(f[0].1["client_id"], "123");
let a = shown(&f, 1);
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();
}
#[test]
fn quitting_clears_the_status_and_says_goodbye() {
let _turn = SOCKET.lock().unwrap();
let server = fake_discord(&socket("quit"));
let tx = spawn();
tx.send(Update::Id("123".into())).unwrap();
tx.send(editing()).unwrap();
// the worker has to have connected before there's anything to unload
std::thread::sleep(Duration::from_millis(150));
shut_down(&tx);
let f = server.join().unwrap();
let n = f.len();
assert!(shown(&f, n - 2).is_null(), "activity cleared last: {f:?}");
assert_eq!(f[n - 1].0, 2, "then a proper close");
assert!(tx.send(Update::Id("x".into())).is_err(), "and the worker has ended");
}
#[test]
fn switching_it_off_clears_the_status_without_quitting() {
let _turn = SOCKET.lock().unwrap();
let server = fake_discord(&socket("off"));
let tx = spawn();
tx.send(Update::Id("123".into())).unwrap();
tx.send(editing()).unwrap();
std::thread::sleep(Duration::from_millis(150));
tx.send(Update::Id(String::new())).unwrap();
let f = server.join().unwrap();
assert!(shown(&f, f.len() - 2).is_null());
assert_eq!(f[f.len() - 1].0, 2);
assert!(tx.send(Update::Id(String::new())).is_ok(), "still running, ready to turn back on");
}
#[test]
fn quitting_never_hangs_on_a_silent_discord() {
let _turn = SOCKET.lock().unwrap();
let path = socket("silent");
let l = UnixListener::bind(&path).unwrap();
// answers the handshake and the first activity, then goes quiet with the socket open
let server = std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
read_frame(&mut s).unwrap();
write_frame(&mut s, 1, &json!({"evt": "READY"})).unwrap();
read_frame(&mut s).unwrap();
write_frame(&mut s, 1, &json!({})).unwrap();
std::thread::sleep(Duration::from_secs(3));
});
let tx = spawn();
tx.send(Update::Id("123".into())).unwrap();
tx.send(editing()).unwrap();
std::thread::sleep(Duration::from_millis(150));
let t = std::time::Instant::now();
shut_down(&tx);
assert!(t.elapsed() < Duration::from_millis(1200), "took {:?}", t.elapsed());
server.join().unwrap();
}
#[test]
fn quitting_with_no_discord_is_instant() {
let _turn = SOCKET.lock().unwrap();
std::env::set_var("DAMSON_DISCORD_SOCKET", "/nonexistent/ipc");
let tx = spawn();
tx.send(Update::Id("123".into())).unwrap();
let t = std::time::Instant::now();
shut_down(&tx);
assert!(t.elapsed() < Duration::from_millis(200));
}
}

View file

@ -1,14 +1,18 @@
use damson::{app::App, config};
use eframe::egui;
fn app_icon() -> egui::IconData {
let size = 256u32;
fn render_icon(size: u32) -> resvg::tiny_skia::Pixmap {
let mut pm = resvg::tiny_skia::Pixmap::new(size, size).unwrap();
if let Ok(tree) = resvg::usvg::Tree::from_str(include_str!("../assets/damson.svg"), &resvg::usvg::Options::default()) {
let s = size as f32 / tree.size().width();
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(s, s), &mut pm.as_mut());
}
let mut rgba = pm.take();
pm
}
fn app_icon() -> egui::IconData {
let size = 256u32;
let mut rgba = render_icon(size).take();
for px in rgba.chunks_exact_mut(4) {
let a = px[3] as u32;
if a > 0 && a < 255 {
@ -20,6 +24,17 @@ fn app_icon() -> egui::IconData {
fn main() -> eframe::Result {
let files: Vec<String> = std::env::args().skip(1).collect();
// used by install.sh for the icon theme's PNG sizes
if let [flag, size, path] = files.as_slice() {
if flag == "--export-icon" {
let size = size.parse().unwrap_or_else(|_| { eprintln!("bad icon size: {size}"); std::process::exit(2) });
if let Err(e) = render_icon(size).save_png(path) {
eprintln!("couldn't write {path}: {e}");
std::process::exit(1);
}
return Ok(());
}
}
let [w, h] = config::Settings::load().win;
let viewport = egui::ViewportBuilder::default()
.with_title(config::APP_NAME)