diff --git a/README.md b/README.md index 2897dff..a354ab5 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. | | ⌨️ **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..290d594 100644 --- a/src/ui/Fuzzy.cpp +++ b/src/ui/Fuzzy.cpp @@ -1,7 +1,9 @@ #include "ui/Fuzzy.hpp" +#include #include -#include +#include +#include namespace copyclip::ui { @@ -11,18 +13,20 @@ namespace { return static_cast(std::tolower(static_cast(c))); } -} // namespace +// 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(); +} +// True when every character of a non-empty `query` appears in `text`, in order. // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly. -bool fuzzy_matches(std::string_view query, std::string_view text) { - if (query.empty()) { - return true; - } - std::size_t matched = 0; +[[nodiscard]] bool contains_in_order(std::string_view query, std::string_view text) { + std::string_view pending = query; // the characters still to find, in order for (const char glyph : text) { - if (lower(glyph) == lower(query[matched])) { - ++matched; - if (matched == query.size()) { + if (lower(glyph) == lower(pending.front())) { + pending.remove_prefix(1); + if (pending.empty()) { return true; } } @@ -30,4 +34,20 @@ bool fuzzy_matches(std::string_view query, std::string_view text) { return false; } +} // namespace + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): query/text read clearly. +MatchQuality match_quality(std::string_view query, std::string_view text) { + if (query.empty()) { + return MatchQuality::Substring; + } + if (contains(query, text)) { + return MatchQuality::Substring; + } + if (contains_in_order(query, text)) { + return MatchQuality::Subsequence; + } + return MatchQuality::None; +} + } // namespace copyclip::ui diff --git a/src/ui/Fuzzy.hpp b/src/ui/Fuzzy.hpp index 7d661b2..8cb81a3 100644 --- a/src/ui/Fuzzy.hpp +++ b/src/ui/Fuzzy.hpp @@ -1,18 +1,29 @@ #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 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]] bool fuzzy_matches(std::string_view query, std::string_view text); +[[nodiscard]] MatchQuality match_quality(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..1f3a3be 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,10 @@ 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); + const bool shown = quality != MatchQuality::None; card->set_visible(shown); if (!shown) { continue; @@ -420,6 +427,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 +553,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 +689,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.hpp b/src/ui/widgets/ClipCard.hpp index 1c4a3a9..07cf001 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,11 @@ 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; } + private: void render_text(); void toggle_expand(); @@ -48,8 +54,9 @@ 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 + 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..414fa88 100644 --- a/tests/ui/FuzzyTest.cpp +++ b/tests/ui/FuzzyTest.cpp @@ -4,29 +4,52 @@ 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, 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, 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, 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); } } // namespace