From 7b5f2c126a271dcacee1ca2d63bc840ab91becc8 Mon Sep 17 00:00:00 2001 From: haffel Date: Thu, 10 Sep 2026 20:34:48 +0200 Subject: [PATCH] Add app baseline and keep UI state consistent --- .agents/BIBLE.md | 1699 +++++++++++++++++ .agents/SHIP_CHECKLIST.md | 45 + .dockerignore | 4 + .gitignore | 1 + Cargo.lock | 1610 ++++++++++++++++ Cargo.toml | 36 + Dockerfile | 22 + README.md | 45 + ...io.clipbhoard.Clipbhoard-autostart.desktop | 7 + data/io.clipbhoard.Clipbhoard.desktop | 10 + data/io.clipbhoard.Clipbhoard.svg | 4 + migrations/001_initial.sql | 12 + packaging/build-deb.sh | 19 + packaging/clipbhoard.install | 4 + packaging/clipbhoard.service | 2 + packaging/debian/control | 11 + src/core/entry.rs | 25 + src/core/history.rs | 232 +++ src/core/mod.rs | 7 + src/core/search.rs | 77 + src/gui.rs | 517 +++++ src/main.rs | 93 + src/platform/linux/mod.rs | 7 + src/platform/linux/x11_clipboard.rs | 67 + src/platform/linux/x11_events.rs | 190 ++ src/platform/linux/x11_input.rs | 113 ++ src/platform/mod.rs | 45 + src/storage/migrations.rs | 28 + src/storage/mod.rs | 6 +- src/tray.rs | 55 + 30 files changed, 4992 insertions(+), 1 deletion(-) create mode 100644 .agents/BIBLE.md create mode 100644 .agents/SHIP_CHECKLIST.md create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 data/io.clipbhoard.Clipbhoard-autostart.desktop create mode 100644 data/io.clipbhoard.Clipbhoard.desktop create mode 100644 data/io.clipbhoard.Clipbhoard.svg create mode 100644 migrations/001_initial.sql create mode 100755 packaging/build-deb.sh create mode 100644 packaging/clipbhoard.install create mode 100644 packaging/clipbhoard.service create mode 100644 packaging/debian/control create mode 100644 src/core/entry.rs create mode 100644 src/core/history.rs create mode 100644 src/core/mod.rs create mode 100644 src/core/search.rs create mode 100644 src/gui.rs create mode 100644 src/main.rs create mode 100644 src/platform/linux/mod.rs create mode 100644 src/platform/linux/x11_clipboard.rs create mode 100644 src/platform/linux/x11_events.rs create mode 100644 src/platform/linux/x11_input.rs create mode 100644 src/platform/mod.rs create mode 100644 src/storage/migrations.rs create mode 100644 src/tray.rs diff --git a/.agents/BIBLE.md b/.agents/BIBLE.md new file mode 100644 index 0000000..f79104b --- /dev/null +++ b/.agents/BIBLE.md @@ -0,0 +1,1699 @@ +# Clipb(h)oard — Implementation Bible + +## 0. Mission + +Build **Clipb(h)oard**, a tiny, extremely fast, keyboard-first clipboard history utility. + +Primary target: + +- Linux Mint / Cinnamon +- X11 first-class for v1 + +Future-friendly: + +- Linux Wayland +- Windows +- macOS + +But **do not compromise v1 simplicity to prematurely support every platform**. + +Clipb(h)oard is intentionally small. + +The core workflow is: + +> **Copy normally → press global shortcut → type a few characters → select entry → copy or paste it.** + +The application must feel instantaneous, native, boringly reliable, easy to install, easy to debug, and almost invisible when not being used. + +This is **not** a clipboard productivity suite. + +--- + +# 1. Product Principles + +These principles override feature temptation. + +## 1.1 Minimal + +The application should consist conceptually of: + +- one background process +- one popup window +- one clipboard history +- one pinned collection +- one search box +- one SQLite database +- one config file +- simple logs + +Do not add abstractions, services, windows, menus, dependency layers, or frameworks without a concrete reason. + +## 1.2 Fast + +Expected experience: + +- negligible idle CPU usage +- low memory consumption +- popup appears perceptually instantly +- fuzzy search updates immediately +- clipboard monitoring has effectively no noticeable delay + +Performance should come primarily from simple architecture, not premature optimization. + +## 1.3 Reliable + +Prefer: + +- deterministic behavior +- explicit error handling +- transactions +- atomic state changes +- simple state machines +- clear logging +- graceful fallback behavior + +Avoid cleverness. + +## 1.4 Keyboard-first + +The complete primary workflow must work without a mouse. + +Mouse support is useful, but secondary. + +## 1.5 Local-only + +No: + +- network access +- cloud +- telemetry +- analytics +- accounts +- remote API +- online dependency + +All clipboard data stays on the machine. + +## 1.6 Debuggable + +When something fails, the cause should be discoverable from logs without recompiling the application. + +Avoid swallowing errors. + +--- + +# 2. Recommended Technology Stack + +Use: + +- **Rust** +- **GTK4** +- **SQLite** +- **TOML configuration** + +Linux/X11 platform functionality must be isolated behind backend interfaces. + +Suggested logical architecture: + +```text +src/ +├── main.rs +├── app/ +│ ├── state.rs +│ ├── commands.rs +│ └── lifecycle.rs +├── core/ +│ ├── entry.rs +│ ├── history.rs +│ ├── search.rs +│ └── limits.rs +├── storage/ +│ ├── sqlite.rs +│ └── migrations.rs +├── config/ +│ └── mod.rs +├── platform/ +│ ├── mod.rs +│ └── linux/ +│ ├── x11_clipboard.rs +│ ├── x11_hotkey.rs +│ ├── x11_input.rs +│ └── autostart.rs +├── ui/ +│ ├── window.rs +│ ├── search.rs +│ ├── entry_row.rs +│ └── settings.rs +└── logging.rs +``` + +Exact filenames may change. + +The separation of responsibilities should not. + +--- + +# 3. Platform Abstraction + +All OS-specific behavior must live behind explicit interfaces. + +Conceptually: + +```rust +trait ClipboardBackend { + fn read_text(&self) -> Result>; + fn write_text(&self, text: &str) -> Result<()>; + fn watch(&self, callback: ...) -> Result<()>; +} + +trait HotkeyBackend { + fn register(&self, shortcut: &Shortcut) -> Result<()>; + fn unregister(&self) -> Result<()>; +} + +trait InputBackend { + fn paste_into_active_window(&self) -> Result<()>; +} +``` + +Do not let X11-specific implementation details leak into history, storage, search, or UI logic. + +For v1: + +- implement Linux/X11 properly +- design Wayland/Windows/macOS backends for later +- do not build fake cross-platform abstractions that are never exercised + +--- + +# 4. Core Clipboard Behavior + +## 4.1 Capture + +Automatically capture textual clipboard contents whenever the clipboard changes. + +For v1: + +- text only +- ignore images +- ignore arbitrary binary clipboard formats +- files may be represented only if they naturally arrive as text + +Ignore: + +- empty strings +- zero-length clipboard data +- clipboard events generated internally when necessary + +Whitespace-only strings may be ignored. + +Do not silently modify copied text. + +Clipboard contents must be stored exactly as copied unless explicitly required for hashing/indexing. + +--- + +# 5. Deduplication + +Clipboard history must not accumulate exact duplicates. + +When text is copied: + +1. determine whether identical text already exists +2. if it exists: + - do not create another row + - update its `last_used_at` + - move it to the top of history +3. if it does not exist: + - create a new history entry + +Pinned status must survive deduplication. + +Example: + +```text +History: + +A +B +C +``` + +Copying `C` again becomes: + +```text +C +A +B +``` + +There must still be exactly one `C`. + +Use a content hash for efficient lookup if useful, but always protect against theoretical hash collisions by confirming content equality. + +--- + +# 6. Entries + +Minimum logical fields: + +```text +id +content +content_hash +created_at +last_used_at +pinned +``` + +Optional future-friendly fields are acceptable only if justified. + +Do not add metadata merely because it might someday be useful. + +--- + +# 7. Pinned Entries + +Any entry may be pinned or unpinned. + +Pinned entries: + +- persist indefinitely until manually unpinned/deleted +- are exempt from normal history cleanup +- remain searchable +- are visually distinguishable +- participate in deduplication + +Pinning does not duplicate the entry into another table unless there is a compelling architectural reason. + +Prefer one canonical entry with a `pinned` flag. + +--- + +# 8. Limits + +Provide separate configurable limits: + +```toml +history_limit = 100 +pinned_limit = 25 +``` + +These are independent. + +`history_limit` applies only to unpinned history entries. + +`pinned_limit` applies only to pinned entries. + +When normal history exceeds its limit: + +- remove oldest unpinned entries first + +Pinned entries must never be removed by normal history trimming. + +When pinning would exceed `pinned_limit`: + +- reject the pin operation cleanly +- show a small understandable error +- never silently unpin or delete something else + +Reasonable defaults: + +```toml +history_limit = 100 +pinned_limit = 25 +``` + +--- + +# 9. Maximum Clipboard Entry Size + +Prevent pathological clipboard contents from bloating storage. + +Provide: + +```toml +max_entry_bytes = 1048576 +``` + +Default: + +**1 MiB** + +Entries larger than the limit should not be stored. + +Do not crash. + +Log the event at an appropriate level. + +Optional unobtrusive user feedback is acceptable. + +--- + +# 10. Search + +Search must be fuzzy and effectively instantaneous. + +Search: + +- history +- pinned entries +- entire textual content + +Expected matching behavior: + +- exact matches rank very highly +- exact substring matches rank highly +- fuzzy matches rank beneath stronger matches +- recency breaks ties +- pinned status may provide a modest ranking bonus + +Possible ranking logic: + +```text +exact equality +→ prefix / substring strength +→ fuzzy score +→ pinned bonus +→ recency +``` + +Do not build a complex search index for a few hundred clipboard entries. + +Load lightweight entry data into memory. + +Search in memory. + +SQLite FTS is unnecessary for v1 unless testing demonstrates otherwise. + +--- + +# 11. Popup UI + +The main UI is a small popup. + +Conceptually: + +```text +┌──────────────────────────────────────────────┐ +│ Search clipboard… ⌕ │ +├──────────────────────────────────────────────┤ +│ 📌 ssh user@192.168.1.20 │ +│ 📌 docker compose up -d │ +│ https://example.com/document │ +│ const foo = calculateSomething(...) │ +│ sudo systemctl restart nginx │ +└──────────────────────────────────────────────┘ +``` + +Design principles: + +- minimal chrome +- compact rows +- no unnecessary toolbar +- no permanent sidebar +- no giant headings +- no decorative animation +- no card-heavy UI +- native-feeling GTK widgets +- fast rendering + +Each row should show enough text to identify the clipboard item. + +Long entries should be truncated visually. + +Full content remains stored. + +--- + +# 12. Popup Invocation + +The application runs in the background. + +A configurable global keyboard shortcut opens the popup from anywhere. + +Default suggestion: + +```text +Super+V +``` + +The shortcut must be configurable. + +When opened: + +1. popup appears +2. search field receives focus immediately +3. current entries appear +4. keyboard navigation works immediately + +Avoid requiring a second click. + +--- + +# 13. Popup Position + +Default: + +- center of active monitor + +Possible future setting: + +```toml +popup_position = "active-monitor-center" +``` + +Future options may include cursor position. + +Do not spend excessive v1 effort on advanced positioning. + +Correct multi-monitor behavior matters. + +--- + +# 14. Keyboard Controls + +At minimum: + +```text +Global shortcut + Open/toggle Clipb(h)oard + +Escape + Close popup + +Arrow Up / Down + Move selection + +Enter + Copy selected entry to clipboard + +Ctrl+Enter + Paste selected entry into previously focused application + +Delete + Delete selected entry + +Ctrl+P + Pin/unpin selected entry +``` + +Exact secondary shortcuts may change if GTK/platform conflicts exist. + +The principles must remain: + +- obvious +- keyboard-first +- configurable where necessary +- documented + +Do not overload dozens of obscure shortcuts. + +--- + +# 15. Copy Action + +Selecting `Copy`: + +1. writes the selected entry to the system clipboard +2. marks it recently used +3. moves it to the top according to normal ordering +4. closes the popup by default + +The internal clipboard watcher must not accidentally create a duplicate event. + +--- + +# 16. Paste Action + +Selecting `Paste`: + +1. place selected content onto the clipboard +2. hide the popup +3. restore focus to the previously active application +4. invoke the platform paste action + +For X11, implement this reliably. + +The paste mechanism belongs to the `InputBackend`. + +Do not put input simulation logic in UI code. + +If paste injection fails: + +- leave the selected content on the clipboard +- show/log a useful error +- do not lose data + +This means the user can still manually press `Ctrl+V`. + +--- + +# 17. Clipboard Self-Change Suppression + +Clipb(h)oard itself changes the clipboard when users restore entries. + +These changes must not produce broken behavior such as: + +```text +select old item +→ write clipboard +→ watcher sees clipboard +→ creates another history entry +→ duplicates / loops / reorder weirdness +``` + +Implement explicit self-change handling. + +This must be deterministic. + +Do not rely purely on arbitrary sleep timers. + +A short-lived expected-content marker/hash may be used. + +--- + +# 18. Delete + +Deleting an entry removes it from history and persistent storage. + +Deletion should be immediate. + +Normal individual deletion does not require a confirmation modal. + +Pinned entries may also be deleted deliberately. + +--- + +# 19. Clear History + +Provide: + +**Clear History** + +Meaning: + +> delete all unpinned entries while preserving pinned entries. + +This must be the normal bulk-clear action. + +An optional: + +**Clear Everything** + +may exist, but should require deliberate confirmation because it also deletes pinned entries. + +--- + +# 20. Persistence + +Use SQLite. + +Suggested location: + +```text +~/.local/share/clipbhoard/clipbhoard.db +``` + +Follow XDG directories where appropriate. + +Database operations must use transactions where multiple related state changes occur. + +SQLite settings should prioritize reliability while remaining lightweight. + +WAL mode may be used if justified. + +Do not keep the database connection architecture more complicated than necessary. + +--- + +# 21. Database Schema + +A reasonable starting schema: + +```sql +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 +); + +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); +``` + +This is a guideline, not sacred SQL. + +Schema migrations must exist from the start. + +Even migration `001_initial.sql` is enough initially. + +Never rely on deleting users' databases to handle schema changes during development. + +--- + +# 22. Configuration + +Use TOML. + +Suggested path: + +```text +~/.config/clipbhoard/config.toml +``` + +Follow XDG configuration directories. + +Suggested v1 config: + +```toml +history_limit = 100 +pinned_limit = 25 +max_entry_bytes = 1048576 + +global_shortcut = "Super+V" + +autostart = true + +popup_position = "active-monitor-center" + +log_level = "info" +``` + +Provide robust defaults if the config file does not exist. + +Malformed config should: + +- not crash the entire application where avoidable +- report exactly what is invalid +- fall back carefully +- preserve the user's broken config for debugging + +Do not silently overwrite malformed user configuration. + +--- + +# 23. Settings UI + +Settings UI is optional but desirable. + +If implemented, it must remain tiny. + +Expose only useful settings: + +- global shortcut +- history limit +- pinned limit +- autostart +- maximum entry size +- popup position +- logging level, if useful + +Do not make a giant preferences application. + +The config file remains understandable and editable manually. + +--- + +# 24. Autostart + +Clipb(h)oard should autostart with the user's graphical session. + +For Linux Mint/X11, use normal desktop autostart mechanisms. + +Prefer an XDG autostart `.desktop` entry. + +The app must also be able to run manually without autostart. + +Autostart behavior should be configurable. + +--- + +# 25. Single Instance + +Only one Clipb(h)oard process may own clipboard monitoring at a time. + +Starting Clipb(h)oard while it is already running should: + +- communicate with the existing instance if practical +- open/toggle the popup +- exit the new process + +At minimum, prevent duplicate background watchers. + +Do not allow two instances to race against the same clipboard/database. + +--- + +# 26. Logging + +Provide useful application logs. + +Suggested path: + +```text +~/.local/state/clipbhoard/clipbhoard.log +``` + +Respect XDG state directories. + +Supported levels: + +```text +error +warn +info +debug +trace +``` + +Normal default: + +```text +info +``` + +Logs should include: + +- application startup +- application version +- loaded backend +- database initialization/migration failures +- hotkey registration failures +- clipboard backend failures +- paste injection failures +- malformed configuration +- unexpected recoverable errors + +Do not log clipboard contents by default. + +That is a privacy requirement. + +Debug logging should still avoid dumping full clipboard contents unless explicitly enabled by a special developer option. + +--- + +# 27. Privacy + +Clipboard history is sensitive. + +Hard rules: + +- no telemetry +- no network requests +- no cloud sync +- no analytics +- no automatic external crash reporting +- no clipboard content in normal logs + +Provide: + +**Pause Recording** + +When paused: + +- do not store new clipboard changes +- existing history remains accessible + +A tray/menu action or minimal application action is sufficient. + +--- + +# 28. Sensitive Clipboard Support + +Design clipboard ingestion so sensitive entries can eventually be ignored based on platform/application hints. + +Do not over-engineer this in v1. + +If Linux clipboard protocols expose a reliable standard signal indicating secrecy/private content, respect it where practical. + +Password-manager compatibility is desirable. + +Never claim security guarantees the platform cannot provide. + +--- + +# 29. Tray / Background Presence + +If a tray icon is used, keep its menu minimal: + +```text +Open Clipb(h)oard +Pause Recording +Clear History +Settings +Quit +``` + +The application should not require users to interact with the tray during normal use. + +If tray integration creates disproportionate platform complexity, v1 may omit it in favor of application actions accessible from the popup. + +--- + +# 30. Error Handling + +Clipb(h)oard must not panic for ordinary runtime failures. + +Use idiomatic Rust error handling. + +Errors should have context. + +Bad: + +```text +Error: failed +``` + +Good: + +```text +Failed to register global shortcut 'Super+V': +X11 reported that the key combination is already grabbed by another application. +``` + +The user should understand: + +- what failed +- whether Clipb(h)oard can continue +- what they can do about it + +Fatal errors should terminate cleanly with a useful message and log. + +--- + +# 31. Startup Behavior + +Startup sequence should approximately be: + +```text +initialize logging +→ load config +→ establish single-instance ownership +→ initialize database +→ run migrations +→ load clipboard entries +→ apply limits if necessary +→ initialize platform backend +→ register global shortcut +→ initialize GTK application +→ begin clipboard monitoring +→ remain idle +``` + +Exact ordering may differ where required by GTK. + +Failures in optional features should not unnecessarily kill the entire app. + +Example: + +If global shortcut registration fails, the app may remain running and expose an error rather than corrupting data or crashing. + +--- + +# 32. Shutdown Behavior + +On clean shutdown: + +- stop clipboard watcher +- unregister hotkey +- flush necessary state +- close database cleanly +- terminate background resources + +No complicated shutdown orchestration. + +SQLite already handles most persistence. + +--- + +# 33. Ordering + +Default visible ordering: + +1. pinned entries receive appropriate prominence +2. otherwise most recently used/copied first + +When no search query exists, likely show: + +```text +Pinned entries +then +Recent entries +``` + +or interleave them with a clear pinned indicator. + +Choose whichever produces the fastest keyboard workflow. + +Do not maintain entirely separate screens for pinned/history. + +--- + +# 34. Entry Preview + +Rows must efficiently represent: + +- short snippets +- multiline text +- URLs +- code +- commands +- long paragraphs + +Normalize only presentation. + +Do not alter stored content. + +Suggested display: + +- collapse line breaks to spaces for row preview +- truncate after reasonable width +- optionally show line count or character count for large entries + +No syntax highlighting in v1. + +--- + +# 35. Search Empty State + +When search returns nothing: + +```text +No matching clipboard entries +``` + +Do not create elaborate empty-state artwork. + +--- + +# 36. First Launch + +First launch should require no setup. + +Expected: + +1. install +2. launch +3. clipboard tracking starts +4. `Super+V` works + +If `Super+V` conflicts with the desktop environment, detect/report it clearly. + +The application should remain usable through another invocation mechanism. + +--- + +# 37. Packaging + +Primary Linux packaging: + +**`.deb`** + +Target: + +- Ubuntu +- Linux Mint +- Debian-compatible systems where dependencies permit + +Package should install: + +- executable +- application `.desktop` file +- icon +- metadata +- optional autostart entry + +Later packaging may include: + +- AppImage +- Flatpak + +Priority: + +```text +.deb +→ AppImage +→ Flatpak +``` + +Do not make Flatpak the main v1 distribution because sandbox restrictions complicate global clipboard monitoring and input simulation. + +--- + +# 38. Application Identity + +Use one consistent application ID. + +For example: + +```text +io.clipbhoard.Clipbhoard +``` + +or another sensible reverse-domain identifier. + +Keep: + +- package name +- executable name +- desktop ID +- config directory +- database directory + +consistent. + +Executable suggestion: + +```text +clipbhoard +``` + +Display name: + +```text +Clipb(h)oard +``` + +--- + +# 39. X11 First + +For v1, X11 is the reference backend. + +Must support reliably: + +- observing clipboard changes +- reading clipboard text +- setting clipboard text +- registering global shortcut +- determining correct foreground/focus behavior as required +- injecting paste into previously active application + +Test specifically on current Linux Mint/Cinnamon X11. + +Do not claim Wayland parity until implemented and tested. + +--- + +# 40. Wayland + +Wayland support is future work. + +Important architectural fact: + +Wayland intentionally restricts: + +- arbitrary input injection +- global keyboard hooks +- some clipboard behavior + +Future Wayland support may require: + +- compositor protocols +- desktop portals +- compositor-specific integrations + +Do not hack around Wayland security boundaries. + +Keep platform interfaces clean enough that a real Wayland backend can be added later. + +--- + +# 41. Windows/macOS Future Support + +The following must remain platform-independent: + +- history model +- deduplication +- pinning +- limits +- SQLite persistence +- search +- configuration semantics +- application commands + +Only platform interaction should require replacement. + +GTK cross-platform support is a secondary concern. + +If future Windows/macOS adoption becomes important, replacing only the UI layer should remain possible. + +Do not build a UI abstraction framework today merely to guarantee this. + +--- + +# 42. Testing Strategy + +Focus tests on behavior that could destroy, duplicate, or reorder user data incorrectly. + +Unit tests should cover: + +- insert new entry +- duplicate entry moves to top +- duplicate preserves pin state +- pin +- unpin +- history limit +- pinned limit +- clear history preserves pins +- delete +- search ranking +- oversized entry rejection +- malformed configuration +- self-generated clipboard event suppression + +Integration tests should cover: + +- SQLite persistence +- migrations +- startup/restart +- global shortcut where automatable +- clipboard watching +- copy behavior +- paste behavior + +Manual acceptance tests are acceptable for inherently desktop-specific interactions. + +--- + +# 43. Core Invariants + +These invariants must always hold. + +## Invariant 1 + +There is never more than one canonical stored entry for identical clipboard text. + +## Invariant 2 + +Pinned entries are never deleted by normal history cleanup. + +## Invariant 3 + +Clear History never deletes pinned entries. + +## Invariant 4 + +Restoring an entry must not create duplicate history pollution. + +## Invariant 5 + +Storage failures must not silently pretend success. + +## Invariant 6 + +Clipboard content must never be transmitted over the network. + +## Invariant 7 + +Clipboard content must not appear in ordinary logs. + +## Invariant 8 + +The UI is not the source of truth. + +The core state/database owns history. + +## Invariant 9 + +OS-specific clipboard/input logic never leaks into core history logic. + +## Invariant 10 + +The app must remain useful even if the direct-paste action fails: content should still be copied to the clipboard. + +--- + +# 44. Performance Targets + +Treat these as goals rather than premature hard guarantees. + +Aim for: + +- idle CPU effectively zero +- low tens of MB of memory +- popup visible within ~100 ms under normal conditions +- search response effectively instantaneous for normal configured history sizes +- clipboard events processed immediately +- no polling loops burning CPU + +Prefer event-driven clipboard monitoring. + +Avoid frequent timers. + +--- + +# 45. Dependency Philosophy + +Use dependencies where they eliminate substantial complexity. + +Do not reimplement: + +- SQLite +- TOML parser +- robust error handling infrastructure +- proven fuzzy matching + +But inspect dependency cost. + +Avoid enormous dependency trees for tiny conveniences. + +Before adding a crate, ask: + +> Does this substantially simplify or harden the application? + +If not, write the small amount of code locally. + +--- + +# 46. Async / Threads + +Do not introduce async Rust simply because it exists. + +The program has relatively simple concurrency: + +- GTK main thread +- clipboard events +- lightweight database operations +- platform communication + +Use the simplest concurrency model compatible with GTK/platform APIs. + +The UI must never freeze due to blocking clipboard/platform work. + +Do not create a distributed system inside a clipboard manager. + +--- + +# 47. Security + +Treat clipboard data as sensitive local information. + +Basic requirements: + +- database stored in user-owned directories +- files created with appropriate user-only permissions where practical +- no elevated privileges +- never run as root +- no shell invocation with clipboard content +- no evaluation/execution of clipboard contents +- parameterized SQL queries +- safe handling of arbitrary Unicode +- safe handling of massive/malformed clipboard text + +Clipboard contents are data. + +Never treat them as executable instructions. + +--- + +# 48. Unicode + +Clipboard content may contain arbitrary Unicode. + +Support it correctly. + +Do not: + +- assume ASCII +- truncate in the middle of invalid UTF-8 boundaries +- corrupt emoji +- corrupt combining characters unnecessarily + +Rust strings and GTK text handling should make this manageable. + +--- + +# 49. Configuration Reload + +Live configuration reload is not required for v1. + +Changing settings may require: + +- immediate application of simple limits +- re-registering hotkeys +- restart for uncommon settings if necessary + +Prefer immediate application where simple. + +Do not add filesystem watchers solely for configuration reload. + +--- + +# 50. Versioning + +Use semantic versioning. + +Begin with something like: + +```text +0.1.0 +``` + +Expose: + +```bash +clipbhoard --version +``` + +Also provide: + +```bash +clipbhoard --help +``` + +Useful CLI options may eventually include: + +```text +--version +--help +--show +--quit +--debug +``` + +Keep CLI scope small. + +--- + +# 51. Diagnostics + +Provide enough diagnostics to debug installations. + +Useful command eventually: + +```bash +clipbhoard --diagnostics +``` + +Possible output: + +```text +Version: 0.1.0 +OS: Linux +Desktop: Cinnamon +Session: X11 +Database: OK +Config: OK +Clipboard backend: X11 +Hotkey backend: X11 +Registered hotkey: Super+V +Autostart: enabled +``` + +Never include clipboard contents. + +This is optional for earliest MVP, but highly desirable. + +--- + +# 52. Explicit Non-Goals for v1 + +Do **not** implement unless specifically requested later: + +- cloud sync +- accounts +- clipboard sync between computers +- AI features +- image clipboard history +- rich-text preview +- HTML preview +- file preview +- plugin ecosystem +- scripting +- macros +- transformations +- automatic translation +- OCR +- categories +- tags +- workspaces +- clipboard analytics +- themes beyond normal GTK/system appearance +- mobile companion +- browser extension +- collaboration +- clipboard sharing +- network server +- fuzzy-search configuration laboratory +- custom database engine + +Feature creep is a bug. + +--- + +# 53. MVP Completion Criteria + +The first real release is complete when all of these work reliably: + +1. application installs on Linux Mint using `.deb` +2. application launches at login +3. clipboard text changes are recorded +4. duplicate copies move existing entries to top +5. entries persist after reboot/restart +6. `Super+V` opens popup globally +7. popup search is fuzzy and instantaneous +8. arrow keys navigate +9. Enter copies selected entry +10. direct paste works into the previously focused X11 application +11. Delete removes entries +12. entries can be pinned/unpinned +13. Clear History preserves pins +14. history and pin limits are separately configurable +15. oversized clipboard entries are safely rejected +16. only one application instance runs +17. pause recording works +18. errors are logged +19. ordinary logs contain no clipboard data +20. the app remains low-resource and responsive + +Everything else is secondary. + +--- + +# 54. Implementation Order + +Implement in this sequence unless technical constraints require adjustment. + +## Phase 1 — Core + +Build and test: + +- entry model +- history ordering +- deduplication +- pin/unpin +- deletion +- clearing +- limits +- search + +No GUI necessary yet. + +## Phase 2 — Storage + +Implement: + +- SQLite database +- migrations +- repository layer +- persistence tests +- startup loading + +## Phase 3 — Linux/X11 Clipboard + +Implement: + +- read clipboard +- monitor clipboard +- write clipboard +- self-change suppression + +Test heavily. + +## Phase 4 — Minimal GTK UI + +Implement: + +- popup +- search box +- list +- selection +- keyboard navigation +- pin/delete actions + +Keep it ugly-but-functional initially. + +## Phase 5 — Global Hotkey + +Register default global shortcut. + +Popup should open correctly from arbitrary applications. + +## Phase 6 — Direct Paste + +Implement: + +```text +choose entry +→ set clipboard +→ close popup +→ focus previous app +→ paste +``` + +Handle failure safely. + +## Phase 7 — Config + +Add: + +- TOML +- limits +- shortcut +- autostart +- max entry size +- log level + +## Phase 8 — Reliability + +Add: + +- single-instance enforcement +- structured logging +- graceful recovery +- privacy behavior +- pause recording + +## Phase 9 — Packaging + +Produce `.deb`. + +Test: + +- clean install +- upgrade +- uninstall +- autostart +- config persistence +- database persistence + +## Phase 10 — Polish + +Only now improve: + +- spacing +- typography +- previews +- tiny settings UI +- icons +- diagnostics + +Do not polish unfinished architecture. + +--- + +# 55. Code Quality Rules + +The implementation agent should follow these rules. + +### Keep functions small. + +Prefer functions with one obvious responsibility. + +### Prefer explicit types for important domain concepts. + +Do not pass random booleans everywhere. + +### Do not use `unwrap()` in normal runtime paths. + +Tests and provably impossible invariants are exceptions. + +### Add context to errors. + +Use an idiomatic error strategy such as `thiserror` / `anyhow` where appropriate. + +### Avoid global mutable state. + +Use a clear application state owner. + +### Separate persistence from business logic. + +Core behavior should be testable without SQLite. + +### Separate UI from business logic. + +GTK callbacks should invoke application/core commands rather than implement history rules themselves. + +### Separate platform code. + +No X11 imports inside core modules. + +### Comment why, not what. + +Avoid comments explaining obvious Rust syntax. + +Document unusual platform constraints and invariants. + +--- + +# 56. Development Rule for AI Agents + +When implementing this project: + +**Do not expand scope without explicit instruction.** + +If a design decision is ambiguous: + +1. choose the simplest reliable option +2. preserve architecture boundaries +3. document the decision briefly +4. continue implementation + +Do not stop progress for trivial decisions. + +Do not redesign the application into a larger framework. + +Do not replace the agreed stack unless there is a concrete blocker. + +If proposing a dependency or architectural change, explain: + +```text +Problem +Current approach +Proposed change +Why it materially improves reliability/simplicity +Cost +``` + +--- + +# 57. Definition of Success + +Clipb(h)oard succeeds if the user forgets it exists until they need something they copied earlier. + +Then: + +```text +Super+V +→ type +→ Enter +``` + +and it works. + +Every time. + +The best version of Clipb(h)oard is not the version with the most features. + +It is the version where the core interaction is so fast and dependable that there is nothing left to think about. diff --git a/.agents/SHIP_CHECKLIST.md b/.agents/SHIP_CHECKLIST.md new file mode 100644 index 0000000..8a43036 --- /dev/null +++ b/.agents/SHIP_CHECKLIST.md @@ -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. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..76039ed --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +.git +target +Dockerfile +*.deb diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a5b00d3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1610 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "ansi_term" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" +dependencies = [ + "winapi", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cairo-rs" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e3bd0f4e25afa9cabc157908d14eeef9067d6448c49414d17b3fb55f0eadd0" +dependencies = [ + "bitflags 2.13.1", + "cairo-sys-rs", + "glib", + "libc", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "059cc746549898cbfd9a47754288e5a958756650ef4652bbb6c5f71a6bda4f8b" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-expr" +version = "0.20.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "2.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +dependencies = [ + "ansi_term", + "atty", + "bitflags 1.3.2", + "strsim", + "textwrap", + "unicode-width", + "vec_map", +] + +[[package]] +name = "clipbhoard" +version = "0.1.0" +dependencies = [ + "anyhow", + "dirs", + "fs2", + "glib", + "gtk4", + "ksni", + "rusqlite", + "serde", + "sha2", + "thiserror 2.0.20", + "toml 0.8.23", + "tracing", + "tracing-appender", + "tracing-subscriber", + "x11-clipboard", + "x11rb", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "dbus-codegen" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a49da9fdfbe872d4841d56605dc42efa5e6ca3291299b87f44e1cde91a28617c" +dependencies = [ + "clap", + "dbus", + "xml-rs", +] + +[[package]] +name = "dbus-tree" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f456e698ae8e54575e19ddb1f9b7bce2298568524f215496b248eb9498b4f508" +dependencies = [ + "dbus", +] + +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd242894c084f4beed508a56952750bce3e96e85eb68fdc153637daa163e10c" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b34f3b580c988bd217e9543a2de59823fafae369d1a055555e5f95a8b130b96" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk4" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4850c9d9c1aecd1a3eb14fadc1cdb0ac0a2298037e116264c7473e1740a32d60" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk4-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk4-sys" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f6eb95798e2b46f279cf59005daf297d5b69555428f185650d71974a910473a" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gio" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e27e276e7b6b8d50f6376ee7769a71133e80d093bdc363bd0af71664228b831" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "pin-project-lite", + "smallvec", +] + +[[package]] +name = "gio-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521e93a7e56fc89e84aea9a52cfc9436816a4b363b030260b699950ff1336c83" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "windows-sys 0.59.0", +] + +[[package]] +name = "glib" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffc4b6e352d4716d84d7dde562dd9aee2a7d48beb872dd9ece7f2d1515b2d683" +dependencies = [ + "bitflags 2.13.1", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "smallvec", +] + +[[package]] +name = "glib-macros" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8084af62f09475a3f529b1629c10c429d7600ee1398ae12dd3bf175d74e7145" +dependencies = [ + "heck", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ab79e1ed126803a8fb827e3de0e2ff95191912b8db65cee467edb56fc4cc215" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "gobject-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec9aca94bb73989e3cfdbf8f2e0f1f6da04db4d291c431f444838925c4c63eda" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "graphene-rs" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b86dfad7d14251c9acaf1de63bc8754b7e3b4e5b16777b6f5a748208fe9519b" +dependencies = [ + "glib", + "graphene-sys", + "libc", +] + +[[package]] +name = "graphene-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df583a85ba2d5e15e1797e40d666057b28bc2f60a67c9c24145e6db2cc3861ea" +dependencies = [ + "glib-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gsk4" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61f5e72f931c8c9f65fbfc89fe0ddc7746f147f822f127a53a9854666ac1f855" +dependencies = [ + "cairo-rs", + "gdk4", + "glib", + "graphene-rs", + "gsk4-sys", + "libc", + "pango", +] + +[[package]] +name = "gsk4-sys" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "755059de55fa6f85a46bde8caf03e2184c96bfda1f6206163c72fb0ea12436dc" +dependencies = [ + "cairo-sys-rs", + "gdk4-sys", + "glib-sys", + "gobject-sys", + "graphene-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk4" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f274dd0102c21c47bbfa8ebcb92d0464fab794a22fad6c3f3d5f165139a326d6" +dependencies = [ + "cairo-rs", + "field-offset", + "futures-channel", + "gdk-pixbuf", + "gdk4", + "gio", + "glib", + "graphene-rs", + "gsk4", + "gtk4-macros", + "gtk4-sys", + "libc", + "pango", +] + +[[package]] +name = "gtk4-macros" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ed1786c4703dd196baf7e103525ce0cf579b3a63a0570fe653b7ee6bac33999" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gtk4-sys" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41e03b01e54d77c310e1d98647d73f996d04b2f29b9121fe493ea525a7ec03d6" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk4-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "graphene-sys", + "gsk4-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "ksni" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4934310bdd016e55725482b8d35ac0c16fd058c1b955d8959aa2d953b918c85b" +dependencies = [ + "dbus", + "dbus-codegen", + "dbus-tree", + "thiserror 1.0.69", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libredox" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "pango" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6576b311f6df659397043a5fa8a021da8f72e34af180b44f7d57348de691ab5c" +dependencies = [ + "gio", + "glib", + "libc", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "186909673fc09be354555c302c0b3dcf753cd9fa08dcb8077fa663c80fb243fa" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.13+spec-1.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom", + "libredox", + "thiserror 2.0.20", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags 2.13.1", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "strsim" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml 1.1.5+spec-1.1.0", + "version-compare", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12c0ba9680044b4ce98d391a62094047eada0d64860b80166c39f4a6b5640785" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.4", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.20", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "x11-clipboard" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "662d74b3d77e396b8e5beb00b9cad6a9eccf40b2ef68cc858784b14c41d535a3" +dependencies = [ + "libc", + "x11rb", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "zerocopy" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7e06ef4 --- /dev/null +++ b/Cargo.toml @@ -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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ece08ea --- /dev/null +++ b/Dockerfile @@ -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/"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..0191b44 --- /dev/null +++ b/README.md @@ -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). diff --git a/data/io.clipbhoard.Clipbhoard-autostart.desktop b/data/io.clipbhoard.Clipbhoard-autostart.desktop new file mode 100644 index 0000000..e7474d9 --- /dev/null +++ b/data/io.clipbhoard.Clipbhoard-autostart.desktop @@ -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 diff --git a/data/io.clipbhoard.Clipbhoard.desktop b/data/io.clipbhoard.Clipbhoard.desktop new file mode 100644 index 0000000..c08a14d --- /dev/null +++ b/data/io.clipbhoard.Clipbhoard.desktop @@ -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 diff --git a/data/io.clipbhoard.Clipbhoard.svg b/data/io.clipbhoard.Clipbhoard.svg new file mode 100644 index 0000000..1aff001 --- /dev/null +++ b/data/io.clipbhoard.Clipbhoard.svg @@ -0,0 +1,4 @@ + + + + diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..c16b88f --- /dev/null +++ b/migrations/001_initial.sql @@ -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); diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh new file mode 100755 index 0000000..0b0da96 --- /dev/null +++ b/packaging/build-deb.sh @@ -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" diff --git a/packaging/clipbhoard.install b/packaging/clipbhoard.install new file mode 100644 index 0000000..42d92e8 --- /dev/null +++ b/packaging/clipbhoard.install @@ -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 diff --git a/packaging/clipbhoard.service b/packaging/clipbhoard.service new file mode 100644 index 0000000..8ddb6c9 --- /dev/null +++ b/packaging/clipbhoard.service @@ -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. diff --git a/packaging/debian/control b/packaging/debian/control new file mode 100644 index 0000000..38ad011 --- /dev/null +++ b/packaging/debian/control @@ -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. diff --git a/src/core/entry.rs b/src/core/entry.rs new file mode 100644 index 0000000..7e3dda8 --- /dev/null +++ b/src/core/entry.rs @@ -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, + } + } +} diff --git a/src/core/history.rs b/src/core/history.rs new file mode 100644 index 0000000..8bf3436 --- /dev/null +++ b/src/core/history.rs @@ -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, + 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, + 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 { + self.entries.values().cloned().collect() + } + + pub fn record(&mut self, content: &str, now: i64) -> Result { + 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 { + 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 { + 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 { + 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 + }) + ); + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs new file mode 100644 index 0000000..dc5964f --- /dev/null +++ b/src/core/mod.rs @@ -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; diff --git a/src/core/search.rs b/src/core/search.rs new file mode 100644 index 0000000..abc6be5 --- /dev/null +++ b/src/core/search.rs @@ -0,0 +1,77 @@ +use super::Entry; + +pub fn search(entries: &[Entry], query: &str) -> Vec { + 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 { + 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"); + } +} diff --git a/src/gui.rs b/src/gui.rs new file mode 100644 index 0000000..3e64e41 --- /dev/null +++ b/src/gui.rs @@ -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, + clipboard: X11Clipboard, + expected_change: ExpectedClipboardChange, + clipboard_watcher: Option, + hotkey: Option, + previous_focus: Option, + recording: bool, + show_requested: Arc, +} + +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>, + 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(©_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::() { + 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::>().join(" "); + let preview = if preview.chars().count() > 180 { + format!("{}…", preview.chars().take(180).collect::()) + } 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 { + list.selected_row()?.tooltip_text()?.parse::().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 +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..6075524 --- /dev/null +++ b/src/main.rs @@ -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 = 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(()) + } +} diff --git a/src/platform/linux/mod.rs b/src/platform/linux/mod.rs new file mode 100644 index 0000000..e1c9eb1 --- /dev/null +++ b/src/platform/linux/mod.rs @@ -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; diff --git a/src/platform/linux/x11_clipboard.rs b/src/platform/linux/x11_clipboard.rs new file mode 100644 index 0000000..c4fa244 --- /dev/null +++ b/src/platform/linux/x11_clipboard.rs @@ -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, +} + +impl X11Clipboard { + pub fn connect() -> Result { + 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 { + self.input + .as_ref() + .context("X11 paste injection is unavailable")? + .focused_window() + } +} + +impl ClipboardBackend for X11Clipboard { + fn read_text(&mut self) -> Result> { + 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) + } +} diff --git a/src/platform/linux/x11_events.rs b/src/platform/linux/x11_events.rs new file mode 100644 index 0000000..270cbfe --- /dev/null +++ b/src/platform/linux/x11_events.rs @@ -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, +} + +impl X11ClipboardWatcher { + pub fn start() -> Result { + 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) { + 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, +} + +impl X11Hotkey { + pub fn start(shortcut: &str) -> Result { + 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, + modifiers: xproto::ModMask, + triggered: Arc, +) { + 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 { + 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 { + 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)) +} diff --git a/src/platform/linux/x11_input.rs b/src/platform/linux/x11_input.rs new file mode 100644 index 0000000..82a9bc4 --- /dev/null +++ b/src/platform/linux/x11_input.rs @@ -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 { + 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 { + 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 { + 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") +} diff --git a/src/platform/mod.rs b/src/platform/mod.rs new file mode 100644 index 0000000..f001585 --- /dev/null +++ b/src/platform/mod.rs @@ -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>; + 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, +} + +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")); + } +} diff --git a/src/storage/migrations.rs b/src/storage/migrations.rs new file mode 100644 index 0000000..4821378 --- /dev/null +++ b/src/storage/migrations.rs @@ -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(()) +} diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 07ccf4e..fbd1e49 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -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<()> { diff --git a/src/tray.rs b/src/tray.rs new file mode 100644 index 0000000..db1deba --- /dev/null +++ b/src/tray.rs @@ -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> { + 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(()) +}