Polish clipboard panel UX and interactions

This commit is contained in:
Akshay Kolli
2026-07-09 19:32:57 -04:00
parent 23cd8b64a9
commit 52f712eb73
18 changed files with 2109 additions and 3273 deletions

View File

@@ -1,51 +1,51 @@
# ClipBored # ClipBored
ClipBored is a small native macOS clipboard manager. It captures local clipboard history and opens a keyboard-first side panel for search, sorting, copy, paste, pinning, and deletion. It runs as a dockless menu-bar utility by default, with an optional Dock icon mode. ClipBored is a native macOS clipboard manager with a keyboard-first side shelf. It captures local clipboard history and makes clips easy to find, preview, organize, copy, paste, pin, and delete. It runs as a dockless menu-bar utility by default, with an optional Dock icon.
The project is intentionally dependency-light: Swift Package Manager, AppKit, Carbon hotkeys, SQLite, and system frameworks only. The project is intentionally dependency-light: Swift Package Manager, AppKit, Carbon hotkeys, SQLite, and system frameworks only.
## Features ## Features
- Dockless menu-bar utility by default (`LSUIElement=true`), with a Settings toggle for normal Dock presence - A compact toolbar with an expanding search control, clear-history and settings actions, plus a vertically scrollable category icon rail beside the cards
- First-run setup assistant for the open shortcut, Keep History retention, menu-bar/Dock presence, launch-at-login, iCloud sync, and Accessibility permission - Category filtering without a separate filter panel: click a chip to select it, or Command-click chips to show their union; unused empty built-in categories stay hidden while named Pinboards remain available even when empty
- Right-click menu-bar status menu with capture state, history count, settings, manual or timed pause/resume, and quit - A vertically scrolling list of cards with full-color kind or Pinboard headers that fills the space beside the category rail. Hover expands a card's preview without changing keyboard selection or filtering; commands live in card context menus and keyboard shortcuts
- Global shortcuts: - Search that collapses to a magnifying-glass button when it is empty and unfocused, expands on click, typing, or `Command + F`, and stays expanded while a query is active
- `Shift + Command + V` or the configured open shortcut toggles the clipboard panel - Fast, short panel, search, category, and card transitions that honor the macOS Reduce Motion accessibility setting
- First-run setup for the open shortcut, Keep History retention, menu-bar/Dock presence, launch at login, iCloud sync, and Accessibility permission
- A menu-bar status menu with capture state, history count, settings, manual or timed pause/resume, and quit
- Global and panel shortcuts:
- The configured open shortcut toggles the clipboard shelf
- `Command + ,` opens settings - `Command + ,` opens settings
- `Command + F` focuses search; press it again while search is active to show filters - `Command + F` focuses search
- `Command + 1` through `Command + 9` paste the numbered visible card; add `Shift` to paste that card as plain text - `Command + 1` through `Command + 9` pastes the numbered visible card; add `Shift` to use plain text
- `Return` pastes the selected clip; `Shift + Return` or `Command + Shift + V` pastes it as plain text - `Return` pastes the selected clip; `Shift + Return` or `Command + Shift + V` uses plain text
- `Command + C` copies the selected clip or selected clips - `Command + C` copies the selected clip or selected clips
- `Command + E` edits the selected text or code clip - `Command + E` edits the selected text or code clip, and `Command + R` renames it
- `Command + R` renames the selected clip
- `Delete` removes selected clips, and `Command + Z` restores the last deleted batch - `Delete` removes selected clips, and `Command + Z` restores the last deleted batch
- `Command + G` shows a filtered result back in the full clipboard history - `Command + G` shows a filtered result in the full clipboard history
- `Command + O` opens the selected link, file, or media clip when possible - `Command + O` opens the selected link, file, or media clip when possible
- `Command + N` creates a new text clip - `Shift + Command + N` creates a Pinboard collection
- `Shift + Command + N` creates a new collection - `Shift + Command + C` toggles Stack capture for queued multi-paste workflows
- `Shift + Command + C` toggles Stack capture mode for queued multi-paste workflows
- `Command + Left` and `Command + Right` move between collections - `Command + Left` and `Command + Right` move between collections
- `Command + Up` and `Command + Down` jump to the first or last visible clip - `Command + Up` and `Command + Down` jump to the first or last visible clip
- `Command + T` pauses or resumes clipboard capture - `Command + T` pauses or resumes clipboard capture
- `Command + A` selects the visible shelf from a focused card; `Shift` + shelf navigation extends the selected range - `Command + A` selects the visible list from a focused card; Shift-modified navigation extends a range
- `Space` or `Command + Y` previews the selected card when the focused search field is empty - `Space` or `Command + Y` previews the selected card when the focused search field is empty
- Clipboard history for text, URLs with local preview thumbnails when available, images, audio, video with movie thumbnails when available, RTF/HTML rich text, PDFs, and file references - Keyboard-focusable cards and category chips with type-to-search, visible focus chrome, VoiceOver descriptions, context menus, Up/Down card navigation, and direct category navigation
- Keyboard-focusable compact rows and collection chips with type-to-search, Return-to-paste/select, Space-to-preview for text, built-in browser previews for links, Quick Look for files and media, remote copied-on device metadata, image rotation and text extraction quick actions, vertical wheel/trackpad panning, visible focus chrome, and VoiceOver action hints - Clipboard history for text, code, colors, URLs, images, audio, video, RTF/HTML rich text, PDFs, and file references
- Shelf navigation keys for focused cards: Left/Right, Page Up/Page Down, Home, and End; add `Shift` to extend the selected range - Immediate cards with previews loaded asynchronously. Image, link, document, and movie thumbnails fill in without blocking search, selection, or scrolling
- Shelf navigation keys for focused collection chips: Left/Right, Home, and End - Built-in browser previews for links, Quick Look for files and media, image rotation, and local text extraction for images
- Independent-token and structured search, including `app:Safari`, `type:image,pdf`, `device:MacBook`, `pinboard:"Client Work","Read Later"`, and `date:2026-06-30`
- Custom color-coded Pinboards, including empty Pinboards, with drag-and-drop collection assignment, context-menu editing and export, and durable retention
- Searchable custom clip titles that do not alter the copied payload
- Multi-selection, original-format or plain-text batch copy/paste, Stack capture, next-item Stack actions, and Stack-as-text workflows
- SQLite persistence with bounded history, time-based retention, pinned-item and Pinboard retention, and encrypted app-managed payloads - SQLite persistence with bounded history, time-based retention, pinned-item and Pinboard retention, and encrypted app-managed payloads
- Search with independent token matching, a Paste-style filter menu, structured filters such as `app:Safari`, `type:image,pdf`, `device:MacBook`, `pinboard:"Client Work","Read Later"`, `date:2026-06-30`, result jump-back to full history, optional local OCR for copied images, and on-demand OCR from image cards - A bounded thumbnail cache with asynchronous loading and byte/file-count pruning
- Sort modes for recent, most used, images, links, text, files, audio, and pinned items - Portable local archive export/import for history, Pinboards, and managed attachments; external file references stay path-based
- Custom named collections that behave as durable Pinboards, including empty color-coded collections, for organizing clips from the card Collect control, context menu, keyboard-focusable collection rail, direct text-clip creation, or by dragging cards onto collection chips; collection chips can be edited or deleted from their context menu - Optional iCloud archive sync for signed builds with an iCloud entitlement
- Pinboard-level archive export from a collection chip for sharing one Pinboard, including empty Pinboards and color metadata - A redesigned, resizable Settings window with top-level `General`, `Shortcuts`, `Capture`, `Privacy`, `Performance`, and `Data` tabs. Each page is vertically scrollable and keeps controls aligned at narrow window sizes
- Plain-text clip creation and editing with native macOS Writing Tools support when available - Settings for shelf side, retention, history length, default sort, cache limit, adaptive polling profile, ignored apps, content kinds, shortcuts, launch at login, Dock/menu-bar presence, screen-capture privacy, capture pause, and clear-on-quit behavior
- Searchable custom titles for clips, so media, files, links, PDFs, audio, and text can be renamed without changing the copied payload - Local-first storage, with optional sensitive-content exclusion and iCloud sync disabled by default
- Copy and paste actions with Accessibility permission fallback, including Command/Shift multi-select original-format or plain-text batching, Stack capture mode, Stack next-item actions, and Stack-as-text batch copy/paste
- Image thumbnail cache with byte and file-count pruning
- Portable local archive export/import for moving history, Pinboards, and app-managed image/audio/video/rich-text/PDF attachments between Macs; external file references stay path-based
- Optional iCloud archive sync for signed builds with an iCloud entitlement, using ClipBored's app-private ubiquity container and the same portable archive format
- Configurable left or right shelf side, Keep History retention, history length, cache limit, polling profile, ignored apps, content kinds, launch-at-login, Dock/menu-bar presence, screen-capture privacy, temporary capture pause, and clear-on-quit behavior, with card-level capture rules for ignoring a source app or content type
- Local-first storage, with optional sensitive-content exclusion for common secrets and iCloud sync disabled by default
## Requirements ## Requirements
@@ -79,8 +79,7 @@ swift test -q
./scripts/idle-soak-report.sh 900 ./scripts/idle-soak-report.sh 900
``` ```
For app-level behavior that cannot be fully covered by unit tests, run the manual checklist in [docs/SMOKE_TEST.md](docs/SMOKE_TEST.md). For app-level behavior that cannot be fully covered by unit tests, run [docs/SMOKE_TEST.md](docs/SMOKE_TEST.md). For distribution builds, see [docs/RELEASE.md](docs/RELEASE.md).
For distribution builds, see [docs/RELEASE.md](docs/RELEASE.md).
Project layout: Project layout:
@@ -89,16 +88,16 @@ Project layout:
- `sources/clipbored/extensions` - small AppKit/Foundation helpers - `sources/clipbored/extensions` - small AppKit/Foundation helpers
- `sources/clipbored/models` - clipboard item and settings models - `sources/clipbored/models` - clipboard item and settings models
- `sources/clipbored/resources` - app bundle metadata and icon assets - `sources/clipbored/resources` - app bundle metadata and icon assets
- `sources/clipbored/services` - clipboard capture, persistence, cache, shortcuts, paste, diagnostics, privacy filters - `sources/clipbored/services` - capture, persistence, cache, shortcuts, paste, diagnostics, and privacy filters
- `sources/clipbored/views` - panel and settings UI - `sources/clipbored/views` - panel, onboarding, preview, and settings UI
- `tests/clipboredtests` - unit tests for persistence, filtering, shortcuts, pasteboard writes, diagnostics, and sensitive-content detection - `tests/clipboredtests` - unit and UI-structure regression tests
- `docs` - architecture, security notes, and roadmap - `docs` - architecture, security, release, smoke-test, and roadmap notes
## Privacy And Security ## Privacy And Security
ClipBored does not use telemetry or background networking. Clipboard history is stored locally under Application Support unless iCloud Sync is explicitly enabled in a signed build with an iCloud entitlement. User-triggered link previews load the selected web page in an ephemeral built-in WebKit view. ClipBored does not use telemetry or background networking. Clipboard history is stored locally under Application Support unless iCloud Sync is explicitly enabled in a signed build with an iCloud entitlement. User-triggered link previews load the selected web page in an ephemeral built-in WebKit view.
Textual SQLite fields, image cache files, audio clips, video clips, rich text sidecars, and PDF attachments are encrypted with AES-GCM using a Keychain-held key when Keychain access is available. If Keychain access blocks or fails, ClipBored uses an owner-only app-local fallback key so capture does not stall. Full history clears remove the local fallback key when present and reset cached key state for future captures. Portable archive exports and iCloud sync archives are not encrypted by ClipBored, so treat them like sensitive backups. Temporary decrypted preview files may be created when thumbnailing, opening, or revealing encrypted media; stale previews are cleared on launch, cache/history clear, and quit. Use sensitive-content exclusion, ignored app settings, and the screen-sharing privacy toggle for high-risk sources or calls. See [docs/SECURITY.md](docs/SECURITY.md) for details and responsible disclosure. Textual SQLite fields, image cache files, audio clips, video clips, rich text sidecars, and PDF attachments are encrypted with AES-GCM using a Keychain-held key when Keychain access is available. If Keychain access blocks or fails, ClipBored uses an owner-only app-local fallback key so capture does not stall. Portable archive exports and iCloud sync archives are not encrypted by ClipBored, so treat them as sensitive backups. Temporary decrypted preview files are cleared on launch, cache/history clear, and quit. See [docs/SECURITY.md](docs/SECURITY.md) for details and responsible disclosure.
## Contributing ## Contributing

View File

@@ -1,64 +1,76 @@
# Architecture # Architecture
ClipBored is a single-process AppKit utility built with Swift Package Manager. ClipBored is a single-process AppKit utility built with Swift Package Manager. UI, capture, persistence, preview generation, and paste orchestration stay in-process. Capture persistence, card-thumbnail loading, archive and sync operations, image rotation, and OCR use bounded background queues; their UI state and completion feedback return to the main thread.
## Runtime Shape ## Runtime Shape
- `ClipBoredApp` creates `NSApplication`, sets accessory activation, installs `AppDelegate`, and starts the run loop. - `ClipBoredApp` creates `NSApplication`, installs `AppDelegate`, and starts the run loop.
- `AppDelegate` wires shared services, status menu items, settings observers, and global shortcuts. - `AppDelegate` wires services, menu-bar commands, settings observers, and global shortcuts.
- `ClipboardMonitorService` polls `NSPasteboard.changeCount` on a utility queue with adaptive active/idle intervals. - `ClipboardMonitorService` watches `NSPasteboard.changeCount` on a utility queue with adaptive active/idle polling intervals selected by the Performance setting.
- `ClipboardStore` keeps the in-memory item list and persists rows to SQLite on a serial queue. - `ClipboardStore` owns the in-memory item list and SQLite persistence on a serial queue.
- `ClipboardCacheService` stores bounded image previews under Application Support and keeps a small `NSCache`. - `ClipboardCacheService` stores bounded encrypted preview sidecars under Application Support and maintains a small in-memory cache.
- `ClipboardCloudSyncService` resolves the app-private iCloud ubiquity container when sync is enabled and pushes or pulls the portable archive file. - `ClipboardCloudSyncService` resolves the private iCloud ubiquity container and pushes or pulls portable archives only when sync is enabled.
- `ShortcutManager` registers Carbon hotkeys for app-wide commands. - `ShortcutManager` registers only intentional system-wide Carbon hotkeys (open shelf and Stack capture). The Settings binding is handled by the shelf's local key monitor and is never registered globally.
- `ClipboardPanelController` owns the side panel lifecycle, Dock-aware frame planning, configured left/right placement, and target-app tracking. - `ClipboardPanelController` owns shelf lifecycle, current-screen placement, left/right frame planning, target-app tracking, and show/hide/reflow animation.
- `ClipboardPanelViewModel` filters, sorts, selects, copies, pastes, pins, organizes, deletes, opens, and reveals items. - `ClipboardPanelViewModel` owns query parsing, indexed category unions, sorting, selection, copy/paste, pinning, Pinboards, Stack, deletion, opening, and asynchronous thumbnail request coalescing.
- `LinkPreviewWindowController` opens selected HTTP(S) links in an ephemeral WebKit preview window instead of handing them to another browser. - `ClipboardPanelView` renders the toolbar, vertical category icon rail, and viewport-aware card list beside it.
- `OnboardingWindowController` shows the first-run setup assistant for shortcut, retention, system entry points, launch-at-login, iCloud sync, and Accessibility permission choices. - `LinkPreviewWindowController` opens user-selected HTTP(S) links in an ephemeral WebKit preview window.
- `SettingsWindowController` exposes native controls for capture, privacy, performance, shortcuts, and data management. - `OnboardingWindowController` handles first-run shortcut, retention, lifecycle, sync, and Accessibility choices.
- `SettingsWindowController` presents six resizable, vertically scrollable settings pages and routes common settings changes through targeted control refreshes.
## Data Flow ## Capture And Presentation Flow
1. The monitor notices a pasteboard change. 1. The monitor notices a pasteboard change.
2. Source app metadata is checked against ignored apps. 2. Capture rules check paused state, ignored source apps, allowed content kinds, and optional sensitive-text exclusion.
3. Pasteboard content is normalized into a `ClipboardItem`. 3. Pasteboard content is normalized into a `ClipboardItem`; local Vision OCR runs when image-label search is enabled.
4. Sensitive text is skipped when exclusion is enabled. 4. The store deduplicates, preserves pinned and Pinboard-assigned items, enforces retention/length limits, and persists the mutation.
5. Copied images run local Vision OCR only when `Search in image labels` is enabled; image cards can also run the same local OCR on demand from their quick actions. 5. The panel view model maintains category/Pinboard indexes, applies the text query and selected category union, and caches parsed search matches across counts and category changes.
6. The store deduplicates, preserves pinned and collection-assigned items, enforces limits, and persists the mutation. 6. The view lays out card slots beside the category rail in one vertical document and materializes cards near the visible viewport.
7. The panel view model receives store updates and recomputes the visible list. 7. Cards render immediately with a fallback presentation. Preview thumbnails load on a bounded operation queue; identical in-flight requests share work, and a still-relevant card is replaced in place on the main thread when its image arrives.
## Persistence ## Shelf Interaction Model
History is stored in SQLite at: The shelf uses a fixed vertical layout on the configured left or right edge of the active screen.
- Header row one contains the collapsed/expanded search control plus clear-history and settings actions.
- Header row two is a labeled, horizontally scrollable category rail. Built-in categories without clips are omitted unless currently selected; custom Pinboards remain available when empty.
- A normal chip click replaces the active category filter. Command-click adds or removes chips from a union. Hover changes chrome only and never changes filtering.
- An empty, unfocused search field collapses to an icon. Click, typing, or `Command + F` expands and focuses it; clicking elsewhere collapses it only when the query is empty. Repeated `Command + F` keeps focus in the same field.
- Cards scroll vertically and fill the usable shelf width. Hover expansion changes visual presentation only: it does not mutate keyboard selection, the selected range, or query/category state.
- Card commands are discoverable through context menus, VoiceOver descriptions, and keyboard shortcuts. Hover-only action controls are not part of the interaction contract.
- Category changes and card/search expansion use short AppKit/Core Animation transitions. Both panel-controller and panel-view durations resolve to zero when macOS Reduce Motion is enabled.
The panel has no user-facing resize lip, alternate density/layout mode, close button, new-text action, or persistent status bar. It is dismissed with `Esc` or the configured global shortcut.
## Settings UI
Settings uses a custom segmented selector backed by a borderless `NSTabView`:
- `General` - history, sorting, shelf side, launch, and menu-bar/Dock presence
- `Shortcuts` - a system-wide open-shelf binding and a pane-local open-settings binding
- `Capture` - pause state, content kinds, image-label search, likely-secret exclusion, ignored apps, and capture status
- `Privacy` - local-data behavior, screen-capture hiding, Accessibility permission, and paste status
- `Performance` - adaptive polling profile and thumbnail-cache cap
- `Data` - iCloud archive sync, local archive import/export, storage location, and destructive clears
Each tab is a top-aligned document inside its own vertical scroll view. The window has a practical minimum size, no horizontal scrollers, and commits focused text/shortcut drafts when it closes. Common narrow settings changes update their bound controls without rebuilding the whole window; expensive cloud status checks are cached across unrelated refreshes.
## Persistence And Privacy Boundaries
History is stored in:
```text ```text
~/Library/Application Support/ClipBored/history.sqlite ~/Library/Application Support/ClipBored/history.sqlite
``` ```
Images are stored under: Image previews are stored under `images/`; restorable audio, video, rich-text, and PDF payloads are stored under `attachments/`. Legacy JSON import remains for migration from early builds.
```text Portable `.clipboredarchive` files preserve item metadata, Pinboards, and decrypted bytes for app-managed sidecars so another Mac can re-cache them with its own storage paths and encryption key. External file references remain path-based. Optional iCloud sync uses the same unencrypted archive format inside the app-private ubiquity container and is disabled by default.
~/Library/Application Support/ClipBored/images/
```
Restorable non-image payloads such as audio clips, rich text, and PDFs are stored under: Textual SQLite fields are encrypted and decrypted at the `ClipboardStore` boundary. Managed cache and attachment files are encrypted and decrypted at the `ClipboardCacheService` boundary. The key lives in Keychain when available, with an owner-only local fallback if Keychain access fails. Runtime `ClipboardItem` values remain plaintext in memory for search and clipboard operations. Opening encrypted media may create a temporary decrypted file; stale previews are cleared on launch, cache/history clear, and quit. Link previews are user-triggered and use a non-persistent WebKit data store.
```text
~/Library/Application Support/ClipBored/attachments/
```
Legacy JSON import still exists for migration from early builds.
Portable `.clipboredarchive` files are JSON exports created by `ClipboardArchiveService`. They preserve item metadata and include decrypted bytes for app-managed image, URL-thumbnail, audio, video, rich-text, and PDF sidecars so a different Mac can re-cache them under its own storage directory and encryption key. External file references remain path-based and are not copied into the archive.
Optional iCloud Sync uses that same archive format at `Documents/ClipBored/ClipBored.clipboredarchive` inside the app-private ubiquity container. It is disabled by default, requires a signed build with iCloud entitlement access, pulls once when enabled at launch, and debounces pushes after local store changes. Shared Pinboard collaboration is not implemented.
Textual SQLite fields, including optional collection names and image OCR text, are encrypted and decrypted at the `ClipboardStore` boundary. App-managed image cache files, URL preview thumbnails, audio clips, rich text sidecars, and PDF attachments are encrypted and decrypted at the `ClipboardCacheService` boundary. The encryption key is stored in Keychain when available, with an owner-only app-local fallback key if Keychain access blocks or fails. Full history clears remove the local fallback key when present and reset cached key state after SQLite deletion succeeds. Runtime `ClipboardItem` values remain plaintext in memory so search, duplicate detection, copy, paste, organization, archive export/import, and cache cleanup operate normally. Opening or revealing encrypted media creates a temporary decrypted copy for macOS handoff; stale temporary previews are cleared on launch, cache/history clear, and quit. Link previews are user-triggered and use a non-persistent WebKit data store.
## Size And Power Constraints ## Size And Power Constraints
The release build intentionally avoids SwiftUI, Combine, Swift Concurrency, third-party packages, bundled media, and app resources beyond `Info.plist`. The release build intentionally avoids SwiftUI, Combine, Swift Concurrency, third-party packages, and bundled media. The shelf avoids continuous layout work, renders only cards near the viewport, coalesces preview requests, keeps card-thumbnail decoding off the main thread, and bounds both memory and disk caches. Clipboard monitoring uses change-count polling with selectable adaptive profiles rather than continuous file scans.
The side shelf is anchored to the current screen's visible frame and can be placed on the left or right edge. It uses compact horizontal rows in a vertical list; the active or hovered row expands in place while the panel stays clear of side Docks and reserves bottom Dock space for content padding. The build script uses `-Osize`, whole-module optimization, disabled reflection metadata, linker dead stripping, symbol stripping, and hardened-runtime signing. `scripts/build-macos-app.sh` enforces 2 MiB gates for both the executable and app bundle.
The build script uses `-Osize`, whole-module optimization, disabled reflection metadata, linker dead stripping, symbol stripping, and hardened-runtime signing. The current public targets, enforced by `scripts/build-macos-app.sh`, are 2 MiB gates for both the executable and app bundle.

View File

@@ -15,7 +15,8 @@ This roadmap keeps future work aligned with the project's constraints: small exe
## Product Polish ## Product Polish
- Improve keyboard focus states and VoiceOver labels. - Keep keyboard focus, VoiceOver descriptions, Command-click category unions, and context-menu parity covered as the side-rail shelf evolves.
- Validate motion, cross-display placement, and card expansion on each supported macOS release, including the system Reduce Motion path.
- Consider optional password-protected archive exports if migration needs outgrow owner-only local archive files. - Consider optional password-protected archive exports if migration needs outgrow owner-only local archive files.
- Design true shared Pinboard collaboration separately from private iCloud archive sync. - Design true shared Pinboard collaboration separately from private iCloud archive sync.
@@ -24,4 +25,5 @@ This roadmap keeps future work aligned with the project's constraints: small exe
- Keep measuring binary size after each feature. - Keep measuring binary size after each feature.
- Avoid continuous background file scans. - Avoid continuous background file scans.
- Revisit polling intervals only with measured idle wakeup evidence. - Revisit polling intervals only with measured idle wakeup evidence.
- Keep image decoding lazy and cache bounded. - Track asynchronous preview latency and viewport materialization under large histories.
- Keep card-thumbnail decoding and user-triggered image transforms off the main thread, with bounded queues and caches.

View File

@@ -1,137 +1,93 @@
# Manual Smoke Test Checklist # Manual Smoke Test Checklist
Use this checklist before a release or after changes to panel, pasteboard, settings, permissions, storage, launch-at-login, or packaging behavior. Use this checklist before a release or after changes to the shelf, pasteboard, settings, permissions, storage, launch-at-login, or packaging behavior.
## Setup ## Setup
1. Build the app: 1. Run `./scripts/check.sh`, quit any running copy, and open `build/ClipBored.app`.
2. With fresh preferences, confirm the setup assistant appears before the shelf and covers the open shortcut, Keep History, menu-bar/Dock presence, launch at login, iCloud sync, and Accessibility.
3. Finish setup, relaunch, and confirm the assistant does not return.
4. Confirm the menu-bar icon appears when `Show ClipBored in the menu bar` is enabled.
```bash ## Capture And Preview Loading
./scripts/check.sh
```
2. Quit any running ClipBored copy. 1. Copy plain text, code, a URL, a color, an image, audio, video, rich text, a PDF, one Finder file, and multiple Finder files. Confirm each appears with the correct kind and grouped files remain one clip.
3. Open `build/ClipBored.app`. 2. Confirm a new card appears immediately even when its preview is not cached. Keep searching and scrolling while the thumbnail loads, then confirm the card updates in place without changing selection or scroll position.
4. With a fresh preferences profile, confirm the setup assistant appears before the clipboard panel; choose the open shortcut, Keep History retention, menu-bar/Dock presence, launch-at-login, iCloud sync, and Accessibility option, then finish setup. 3. Confirm URL and video thumbnails appear when source data is available, and that a missing or failed thumbnail leaves a usable fallback card.
5. Reopen ClipBored and confirm the setup assistant does not reappear. 4. Enable `Search in image labels`, copy an image containing readable text, and confirm the OCR text is searchable after processing finishes.
6. Confirm ClipBored appears in the menu bar when `Show ClipBored in the menu bar` is enabled. 5. Disable a content kind in Settings > Capture, copy that kind again, and confirm it is skipped. Re-enable it afterward.
6. Copy from an ignored source app and confirm the capture status reports that the item was skipped.
## Capture ## Shelf Chrome, Search, And Categories
1. Copy plain text from TextEdit, Notes, or a browser. 1. Open the shelf and confirm the collapsed search icon is at the toolbar's leading edge. Activate it and confirm the same liquid-glass pill expands smoothly to the right toward Clear History and Settings without moving its left edge or icon, with text and caret aligned after the icon.
2. Open the panel with the configured open shortcut. 2. With an empty query, confirm search is a circular magnifying-glass button. Click it or press `Command + F` and confirm it expands to an aligned search field without moving the card list.
3. Confirm the copied text appears in Most Recent. 3. Click a card or category while the empty search field is focused and confirm search collapses again. Enter a query and confirm it remains expanded after focus moves elsewhere; clearing the idle query collapses it.
4. Copy a URL and confirm it appears as a Link with a browser-style site preview; if the source provides a local preview image, confirm the Link card uses that image preview instead and that tall shelves give the preview more room. 4. Press `Command + F` repeatedly and confirm it keeps focus in the same search field.
5. Copy an image and confirm it appears as an Image with a thumbnail and a centered dimension overlay. 5. Type a query and confirm results update immediately. Press `Esc` once to clear an active query and again to close the shelf.
6. Enable `Search in image labels`, copy an image containing readable text, and confirm searching for that text finds the Image. 6. Type a structured query such as `pinboard:"Client Work" type:image,pdf device:<part of this Mac's name>` and confirm the terms are combined with the text query.
7. Copy a sound clip and confirm it appears as Audio with an album-style artwork tile. 7. Confirm the category icon rail scrolls vertically when its icons exceed the available height, while the card list scrolls independently beside it.
8. Copy a movie or video clip and confirm it appears as Video with a player-style preview and centered format pill. 8. With sparse history, confirm built-in type/sort categories with zero matches are absent. Clipboard remains available, and empty custom Pinboards remain visible.
9. Copy a PDF or PDF selection and confirm it appears as a PDF. 9. Click Text and confirm it replaces the current category filter. Command-click Links and confirm the list becomes the union of Text and Links; Command-click either selected chip again to remove it from the union.
10. Copy one Finder file and confirm it appears as a File. 10. Hover several category chips without clicking and confirm neither the active filters nor the visible clips change.
11. Copy multiple Finder files at once and confirm they appear as one grouped File item with the file count. 11. Tab to search, toolbar controls, chips, and cards. Confirm focus is visible and VoiceOver labels explain each action. Use Left/Right and Home/End on category icons, and Up/Down/Page/Home/End navigation on cards; Left/Right must not move card selection.
12. Copy formatted text from a browser or Mail message and confirm it appears as Rich Text rather than flattened plain text.
13. Disable Images, Audio, Video, Rich Text, PDFs, or Files in Settings > Capture, copy that type again, and confirm it is not captured.
## Panel ## Cards, Selection, And Actions
1. Open the panel and confirm the search field is focused. 1. Confirm cards form one vertical list beside the category rail, with full-color kind or Pinboard headers and readable alignment at both left and right shelf positions.
2. Type a query and confirm results filter immediately. 2. Hover an unselected card and confirm only that card's preview expands. The selected/focused card, selected range, visible results, and keyboard navigation must not change, and the content must remain unobscured.
3. Press `Command + F` to focus search, press it again to show filters, then add Type, Device, and Pinboard filters and confirm they appear as structured tokens. Type a structured query such as `pinboard:"Client Work","Read Later" type:image,pdf device:<part of this Mac's name>` and confirm only clips from those collections, content types, and the copied-on Mac remain. 3. Move focus with the keyboard while another card is hovered. Confirm focus moves from the keyboard selection and stale hover expansion clears.
4. Clear the search field, press `Space`, and confirm a selected web link opens in ClipBored's built-in browser preview while non-link previewable clips open in Quick Look instead of inserting a blank query. 4. Confirm card and category transitions feel continuous rather than snapping. Enable macOS System Settings > Accessibility > Display > Reduce Motion and confirm panel, search, category, and card transitions become immediate; restore the original system setting afterward.
5. Use arrow keys to move selection while the search field is focused. 5. Right-click representative text, link, image, file, and media cards. Confirm applicable commands appear in the context menu: paste/copy, plain-text variants, preview/open, edit/rename, pin/collect, Stack, image rotate/extract text, capture rules, show in Clipboard, and delete.
6. Tab to the search controls, collection `+`, toolbar buttons, and collection chips; confirm VoiceOver help explains the matching actions and shortcuts. Press `Space` or `Return` on a focused chip and confirm it is selected and the visible focus state is clear. Use Left/Right, Home, and End to move through the chip rail, including custom collections and Stack when present, and confirm VoiceOver help mentions those keys plus Pinboard/Stack context actions where available. 6. With a card focused, confirm `Return` pastes, `Shift + Return` uses plain text, `Command + C` copies, `Space` or `Command + Y` previews, `Command + O` opens applicable clips, `Command + E` edits text/code, and `Command + R` renames without changing the payload.
7. Tab to cards; confirm the focused card gets a clear focus border, `Return` pastes or copies it, `Command + C` copies it, `Shift + Return` and `Command + Shift + V` paste or copy it as plain text, and `Space` or `Command + Y` opens the built-in browser for web links or Quick Look for text, files, and media. 7. Press `Command + 1` through `Command + 9` and confirm the matching numbered cards are used; add `Shift` and confirm plain-text output.
8. With a card focused, press `Command + F` and confirm focus returns to search; press `Command + E` on a text/code clip and confirm the edit dialog opens. On a Mac with Writing Tools available, confirm the dialog offers Writing Tools and keeps the saved clip as plain text. Press `Command + R` and confirm the rename dialog opens. 8. Command-click non-adjacent cards and Shift-click a range. Confirm context-menu batch actions use the selected set and `Command + A` selects all visible cards.
9. With a card focused, use Left/Right, Page Up/Page Down, Home, End, `Command + Up`, and `Command + Down`; confirm selection and focus move together across the shelf. Select two clips, press `Delete`, confirm both disappear, then press `Command + Z` and confirm both return selected. 9. Delete multiple selected clips, press `Command + Z`, and confirm the batch returns selected.
10. With a card or collection chip focused, type a normal character and confirm focus returns to search with that character inserted and results filtered. 10. From a filtered result, choose Show in Clipboard or press `Command + G`; confirm search clears and the same clip stays selected in Clipboard.
11. Use a mouse wheel or two-finger vertical scroll over the card shelf and a crowded collection rail; confirm each pans horizontally, clamps at both ends, and shows subtle edge fades only where more content is hidden, with collection-chip labels fading cleanly instead of hard-clipping at the utility buttons. 11. Double-click a card and confirm paste or copy fallback occurs without creating a duplicate history item.
12. Right-click a filtered result and choose Show in Clipboard, or press `Command + G` with the result card focused, and confirm search clears while the same card stays selected in Most Recent. Press `Command + O` on a focused link, file, or media card and confirm it opens. 12. Confirm text cards do not repeat a one-line title in the body, multi-line text shows the remaining lines, files/PDFs use document previews, and missing source apps do not display `Unknown`.
13. Press `Esc` once with a non-empty search while the search field, a card, or a collection chip is focused and confirm search clears without closing the panel. 13. On multiple displays and Spaces, confirm the shortcut opens on the pointer's active display/Space and the menu-bar icon opens on its display. Switch Settings > General > Shelf side and verify both left and right placement.
14. Press `Esc` again and confirm the panel closes.
15. Reopen the panel, change sort segments, and confirm each segment updates results. ## Pinboards And Stack
16. Press `Shift + Command + N` or the collection rail `+`, enter `Client Work`, choose a color, and confirm a Client Work chip appears with 0 clips and an empty collection view.
17. Press `Command + N` or the shelf pencil button, enter text, and confirm a new text clip appears selected in the active shelf; on a Mac with Writing Tools available, confirm the new-text dialog offers Writing Tools. Repeat while Client Work is selected and confirm the clip is created in that collection. 1. Press `Shift + Command + N` or use the category-row add button to create an empty color-coded Pinboard named `Client Work`; confirm its labeled chip remains visible with no count pill.
18. Return to Clipboard, select a card, use its Collect button to choose Client Work, and confirm the Client Work chip count increases. 2. Assign an existing card through Collect or drag it onto the Pinboard. Confirm its count, color, and assignment survive relaunch and normal history pruning.
19. Select the Client Work chip and confirm the rail filters to assigned items, cards use the Client Work name/color in their headers, and the collection/color/assignment persists after quitting and reopening ClipBored. Confirm collection-assigned clips stay in Client Work even as normal clipboard history rolls over. 3. Right-click the Pinboard chip to edit its name/color, export it, and delete it. Import the archive into a fresh profile and confirm clips plus empty Pinboard metadata are restored.
20. Create a second collection, then press `Command + Right` and `Command + Left`; confirm selection moves between collections and wraps around. 4. Press `Shift + Command + C`, copy two clips, and confirm Stack capture records them in copy order. Toggle capture off again.
21. Right-click the Client Work chip, choose Edit Collection..., rename it, change its color, and confirm the chip and assigned card headers update. 5. From a card or Stack context menu, test Add Visible Clips to Stack, next-item paste/copy, Stack-as-text, and Clear Stack. Confirm queue order and duplicate protection.
22. Right-click a custom Pinboard chip, choose Export Pinboard..., save a `.clipboredarchive`, import it into a fresh test profile from Settings > Data, and confirm only that Pinboard's clips, empty Pinboard state, and color are restored.
23. Confirm collection chips with 0 clips do not show a visible count pill, while chips with clips still show their counts.
24. Right-click a media, file, link, PDF, audio, or text card, choose Rename..., give it a title, and confirm the card title and search results use the custom title while paste/copy still uses the original payload.
25. Right-click an image card or focus its action rail, choose `Rotate Image`, and confirm the preview updates while the title, Pinboard, source app, and searchable image text remain. Then choose `Extract Text` on an image containing text and confirm the card shows the extracted text and `Copy Plain Text` can copy it.
26. Double-click an item and confirm it attempts to paste or falls back to copy without creating a duplicate history entry.
27. Right-click a card, use Capture Rules to ignore its source app, copy from that app again, and confirm the new item is skipped.
28. Drag an unassigned card onto the renamed collection chip and confirm the chip count increases and the card appears when that collection is selected.
29. Open the panel and confirm it appears as a vertical side shelf with compact horizontal rows; hover a row and confirm it expands in place. On a multi-display setup, open from the global shortcut with the pointer on each display and confirm the shelf opens on that display; click the menu-bar icon and confirm it opens on the menu-bar icon's display. Switch Spaces or use a full-screen app and confirm the shelf opens on the active Space instead of following every desktop.
30. Switch Settings > General > Panel > Shelf side between Left and Right. Reopen the panel after each change and confirm it slides from the configured side and keeps the category row centered.
31. Select a file, rich text, or URL card, then hover or keyboard-focus it and confirm the action rail exposes `Paste Plain Text`, the corner source/kind badge remains visible, and on a narrow shelf secondary actions collapse behind `More` instead of overflowing the card.
32. Confirm card footers do not show `Unknown` for clips without a source app, confirm used clips show their usage count beside the source app, and confirm clips synced or imported from another Mac show that copied-on device in the footer.
33. Confirm card headers use readable relative ages such as `3 minutes ago` or `2 hours ago`, including when viewing a named collection.
34. Confirm the selected card shows a green corner Stack control, the hover/focus action rail does not duplicate Stack, and clips added to Stack keep a visible corner indicator when selection moves away.
35. Confirm text cards use a quiet paper-style body, single-line text cards do not repeat the same text in both title and body, and multi-line text cards show the remaining lines below the first line with a subtle bottom fade.
36. Confirm the Pinned empty state points to the Pin action instead of a plain-key shortcut.
37. Confirm each card's source or type badge reads as an attached header-corner tile instead of a small floating icon.
38. Confirm built-in collection chips use recognizable glyphs, while custom collection chips keep color-dot swatches.
39. Confirm cards from known apps show app identity in the header tile, falling back to source initials when an app icon is unavailable.
40. Confirm single-file and PDF cards show a centered document-cover preview with a file-type pill, while multi-file cards show a stacked file preview.
41. Confirm the shelf chrome uses one row with compact search, collection chips, and separate soft utility icon buttons instead of a heavy grouped block; typing a search expands the search field without pushing cards out of view.
42. Confirm the top collection rail reads as a quiet translucent strip, the selected collection is a subtle pill, and the active card visibly floats above neighboring cards while the rest stay docked in the shelf.
43. Copy a color swatch from a design tool and confirm it appears as a centered paint-chip Color card, can be filtered with the Colors chip, and copies back as both a color and hex text.
44. Copy a code snippet from an editor and confirm it appears as a Code card, remains visible in the Text chip, can be isolated with the Code chip or `type:code`, and copies back as plain text.
45. Copy a video/movie clip and confirm it appears as a Video card, uses a movie-frame thumbnail when available, filters with the Videos chip or `type:video`, `type:movie`, and `mp4`, previews/opens as a temp movie, and copies back as movie data.
46. Press `Shift + Command + C`, confirm the Stack chip appears active with 0 clips, copy two text snippets, and confirm Stack count increments and the Stack view shows them in copy order. Press `Shift + Command + C` again and confirm capture stops.
47. Filter to a few clips, right-click a card or the Stack chip, choose Add Visible Clips to Stack, and confirm only the visible clips are queued once in shelf order.
48. With multiple text-like clips in Stack, choose Copy Stack as Text or Paste Stack as Text and confirm the queued text is written in stack order with blank lines between clips and consumed from Stack.
49. Command-click non-adjacent cards and Shift-click a range; confirm the status count changes to selected clips, selected cards remain highlighted while hovering, and the card menu offers Paste Selection, Copy Selection, Paste Selection as Text, Copy Selection as Text, and Add Selection to Stack.
50. With a card focused, press `Shift` with Left/Right, Page Up/Page Down, Home, or End to extend the range, then press `Command + A` and confirm every visible card is selected without changing the active card.
## Copy And Paste ## Copy And Paste
1. Select a text item and press the Copy button. Confirm the system clipboard contains that text. 1. Copy/paste text, URL, image, audio, video, PDF, rich text, and file clips into suitable apps. Confirm original pasteboard representations are preserved.
2. Select a URL item and confirm the system clipboard contains both string and URL data by pasting into a browser address bar. 2. Paste a multi-file clip into Finder and confirm all file references are present.
3. Select one-file and multi-file File items and paste into Finder or an app that accepts file references. Confirm all files are preserved for the multi-file item. 3. Use plain-text paste on URL and rich-text clips and confirm formatting and non-text representations are omitted.
4. Select an audio item and paste into an app that accepts sound pasteboard data. 4. Without Accessibility permission, confirm paste falls back to copying and Settings > Privacy reports the permission requirement.
5. Select a Video item and paste into an app that accepts movie pasteboard data. 5. With Accessibility permission, confirm paste returns focus to the previous app and inserts the selected clip.
6. Select a PDF item and paste into Preview, Finder, or an app that accepts PDF pasteboard data.
7. Select a rich text item and paste into TextEdit rich text mode or Mail. Confirm basic formatting is preserved and plain-text paste still works in a text-only field.
8. Press `Command + 1` through `Command + 9` on visible numbered cards and confirm the matching card is pasted or copied; add `Shift` and confirm URL/rich items paste as plain text only.
9. Without Accessibility permission, confirm paste actions copy and show the permission fallback status.
10. With Accessibility permission granted, confirm paste returns focus to the previous app and inserts the selected item.
## Settings ## Settings
1. Open Settings with `Command + ,`. 1. With the ClipBored pane open, open Settings with `Command + ,` and confirm a resizable window with six clean selector tabs: `General`, `Shortcuts`, `Capture`, `Privacy`, `Performance`, and `Data`. Close the pane, switch to another app, and confirm `Command + ,` opens that app's settings instead of ClipBored.
2. Change Shelf side, Keep History, history length, default sort, polling profile, cache limit, ignored apps, and allowed content types; quit and reopen the app; confirm settings persist. 2. Resize to the practical minimum. Visit every tab and confirm content stays anchored to the top-left, scrolls vertically when needed, and has no horizontal clipping, zero-sized controls, or duplicate selector labels.
3. Change the open-panel shortcut and confirm the old shortcut no longer opens the panel and the new shortcut does. 3. In General, change shelf side, Keep History, history length, default sort, launch-at-login, and menu-bar/Dock presence. Relaunch and confirm persistence.
4. Toggle `Pause clipboard capture` or press `Command + T`, copy text, and confirm paused capture does not record it; press `Command + T` again and confirm capture resumes. 4. In Shortcuts, change the open shortcut, close Settings while a field is focused, and confirm the edited binding is committed and the old shortcut no longer opens the shelf.
5. Toggle `Exclude likely secrets`, copy a representative token, and confirm it is not recorded. 5. In Capture, pause/resume capture, toggle likely-secret exclusion and image-label search, edit ignored apps, and toggle allowed content types. Confirm at least one content type must remain enabled and status feedback stays inside this tab.
6. Toggle `Hide panel from screen sharing and recordings`, open the clipboard panel, and confirm it is omitted from a macOS screenshot or screen recording; disable it and confirm capture works normally again. 6. In Privacy, test clear-on-quit, screen-capture hiding, Accessibility settings, permission refresh, and paste-status feedback.
7. Use `Open Accessibility Settings` and confirm System Settings opens to the permission area or fallback settings app. 7. In Performance, change the polling profile and image-cache cap. Confirm capture continues at the selected cadence, UI input remains responsive while polling, and the values persist.
8. Use Settings > Data > `Export Archive...`, save a `.clipboredarchive`, then import it into a fresh or cleared test profile and confirm text, Pinboard assignments, image previews, and PDF/audio/video/rich-text clips reappear; confirm external file-reference clips still point at their original paths. 8. In Data, export/import an archive, exercise available iCloud controls, open the history folder, and confirm destructive clear actions require confirmation and show success or error feedback in the Data page.
9. In an ad-hoc local build, turn on Settings > Data > `Sync history with iCloud` and confirm the status reports iCloud Sync unavailable. In a signed build with an iCloud entitlement, use `Sync Now`, then restore into a fresh test profile and confirm text, Pinboard assignments, and app-managed attachments reappear. 9. Change one control and confirm unrelated tabs do not jump, reset, or flash; long status messages should wrap instead of widening the window.
10. Use `Clear Clipboard History` and `Clear Thumbnail Cache`; confirm each shows a warning confirmation before deleting data.
## Storage And Privacy ## Storage And Privacy
1. Open the data folder from Settings > Data. 1. Open the data folder and confirm `history.sqlite`, `images/`, and `attachments/` appear as applicable.
2. Confirm `history.sqlite` exists after capture. 2. Copy unique text and managed attachment data; confirm `strings` does not expose the test content from the SQLite database or encrypted sidecars.
3. Copy unique text and confirm `strings ~/Library/Application\ Support/ClipBored/history.sqlite | grep "unique text"` does not find it. 3. Treat exported and iCloud `.clipboredarchive` files as sensitive because they are portable and not encrypted by ClipBored.
4. Copy uniquely identifiable rich text/audio/video/PDF data and confirm `strings ~/Library/Application\ Support/ClipBored/attachments/* | grep "unique text"` does not find it. 4. Open or reveal encrypted media, quit ClipBored, and confirm temporary preview files under `/tmp/ClipBored/Previews` are removed.
5. Export an archive with unique test content and confirm the archive file is treated as sensitive backup material because it is portable and not encrypted by ClipBored. 5. Clear history and confirm saved rows, managed attachments, temporary previews, and the fallback encryption key are removed when present. Clear the thumbnail cache separately and confirm history remains.
6. If iCloud Sync is enabled in a signed build, confirm `ClipBored.clipboredarchive` in the app-private iCloud container is treated as sensitive backup material because it is portable and not encrypted by ClipBored. 6. Enable `Clear history on quit`, relaunch, and confirm history and managed cache/attachment files were removed.
7. If `history-encryption.key` exists, confirm it is readable only by the current user.
8. Confirm image files are under `images/` and rich text/audio/video/PDF attachments are under `attachments/`.
9. Confirm app storage is local to `~/Library/Application Support/ClipBored` when iCloud Sync is off.
10. Open or reveal an encrypted image/audio/video/PDF, then quit ClipBored and confirm `/tmp/ClipBored/Previews` is removed.
11. Use `Clear Clipboard History` and confirm saved history, app-managed attachments, temporary previews, and `history-encryption.key` are removed when that fallback key exists.
12. Confirm quitting with `Clear history on quit` enabled removes history and app-managed cache/attachment files.
## Launch And Lifecycle ## Launch And Lifecycle
1. Enable Launch at Login, log out and back in, and confirm ClipBored starts. 1. Enable and disable Launch at Login and verify the next login behavior each time.
2. Disable Launch at Login and confirm it no longer starts after the next login. 2. Right-click or Control-click the menu-bar icon and confirm the menu includes capture state/count, Show Clipboard, New Collection, Stack Capture, Settings, pause/resume options, and Quit.
3. Right-click the menu-bar icon and confirm the status menu opens with capture state, clip count, Show Clipboard, Settings, Pause/Resume Capture, Pause for 5 Minutes, Pause for 30 Minutes, Pause for 1 Hour, and Quit. 3. Test a timed pause, manual pause, and resume; confirm copied items are skipped only while capture is paused.
4. Control-click the menu-bar icon and confirm the same status menu opens without toggling the panel. 4. Quit from the menu-bar menu and confirm no `ClipBored` process remains.
5. Choose `Pause for 5 Minutes`, confirm the status detail shows a timed pause and copied text is not recorded, then choose `Resume Capture`.
6. Toggle manual Pause/Resume Capture from the status menu and confirm the status row changes.
7. Quit ClipBored from the menu bar and confirm no `ClipBored` process remains.

View File

@@ -1,11 +1,15 @@
1. When hovering over a copied item, the options that appear on hover obscure the text. # UI Cleanup Resolution
2. When hovering over an item, key board arrow navigation breaks.
3. There needs to be some kind of animation? or smooothening effect when switching categories. All eleven findings from the original cleanup list are resolved in the current shelf design.
4. The search bar is broken when compressed, and clicking elsewhere should compress it again.
5. The search filter should just be the categories selected. Select categories with cmd. 1. [x] **Hover controls obscured clip text.** Hover now expands the preview visually; commands are exposed through the context menu and keyboard, so no hover rail covers content.
6. There're a lot of categories, if there's nothing in them, don't show the categories by default. 2. [x] **Hover broke keyboard navigation.** Hover state is independent from keyboard focus and selection, and arrow navigation clears stale hover ownership without changing the wrong clip.
7. There is a resize bar at the top lip of the window, don't bother with it. it doesn't allow resizing anywa.yz 3. [x] **Category changes felt abrupt.** Search, category, card, and panel changes use short eased transitions and become immediate when macOS Reduce Motion is enabled.
8. Get rid of new text clip button. Don't need it. 4. [x] **The collapsed search control was broken.** Search has one aligned container: it expands on click, typing, or `Command + F`, and collapses after click-away only when the query is empty.
9. Get rid of compact mode. 5. [x] **Filtering was split across categories and a search menu.** Category chips are the primary visual filters; a click replaces the filter and Command-click builds a union. `Command + F` only focuses search.
10. Get rid of close window. Don't need it. We use the macro from the keyboard. 6. [x] **Empty built-in categories added noise.** Built-in type/sort chips are created only when they have matches or are selected; empty custom Pinboards remain visible by design.
11. Get rid of the status bar. 7. [x] **A nonfunctional resize lip was visible.** The shelf has no resize handle and uses its fixed side-shelf frame.
8. [x] **New Text Clip was unnecessary.** The panel, menu-bar menu, and shortcut map no longer expose a new-text action.
9. [x] **The alternate compact mode was unnecessary.** Settings exposes one Side Shelf layout; row sizing adapts automatically to available space instead of presenting a mode toggle.
10. [x] **The panel did not need a close control.** There is no close button in shelf chrome; `Esc` and the configured global shortcut dismiss it.
11. [x] **The persistent status bar consumed space.** The shelf flows directly from its toolbar into the side-rail card list; feedback is shown in the relevant menu or Settings page.

View File

@@ -44,7 +44,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private var statusMenu: NSMenu? private var statusMenu: NSMenu?
private var pauseResumeTimer: Timer? private var pauseResumeTimer: Timer?
private var cloudSyncPushWorkItem: DispatchWorkItem? private var cloudSyncPushWorkItem: DispatchWorkItem?
private let cloudSyncOperationQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "clipbored.cloud-sync"
queue.qualityOfService = .utility
queue.maxConcurrentOperationCount = 1
return queue
}()
private let cloudSyncStateLock = NSLock()
private var suppressCloudSyncPush = false private var suppressCloudSyncPush = false
private var cloudSyncOperationGeneration = 0
func applicationDidFinishLaunching(_ notification: Notification) { func applicationDidFinishLaunching(_ notification: Notification) {
settings = SettingsModel() settings = SettingsModel()
@@ -57,7 +66,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
settings: settings, settings: settings,
cacheService: cacheService, cacheService: cacheService,
pollClipboardNow: { [weak monitor] in pollClipboardNow: { [weak monitor] in
monitor?.pollNowAndWait() monitor?.pollNow()
}, },
openSettings: { [weak self] in openSettings: { [weak self] in
self?.openSettings() self?.openSettings()
@@ -79,12 +88,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self?.panelController.toggle() self?.panelController.toggle()
} }
}, },
onOpenSettings: { [weak self] in
DispatchQueue.main.async {
self?.refreshAccessibilityPermissionMessage()
self?.settingsController.show()
}
},
onToggleStackCapture: { [weak self] in onToggleStackCapture: { [weak self] in
DispatchQueue.main.async { DispatchQueue.main.async {
self?.panelController.toggleStackCaptureMode() self?.panelController.toggleStackCaptureMode()
@@ -95,8 +98,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self?.settings.setShortcutStatus(message: status.message) self?.settings.setShortcutStatus(message: status.message)
} }
}, },
openShortcut: settings.openShortcut, openShortcut: settings.openShortcut
settingsShortcut: settings.settingsShortcut
) )
bindSettings() bindSettings()
bindCloudSync() bindCloudSync()
@@ -120,6 +122,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillTerminate(_ notification: Notification) { func applicationWillTerminate(_ notification: Notification) {
pauseResumeTimer?.invalidate() pauseResumeTimer?.invalidate()
cloudSyncPushWorkItem?.cancel() cloudSyncPushWorkItem?.cancel()
cloudSyncOperationQueue.cancelAllOperations()
monitor.stop() monitor.stop()
shortcutManager.stop() shortcutManager.stop()
cacheService.clearTemporaryPreviews(wait: true) cacheService.clearTemporaryPreviews(wait: true)
@@ -571,7 +574,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
observedInitialItems = true observedInitialItems = true
return return
} }
guard self.settings.iCloudSyncEnabled, !self.suppressCloudSyncPush else { return } guard self.settings.iCloudSyncEnabled, !self.isCloudSyncPushSuppressed else { return }
self.scheduleCloudSyncPush() self.scheduleCloudSyncPush()
} }
@@ -590,22 +593,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
store.normalizeHistoryLength() store.normalizeHistoryLength()
case .imageCacheMaxBytes: case .imageCacheMaxBytes:
cacheService.purgeIfNeeded(maxBytes: settings.imageCacheMaxBytes) cacheService.purgeIfNeeded(maxBytes: settings.imageCacheMaxBytes)
case .openShortcut, .settingsShortcut: case .openShortcut:
let status = shortcutManager.reconfigure(openShortcut: settings.openShortcut, settingsShortcut: settings.settingsShortcut) let status = shortcutManager.reconfigure(openShortcut: settings.openShortcut)
settings.setShortcutStatus(message: status.message) settings.setShortcutStatus(message: status.message)
refreshStatusItem() refreshStatusItem()
configureMainMenu() configureMainMenu()
case .settingsShortcut:
refreshStatusItem()
configureMainMenu()
case .launchAtLogin: case .launchAtLogin:
applyLaunchAtLoginSetting(settings.launchAtLogin) applyLaunchAtLoginSetting(settings.launchAtLogin)
case .showMenuBarIcon: case .showMenuBarIcon:
applyPresentation(changedSurface: .menuBar) applyPresentation(changedSurface: .menuBar)
case .showDockIcon: case .showDockIcon:
applyPresentation(changedSurface: .dock) applyPresentation(changedSurface: .dock)
case .compactMode: case .panelSide:
break
case .panelLayout:
break
case .panelSizing:
break break
case .cloudSync: case .cloudSync:
applyCloudSyncSetting() applyCloudSyncSetting()
@@ -627,30 +629,43 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private func applyCloudSyncSetting() { private func applyCloudSyncSetting() {
cloudSyncPushWorkItem?.cancel() cloudSyncPushWorkItem?.cancel()
cloudSyncPushWorkItem = nil cloudSyncPushWorkItem = nil
cloudSyncOperationGeneration += 1
let generation = cloudSyncOperationGeneration
guard settings.iCloudSyncEnabled else { guard settings.iCloudSyncEnabled else {
setCloudSyncPushSuppressed(false)
settings.setCloudSyncStatus(message: "iCloud Sync is off.") settings.setCloudSyncStatus(message: "iCloud Sync is off.")
return return
} }
let status = cloudSyncService.status() settings.setCloudSyncStatus(message: "Checking iCloud Sync…")
settings.setCloudSyncStatus(message: status.message) setCloudSyncPushSuppressed(true)
guard status.isAvailable else { return } cloudSyncOperationQueue.addOperation { [weak self] in
pullCloudSyncArchiveIfAvailable() guard let self else { return }
} let status = self.cloudSyncService.status()
let result: (message: String, schedulesInitialPush: Bool)
private func pullCloudSyncArchiveIfAvailable() { if !status.isAvailable {
suppressCloudSyncPush = true result = (status.message, false)
defer { suppressCloudSyncPush = false } } else {
do { do {
let summary = try cloudSyncService.pull(store: store) let summary = try self.cloudSyncService.pull(store: self.store)
settings.setCloudSyncStatus(message: "Restored \(summary.itemCount) clips from iCloud.") result = ("Restored \(summary.itemCount) clips from iCloud.", false)
} catch ClipboardCloudSyncError.noRemoteArchive(_) { } catch ClipboardCloudSyncError.noRemoteArchive(_) {
settings.setCloudSyncStatus(message: "iCloud Sync is ready. No remote archive yet.") result = ("iCloud Sync is ready. No remote archive yet.", true)
scheduleCloudSyncPush(after: 1.0)
} catch { } catch {
settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)") result = ("iCloud Sync failed: \(error.localizedDescription)", false)
}
}
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.setCloudSyncPushSuppressed(false)
guard generation == self.cloudSyncOperationGeneration,
self.settings.iCloudSyncEnabled else { return }
self.settings.setCloudSyncStatus(message: result.message)
if result.schedulesInitialPush {
self.scheduleCloudSyncPush(after: 1.0)
}
}
} }
} }
@@ -665,12 +680,35 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private func pushCloudSyncArchive() { private func pushCloudSyncArchive() {
guard settings.iCloudSyncEnabled else { return } guard settings.iCloudSyncEnabled else { return }
let generation = cloudSyncOperationGeneration
cloudSyncOperationQueue.addOperation { [weak self] in
guard let self else { return }
let message: String
do { do {
let summary = try cloudSyncService.push(store: store) let summary = try self.cloudSyncService.push(store: self.store)
settings.setCloudSyncStatus(message: "Synced \(summary.itemCount) clips to iCloud.") message = "Synced \(summary.itemCount) clips to iCloud."
} catch { } catch {
settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)") message = "iCloud Sync failed: \(error.localizedDescription)"
} }
DispatchQueue.main.async { [weak self] in
guard let self,
generation == self.cloudSyncOperationGeneration,
self.settings.iCloudSyncEnabled else { return }
self.settings.setCloudSyncStatus(message: message)
}
}
}
private var isCloudSyncPushSuppressed: Bool {
cloudSyncStateLock.lock()
defer { cloudSyncStateLock.unlock() }
return suppressCloudSyncPush
}
private func setCloudSyncPushSuppressed(_ suppressed: Bool) {
cloudSyncStateLock.lock()
suppressCloudSyncPush = suppressed
cloudSyncStateLock.unlock()
} }
private func applyCapturePauseSetting(now: Date = Date()) { private func applyCapturePauseSetting(now: Date = Date()) {

View File

@@ -25,15 +25,6 @@ enum HistoryRetention: Int {
} }
} }
enum ClipboardPanelLayout: Int, CaseIterable {
case horizontal = 0
case vertical = 1
var title: String {
"Side Shelf"
}
}
enum ClipboardPanelSide: Int, CaseIterable { enum ClipboardPanelSide: Int, CaseIterable {
case left = 0 case left = 0
case right = 1 case right = 1
@@ -59,9 +50,7 @@ final class SettingsModel {
case launchAtLogin case launchAtLogin
case showMenuBarIcon case showMenuBarIcon
case showDockIcon case showDockIcon
case compactMode case panelSide
case panelLayout
case panelSizing
case cloudSync case cloudSync
case pauseCapture case pauseCapture
case ignoredApps case ignoredApps
@@ -87,10 +76,7 @@ final class SettingsModel {
static let launchAtLogin = "launchAtLogin" static let launchAtLogin = "launchAtLogin"
static let showMenuBarIcon = "showMenuBarIcon" static let showMenuBarIcon = "showMenuBarIcon"
static let showDockIcon = "showDockIcon" static let showDockIcon = "showDockIcon"
static let compactMode = "compactMode"
static let panelLayout = "panelLayout"
static let panelSide = "panelSide" static let panelSide = "panelSide"
static let panelShelfHeight = "panelShelfHeight"
static let iCloudSyncEnabled = "iCloudSyncEnabled" static let iCloudSyncEnabled = "iCloudSyncEnabled"
static let openShortcut = "openShortcut" static let openShortcut = "openShortcut"
static let settingsShortcut = "settingsShortcut" static let settingsShortcut = "settingsShortcut"
@@ -142,22 +128,8 @@ final class SettingsModel {
var showDockIcon: Bool { var showDockIcon: Bool {
didSet { if oldValue != showDockIcon { storeAndNotify(.showDockIcon) } } didSet { if oldValue != showDockIcon { storeAndNotify(.showDockIcon) } }
} }
var compactMode: Bool {
didSet { if oldValue != compactMode { storeAndNotify(.compactMode) } }
}
var panelLayout: ClipboardPanelLayout {
didSet {
if panelLayout != .vertical {
panelLayout = .vertical
}
if oldValue != panelLayout { storeAndNotify(.panelLayout) }
}
}
var panelSide: ClipboardPanelSide { var panelSide: ClipboardPanelSide {
didSet { if oldValue != panelSide { storeAndNotify(.panelLayout) } } didSet { if oldValue != panelSide { storeAndNotify(.panelSide) } }
}
var panelShelfHeight: Double {
didSet { if oldValue != panelShelfHeight { storeAndNotify(.panelSizing) } }
} }
var iCloudSyncEnabled: Bool { var iCloudSyncEnabled: Bool {
didSet { didSet {
@@ -241,10 +213,7 @@ final class SettingsModel {
launchAtLogin = defaults.object(forKey: Keys.launchAtLogin) as? Bool ?? false launchAtLogin = defaults.object(forKey: Keys.launchAtLogin) as? Bool ?? false
showMenuBarIcon = defaults.object(forKey: Keys.showMenuBarIcon) as? Bool ?? true showMenuBarIcon = defaults.object(forKey: Keys.showMenuBarIcon) as? Bool ?? true
showDockIcon = defaults.object(forKey: Keys.showDockIcon) as? Bool ?? false showDockIcon = defaults.object(forKey: Keys.showDockIcon) as? Bool ?? false
compactMode = defaults.object(forKey: Keys.compactMode) as? Bool ?? false
panelLayout = .vertical
panelSide = savedPanelSide.flatMap(ClipboardPanelSide.init(rawValue:)) ?? .right panelSide = savedPanelSide.flatMap(ClipboardPanelSide.init(rawValue:)) ?? .right
panelShelfHeight = defaults.object(forKey: Keys.panelShelfHeight) as? Double ?? 0
iCloudSyncEnabled = defaults.object(forKey: Keys.iCloudSyncEnabled) as? Bool ?? false iCloudSyncEnabled = defaults.object(forKey: Keys.iCloudSyncEnabled) as? Bool ?? false
openShortcut = Self.readShortcut(from: defaults.string(forKey: Keys.openShortcut)) ?? AppConfiguration.defaultOpenShortcut openShortcut = Self.readShortcut(from: defaults.string(forKey: Keys.openShortcut)) ?? AppConfiguration.defaultOpenShortcut
settingsShortcut = Self.readShortcut(from: defaults.string(forKey: Keys.settingsShortcut)) ?? AppConfiguration.defaultSettingsShortcut settingsShortcut = Self.readShortcut(from: defaults.string(forKey: Keys.settingsShortcut)) ?? AppConfiguration.defaultSettingsShortcut
@@ -271,10 +240,6 @@ final class SettingsModel {
maxHistoryItems = Self.clampedMaxHistoryItems(maxHistoryItems) maxHistoryItems = Self.clampedMaxHistoryItems(maxHistoryItems)
imageCacheMaxBytes = Self.clampedImageCacheMaxBytes(imageCacheMaxBytes) imageCacheMaxBytes = Self.clampedImageCacheMaxBytes(imageCacheMaxBytes)
if panelShelfHeight < 0 {
panelShelfHeight = 0
}
if defaults.object(forKey: Keys.maxHistoryItems) == nil if defaults.object(forKey: Keys.maxHistoryItems) == nil
|| savedHistory != maxHistoryItems || savedHistory != maxHistoryItems
|| defaults.object(forKey: Keys.historyRetention) == nil || defaults.object(forKey: Keys.historyRetention) == nil
@@ -282,7 +247,6 @@ final class SettingsModel {
|| savedCache <= 0 || savedCache <= 0
|| Int64(savedCache) != imageCacheMaxBytes || Int64(savedCache) != imageCacheMaxBytes
|| storedIgnoredItemKinds != ignoredItemKindsRaw || storedIgnoredItemKinds != ignoredItemKindsRaw
|| defaults.object(forKey: Keys.panelLayout) as? Int != ClipboardPanelLayout.vertical.rawValue
|| savedPanelSide == nil || savedPanelSide == nil
|| ClipboardPanelSide(rawValue: savedPanelSide ?? -1) == nil { || ClipboardPanelSide(rawValue: savedPanelSide ?? -1) == nil {
store() store()
@@ -299,10 +263,7 @@ final class SettingsModel {
defaults.set(launchAtLogin, forKey: Keys.launchAtLogin) defaults.set(launchAtLogin, forKey: Keys.launchAtLogin)
defaults.set(showMenuBarIcon, forKey: Keys.showMenuBarIcon) defaults.set(showMenuBarIcon, forKey: Keys.showMenuBarIcon)
defaults.set(showDockIcon, forKey: Keys.showDockIcon) defaults.set(showDockIcon, forKey: Keys.showDockIcon)
defaults.set(compactMode, forKey: Keys.compactMode)
defaults.set(panelLayout.rawValue, forKey: Keys.panelLayout)
defaults.set(panelSide.rawValue, forKey: Keys.panelSide) defaults.set(panelSide.rawValue, forKey: Keys.panelSide)
defaults.set(panelShelfHeight, forKey: Keys.panelShelfHeight)
defaults.set(iCloudSyncEnabled, forKey: Keys.iCloudSyncEnabled) defaults.set(iCloudSyncEnabled, forKey: Keys.iCloudSyncEnabled)
defaults.set(openShortcut.encoded(), forKey: Keys.openShortcut) defaults.set(openShortcut.encoded(), forKey: Keys.openShortcut)
defaults.set(settingsShortcut.encoded(), forKey: Keys.settingsShortcut) defaults.set(settingsShortcut.encoded(), forKey: Keys.settingsShortcut)

View File

@@ -24,36 +24,28 @@ final class ShortcutManager {
private enum HotKeyID: UInt32 { private enum HotKeyID: UInt32 {
case openPanel = 1 case openPanel = 1
case openSettings = 2
case stackCapture = 3 case stackCapture = 3
} }
private let onOpenClipboardPanel: () -> Void private let onOpenClipboardPanel: () -> Void
private let onOpenSettings: () -> Void
private let onToggleStackCapture: () -> Void private let onToggleStackCapture: () -> Void
private let onStatusChange: (RegistrationStatus) -> Void private let onStatusChange: (RegistrationStatus) -> Void
private var openBinding: ShortcutBinding private var openBinding: ShortcutBinding
private var settingsBinding: ShortcutBinding
private var openHotKey: EventHotKeyRef? private var openHotKey: EventHotKeyRef?
private var settingsHotKey: EventHotKeyRef?
private var stackCaptureHotKey: EventHotKeyRef? private var stackCaptureHotKey: EventHotKeyRef?
private var eventHandler: EventHandlerRef? private var eventHandler: EventHandlerRef?
init( init(
onOpenClipboardPanel: @escaping () -> Void, onOpenClipboardPanel: @escaping () -> Void,
onOpenSettings: @escaping () -> Void,
onToggleStackCapture: @escaping () -> Void = {}, onToggleStackCapture: @escaping () -> Void = {},
onStatusChange: @escaping (RegistrationStatus) -> Void = { _ in }, onStatusChange: @escaping (RegistrationStatus) -> Void = { _ in },
openShortcut: ShortcutBinding, openShortcut: ShortcutBinding
settingsShortcut: ShortcutBinding
) { ) {
self.onOpenClipboardPanel = onOpenClipboardPanel self.onOpenClipboardPanel = onOpenClipboardPanel
self.onOpenSettings = onOpenSettings
self.onToggleStackCapture = onToggleStackCapture self.onToggleStackCapture = onToggleStackCapture
self.onStatusChange = onStatusChange self.onStatusChange = onStatusChange
self.openBinding = openShortcut self.openBinding = openShortcut
self.settingsBinding = settingsShortcut
} }
deinit { deinit {
@@ -64,16 +56,11 @@ final class ShortcutManager {
func start() -> RegistrationStatus { func start() -> RegistrationStatus {
stop() stop()
if let status = Self.validationFailure(for: openBinding) ?? Self.validationFailure(for: settingsBinding) { if let status = Self.validationFailure(for: openBinding) {
onStatusChange(status) onStatusChange(status)
return status return status
} }
if openBinding == settingsBinding { if openBinding == Self.stackCaptureShortcut {
let status = RegistrationStatus.conflict(openBinding.displayText)
onStatusChange(status)
return status
}
if openBinding == Self.stackCaptureShortcut || settingsBinding == Self.stackCaptureShortcut {
let status = RegistrationStatus.conflict(Self.stackCaptureShortcut.displayText) let status = RegistrationStatus.conflict(Self.stackCaptureShortcut.displayText)
onStatusChange(status) onStatusChange(status)
return status return status
@@ -107,13 +94,6 @@ final class ShortcutManager {
return openStatus return openStatus
} }
let settingsStatus = register(binding: settingsBinding, id: .openSettings, target: &settingsHotKey)
guard settingsStatus == .registered else {
stop()
onStatusChange(settingsStatus)
return settingsStatus
}
let stackCaptureStatus = register(binding: Self.stackCaptureShortcut, id: .stackCapture, target: &stackCaptureHotKey) let stackCaptureStatus = register(binding: Self.stackCaptureShortcut, id: .stackCapture, target: &stackCaptureHotKey)
guard stackCaptureStatus == .registered else { guard stackCaptureStatus == .registered else {
stop() stop()
@@ -126,9 +106,8 @@ final class ShortcutManager {
} }
@discardableResult @discardableResult
func reconfigure(openShortcut: ShortcutBinding, settingsShortcut: ShortcutBinding) -> RegistrationStatus { func reconfigure(openShortcut: ShortcutBinding) -> RegistrationStatus {
openBinding = openShortcut openBinding = openShortcut
settingsBinding = settingsShortcut
return start() return start()
} }
@@ -136,9 +115,6 @@ final class ShortcutManager {
if let openHotKey { if let openHotKey {
UnregisterEventHotKey(openHotKey) UnregisterEventHotKey(openHotKey)
} }
if let settingsHotKey {
UnregisterEventHotKey(settingsHotKey)
}
if let stackCaptureHotKey { if let stackCaptureHotKey {
UnregisterEventHotKey(stackCaptureHotKey) UnregisterEventHotKey(stackCaptureHotKey)
} }
@@ -147,7 +123,6 @@ final class ShortcutManager {
} }
openHotKey = nil openHotKey = nil
settingsHotKey = nil
stackCaptureHotKey = nil stackCaptureHotKey = nil
eventHandler = nil eventHandler = nil
} }
@@ -206,8 +181,6 @@ final class ShortcutManager {
switch HotKeyID(rawValue: hotKeyID.id) { switch HotKeyID(rawValue: hotKeyID.id) {
case .openPanel: case .openPanel:
onOpenClipboardPanel() onOpenClipboardPanel()
case .openSettings:
onOpenSettings()
case .stackCapture: case .stackCapture:
onToggleStackCapture() onToggleStackCapture()
case nil: case nil:
@@ -288,6 +261,10 @@ final class ShortcutManager {
modifierFlags: NSEvent.ModifierFlags([.command, .shift]).rawValue modifierFlags: NSEvent.ModifierFlags([.command, .shift]).rawValue
) )
static func globalShortcutBindings(openShortcut: ShortcutBinding) -> [ShortcutBinding] {
[openShortcut, stackCaptureShortcut]
}
private func osStatusMessage(_ status: OSStatus) -> String { private func osStatusMessage(_ status: OSStatus) -> String {
"OSStatus \(status)" "OSStatus \(status)"
} }

View File

@@ -59,14 +59,12 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
static let hideDuration: TimeInterval = 0.16 static let hideDuration: TimeInterval = 0.16
static let reflowDuration: TimeInterval = 0.18 static let reflowDuration: TimeInterval = 0.18
static let easing: CAMediaTimingFunctionName = .easeInEaseOut static let easing: CAMediaTimingFunctionName = .easeInEaseOut
static func duration(_ preferredDuration: TimeInterval) -> TimeInterval {
NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? 0 : preferredDuration
}
} }
private enum Metrics { private enum Metrics {
static let shelfHeightRatio: CGFloat = 0.18
static let minimumShelfHeight: CGFloat = 156
static let maximumShelfHeight: CGFloat = 176
static let minimumUserShelfHeight: CGFloat = 150
static let maximumUserShelfHeight: CGFloat = 680
static let maximumUserShelfHeightRatio: CGFloat = 0.72
static let preferredVerticalShelfWidth: CGFloat = 336 static let preferredVerticalShelfWidth: CGFloat = 336
static let minimumVerticalShelfWidth: CGFloat = 320 static let minimumVerticalShelfWidth: CGFloat = 320
static let maximumVerticalShelfWidthRatio: CGFloat = 0.30 static let maximumVerticalShelfWidthRatio: CGFloat = 0.30
@@ -170,7 +168,7 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
applyPanelSharingSetting() applyPanelSharingSetting()
settings.observe { [weak self] change in settings.observe { [weak self] change in
guard change == .hideFromScreenCapture || change == .panelLayout else { return } guard change == .hideFromScreenCapture || change == .panelSide else { return }
DispatchQueue.main.async { DispatchQueue.main.async {
if change == .hideFromScreenCapture { if change == .hideFromScreenCapture {
self?.applyPanelSharingSetting() self?.applyPanelSharingSetting()
@@ -205,13 +203,6 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
} }
} }
func createTextClip() {
performWhenVisible { [weak self] in
guard let self else { return }
self.panelView.createTextClip()
}
}
func createCollection() { func createCollection() {
performWhenVisible { [weak self] in performWhenVisible { [weak self] in
guard let self else { return } guard let self else { return }
@@ -256,7 +247,7 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
panelView.beginOpeningTransition() panelView.beginOpeningTransition()
NSAnimationContext.runAnimationGroup { context in NSAnimationContext.runAnimationGroup { context in
context.duration = Animation.showDuration context.duration = Animation.duration(Animation.showDuration)
context.allowsImplicitAnimation = true context.allowsImplicitAnimation = true
context.timingFunction = CAMediaTimingFunction(name: Animation.easing) context.timingFunction = CAMediaTimingFunction(name: Animation.easing)
panel.animator().setFrame(frames.shown, display: true) panel.animator().setFrame(frames.shown, display: true)
@@ -299,7 +290,7 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
isAnimating = true isAnimating = true
NSAnimationContext.runAnimationGroup { context in NSAnimationContext.runAnimationGroup { context in
context.duration = Animation.hideDuration context.duration = Animation.duration(Animation.hideDuration)
context.allowsImplicitAnimation = true context.allowsImplicitAnimation = true
context.timingFunction = CAMediaTimingFunction(name: Animation.easing) context.timingFunction = CAMediaTimingFunction(name: Animation.easing)
panel.animator().alphaValue = 0.0 panel.animator().alphaValue = 0.0
@@ -323,7 +314,9 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
} }
show() show()
DispatchQueue.main.asyncAfter(deadline: .now() + Animation.showDuration + 0.03) { [weak self] in let animationDelay = Animation.duration(Animation.showDuration)
let deadline = DispatchTime.now() + animationDelay + (animationDelay > 0 ? 0.03 : 0)
DispatchQueue.main.asyncAfter(deadline: deadline) { [weak self] in
guard let self, self.isVisible else { return } guard let self, self.isVisible else { return }
action() action()
} }
@@ -374,7 +367,6 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
static func panelFrames( static func panelFrames(
forScreenFrame screenFrame: CGRect, forScreenFrame screenFrame: CGRect,
visibleFrame: CGRect, visibleFrame: CGRect,
preferredHeight _: CGFloat? = nil,
side: ClipboardPanelSide = .right side: ClipboardPanelSide = .right
) -> (shown: NSRect, hidden: NSRect) { ) -> (shown: NSRect, hidden: NSRect) {
let intersectedFrame = visibleFrame.intersection(screenFrame) let intersectedFrame = visibleFrame.intersection(screenFrame)
@@ -454,7 +446,6 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
static func reflowPlan( static func reflowPlan(
forScreenFrame screenFrame: CGRect, forScreenFrame screenFrame: CGRect,
visibleFrame: CGRect, visibleFrame: CGRect,
preferredHeight _: CGFloat? = nil,
side: ClipboardPanelSide = .right side: ClipboardPanelSide = .right
) -> ClipboardPanelReflowPlan { ) -> ClipboardPanelReflowPlan {
let frames = panelFrames( let frames = panelFrames(
@@ -526,6 +517,15 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
self.viewModel.sortMode = mode self.viewModel.sortMode = mode
return nil return nil
} }
if self.shouldHandlePanelKeyEvent(event, allowSearchFieldEditing: true),
Self.matchesShortcut(
keyCode: event.keyCode,
modifiers: event.modifierFlags,
binding: self.settings.settingsShortcut
) {
self.openSettings()
return nil
}
if self.shouldHandlePanelKeyEvent(event, allowSearchFieldEditing: true), if self.shouldHandlePanelKeyEvent(event, allowSearchFieldEditing: true),
let action = Self.commandShortcutAction(forKeyCode: event.keyCode, modifiers: event.modifierFlags) { let action = Self.commandShortcutAction(forKeyCode: event.keyCode, modifiers: event.modifierFlags) {
self.performShortcutAction(action) self.performShortcutAction(action)
@@ -624,7 +624,7 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
case .edit: case .edit:
panelView.editSelectedClip() panelView.editSelectedClip()
case .focusSearch: case .focusSearch:
panelView.focusSearchOrShowFilters() panelView.focusSearch()
case .newCollection: case .newCollection:
panelView.createCollection() panelView.createCollection()
case .nextCollection: case .nextCollection:
@@ -775,6 +775,18 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
return keyCode == 49 && relevantModifiers.isEmpty && searchText.clipboardTrimmed.isEmpty return keyCode == 49 && relevantModifiers.isEmpty && searchText.clipboardTrimmed.isEmpty
} }
static func matchesShortcut(
keyCode: UInt16,
modifiers: NSEvent.ModifierFlags,
binding: ShortcutBinding
) -> Bool {
guard ShortcutManager.virtualKeyCode(for: binding.key) == keyCode else { return false }
let relevantModifiers = modifiers.intersection(.deviceIndependentFlagsMask)
let bindingModifiers = NSEvent.ModifierFlags(rawValue: binding.modifierFlags)
.intersection(.deviceIndependentFlagsMask)
return relevantModifiers == bindingModifiers
}
static func commandShortcutAction(forKeyCode keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> ClipboardPanelShortcutAction? { static func commandShortcutAction(forKeyCode keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> ClipboardPanelShortcutAction? {
let relevantModifiers = modifiers.intersection(.deviceIndependentFlagsMask) let relevantModifiers = modifiers.intersection(.deviceIndependentFlagsMask)
guard relevantModifiers == .command else { return nil } guard relevantModifiers == .command else { return nil }
@@ -924,7 +936,7 @@ final class ClipboardPanelController: NSObject, NSWindowDelegate, QLPreviewPanel
isAnimating = true isAnimating = true
NSAnimationContext.runAnimationGroup { context in NSAnimationContext.runAnimationGroup { context in
context.duration = Animation.reflowDuration context.duration = Animation.duration(Animation.reflowDuration)
context.allowsImplicitAnimation = true context.allowsImplicitAnimation = true
context.timingFunction = CAMediaTimingFunction(name: Animation.easing) context.timingFunction = CAMediaTimingFunction(name: Animation.easing)
panel.animator().setFrame(plan.frame, display: true) panel.animator().setFrame(plan.frame, display: true)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -8,11 +8,12 @@ private final class TopAlignedSettingsDocumentView: NSView {
final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDelegate, NSTextViewDelegate { final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDelegate, NSTextViewDelegate {
private enum Metrics { private enum Metrics {
static let windowSize = NSSize(width: 720, height: 620) static let windowSize = NSSize(width: 620, height: 520)
static let minimumWindowSize = NSSize(width: 620, height: 560) static let minimumWindowSize = NSSize(width: 560, height: 440)
static let settingsContentMinimumWidth: CGFloat = 520 static let settingsContentMinimumWidth: CGFloat = 440
static let settingsLabelWidth: CGFloat = 150 static let settingsLabelWidth: CGFloat = 128
} }
private static let tabTitles = ["General", "Shortcuts", "Capture", "Privacy", "Performance", "Data"]
private static let allowedContentTypesValidationMessage = "At least one content type must stay enabled." private static let allowedContentTypesValidationMessage = "At least one content type must stay enabled."
private static let allowedContentTypesUpdatedMessage = "Allowed content types updated." private static let allowedContentTypesUpdatedMessage = "Allowed content types updated."
@@ -20,9 +21,23 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
private let store: ClipboardStore private let store: ClipboardStore
private let cacheService: ClipboardCacheService private let cacheService: ClipboardCacheService
private let cloudSyncService: ClipboardCloudSyncServicing private let cloudSyncService: ClipboardCloudSyncServicing
private let dataOperationQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "clipbored.settings.data-operations"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 1
return queue
}()
private var dataOperationInProgress = false
private var window: NSWindow? private var window: NSWindow?
private var cachedCloudSyncStatus: ClipboardCloudSyncStatus? private var cachedCloudSyncStatus: ClipboardCloudSyncStatus?
private let tabView = NSTabView() private let tabView = NSTabView()
private let tabSelector = NSSegmentedControl(
labels: SettingsWindowController.tabTitles,
trackingMode: .selectOne,
target: nil,
action: nil
)
private let historyLabel = NSTextField(labelWithString: "") private let historyLabel = NSTextField(labelWithString: "")
private let historyStepper = NSStepper() private let historyStepper = NSStepper()
@@ -64,6 +79,8 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
private let iCloudRestoreButton = NSButton() private let iCloudRestoreButton = NSButton()
private let iCloudRevealButton = NSButton() private let iCloudRevealButton = NSButton()
private let cloudSyncStatusLabel = NSTextField(labelWithString: "") private let cloudSyncStatusLabel = NSTextField(labelWithString: "")
private let exportArchiveButton = NSButton()
private let importArchiveButton = NSButton()
#if DEBUG #if DEBUG
private var debugFullRefreshCountValue = 0 private var debugFullRefreshCountValue = 0
@@ -118,24 +135,44 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
private func makeContentView() -> NSView { private func makeContentView() -> NSView {
tabView.translatesAutoresizingMaskIntoConstraints = false tabView.translatesAutoresizingMaskIntoConstraints = false
tabView.tabViewType = .noTabsNoBorder
tabView.addTabViewItem(tab("General", generalSettingsView())) tabView.addTabViewItem(tab("General", generalSettingsView()))
tabView.addTabViewItem(tab("Shortcuts", shortcutSettingsView())) tabView.addTabViewItem(tab("Shortcuts", shortcutSettingsView()))
tabView.addTabViewItem(tab("Capture", captureSettingsView())) tabView.addTabViewItem(tab("Capture", captureSettingsView()))
tabView.addTabViewItem(tab("Privacy", privacySettingsView())) tabView.addTabViewItem(tab("Privacy", privacySettingsView()))
tabView.addTabViewItem(tab("Performance", performanceSettingsView())) tabView.addTabViewItem(tab("Performance", performanceSettingsView()))
tabView.addTabViewItem(tab("Data ", dataSettingsView())) tabView.addTabViewItem(tab("Data", dataSettingsView()))
tabSelector.translatesAutoresizingMaskIntoConstraints = false
tabSelector.target = self
tabSelector.action = #selector(settingsTabChanged(_:))
tabSelector.selectedSegment = 0
tabSelector.segmentStyle = .rounded
let container = NSView() let container = NSView()
container.wantsLayer = true
container.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
container.addSubview(tabSelector)
container.addSubview(tabView) container.addSubview(tabView)
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
tabSelector.topAnchor.constraint(equalTo: container.topAnchor, constant: 10),
tabSelector.centerXAnchor.constraint(equalTo: container.centerXAnchor),
tabSelector.leadingAnchor.constraint(greaterThanOrEqualTo: container.leadingAnchor, constant: 12),
tabSelector.trailingAnchor.constraint(lessThanOrEqualTo: container.trailingAnchor, constant: -12),
tabView.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 12), tabView.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 12),
tabView.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -12), tabView.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -12),
tabView.topAnchor.constraint(equalTo: container.topAnchor, constant: 12), tabView.topAnchor.constraint(equalTo: tabSelector.bottomAnchor, constant: 10),
tabView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -12) tabView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -12)
]) ])
return container return container
} }
@objc private func settingsTabChanged(_ sender: NSSegmentedControl) {
let index = sender.selectedSegment
guard index >= 0, index < tabView.numberOfTabViewItems else { return }
tabView.selectTabViewItem(at: index)
}
private func tab(_ title: String, _ view: NSView) -> NSTabViewItem { private func tab(_ title: String, _ view: NSView) -> NSTabViewItem {
let item = NSTabViewItem(identifier: title) let item = NSTabViewItem(identifier: title)
item.label = title item.label = title
@@ -159,16 +196,18 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
content.translatesAutoresizingMaskIntoConstraints = false content.translatesAutoresizingMaskIntoConstraints = false
documentView.addSubview(content) documentView.addSubview(content)
scrollView.documentView = documentView scrollView.documentView = documentView
let documentFillsViewport = documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.contentView.bottomAnchor)
let documentContainsContent = documentView.bottomAnchor.constraint(greaterThanOrEqualTo: content.bottomAnchor)
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
documentView.leadingAnchor.constraint(equalTo: scrollView.contentView.leadingAnchor), documentView.leadingAnchor.constraint(equalTo: scrollView.contentView.leadingAnchor),
documentView.trailingAnchor.constraint(equalTo: scrollView.contentView.trailingAnchor), documentView.trailingAnchor.constraint(equalTo: scrollView.contentView.trailingAnchor),
documentView.topAnchor.constraint(equalTo: scrollView.contentView.topAnchor), documentView.topAnchor.constraint(equalTo: scrollView.contentView.topAnchor),
documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.contentView.bottomAnchor), documentFillsViewport,
documentContainsContent,
documentView.widthAnchor.constraint(equalTo: scrollView.contentView.widthAnchor), documentView.widthAnchor.constraint(equalTo: scrollView.contentView.widthAnchor),
content.leadingAnchor.constraint(equalTo: documentView.leadingAnchor), content.leadingAnchor.constraint(equalTo: documentView.leadingAnchor),
content.trailingAnchor.constraint(equalTo: documentView.trailingAnchor), content.trailingAnchor.constraint(equalTo: documentView.trailingAnchor),
content.topAnchor.constraint(equalTo: documentView.topAnchor), content.topAnchor.constraint(equalTo: documentView.topAnchor)
content.bottomAnchor.constraint(equalTo: documentView.bottomAnchor)
]) ])
return scrollView return scrollView
} }
@@ -354,6 +393,8 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
configureButton(iCloudSyncNowButton, title: "Sync Now", action: #selector(pushICloudSyncArchive)) configureButton(iCloudSyncNowButton, title: "Sync Now", action: #selector(pushICloudSyncArchive))
configureButton(iCloudRestoreButton, title: "Restore from iCloud", action: #selector(pullICloudSyncArchive)) configureButton(iCloudRestoreButton, title: "Restore from iCloud", action: #selector(pullICloudSyncArchive))
configureButton(iCloudRevealButton, title: "Reveal Sync File", action: #selector(revealICloudSyncFile)) configureButton(iCloudRevealButton, title: "Reveal Sync File", action: #selector(revealICloudSyncFile))
configureButton(exportArchiveButton, title: "Export Archive...", action: #selector(exportClipboardArchive))
configureButton(importArchiveButton, title: "Import Archive...", action: #selector(importClipboardArchive))
let archiveLabel = caption("Export a portable archive for history, Pinboards, and managed attachments. Archives are not encrypted; file references stay path-based.") let archiveLabel = caption("Export a portable archive for history, Pinboards, and managed attachments. Archives are not encrypted; file references stay path-based.")
let cloudLabel = caption("Uses the same archive in ClipBored's private iCloud container when iCloud signing and iCloud Drive are available.") let cloudLabel = caption("Uses the same archive in ClipBored's private iCloud container when iCloud signing and iCloud Drive are available.")
return page([ return page([
@@ -370,8 +411,8 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
section("Archive", [ section("Archive", [
archiveLabel, archiveLabel,
row([ row([
button("Export Archive...", #selector(exportClipboardArchive)), exportArchiveButton,
button("Import Archive...", #selector(importClipboardArchive)) importArchiveButton
]) ])
]), ]),
section("Data", [ section("Data", [
@@ -387,8 +428,8 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
let stack = NSStackView(views: views) let stack = NSStackView(views: views)
stack.orientation = .vertical stack.orientation = .vertical
stack.alignment = .leading stack.alignment = .leading
stack.spacing = 18 stack.spacing = 12
stack.edgeInsets = NSEdgeInsets(top: 18, left: 18, bottom: 18, right: 18) stack.edgeInsets = NSEdgeInsets(top: 14, left: 14, bottom: 14, right: 14)
return stack return stack
} }
@@ -398,7 +439,7 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
let stack = NSStackView(views: [titleLabel] + views) let stack = NSStackView(views: [titleLabel] + views)
stack.orientation = .vertical stack.orientation = .vertical
stack.alignment = .leading stack.alignment = .leading
stack.spacing = 8 stack.spacing = 7
let minimumWidth = stack.widthAnchor.constraint(greaterThanOrEqualToConstant: Metrics.settingsContentMinimumWidth) let minimumWidth = stack.widthAnchor.constraint(greaterThanOrEqualToConstant: Metrics.settingsContentMinimumWidth)
minimumWidth.priority = .defaultLow minimumWidth.priority = .defaultLow
minimumWidth.isActive = true minimumWidth.isActive = true
@@ -513,7 +554,10 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
private func modifierButton(_ title: String, _ tag: Int) -> NSButton { private func modifierButton(_ title: String, _ tag: Int) -> NSButton {
let control = NSButton() let control = NSButton()
configureCheckbox(control, title: title, action: #selector(shortcutChanged(_:))) configureCheckbox(control, title: title, action: #selector(shortcutChanged(_:)))
control.toolTip = modifierTooltip(title) let modifierName = modifierTooltip(title)
control.toolTip = modifierName
control.setAccessibilityLabel("\(modifierName) modifier")
control.setAccessibilityHelp("Include or remove the \(modifierName) key from this shortcut.")
control.tag = tag control.tag = tag
return control return control
} }
@@ -572,7 +616,7 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
clearHistoryOnQuitButton.state = settings.clearHistoryOnQuit ? .on : .off clearHistoryOnQuitButton.state = settings.clearHistoryOnQuit ? .on : .off
case .pollProfile: case .pollProfile:
select(pollProfilePopup, rawValue: settings.pollProfileRaw.rawValue) select(pollProfilePopup, rawValue: settings.pollProfileRaw.rawValue)
case .panelLayout: case .panelSide:
select(panelSidePopup, rawValue: settings.panelSide.rawValue) select(panelSidePopup, rawValue: settings.panelSide.rawValue)
case .showMenuBarIcon: case .showMenuBarIcon:
refreshVisibilityControls() refreshVisibilityControls()
@@ -859,7 +903,9 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
) )
cloudSyncStatusLabel.stringValue = presentation.message cloudSyncStatusLabel.stringValue = presentation.message
cloudSyncStatusLabel.textColor = presentation.textColor cloudSyncStatusLabel.textColor = presentation.textColor
let cloudActionsEnabled = settings.iCloudSyncEnabled && cloudStatus?.isAvailable == true let cloudActionsEnabled = settings.iCloudSyncEnabled
&& cloudStatus?.isAvailable == true
&& !dataOperationInProgress
iCloudSyncNowButton.isEnabled = cloudActionsEnabled iCloudSyncNowButton.isEnabled = cloudActionsEnabled
iCloudRestoreButton.isEnabled = cloudActionsEnabled iCloudRestoreButton.isEnabled = cloudActionsEnabled
iCloudRevealButton.isEnabled = cloudActionsEnabled iCloudRevealButton.isEnabled = cloudActionsEnabled
@@ -1244,11 +1290,16 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
configureArchivePanel(panel) configureArchivePanel(panel)
guard panel.runModal() == .OK, let url = panel.url else { return } guard panel.runModal() == .OK, let url = panel.url else { return }
do { setDataStatus("Exporting archive…")
let summary = try store.exportArchive(to: url) performDataOperation({ [store] in
setDataStatus("Exported \(summary.itemCount) clips and \(summary.sidecarCount) attachments.") Result { try store.exportArchive(to: url) }
} catch { }) { [weak self] result in
setDataStatus(error.localizedDescription) switch result {
case .success(let summary):
self?.setDataStatus("Exported \(summary.itemCount) clips and \(summary.sidecarCount) attachments.")
case .failure(let error):
self?.setDataStatus(error.localizedDescription)
}
} }
} }
@@ -1261,15 +1312,20 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
configureArchivePanel(panel) configureArchivePanel(panel)
guard panel.runModal() == .OK, let url = panel.url else { return } guard panel.runModal() == .OK, let url = panel.url else { return }
do { setDataStatus("Importing archive…")
let summary = try store.importArchive(from: url) performDataOperation({ [store] in
Result { try store.importArchive(from: url) }
}) { [weak self] result in
switch result {
case .success(let summary):
var message = "Imported \(summary.itemCount) clips and \(summary.sidecarCount) attachments." var message = "Imported \(summary.itemCount) clips and \(summary.sidecarCount) attachments."
if summary.skippedItemCount > 0 || summary.skippedSidecarCount > 0 { if summary.skippedItemCount > 0 || summary.skippedSidecarCount > 0 {
message += " Skipped \(summary.skippedItemCount) clips and \(summary.skippedSidecarCount) attachments." message += " Skipped \(summary.skippedItemCount) clips and \(summary.skippedSidecarCount) attachments."
} }
setDataStatus(message) self?.setDataStatus(message)
} catch { case .failure(let error):
setDataStatus(error.localizedDescription) self?.setDataStatus(error.localizedDescription)
}
} }
} }
@@ -1279,12 +1335,20 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
return return
} }
do { settings.setCloudSyncStatus(message: "Syncing with iCloud…")
performDataOperation({ [cloudSyncService, store] in
Result {
let summary = try cloudSyncService.push(store: store) let summary = try cloudSyncService.push(store: store)
cachedCloudSyncStatus = cloudSyncService.status() return (summary, cloudSyncService.status())
settings.setCloudSyncStatus(message: "Synced \(summary.itemCount) clips and \(summary.sidecarCount) attachments to iCloud.") }
} catch { }) { [weak self] result in
settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)") switch result {
case .success(let (summary, status)):
self?.cachedCloudSyncStatus = status
self?.settings.setCloudSyncStatus(message: "Synced \(summary.itemCount) clips and \(summary.sidecarCount) attachments to iCloud.")
case .failure(let error):
self?.settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)")
}
} }
} }
@@ -1294,16 +1358,45 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
return return
} }
do { settings.setCloudSyncStatus(message: "Restoring from iCloud…")
performDataOperation({ [cloudSyncService, store] in
Result {
let summary = try cloudSyncService.pull(store: store) let summary = try cloudSyncService.pull(store: store)
cachedCloudSyncStatus = cloudSyncService.status() return (summary, cloudSyncService.status())
}
}) { [weak self] result in
switch result {
case .success(let (summary, status)):
self?.cachedCloudSyncStatus = status
var message = "Restored \(summary.itemCount) clips and \(summary.sidecarCount) attachments from iCloud." var message = "Restored \(summary.itemCount) clips and \(summary.sidecarCount) attachments from iCloud."
if summary.skippedItemCount > 0 || summary.skippedSidecarCount > 0 { if summary.skippedItemCount > 0 || summary.skippedSidecarCount > 0 {
message += " Skipped \(summary.skippedItemCount) clips and \(summary.skippedSidecarCount) attachments." message += " Skipped \(summary.skippedItemCount) clips and \(summary.skippedSidecarCount) attachments."
} }
settings.setCloudSyncStatus(message: message) self?.settings.setCloudSyncStatus(message: message)
} catch { case .failure(let error):
settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)") self?.settings.setCloudSyncStatus(message: "iCloud Sync failed: \(error.localizedDescription)")
}
}
}
private func performDataOperation<ResultValue>(
_ operation: @escaping () -> ResultValue,
completion: @escaping (ResultValue) -> Void
) {
dataOperationInProgress = true
exportArchiveButton.isEnabled = false
importArchiveButton.isEnabled = false
refreshCloudSyncControls(refreshStatus: false)
dataOperationQueue.addOperation { [weak self] in
let result = operation()
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.dataOperationInProgress = false
self.exportArchiveButton.isEnabled = true
self.importArchiveButton.isEnabled = true
completion(result)
self.refreshCloudSyncControls(refreshStatus: false)
}
} }
} }
@@ -1736,6 +1829,36 @@ final class SettingsWindowController: NSObject, NSWindowDelegate, NSTextFieldDel
shortcutStatusLabel.stringValue shortcutStatusLabel.stringValue
} }
var debugOpenShortcutModifierAccessibilityLabels: [String] {
guard let controls = openShortcutControls else { return [] }
return [controls.command, controls.option, controls.control, controls.shift]
.compactMap { $0.accessibilityLabel() }
}
var debugOpenShortcutModifierAccessibilityHelps: [String] {
guard let controls = openShortcutControls else { return [] }
return [controls.command, controls.option, controls.control, controls.shift]
.compactMap { $0.accessibilityHelp() }
}
var debugSettingsContentView: NSView? {
window?.contentView
}
func debugSelectSettingsTab(at index: Int) {
guard index >= 0, index < tabView.numberOfTabViewItems else { return }
tabSelector.selectedSegment = index
tabView.selectTabViewItem(at: index)
window?.contentView?.layoutSubtreeIfNeeded()
}
func debugPrepareWindowForSnapshot() {
window?.setFrameOrigin(.zero)
window?.orderFront(nil)
window?.contentView?.layoutSubtreeIfNeeded()
window?.contentView?.displayIfNeeded()
}
var debugFullRefreshCount: Int { var debugFullRefreshCount: Int {
debugFullRefreshCountValue debugFullRefreshCountValue
} }

View File

@@ -1,4 +1,5 @@
import AppKit import AppKit
import Carbon
import XCTest import XCTest
@testable import ClipBored @testable import ClipBored
@@ -140,59 +141,6 @@ final class ClipboardPanelControllerTests: XCTestCase {
XCTAssertEqual(frames.hidden.minX, screenFrame.maxX + 1) XCTAssertEqual(frames.hidden.minX, screenFrame.maxX + 1)
} }
func testPanelFrameIgnoresLegacyPreferredResizableHeight() {
let screenFrame = CGRect(x: 0, y: 0, width: 1512, height: 982)
let visibleFrame = CGRect(x: 0, y: 96, width: 1512, height: 861)
let frames = ClipboardPanelController.panelFrames(
forScreenFrame: screenFrame,
visibleFrame: visibleFrame,
preferredHeight: 600
)
XCTAssertEqual(frames.shown.minY, screenFrame.minY)
XCTAssertEqual(frames.shown.maxY, visibleFrame.maxY)
XCTAssertEqual(frames.shown.height, 957)
XCTAssertEqual(frames.hidden.minX, visibleFrame.maxX + 1)
}
func testPanelFrameLegacyPreferredHeightDoesNotAffectSideShelf() {
let screenFrame = CGRect(x: 0, y: 0, width: 1512, height: 982)
let visibleFrame = CGRect(x: 0, y: 0, width: 1512, height: 982)
let tooTall = ClipboardPanelController.panelFrames(
forScreenFrame: screenFrame,
visibleFrame: visibleFrame,
preferredHeight: 900
)
let tooShort = ClipboardPanelController.panelFrames(
forScreenFrame: screenFrame,
visibleFrame: visibleFrame,
preferredHeight: 120
)
XCTAssertEqual(tooTall.shown.height, 982)
XCTAssertEqual(tooShort.shown.height, 982)
XCTAssertEqual(tooTall.shown.width, 336)
XCTAssertEqual(tooShort.shown.width, 336)
}
func testPanelFrameLegacyPreferredHeightDoesNotOverflowTinyVisibleFrame() {
let screenFrame = CGRect(x: 0, y: 0, width: 640, height: 320)
let visibleFrame = CGRect(x: 0, y: 48, width: 640, height: 220)
let frames = ClipboardPanelController.panelFrames(
forScreenFrame: screenFrame,
visibleFrame: visibleFrame,
preferredHeight: 620
)
XCTAssertEqual(frames.shown.height, 268)
XCTAssertEqual(frames.shown.width, 320)
XCTAssertLessThanOrEqual(frames.shown.height, visibleFrame.maxY - screenFrame.minY)
XCTAssertEqual(frames.shown.minY, screenFrame.minY)
}
func testPanelFramePlanningIsDeterministicAcrossRepeatedToggles() { func testPanelFramePlanningIsDeterministicAcrossRepeatedToggles() {
let screenFrame = CGRect(x: -1512, y: -120, width: 1512, height: 982) let screenFrame = CGRect(x: -1512, y: -120, width: 1512, height: 982)
let visibleFrame = CGRect(x: -1512, y: -24, width: 1512, height: 861) let visibleFrame = CGRect(x: -1512, y: -24, width: 1512, height: 861)
@@ -234,10 +182,10 @@ final class ClipboardPanelControllerTests: XCTestCase {
controller.debugSetSearchFieldText("stale query") controller.debugSetSearchFieldText("stale query")
drainMainQueue() drainMainQueue()
XCTAssertEqual(controller.debugSearchFieldText, "stale query") XCTAssertEqual(controller.debugSearchFieldText, "stale query")
XCTAssertEqual(controller.debugSearchFieldWidth, 164, accuracy: 0.5) XCTAssertEqual(controller.debugSearchFieldWidth, 238, accuracy: 1)
XCTAssertEqual(controller.debugSearchFieldPlaceholderText, "Search clips") XCTAssertEqual(controller.debugSearchFieldPlaceholderText, "Search clips")
XCTAssertTrue(controller.debugSearchFieldIsVisible) XCTAssertTrue(controller.debugSearchFieldIsVisible)
XCTAssertFalse(controller.debugSearchIconButtonIsVisible) XCTAssertTrue(controller.debugSearchIconButtonIsVisible)
controller.show(preferredScreen: screen) controller.show(preferredScreen: screen)
defer { controller.hide(immediate: true) } defer { controller.hide(immediate: true) }
@@ -277,22 +225,6 @@ final class ClipboardPanelControllerTests: XCTestCase {
XCTAssertEqual(plan.bottomSafeInset, 18) XCTAssertEqual(plan.bottomSafeInset, 18)
} }
func testReflowPlanIgnoresLegacyPreferredResizableHeight() {
let screenFrame = CGRect(x: 0, y: 0, width: 1512, height: 982)
let visibleFrame = CGRect(x: 0, y: 96, width: 1512, height: 861)
let plan = ClipboardPanelController.reflowPlan(
forScreenFrame: screenFrame,
visibleFrame: visibleFrame,
preferredHeight: 600
)
XCTAssertEqual(plan.frame.minY, screenFrame.minY)
XCTAssertEqual(plan.frame.height, 957)
XCTAssertEqual(plan.frame.width, 336)
XCTAssertEqual(plan.bottomSafeInset, 20)
}
func testReflowPlanTracksSideDockVisibleFrameWithoutBottomInsetInflation() { func testReflowPlanTracksSideDockVisibleFrameWithoutBottomInsetInflation() {
let screenFrame = CGRect(x: 0, y: 0, width: 1512, height: 982) let screenFrame = CGRect(x: 0, y: 0, width: 1512, height: 982)
let visibleFrame = CGRect(x: 86, y: 0, width: 1426, height: 957) let visibleFrame = CGRect(x: 86, y: 0, width: 1426, height: 957)
@@ -496,6 +428,32 @@ final class ClipboardPanelControllerTests: XCTestCase {
XCTAssertNil(ClipboardPanelController.commandShortcutAction(forKeyCode: 9, modifiers: .command)) XCTAssertNil(ClipboardPanelController.commandShortcutAction(forKeyCode: 9, modifiers: .command))
} }
func testSettingsShortcutMatchesOnlyItsExactLocalBinding() {
let binding = AppConfiguration.defaultSettingsShortcut
XCTAssertTrue(
ClipboardPanelController.matchesShortcut(
keyCode: UInt16(kVK_ANSI_Comma),
modifiers: .command,
binding: binding
)
)
XCTAssertFalse(
ClipboardPanelController.matchesShortcut(
keyCode: UInt16(kVK_ANSI_Comma),
modifiers: [.command, .shift],
binding: binding
)
)
XCTAssertFalse(
ClipboardPanelController.matchesShortcut(
keyCode: UInt16(kVK_ANSI_Period),
modifiers: .command,
binding: binding
)
)
}
func testModifiedShortcutsMapToPanelActions() { func testModifiedShortcutsMapToPanelActions() {
XCTAssertEqual(ClipboardPanelController.modifiedShortcutAction(forKeyCode: 36, modifiers: .shift), .pastePlainText) XCTAssertEqual(ClipboardPanelController.modifiedShortcutAction(forKeyCode: 36, modifiers: .shift), .pastePlainText)
XCTAssertEqual(ClipboardPanelController.modifiedShortcutAction(forKeyCode: 1, modifiers: [.command, .shift]), .toggleStack) XCTAssertEqual(ClipboardPanelController.modifiedShortcutAction(forKeyCode: 1, modifiers: [.command, .shift]), .toggleStack)

View File

@@ -206,6 +206,205 @@ final class ClipboardPanelViewModelTests: XCTestCase {
XCTAssertEqual(viewModel.debugCollectionCountIndexedLookupCount, 1) XCTAssertEqual(viewModel.debugCollectionCountIndexedLookupCount, 1)
} }
func testSearchMatchesAreEvaluatedOnceAcrossVisibleItemsCountsAndCategoryChanges() {
let settings = makeSettings()
settings.maxHistoryItems = 120
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
for index in 0..<100 {
var item = makeTextItem(
index.isMultiple(of: 5) ? "shared search needle \(index)" : "unmatched history \(index)",
createdAt: Date(timeIntervalSince1970: Double(index))
)
if index.isMultiple(of: 2) {
item.collectionName = "Client Work"
}
store.upsert(item)
}
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 100)
viewModel.debugResetVisibleItemsPerformanceCounters()
viewModel.searchText = "needle"
XCTAssertEqual(viewModel.visibleItems.count, 20)
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 100)
XCTAssertEqual(viewModel.debugSearchDocumentBuildCount, 100)
let counts = viewModel.collectionCountSummary()
XCTAssertEqual(counts.count(for: .text), 20)
XCTAssertEqual(counts.count(named: "Client Work"), 10)
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 100)
XCTAssertEqual(viewModel.debugSearchMatchCacheHitCount, 1)
viewModel.selectSortMode(.text, extending: true)
viewModel.selectSortMode(.links, extending: true)
XCTAssertEqual(viewModel.visibleItems.count, 20)
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 100)
XCTAssertEqual(viewModel.debugSearchMatchCacheHitCount, 3)
viewModel.searchText = "shared"
XCTAssertEqual(viewModel.visibleItems.count, 20)
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 200)
XCTAssertEqual(viewModel.debugSearchDocumentBuildCount, 100)
XCTAssertEqual(viewModel.debugSearchDocumentCacheHitCount, 100)
}
func testEquivalentDiacriticSearchReusesVisibleAndCollectionCountCaches() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("Résumé draft", createdAt: Date(timeIntervalSince1970: 100)))
store.upsert(makeTextItem("Meeting note", createdAt: Date(timeIntervalSince1970: 200)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 2)
viewModel.debugResetVisibleItemsPerformanceCounters()
viewModel.searchText = "resume"
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["Résumé draft"])
_ = viewModel.collectionCountSummary()
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 2)
XCTAssertEqual(viewModel.debugCollectionCountFullScanCount, 1)
viewModel.searchText = " RÉSUMÉ "
_ = viewModel.collectionCountSummary()
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["Résumé draft"])
XCTAssertEqual(viewModel.debugSearchItemEvaluationCount, 2)
XCTAssertEqual(viewModel.debugCollectionCountFullScanCount, 1)
}
func testCategoryFilterSelectionIsBuiltOncePerMutationAndReusedForChipStateQueries() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("category state", createdAt: Date(timeIntervalSince1970: 100)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
viewModel.debugResetVisibleItemsPerformanceCounters()
viewModel.selectSortMode(.text, extending: true)
XCTAssertEqual(viewModel.debugCategoryFilterSelectionBuildCount, 1)
for _ in 0..<20 {
for mode in ClipboardSortMode.allCases {
_ = viewModel.isSortModeCategorySelected(mode)
}
_ = viewModel.isCollectionCategorySelected(named: "Client Work")
_ = viewModel.canShowVisibleItemsInClipboard
}
XCTAssertEqual(viewModel.debugCategoryFilterSelectionBuildCount, 1)
}
func testRepeatedRecomputesDoNotRescanUnchangedStackMembership() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("stacked needle", createdAt: Date(timeIntervalSince1970: 100)))
store.upsert(makeTextItem("outside note", createdAt: Date(timeIntervalSince1970: 200)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 2)
viewModel.selectItem(at: 1)
viewModel.toggleSelectedStackMembership()
viewModel.debugResetVisibleItemsPerformanceCounters()
viewModel.searchText = "needle"
viewModel.clearSearch()
viewModel.selectSortMode(.text)
viewModel.selectSortMode(.mostRecent)
XCTAssertEqual(viewModel.stackCount, 1)
XCTAssertEqual(viewModel.debugStackPruneScanCount, 0)
}
func testRepeatedHoverSelectionDoesNotNotifyAnUnchangedSelection() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("hover target", createdAt: Date(timeIntervalSince1970: 100)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
var selectedIndexCallbackCount = 0
var selectedItemsCallbackCount = 0
viewModel.onSelectedIndexChanged = { _ in selectedIndexCallbackCount += 1 }
viewModel.onSelectedItemsChanged = { selectedItemsCallbackCount += 1 }
viewModel.selectItem(at: 0, mode: .hover)
let callbackCountsAfterFirstHover = (selectedIndexCallbackCount, selectedItemsCallbackCount)
viewModel.selectItem(at: 0, mode: .hover)
XCTAssertEqual(selectedIndexCallbackCount, callbackCountsAfterFirstHover.0)
XCTAssertEqual(selectedItemsCallbackCount, callbackCountsAfterFirstHover.1)
}
func testAsyncThumbnailLoadingRunsOffMainCoalescesRequestsAndCompletesOnMain() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let loaderStarted = expectation(description: "thumbnail loader started")
let completionsFinished = expectation(description: "thumbnail completions")
completionsFinished.expectedFulfillmentCount = 2
let loaderGate = DispatchSemaphore(value: 0)
let loaderStateLock = NSLock()
var loaderCallCount = 0
var loaderRanOnMain = true
let viewModel = ClipboardPanelViewModel(
store: store,
settings: settings,
cacheService: cacheService,
thumbnailLoader: { _ in
loaderStateLock.lock()
loaderCallCount += 1
loaderRanOnMain = Thread.isMainThread
loaderStateLock.unlock()
loaderStarted.fulfill()
_ = loaderGate.wait(timeout: .now() + 2)
return NSImage(size: NSSize(width: 20, height: 20))
}
)
var item = makeTextItem("thumbnail request", createdAt: Date(timeIntervalSince1970: 100))
item.kind = .image
item.thumbnailPath = "/tmp/thumbnail-request.png"
var completionMainThreadValues: [Bool] = []
viewModel.loadThumbnail(for: item) { image in
completionMainThreadValues.append(Thread.isMainThread)
XCTAssertNotNil(image)
completionsFinished.fulfill()
}
wait(for: [loaderStarted], timeout: 1)
viewModel.loadThumbnail(for: item) { image in
completionMainThreadValues.append(Thread.isMainThread)
XCTAssertNotNil(image)
completionsFinished.fulfill()
}
loaderGate.signal()
wait(for: [completionsFinished], timeout: 2)
loaderStateLock.lock()
let finalLoaderCallCount = loaderCallCount
let finalLoaderRanOnMain = loaderRanOnMain
loaderStateLock.unlock()
XCTAssertEqual(finalLoaderCallCount, 1)
XCTAssertFalse(finalLoaderRanOnMain)
XCTAssertEqual(completionMainThreadValues, [true, true])
}
func testComputeVisibleItemsFiltersColorClipsAndStructuredType() { func testComputeVisibleItemsFiltersColorClipsAndStructuredType() {
let settings = makeSettings() let settings = makeSettings()
let store = makeStore(settings: settings) let store = makeStore(settings: settings)
@@ -1141,6 +1340,50 @@ final class ClipboardPanelViewModelTests: XCTestCase {
XCTAssertEqual(collectionCallbackCount, 0) XCTAssertEqual(collectionCallbackCount, 0)
} }
func testCreatingUnselectedCollectionUpdatesChromeWithoutReloadingVisibleItems() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("visible note", createdAt: Date(timeIntervalSince1970: 100)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
var visibleCallbackCount = 0
var collectionCallbackCount = 0
viewModel.onVisibleItemsChanged = { _ in visibleCallbackCount += 1 }
viewModel.onCollectionsChanged = { collectionCallbackCount += 1 }
viewModel.createCollection(named: "Client Work", colorHex: "#0A9EB8", selectAfterCreate: false)
XCTAssertEqual(viewModel.collectionNames, ["Client Work"])
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["visible note"])
XCTAssertEqual(visibleCallbackCount, 0)
XCTAssertEqual(collectionCallbackCount, 1)
}
func testExternalCollectionSettingsChangeUpdatesChromeWithoutReloadingVisibleItems() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
store.upsert(makeTextItem("visible note", createdAt: Date(timeIntervalSince1970: 100)))
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
var visibleCallbackCount = 0
var collectionCallbackCount = 0
viewModel.onVisibleItemsChanged = { _ in visibleCallbackCount += 1 }
viewModel.onCollectionsChanged = { collectionCallbackCount += 1 }
settings.ensureCollection(named: "Client Work", colorHex: "#0A9EB8")
XCTAssertEqual(viewModel.collectionNames, ["Client Work"])
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["visible note"])
XCTAssertEqual(visibleCallbackCount, 0)
XCTAssertEqual(collectionCallbackCount, 1)
}
func testSettingsChangesRefreshPanelSortAndImageTextSearch() { func testSettingsChangesRefreshPanelSortAndImageTextSearch() {
let settings = makeSettings() let settings = makeSettings()
let cacheService = makeCacheService() let cacheService = makeCacheService()
@@ -1190,6 +1433,44 @@ final class ClipboardPanelViewModelTests: XCTestCase {
XCTAssertEqual(viewModel.collectionCount(for: .images), 1) XCTAssertEqual(viewModel.collectionCount(for: .images), 1)
} }
func testImageTextSearchSettingSkipsReloadWhenActiveQueryHasNoTextTokens() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let image = ClipboardItem(
id: UUID(),
kind: .image,
displayText: "Screenshot",
payload: "screenshot-path",
payloadHash: hash("screenshot-path"),
createdAt: Date(timeIntervalSince1970: 100),
lastUsedAt: Date(timeIntervalSince1970: 100),
useCount: 0,
sourceApp: nil,
imagePath: nil,
thumbnailPath: nil,
ocrText: "Receipt total"
)
store.upsert(image)
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
var visibleCallbackCount = 0
viewModel.onVisibleItemsChanged = { _ in visibleCallbackCount += 1 }
settings.includeImageTextInSearch = true
XCTAssertEqual(visibleCallbackCount, 0)
viewModel.searchText = "type:image"
XCTAssertEqual(visibleCallbackCount, 1)
visibleCallbackCount = 0
settings.includeImageTextInSearch = false
XCTAssertEqual(viewModel.visibleItems.map(\.id), [image.id])
XCTAssertEqual(visibleCallbackCount, 0)
}
func testAdjacentCollectionNavigationWrapsThroughPinboards() { func testAdjacentCollectionNavigationWrapsThroughPinboards() {
let settings = makeSettings() let settings = makeSettings()
let cacheService = makeCacheService() let cacheService = makeCacheService()
@@ -1226,142 +1507,6 @@ final class ClipboardPanelViewModelTests: XCTestCase {
XCTAssertEqual(viewModel.statusMessage, "No collections") XCTAssertEqual(viewModel.statusMessage, "No collections")
} }
func testCompactModeToggleIsRemovedAndDoesNotPersist() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
XCTAssertFalse(viewModel.isCompactModeEnabled)
viewModel.toggleCompactMode()
XCTAssertFalse(settings.compactMode)
XCTAssertFalse(viewModel.isCompactModeEnabled)
XCTAssertEqual(viewModel.statusMessage, "Compact Mode was removed")
viewModel.toggleCompactMode()
XCTAssertFalse(settings.compactMode)
XCTAssertFalse(viewModel.isCompactModeEnabled)
XCTAssertEqual(viewModel.statusMessage, "Compact Mode was removed")
}
func testCreateTextClipAddsSearchableSelectedItem() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
viewModel.sortMode = .images
viewModel.searchText = "old query"
let now = Date(timeIntervalSince1970: 1_800)
let created = viewModel.createTextClip(" Launch note ", now: now)
store.flushPersistenceForTesting()
waitForVisibleItems(in: viewModel, count: 1)
XCTAssertEqual(created?.kind, .text)
XCTAssertEqual(created?.payload, "Launch note")
XCTAssertEqual(created?.displayText, "Launch note")
XCTAssertEqual(created?.sourceApp, AppConfiguration.appName)
XCTAssertEqual(created?.useCount, 0)
XCTAssertEqual(created?.createdAt, now)
XCTAssertEqual(viewModel.sortMode, .text)
XCTAssertEqual(viewModel.searchText, "")
XCTAssertEqual(viewModel.selectedItem?.id, created?.id)
XCTAssertEqual(viewModel.visibleItems.first?.payload, "Launch note")
XCTAssertEqual(viewModel.statusMessage, "Created text clip")
}
func testCreateTextClipBatchesFilterResetIntoSingleVisibleReload() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let seed = makeTextItem("stack seed", createdAt: Date(timeIntervalSince1970: 100))
store.upsert(seed)
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
viewModel.selectItem(at: 0)
viewModel.toggleSelectedStackMembership()
viewModel.sortMode = .images
viewModel.selectStack()
viewModel.searchText = "old query"
XCTAssertTrue(viewModel.isStackFilterSelected)
XCTAssertEqual(viewModel.sortMode, .images)
XCTAssertEqual(viewModel.searchText, "old query")
var visibleCallbackCount = 0
var searchTextCallbacks: [String] = []
var sortCallbacks: [ClipboardSortMode] = []
var collectionCallbackCount = 0
var stackCallbackCount = 0
viewModel.onVisibleItemsChanged = { _ in visibleCallbackCount += 1 }
viewModel.onSearchTextChanged = { searchTextCallbacks.append($0) }
viewModel.onSortModeChanged = { sortCallbacks.append($0) }
viewModel.onCollectionsChanged = { collectionCallbackCount += 1 }
viewModel.onStackChanged = { stackCallbackCount += 1 }
let created = viewModel.createTextClip("Launch note", now: Date(timeIntervalSince1970: 200))
XCTAssertEqual(created?.payload, "Launch note")
XCTAssertFalse(viewModel.isStackFilterSelected)
XCTAssertEqual(viewModel.sortMode, .text)
XCTAssertEqual(viewModel.searchText, "")
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["Launch note", "stack seed"])
XCTAssertEqual(viewModel.selectedItem?.id, created?.id)
XCTAssertEqual(visibleCallbackCount, 1)
XCTAssertEqual(searchTextCallbacks, [""])
XCTAssertEqual(sortCallbacks, [.text])
XCTAssertEqual(collectionCallbackCount, 0)
XCTAssertEqual(stackCallbackCount, 0)
XCTAssertEqual(viewModel.statusMessage, "Created text clip")
}
func testCreateTextClipAddsItemToActiveCollection() {
let settings = makeSettings()
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
viewModel.createCollection(named: "Client Work", colorHex: "#0A9EB8")
let created = viewModel.createTextClip("Pinboard note", now: Date(timeIntervalSince1970: 1_900))
store.flushPersistenceForTesting()
waitForVisibleItems(in: viewModel, count: 1)
XCTAssertEqual(created?.collectionName, "Client Work")
XCTAssertEqual(store.items.first?.collectionName, "Client Work")
XCTAssertEqual(viewModel.selectedCollectionName, "Client Work")
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["Pinboard note"])
XCTAssertEqual(viewModel.collectionCount(named: "Client Work"), 1)
}
func testCreateTextClipMergesDuplicateIntoActiveCollection() {
let settings = makeSettings()
settings.pruneDuplicates = true
let cacheService = makeCacheService()
let store = makeStore(settings: settings, cacheService: cacheService)
var existing = makeTextItem("Reusable note", createdAt: Date(timeIntervalSince1970: 100))
existing.payloadHash = store.hashString(existing.payload)
store.upsert(existing)
store.flushPersistenceForTesting()
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1)
viewModel.createCollection(named: "Client Work", colorHex: "#0A9EB8")
let created = viewModel.createTextClip("Reusable note", now: Date(timeIntervalSince1970: 2_000))
store.flushPersistenceForTesting()
waitForVisibleItems(in: viewModel, count: 1)
XCTAssertEqual(store.items.count, 1)
XCTAssertEqual(created?.id, existing.id)
XCTAssertEqual(store.items.first?.id, existing.id)
XCTAssertEqual(store.items.first?.collectionName, "Client Work")
XCTAssertEqual(viewModel.selectedItem?.id, existing.id)
XCTAssertEqual(viewModel.visibleItems.map(\.payload), ["Reusable note"])
}
func testUpdateCollectionRenamesAssignedItemsAndColor() { func testUpdateCollectionRenamesAssignedItemsAndColor() {
let settings = makeSettings() let settings = makeSettings()
let cacheService = makeCacheService() let cacheService = makeCacheService()
@@ -2419,6 +2564,10 @@ final class ClipboardPanelViewModelTests: XCTestCase {
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService) let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1) waitForVisibleItems(in: viewModel, count: 1)
viewModel.searchText = "draft"
XCTAssertEqual(viewModel.visibleItems.map(\.id), [item.id])
viewModel.clearSearch()
XCTAssertEqual(viewModel.editableTextForSelected(), "draft meeting note") XCTAssertEqual(viewModel.editableTextForSelected(), "draft meeting note")
viewModel.updateSelectedText(to: "final launch note") viewModel.updateSelectedText(to: "final launch note")
store.flushPersistenceForTesting() store.flushPersistenceForTesting()
@@ -2530,7 +2679,9 @@ final class ClipboardPanelViewModelTests: XCTestCase {
let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService) let viewModel = ClipboardPanelViewModel(store: store, settings: settings, cacheService: cacheService)
waitForVisibleItems(in: viewModel, count: 1) waitForVisibleItems(in: viewModel, count: 1)
viewModel.rotateSelectedImageClockwise() let completion = expectation(description: "Rotate image off the main thread")
viewModel.rotateSelectedImageClockwise(completion: completion.fulfill)
wait(for: [completion], timeout: 2)
store.flushPersistenceForTesting() store.flushPersistenceForTesting()
XCTAssertEqual(viewModel.statusMessage, "Rotated image") XCTAssertEqual(viewModel.statusMessage, "Rotated image")
@@ -2597,7 +2748,9 @@ final class ClipboardPanelViewModelTests: XCTestCase {
) )
waitForVisibleItems(in: viewModel, count: 1) waitForVisibleItems(in: viewModel, count: 1)
viewModel.extractTextFromSelectedImage() let completion = expectation(description: "Extract image text off the main thread")
viewModel.extractTextFromSelectedImage(completion: completion.fulfill)
wait(for: [completion], timeout: 2)
store.flushPersistenceForTesting() store.flushPersistenceForTesting()
XCTAssertEqual(extractionCount, 1) XCTAssertEqual(extractionCount, 1)
@@ -2650,7 +2803,9 @@ final class ClipboardPanelViewModelTests: XCTestCase {
) )
waitForVisibleItems(in: viewModel, count: 1) waitForVisibleItems(in: viewModel, count: 1)
viewModel.extractTextFromSelectedImage() let completion = expectation(description: "Finish empty image text extraction")
viewModel.extractTextFromSelectedImage(completion: completion.fulfill)
wait(for: [completion], timeout: 2)
store.flushPersistenceForTesting() store.flushPersistenceForTesting()
XCTAssertEqual(viewModel.statusMessage, "No text found in image") XCTAssertEqual(viewModel.statusMessage, "No text found in image")
@@ -2737,10 +2892,17 @@ final class ClipboardPanelViewModelTests: XCTestCase {
XCTAssertEqual(viewModel.statusMessage, "Copied") XCTAssertEqual(viewModel.statusMessage, "Copied")
var statusCallbacks: [String] = []
var captureStatusCallbackCount = 0
viewModel.onStatusMessageChanged = { statusCallbacks.append($0) }
viewModel.onCaptureStatusChanged = { captureStatusCallbackCount += 1 }
settings.setCaptureStatus(message: "Capture status updated while panel is open") settings.setCaptureStatus(message: "Capture status updated while panel is open")
RunLoop.main.run(until: Date().addingTimeInterval(0.05)) RunLoop.main.run(until: Date().addingTimeInterval(0.05))
XCTAssertEqual(viewModel.statusMessage, "") XCTAssertEqual(viewModel.statusMessage, "")
XCTAssertEqual(statusCallbacks, [""])
XCTAssertEqual(captureStatusCallbackCount, 1)
} }
private func makeSettings() -> SettingsModel { private func makeSettings() -> SettingsModel {

File diff suppressed because it is too large Load Diff

View File

@@ -84,27 +84,6 @@ final class SettingsModelTests: XCTestCase {
XCTAssertTrue(restored.hideFromScreenCapture) XCTAssertTrue(restored.hideFromScreenCapture)
} }
func testCompactModePersistsAndNotifies() {
let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer {
defaults.removePersistentDomain(forName: suiteName)
}
let settings = SettingsModel(defaults: defaults)
var changes: [SettingsModel.Change] = []
settings.observe { changes.append($0) }
XCTAssertFalse(settings.compactMode)
settings.compactMode = true
XCTAssertTrue(defaults.bool(forKey: SettingsModel.Keys.compactMode))
XCTAssertEqual(changes, [.compactMode])
let restored = SettingsModel(defaults: defaults)
XCTAssertTrue(restored.compactMode)
}
func testPanelSidePersistsAndNotifies() { func testPanelSidePersistsAndNotifies() {
let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)" let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)! let defaults = UserDefaults(suiteName: suiteName)!
@@ -115,17 +94,14 @@ final class SettingsModelTests: XCTestCase {
var changes: [SettingsModel.Change] = [] var changes: [SettingsModel.Change] = []
settings.observe { changes.append($0) } settings.observe { changes.append($0) }
XCTAssertEqual(settings.panelLayout, .vertical)
XCTAssertEqual(settings.panelSide, .right) XCTAssertEqual(settings.panelSide, .right)
settings.panelSide = .left settings.panelSide = .left
XCTAssertEqual(defaults.integer(forKey: SettingsModel.Keys.panelLayout), ClipboardPanelLayout.vertical.rawValue)
XCTAssertEqual(defaults.integer(forKey: SettingsModel.Keys.panelSide), ClipboardPanelSide.left.rawValue) XCTAssertEqual(defaults.integer(forKey: SettingsModel.Keys.panelSide), ClipboardPanelSide.left.rawValue)
XCTAssertEqual(changes, [.panelLayout]) XCTAssertEqual(changes, [.panelSide])
let restored = SettingsModel(defaults: defaults) let restored = SettingsModel(defaults: defaults)
XCTAssertEqual(restored.panelLayout, .vertical)
XCTAssertEqual(restored.panelSide, .left) XCTAssertEqual(restored.panelSide, .left)
} }
@@ -178,27 +154,6 @@ final class SettingsModelTests: XCTestCase {
XCTAssertFalse(restored.iCloudSyncEnabled) XCTAssertFalse(restored.iCloudSyncEnabled)
} }
func testPanelShelfHeightPersistsAndNotifies() {
let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer {
defaults.removePersistentDomain(forName: suiteName)
}
let settings = SettingsModel(defaults: defaults)
var changes: [SettingsModel.Change] = []
settings.observe { changes.append($0) }
XCTAssertEqual(settings.panelShelfHeight, 0)
settings.panelShelfHeight = 620
XCTAssertEqual(defaults.double(forKey: SettingsModel.Keys.panelShelfHeight), 620)
XCTAssertEqual(changes, [.panelSizing])
let restored = SettingsModel(defaults: defaults)
XCTAssertEqual(restored.panelShelfHeight, 620)
}
func testPauseCaptureUntilPersistsAndCanBeCleared() { func testPauseCaptureUntilPersistsAndCanBeCleared() {
let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)" let suiteName = "com.clipbored.settingsmodel.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)! let defaults = UserDefaults(suiteName: suiteName)!

View File

@@ -20,10 +20,10 @@ final class SettingsWindowControllerTests: XCTestCase {
let (controller, _) = makeController() let (controller, _) = makeController()
XCTAssertTrue(controller.debugWindowStyleMask.contains(.resizable)) XCTAssertTrue(controller.debugWindowStyleMask.contains(.resizable))
XCTAssertEqual(controller.debugWindowMinSize.width, 620, accuracy: 0.5) XCTAssertEqual(controller.debugWindowMinSize.width, 560, accuracy: 0.5)
XCTAssertEqual(controller.debugWindowMinSize.height, 560, accuracy: 0.5) XCTAssertEqual(controller.debugWindowMinSize.height, 440, accuracy: 0.5)
XCTAssertGreaterThanOrEqual(controller.debugWindowContentSize.width, 700) XCTAssertGreaterThanOrEqual(controller.debugWindowContentSize.width, 600)
XCTAssertGreaterThanOrEqual(controller.debugWindowContentSize.height, 600) XCTAssertGreaterThanOrEqual(controller.debugWindowContentSize.height, 500)
} }
func testSettingsTabsUsePinnedScrollableDocuments() { func testSettingsTabsUsePinnedScrollableDocuments() {
@@ -40,12 +40,12 @@ final class SettingsWindowControllerTests: XCTestCase {
} }
} }
func testSettingsDataTabKeepsExtraNativeHighlightPadding() { func testSettingsTabsUseUnpaddedLabelsWithCustomSelector() {
let (controller, _) = makeController() let (controller, _) = makeController()
XCTAssertEqual(controller.debugSettingsTabLayoutMetrics.map { $0.label }, ["General", "Shortcuts", "Capture", "Privacy", "Performance", "Data"]) XCTAssertEqual(controller.debugSettingsTabLayoutMetrics.map { $0.label }, ["General", "Shortcuts", "Capture", "Privacy", "Performance", "Data"])
XCTAssertEqual(controller.debugRawSettingsTabLabels.last?.clipboardTrimmed, "Data") XCTAssertEqual(controller.debugRawSettingsTabLabels.last?.clipboardTrimmed, "Data")
XCTAssertGreaterThan(controller.debugRawSettingsTabLabels.last?.count ?? 0, "Data".count) XCTAssertEqual(controller.debugRawSettingsTabLabels.last, "Data")
} }
func testSettingsTabsKeepContentAnchoredToTopLeadingCorner() { func testSettingsTabsKeepContentAnchoredToTopLeadingCorner() {
@@ -64,7 +64,7 @@ final class SettingsWindowControllerTests: XCTestCase {
func testSettingsTabsAvoidHorizontalOverflowAtMinimumWindowSize() { func testSettingsTabsAvoidHorizontalOverflowAtMinimumWindowSize() {
let (controller, _) = makeController() let (controller, _) = makeController()
controller.debugSetWindowContentSize(NSSize(width: 620, height: 560)) controller.debugSetWindowContentSize(NSSize(width: 560, height: 440))
let metrics = controller.debugSettingsTabLayoutAuditMetrics let metrics = controller.debugSettingsTabLayoutAuditMetrics
@@ -75,6 +75,63 @@ final class SettingsWindowControllerTests: XCTestCase {
} }
} }
func testSettingsGeneralTabUsesCompactVerticalLayout() {
let (controller, _) = makeController()
let metrics = controller.debugSettingsTabContentPlacementMetrics
let general = try! XCTUnwrap(metrics.first { $0.label == "General" })
XCTAssertLessThan(general.contentBounds.maxY, 380)
}
func testShortcutModifiersExposeHumanAccessibilityNames() {
let (controller, _) = makeController()
XCTAssertEqual(
controller.debugOpenShortcutModifierAccessibilityLabels,
["Command modifier", "Option modifier", "Control modifier", "Shift modifier"]
)
XCTAssertEqual(
controller.debugOpenShortcutModifierAccessibilityHelps,
[
"Include or remove the Command key from this shortcut.",
"Include or remove the Option key from this shortcut.",
"Include or remove the Control key from this shortcut.",
"Include or remove the Shift key from this shortcut."
]
)
}
func testWritesSettingsVisualSnapshotWhenRequested() throws {
guard ProcessInfo.processInfo.environment["CLIPBORED_WRITE_SETTINGS_SNAPSHOT"] == "1" else {
throw XCTSkip("Set CLIPBORED_WRITE_SETTINGS_SNAPSHOT=1 to write a Settings snapshot.")
}
let (controller, _) = makeController()
controller.debugSelectSettingsTab(at: 5)
controller.debugPrepareWindowForSnapshot()
drainMainQueue()
let view = try XCTUnwrap(controller.debugSettingsContentView)
view.layoutSubtreeIfNeeded()
view.displayIfNeeded()
let output = URL(
fileURLWithPath: ProcessInfo.processInfo.environment["CLIPBORED_SETTINGS_SNAPSHOT_PATH"]
?? "build/visual-snapshots/settings-data.png"
)
try FileManager.default.createDirectory(
at: output.deletingLastPathComponent(),
withIntermediateDirectories: true
)
let rep = try XCTUnwrap(view.bitmapImageRepForCachingDisplay(in: view.bounds))
rep.size = view.bounds.size
view.cacheDisplay(in: view.bounds, to: rep)
let image = NSImage(size: view.bounds.size)
image.addRepresentation(rep)
let bitmap = try XCTUnwrap(NSBitmapImageRep(data: try XCTUnwrap(image.tiffRepresentation)))
let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
try png.write(to: output)
}
func testCloudSyncStatusIsCachedAcrossUnrelatedSettingsRefreshes() { func testCloudSyncStatusIsCachedAcrossUnrelatedSettingsRefreshes() {
let cloudSyncService = CloudSyncProbe( let cloudSyncService = CloudSyncProbe(
status: ClipboardCloudSyncStatus( status: ClipboardCloudSyncStatus(

View File

@@ -36,24 +36,11 @@ final class ShortcutManagerTests: XCTestCase {
manager.stop() manager.stop()
} }
func testRejectsUnsupportedSettingsShortcutBeforeRegistration() { func testGlobalRegistrationExcludesLocalSettingsShortcut() {
let manager = makeManager( let bindings = ShortcutManager.globalShortcutBindings(openShortcut: AppConfiguration.defaultOpenShortcut)
openShortcut: AppConfiguration.defaultOpenShortcut,
settingsShortcut: ShortcutBinding(key: "space", modifierFlags: NSEvent.ModifierFlags.command.rawValue)
)
XCTAssertEqual(manager.start(), .unsupportedShortcut("⌘SPACE")) XCTAssertEqual(bindings, [AppConfiguration.defaultOpenShortcut, ShortcutManager.stackCaptureShortcut])
manager.stop() XCTAssertFalse(bindings.contains(AppConfiguration.defaultSettingsShortcut))
}
func testRejectsDuplicateShortcutBindingsBeforeRegistration() {
let manager = makeManager(
openShortcut: AppConfiguration.defaultOpenShortcut,
settingsShortcut: AppConfiguration.defaultOpenShortcut
)
XCTAssertEqual(manager.start(), .conflict(AppConfiguration.defaultOpenShortcut.displayText))
manager.stop()
} }
func testRejectsConfiguredShortcutConflictWithFixedStackCaptureShortcut() { func testRejectsConfiguredShortcutConflictWithFixedStackCaptureShortcut() {
@@ -63,15 +50,10 @@ final class ShortcutManagerTests: XCTestCase {
manager.stop() manager.stop()
} }
private func makeManager( private func makeManager(openShortcut: ShortcutBinding) -> ShortcutManager {
openShortcut: ShortcutBinding,
settingsShortcut: ShortcutBinding = AppConfiguration.defaultSettingsShortcut
) -> ShortcutManager {
ShortcutManager( ShortcutManager(
onOpenClipboardPanel: {}, onOpenClipboardPanel: {},
onOpenSettings: {}, openShortcut: openShortcut
openShortcut: openShortcut,
settingsShortcut: settingsShortcut
) )
} }
} }