Skip to content
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ To start hidden — for autostart entries — pass `--background`.
| <kbd>Super</kbd>+<kbd>C</kbd> | Toggle the CopyClip window (default; configurable) |
| <kbd>Click</kbd> | Copy the clip (and auto-paste if enabled) |
| <kbd>Ctrl</kbd>+<kbd>Click</kbd> | Pin / unpin a clip |
| <kbd>Delete</kbd> | Remove the highlighted clip |
| Type | Fuzzy-search the history |
| <kbd>Esc</kbd> | Hide the window |

Expand Down
11 changes: 11 additions & 0 deletions src/ui/KeyAction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ BoundAccelerator bound_accelerator(std::string_view accelerator) {
return BoundAccelerator{.keyval = keyval, .modifiers = static_cast<unsigned int>(mods) & mask};
}

bool is_remove_key(unsigned int keyval) {
return keyval == GDK_KEY_Delete || keyval == GDK_KEY_KP_Delete;
}

KeyAction key_action(unsigned int keyval, unsigned int modifiers, const KeyContext& context,
const WindowShortcuts& shortcuts) {
switch (keyval) {
Expand Down Expand Up @@ -90,6 +94,13 @@ KeyAction key_action(unsigned int keyval, unsigned int modifiers, const KeyConte
default:
break;
}
// Delete removes the highlighted clip — but only outside an active search,
// where the entry needs Delete to forward-delete the query text, and never
// for a press continuing a run that began as such an edit. Removal is
// irreversible, so the run's opening press decides its role for all of it.
if (is_remove_key(keyval) && !context.search_active && !context.delete_disarmed) {
return KeyAction::RemoveSelected;
}
}
return KeyAction::None; // typing, Tab, modified arrows, everything else
}
Expand Down
9 changes: 9 additions & 0 deletions src/ui/KeyAction.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@ enum class KeyAction : std::uint8_t {
SelectNext, // move the highlight to the next match
Paste, // paste the highlighted clip
TogglePin, // pin / unpin the highlighted clip
RemoveSelected, // delete the highlighted clip from history
};

// The window state the policy depends on. Grouped in a struct so the call site
// reads as named fields rather than a row of anonymous bools.
struct KeyContext {
bool search_active = false; // the search entry holds text
bool button_focused = false; // a button has focus, so it owns Enter
// This Delete press continues a run that began while the query was non-empty.
// Such a run keeps editing text once the query empties, so holding Delete to
// clear the filter never rolls into destroying clips mid-press.
bool delete_disarmed = false;
};

// A parsed GNOME accelerator (keyval + modifier mask). Produced by
Expand All @@ -51,6 +56,10 @@ struct WindowShortcuts {
BoundAccelerator pin;
};

// True for the keys that remove the highlighted clip. Exposed so the window can
// track a held Delete across press and release without duplicating the keyval list.
[[nodiscard]] bool is_remove_key(unsigned int keyval);

// Map a key event to the action it asks for. `modifiers` must already be masked
// to gtk_accelerator_get_default_mod_mask() so it lines up with BoundAccelerator.
[[nodiscard]] KeyAction key_action(unsigned int keyval, unsigned int modifiers,
Expand Down
52 changes: 50 additions & 2 deletions src/ui/MainWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ void MainWindow::build_ui(GtkApplication* application) {
key_controller->set_propagation_phase(Gtk::PropagationPhase::CAPTURE);
key_controller->signal_key_pressed().connect(sigc::mem_fun(*this, &MainWindow::on_key_pressed),
false);
// Releases close a held-Delete run (see delete_run_disarmed_); nothing else
// needs them, and they carry no propagation decision.
key_controller->signal_key_released().connect(
sigc::mem_fun(*this, &MainWindow::on_key_released), false);
// add_controller takes ownership of a ref, so gobj_copy() mints it — unlike the
// plain gobj() handoff used for child widgets below, which would double-unref here.
gtk_widget_add_controller(GTK_WIDGET(window_),
Expand Down Expand Up @@ -450,8 +454,17 @@ bool MainWindow::on_key_pressed(guint keyval, guint /*keycode*/, Gdk::ModifierTy
// Caveat: an in-progress input-method preedit is not detected, so Enter and
// the arrows preempt CJK candidate selection. Filter through Gtk::IMContext if
// that ever matters.
const KeyContext context{.search_active = !search_->get_text().empty(),
.button_focused = button_focused(GTK_WINDOW(window_))};
const bool searching = !search_->get_text().empty();
// Latch the role of a run of Delete presses on its opening press. Auto-repeat
// re-enters here with the same key still down, and emptying the query flips
// `searching` mid-run — without the latch that turns a text edit into an
// unrecoverable removal, and then into a cascade of them.
if (is_remove_key(keyval) && !delete_run_disarmed_.has_value()) {
delete_run_disarmed_ = searching;
}
const KeyContext context{.search_active = searching,
.button_focused = button_focused(GTK_WINDOW(window_)),
.delete_disarmed = delete_run_disarmed_.value_or(false)};
// Same GNOME accelerator strings Settings stores; mask matches BoundAccelerator.
const auto mod_mask = static_cast<Gdk::ModifierType>(gtk_accelerator_get_default_mod_mask());
const auto modifiers = static_cast<unsigned int>(state & mod_mask);
Expand Down Expand Up @@ -482,13 +495,23 @@ bool MainWindow::on_key_pressed(guint keyval, guint /*keycode*/, Gdk::ModifierTy
// still points at a visible match after a just-typed query.
sync_search_from_entry();
return pin_selection();
case KeyAction::RemoveSelected:
// Only reached with an empty search (see key_action), so no filter to sync.
return remove_selection();
case KeyAction::None:
return false;
}
// No default case, so a new KeyAction trips -Wswitch rather than being ignored.
return false;
}

void MainWindow::on_key_released(guint keyval, guint /*keycode*/, Gdk::ModifierType /*state*/) {
// The run is over: the next Delete press re-reads the query and decides afresh.
if (is_remove_key(keyval)) {
delete_run_disarmed_.reset();
}
}

void MainWindow::move_selection(bool forward) {
// Ctrl+click reaches GtkListBox as a toggle and leaves the list unselected, so
// the cursor can be missing even with matches on screen. Start the scan at the
Expand Down Expand Up @@ -557,6 +580,28 @@ void MainWindow::reset_to_top() {
scrolled_->get_vadjustment()->set_value(kScrollTop);
}

bool MainWindow::remove_selection() {
ClipCard* const card = selected_card();
if (card == nullptr) {
return false;
}
const std::string content = card->entry().content;
// Hand the cursor to the neighbour that will outlive the removal — next match,
// else previous — so rebuild_cards restores the selection there instead of
// letting apply_filter snap it to the top. Delete can then be held down the list.
Gtk::ListBoxRow* neighbour = visible_row_from(card->get_next_sibling(), true);
if (neighbour == nullptr) {
neighbour = visible_row_from(card->get_prev_sibling(), false);
}
if (neighbour != nullptr) {
list_->select_row(*neighbour);
}
// remove() drops the entry whatever its pin state — Delete is an explicit user
// act, unlike the Clear button which spares pinned clips (clear_unpinned).
history_.get().remove(content);
return true;
}

void MainWindow::reveal(Gtk::ListBoxRow& row) {
double row_x = 0.0;
double row_y = 0.0;
Expand Down Expand Up @@ -669,6 +714,9 @@ void MainWindow::present() {
} else {
gtk_window_set_focus(GTK_WINDOW(window_), nullptr);
}
// A Delete held while the window went away never delivers its release here, so
// open with no run in flight rather than a key disarmed for the rest of the run.
delete_run_disarmed_.reset();
}

void MainWindow::refresh_tray() {
Expand Down
13 changes: 13 additions & 0 deletions src/ui/MainWindow.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>

namespace copyclip::ui {
Expand Down Expand Up @@ -80,6 +81,8 @@ class MainWindow {
// Returns true when the key was consumed; everything else falls through to
// the focused widget.
bool on_key_pressed(guint keyval, guint keycode, Gdk::ModifierType state);
// Close the run of Delete presses tracked by delete_run_disarmed_.
void on_key_released(guint keyval, guint keycode, Gdk::ModifierType state);
// Move the highlighted row to the next/previous match, and scroll it into view.
void move_selection(bool forward);
// Paste the highlighted clip. False when there is nothing highlighted, so the
Expand All @@ -95,6 +98,9 @@ class MainWindow {
// (gone, or hidden by the filter), leaving the cursor untouched for the caller to
// decide what that means.
bool cursor_to(const std::string& content);
// Delete the highlighted clip, moving the cursor to the next match first so the
// key can be pressed repeatedly down the list. False when nothing is selected.
bool remove_selection();
// The selected ClipCard, or nullptr when the list has no keyboard cursor.
[[nodiscard]] ClipCard* selected_card() const;
// Drop the filter immediately (entry + cached query + list). GtkSearchEntry's
Expand All @@ -121,6 +127,13 @@ class MainWindow {
bool refresh_pending_ = false;
std::size_t card_count_ = 0;
std::string search_text_;
// Whether the in-flight run of Delete presses began on a non-empty query — set
// by its first press, cleared on release, empty while no Delete is held. The
// run keeps that role throughout: clearing the query with a held Delete would
// otherwise turn destructive the instant the entry empties, and a removal has
// no undo. Also reset on present(), since a Delete held across a hide never
// delivers its release here and would leave the key disarmed for good.
std::optional<bool> delete_run_disarmed_;
// The newest created_at seen so far. When a rebuild's max exceeds it, a clip was
// just added (a copy or a paste) — the cue to put the cursor on it. Starts at
// startup time so the history already on disk, all of it older, counts as history
Expand Down
35 changes: 35 additions & 0 deletions tests/core/HistoryServiceTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,41 @@ TEST(HistoryServiceTest, ReAddsDuplicateAfterRemoval) {
EXPECT_EQ(contents_in_order(harness.service.entries()), (std::vector<std::string>{"x"}));
}

// remove() takes the entry whatever its pin state, unlike clear_unpinned. The UI's
// Delete key rides this, so a pinned clip is one keystroke from gone.
TEST(HistoryServiceTest, RemoveDropsAPinnedEntry) {
ServiceHarness harness;
harness.service.add("keep");
EXPECT_TRUE(harness.service.toggle_pin("keep"));
harness.service.remove("keep");
EXPECT_TRUE(harness.service.entries().empty());
}

// The window's card rebuild hangs off this notification; without it the deleted
// card would stay on screen.
TEST(HistoryServiceTest, RemoveNotifiesSubscribers) {
ServiceHarness harness;
harness.service.add("x");
std::vector<int> calls;
const auto sub = harness.service.subscribe([&calls] { calls.push_back(1); });
harness.service.remove("x");
EXPECT_TRUE(harness.service.entries().empty());
EXPECT_EQ(calls.size(), 1U);
}

// Removing absent content leaves the history alone — but still notifies. Holding
// Delete can re-issue a removal for a card the deferred rebuild has not dropped
// yet, so this path must stay harmless.
TEST(HistoryServiceTest, RemoveOfMissingContentIsHarmless) {
ServiceHarness harness;
harness.service.add("x");
std::vector<int> calls;
const auto sub = harness.service.subscribe([&calls] { calls.push_back(1); });
harness.service.remove("nope");
EXPECT_EQ(contents_in_order(harness.service.entries()), (std::vector<std::string>{"x"}));
EXPECT_EQ(calls.size(), 1U); // notifies unconditionally, even for a no-op
}

TEST(HistoryServiceTest, CapEvictsOldestUnpinned) {
ServiceHarness harness{2};
for (const auto* text : {"a", "b", "c"}) {
Expand Down
79 changes: 79 additions & 0 deletions tests/ui/KeyActionTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace {

using copyclip::ui::bound_accelerator;
using copyclip::ui::BoundAccelerator;
using copyclip::ui::is_remove_key;
using copyclip::ui::key_action;
using copyclip::ui::KeyAction;
using copyclip::ui::KeyContext;
Expand Down Expand Up @@ -106,6 +107,84 @@ TEST(KeyActionTest, ModifiedArrowsFallThrough) {
EXPECT_EQ(act(GDK_KEY_KP_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK), KeyAction::None);
}

// Delete removes the highlighted clip when the user is not filtering.
TEST(KeyActionTest, DeleteRemovesTheSelectionWhenNotSearching) {
EXPECT_EQ(act(GDK_KEY_Delete), KeyAction::RemoveSelected);
EXPECT_EQ(act(GDK_KEY_KP_Delete), KeyAction::RemoveSelected);
}

// Mid-search, Delete belongs to the entry (forward-delete a character), or the
// filter can't be edited with it.
TEST(KeyActionTest, DeleteEditsTextWhileSearching) {
EXPECT_EQ(act(GDK_KEY_Delete, 0, kSearching), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_KP_Delete, 0, kSearching), KeyAction::None);
}

// Modified Delete falls through so the entry keeps Ctrl+Delete (word delete).
TEST(KeyActionTest, ModifiedDeleteFallsThrough) {
EXPECT_EQ(act(GDK_KEY_Delete, GDK_CONTROL_MASK), KeyAction::None);
}

// Only the bare key removes: Shift+Delete is the desktop-wide "cut", and the rest
// belong to the entry. A removal is unrecoverable, so it must not ride a chord.
TEST(KeyActionTest, DeleteWithAnyOtherModifierFallsThrough) {
EXPECT_EQ(act(GDK_KEY_Delete, GDK_SHIFT_MASK), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_Delete, GDK_ALT_MASK), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_Delete, GDK_SUPER_MASK), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_KP_Delete, GDK_SHIFT_MASK), KeyAction::None);
}

// With NumLock on, the keypad's delete key reports KP_Decimal — a "." the user is
// typing. Only the NumLock-off KP_Delete may remove a clip.
TEST(KeyActionTest, KeypadDecimalIsNotDelete) {
EXPECT_EQ(act(GDK_KEY_KP_Decimal), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_KP_Decimal, 0, kSearching), KeyAction::None);
}

// Delete acts on the list selection, not the focused widget — like pin, unlike
// Enter, which a focused button owns.
TEST(KeyActionTest, DeleteRemovesWithAButtonFocused) {
EXPECT_EQ(act(GDK_KEY_Delete, 0, kOnButton), KeyAction::RemoveSelected);
}

// The hazard the disarm flag exists for: holding Delete to clear the query empties
// the entry mid-press, flipping search_active to false. Without the latch the same
// physical press would roll straight into removing clips, which has no undo.
TEST(KeyActionTest, DisarmedDeleteKeepsEditingTextOnceTheQueryEmpties) {
constexpr KeyContext disarmed{
.search_active = false, .button_focused = false, .delete_disarmed = true};
EXPECT_EQ(act(GDK_KEY_Delete, 0, disarmed), KeyAction::None);
EXPECT_EQ(act(GDK_KEY_KP_Delete, 0, disarmed), KeyAction::None);
}

// The flag is scoped to the Delete run and must not disarm anything else.
TEST(KeyActionTest, DisarmingDeleteLeavesTheOtherKeysAlone) {
constexpr KeyContext disarmed{
.search_active = false, .button_focused = false, .delete_disarmed = true};
EXPECT_EQ(act(GDK_KEY_Down, 0, disarmed), KeyAction::SelectNext);
EXPECT_EQ(act(GDK_KEY_Return, 0, disarmed), KeyAction::Paste);
EXPECT_EQ(act(GDK_KEY_Escape, 0, disarmed), KeyAction::Dismiss);
}

// MainWindow tracks a held Delete through this predicate, so it must cover exactly
// the keys the policy removes on — no more (KP_Decimal is a typed ".").
TEST(KeyActionTest, IsRemoveKeyCoversTheDeleteFamilyOnly) {
EXPECT_TRUE(is_remove_key(GDK_KEY_Delete));
EXPECT_TRUE(is_remove_key(GDK_KEY_KP_Delete));
EXPECT_FALSE(is_remove_key(GDK_KEY_KP_Decimal));
EXPECT_FALSE(is_remove_key(GDK_KEY_BackSpace));
}

// Configured shortcuts are matched before the fixed keys, so rebinding pin (or
// paste) onto Delete silently costs the user the removal shortcut.
TEST(KeyActionTest, RebindingOntoDeleteWinsOverRemoval) {
const WindowShortcuts pin_on_delete{
.paste = BoundAccelerator{.keyval = GDK_KEY_Return, .modifiers = 0},
.pin = BoundAccelerator{.keyval = GDK_KEY_Delete, .modifiers = 0},
};
EXPECT_EQ(act(GDK_KEY_Delete, 0, kFresh, pin_on_delete), KeyAction::TogglePin);
}

// Typing must reach the search entry untouched, or the filter stops working.
TEST(KeyActionTest, OtherKeysFallThrough) {
EXPECT_EQ(act(GDK_KEY_a, 0, kSearching), KeyAction::None);
Expand Down
Loading