summaryrefslogtreecommitdiff
path: root/gui-libs/wayfire-plugins-custom/files/wayfire-plugins-custom-0.1.0-qol-6.patch
blob: 67992f730928a9c94e36b47b48ce36f82c883428 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
diff --git a/plugins/clipboard-keys/README.md b/plugins/clipboard-keys/README.md
index a203b62..2363b42 100644
--- a/plugins/clipboard-keys/README.md
+++ b/plugins/clipboard-keys/README.md
@@ -20,9 +20,31 @@ screen is locked, or when nothing has keyboard focus, the keys pass through
 unchanged. Apps that inhibit compositor shortcuts (virtual machines, remote
 desktops) receive Super+C and Super+V themselves.
 
+## Copies outlive their app
+
+On Wayland the app you copied from holds the copy, so it used to vanish when
+that app quit. Wayfire now reads each copy's useful formats as soon as it is
+made and, when the app quits, offers them itself:
+
+- one text format, offered under every usual text name;
+- formatting and file lists (`text/html`, `text/uri-list`,
+  `x-special/gnome-copied-files`, RTF), so a table keeps its layout and copied
+  files still paste as files;
+- one image, unless the copy also has text (a spreadsheet's cells come with a
+  picture of them, costly to render and not what a paste wants).
+
+Limits: 8 MiB per text format, 64 MiB for the image, 80 MiB per copy; formats
+an app has not finished writing within 5 s are dropped. Copies a password
+manager marks secret (`x-kde-passwordManagerHint`) are never read, so nothing
+comes back after them, and clearing the clipboard on purpose (`wl-copy
+--clear`) leaves it empty. While the app runs it keeps serving its copy
+itself, with every format it offers. Nothing is written to disk. The copy of
+an X11 app that quits is not kept.
+
 | Option | Default | Meaning |
 | --- | --- | --- |
 | `copy` | `<super> KEY_C` | Copy in the focused app |
 | `paste` | `<super> KEY_V` | Paste in the focused app |
+| `keep_copies` | `true` | Keep what you copy for when its app quits |
 | `cut` | `none` | Cut (Ctrl+X); in a terminal it copies. Unbound because Super+X keeps a window on top |
 | `terminals` | a list of terminal names | Words that mark an app id as a terminal |
diff --git a/plugins/clipboard-keys/clipboard-keys.xml b/plugins/clipboard-keys/clipboard-keys.xml
index f8c1960..e577491 100644
--- a/plugins/clipboard-keys/clipboard-keys.xml
+++ b/plugins/clipboard-keys/clipboard-keys.xml
@@ -2,7 +2,7 @@
 <wayfire>
   <plugin name="clipboard-keys">
     <_short>Clipboard</_short>
-    <_long>Super+C and Super+V copy and paste in every app, terminals included. A terminal gets Ctrl+Shift+C and Ctrl+Shift+V, so Super+C never stops a running program; other apps get Ctrl+C and Ctrl+V.</_long>
+    <_long>Super+C and Super+V copy and paste in every app, terminals included. A terminal gets Ctrl+Shift+C and Ctrl+Shift+V, so Super+C never stops a running program; other apps get Ctrl+C and Ctrl+V. What you copy still pastes after its app quits.</_long>
     <category>Utility</category>
     <option name="copy" type="activator">
       <_short>Copy in any app</_short>
@@ -17,6 +17,11 @@
       <_long>Unbound by default because Super+X keeps a window on top. In a terminal it copies.</_long>
       <default>none</default>
     </option>
+    <option name="keep_copies" type="bool">
+      <_short>Keep copies after their app quits</_short>
+      <_long>Wayfire reads what you copy (text, formatting, file lists, an image) and offers it itself when the app it came from quits, so it still pastes. A password manager's copies are never kept, and clearing the clipboard clears it.</_long>
+      <default>true</default>
+    </option>
     <option name="terminals" type="string">
       <_short>Terminal app ids</_short>
       <_long>An app is a terminal when a word of its app id is in this list: "org.gnome.Terminal" and "xfce4-terminal" match "terminal". Add your terminal here if Super+C stops programs in it.</_long>
diff --git a/plugins/clipboard-keys/meson.build b/plugins/clipboard-keys/meson.build
index 2204529..b5071ce 100644
--- a/plugins/clipboard-keys/meson.build
+++ b/plugins/clipboard-keys/meson.build
@@ -3,4 +3,5 @@ shared_module('clipboard-keys', 'src/plugin.cpp', dependencies: wf,
 install_data('clipboard-keys.xml', install_dir: wf.get_variable(pkgconfig: 'metadatadir'))
 if get_option('tests')
   test('clipboard-keys-shortcuts', executable('clipboard-keys-test', 'tests/keys-test.cpp'), timeout: 30)
+  test('clipboard-keys-keeper', executable('clipboard-keys-keeper-test', 'tests/keeper-test.cpp'), timeout: 30)
 endif
diff --git a/plugins/clipboard-keys/src/keeper.hpp b/plugins/clipboard-keys/src/keeper.hpp
new file mode 100644
index 0000000..3441870
--- /dev/null
+++ b/plugins/clipboard-keys/src/keeper.hpp
@@ -0,0 +1,118 @@
+// Which formats of a copy Wayfire keeps for when its app quits, and which it
+// offers again. Display-free, so the unit test covers it.
+#pragma once
+#include <algorithm>
+#include <cstddef>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace clipboard_keys
+{
+constexpr size_t text_limit  = 8u << 20;  // per text format
+constexpr size_t image_limit = 64u << 20; // the one kept image
+constexpr size_t copy_limit  = 80u << 20; // everything kept from one copy
+
+inline const std::vector<std::string>& text_types()
+{
+    static const std::vector<std::string> types{"text/plain;charset=utf-8", "text/plain", "UTF8_STRING", "STRING",
+        "TEXT"};
+    return types;
+}
+
+// Formatting and file lists, kept as they are.
+inline const std::vector<std::string>& rich_types()
+{
+    static const std::vector<std::string> types{"text/html", "text/uri-list", "x-special/gnome-copied-files",
+        "text/rtf", "application/rtf"};
+    return types;
+}
+
+inline const std::vector<std::string>& image_types()
+{
+    static const std::vector<std::string> types{"image/png", "image/jpeg", "image/webp", "image/gif", "image/bmp",
+        "image/tiff"};
+    return types;
+}
+
+inline bool has(const std::vector<std::string>& list, const std::string& item)
+{
+    return std::find(list.begin(), list.end(), item) != list.end();
+}
+
+// A password manager's copy: nothing of it is kept.
+inline bool sensitive(const std::vector<std::string>& offered)
+{
+    return has(offered, "x-kde-passwordManagerHint");
+}
+
+struct wanted_t
+{
+    std::string mime;
+    size_t limit;
+};
+
+// One text format (the best named), every rich format, and one image unless
+// there is text: a spreadsheet's cells also come as a picture of them, which
+// is costly to render and not what a paste wants.
+inline std::vector<wanted_t> types_to_keep(const std::vector<std::string>& offered)
+{
+    std::vector<wanted_t> result;
+    if (sensitive(offered))
+    {
+        return result;
+    }
+
+    auto text = std::find_if(text_types().begin(), text_types().end(),
+        [&] (const std::string& t) { return has(offered, t); });
+    if (text != text_types().end())
+    {
+        result.push_back({*text, text_limit});
+    }
+
+    for (auto& mime : offered)
+    {
+        if (has(rich_types(), mime))
+        {
+            result.push_back({mime, text_limit});
+        }
+    }
+
+    if (text == text_types().end())
+    {
+        auto image = std::find_if(image_types().begin(), image_types().end(),
+            [&] (const std::string& t) { return has(offered, t); });
+        if (image != image_types().end())
+        {
+            result.push_back({*image, image_limit});
+        }
+    }
+
+    return result;
+}
+
+// What a kept copy offers, as (offered type, kept type): every kept type, and
+// the kept text under each of the usual text names.
+inline std::vector<std::pair<std::string, std::string>> types_to_offer(const std::vector<std::string>& kept)
+{
+    std::vector<std::pair<std::string, std::string>> result;
+    for (auto& mime : kept)
+    {
+        result.push_back({mime, mime});
+    }
+
+    auto text = std::find_if(kept.begin(), kept.end(), [] (const std::string& t) { return has(text_types(), t); });
+    if (text != kept.end())
+    {
+        for (auto& alias : text_types())
+        {
+            if (!has(kept, alias))
+            {
+                result.push_back({alias, *text});
+            }
+        }
+    }
+
+    return result;
+}
+}
diff --git a/plugins/clipboard-keys/src/plugin.cpp b/plugins/clipboard-keys/src/plugin.cpp
index b2435e6..21b7341 100644
--- a/plugins/clipboard-keys/src/plugin.cpp
+++ b/plugins/clipboard-keys/src/plugin.cpp
@@ -1,6 +1,11 @@
 // clipboard-keys: Super+C and Super+V copy and paste in every app, as on
 // Omarchy. The focused app receives Ctrl+Shift+C/V when it is a terminal and
 // Ctrl+C/V otherwise, sent straight to it through the seat.
+//
+// It also keeps each copy: its useful formats are read as soon as something is
+// copied, and when the app that copied quits Wayfire offers them itself, so the
+// copy can still be pasted, with its formatting or as files.
+#include "keeper.hpp"
 #include "keys.hpp"
 #include <wayfire/bindings-repository.hpp>
 #include <wayfire/core.hpp>
@@ -13,7 +18,14 @@
 #include <wayfire/view.hpp>
 #include <wayfire/nonstd/wlroots-full.hpp>
 #include <xkbcommon/xkbcommon.h>
+#include <cerrno>
+#include <cstring>
+#include <fcntl.h>
+#include <map>
+#include <memory>
 #include <optional>
+#include <set>
+#include <unistd.h>
 
 namespace
 {
@@ -54,12 +66,253 @@ std::optional<key_t> find_key(xkb_keymap *keymap, xkb_layout_index_t active, xkb
     return {};
 }
 
+// One copy's formats, read from the app that made it.
+class capture_t
+{
+    struct reader_t
+    {
+        capture_t *capture;
+        std::string mime, bytes;
+        size_t limit;
+        int fd;
+        wl_event_source *source;
+    };
+
+    std::vector<std::unique_ptr<reader_t>> readers;
+    size_t total = 0;
+    wf::wl_timer<false> deadline;
+    std::function<void()> on_done;
+
+    static int readable(int fd, uint32_t mask, void *data)
+    {
+        auto reader = static_cast<reader_t*>(data);
+        char buffer[65536];
+        while (true)
+        {
+            ssize_t got = read(fd, buffer, sizeof(buffer));
+            if (got > 0)
+            {
+                reader->bytes.append(buffer, got);
+                reader->capture->total += got;
+                if ((reader->bytes.size() > reader->limit) || (reader->capture->total > clipboard_keys::copy_limit))
+                {
+                    reader->capture->finish(reader, false);
+                    return 0;
+                }
+
+                continue;
+            }
+
+            if (got == 0)
+            {
+                reader->capture->finish(reader, true);
+            } else if ((errno != EAGAIN) && (errno != EINTR))
+            {
+                reader->capture->finish(reader, false);
+            } else if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR))
+            {
+                reader->capture->finish(reader, true);
+            }
+
+            return 0;
+        }
+    }
+
+    // Finished formats are kept (complete ones only); the copy is done when
+    // none is left.
+    void finish(reader_t *reader, bool complete)
+    {
+        wl_event_source_remove(reader->source);
+        close(reader->fd);
+        if (complete && !reader->bytes.empty())
+        {
+            formats[reader->mime] = std::move(reader->bytes);
+        }
+
+        auto it = std::find_if(readers.begin(), readers.end(), [&] (auto& r) { return r.get() == reader; });
+        readers.erase(it);
+        if (readers.empty())
+        {
+            deadline.disconnect();
+            if (on_done)
+            {
+                on_done();
+            }
+        }
+    }
+
+  public:
+    std::map<std::string, std::string> formats;
+
+    capture_t(wlr_data_source *source, const std::vector<clipboard_keys::wanted_t>& wanted,
+        std::function<void()> done) : on_done(std::move(done))
+    {
+        for (auto& want : wanted)
+        {
+            int fds[2];
+            if (pipe2(fds, O_CLOEXEC) != 0)
+            {
+                continue;
+            }
+
+            // Only our end is non-blocking: the app writes as it likes.
+            fcntl(fds[0], F_SETFL, O_NONBLOCK);
+            auto reader = std::make_unique<reader_t>(reader_t{this, want.mime, {}, want.limit, fds[0], nullptr});
+            reader->source = wl_event_loop_add_fd(wf::get_core().ev_loop, fds[0], WL_EVENT_READABLE, readable,
+                reader.get());
+            if (!reader->source)
+            {
+                close(fds[0]);
+                close(fds[1]);
+                continue;
+            }
+
+            // wlroots passes the write end to the app and closes ours.
+            wlr_data_source_send(source, want.mime.c_str(), fds[1]);
+            readers.push_back(std::move(reader));
+        }
+
+        // An app that never finishes writing is not waited for.
+        if (!readers.empty())
+        {
+            deadline.set_timeout(5000, [this]
+            {
+                while (!readers.empty())
+                {
+                    finish(readers.front().get(), false);
+                }
+            });
+        }
+    }
+
+    ~capture_t()
+    {
+        on_done = nullptr;
+        for (auto& reader : readers)
+        {
+            wl_event_source_remove(reader->source);
+            close(reader->fd);
+        }
+    }
+
+    bool reading() const
+    {
+        return !readers.empty();
+    }
+};
+
+// What Wayfire offers in place of an app that quit: a data source whose
+// formats are served from memory.
+struct kept_copy_t
+{
+    std::map<std::string, std::string> formats;
+    std::map<std::string, std::string> offered; // offered type -> kept type
+};
+
+// Standard layout with the wlroots source first, so the source pointer
+// wlroots hands back converts to it.
+struct kept_source_t
+{
+    wlr_data_source base;
+    std::shared_ptr<kept_copy_t> *copy;
+    void (*gone)(kept_source_t*);
+};
+
+// Writes one format to a pasting app without blocking Wayfire.
+struct writer_t
+{
+    std::shared_ptr<kept_copy_t> copy;
+    const std::string *bytes;
+    size_t offset;
+    int fd;
+    wl_event_source *source;
+};
+
+std::set<writer_t*> writers;
+
+void end_writer(writer_t *writer)
+{
+    wl_event_source_remove(writer->source);
+    close(writer->fd);
+    writers.erase(writer);
+    delete writer;
+}
+
+int writable(int fd, uint32_t mask, void *data)
+{
+    auto writer = static_cast<writer_t*>(data);
+    while (writer->offset < writer->bytes->size())
+    {
+        ssize_t sent = write(fd, writer->bytes->data() + writer->offset,
+            std::min<size_t>(65536, writer->bytes->size() - writer->offset));
+        if (sent > 0)
+        {
+            writer->offset += sent;
+            continue;
+        }
+
+        if ((sent < 0) && ((errno == EAGAIN) || (errno == EINTR)) && !(mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)))
+        {
+            return 0;
+        }
+
+        break; // the reader went away
+    }
+
+    end_writer(writer);
+    return 0;
+}
+
+void kept_send(wlr_data_source *source, const char *mime, int32_t fd)
+{
+    auto kept = reinterpret_cast<kept_source_t*>(source);
+    auto copy = *kept->copy;
+    auto offered = copy->offered.find(mime);
+    if (offered == copy->offered.end())
+    {
+        close(fd);
+        return;
+    }
+
+    fcntl(fd, F_SETFL, O_NONBLOCK);
+    auto writer = new writer_t{copy, &copy->formats.at(offered->second), 0, fd, nullptr};
+    writer->source = wl_event_loop_add_fd(wf::get_core().ev_loop, fd, WL_EVENT_WRITABLE, writable, writer);
+    if (!writer->source)
+    {
+        close(fd);
+        delete writer;
+        return;
+    }
+
+    writers.insert(writer);
+}
+
+void kept_destroy(wlr_data_source *source)
+{
+    auto kept = reinterpret_cast<kept_source_t*>(source);
+    kept->gone(kept);
+    delete kept->copy;
+    delete kept;
+}
+
+const wlr_data_source_impl kept_impl = []
+{
+    wlr_data_source_impl impl{};
+    impl.send    = kept_send;
+    impl.destroy = kept_destroy;
+    return impl;
+}();
+
+class clipboard_keys_plugin_t;
+clipboard_keys_plugin_t *instance = nullptr;
+
 class clipboard_keys_plugin_t : public wf::plugin_interface_t
 {
     wf::option_wrapper_t<wf::activatorbinding_t> copy_binding{"clipboard-keys/copy"};
     wf::option_wrapper_t<wf::activatorbinding_t> paste_binding{"clipboard-keys/paste"};
     wf::option_wrapper_t<wf::activatorbinding_t> cut_binding{"clipboard-keys/cut"};
     wf::option_wrapper_t<std::string> terminals{"clipboard-keys/terminals"};
+    wf::option_wrapper_t<bool> keep_copies{"clipboard-keys/keep_copies"};
 
     static bool locked()
     {
@@ -119,13 +372,166 @@ class clipboard_keys_plugin_t : public wf::plugin_interface_t
     wf::activator_callback on_paste = [this] (auto) { return send(action_t::paste); };
     wf::activator_callback on_cut   = [this] (auto) { return send(action_t::cut); };
 
+    // Keeping copies. `owner` is the app's copy on the clipboard now: wlroots
+    // drops it before announcing a replacement or a deliberate clear, but
+    // announces an empty clipboard while it is still tearing it down after
+    // its app quit. Only that last case brings the copy back.
+    wlr_data_source *owner = nullptr;
+    wf::wl_listener_wrapper on_owner_gone, on_selection;
+    std::unique_ptr<capture_t> capture;
+    kept_source_t *kept = nullptr;
+    bool restore_wanted = false;
+    wf::wl_idle_call idle_restore;
+    wf::wl_timer<false> restore_deadline;
+
+    void watch_owner(wlr_data_source *source)
+    {
+        on_owner_gone.disconnect();
+        owner = source;
+        if (source)
+        {
+            on_owner_gone.connect(&source->events.destroy);
+        }
+    }
+
+    void selection_changed()
+    {
+        wlr_seat *seat = wf::get_core().get_current_seat();
+        wlr_data_source *source = seat->selection_source;
+        if (kept && (source == &kept->base))
+        {
+            return;
+        }
+
+        if (!source)
+        {
+            if (owner && keep_copies)
+            {
+                // Its app quit: put the copy back once its formats are read
+                // (they usually are by now) and the teardown has finished.
+                restore_wanted = true;
+                if (capture && capture->reading())
+                {
+                    restore_deadline.set_timeout(1000, [this] { idle_restore.run_once(); });
+                } else
+                {
+                    idle_restore.run_once();
+                }
+            } else
+            {
+                // Cleared on purpose: nothing comes back.
+                capture.reset();
+            }
+
+            return;
+        }
+
+        // Something new was copied.
+        restore_wanted = false;
+        restore_deadline.disconnect();
+        idle_restore.disconnect();
+        watch_owner(source);
+        capture.reset();
+        if (!keep_copies)
+        {
+            return;
+        }
+
+        std::vector<std::string> offered;
+        auto types = static_cast<char**>(source->mime_types.data);
+        for (size_t i = 0; i < source->mime_types.size / sizeof(char*); i++)
+        {
+            offered.push_back(types[i]);
+        }
+
+        // A password manager's secret leaves nothing to bring back.
+        auto wanted = clipboard_keys::types_to_keep(offered);
+        if (!wanted.empty())
+        {
+            capture = std::make_unique<capture_t>(source, wanted, [this]
+            {
+                if (restore_wanted)
+                {
+                    restore_deadline.disconnect();
+                    idle_restore.run_once();
+                }
+            });
+        }
+    }
+
+    void restore()
+    {
+        restore_deadline.disconnect();
+        if (!restore_wanted)
+        {
+            return;
+        }
+
+        restore_wanted = false;
+        wlr_seat *seat = wf::get_core().get_current_seat();
+        // Not over anything copied in the meantime.
+        if (seat->selection_source || !capture || capture->formats.empty())
+        {
+            capture.reset();
+            return;
+        }
+
+        auto copy = std::make_shared<kept_copy_t>();
+        copy->formats = std::move(capture->formats);
+        capture.reset();
+        std::vector<std::string> types;
+        for (auto& [mime, bytes] : copy->formats)
+        {
+            types.push_back(mime);
+        }
+
+        auto source = new kept_source_t{};
+        wlr_data_source_init(&source->base, &kept_impl);
+        source->copy = new std::shared_ptr<kept_copy_t>(copy);
+        source->gone = [] (kept_source_t *gone)
+        {
+            if (instance && (instance->kept == gone))
+            {
+                instance->kept = nullptr;
+            }
+        };
+        for (auto& [offered, mime] : clipboard_keys::types_to_offer(types))
+        {
+            copy->offered[offered] = mime;
+            auto slot = static_cast<char**>(wl_array_add(&source->base.mime_types, sizeof(char*)));
+            *slot = strdup(offered.c_str());
+        }
+
+        kept = source;
+        watch_owner(nullptr);
+        wlr_seat_set_selection(seat, &source->base, wl_display_next_serial(wf::get_core().display));
+    }
+
   public:
     void init() override
     {
+        instance = this;
         auto& bindings = wf::get_core().bindings;
         bindings->add_activator(copy_binding, &on_copy);
         bindings->add_activator(paste_binding, &on_paste);
         bindings->add_activator(cut_binding, &on_cut);
+
+        on_owner_gone.set_callback([this] (void*)
+        {
+            on_owner_gone.disconnect();
+            owner = nullptr;
+        });
+        on_selection.set_callback([this] (void*) { selection_changed(); });
+        on_selection.connect(&wf::get_core().get_current_seat()->events.set_selection);
+        idle_restore.set_callback([this] { restore(); });
+        keep_copies.set_callback([this]
+        {
+            if (!keep_copies)
+            {
+                capture.reset();
+                restore_wanted = false;
+            }
+        });
     }
 
     void fini() override
@@ -134,6 +540,24 @@ class clipboard_keys_plugin_t : public wf::plugin_interface_t
         bindings->rem_binding(&on_copy);
         bindings->rem_binding(&on_paste);
         bindings->rem_binding(&on_cut);
+        on_selection.disconnect();
+        on_owner_gone.disconnect();
+        idle_restore.disconnect();
+        restore_deadline.disconnect();
+        capture.reset();
+        // Our copy's code leaves with the plugin, so it must leave the clipboard too.
+        wlr_seat *seat = wf::get_core().get_current_seat();
+        if (kept && (seat->selection_source == &kept->base))
+        {
+            wlr_seat_set_selection(seat, nullptr, wl_display_next_serial(wf::get_core().display));
+        }
+
+        while (!writers.empty())
+        {
+            end_writer(*writers.begin());
+        }
+
+        instance = nullptr;
     }
 };
 }
diff --git a/plugins/clipboard-keys/tests/keeper-test.cpp b/plugins/clipboard-keys/tests/keeper-test.cpp
new file mode 100644
index 0000000..8ff8b75
--- /dev/null
+++ b/plugins/clipboard-keys/tests/keeper-test.cpp
@@ -0,0 +1,55 @@
+// Unit test: which formats of a copy are kept, and what a kept copy offers.
+#include "../src/keeper.hpp"
+#include <cstdio>
+
+using namespace clipboard_keys;
+
+static int failures = 0;
+#define CHECK(cond) do { if (!(cond)) { std::printf("FAIL line %d: %s\n", __LINE__, #cond); failures++; } } while (0)
+
+static std::vector<std::string> mimes(const std::vector<wanted_t>& wanted)
+{
+    std::vector<std::string> result;
+    for (auto& w : wanted) result.push_back(w.mime);
+    return result;
+}
+
+int main()
+{
+    // Plain text: the best-named text type only.
+    CHECK(mimes(types_to_keep({"TEXT", "text/plain", "text/plain;charset=utf-8", "STRING", "UTF8_STRING"})) ==
+        (std::vector<std::string>{"text/plain;charset=utf-8"}));
+    CHECK(mimes(types_to_keep({"UTF8_STRING", "STRING"})) == (std::vector<std::string>{"UTF8_STRING"}));
+    // A web page: text and its formatting.
+    CHECK(mimes(types_to_keep({"text/html", "text/plain;charset=utf-8", "text/x-moz-url-priv"})) ==
+        (std::vector<std::string>{"text/plain;charset=utf-8", "text/html"}));
+    // Files: both file-list forms and the path text.
+    CHECK(mimes(types_to_keep({"text/uri-list", "x-special/gnome-copied-files", "text/plain;charset=utf-8"})) ==
+        (std::vector<std::string>{"text/plain;charset=utf-8", "text/uri-list", "x-special/gnome-copied-files"}));
+    // An image alone: PNG preferred.
+    CHECK(mimes(types_to_keep({"image/jpeg", "image/png", "text/html"})) ==
+        (std::vector<std::string>{"text/html", "image/png"}));
+    CHECK(mimes(types_to_keep({"image/bmp"})) == (std::vector<std::string>{"image/bmp"}));
+    // Spreadsheet cells: text, formatting, no picture.
+    CHECK(mimes(types_to_keep({"text/plain;charset=utf-8", "text/html", "text/rtf", "image/png",
+        "application/x-libreoffice-tsvc"})) ==
+        (std::vector<std::string>{"text/plain;charset=utf-8", "text/html", "text/rtf"}));
+    // Secrets and unknown formats: nothing.
+    CHECK(types_to_keep({"text/plain", "x-kde-passwordManagerHint"}).empty());
+    CHECK(types_to_keep({"application/x-something"}).empty());
+    CHECK(types_to_keep({}).empty());
+    CHECK(types_to_keep({"image/png"})[0].limit == image_limit);
+    CHECK(types_to_keep({"text/html"})[0].limit == text_limit);
+
+    // Offers: kept types, plus every text name for the kept text.
+    auto offer = types_to_offer({"text/html", "text/plain;charset=utf-8"});
+    CHECK(offer.size() == 6);
+    CHECK(offer[0] == (std::pair<std::string, std::string>{"text/html", "text/html"}));
+    CHECK(offer[2] == (std::pair<std::string, std::string>{"text/plain", "text/plain;charset=utf-8"}));
+    CHECK(offer[5] == (std::pair<std::string, std::string>{"TEXT", "text/plain;charset=utf-8"}));
+    CHECK(types_to_offer({"image/png"}).size() == 1);
+    CHECK(types_to_offer({}).empty());
+
+    std::printf("%s\n", failures ? "FAILED" : "ok");
+    return failures ? 1 : 0;
+}