diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b146c5b..bf46036 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,7 +1,7 @@ # clap — Architecture Contract Native macOS clipboard manager. Local-first, no network, no telemetry. -This document is the binding contract between the three targets. Do not +This document is the binding contract between the targets. Do not deviate from public API signatures, schema, or IPC names without updating this file. @@ -83,16 +83,26 @@ CREATE INDEX IF NOT EXISTS idx_entry_tags_entry ON entry_tags(entry_id); ## Config keys (strings in `config` table, typed accessors in Settings) -- `text.max_entries` (Int, default 100_000) -- `text.max_size` (bytes, Int64, default 52_428_800 = 50MB) -- `image.max_entries` (Int, default 500) -- `image.max_size` (bytes, Int64, default 104_857_600 = 100MB) +All keys are constants on `ConfigKey` (CoreConstants.swift); defaults live in +`ClipboardStore.configDefaults`, so `clap config get` lists every key. + +- `text.max_entries` (Int, default 100_000) / `text.max_size` (bytes, default 50MB) +- `image.max_entries` (Int, default 500) / `image.max_size` (bytes, default 100MB) +- `shell.max_entries` (Int, default 50_000) / `shell.max_size` (bytes, default 10MB) +- `shell.enabled` ("0"/"1", default "1") — watch and ingest shell history +- `shell.histfile` (path, default "" = auto-detect `$HISTFILE`, ~/.zsh_history, ~/.bash_history) +- `shell.initial_imported` ("0"/"1", default "0") — app sets "1" after the + one-time history backfill succeeds - `monitoring.paused` ("0"/"1", default "0") - `exclusions` (JSON array of bundle ids, default `[]`) - `retention.days` (Int, 0 = never, default 0) - `launch_at_login` ("0"/"1", default "0") - `paste.on_copy` ("0"/"1", default "1") — after a UI copy, synthesize Cmd+V - into the frontmost app (needs Accessibility; copy-only fallback) + into the frontmost app (needs Accessibility; AppleScript fallback) +- `snippets.enabled` ("0"/"1", default "1") — snippet expansion keystroke tap +- `ui.hotkey` (preset id, default "cmd+shift+v"; must match + `HotKeyDefinition.defaultID`) +- `ui.panel_frame` (NSStringFromRect; no default — unset means "center") Size values accept human forms in CLI (`50MB`, `1GB`) — parse in ClapCore (`ByteSize.parse/format`). @@ -100,12 +110,12 @@ Size values accept human forms in CLI (`50MB`, `1GB`) — parse in ClapCore ## ClapCore public API (implement exactly) ```swift -public enum EntryType: String, Codable, Sendable { case text, image } +public enum EntryType: String, Codable, Sendable, CaseIterable { case text, image, shell } public struct ClipboardEntry: Identifiable, Sendable, Equatable { public let id: Int64 public let type: EntryType - public let content: String? // normalized text + public let content: String? // normalized text; OCR text for images public let imagePath: String? // relative path under images/ public let imageFormat: String? public let contentHash: String @@ -113,47 +123,60 @@ public struct ClipboardEntry: Identifiable, Sendable, Equatable { public let lastUsedAt: Date public let sizeBytes: Int64 public let isPinned: Bool + public let isFavorite: Bool public let useCount: Int public let sourceApp: String? + public let shortcut: String? // snippet trigger, e.g. ";email" + public let tags: [String] } public struct SearchQuery: Sendable { public var text: String? // FTS terms / phrase (quoted) public var regex: String? // regex pattern (mutually exclusive with text) - public var type: EntryType? // nil = all + public var type: EntryType? // single-type filter; wins over `types` + public var types: Set? // multi-type filter (Classic = text+image) public var pinnedOnly: Bool + public var favoriteOnly: Bool + public var tag: String? public var limit: Int public var offset: Int - public init(text: String? = nil, regex: String? = nil, type: EntryType? = nil, - pinnedOnly: Bool = false, limit: Int = 100, offset: Int = 0) + public var effectiveTypes: Set? { get } /// Parses UI/CLI query syntax: bare terms, "quoted phrase", - /// `regex:`, `type:text|image`. Unknown filters ignored. + /// `regex:`, `type:text|image|shell`, `tag:`. Unknown filters ignored. public static func parse(_ raw: String, limit: Int, offset: Int) -> SearchQuery } public struct StoreStats: Sendable { - public let textCount: Int, imageCount: Int - public let textBytes: Int64, imageBytes: Int64 + public let textCount: Int, imageCount: Int, shellCount: Int + public let textBytes: Int64, imageBytes: Int64, shellBytes: Int64 public let pinnedCount: Int public let eventsToday: Int, duplicatesAvoidedToday: Int public let oldestEntry: Date? } /// The single entry point. An actor so all DB access is serialized per process. -/// Multi-process safety comes from SQLite WAL + busy_timeout. +/// Multi-process safety comes from SQLite WAL + busy_timeout. Implementation is +/// split across ClipboardStore+Capture/+Query/+Mutations/+Maintenance/ +/// +Diagnostics/+Backup. public actor ClipboardStore { public init(dataDir: URL? = nil, now: @escaping @Sendable () -> Date = { Date() }, ocr: any OCREngine = VisionOCREngine()) throws public nonisolated let dataDir: URL - // Capture path (fast): normalize → hash → indexed lookup → insert or touch. - // Returns the entry and whether it was a duplicate (touched, not inserted). + // Capture (fast path): normalize → hash → indexed lookup → insert or touch. // OCR runs OUTSIDE the write transaction and off the actor executor. - @discardableResult - public func captureText(_ raw: String, sourceApp: String?) throws -> (entry: ClipboardEntry, wasDuplicate: Bool)? // nil if empty after normalization - @discardableResult + public func captureText(_ raw: String, sourceApp: String?) throws -> (entry: ClipboardEntry, wasDuplicate: Bool)? public func captureImage(data: Data, format: String, sourceApp: String?) async throws -> (entry: ClipboardEntry, wasDuplicate: Bool)? + public func updateOCRText(for entryID: Int64, ocrText: String) throws + + // Shell history (no daily clipboard counters; re-runs merge into use_count) + public func ingestShell(_ command: String, executedAt: Date?, source: String? = nil) throws -> (id: Int64, merged: Bool)? + public func ingestShellBatch(_ commands: [(text: String, executedAt: Date?)], source: String? = nil) throws -> (imported: Int, merged: Int) + + // Import (preserve metadata; duplicates merge) + public func importText(_ raw: String, createdAt: Date, lastUsedAt: Date, useCount: Int, pinned: Bool, sourceApp: String?, as type: EntryType = .text) async throws -> (id: Int64, merged: Bool)? + public func importImage(data: Data, format: String, createdAt: Date, lastUsedAt: Date, useCount: Int, pinned: Bool, sourceApp: String?) async throws -> (id: Int64, merged: Bool)? // Queries public func list(type: EntryType?, limit: Int, offset: Int) throws -> [ClipboardEntry] @@ -162,21 +185,33 @@ public actor ClipboardStore { public func count(type: EntryType?) throws -> Int // Mutations - public func touch(id: Int64) throws // bump last_used_at + use_count + public func touch(id: Int64) throws public func delete(id: Int64) throws -> Bool - public func deleteMatching(text: String) throws -> Int // exact normalized text + public func deleteMatching(text: String) throws -> Int public func deleteMatching(regexPattern: String) throws -> Int public func setPinned(_ pinned: Bool, id: Int64) throws -> Bool - public func clearAll() throws -> Int // returns removed count; also wipes image files - - // Maintenance (called by background workers / CLI) - public func enforceLimits() throws -> Int // LRU eviction, returns evicted count + public func setFavorite(_ favorite: Bool, id: Int64) throws -> Bool + public func setShortcut(_ shortcut: String?, id: Int64) throws -> Bool + public func allShortcuts() throws -> [String: String] + public func addTag(_ rawTag: String, entryID: Int64) throws -> Bool + public func removeTag(_ rawTag: String, entryID: Int64) throws -> Bool + public func setTags(_ tags: [String], entryID: Int64) throws + public func tags(for entryID: Int64) throws -> [String] + public func allTags() throws -> [(tag: String, count: Int)] + public func clearAll() throws -> Int // removes EVERYTHING incl. pinned/favorites; wipes image files + + // Maintenance (background workers / CLI) — pinned AND favorites exempt + public func enforceLimits() throws -> Int public func applyRetention() throws -> Int public func vacuumIfNeeded() throws + // Backup: backup.json (format "clap-backup" v1) + images/ folder + public func exportBackup(to directory: URL) throws -> Int + public func importBackup(from directory: URL) async throws -> (imported: Int, merged: Int, skipped: Int) + // Image helpers public func imageFileURL(for entry: ClipboardEntry) -> URL? - public func thumbnailURL(for entry: ClipboardEntry) throws -> URL? // generates lazily + public func thumbnailURL(for entry: ClipboardEntry) throws -> URL? // generates lazily, atomically // Settings / stats / doctor public func config(_ key: String) throws -> String? @@ -197,18 +232,20 @@ public enum ByteSize { public static func format(_ bytes: Int64) -> String } public enum SafeRegex { - /// Compiles NSRegularExpression; evaluates with a match-count/length guard. - /// Never throws at match time; invalid pattern → .invalidPattern error on compile. + /// Case-insensitive by default ((?-i) opts out). Length-capped pattern and + /// input slice; scans also have a wall-clock budget. public static func compile(_ pattern: String) throws -> NSRegularExpression } +public enum ShellHistoryParser { /* zsh (metafied, extended, multiline) + bash */ } public enum TextSummaries { - public static func singleLine(_ s: String, maxChars: Int) -> String // collapse ws/control chars, "…" truncate - public static func relativeTime(_ date: Date, now: Date) -> String // "now", "5m", "2h", "3d", else "yyyy-MM-dd" + public static func singleLine(_ s: String, maxChars: Int) -> String + public static func relativeTime(_ date: Date, now: Date) -> String } public enum ImageFormats { - public static func uti(forFormat format: String) -> String? // 'gif' → 'com.compuserve.gif' + public static func uti(forFormat format: String) -> String? } public enum ConfigKey { /* typed constants for every config-table key */ } +public enum ClapVersion { public static let current: String } // single version source /// Injectable OCR seam (Vision-backed default; tests use stubs). public protocol OCREngine: Sendable { @@ -216,13 +253,17 @@ public protocol OCREngine: Sendable { } public struct VisionOCREngine: OCREngine {} -// Shared clipboard content analysis (used by app UI and available to CLI): -public struct ParsedColor: Sendable, Equatable {} // r/g/b/a components +// Shared clipboard content analysis (used by the app's preview smart cards): +public struct ParsedColor: Sendable, Equatable {} public enum ColorParser { public static func parse(_ raw: String?) -> ParsedColor? } public enum CaseConverter { /* camel/pascal/snake/kebab/constant/upper/lower/title */ } public enum TextTransformer { /* Base64 + URL encode/decode with length guards */ } public struct JWTData: Sendable, Equatable { public static func parse(_ text: String?) -> JWTData? } public struct EpochData: Sendable, Equatable { public static func parse(_ text: String?) -> EpochData? } +public struct JSONData: Sendable, Equatable { public static func parse(_ text: String?) -> JSONData? } +public struct JSONRepairResult: Sendable, Equatable { public let repaired: String; public let fixes: [String] } +public enum JSONRepair { public static func repair(_ source: String) -> JSONRepairResult? } +public enum QRCodeBuilder { /* CoreImage QR, level M, <= 2000 bytes */ } // IPC names shared by both processes: public enum ClapIdentity { public static let bundleID = "com.spongycode.clap" } @@ -241,10 +282,10 @@ Notes: to avoid pathological latency. - Default ordering everywhere: pinned first optional in UI layer; store returns `ORDER BY last_used_at DESC`. -- Eviction: per-category count and byte limits applied to NON-PINNED rows only - (pinned entries live outside the budget — counting them would let enough - pinned rows permanently starve new captures); delete lowest `last_used_at` - where `is_pinned = 0`; entries larger than the whole category budget are +- Eviction: per-category (text/image/shell) count and byte limits applied to + rows that are neither pinned nor favorite (those live outside the budget — + counting them would let enough of them permanently starve new captures); + delete lowest `last_used_at` first; entries larger than the whole category budget are evicted first; delete image files + thumbnails for evicted images. - Capture rejects content larger than the category's max_size outright (a single oversize entry must never trigger history-wiping eviction). @@ -269,75 +310,95 @@ pgrep ClapApp), print hint to start the app. ## App specifics - Activation policy `.accessory` (no Dock icon). `LSUIElement` in packaged app. -- Hotkey: Carbon `RegisterEventHotKey` (cmd+shift, key `B` = kVK_ANSI_B). No - accessibility permission needed. +- Hotkey: Carbon `RegisterEventHotKey`, no Accessibility needed. Default + ⌘⇧V; 7 presets (`HotKeyDefinition.presets`: ⌘⇧V, ⌘⇧B, ⌘⇧C, ⌘⇧Space, + ⌥Space, ⌃⌥V, ⌃⌘V) chosen in Settings, persisted in `ui.hotkey`, and + re-registered live on `configChanged`. - Panel: borderless `NSPanel` (floating, `.nonactivatingPanel`, `.resizable`, - min 480×320), hosts SwiftUI. Movable by background drag, resizable at the - edges; the user-chosen frame is debounce-persisted to config key - `ui.panel_frame` and restored on every open (fallback: centered ~720×480 on - the mouse's screen when unset or the saved display is gone). Esc closes. - Opens with search focused. -- Preview: a non-key child `NSPanel` follows the selection (200 ms debounce): - placed right of the panel, else left, else below, else above. Shows - scrollable text / fitted image plus metadata (id + transient-marked Copy ID - button, type, size, created/last-used, use count, source app name, pin). - Hidden with the panel; repositioned on move/resize. + min 460×280) hosting SwiftUI, with Liquid Glass (`NSGlassEffectView`) on + macOS 26 and `NSVisualEffectView` fallback. Movable by background drag; + resized via `EdgeResizeOverlay` handles (9pt edges / 20pt corners). The + user-chosen frame is debounce-persisted to `ui.panel_frame` and restored on + open (fallback: centered on the mouse's screen). Esc closes. Opens with + search focused. +- Tabs: Classic (text+image), Shell, Favs (favorites, or one tag pinboard via + the tag pill bar), Media (image grid). +- Preview (slideout): the panel window itself animates wider (0.28 s) to + reveal a preview pane, auto-opening 1 s after a selection; left/right side + chosen by screen room; draggable divider (content min 460, pane min 320). + Shows scrollable text (TextKit 2 for ≥1000 chars, with search-match + highlighting) or the image, smart cards (color, Base64/URL, JWT, epoch, + JSON pretty/minify/repair, OCR, QR), an Actions row (case/encoding + transforms, QR, snippet shortcut, tags), and metadata (id + transient-marked + Copy ID button, type, dimensions, size, first/last used, use count, source + app, tags, pin/favorite). - Pasteboard monitor: poll `NSPasteboard.general.changeCount` every 150 ms on a background task; on change, read text/image off the main thread, skip when - paused, skip when frontmost app is in exclusions, skip transient/concealed - pasteboard types (`org.nspasteboard.TransientType`, - `org.nspasteboard.ConcealedType`), then call `store.captureText/Image`. - When clap itself writes to the pasteboard (copy action), pre-bump the - expected changeCount so its own write is only used to touch recency, not - re-captured as new. + paused, skip when frontmost app is in exclusions, skip transient/concealed/ + auto-generated pasteboard types, then call `store.captureText/Image`. When + clap itself writes (copy action) it calls expect/confirm with the resulting + changeCount so its own write only touches recency, while a foreign copy in + the same poll window is still captured. +- Shell history monitor: one-time backfill on first launch (sets + `shell.initial_imported`), then polls the history file every 2 s reading only + appended bytes (inode change or shrink → re-anchor at EOF; partial trailing + line carried over). +- Snippet expander: CGEvent keystroke tap (needs Accessibility; retries every + 2 s until granted), 40-char buffer; on a `shortcut` match it deletes the + trigger and pastes the expansion. - UI lists are paged: fetch 100 rows, fetch more as selection/scroll nears the - end. Media tab = LazyVGrid of thumbnails. -- Keys: ↑/↓ navigate, Enter copy+close, Esc close, Cmd+F focus search, - Cmd+1-Cmd+4 tabs, Cmd+P pin toggle, Cmd+D or Option+Delete delete (the - latter yields to delete-word while editing a non-empty search), hover - selects a row (pointer-driven selection never auto-scrolls), Cmd+R - regex-mode toggle - (also a `.*` button beside the search field; in regex mode the whole query - is the pattern). Number keys ①-⑨ shown for the first 9 rows; pressing 1-9 - copies that row. -- Copy action: write to NSPasteboard (declare types properly), `touch(id:)`, - close panel; when `paste.on_copy` is enabled, then synthesize Cmd+V into the - frontmost app (Paster, CGEvent; requires Accessibility, degrades to - copy-only with a one-time system prompt). -- Background workers (in app): periodic `enforceLimits`, `applyRetention`, - thumbnail pre-generation, `vacuumIfNeeded` — all via detached low-priority - tasks, never on the main actor. -- Menu bar: clipboard icon; menu = Open (Cmd+Shift+V hint), Pause/Resume - Monitoring (reflects state), Recent (top 5 text previews, truncated 40 chars), - Settings…, Quit. -- Settings window (SwiftUI): limits (entries + sizes with MB fields), retention - picker, launch at login (SMAppService.mainApp), exclusions list (add via - bundle id text field + list of running apps), pause toggle. + end. +- Keys: ↑/↓ navigate, Enter copy+close(+paste), Esc close, ⌘F focus search, + ⌘1–⌘4 tabs (Classic/Shell/Favs/Media), ⌘P pin, ⌘S or ⌘B favorite, + ⌘D or ⌥⌫ delete (⌥⌫ yields to delete-word while editing a non-empty + search), ⌘R regex toggle (also the `.*` button). Hover selects a row; + pointer-driven selection never auto-scrolls. +- Copy action: write to NSPasteboard, `touch(id:)`, close panel; when + `paste.on_copy` is enabled, synthesize ⌘V into the frontmost app (Paster: + CGEvent, AppleScript fallback, rate-limited Accessibility prompt). Pop sound + + trackpad haptic feedback on success. +- Background workers (in app): `enforceLimits` + `applyRetention` at launch and + every 5 minutes, hourly `vacuumIfNeeded`, thumbnail warmup — all detached, + low priority, never on the main actor. +- Menu bar: template icon; menu = Open (shows current hotkey), Pause/Resume + Monitoring, Recent (top 5), Settings…, Quit. +- Settings window (SwiftUI): limits per type with usage pills, shell history + section, retention picker, hotkey preset picker, launch at login + (SMAppService.mainApp), paste-on-select, snippets toggle, exclusions, + backup/restore, and a live Health section (hotkey registration, snippet tap). ## CLI command surface ``` -clap open UI (notify app) -clap list [--images] [--limit N] [--offset N] -clap search [--regex ] [--type text|image] [--limit N] -clap get +clap open UI (notify app; launches it if found next to the CLI) +clap list [--images|--shell] [--favorites] [--tag ] [--limit N] [--offset N] [--json] +clap search [--regex ] [--type text|image|shell] [--tag ] [--limit N] [--offset N] [--json] +clap get [--json] clap copy -clap add | - insert entry (- reads stdin); alias: clap in +clap add | - insert entry (- reads stdin); alias: clap in clap delete | --text | --regex -clap out [ | ] alias of delete +clap out [ | ] alias of delete clap pin / clap unpin -clap clear [--force] -clap stats +clap fav / clap unfav aliases: favorite / unfavorite +clap tag add|remove|set / clap tag list [id] / clap tags +clap backup / clap restore +clap clear [--force] deletes ALL entries, pinned and favorites included +clap stats [--json] clap config get [key] / clap config set clap doctor clap import maccy [--db ] [--dry-run] +clap import shell-history [--file ] [--dry-run] clap pause / clap resume ``` +- Command logic lives in `ClapCLIKit`; `Sources/ClapCLI/Main.swift` only calls + `ClapCLI.main()`. - Output: aligned plain text; single-line previews truncated to 60 chars with - control chars stripped. `--json` flag on list/search/get/stats for scripting. + control chars stripped. `--json` on list/search/get/stats for scripting; + entry JSON includes isPinned, isFavorite, tags, and shortcut. - `copy`: read entry; text → NSPasteboard string; image → load file data, set - as image data with correct type; then `touch(id:)` and post `storeChanged`. + as image data with correct type; `touch(id:)` for shell entries, or when the + app isn't running (otherwise the app's monitor records the re-copy). - All commands honor `--data-dir ` and `CLAP_DATA_DIR`. - Exit codes: 0 ok, 1 not found / no match, 2 usage error. diff --git a/README.md b/README.md index 28018ad..4787a76 100644 --- a/README.md +++ b/README.md @@ -34,18 +34,24 @@ --- -## Screenshots +## See it in action

- Classic Tab — Clipboard History & Previews - Media Tab — Image History & Tags + + clap in 30 seconds — shortcut, search, OCR, smart cards, shell history, privacy +

- Shell Tab — Shell Command History - Settings Window — Limits & Customization + Classic tab — clipboard history with pins, favorites, tags and a JSON preview + Media tab — image grid with OCR text extracted from a screenshot

+

+ Settings with live usage and health checks; the Favs pinboard in front of the Shell tab; smart cards for JWT, epoch timestamps, colors and JSON repair +

+ + --- ## Installation @@ -93,7 +99,7 @@ For development & testing: ```bash swift build # Build ClapApp + clap CLI -swift test # Run 92 unit tests +swift test # Run the test suites (core, CLI, app) .build/debug/ClapApp # Run debug app directly ``` @@ -130,7 +136,7 @@ Press **⌘⇧V** to open the panel (configurable in Settings to `⌘⇧B`, `⌘ ```bash clap # Open clipboard UI -clap list [--images] [--shell] [--limit N] # List recent clipboard or shell entries +clap list [--images|--shell] [--favorites] # List recent entries (also --tag, --limit, --json) clap search [--type text|image|shell] # Full-text search clap search --regex "^docker.*" # Regex search clap get # Show entry (pipe-friendly raw output) @@ -139,8 +145,10 @@ clap add | - # Insert an entry (alias: clap echo "piped" | clap add - # Insert from a pipe clap delete | --text | --regex # Delete entries (alias: clap out) clap pin / clap unpin # Pin/unpin entries +clap fav / clap unfav # Favorite/unfavorite entries +clap tag add|remove / clap tags # Tags & pinboards clap backup / clap restore # Full-history backup & restore -clap clear [--force] # Wipe history (preserves pinned) +clap clear [--force] # Wipe ALL history, pinned and favorites included clap stats [--json] # Storage and activity metrics clap config get [key] / set # Manage limits, retention, exclusions clap doctor # System diagnostic checks diff --git a/Resources/reel/clap_reel.mp4 b/Resources/reel/clap_reel.mp4 new file mode 100644 index 0000000..4f327b3 Binary files /dev/null and b/Resources/reel/clap_reel.mp4 differ diff --git a/Resources/reel/clap_reel_preview.webp b/Resources/reel/clap_reel_preview.webp new file mode 100644 index 0000000..d9852f6 Binary files /dev/null and b/Resources/reel/clap_reel_preview.webp differ diff --git a/Resources/screens/classic_items.png b/Resources/screens/classic_items.png index 80183e9..2f4658a 100644 Binary files a/Resources/screens/classic_items.png and b/Resources/screens/classic_items.png differ diff --git a/Resources/screens/features_overview.png b/Resources/screens/features_overview.png new file mode 100644 index 0000000..e38e51c Binary files /dev/null and b/Resources/screens/features_overview.png differ diff --git a/Resources/screens/media_items.png b/Resources/screens/media_items.png index a7cb7e4..571cb69 100644 Binary files a/Resources/screens/media_items.png and b/Resources/screens/media_items.png differ diff --git a/Resources/screens/settings.png b/Resources/screens/settings.png deleted file mode 100644 index 44f5ccb..0000000 Binary files a/Resources/screens/settings.png and /dev/null differ diff --git a/Resources/screens/shell_items.png b/Resources/screens/shell_items.png deleted file mode 100644 index 0453c6a..0000000 Binary files a/Resources/screens/shell_items.png and /dev/null differ diff --git a/Sources/ClapApp/AppDelegate.swift b/Sources/ClapApp/AppDelegate.swift index e32602d..3e7330a 100644 --- a/Sources/ClapApp/AppDelegate.swift +++ b/Sources/ClapApp/AppDelegate.swift @@ -124,17 +124,47 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // rendering of clipboard history. #if DEBUG if let snapshotDir = ProcessInfo.processInfo.environment["CLAP_DEBUG_SNAPSHOT_DIR"] { + // Scriptable for README screenshots (all optional): + // CLAP_DEBUG_SNAPSHOT_TAB classic|shell|favs|media + // CLAP_DEBUG_SNAPSHOT_TAG pinboard tag for the Favs tab + // CLAP_DEBUG_SNAPSHOT_QUERY search text to type + // CLAP_DEBUG_SNAPSHOT_SELECT_ID entry id to select (default: row one) + // CLAP_DEBUG_SNAPSHOT_SETTINGS "1" = open the Settings window instead + let env = ProcessInfo.processInfo.environment DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in guard let self else { return } + if env["CLAP_DEBUG_SNAPSHOT_SETTINGS"] == "1" { + self.settingsController.show() + return + } self.panelController.show() - if ProcessInfo.processInfo.environment["CLAP_DEBUG_SNAPSHOT_TAB"] == "media" { - self.appState.selectTab(.media) + switch env["CLAP_DEBUG_SNAPSHOT_TAB"] { + case "media": self.appState.selectTab(.media) + case "shell": self.appState.selectTab(.shell) + case "favs": self.appState.selectTab(.favs) + default: break } - // Select the first row so the preview window appears too. - DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { - self.appState.moveSelection(1) + if let tag = env["CLAP_DEBUG_SNAPSHOT_TAG"] { self.appState.selectTag(tag) } + if let query = env["CLAP_DEBUG_SNAPSHOT_QUERY"] { self.appState.queryChanged(query) } + if let raw = env["CLAP_DEBUG_SNAPSHOT_SELECT_ID"], let id = Int64(raw) { + // Wait until the entry is actually loaded: selecting before + // the reload lands gets overwritten by its row-one default. + Task { @MainActor in + for _ in 0..<30 where !self.appState.flatRows.contains(where: { $0.id == id }) { + try? await Task.sleep(nanoseconds: 100_000_000) + } + try? await Task.sleep(nanoseconds: 200_000_000) + self.appState.selectedID = id + } + } else { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { + // The reload usually auto-selects row one already. + if self.appState.selectedID == nil { self.appState.moveSelection(1) } + } } - DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { + // Selection at +0.7s, preview auto-opens 1s later and animates + // for 0.28s — snapshot well after it has settled. + DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { let dir = URL(fileURLWithPath: snapshotDir, isDirectory: true) self.panelController.writeSnapshot(to: dir.appendingPathComponent("panel.png")) } diff --git a/Sources/ClapApp/EdgeResizeOverlay.swift b/Sources/ClapApp/EdgeResizeOverlay.swift index 78b90fd..b4fce25 100644 --- a/Sources/ClapApp/EdgeResizeOverlay.swift +++ b/Sources/ClapApp/EdgeResizeOverlay.swift @@ -12,11 +12,28 @@ enum ResizeDirection { case topLeft, topRight, bottomLeft, bottomRight var cursor: NSCursor { + if #available(macOS 15.0, *) { + return .frameResize(position: frameResizePosition, directions: .all) + } switch self { case .left, .right: return .resizeLeftRight case .top, .bottom: return .resizeUpDown - case .topLeft, .bottomRight: return .closedHand - case .topRight, .bottomLeft: return .closedHand + // No public diagonal resize cursor before macOS 15. + case .topLeft, .topRight, .bottomLeft, .bottomRight: return .crosshair + } + } + + @available(macOS 15.0, *) + private var frameResizePosition: NSCursor.FrameResizePosition { + switch self { + case .left: return .left + case .right: return .right + case .top: return .top + case .bottom: return .bottom + case .topLeft: return .topLeft + case .topRight: return .topRight + case .bottomLeft: return .bottomLeft + case .bottomRight: return .bottomRight } } } diff --git a/Sources/ClapApp/MenuBar.swift b/Sources/ClapApp/MenuBar.swift index c725667..beeb3c0 100644 --- a/Sources/ClapApp/MenuBar.swift +++ b/Sources/ClapApp/MenuBar.swift @@ -60,7 +60,7 @@ final class MenuBarController: NSObject, NSMenuDelegate { guard let self else { return } let recent = (try? await self.store.list(type: .text, limit: 5, offset: 0)) ?? [] let paused = ((try? await self.store.config(ConfigKey.monitoringPaused)) ?? "0") == "1" - let hotkeyStr = ((try? await self.store.config("ui.hotkey")) ?? "cmd+shift+v") + let hotkeyStr = ((try? await self.store.config(ConfigKey.uiHotkey)) ?? HotKeyDefinition.defaultID) self.currentShortcut = HotKeyDefinition.find(hotkeyStr) self.cachedRecent = recent self.cachedPaused = paused diff --git a/Sources/ClapApp/Panel.swift b/Sources/ClapApp/Panel.swift index a864fdb..fe10a08 100644 --- a/Sources/ClapApp/Panel.swift +++ b/Sources/ClapApp/Panel.swift @@ -8,9 +8,13 @@ final class ClapPanel: NSPanel { override var canBecomeKey: Bool { true } override var canBecomeMain: Bool { false } + /// Set by PanelController so every close path collapses the preview and + /// records the frame, rather than a bare orderOut leaving it widened. + var onCancel: (() -> Void)? + /// Esc via the responder chain. override func cancelOperation(_ sender: Any?) { - orderOut(nil) + if let onCancel { onCancel() } else { orderOut(nil) } } } @@ -65,6 +69,7 @@ final class PanelController: NSObject, NSWindowDelegate { panel.delegate = self panel.contentView = NSHostingView(rootView: ContentView().environmentObject(appState)) + panel.onCancel = { [weak self] in self?.hide() } installKeyMonitor() appState.slideout.window = panel @@ -91,8 +96,9 @@ final class PanelController: NSObject, NSWindowDelegate { Task { [weak self] in guard let raw = try? await appState.store.config(Self.frameConfigKey) else { return } let rect = NSRectFromString(raw) + guard let self, self.savedFrame == nil else { return } if rect.width >= Self.minPanelSize.width, rect.height >= Self.minPanelSize.height { - self?.savedFrame = rect + self.savedFrame = rect } } } @@ -117,26 +123,32 @@ final class PanelController: NSObject, NSWindowDelegate { front.bundleIdentifier != Bundle.main.bundleIdentifier { previousApp = front } - appState.panelWillShow() + appState.panelWillShow() // collapses any open preview first suppressFrameSave = true - var targetSize = savedFrame?.size ?? Self.panelSize - targetSize.width = appState.slideout.contentWidth - - if let saved = savedFrame, frameIsOnAVisibleScreen(saved) { - // Reopen exactly where the user last dragged/resized it. - var reopenFrame = saved - reopenFrame.size.width = targetSize.width - panel.setFrame(reopenFrame, display: false) + let slideout = appState.slideout + if let saved = savedFrame { + // The saved frame is the source of truth for the list width; + // contentWidth starts at a default every launch. + slideout.contentWidth = max(slideout.minimumContentWidth, saved.width) + } + let targetSize = NSSize(width: slideout.contentWidth, + height: savedFrame?.height ?? Self.panelSize.height) + + if let saved = savedFrame, let screen = Self.bestScreen(for: saved) { + // Reopen where the user left it, nudged fully on-screen (a display + // may have been rearranged or unplugged since). + let reopen = NSRect(origin: saved.origin, size: targetSize) + panel.setFrame(Self.clamp(reopen, to: screen.visibleFrame), display: false) } else if let screen = screenWithMouse() { let frame = screen.visibleFrame let origin = NSPoint( x: frame.midX - targetSize.width / 2, y: frame.midY - targetSize.height / 2 ) - panel.setFrame(NSRect(origin: origin, size: targetSize), display: false) + panel.setFrame(Self.clamp(NSRect(origin: origin, size: targetSize), to: frame), + display: false) } suppressFrameSave = false - appState.slideout.closePreview(animated: false) if appState.selectedEntry != nil { appState.slideout.startAutoOpen() } @@ -177,21 +189,40 @@ final class PanelController: NSObject, NSWindowDelegate { return NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) } ?? NSScreen.main } - /// A frame counts as restorable when a meaningful part of it is on some - /// screen (the saved display may have been unplugged). - private func frameIsOnAVisibleScreen(_ frame: NSRect) -> Bool { - NSScreen.screens.contains { screen in - let visible = screen.visibleFrame.intersection(frame) - return visible.width >= 100 && visible.height >= 100 + /// The screen showing the largest part of `frame`, or nil when it is on + /// none of them (display unplugged) — the caller then re-centers. + static func bestScreen(for frame: NSRect) -> NSScreen? { + var best: NSScreen? + var bestArea: CGFloat = 0 + for screen in NSScreen.screens { + let overlap = screen.visibleFrame.intersection(frame) + guard !overlap.isNull else { continue } + let area = overlap.width * overlap.height + if area > bestArea { + best = screen + bestArea = area + } } + return best + } + + /// Shrinks `frame` to fit `bounds` if needed, then slides it inside. + static func clamp(_ frame: NSRect, to bounds: NSRect) -> NSRect { + var result = frame + result.size.width = min(result.width, bounds.width) + result.size.height = min(result.height, bounds.height) + result.origin.x = min(max(result.minX, bounds.minX), bounds.maxX - result.width) + result.origin.y = min(max(result.minY, bounds.minY), bounds.maxY - result.height) + return result } private func rememberCurrentFrame() { - guard !suppressFrameSave, panel.isVisible else { return } - var frame = panel.frame - if appState.slideout.state.isOpen { - frame.size.width = appState.slideout.contentWidth - } + let slideout = appState.slideout + // Preview open/close animations move and resize the window without + // the user doing anything; those intermediate frames must not be + // saved. The list itself doesn't move during them. + guard !suppressFrameSave, panel.isVisible, !slideout.state.isAnimating else { return } + let frame = slideout.listFrame(of: panel) savedFrame = frame // Debounced: windowDidMove fires continuously while dragging. frameSaveTask?.cancel() @@ -216,10 +247,15 @@ final class PanelController: NSObject, NSWindowDelegate { func windowDidResize(_ notification: Notification) { // Live-sync while dragging an edge with the preview open; the list // absorbs the delta and the pane keeps its width. - guard appState.slideout.state == .open else { return } - appState.slideout.contentWidth = max( - appState.slideout.minimumContentWidth, - panel.frame.width - appState.slideout.slideoutWidth) + if appState.slideout.state == .open { + appState.slideout.contentWidth = max( + appState.slideout.minimumContentWidth, + panel.frame.width - appState.slideout.slideoutWidth) + } + // The edge-resize handles call setFrame directly, which never ends a + // "live resize", and top/right drags don't move the origin — so + // windowDidMove alone would miss them. Saves are debounced. + rememberCurrentFrame() } func windowDidEndLiveResize(_ notification: Notification) { diff --git a/Sources/ClapApp/PreviewCards.swift b/Sources/ClapApp/PreviewCards.swift index cd9558f..dc6ad3c 100644 --- a/Sources/ClapApp/PreviewCards.swift +++ b/Sources/ClapApp/PreviewCards.swift @@ -123,6 +123,7 @@ struct JWTCardView: View { Text("JWT Inspector") .font(.system(size: 12.5, weight: .bold)) .foregroundStyle(.primary) + .fixedSize() Text(jwt.algorithm) .font(.system(size: 10, weight: .semibold, design: .monospaced)) @@ -132,6 +133,7 @@ struct JWTCardView: View { Capsule() .fill(Color.primary.opacity(0.08)) ) + .fixedSize() if let isExp = jwt.isExpired { HStack(spacing: 3) { @@ -148,6 +150,7 @@ struct JWTCardView: View { Capsule() .fill((isExp ? Color.red : Color.green).opacity(0.12)) ) + .fixedSize() } Spacer() @@ -158,9 +161,14 @@ struct JWTCardView: View { } label: { Label("Copy JSON", systemImage: "doc.on.doc") .font(.system(size: 10)) + // Icon-only: title + both badges + a text label don't + // fit the minimum pane width without truncation. + .labelStyle(.iconOnly) } .buttonStyle(.bordered) .controlSize(.mini) + .fixedSize() + .help("Copy payload or header JSON") } if jwt.subject != nil || jwt.issuer != nil || jwt.expirationDate != nil { @@ -191,7 +199,12 @@ struct JWTCardView: View { Text(jwt.payloadJSON) .font(.system(size: 11, design: .monospaced)) - .textSelection(.enabled) + // No .textSelection here: on macOS a selectable multi-line + // Text in this card collapses to its first line ("{…"). + // "Copy JSON" covers copying. Capped so huge tokens can't + // swallow the pane. + .lineLimit(10) + .fixedSize(horizontal: false, vertical: true) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background( diff --git a/Sources/ClapApp/PreviewPanel.swift b/Sources/ClapApp/PreviewPanel.swift index 40f11d3..4e5ea3b 100644 --- a/Sources/ClapApp/PreviewPanel.swift +++ b/Sources/ClapApp/PreviewPanel.swift @@ -171,6 +171,7 @@ struct PreviewView: View { @State private var image: NSImage? @State private var parsed: ParsedEntryContent = .empty @State private var qrVisible = false + @State private var idCopied = false var body: some View { VStack(alignment: .leading, spacing: 0) { @@ -347,6 +348,19 @@ struct PreviewView: View { } } } + GridRow { + metaLabel("ID") + HStack(spacing: 6) { + Text(String(entry.id)) + .font(.system(size: 12, design: .monospaced)) + .textSelection(.enabled) + IconActionButton(systemImage: idCopied ? "checkmark" : "doc.on.doc", + help: "Copy id for CLI use (e.g. clap get \(entry.id))", + isSelected: idCopied) { + copyID() + } + } + } GridRow { metaLabel("Type") Text(entryTypeDescription) @@ -435,6 +449,20 @@ struct PreviewView: View { // MARK: Helpers + /// Copies the numeric id marked transient, so clap's own pasteboard + /// monitor doesn't record the digits as a new history entry. + private func copyID() { + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + pasteboard.setString(String(entry.id), forType: .string) + pasteboard.setString("", forType: NSPasteboard.PasteboardType("org.nspasteboard.TransientType")) + idCopied = true + Task { @MainActor in + try? await Task.sleep(nanoseconds: 1_500_000_000) + idCopied = false + } + } + private var highlightedDisplayedText: AttributedString { SearchHighlighter.highlight( text: displayedText, diff --git a/Sources/ClapApp/SettingsView+Persistence.swift b/Sources/ClapApp/SettingsView+Persistence.swift index 0e65903..52c45d3 100644 --- a/Sources/ClapApp/SettingsView+Persistence.swift +++ b/Sources/ClapApp/SettingsView+Persistence.swift @@ -48,7 +48,7 @@ extension SettingsView { // MARK: - Component health - private func refreshHealth() { + func refreshHealth() { guard let health = healthProvider?() else { return } hotKeyOK = health.hotKeyOK snippetTapOK = health.snippetTapOK diff --git a/Sources/ClapApp/SettingsView.swift b/Sources/ClapApp/SettingsView.swift index daf50dd..d3523d4 100644 --- a/Sources/ClapApp/SettingsView.swift +++ b/Sources/ClapApp/SettingsView.swift @@ -93,6 +93,15 @@ struct SettingsView: View { .task { await load() } + .task { + // Health can change while Settings is open (the snippet tap + // retries until Accessibility is granted; the hotkey + // re-registers on preset changes). Cancelled on disappear. + while !Task.isCancelled { + refreshHealth() + try? await Task.sleep(nanoseconds: 2_000_000_000) + } + } .onReceive(DistributedNotificationCenter.default().publisher(for: IPC.Name.storeChanged.notification)) { _ in Task { await refreshStats() } } diff --git a/Sources/ClapApp/SlideoutController.swift b/Sources/ClapApp/SlideoutController.swift index 4a32dfc..0aaea65 100644 --- a/Sources/ClapApp/SlideoutController.swift +++ b/Sources/ClapApp/SlideoutController.swift @@ -102,12 +102,30 @@ public final class SlideoutController: ObservableObject { public func computePlacement(window: NSWindow, for size: NSSize) -> SlideoutPlacement { guard let screen = window.screen?.visibleFrame else { return placement } - let windowFrame = window.frame - if windowFrame.minX + size.width > screen.maxX { - return .left - } else { - return .right + return Self.placement(listFrame: window.frame, totalWidth: size.width, screen: screen) + } + + /// Right if the widened window fits on screen, else left if that fits, + /// else whichever side overflows less (a narrow screen fits neither). + static func placement(listFrame: NSRect, totalWidth: CGFloat, screen: NSRect) -> SlideoutPlacement { + let extra = totalWidth - listFrame.width + let rightOverflow = max(0, listFrame.minX + totalWidth - screen.maxX) + let leftOverflow = max(0, screen.minX - (listFrame.minX - extra)) + if rightOverflow == 0 { return .right } + if leftOverflow == 0 { return .left } + return leftOverflow < rightOverflow ? .left : .right + } + + /// Screen rect of the list column alone, whatever the preview's state. + /// This is what gets persisted as the panel's frame: the list is the + /// anchor, the preview is transient. + func listFrame(of window: NSWindow) -> NSRect { + var frame = window.frame + if state.isOpen, placement == .left { + frame.origin.x = frame.maxX - contentWidth } + frame.size.width = state.isOpen ? contentWidth : frame.width + return frame } public func openPreview(animated: Bool = true) { @@ -153,7 +171,10 @@ public final class SlideoutController: ObservableObject { } public func closePreview(animated: Bool = true) { - guard state != .closed, state != .closing else { return } + guard state != .closed else { return } + // An animated close already in flight is fine to leave running; an + // instant close must still take over from it (e.g. hiding mid-close). + if animated, state == .closing { return } guard let window else { return } let targetSize = NSSize(width: contentWidth, height: window.frame.height) @@ -184,12 +205,36 @@ public final class SlideoutController: ObservableObject { } } } else { - var newOrigin = window.frame.origin - if placement == .left && state == .open { + closeImmediately(window: window, targetSize: targetSize) + } + } + + /// Instant close from ANY non-closed state. Handles hiding mid-animation: + /// the list's position comes from the pre-animation origin rather than + /// the half-animated frame, and the in-flight frame animation is + /// superseded so it can't keep widening the window after we've settled it. + private func closeImmediately(window: NSWindow, targetSize: NSSize) { + var newOrigin = window.frame.origin + switch state { + case .opening, .closing: + // Both animations started from the list's own origin. + newOrigin = windowAnimationOrigin ?? newOrigin + if state == .closing, placement == .left { newOrigin.x += slideoutWidth } - state = .closed - window.setFrame(NSRect(origin: newOrigin, size: targetSize), display: true) + case .open: + if placement == .left { newOrigin.x += slideoutWidth } + case .closed: + break + } + state = .closed + let target = NSRect(origin: newOrigin, size: targetSize) + // A zero-duration animator write replaces any running frame animation; + // a plain setFrame would be overwritten by the animation's next tick. + NSAnimationContext.runAnimationGroup { context in + context.duration = 0 + window.animator().setFrame(target, display: true) } + window.setFrame(target, display: true) } } diff --git a/Sources/ClapCLIKit/ClapCLI.swift b/Sources/ClapCLIKit/ClapCLI.swift index 0335615..4606f69 100644 --- a/Sources/ClapCLIKit/ClapCLI.swift +++ b/Sources/ClapCLIKit/ClapCLI.swift @@ -22,6 +22,10 @@ public enum ClapCLI { "out": { await DeleteCommand.runOutAlias($0, context: $1) }, "pin": { await PinCommand.run($0, pinned: true, context: $1) }, "unpin": { await PinCommand.run($0, pinned: false, context: $1) }, + "fav": { await PinCommand.run($0, flag: .favorite, on: true, context: $1) }, + "unfav": { await PinCommand.run($0, flag: .favorite, on: false, context: $1) }, + "favorite": { await PinCommand.run($0, flag: .favorite, on: true, context: $1) }, + "unfavorite": { await PinCommand.run($0, flag: .favorite, on: false, context: $1) }, "tag": { await TagCommand.run($0, context: $1) }, "tags": { await TagCommand.run(["list"] + $0, context: $1) }, "backup": { await BackupCommand.run($0, mode: .backup, context: $1) }, @@ -99,7 +103,7 @@ enum HelpText { Usage: clap Open the clipboard UI (asks ClapApp) - clap list [--images] [--shell] [--tag ] [--limit N] [--offset N] [--json] + clap list [--images] [--shell] [--favorites] [--tag ] [--limit N] [--offset N] [--json] clap search [--regex ] [--type text|image|shell] [--tag ] [--limit N] [--offset N] [--json] clap get [--json] clap copy @@ -108,6 +112,7 @@ enum HelpText { clap in Alias for clap add clap out [ | ] Alias for clap delete clap pin / clap unpin + clap fav / clap unfav Favorite (alias: favorite/unfavorite) clap tag add / clap tag remove clap tags / clap tag list [id] clap backup / clap restore Full-history backup & restore diff --git a/Sources/ClapCLIKit/Commands/ListCommand.swift b/Sources/ClapCLIKit/Commands/ListCommand.swift index 618a772..d84e554 100644 --- a/Sources/ClapCLIKit/Commands/ListCommand.swift +++ b/Sources/ClapCLIKit/Commands/ListCommand.swift @@ -3,11 +3,12 @@ import ClapCore enum ListCommand { static let usage = """ - Usage: clap list [--images] [--shell] [--tag ] [--limit N] [--offset N] [--json] + Usage: clap list [--images] [--shell] [--favorites] [--tag ] [--limit N] [--offset N] [--json] Lists clipboard and shell entries, most recently used first. --images Only image entries --shell Only shell command entries + --favorites Only favorites --tag Filter by tag / pinboard --limit N Max rows (default 20) --offset N Skip N rows @@ -16,7 +17,7 @@ enum ListCommand { static func run(_ args: [String], context: CLIContext) async { let parsed = ArgParser.parse(args, - boolFlags: ["--images", "--shell", "--json"], + boolFlags: ["--images", "--shell", "--favorites", "--json"], valueFlags: ["--tag", "--limit", "--offset"], usage: usage) guard parsed.positionals.isEmpty else { @@ -32,7 +33,8 @@ enum ListCommand { let (entries, dataDir) = await CLI.run { () -> ([ClipboardEntry], URL) in let store = try context.makeStore() - let query = SearchQuery(type: type, tag: tag, limit: limit, offset: offset) + let query = SearchQuery(type: type, favoriteOnly: parsed.has("--favorites"), + tag: tag, limit: limit, offset: offset) let entries = try await store.search(query) return (entries, store.dataDir) } diff --git a/Sources/ClapCLIKit/Commands/PinCommand.swift b/Sources/ClapCLIKit/Commands/PinCommand.swift index 378cdf8..5a3e088 100644 --- a/Sources/ClapCLIKit/Commands/PinCommand.swift +++ b/Sources/ClapCLIKit/Commands/PinCommand.swift @@ -1,28 +1,64 @@ import Foundation import ClapCore +/// `clap pin/unpin ` and `clap fav/unfav ` — both flags are +/// eviction-exempt markers with identical CLI shape. enum PinCommand { - static func usage(pinned: Bool) -> String { - let verb = pinned ? "pin" : "unpin" - return """ - Usage: clap \(verb) + enum Flag { + case pin, favorite - \(pinned ? "Pins an entry so it is never evicted." : "Removes the pin from an entry.") + func verb(_ on: Bool) -> String { + switch self { + case .pin: return on ? "pin" : "unpin" + case .favorite: return on ? "fav" : "unfav" + } + } + + func pastTense(_ on: Bool) -> String { + switch self { + case .pin: return on ? "Pinned" : "Unpinned" + case .favorite: return on ? "Favorited" : "Unfavorited" + } + } + + func summary(_ on: Bool) -> String { + switch self { + case .pin: + return on ? "Pins an entry so it is never evicted." : "Removes the pin from an entry." + case .favorite: + return on ? "Marks an entry as a favorite (shown in the Favs tab, never evicted)." + : "Removes an entry from favorites." + } + } + } + + static func usage(_ flag: Flag, on: Bool) -> String { + """ + Usage: clap \(flag.verb(on)) + + \(flag.summary(on)) """ } static func run(_ args: [String], pinned: Bool, context: CLIContext) async { - let parsed = ArgParser.parse(args, usage: usage(pinned: pinned)) - let id = parsed.requiredID(commandName: pinned ? "pin" : "unpin") + await run(args, flag: .pin, on: pinned, context: context) + } + + static func run(_ args: [String], flag: Flag, on: Bool, context: CLIContext) async { + let parsed = ArgParser.parse(args, usage: usage(flag, on: on)) + let id = parsed.requiredID(commandName: flag.verb(on)) let changed = await CLI.run { let store = try context.makeStore() - return try await store.setPinned(pinned, id: id) + switch flag { + case .pin: return try await store.setPinned(on, id: id) + case .favorite: return try await store.setFavorite(on, id: id) + } } guard changed else { CLI.fail("entry \(id) not found") } Notify.storeChanged() - print("\(pinned ? "Pinned" : "Unpinned") entry \(id).") + print("\(flag.pastTense(on)) entry \(id).") } } diff --git a/Sources/ClapCLIKit/OutputFormatter.swift b/Sources/ClapCLIKit/OutputFormatter.swift index 263bfd9..43e0d3c 100644 --- a/Sources/ClapCLIKit/OutputFormatter.swift +++ b/Sources/ClapCLIKit/OutputFormatter.swift @@ -86,6 +86,9 @@ enum OutputFormatter { let lastUsedAt: String let sizeBytes: Int64 let isPinned: Bool + let isFavorite: Bool + let tags: [String] + let shortcut: String? let useCount: Int let sourceApp: String? } @@ -105,6 +108,9 @@ enum OutputFormatter { lastUsedAt: iso8601.string(from: entry.lastUsedAt), sizeBytes: entry.sizeBytes, isPinned: entry.isPinned, + isFavorite: entry.isFavorite, + tags: entry.tags, + shortcut: entry.shortcut, useCount: entry.useCount, sourceApp: entry.sourceApp ) diff --git a/Sources/ClapCore/ClipboardStore+Diagnostics.swift b/Sources/ClapCore/ClipboardStore+Diagnostics.swift index ae5ad2a..8bc8405 100644 --- a/Sources/ClapCore/ClipboardStore+Diagnostics.swift +++ b/Sources/ClapCore/ClipboardStore+Diagnostics.swift @@ -21,7 +21,12 @@ extension ClipboardStore { ConfigKey.shellEnabled: "1", ConfigKey.shellMaxEntries: "50000", ConfigKey.shellMaxSize: "10485760", // 10 MB - ConfigKey.shellHistfile: "" // empty = auto-detect + ConfigKey.shellHistfile: "", // empty = auto-detect + // Set to "1" by the app after the one-time history backfill. + ConfigKey.shellInitialImported: "0", + ConfigKey.snippetsEnabled: "1", + // Must match HotKeyDefinition.defaultID in ClapApp. + ConfigKey.uiHotkey: "cmd+shift+v" ] /// Returns the stored value, falling back to the documented default when diff --git a/Tests/ClapAppTests/AppStateTests.swift b/Tests/ClapAppTests/AppStateTests.swift index 1e658af..74b04fe 100644 --- a/Tests/ClapAppTests/AppStateTests.swift +++ b/Tests/ClapAppTests/AppStateTests.swift @@ -77,3 +77,74 @@ struct AppStateLogicTests { #expect(tagged?.tag == "work") } } + +@Suite("Config defaults stay in sync with the app") +struct AppConfigDefaultsTests { + @Test func storeHotkeyDefaultMatchesHotKeyPreset() async throws { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("clap-defaults-tests", isDirectory: true) + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: dir) } + let store = try ClipboardStore(dataDir: dir) + let stored = try await store.config(ConfigKey.uiHotkey) + #expect(stored == HotKeyDefinition.defaultID) + } +} + +@MainActor +@Suite("Panel frame persistence") +struct PanelFrameTests { + private let screen = NSRect(x: 0, y: 0, width: 1728, height: 1080) + + @Test func placementPrefersRightThenLeftThenLessOverflow() { + let list = NSRect(x: 100, y: 200, width: 480, height: 500) + #expect(SlideoutController.placement(listFrame: list, totalWidth: 840, screen: screen) == .right) + + let nearRight = NSRect(x: 1128, y: 200, width: 480, height: 500) + #expect(SlideoutController.placement(listFrame: nearRight, totalWidth: 840, screen: screen) == .left) + + // Neither side fits on a narrow screen: pick the smaller overflow. + let narrow = NSRect(x: 0, y: 0, width: 900, height: 800) + // x=100: right overflows 40pt, left would overflow 260pt. + let leftish = NSRect(x: 100, y: 100, width: 480, height: 500) + #expect(SlideoutController.placement(listFrame: leftish, totalWidth: 840, screen: narrow) == .right) + // x=300: right overflows 240pt, left only 60pt. + let rightish = NSRect(x: 300, y: 100, width: 480, height: 500) + #expect(SlideoutController.placement(listFrame: rightish, totalWidth: 840, screen: narrow) == .left) + } + + @Test func clampPullsFrameFullyOnScreen() { + let offRight = NSRect(x: 1600, y: -50, width: 480, height: 500) + let clamped = PanelController.clamp(offRight, to: screen) + #expect(clamped.maxX == screen.maxX) + #expect(clamped.minY == screen.minY) + #expect(clamped.size == offRight.size) + + let huge = NSRect(x: -10, y: -10, width: 5000, height: 5000) + #expect(PanelController.clamp(huge, to: screen) == screen) + + let inside = NSRect(x: 100, y: 100, width: 480, height: 500) + #expect(PanelController.clamp(inside, to: screen) == inside) + } + + @Test func listFrameIgnoresPreviewOnEitherSide() { + let slideout = SlideoutController() + slideout.contentWidth = 480 + slideout.slideoutWidth = 360 + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 840, height: 500), + styleMask: [.borderless], backing: .buffered, defer: true) + window.setFrame(NSRect(x: 768, y: 200, width: 840, height: 500), display: false) + + slideout.state = .open + slideout.placement = .left + // Preview on the left: the list starts 360pt to the right. + #expect(slideout.listFrame(of: window) == NSRect(x: 1128, y: 200, width: 480, height: 500)) + + slideout.placement = .right + #expect(slideout.listFrame(of: window) == NSRect(x: 768, y: 200, width: 480, height: 500)) + + slideout.state = .closed + window.setFrame(NSRect(x: 768, y: 200, width: 520, height: 500), display: false) + #expect(slideout.listFrame(of: window) == NSRect(x: 768, y: 200, width: 520, height: 500)) + } +} diff --git a/Tests/ClapCLITests/CLITests.swift b/Tests/ClapCLITests/CLITests.swift index a09d619..245039e 100644 --- a/Tests/ClapCLITests/CLITests.swift +++ b/Tests/ClapCLITests/CLITests.swift @@ -85,6 +85,21 @@ struct OutputFormatterTests { #expect(lines[1].contains("hello")) } + @Test func entryJSONIncludesFavoriteTagsAndShortcut() throws { + let entry = ClipboardEntry( + id: 3, type: .text, content: "me@example.com", imagePath: nil, imageFormat: nil, + contentHash: "h", createdAt: Date(), lastUsedAt: Date(), sizeBytes: 14, + isPinned: false, isFavorite: true, useCount: 2, sourceApp: nil, + shortcut: ";email", tags: ["work", "contact"]) + let json = OutputFormatter.entryJSON(entry, dataDir: URL(fileURLWithPath: "/tmp")) + #expect(json.isFavorite) + #expect(json.tags == ["work", "contact"]) + #expect(json.shortcut == ";email") + let encoded = try OutputFormatter.encodeJSON(json) + #expect(encoded.contains("\"isFavorite\" : true")) + #expect(encoded.contains("\"shortcut\" : \";email\"")) + } + @Test func encodeJSONProducesSortedStableOutput() throws { struct Payload: Codable, Equatable { let b: Int; let a: Int } let json = try OutputFormatter.encodeJSON(Payload(b: 1, a: 2)) diff --git a/Tests/ClapCoreTests/StoreTests.swift b/Tests/ClapCoreTests/StoreTests.swift index b9194fd..0ec6975 100644 --- a/Tests/ClapCoreTests/StoreTests.swift +++ b/Tests/ClapCoreTests/StoreTests.swift @@ -535,7 +535,8 @@ struct ConfigStatsTests { let expectedKeys = ["text.max_entries", "text.max_size", "image.max_entries", "image.max_size", "monitoring.paused", "exclusions", "retention.days", "launch_at_login", "paste.on_copy", - "shell.enabled", "shell.max_entries", "shell.max_size", "shell.histfile"] + "shell.enabled", "shell.max_entries", "shell.max_size", "shell.histfile", + "shell.initial_imported", "snippets.enabled", "ui.hotkey"] for key in expectedKeys { #expect(dict[key] != nil, "missing \(key)") }