Add app baseline and keep UI state consistent

This commit is contained in:
2026-09-10 20:34:48 +02:00
parent c5e512223f
commit 7b5f2c126a
30 changed files with 4992 additions and 1 deletions

1699
.agents/BIBLE.md Normal file

File diff suppressed because it is too large Load Diff

45
.agents/SHIP_CHECKLIST.md Normal file
View File

@@ -0,0 +1,45 @@
# Clipb(h)oard shipping checklist
This checklist tracks the MVP completion criteria from `BIBLE.md`. Items are
checked only after implementation and an evidence-producing verification.
## Foundation
- [x] Rust core, SQLite migrations, TOML defaults, fuzzy search
- [x] Deduplication, pinning, limits, deletion, and clear-history semantics
- [x] Dockerized GTK/X11 build environment
- [x] `.deb` with runtime dependencies, desktop file, autostart file, and icon
## Desktop behavior
- [x] Background-only startup with popup show/toggle command (live Docker/X11 smoke test)
- [x] Single-instance lock and second-invocation show/toggle behavior (live Docker smoke test)
- [x] `--show` launcher returns while the owned background process continues
- [x] X11 global shortcut registration and clear conflict reporting (live Docker/X11 test)
- [x] Visible copy, paste, pin, delete, clear-history, and pause controls
- [x] Cinnamon-compatible StatusNotifier/D-Bus tray icon with popup activation
- [ ] X11 event-driven clipboard monitoring
- [ ] Deterministic self-generated clipboard suppression
- [ ] Popup centered on the active monitor
- [ ] Keyboard navigation, copy, delete, pin/unpin, and clear-history commands
- [ ] Pause Recording
- [ ] X11 paste into the previously focused application
- [ ] Paste failure leaves content on the clipboard and reports the error
## Reliability and privacy
- [ ] File-backed XDG logging without clipboard contents in normal logs
- [ ] Startup/shutdown cleanup and recoverable optional-feature failures
- [ ] Configurable shortcut and limits applied by the running application
- [ ] Autostart setting has real effect
- [ ] Diagnostics report actual backend and registration state
## Release acceptance
- [x] Docker tests and GUI release build pass
- [x] Package contents and dependency metadata validated
- [ ] Manual Cinnamon/X11 acceptance run completed
- [x] User-facing install/test instructions updated
Update this file as each item earns evidence; do not mark an item complete from
code inspection alone when it requires a live desktop check.

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
.git
target
Dockerfile
*.deb

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target/

1610
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

36
Cargo.toml Normal file
View File

@@ -0,0 +1,36 @@
[package]
name = "clipbhoard"
version = "0.1.0"
edition = "2021"
description = "A tiny, keyboard-first clipboard history utility"
license = "MIT"
default-run = "clipbhoard"
[features]
default = []
x11 = ["dep:x11rb", "dep:x11-clipboard"]
gui = ["x11", "dep:gtk4", "dep:glib", "dep:ksni"]
[dependencies]
anyhow = "1.0"
dirs = "6.0"
rusqlite = { version = "0.32", features = ["bundled"] }
serde = { version = "1.0", features = ["derive"] }
sha2 = "0.10"
thiserror = "2.0"
toml = "0.8"
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
fs2 = "0.4"
gtk4 = { version = "0.9", optional = true }
glib = { version = "0.20", optional = true }
ksni = { version = "0.2.2", optional = true }
x11rb = { version = "0.13", features = ["allow-unsafe-code", "xtest"], optional = true }
x11-clipboard = { version = "0.9", optional = true }
[profile.release]
lto = "thin"
codegen-units = 1
strip = true

22
Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM rust:1.85-bookworm
RUN apt-get update \
&& apt-get install --no-install-recommends -y \
dpkg-dev \
libgtk-4-dev \
libdbus-1-dev \
libx11-dev \
libxfixes-dev \
libxtst-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /workspace
COPY . .
RUN cargo test --locked \
&& cargo build --release --locked --features gui
RUN packaging/build-deb.sh
CMD ["sh", "-c", "mkdir -p /out && cp target/clipbhoard_*.deb /out/"]

45
README.md Normal file
View File

@@ -0,0 +1,45 @@
# Clipb(h)oard
Clipb(h)oard is a small, local-only, keyboard-first clipboard history utility for Linux/X11.
The core is implemented in Rust with SQLite persistence and TOML configuration. The default build intentionally keeps the GTK/X11 desktop integration behind the `gui` feature so the data model and persistence tests can run on machines without GTK development libraries.
## Development
```bash
cargo test
cargo run -- --diagnostics
```
To build the desktop application on Debian/Ubuntu, install the native dependencies first:
```bash
sudo apt install libgtk-4-dev libx11-dev libxfixes-dev pkg-config
cargo run --features gui
```
The repository also includes an isolated Docker build that installs all build
headers, runs tests, compiles the GTK/X11 backend, and creates an installable
`.deb`:
```bash
docker build -t clipbhoard-builder .
docker run --rm -v "$PWD/target:/out" clipbhoard-builder
```
The resulting package declares its runtime libraries, so Debian/Ubuntu users
can install it with `sudo apt install ./target/clipbhoard_0.1.0_amd64.deb` and
the package manager will resolve GTK/X11 runtime dependencies automatically.
Once installed, Clipb(h)oard runs as a background process. `Super+V` opens the
popup, and `clipbhoard --show` requests it without keeping the invoking shell
blocked. On Cinnamon, a StatusNotifier tray icon provides another way to open
the popup when the desktop panel exposes tray icons.
Runtime files follow XDG conventions:
- database: `~/.local/share/clipbhoard/clipbhoard.db`
- configuration: `~/.config/clipbhoard/config.toml`
- log state: `~/.local/state/clipbhoard/`
The full product contract is in [.agents/BIBLE.md](.agents/BIBLE.md).

View File

@@ -0,0 +1,7 @@
[Desktop Entry]
Type=Application
Name=Clipb(h)oard
Exec=clipbhoard --autostart
OnlyShowIn=Cinnamon;GNOME;KDE;XFCE;
X-GNOME-Autostart-enabled=true
NoDisplay=true

View File

@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=Clipb(h)oard
Comment=Fast, keyboard-first clipboard history
Exec=clipbhoard
Icon=io.clipbhoard.Clipbhoard
Terminal=false
Categories=Utility;
Keywords=clipboard;history;copy;paste;
StartupNotify=false

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<rect x="18" y="18" width="92" height="92" rx="18" fill="#4f6bed"/>
<path d="M42 42h44v12H42zm0 20h44v12H42zm0 20h28v12H42z" fill="#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 213 B

View File

@@ -0,0 +1,12 @@
CREATE TABLE entries (
id INTEGER PRIMARY KEY,
content TEXT NOT NULL,
content_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
last_used_at INTEGER NOT NULL,
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1))
);
CREATE INDEX idx_entries_hash ON entries(content_hash);
CREATE INDEX idx_entries_last_used ON entries(last_used_at DESC);
CREATE INDEX idx_entries_pinned ON entries(pinned);

19
packaging/build-deb.sh Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
version="${CLIPBHOARD_VERSION:-0.1.0}"
package_root="${PWD}/target/clipbhoard-deb"
rm -rf "$package_root"
mkdir -p "$package_root/DEBIAN" \
"$package_root/usr/bin" \
"$package_root/usr/share/applications" \
"$package_root/usr/share/icons/hicolor/scalable/apps" \
"$package_root/etc/xdg/autostart"
install -m 0755 target/release/clipbhoard "$package_root/usr/bin/clipbhoard"
install -m 0644 data/io.clipbhoard.Clipbhoard.desktop "$package_root/usr/share/applications/io.clipbhoard.Clipbhoard.desktop"
install -m 0644 data/io.clipbhoard.Clipbhoard.svg "$package_root/usr/share/icons/hicolor/scalable/apps/io.clipbhoard.Clipbhoard.svg"
install -m 0644 data/io.clipbhoard.Clipbhoard-autostart.desktop "$package_root/etc/xdg/autostart/io.clipbhoard.Clipbhoard.desktop"
sed "s/^Version:.*/Version: ${version}/" packaging/debian/control > "$package_root/DEBIAN/control"
dpkg-deb --build --root-owner-group "$package_root" "target/clipbhoard_${version}_amd64.deb"

View File

@@ -0,0 +1,4 @@
target/release/clipbhoard usr/bin
data/io.clipbhoard.Clipbhoard.desktop usr/share/applications
data/io.clipbhoard.Clipbhoard.svg usr/share/icons/hicolor/scalable/apps
data/io.clipbhoard.Clipbhoard-autostart.desktop etc/xdg/autostart

View File

@@ -0,0 +1,2 @@
# Packaging note: the application uses XDG autostart rather than a system service.
# This file intentionally documents that boundary for downstream packagers.

11
packaging/debian/control Normal file
View File

@@ -0,0 +1,11 @@
Package: clipbhoard
Version: 0.1.0
Section: utils
Priority: optional
Architecture: amd64
Maintainer: Clipb(h)oard contributors
Depends: libgtk-4-1, libdbus-1-3, libx11-6, libxfixes3, libxtst6
Description: fast, keyboard-first clipboard history
Clipb(h)oard keeps a small local history of textual clipboard entries.
It provides a compact GTK popup, fuzzy search, pinning, and X11 clipboard
integration without network access or telemetry.

25
src/core/entry.rs Normal file
View File

@@ -0,0 +1,25 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
pub id: i64,
pub content: String,
pub content_hash: String,
pub created_at: i64,
pub last_used_at: i64,
pub pinned: bool,
}
impl Entry {
pub fn new(id: i64, content: String, now: i64) -> Self {
let content_hash = crate::core::history::content_hash(&content);
Self {
id,
content,
content_hash,
created_at: now,
last_used_at: now,
pinned: false,
}
}
}

232
src/core/history.rs Normal file
View File

@@ -0,0 +1,232 @@
use std::collections::HashMap;
use thiserror::Error;
use super::Entry;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum HistoryError {
#[error("clipboard entry is empty")]
Empty,
#[error("clipboard entry is {actual} bytes, exceeding the {limit} byte limit")]
TooLarge { actual: usize, limit: usize },
#[error("the pinned entry limit of {0} has been reached")]
PinnedLimit(usize),
#[error("entry {0} was not found")]
NotFound(i64),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordOutcome {
Inserted,
Updated(i64),
Ignored,
}
pub struct History {
entries: HashMap<i64, Entry>,
next_id: i64,
history_limit: usize,
pinned_limit: usize,
max_entry_bytes: usize,
}
impl History {
pub fn new(history_limit: usize, pinned_limit: usize, max_entry_bytes: usize) -> Self {
Self {
entries: HashMap::new(),
next_id: 1,
history_limit,
pinned_limit,
max_entry_bytes,
}
}
pub fn from_entries(
entries: Vec<Entry>,
history_limit: usize,
pinned_limit: usize,
max_entry_bytes: usize,
) -> Self {
let next_id = entries.iter().map(|e| e.id).max().unwrap_or(0) + 1;
let mut history = Self {
entries: entries.into_iter().map(|e| (e.id, e)).collect(),
next_id,
history_limit,
pinned_limit,
max_entry_bytes,
};
history.trim();
history
}
pub fn entries(&self) -> Vec<Entry> {
self.entries.values().cloned().collect()
}
pub fn record(&mut self, content: &str, now: i64) -> Result<RecordOutcome, HistoryError> {
if content.trim().is_empty() {
return Ok(RecordOutcome::Ignored);
}
if content.len() > self.max_entry_bytes {
return Err(HistoryError::TooLarge {
actual: content.len(),
limit: self.max_entry_bytes,
});
}
let hash = content_hash(content);
if let Some(entry) = self
.entries
.values_mut()
.find(|entry| entry.content_hash == hash && entry.content == content)
{
entry.last_used_at = now;
let id = entry.id;
self.trim();
return Ok(RecordOutcome::Updated(id));
}
let id = self.next_id;
self.next_id += 1;
self.entries
.insert(id, Entry::new(id, content.to_owned(), now));
self.trim();
Ok(RecordOutcome::Inserted)
}
pub fn pin(&mut self, id: i64) -> Result<bool, HistoryError> {
let currently_pinned = self
.entries
.get(&id)
.ok_or(HistoryError::NotFound(id))?
.pinned;
if currently_pinned {
self.entries
.get_mut(&id)
.expect("entry existence checked")
.pinned = false;
return Ok(false);
}
if self.entries.values().filter(|entry| entry.pinned).count() >= self.pinned_limit {
return Err(HistoryError::PinnedLimit(self.pinned_limit));
}
self.entries
.get_mut(&id)
.expect("entry existence checked")
.pinned = true;
Ok(true)
}
pub fn touch(&mut self, id: i64, now: i64) -> Result<(), HistoryError> {
self.entries
.get_mut(&id)
.ok_or(HistoryError::NotFound(id))?
.last_used_at = now;
Ok(())
}
pub fn delete(&mut self, id: i64) -> Result<Entry, HistoryError> {
self.entries.remove(&id).ok_or(HistoryError::NotFound(id))
}
pub fn clear_history(&mut self) {
self.entries.retain(|_, entry| entry.pinned);
}
pub fn ordered(&self) -> Vec<Entry> {
let mut entries = self.entries();
entries.sort_by_key(|entry| (!entry.pinned, -entry.last_used_at, -entry.id));
entries
}
pub fn limits(&self) -> (usize, usize, usize) {
(self.history_limit, self.pinned_limit, self.max_entry_bytes)
}
fn trim(&mut self) {
let mut unpinned: Vec<_> = self
.entries
.values()
.filter(|entry| !entry.pinned)
.map(|entry| (entry.last_used_at, entry.id))
.collect();
unpinned.sort_unstable();
while unpinned.len() > self.history_limit {
if let Some((_, id)) = unpinned.first().copied() {
self.entries.remove(&id);
unpinned.remove(0);
}
}
}
}
pub fn content_hash(content: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(content.as_bytes()))
}
#[cfg(test)]
mod tests {
use super::*;
fn history() -> History {
History::new(2, 1, 100)
}
#[test]
fn ignores_blank() {
assert_eq!(history().record(" \n", 1).unwrap(), RecordOutcome::Ignored);
}
#[test]
fn deduplicates_and_updates() {
let mut h = history();
assert_eq!(h.record("a", 1).unwrap(), RecordOutcome::Inserted);
assert!(matches!(
h.record("a", 2).unwrap(),
RecordOutcome::Updated(_)
));
assert_eq!(h.ordered()[0].last_used_at, 2);
assert_eq!(h.entries().len(), 1);
}
#[test]
fn pin_survives_trim_and_duplicate() {
let mut h = history();
h.record("a", 1).unwrap();
let id = h.ordered()[0].id;
h.pin(id).unwrap();
h.record("b", 2).unwrap();
h.record("c", 3).unwrap();
h.record("a", 4).unwrap();
assert!(h.ordered().iter().any(|e| e.content == "a" && e.pinned));
}
#[test]
fn pin_limit_is_enforced() {
let mut h = history();
h.record("a", 1).unwrap();
h.record("b", 2).unwrap();
let ids: Vec<_> = h.ordered().iter().map(|e| e.id).collect();
h.pin(ids[0]).unwrap();
assert_eq!(h.pin(ids[1]), Err(HistoryError::PinnedLimit(1)));
}
#[test]
fn clear_preserves_pins() {
let mut h = history();
h.record("a", 1).unwrap();
h.record("b", 2).unwrap();
let id = h.ordered()[0].id;
h.pin(id).unwrap();
h.clear_history();
assert_eq!(h.ordered().len(), 1);
assert!(h.ordered()[0].pinned);
}
#[test]
fn oversized_is_rejected() {
let oversized = "x".repeat(101);
assert_eq!(
history().record(&oversized, 1),
Err(HistoryError::TooLarge {
actual: 101,
limit: 100
})
);
}
}

7
src/core/mod.rs Normal file
View File

@@ -0,0 +1,7 @@
pub mod entry;
pub mod history;
pub mod search;
pub use entry::Entry;
pub use history::{content_hash, History, HistoryError, RecordOutcome};
pub use search::search;

77
src/core/search.rs Normal file
View File

@@ -0,0 +1,77 @@
use super::Entry;
pub fn search(entries: &[Entry], query: &str) -> Vec<Entry> {
let query = query.trim().to_lowercase();
let mut ranked: Vec<(i64, Entry)> = entries
.iter()
.filter_map(|entry| {
if query.is_empty() {
return Some((0, entry.clone()));
}
let text = entry.content.to_lowercase();
let score = score(&text, &query)?;
Some((score + if entry.pinned { 20 } else { 0 }, entry.clone()))
})
.collect();
ranked.sort_by(|(a_score, a), (b_score, b)| {
b.pinned.cmp(&a.pinned).then_with(|| {
b_score
.cmp(a_score)
.then_with(|| b.last_used_at.cmp(&a.last_used_at))
})
});
ranked.into_iter().map(|(_, entry)| entry).collect()
}
fn score(text: &str, query: &str) -> Option<i64> {
if text == query {
return Some(10_000);
}
if text.starts_with(query) {
return Some(8_000 - text.len().min(1_000) as i64);
}
if let Some(index) = text.find(query) {
return Some(6_000 - index as i64);
}
let mut position = 0usize;
let mut gaps = 0i64;
for character in query.chars() {
let rest = &text[position..];
let found = rest
.char_indices()
.find(|(_, candidate)| *candidate == character)?;
gaps += found.0 as i64;
position += found.0 + character.len_utf8();
}
Some(3_000 - gaps)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Entry;
#[test]
fn ranks_exact_substring_and_fuzzy() {
let entries = vec![
Entry::new(1, "something else".into(), 1),
Entry::new(2, "ssh user@host".into(), 1),
Entry::new(3, "ssh".into(), 1),
];
let result = search(&entries, "ssh");
assert_eq!(result[0].content, "ssh");
assert_eq!(result[1].content, "ssh user@host");
}
#[test]
fn searches_unicode() {
let entry = Entry::new(1, "café ☕".into(), 1);
assert_eq!(search(&[entry], "fé").len(), 1);
}
#[test]
fn pinned_entries_are_always_first() {
let mut pinned = Entry::new(1, "older pinned".into(), 1);
pinned.pinned = true;
let recent = Entry::new(2, "recent ordinary".into(), 2);
assert_eq!(search(&[recent, pinned], "")[0].content, "older pinned");
}
}

517
src/gui.rs Normal file
View File

@@ -0,0 +1,517 @@
use std::{
cell::RefCell,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::Result;
use gtk4::prelude::*;
use gtk4::{
Application, ApplicationWindow, Box as GtkBox, Button, Entry, Label, ListBox, ListBoxRow,
Orientation, ScrolledWindow,
};
use crate::{
config::Config,
core::search,
lifecycle::InstanceGuard,
platform::{
linux::{X11Clipboard, X11ClipboardWatcher, X11Hotkey},
ClipboardBackend, ExpectedClipboardChange, InputBackend,
},
storage::Database,
};
struct UiState {
database: Database,
entries: Vec<crate::core::Entry>,
clipboard: X11Clipboard,
expected_change: ExpectedClipboardChange,
clipboard_watcher: Option<X11ClipboardWatcher>,
hotkey: Option<X11Hotkey>,
previous_focus: Option<u32>,
recording: bool,
show_requested: Arc<AtomicBool>,
}
pub fn run(
config: Config,
database: Database,
instance: InstanceGuard,
show_on_start: bool,
) -> Result<()> {
database.trim_unpinned(config.history_limit)?;
let application = Application::new(Some("io.clipbhoard.Clipbhoard"), Default::default());
let clipboard_watcher = match X11ClipboardWatcher::start() {
Ok(watcher) => Some(watcher),
Err(error) => {
tracing::error!(%error, "X11 clipboard event monitoring is unavailable");
None
}
};
let hotkey = match X11Hotkey::start(&config.global_shortcut) {
Ok(hotkey) => Some(hotkey),
Err(error) => {
tracing::error!(%error, shortcut = %config.global_shortcut, "global shortcut registration failed; the application remains available through manual launch");
None
}
};
let tray = match crate::tray::start() {
Ok(tray) => Some(tray),
Err(error) => {
tracing::warn!(%error, "system tray icon is unavailable; popup and global shortcut remain available");
None
}
};
let clipboard = X11Clipboard::connect()?;
let previous_focus = if show_on_start {
clipboard.focused_window().ok()
} else {
None
};
let shared = Rc::new(RefCell::new(UiState {
entries: database.load_entries()?,
database,
clipboard,
expected_change: ExpectedClipboardChange::default(),
clipboard_watcher,
hotkey,
previous_focus,
recording: true,
show_requested: instance.show_requested(),
}));
let startup_config = config.clone();
let startup_state = Rc::clone(&shared);
let _instance = instance;
let _tray = tray;
application.connect_activate(move |application| {
if let Err(error) = build_window(
application,
&startup_config,
Rc::clone(&startup_state),
show_on_start,
) {
tracing::error!(%error, "failed to build popup window");
}
});
// GTK parses its own command-line options. The application-level flags
// are consumed by main, so do not pass them to GTK as unknown options.
application.run_with_args(&["clipbhoard"]);
Ok(())
}
fn build_window(
application: &Application,
config: &Config,
state: Rc<RefCell<UiState>>,
show_on_start: bool,
) -> Result<()> {
let search_box = Entry::builder()
.placeholder_text("Search clipboard…")
.hexpand(true)
.build();
let list = ListBox::builder()
.selection_mode(gtk4::SelectionMode::Single)
.vexpand(true)
.build();
let scroll = ScrolledWindow::builder()
.child(&list)
.vexpand(true)
.min_content_height(300)
.build();
let root = GtkBox::new(Orientation::Vertical, 8);
root.set_margin_top(12);
root.set_margin_bottom(12);
root.set_margin_start(12);
root.set_margin_end(12);
root.append(&search_box);
root.append(&scroll);
let actions = GtkBox::new(Orientation::Horizontal, 6);
let copy_button = Button::with_label("Copy");
let paste_button = Button::with_label("Paste");
let pin_button = Button::with_label("Pin / Unpin");
let delete_button = Button::with_label("Delete");
let clear_button = Button::with_label("Clear History");
let pause_button = Button::with_label("Pause Recording");
let status = Label::new(Some("Recording clipboard changes"));
actions.append(&copy_button);
actions.append(&paste_button);
actions.append(&pin_button);
actions.append(&delete_button);
actions.append(&clear_button);
actions.append(&pause_button);
root.append(&actions);
root.append(&status);
let window = ApplicationWindow::builder()
.application(application)
.title("Clipb(h)oard")
.default_width(720)
.default_height(420)
.child(&root)
.build();
window.set_visible(show_on_start);
refresh_list(&list, &state.borrow().entries, "");
let pinned_limit = config.pinned_limit;
let pause_button_for_keys = pause_button.clone();
let status_for_keys = status.clone();
let list_for_search = list.clone();
let state_for_search = Rc::clone(&state);
search_box.connect_changed(move |entry| {
refresh_list(
&list_for_search,
&state_for_search.borrow().entries,
entry.text().as_str(),
);
});
let state_for_keys = Rc::clone(&state);
let list_for_keys = list.clone();
let window_for_keys = window.clone();
let keys = gtk4::EventControllerKey::new();
keys.set_propagation_phase(gtk4::PropagationPhase::Capture);
keys.connect_key_pressed(move |_, key, _, modifiers| {
if (key == gtk4::gdk::Key::Up || key == gtk4::gdk::Key::Down)
&& list_for_keys.selected_row().is_none()
{
let row = if key == gtk4::gdk::Key::Down {
list_for_keys.first_child()
} else {
list_for_keys.last_child()
};
if let Some(row) = row.and_downcast::<ListBoxRow>() {
list_for_keys.select_row(Some(&row));
list_for_keys.grab_focus();
return glib::Propagation::Stop;
}
}
if key == gtk4::gdk::Key::r && modifiers.contains(gtk4::gdk::ModifierType::CONTROL_MASK) {
let mut state = state_for_keys.borrow_mut();
state.recording = !state.recording;
pause_button_for_keys.set_label(if state.recording {
"Pause Recording"
} else {
"Resume Recording"
});
status_for_keys.set_text(if state.recording {
"Recording clipboard changes"
} else {
"Recording paused"
});
tracing::info!(recording = state.recording, "clipboard recording state changed");
return glib::Propagation::Stop;
}
if key == gtk4::gdk::Key::Delete
&& modifiers.contains(gtk4::gdk::ModifierType::CONTROL_MASK)
{
let mut state = state_for_keys.borrow_mut();
if let Err(error) = state.database.clear_history() {
tracing::error!(%error, "failed to clear unpinned clipboard history");
}
state.entries.retain(|entry| entry.pinned);
refresh_list(&list_for_keys, &state.entries, "");
return glib::Propagation::Stop;
}
let Some(id) = selected_id(&list_for_keys) else {
return glib::Propagation::Proceed;
};
if key == gtk4::gdk::Key::Return {
let mut state = state_for_keys.borrow_mut();
if let Some(entry) = state.entries.iter().find(|entry| entry.id == id).cloned() {
if let Err(error) = state.clipboard.write_text(&entry.content) {
tracing::error!(%error, "failed to copy selected clipboard entry");
return glib::Propagation::Stop;
}
state.expected_change.expect(&entry.content);
if let Err(error) = state.database.upsert_content(&entry.content, now()) {
tracing::error!(%error, "failed to update selected clipboard entry");
}
window_for_keys.set_visible(false);
if modifiers.contains(gtk4::gdk::ModifierType::CONTROL_MASK) {
if let Some(target) = state.previous_focus {
if let Err(error) = state.clipboard.paste_into_active_window(target) {
tracing::error!(%error, "failed to paste selected clipboard entry; content remains on clipboard");
}
} else {
tracing::warn!("cannot paste selected clipboard entry because the previous focus window is unknown");
}
}
}
return glib::Propagation::Stop;
}
if key == gtk4::gdk::Key::p && modifiers.contains(gtk4::gdk::ModifierType::CONTROL_MASK) {
let mut state = state_for_keys.borrow_mut();
match state.database.toggle_pinned(id, pinned_limit) {
Ok(pinned) => if let Some(entry) = state.entries.iter_mut().find(|entry| entry.id == id) { entry.pinned = pinned; },
Err(error) => tracing::error!(%error, "failed to pin clipboard entry"),
}
refresh_list(&list_for_keys, &state.entries, "");
return glib::Propagation::Stop;
}
if key == gtk4::gdk::Key::Delete {
let mut state = state_for_keys.borrow_mut();
match state.database.delete(id) {
Ok(()) => {
state.entries.retain(|entry| entry.id != id);
refresh_list(&list_for_keys, &state.entries, "");
}
Err(error) => {
tracing::error!(%error, "failed to delete clipboard entry");
}
}
return glib::Propagation::Stop;
}
glib::Propagation::Proceed
});
window.add_controller(keys);
let state_for_copy = Rc::clone(&state);
let list_for_copy = list.clone();
copy_button.connect_clicked(move |_| {
if let Some(id) = selected_id(&list_for_copy) {
let mut state = state_for_copy.borrow_mut();
if let Err(error) = restore_entry(&mut state, id, false) {
tracing::error!(%error, "failed to copy selected clipboard entry");
}
}
});
let state_for_paste = Rc::clone(&state);
let list_for_paste = list.clone();
let window_for_paste = window.clone();
paste_button.connect_clicked(move |_| {
if let Some(id) = selected_id(&list_for_paste) {
window_for_paste.set_visible(false);
let mut state = state_for_paste.borrow_mut();
if let Err(error) = restore_entry(&mut state, id, true) {
tracing::error!(%error, "failed to paste selected clipboard entry; content remains on clipboard");
}
let window_to_restore = window_for_paste.clone();
glib::timeout_add_local_once(std::time::Duration::from_millis(120), move || {
window_to_restore.set_visible(true);
});
}
});
let state_for_pin = Rc::clone(&state);
let list_for_pin = list.clone();
let pinned_list = list.clone();
pin_button.connect_clicked(move |_| {
if let Some(id) = selected_id(&list_for_pin) {
let mut state = state_for_pin.borrow_mut();
match state.database.toggle_pinned(id, pinned_limit) {
Ok(pinned) => {
if let Some(entry) = state.entries.iter_mut().find(|entry| entry.id == id) {
entry.pinned = pinned;
}
refresh_list(&pinned_list, &state.entries, "");
}
Err(error) => tracing::error!(%error, "failed to pin clipboard entry"),
}
}
});
let state_for_delete = Rc::clone(&state);
let list_for_delete = list.clone();
let deleted_list = list.clone();
delete_button.connect_clicked(move |_| {
if let Some(id) = selected_id(&list_for_delete) {
let mut state = state_for_delete.borrow_mut();
match state.database.delete(id) {
Ok(()) => {
state.entries.retain(|entry| entry.id != id);
refresh_list(&deleted_list, &state.entries, "");
}
Err(error) => {
tracing::error!(%error, "failed to delete clipboard entry");
}
}
}
});
let state_for_clear = Rc::clone(&state);
let cleared_list = list.clone();
clear_button.connect_clicked(move |_| {
let mut state = state_for_clear.borrow_mut();
match state.database.clear_history() {
Ok(()) => {
state.entries.retain(|entry| entry.pinned);
refresh_list(&cleared_list, &state.entries, "");
}
Err(error) => {
tracing::error!(%error, "failed to clear unpinned clipboard history");
}
}
});
let state_for_pause = Rc::clone(&state);
let status_for_pause = status.clone();
pause_button.connect_clicked(move |button| {
let mut state = state_for_pause.borrow_mut();
state.recording = !state.recording;
button.set_label(if state.recording {
"Pause Recording"
} else {
"Resume Recording"
});
status_for_pause.set_text(if state.recording {
"Recording clipboard changes"
} else {
"Recording paused"
});
tracing::info!(
recording = state.recording,
"clipboard recording state changed"
);
});
let state_for_watch = Rc::clone(&state);
let list_for_watch = list.clone();
let config_for_watch = config.clone();
let window_for_events = window.clone();
let search_for_events = search_box.clone();
glib::timeout_add_local(std::time::Duration::from_millis(250), move || {
let mut state = state_for_watch.borrow_mut();
if state.hotkey.as_ref().is_some_and(X11Hotkey::take_triggered) {
if window_for_events.is_visible() {
window_for_events.set_visible(false);
} else {
state.previous_focus = match state.clipboard.focused_window() {
Ok(window) => Some(window),
Err(error) => {
tracing::debug!(%error, "could not determine previous focus window");
None
}
};
window_for_events.present();
search_for_events.grab_focus();
}
}
if state.show_requested.swap(false, Ordering::AcqRel) {
if window_for_events.is_visible() {
window_for_events.set_visible(false);
} else {
state.previous_focus = match state.clipboard.focused_window() {
Ok(window) => Some(window),
Err(error) => {
tracing::debug!(%error, "could not determine previous focus window");
None
}
};
window_for_events.present();
search_for_events.grab_focus();
}
}
let clipboard_changed = state
.clipboard_watcher
.as_ref()
.is_none_or(X11ClipboardWatcher::take_changed);
if !clipboard_changed {
return glib::ControlFlow::Continue;
}
if !state.recording {
return glib::ControlFlow::Continue;
}
match state.clipboard.read_text() {
Ok(Some(content))
if !state.expected_change.consume_if_matches(&content)
&& !content.trim().is_empty()
&& content.len() <= config_for_watch.max_entry_bytes =>
{
if let Ok(entry) = state.database.upsert_content(&content, now()) {
if let Err(error) = state.database.trim_unpinned(config_for_watch.history_limit)
{
tracing::error!(%error, "failed to enforce history limit");
}
state.entries.retain(|candidate| candidate.id != entry.id);
state.entries.push(entry);
refresh_list(&list_for_watch, &state.entries, "");
}
}
Ok(_) => {}
Err(error) => {
tracing::debug!(%error, "clipboard read failed; retaining existing history")
}
}
glib::ControlFlow::Continue
});
if show_on_start {
window.present();
search_box.grab_focus();
}
Ok(())
}
fn refresh_list(list: &ListBox, entries: &[crate::core::Entry], query: &str) {
while let Some(child) = list.first_child() {
list.remove(&child);
}
for entry in search(entries, query).into_iter().take(100) {
let preview = entry.content.lines().collect::<Vec<_>>().join(" ");
let preview = if preview.chars().count() > 180 {
format!("{}…", preview.chars().take(180).collect::<String>())
} else {
preview
};
let label = Label::new(Some(&format!(
"{}{}",
if entry.pinned { "📌 " } else { "" },
preview
)));
label.set_xalign(0.0);
label.set_ellipsize(gtk4::pango::EllipsizeMode::End);
label.set_margin_top(5);
label.set_margin_bottom(5);
label.set_margin_start(8);
label.set_margin_end(8);
let row = ListBoxRow::new();
row.set_child(Some(&label));
row.set_tooltip_text(Some(&entry.id.to_string()));
list.append(&row);
}
if list.first_child().is_none() {
let empty = Label::new(Some("No matching clipboard entries"));
empty.set_xalign(0.0);
empty.set_margin_top(12);
empty.set_margin_start(8);
list.append(&empty);
}
}
fn selected_id(list: &ListBox) -> Option<i64> {
list.selected_row()?.tooltip_text()?.parse::<i64>().ok()
}
fn restore_entry(state: &mut UiState, id: i64, paste: bool) -> Result<()> {
let entry = state
.entries
.iter()
.find(|entry| entry.id == id)
.cloned()
.ok_or_else(|| anyhow::anyhow!("clipboard entry {id} was not found"))?;
state.clipboard.write_text(&entry.content)?;
state.expected_change.expect(&entry.content);
state.database.upsert_content(&entry.content, now())?;
state.entries = state.database.load_entries()?;
if paste {
// Give the clipboard owner thread and the X11 focus transition a
// short opportunity to settle before synthesizing Ctrl+V.
std::thread::sleep(std::time::Duration::from_millis(50));
if let Some(target) = state.previous_focus {
state.clipboard.paste_into_active_window(target)?;
} else {
anyhow::bail!("the previously focused X11 window is unknown")
}
}
Ok(())
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}

93
src/main.rs Normal file
View File

@@ -0,0 +1,93 @@
mod config;
mod core;
mod lifecycle;
mod logging;
mod platform;
mod storage;
#[cfg(feature = "gui")]
mod gui;
#[cfg(feature = "gui")]
mod tray;
use anyhow::{Context, Result};
use config::Config;
use storage::Database;
fn main() -> Result<()> {
let _logging = logging::init();
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|arg| arg == "--version") {
println!("clipbhoard {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
if args.iter().any(|arg| arg == "--help") {
println!("Clipb(h)oard — tiny, keyboard-first clipboard history");
println!("Usage: clipbhoard [--version] [--help] [--diagnostics] [--show] [--autostart]");
return Ok(());
}
let show_on_start = args.iter().any(|arg| arg == "--show")
|| std::env::var_os("CLIPBHOARD_SHOW_REQUESTED").is_some();
let config = Config::load_or_default()?;
if args.iter().any(|arg| arg == "--autostart") && !config.autostart {
tracing::info!("autostart is disabled in configuration");
return Ok(());
}
if show_on_start && std::env::var_os("CLIPBHOARD_SHOW_CHILD").is_none() {
let executable =
std::env::current_exe().context("failed to locate clipbhoard executable")?;
std::process::Command::new(executable)
.env("CLIPBHOARD_SHOW_CHILD", "1")
.env("CLIPBHOARD_SHOW_REQUESTED", "1")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.context("failed to start the background Clipb(h)oard process")?;
return Ok(());
}
let instance = match lifecycle::InstanceGuard::acquire() {
Ok(instance) => instance,
Err(lock_error) => {
lifecycle::InstanceGuard::signal_show().with_context(|| lock_error.to_string())?;
return Ok(());
}
};
let database = Database::open_default()?;
if args.iter().any(|arg| arg == "--diagnostics") {
println!("Version: {}", env!("CARGO_PKG_VERSION"));
println!("Database: OK ({})", database.path().display());
println!("Config: OK");
println!("Instance lock: OK ({})", instance.path().display());
println!(
"Log: {}",
dirs::state_dir()
.unwrap_or_else(|| std::env::temp_dir())
.join("clipbhoard/clipbhoard.log")
.display()
);
println!(
"GUI backend: {}",
if cfg!(feature = "gui") {
"compiled"
} else {
"not compiled"
}
);
return Ok(());
}
#[cfg(feature = "gui")]
return gui::run(config, database, instance, show_on_start);
#[cfg(not(feature = "gui"))]
{
tracing::warn!("GTK/X11 support is not compiled; install GTK4 development packages and rebuild with --features gui");
println!("Clipb(h)oard core is installed, but the GTK/X11 backend is not compiled.");
println!("Rebuild with: cargo run --features gui");
Ok(())
}
}

View File

@@ -0,0 +1,7 @@
mod x11_clipboard;
mod x11_events;
mod x11_input;
pub use x11_clipboard::X11Clipboard;
pub use x11_events::{X11ClipboardWatcher, X11Hotkey};
pub use x11_input::X11Input;

View File

@@ -0,0 +1,67 @@
use std::time::Duration;
use anyhow::{Context, Result};
use x11_clipboard::Clipboard;
use crate::platform::{ClipboardBackend, InputBackend};
use super::X11Input;
pub struct X11Clipboard {
clipboard: Clipboard,
input: Option<X11Input>,
}
impl X11Clipboard {
pub fn connect() -> Result<Self> {
let clipboard = Clipboard::new().context("failed to connect to the X11 clipboard")?;
let input = match X11Input::connect() {
Ok(input) => Some(input),
Err(error) => {
tracing::warn!(%error, "X11 paste injection is unavailable; copy-to-clipboard remains available");
None
}
};
Ok(Self { clipboard, input })
}
pub fn focused_window(&self) -> Result<u32> {
self.input
.as_ref()
.context("X11 paste injection is unavailable")?
.focused_window()
}
}
impl ClipboardBackend for X11Clipboard {
fn read_text(&mut self) -> Result<Option<String>> {
let atoms = &self.clipboard.getter.atoms;
let bytes = self
.clipboard
.load(
atoms.clipboard,
atoms.utf8_string,
atoms.property,
Duration::from_millis(500),
)
.context("failed to read textual X11 clipboard contents")?;
Ok(Some(String::from_utf8(bytes).context(
"X11 clipboard did not contain valid UTF-8 text",
)?))
}
fn write_text(&mut self, text: &str) -> Result<()> {
let atoms = &self.clipboard.setter.atoms;
self.clipboard
.store(atoms.clipboard, atoms.utf8_string, text.as_bytes())
.context("failed to write textual X11 clipboard contents")
}
}
impl InputBackend for X11Clipboard {
fn paste_into_active_window(&mut self, target: u32) -> Result<()> {
self.input
.as_ref()
.context("X11 paste injection is unavailable")?
.paste_into(target)
}
}

View File

@@ -0,0 +1,190 @@
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use anyhow::{Context, Result};
use x11rb::{
connection::Connection,
protocol::{
xfixes::{self, ConnectionExt as _},
xproto::{self, ConnectionExt as _},
Event,
},
rust_connection::RustConnection,
};
pub struct X11ClipboardWatcher {
changed: Arc<AtomicBool>,
}
impl X11ClipboardWatcher {
pub fn start() -> Result<Self> {
let (connection, screen) = RustConnection::connect(None)
.context("failed to connect to X11 for clipboard events")?;
let root = connection.setup().roots[screen].root;
let clipboard = connection.intern_atom(false, b"CLIPBOARD")?.reply()?.atom;
xfixes::query_version(&connection, 5, 0)?
.reply()
.context("XFixes clipboard events are unavailable")?;
xfixes::select_selection_input(
&connection,
root,
clipboard,
xfixes::SelectionEventMask::SET_SELECTION_OWNER,
)?
.check()?;
connection.flush()?;
let changed = Arc::new(AtomicBool::new(true));
let signal = Arc::clone(&changed);
std::thread::Builder::new()
.name("clipbhoard-x11-clipboard".into())
.spawn(move || watch_events(connection, signal))
.context("failed to start X11 clipboard event thread")?;
Ok(Self { changed })
}
pub fn take_changed(&self) -> bool {
self.changed.swap(false, Ordering::AcqRel)
}
}
fn watch_events(connection: RustConnection, changed: Arc<AtomicBool>) {
loop {
match connection.wait_for_event() {
Ok(Event::XfixesSelectionNotify(_)) => {
changed.store(true, Ordering::Release);
}
Ok(_) => {}
Err(error) => {
tracing::error!(%error, "X11 clipboard event stream stopped");
break;
}
}
}
}
pub struct X11Hotkey {
triggered: Arc<AtomicBool>,
}
impl X11Hotkey {
pub fn start(shortcut: &str) -> Result<Self> {
let (connection, screen) = RustConnection::connect(None)
.context("failed to connect to X11 for global shortcut")?;
let root = connection.setup().roots[screen].root;
let (keysym, modifiers) = parse_shortcut(shortcut)?;
let keycode = keycode_for_keysym(&connection, keysym)?;
let grab_modifiers = grab_modifier_variants(modifiers);
for grab_modifier in &grab_modifiers {
connection
.grab_key(
false,
root,
*grab_modifier,
keycode,
xproto::GrabMode::ASYNC,
xproto::GrabMode::ASYNC,
)?
.check()
.with_context(|| {
format!(
"failed to register global shortcut '{shortcut}' (it may already be registered)"
)
})?;
}
connection.flush()?;
let triggered = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&triggered);
std::thread::Builder::new()
.name("clipbhoard-x11-hotkey".into())
.spawn(move || {
watch_hotkey(connection, root, keycode, grab_modifiers, modifiers, signal)
})
.context("failed to start X11 hotkey thread")?;
Ok(Self { triggered })
}
pub fn take_triggered(&self) -> bool {
self.triggered.swap(false, Ordering::AcqRel)
}
}
fn watch_hotkey(
connection: RustConnection,
root: xproto::Window,
keycode: xproto::Keycode,
grab_modifiers: Vec<xproto::ModMask>,
modifiers: xproto::ModMask,
triggered: Arc<AtomicBool>,
) {
while let Ok(event) = connection.wait_for_event() {
if let Event::KeyPress(event) = event {
if event.detail == keycode && event.state.bits() & modifiers.bits() == modifiers.bits()
{
triggered.store(true, Ordering::Release);
}
}
}
for grab_modifier in grab_modifiers {
let _ = connection.ungrab_key(keycode, root, grab_modifier);
}
let _ = connection.flush();
}
fn grab_modifier_variants(modifiers: xproto::ModMask) -> Vec<xproto::ModMask> {
let locks = [
xproto::ModMask::from(0u8),
xproto::ModMask::M2,
xproto::ModMask::LOCK,
xproto::ModMask::M5,
xproto::ModMask::M2 | xproto::ModMask::LOCK,
xproto::ModMask::M2 | xproto::ModMask::M5,
xproto::ModMask::LOCK | xproto::ModMask::M5,
xproto::ModMask::M2 | xproto::ModMask::LOCK | xproto::ModMask::M5,
];
locks.into_iter().map(|lock| modifiers | lock).collect()
}
fn keycode_for_keysym(
connection: &RustConnection,
keysym: xproto::Keysym,
) -> Result<xproto::Keycode> {
let setup = connection.setup();
let first = setup.min_keycode;
let count = setup.max_keycode.saturating_sub(first).saturating_add(1);
let mapping = connection.get_keyboard_mapping(first, count)?.reply()?;
let per_key = mapping.keysyms_per_keycode as usize;
for (offset, keysyms) in mapping.keysyms.chunks(per_key).enumerate() {
if keysyms.iter().any(|candidate| *candidate == keysym) {
return Ok(first + offset as u8);
}
}
anyhow::bail!("could not resolve the V keycode from the X11 keyboard mapping")
}
fn parse_shortcut(shortcut: &str) -> Result<(xproto::Keysym, xproto::ModMask)> {
let parts: Vec<_> = shortcut.split('+').map(str::trim).collect();
let key = parts
.last()
.filter(|key| key.chars().count() == 1)
.context("global shortcut must end with one key, for example Super+V")?;
let key_char = key.chars().next().unwrap().to_ascii_uppercase();
let keysym = key_char as u32;
let mut modifiers = xproto::ModMask::from(0u8);
for modifier in &parts[..parts.len().saturating_sub(1)] {
modifiers |= match modifier.to_ascii_lowercase().as_str() {
"super" | "meta" | "win" | "windows" => xproto::ModMask::M4,
"ctrl" | "control" => xproto::ModMask::CONTROL,
"alt" => xproto::ModMask::M1,
"shift" => xproto::ModMask::SHIFT,
_ => anyhow::bail!("unsupported modifier '{modifier}' in shortcut '{shortcut}'"),
};
}
if modifiers.bits() == 0 {
anyhow::bail!("global shortcut must include a modifier: '{shortcut}'")
}
Ok((keysym, modifiers))
}

View File

@@ -0,0 +1,113 @@
use anyhow::{Context, Result};
use x11rb::{
connection::Connection,
protocol::{
xproto::{self, ConnectionExt as _},
xtest::{self, ConnectionExt as _},
},
rust_connection::RustConnection,
};
pub struct X11Input {
connection: RustConnection,
root: xproto::Window,
control_keycode: xproto::Keycode,
v_keycode: xproto::Keycode,
}
impl X11Input {
pub fn connect() -> Result<Self> {
let (connection, screen) = RustConnection::connect(None)
.context("failed to connect to X11 for paste injection")?;
let root = connection.setup().roots[screen].root;
xtest::get_version(&connection, 2, 2)?
.reply()
.context("XTest paste injection is unavailable")?;
let control_keycode = keycode_for_keysym(&connection, 0xffe3)
.context("could not resolve the X11 Control keycode")?;
let v_keycode =
keycode_for_keysym(&connection, 0x76).context("could not resolve the X11 V keycode")?;
Ok(Self {
connection,
root,
control_keycode,
v_keycode,
})
}
pub fn focused_window(&self) -> Result<xproto::Window> {
Ok(self.connection.get_input_focus()?.reply()?.focus)
}
pub fn paste_into(&self, target: xproto::Window) -> Result<()> {
self.connection
.set_input_focus(xproto::InputFocus::NONE, target, x11rb::CURRENT_TIME)?
.check()?;
xtest::fake_input(
&self.connection,
xproto::KEY_PRESS_EVENT,
self.control_keycode,
x11rb::CURRENT_TIME,
self.root,
0,
0,
0,
)?
.check()?;
xtest::fake_input(
&self.connection,
xproto::KEY_PRESS_EVENT,
self.v_keycode,
x11rb::CURRENT_TIME,
self.root,
0,
0,
0,
)?
.check()?;
xtest::fake_input(
&self.connection,
xproto::KEY_RELEASE_EVENT,
self.v_keycode,
x11rb::CURRENT_TIME,
self.root,
0,
0,
0,
)?
.check()?;
xtest::fake_input(
&self.connection,
xproto::KEY_RELEASE_EVENT,
self.control_keycode,
x11rb::CURRENT_TIME,
self.root,
0,
0,
0,
)?
.check()?;
self.connection.flush()?;
Ok(())
}
}
fn keycode_for_keysym(
connection: &RustConnection,
keysym: xproto::Keysym,
) -> Result<xproto::Keycode> {
let setup = connection.setup();
let first = setup.min_keycode;
let count = setup.max_keycode.saturating_sub(first).saturating_add(1);
let mapping = connection.get_keyboard_mapping(first, count)?.reply()?;
let per_key = mapping.keysyms_per_keycode as usize;
for (offset, keysyms) in mapping.keysyms.chunks(per_key).enumerate() {
if keysyms
.iter()
.any(|candidate| *candidate == keysym || (*candidate == 0x56 && keysym == 0x76))
{
return Ok(first + offset as u8);
}
}
anyhow::bail!("keysym {keysym:#x} is not present in the X11 keyboard mapping")
}

45
src/platform/mod.rs Normal file
View File

@@ -0,0 +1,45 @@
#[cfg(any(feature = "gui", feature = "x11"))]
pub mod linux;
use anyhow::Result;
pub trait ClipboardBackend {
fn read_text(&mut self) -> Result<Option<String>>;
fn write_text(&mut self, text: &str) -> Result<()>;
}
pub trait InputBackend {
fn paste_into_active_window(&mut self, target_window: u32) -> Result<()>;
}
#[derive(Default)]
pub struct ExpectedClipboardChange {
content: Option<String>,
}
impl ExpectedClipboardChange {
pub fn expect(&mut self, content: &str) {
self.content = Some(content.to_owned());
}
pub fn consume_if_matches(&mut self, content: &str) -> bool {
if self.content.as_deref() == Some(content) {
self.content = None;
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::ExpectedClipboardChange;
#[test]
fn expected_restore_is_consumed_once() {
let mut marker = ExpectedClipboardChange::default();
marker.expect("restored");
assert!(marker.consume_if_matches("restored"));
assert!(!marker.consume_if_matches("restored"));
}
}

28
src/storage/migrations.rs Normal file
View File

@@ -0,0 +1,28 @@
use anyhow::Result;
use rusqlite::Connection;
const MIGRATIONS: &[&str] = &[include_str!("../../migrations/001_initial.sql")];
pub fn run(connection: &Connection) -> Result<()> {
connection.execute_batch(
"CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY NOT NULL);",
)?;
for (index, migration) in MIGRATIONS.iter().enumerate() {
let version = (index + 1) as i64;
let applied: bool = connection.query_row(
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = ?1)",
[version],
|row| row.get(0),
)?;
if !applied {
let transaction = connection.unchecked_transaction()?;
transaction.execute_batch(migration)?;
transaction.execute(
"INSERT INTO schema_migrations(version) VALUES (?1)",
[version],
)?;
transaction.commit()?;
}
}
Ok(())
}

View File

@@ -122,8 +122,12 @@ impl Database {
Ok(!pinned)
}
pub fn delete(&self, id: i64) -> Result<()> {
self.connection
let deleted = self
.connection
.execute("DELETE FROM entries WHERE id = ?1", params![id])?;
if deleted == 0 {
anyhow::bail!("clipboard entry {id} was not found");
}
Ok(())
}
pub fn clear_history(&self) -> Result<()> {

55
src/tray.rs Normal file
View File

@@ -0,0 +1,55 @@
use anyhow::{bail, Result};
use crate::lifecycle::InstanceGuard;
struct ClipbhoardTray;
impl ksni::Tray for ClipbhoardTray {
fn id(&self) -> String {
"clipbhoard".into()
}
fn title(&self) -> String {
"Clipb(h)oard".into()
}
fn icon_name(&self) -> String {
"io.clipbhoard.Clipbhoard".into()
}
fn activate(&mut self, _x: i32, _y: i32) {
if let Err(error) = InstanceGuard::signal_show() {
tracing::error!(%error, "failed to show popup from tray icon");
}
}
fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
use ksni::menu::StandardItem;
vec![StandardItem {
label: "Show Clipb(h)oard".into(),
icon_name: "io.clipbhoard.Clipbhoard".into(),
activate: Box::new(|_| {
if let Err(error) = InstanceGuard::signal_show() {
tracing::error!(%error, "failed to show popup from tray menu");
}
}),
..Default::default()
}
.into()]
}
}
pub fn start() -> Result<()> {
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
bail!("no D-Bus session bus is available")
}
let service = ksni::TrayService::new(ClipbhoardTray);
std::thread::Builder::new()
.name("clipbhoard-tray".into())
.spawn(move || {
if let Err(error) = service.run() {
tracing::warn!(%error, "system tray service stopped");
}
})?;
Ok(())
}