Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Developed and tested on GNOME (Mutter), X11 and Wayland sessions. It is young so
| 🗂️ **History** | Captures text, rich text (HTML), and images or screenshots as you copy them, newest first. |
| 🖼️ **Image thumbnails** | Copied and pasted images render as thumbnails instead of raw byte counts. |
| 📌 **Pinning** | Pin the clips you reuse so they stay at the top. |
| 🔍 **Fuzzy search** | Start typing to filter the whole history. |
| 🔍 **Fuzzy search** | Start typing to filter the whole history — exact matches come first, with the hits highlighted. |
| ⌨️ **One hotkey, both servers** | A configurable shortcut (default `Super+C`) toggles the window on X11 and Wayland. |
| 📋 **Click to paste** | Click a clip to copy it, and optionally auto-paste it into the window you came from. |
| 🌗 **Themes** | Dark, light, or follow the system. |
Expand Down
70 changes: 60 additions & 10 deletions src/ui/Fuzzy.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
#include "ui/Fuzzy.hpp"

#include <algorithm>
#include <cctype>
#include <cstddef>
#include <functional>
#include <string_view>
#include <vector>

namespace copyclip::ui {

Expand All @@ -11,23 +15,69 @@ namespace {
return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}

// True when `query` appears in `text` as one contiguous run.
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
[[nodiscard]] bool contains(std::string_view query, std::string_view text) {
return !std::ranges::search(text, query, std::ranges::equal_to{}, lower, lower).empty();
}

// Offsets in `text` of the characters that spell a non-empty `query` in order,
// taking each at its first chance — empty when the query is not spelled out.
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
[[nodiscard]] std::vector<std::size_t> in_order_offsets(std::string_view query,
std::string_view text) {
std::vector<std::size_t> offsets;
offsets.reserve(query.size());
for (std::size_t at = 0; at < text.size(); ++at) {
if (lower(text[at]) == lower(query[offsets.size()])) {
offsets.push_back(at);
if (offsets.size() == query.size()) {
return offsets;
}
}
}
return {};
}

} // namespace

// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
bool fuzzy_matches(std::string_view query, std::string_view text) {
MatchQuality match_quality(std::string_view query, std::string_view text) {
if (query.empty()) {
return true;
return MatchQuality::Substring;
}
std::size_t matched = 0;
for (const char glyph : text) {
if (lower(glyph) == lower(query[matched])) {
++matched;
if (matched == query.size()) {
return true;
}
if (contains(query, text)) {
return MatchQuality::Substring;
}
if (!in_order_offsets(query, text).empty()) {
return MatchQuality::Subsequence;
}
return MatchQuality::None;
}

// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
std::vector<bool> match_mask(std::string_view query, std::string_view text) {
std::vector<bool> mask(text.size(), false);
if (query.empty()) {
return mask;
}
bool verbatim = false;
for (std::string_view rest = text;;) {
const auto hit = std::ranges::search(rest, query, std::ranges::equal_to{}, lower, lower);
if (hit.empty()) {
break;
}
const auto start = static_cast<std::size_t>(hit.begin() - text.begin());
std::fill_n(mask.begin() + static_cast<std::ptrdiff_t>(start), query.size(), true);
rest = text.substr(start + query.size());
verbatim = true;
}
if (!verbatim) {
for (const std::size_t at : in_order_offsets(query, text)) {
mask[at] = true;
}
}
return false;
return mask;
}

} // namespace copyclip::ui
35 changes: 27 additions & 8 deletions src/ui/Fuzzy.hpp
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
#pragma once

// Fuzzy subsequence matching for the search box — no GTK, so it unit-tests
// headless. A clip matches when every character of the query appears in its text
// in order (not necessarily adjacent), case-insensitively. This is more forgiving
// than a substring search: "spng" still finds "screenshot.png".
// Fuzzy matching for the search box — no GTK, so it unit-tests headless. A clip
// matches when every character of the query appears in its text in order (not
// necessarily adjacent), case-insensitively: "spng" still finds "screenshot.png".
// That forgiveness lets a long clip match almost any query by scattered letters,
// so a match is also ranked: the query found as one contiguous run outranks the
// same characters strewn across the text.

#include <cstdint>
#include <string_view>
#include <vector>

namespace copyclip::ui {

// True when `query` is a case-insensitive (ASCII) subsequence of `text`. An empty
// query always matches. For full Unicode case-folding, pass already-lowercased
// input (the ASCII fold here is then a no-op).
// How a text answers a search query, best first — so comparing two values with <
// ranks them.
enum class MatchQuality : std::uint8_t {
Substring, // the query appears as one contiguous run
Subsequence, // the query's characters appear in order, with gaps between them
None, // the text does not match
};

// How `text` answers `query`, folding ASCII case. An empty query is a substring of
// any text. For full Unicode case-folding, pass already-lowercased input (the
// ASCII fold here is then a no-op).
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
[[nodiscard]] MatchQuality match_quality(std::string_view query, std::string_view text);

// Which bytes of `text` answer `query`, for highlighting it in the card: every
// verbatim occurrence when there is one, else the in-order characters that make
// it a subsequence match. Same case rules as match_quality. All false for an
// empty query or no match.
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly.
[[nodiscard]] bool fuzzy_matches(std::string_view query, std::string_view text);
[[nodiscard]] std::vector<bool> match_mask(std::string_view query, std::string_view text);

} // namespace copyclip::ui
50 changes: 34 additions & 16 deletions src/ui/MainWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,20 @@ void trim_heap() {
return layout;
}

// Orders rows like HistoryService::sorted (pinned first, then newest first) so the
// ListBox places an incrementally-inserted card in its right spot without a full
// rebuild. Rows are always ClipCards; a defensive null check keeps it total.
// Orders rows by how well they match the search, then like HistoryService::sorted
// (pinned first, then newest first) so the ListBox places an incrementally-inserted
// card in its right spot without a full rebuild. With no search every card matches
// alike, leaving the history order. Rows are always ClipCards; a defensive null
// check keeps it total.
[[nodiscard]] int clip_card_sort(Gtk::ListBoxRow* lhs, Gtk::ListBoxRow* rhs) {
const auto* a = dynamic_cast<const ClipCard*>(lhs);
const auto* b = dynamic_cast<const ClipCard*>(rhs);
if (a == nullptr || b == nullptr) {
return 0;
}
if (a->match() != b->match()) {
return a->match() < b->match() ? -1 : 1; // closer matches first
}
const core::ClipboardEntry& ea = a->entry();
const core::ClipboardEntry& eb = b->entry();
if (ea.pinned != eb.pinned) {
Expand Down Expand Up @@ -233,10 +238,8 @@ void MainWindow::build_ui(GtkApplication* application) {

search_ = Gtk::make_managed<Gtk::SearchEntry>();
search_->set_placeholder_text("Search clipboard history…");
search_->signal_search_changed().connect([this] {
search_text_ = search_->get_text().raw();
apply_filter();
});
search_->signal_search_changed().connect(
sigc::mem_fun(*this, &MainWindow::sync_search_from_entry));
content->append(*search_);

stack_ = Gtk::make_managed<Gtk::Stack>();
Expand Down Expand Up @@ -405,21 +408,31 @@ void MainWindow::apply_filter() {

const Gtk::ListBoxRow* selected = list_->get_selected_row();
bool selection_shown = false;
bool reranked = false;
std::size_t visible = 0;
for (Gtk::Widget* child = list_->get_first_child(); child != nullptr;
child = child->get_next_sibling()) {
auto* card = dynamic_cast<ClipCard*>(child);
if (card == nullptr) {
continue;
}
const bool shown = matches(card->content());
const MatchQuality quality = match(card->content());
reranked = reranked || quality != card->match();
card->set_match(quality);
card->set_query(search_text_);
const bool shown = quality != MatchQuality::None;
card->set_visible(shown);
if (!shown) {
continue;
}
++visible;
selection_shown = selection_shown || card == selected;
}
// Re-sort only once the walk is done: sorting reorders the very siblings it steps
// through. Then the cursor's fallback below lands on the best match.
if (reranked) {
list_->invalidate_sort();
}

// Always leave a row highlighted for Enter to act on. When the filter — or a
// rebuild that dropped the card — took the selection away, the cursor goes home.
Expand Down Expand Up @@ -541,12 +554,17 @@ void MainWindow::clear_search() {
}

void MainWindow::sync_search_from_entry() {
const std::string live = search_->get_text().raw();
std::string live = search_->get_text().raw();
if (live == search_text_) {
return;
}
search_text_ = live;
search_text_ = std::move(live);
apply_filter();
// A new query re-ranks the list, so the cursor goes to its best match rather than
// staying on a weaker one the old query left it on: Enter pastes the top result.
if (!search_text_.empty()) {
reset_to_top();
}
}

bool MainWindow::activate_selection() {
Expand Down Expand Up @@ -672,14 +690,14 @@ void MainWindow::open_settings() {
[this] { Glib::signal_idle().connect_once([this] { settings_dialog_.reset(); }); });
}

bool MainWindow::matches(const std::string& content) const {
MatchQuality MainWindow::match(const std::string& content) const {
if (search_text_.empty()) {
return true;
return MatchQuality::Substring; // the empty query: a substring of everything
}
// Fuzzy subsequence match, case-folded through Glib for Unicode correctness.
// Sanitize the content first: a legacy clip may hold invalid UTF-8, which
// Glib::ustring's case-folding rejects.
return fuzzy_matches(Glib::ustring{search_text_}.lowercase().raw(),
// Fuzzy match, case-folded through Glib for Unicode correctness. Sanitize the
// content first: a legacy clip may hold invalid UTF-8, which Glib::ustring's
// case-folding rejects.
return match_quality(Glib::ustring{search_text_}.lowercase().raw(),
Glib::ustring{make_valid_utf8(content)}.lowercase().raw());
}

Expand Down
12 changes: 8 additions & 4 deletions src/ui/MainWindow.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
// is reconciled incrementally — only added, removed, or changed (pin/timestamp)
// cards are touched, and a ListBox sort function repositions rows — so a single
// new clip touches one widget, not all N. Search toggles each card's visibility in
// place. Refreshes are deferred to an idle so a card may safely trigger one from
// inside its own click handler.
// place and ranks the matches, the query found verbatim above the query found as
// scattered letters. Refreshes are deferred to an idle so a card may safely trigger
// one from inside its own click handler.
//
// The window is keyboard-first: focus stays in the search entry, Up/Down move the
// highlighted row through the filtered list, Enter pastes it, and Escape drops the
Expand All @@ -19,6 +20,7 @@
#include "core/Interfaces.hpp"
#include "core/SettingsService.hpp"
#include "ui/CopyAction.hpp"
#include "ui/Fuzzy.hpp"
#include "ui/Paster.hpp"
#include "ui/StatusNotifierItem.hpp"
#include "ui/dialogs/SettingsDialog.hpp"
Expand Down Expand Up @@ -106,7 +108,8 @@ class MainWindow {
// Drop the filter immediately (entry + cached query + list). GtkSearchEntry's
// search-changed is delayed ~150 ms; Escape and hide must not wait for it.
void clear_search();
// Pull the live entry into search_text_ and refilter if it changed. Call before
// Pull the live entry into search_text_ and refilter if it changed, putting the
// cursor on a new query's best match. Runs on search-changed, and before
// paste/arrows so a fast type→Enter does not act on the pre-debounce list.
void sync_search_from_entry();
// Scroll the list so `row` is visible — moving the selection from the search
Expand All @@ -118,7 +121,8 @@ class MainWindow {
void pin(const std::string& content);
void clear_history();
void open_settings();
[[nodiscard]] bool matches(const std::string& content) const;
// How `content` answers the current search query.
[[nodiscard]] MatchQuality match(const std::string& content) const;

std::reference_wrapper<core::HistoryService> history_;
std::reference_wrapper<core::SettingsService> settings_;
Expand Down
Loading
Loading