diff --git a/README.md b/README.md index 2897dff..f44a2c7 100644 --- a/README.md +++ b/README.md @@ -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. | diff --git a/src/ui/Fuzzy.cpp b/src/ui/Fuzzy.cpp index f0370a4..48de847 100644 --- a/src/ui/Fuzzy.cpp +++ b/src/ui/Fuzzy.cpp @@ -1,7 +1,11 @@ #include "ui/Fuzzy.hpp" +#include #include #include +#include +#include +#include namespace copyclip::ui { @@ -11,23 +15,69 @@ namespace { return static_cast(std::tolower(static_cast(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 in_order_offsets(std::string_view query, + std::string_view text) { + std::vector 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 match_mask(std::string_view query, std::string_view text) { + std::vector 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(hit.begin() - text.begin()); + std::fill_n(mask.begin() + static_cast(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 diff --git a/src/ui/Fuzzy.hpp b/src/ui/Fuzzy.hpp index 7d661b2..0b2a096 100644 --- a/src/ui/Fuzzy.hpp +++ b/src/ui/Fuzzy.hpp @@ -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 #include +#include 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 match_mask(std::string_view query, std::string_view text); } // namespace copyclip::ui diff --git a/src/ui/MainWindow.cpp b/src/ui/MainWindow.cpp index f1ef3d9..e317952 100644 --- a/src/ui/MainWindow.cpp +++ b/src/ui/MainWindow.cpp @@ -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(lhs); const auto* b = dynamic_cast(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) { @@ -233,10 +238,8 @@ void MainWindow::build_ui(GtkApplication* application) { search_ = Gtk::make_managed(); 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(); @@ -405,6 +408,7 @@ 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()) { @@ -412,7 +416,11 @@ void MainWindow::apply_filter() { 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; @@ -420,6 +428,11 @@ void MainWindow::apply_filter() { ++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. @@ -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() { @@ -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()); } diff --git a/src/ui/MainWindow.hpp b/src/ui/MainWindow.hpp index 81015e7..5cb2846 100644 --- a/src/ui/MainWindow.hpp +++ b/src/ui/MainWindow.hpp @@ -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 @@ -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" @@ -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 @@ -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 history_; std::reference_wrapper settings_; diff --git a/src/ui/widgets/ClipCard.cpp b/src/ui/widgets/ClipCard.cpp index f986af2..eff2fcf 100644 --- a/src/ui/widgets/ClipCard.cpp +++ b/src/ui/widgets/ClipCard.cpp @@ -10,6 +10,9 @@ #include #include +#include +#include + #include #include @@ -20,6 +23,7 @@ #include +#include #include #include #include @@ -80,6 +84,73 @@ constexpr int kMetaIconSize = 12; return kind == core::ClipKind::Image ? "image-x-generic-symbolic" : "text-x-generic-symbolic"; } +// Search hits are painted like a find-in-page match: bold over a translucent +// yellow (GNOME palette yellow 3, #f6d32d), which reads on light and dark themes. +constexpr guint16 kHighlightRed = 0xf6f6; +constexpr guint16 kHighlightGreen = 0xd3d3; +constexpr guint16 kHighlightBlue = 0x2d2d; +constexpr guint16 kHighlightAlpha = 0x6666; // 40 % + +// `text` lowercased one code point at a time, with the byte offset in `text` of the +// code point behind each folded byte β€” so a hit in the folded text maps back onto +// `text` even where lowercasing changes a character's byte length. +struct Folded { + std::string text; + std::vector origin; +}; + +[[nodiscard]] Folded fold_case(const std::string& text) { + Folded folded; + folded.text.reserve(text.size()); + folded.origin.reserve(text.size()); + const char* const begin = text.data(); + const char* const end = begin + text.size(); + for (const char* at = begin; at < end; at = g_utf8_next_char(at)) { + std::array utf8{}; // the longest UTF-8 sequence g_unichar_to_utf8 writes + const auto length = static_cast( + g_unichar_to_utf8(g_unichar_tolower(g_utf8_get_char(at)), utf8.data())); + folded.text.append(utf8.data(), length); + folded.origin.insert(folded.origin.end(), length, static_cast(at - begin)); + } + return folded; +} + +// Pango attributes painting every hit of `query` in `text` (valid UTF-8). Hits are +// widened to whole code points, so a highlight never splits a character. +// shortcut: per-code-point lowercasing misses multi-character foldings (ß ↔ SS), +// which only costs a highlight, never a match β€” the filter folds whole strings. +[[nodiscard]] Pango::AttrList highlight(const std::string& text, const std::string& query) { + Pango::AttrList attributes; + if (query.empty()) { + return attributes; + } + const Folded folded = fold_case(text); + const std::vector mask = match_mask(fold_case(query).text, folded.text); + for (std::size_t at = 0; at < mask.size();) { + if (!mask[at]) { + ++at; + continue; + } + const std::size_t first = at; + while (at < mask.size() && mask[at]) { + ++at; + } + const auto start = static_cast(folded.origin[first]); + const char* const last = text.data() + folded.origin[at - 1]; + const auto stop = static_cast(g_utf8_next_char(last) - text.data()); + for (Pango::Attribute attribute : + {Pango::Attribute{Pango::Attribute::create_attr_weight(Pango::Weight::BOLD)}, + Pango::Attribute{Pango::Attribute::create_attr_background( + kHighlightRed, kHighlightGreen, kHighlightBlue)}, + Pango::Attribute{Pango::Attribute::create_attr_background_alpha(kHighlightAlpha)}}) { + attribute.set_start_index(start); + attribute.set_end_index(stop); + attributes.insert(attribute); + } + } + return attributes; +} + } // namespace ClipCard::ClipCard(const core::ClipboardEntry& entry, std::vector image, @@ -193,8 +264,11 @@ ClipCard::ClipCard(const core::ClipboardEntry& entry, std::vector ima void ClipCard::render_text() { const Preview preview = make_preview(entry_.content, max_chars_); + const std::string shown = expanded_ ? make_valid_utf8(entry_.content) : preview.text; - content_label_->set_text(expanded_ ? entry_.content : preview.text); + content_label_->set_text(shown); + Pango::AttrList hits = highlight(shown, query_); + content_label_->set_attributes(hits); content_label_->set_ellipsize(expanded_ ? Pango::EllipsizeMode::NONE : Pango::EllipsizeMode::END); content_label_->set_lines(expanded_ ? -1 : kCollapsedLines); @@ -205,6 +279,16 @@ void ClipCard::render_text() { } } +void ClipCard::set_query(const std::string& query) { + if (query == query_) { + return; + } + query_ = query; + if (content_label_ != nullptr) { + render_text(); + } +} + void ClipCard::toggle_expand() { expanded_ = !expanded_; render_text(); diff --git a/src/ui/widgets/ClipCard.hpp b/src/ui/widgets/ClipCard.hpp index 1c4a3a9..443703f 100644 --- a/src/ui/widgets/ClipCard.hpp +++ b/src/ui/widgets/ClipCard.hpp @@ -8,6 +8,7 @@ // reconstruct the right clipboard payload per kind. #include "core/Models.hpp" +#include "ui/Fuzzy.hpp" #include #include @@ -40,6 +41,15 @@ class ClipCard : public Gtk::ListBoxRow { // incrementally β€” detecting a pin/timestamp change without rebuilding every card. [[nodiscard]] const core::ClipboardEntry& entry() const { return entry_; } + // How the card answers the window's current search. The window sets it on each + // filter pass, and the list sorts on it before anything else. + [[nodiscard]] MatchQuality match() const { return match_; } + void set_match(MatchQuality match) { match_ = match; } + + // Highlight where the window's current search query hits the card's text (an + // empty query clears the highlight). Image cards ignore it. + void set_query(const std::string& query); + private: void render_text(); void toggle_expand(); @@ -48,8 +58,10 @@ class ClipCard : public Gtk::ListBoxRow { core::ClipboardEntry entry_; std::size_t max_chars_; bool expanded_ = false; - Gtk::Label* content_label_ = nullptr; // null for image cards - Gtk::Button* toggle_button_ = nullptr; // null for image cards + std::string query_; // the search query highlighted in the text + MatchQuality match_ = MatchQuality::Substring; // no search: every card ranks alike + Gtk::Label* content_label_ = nullptr; // null for image cards + Gtk::Button* toggle_button_ = nullptr; // null for image cards Glib::RefPtr gesture_; ActionCallback on_copy_; ActionCallback on_pin_; diff --git a/tests/ui/FuzzyTest.cpp b/tests/ui/FuzzyTest.cpp index 0a6fc17..f47a38c 100644 --- a/tests/ui/FuzzyTest.cpp +++ b/tests/ui/FuzzyTest.cpp @@ -2,31 +2,83 @@ #include +#include +#include + namespace { -using copyclip::ui::fuzzy_matches; +using copyclip::ui::match_quality; +using copyclip::ui::MatchQuality; TEST(FuzzyTest, EmptyQueryMatchesAnything) { - EXPECT_TRUE(fuzzy_matches("", "anything")); - EXPECT_TRUE(fuzzy_matches("", "")); + EXPECT_EQ(match_quality("", "anything"), MatchQuality::Substring); + EXPECT_EQ(match_quality("", ""), MatchQuality::Substring); +} + +TEST(FuzzyTest, ContiguousRunIsASubstringMatch) { + EXPECT_EQ(match_quality("png", "screenshot.png"), MatchQuality::Substring); + EXPECT_EQ(match_quality("hello", "hello"), MatchQuality::Substring); + EXPECT_EQ(match_quality("ell", "hello"), MatchQuality::Substring); } -TEST(FuzzyTest, MatchesSubsequence) { - EXPECT_TRUE(fuzzy_matches("spng", "screenshot.png")); - EXPECT_TRUE(fuzzy_matches("hlo", "hello")); - EXPECT_TRUE(fuzzy_matches("dl", "download")); - EXPECT_TRUE(fuzzy_matches("hello", "hello")); +TEST(FuzzyTest, ScatteredCharactersAreASubsequenceMatch) { + EXPECT_EQ(match_quality("spng", "screenshot.png"), MatchQuality::Subsequence); + EXPECT_EQ(match_quality("hlo", "hello"), MatchQuality::Subsequence); + EXPECT_EQ(match_quality("dl", "download"), MatchQuality::Subsequence); } TEST(FuzzyTest, IsCaseInsensitive) { - EXPECT_TRUE(fuzzy_matches("PNG", "screenshot.png")); - EXPECT_TRUE(fuzzy_matches("png", "SCREENSHOT.PNG")); + EXPECT_EQ(match_quality("PNG", "screenshot.png"), MatchQuality::Substring); + EXPECT_EQ(match_quality("png", "SCREENSHOT.PNG"), MatchQuality::Substring); + EXPECT_EQ(match_quality("SPNG", "screenshot.png"), MatchQuality::Subsequence); } TEST(FuzzyTest, RespectsOrderAndExhaustsQuery) { - EXPECT_FALSE(fuzzy_matches("gnp", "png")); // out of order - EXPECT_FALSE(fuzzy_matches("xyz", "hello")); // characters absent - EXPECT_FALSE(fuzzy_matches("helloo", "hello")); // query longer than the match + EXPECT_EQ(match_quality("gnp", "png"), MatchQuality::None); // out of order + EXPECT_EQ(match_quality("xyz", "hello"), MatchQuality::None); // characters absent + EXPECT_EQ(match_quality("helloo", "hello"), MatchQuality::None); // query longer than the match +} + +TEST(FuzzyTest, SubstringOutranksSubsequence) { + EXPECT_LT(MatchQuality::Substring, MatchQuality::Subsequence); + EXPECT_LT(MatchQuality::Subsequence, MatchQuality::None); +} + +// A long clip spells almost any query out of scattered letters; the clip that +// holds the query verbatim must still rank above it. +TEST(FuzzyTest, VerbatimClipOutranksLongClipWithScatteredLetters) { + const auto scattered = + match_quality("123soleil", "v1.2.3 changelog: fix the solver, release it later"); + const auto verbatim = match_quality("123soleil", "pass: 123Soleil!"); + EXPECT_EQ(scattered, MatchQuality::Subsequence); + EXPECT_EQ(verbatim, MatchQuality::Substring); + EXPECT_LT(verbatim, scattered); +} + +// The mask drawn as text: '^' under each highlighted byte, '.' elsewhere. +std::string marks(std::string_view query, std::string_view text) { + std::string drawn; + for (const bool hit : copyclip::ui::match_mask(query, text)) { + drawn += hit ? '^' : '.'; + } + return drawn; +} + +TEST(FuzzyTest, MaskMarksEveryVerbatimOccurrence) { + EXPECT_EQ(marks("ab", "abxab"), "^^.^^"); + EXPECT_EQ(marks("PNG", "a.png"), "..^^^"); + EXPECT_EQ(marks("aa", "aaa"), "^^."); // occurrences do not overlap +} + +TEST(FuzzyTest, MaskMarksScatteredCharactersWithoutAVerbatimRun) { + EXPECT_EQ(marks("hlo", "hello"), "^.^.^"); + EXPECT_EQ(marks("spng", "screenshot.png"), "^..........^^^"); +} + +TEST(FuzzyTest, MaskIsEmptyWithoutAMatch) { + EXPECT_EQ(marks("", "hello"), "....."); + EXPECT_EQ(marks("xyz", "hello"), "....."); + EXPECT_EQ(marks("gnp", "png"), "..."); } } // namespace