summaryrefslogtreecommitdiff
path: root/gui-libs/wayfire-plugins-custom/files/wayfire-plugins-custom-0.1.0-qol-5.patch
blob: 2c7fa90521b1536a1505606278c987b3ec7b8d88 (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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
diff --git a/README.md b/README.md
index b2d567d..e38690d 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,9 @@ in Wayfire 0.11.0-r19 or newer. Unpatched upstream Wayfire is not supported.
 | `clipboard-keys` | Super+C and Super+V copy and paste in every app | Wayfire |
 | `hold-super` | Hold Super to see the shortcut sheet | Wayfire, `pyr keys` |
 | `raise-on-release` | Clicking a background window raises it on release, so you can drag out of it | Wayfire |
+| `open-here` | New windows open on the monitor under the pointer, at their app's last size | Wayfire |
 
-All eight build by default. Building a module does not enable it in Wayfire.
+All nine build by default. Building a module does not enable it in Wayfire.
 Window-actions owns the desktop's spatial transactions, previews and physical
 capture identity; it has no storage and no options. It replaces the former
 `window-state` plugin: in `wayfire.ini`, replace `window-state` with
@@ -44,6 +45,7 @@ The installed libraries:
 - `libclipboard-keys.so`.
 - `libhold-super.so`.
 - `libraise-on-release.so`.
+- `libopen-here.so`.
 
 The package replaces the standalone implementations. Compatibility ebuilds for
 `wayfire-window-state` and `wayfire-panel-desktop` depend
diff --git a/meson.build b/meson.build
index f3a7239..805709d 100644
--- a/meson.build
+++ b/meson.build
@@ -2,10 +2,10 @@ project('wayfire-plugins-custom', 'cpp', version: '0.1.0',
   default_options: ['cpp_std=c++17', 'warning_level=3'])
 
 wf = dependency('wayfire', version: '>=0.11.0')
-if not get_option('window-actions') and not get_option('panel-desktop') and not get_option('workspace-backgrounds') and not get_option('screensaver') and not get_option('find-pointer') and not get_option('clipboard-keys') and not get_option('hold-super') and not get_option('raise-on-release')
+if not get_option('window-actions') and not get_option('panel-desktop') and not get_option('workspace-backgrounds') and not get_option('screensaver') and not get_option('find-pointer') and not get_option('clipboard-keys') and not get_option('hold-super') and not get_option('raise-on-release') and not get_option('open-here')
   error('Enable at least one plugin')
 endif
-foreach plugin : ['window-actions', 'panel-desktop', 'workspace-backgrounds', 'screensaver', 'find-pointer', 'clipboard-keys', 'hold-super', 'raise-on-release']
+foreach plugin : ['window-actions', 'panel-desktop', 'workspace-backgrounds', 'screensaver', 'find-pointer', 'clipboard-keys', 'hold-super', 'raise-on-release', 'open-here']
   if get_option(plugin)
     subdir('plugins' / plugin)
   endif
@@ -19,5 +19,6 @@ summary({
   'clipboard-keys': get_option('clipboard-keys'),
   'hold-super': get_option('hold-super'),
   'raise-on-release': get_option('raise-on-release'),
+  'open-here': get_option('open-here'),
   'tests': get_option('tests'),
 }, section: 'Custom Wayfire plugins')
diff --git a/meson_options.txt b/meson_options.txt
index 1b03ef1..d536c1d 100644
--- a/meson_options.txt
+++ b/meson_options.txt
@@ -8,3 +8,4 @@ option('find-pointer', type: 'boolean', value: true, description: 'Press Ctrl tw
 option('clipboard-keys', type: 'boolean', value: true, description: 'Super+C and Super+V copy and paste in every app')
 option('hold-super', type: 'boolean', value: true, description: 'Hold Super to see the shortcut sheet')
 option('raise-on-release', type: 'boolean', value: true, description: 'Clicking a background window raises it on release, so a drag out of it stays behind')
+option('open-here', type: 'boolean', value: true, description: 'New windows open on the monitor under the pointer, at their app\'s last size')
diff --git a/plugins/open-here/LICENSE b/plugins/open-here/LICENSE
new file mode 100644
index 0000000..c90d3ad
--- /dev/null
+++ b/plugins/open-here/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 open-here contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/open-here/README.md b/plugins/open-here/README.md
new file mode 100644
index 0000000..a57218e
--- /dev/null
+++ b/plugins/open-here/README.md
@@ -0,0 +1,46 @@
+# open-here
+
+New windows open where you're working, at the size you left them.
+
+- **On the monitor under the pointer.** Wayfire otherwise opens a window on
+  the focused output, which only changes when you click, so a window started
+  with the pointer on another monitor could open out of sight. Without a
+  pointer, the window opens on the focused window's monitor. On a combined
+  (stitched) output with the `physical` window scope, each member monitor counts,
+  which window scope already did for the pointer. The `place` plugin then
+  positions the window on that monitor as `place/mode` says (centred by default).
+- **At the app's last size.** When an app's window closes, its size is
+  remembered; the app's next window opens at that size, limited to the
+  monitor's work area. Instances of one app share a size: a per-instance
+  suffix of the app id is ignored (`org.wayfire.Files.s1a2b3` is
+  `org.wayfire.Files`).
+
+Left alone:
+
+- dialogs and other windows with a parent: they open over their parent;
+- fixed-size windows, and windows that open maximized or fullscreen (a window
+  closed while maximized remembers its size from before);
+- apps that size their own windows. The size is applied only when the app
+  opens at the size it usually does; an app that comes back at its last size
+  itself, or picks a new one (restoring its own geometry, or fitting content),
+  is respected;
+- windows that set their own position, and apps that a window rule
+  (`core/window_scope_rules`) or `core/default_output` sends to one monitor.
+
+The size is applied as the window maps, before it is shown, so it doesn't
+jump. It is the content size: server-side decorations are added on top.
+
+Sizes are kept per app, most recently used first, for 100 apps, in
+`$XDG_STATE_HOME/wayfire/window-sizes` (`~/.local/state/wayfire/window-sizes`):
+a tab-separated text file, mode 0600, rewritten whole (temporary file, fsync,
+rename) on a worker thread a second after a change. A damaged or oversized file
+is read as far as it makes sense and replaced on the next save; deleting it
+forgets all sizes.
+
+Add `open-here` to `[core] plugins`, next to `place`. It runs after the
+decoration and `place` plugins and needs the local window-scope extensions.
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `follow_pointer` | `true` | Open windows on the monitor under the pointer |
+| `remember_size` | `true` | Open apps at the size their last window had |
diff --git a/plugins/open-here/meson.build b/plugins/open-here/meson.build
new file mode 100644
index 0000000..90ed1cd
--- /dev/null
+++ b/plugins/open-here/meson.build
@@ -0,0 +1,6 @@
+shared_module('open-here', 'src/plugin.cpp', dependencies: [wf, dependency('threads')],
+  install: true, install_dir: wf.get_variable(pkgconfig: 'plugindir'))
+install_data('open-here.xml', install_dir: wf.get_variable(pkgconfig: 'metadatadir'))
+if get_option('tests')
+  test('open-here-placement', executable('open-here-placement-test', 'tests/placement-test.cpp'), timeout: 30)
+endif
diff --git a/plugins/open-here/open-here.xml b/plugins/open-here/open-here.xml
new file mode 100644
index 0000000..96f0b43
--- /dev/null
+++ b/plugins/open-here/open-here.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<wayfire>
+  <plugin name="open-here">
+    <_short>Open Here</_short>
+    <_long>New windows open on the monitor you're working on, the one under the pointer, at the size their app had when its last window closed. Dialogs stay over their parent, and fixed-size windows and windows that open maximized or fullscreen keep their own size. Remembered sizes are kept in ~/.local/state/wayfire/window-sizes.</_long>
+    <category>Window Management</category>
+    <option name="follow_pointer" type="bool">
+      <_short>Open windows on the monitor under the pointer</_short>
+      <_long>Without a pointer, the monitor of the focused window. A window rule or core/default_output that names a monitor wins.</_long>
+      <default>true</default>
+    </option>
+    <option name="remember_size" type="bool">
+      <_short>Open apps at their last size</_short>
+      <_long>Per app, the size its last window had when it closed. An app that sizes or restores its own windows is left alone.</_long>
+      <default>true</default>
+    </option>
+  </plugin>
+</wayfire>
diff --git a/plugins/open-here/src/placement.hpp b/plugins/open-here/src/placement.hpp
new file mode 100644
index 0000000..8c23157
--- /dev/null
+++ b/plugins/open-here/src/placement.hpp
@@ -0,0 +1,406 @@
+// Where a new window opens and at what size, and the small file of remembered
+// sizes. Display-free, so the unit test covers it.
+#pragma once
+#include <algorithm>
+#include <cerrno>
+#include <cmath>
+#include <cstdlib>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+namespace open_here
+{
+struct rect_t
+{
+    double x = 0, y = 0, width = 0, height = 0;
+};
+
+struct point_t
+{
+    double x = 0, y = 0;
+};
+
+struct dims_t
+{
+    int width = 0, height = 0;
+    bool empty() const { return width <= 0 || height <= 0; }
+};
+
+struct margins_t
+{
+    int left = 0, right = 0, top = 0, bottom = 0;
+};
+
+constexpr int max_side = 32767;
+constexpr size_t max_apps = 100;
+constexpr size_t max_file = 64 * 1024;
+
+// The key sizes are remembered under: the app id without a per-instance
+// suffix ("org.wayfire.Files.s1a2b3" -> "org.wayfire.Files"), as GApplication
+// ids made unique per session look. Empty when the id can't be a key (empty,
+// too long, or with spaces or control characters).
+inline std::string app_key(const std::string& app_id)
+{
+    if (app_id.empty() || app_id.size() > 255)
+    {
+        return "";
+    }
+
+    for (unsigned char c : app_id)
+    {
+        if (c <= ' ' || c == 0x7f)
+        {
+            return "";
+        }
+    }
+
+    // An "s" and hex digits with at least one digit, after at least two parts.
+    auto dot = app_id.rfind('.');
+    if ((dot == std::string::npos) || (app_id.find('.') == dot))
+    {
+        return app_id;
+    }
+
+    auto last = app_id.substr(dot + 1);
+    bool suffix = last.size() >= 2 && last[0] == 's' &&
+        last.find_first_not_of("0123456789abcdef", 1) == std::string::npos &&
+        last.find_first_of("0123456789") != std::string::npos;
+    return suffix ? app_id.substr(0, dot) : app_id;
+}
+
+inline bool contains(const rect_t& r, point_t p)
+{
+    return p.x >= r.x && p.x < r.x + r.width && p.y >= r.y && p.y < r.y + r.height;
+}
+
+inline double overlap(const rect_t& a, const rect_t& b)
+{
+    double w = std::min(a.x + a.width, b.x + b.width) - std::max(a.x, b.x);
+    double h = std::min(a.y + a.height, b.y + b.height) - std::max(a.y, b.y);
+    return (w > 0 && h > 0) ? w * h : 0;
+}
+
+inline double distance(const rect_t& r, point_t p)
+{
+    double x = std::clamp(p.x, r.x, r.x + r.width), y = std::clamp(p.y, r.y, r.y + r.height);
+    return std::hypot(p.x - x, p.y - y);
+}
+
+// The monitor you're working on: the one under the pointer, else the one
+// holding most of the focused window, else the one nearest the pointer. -1
+// when there is nothing to go by.
+inline int choose_monitor(const std::vector<rect_t>& monitors, std::optional<point_t> pointer,
+    std::optional<rect_t> focused)
+{
+    int best = -1;
+    if (pointer)
+    {
+        for (size_t i = 0; i < monitors.size(); i++)
+        {
+            if (contains(monitors[i], *pointer))
+            {
+                return i;
+            }
+        }
+    }
+
+    if (focused)
+    {
+        double most = 0;
+        for (size_t i = 0; i < monitors.size(); i++)
+        {
+            if (overlap(monitors[i], *focused) > most)
+            {
+                most = overlap(monitors[i], *focused);
+                best = i;
+            }
+        }
+
+        if (best >= 0)
+        {
+            return best;
+        }
+    }
+
+    std::optional<point_t> from = pointer;
+    if (!from && focused)
+    {
+        from = point_t{focused->x + focused->width / 2, focused->y + focused->height / 2};
+    }
+
+    double nearest = INFINITY;
+    for (size_t i = 0; from && i < monitors.size(); i++)
+    {
+        if (distance(monitors[i], *from) < nearest)
+        {
+            nearest = distance(monitors[i], *from);
+            best = i;
+        }
+    }
+
+    return best;
+}
+
+struct entry_t
+{
+    std::string key;
+    dims_t last;    // content size when its last window closed; empty if none yet
+    dims_t natural; // the size the app itself last opened at
+};
+
+inline bool near(dims_t a, dims_t b)
+{
+    return std::abs(a.width - b.width) <= 2 && std::abs(a.height - b.height) <= 2;
+}
+
+// The size to give a window that opened at `natural`: the remembered size, but
+// only when the app opened at its usual size. An app that comes back at the
+// remembered size, or picks a new size of its own, restores its own geometry
+// or sizes to its content, and is left alone.
+inline std::optional<dims_t> remembered_size(const entry_t *entry, dims_t natural)
+{
+    if (!entry || entry->last.empty() || natural.empty() || near(natural, entry->last) ||
+        !near(natural, entry->natural))
+    {
+        return {};
+    }
+
+    return entry->last;
+}
+
+// The window's box for content of `size` with decoration `margins`: within
+// the app's size limits (0 = none) and the work area, keeping the centre where
+// placement put it (or the top-left corner, for cascading), inside the area.
+inline rect_t fit(const rect_t& placed, dims_t size, margins_t margins, const rect_t& area, dims_t min,
+    dims_t max, bool keep_corner)
+{
+    double w = size.width, h = size.height;
+    w = std::max<double>(w, min.width);
+    h = std::max<double>(h, min.height);
+    if (max.width > 0)
+    {
+        w = std::min<double>(w, max.width);
+    }
+
+    if (max.height > 0)
+    {
+        h = std::min<double>(h, max.height);
+    }
+
+    w = std::floor(std::min(w + margins.left + margins.right, area.width));
+    h = std::floor(std::min(h + margins.top + margins.bottom, area.height));
+    double x = keep_corner ? placed.x : std::round(placed.x + (placed.width - w) / 2);
+    double y = keep_corner ? placed.y : std::round(placed.y + (placed.height - h) / 2);
+    x = std::clamp(x, area.x, std::max(area.x, area.x + area.width - w));
+    y = std::clamp(y, area.y, std::max(area.y, area.y + area.height - h));
+    return {x, y, w, h};
+}
+
+// Remembered sizes, most recently used first, at most max_apps.
+class store_t
+{
+    std::vector<entry_t> entries;
+
+    entry_t& front(const std::string& key)
+    {
+        auto it = std::find_if(entries.begin(), entries.end(), [&] (auto& e) { return e.key == key; });
+        entry_t entry = it == entries.end() ? entry_t{key, {}, {}} : *it;
+        if (it != entries.end())
+        {
+            entries.erase(it);
+        }
+
+        entries.insert(entries.begin(), entry);
+        if (entries.size() > max_apps)
+        {
+            entries.resize(max_apps);
+        }
+
+        return entries.front();
+    }
+
+    static dims_t bounded(dims_t d)
+    {
+        return d.empty() ? dims_t{} : dims_t{std::min(d.width, max_side), std::min(d.height, max_side)};
+    }
+
+  public:
+    const entry_t *find(const std::string& key) const
+    {
+        auto it = std::find_if(entries.begin(), entries.end(), [&] (auto& e) { return e.key == key; });
+        return it == entries.end() ? nullptr : &*it;
+    }
+
+    size_t size() const { return entries.size(); }
+
+    // A window of the app opened at this size of its own choosing.
+    void opened(const std::string& key, dims_t natural)
+    {
+        if (!key.empty() && !natural.empty())
+        {
+            front(key).natural = bounded(natural);
+        }
+    }
+
+    // The app's window closed at this size.
+    void closed(const std::string& key, dims_t last)
+    {
+        if (!key.empty() && !last.empty())
+        {
+            front(key).last = bounded(last);
+        }
+    }
+
+    std::string serialize() const
+    {
+        std::ostringstream out;
+        out << "# Window sizes remembered by Wayfire's open-here plugin: app id, width and height when\n"
+               "# its last window closed, and the size the app opens at by itself. Safe to delete.\n";
+        for (auto& e : entries)
+        {
+            out << e.key << '\t' << e.last.width << '\t' << e.last.height << '\t' << e.natural.width <<
+                '\t' << e.natural.height << '\n';
+        }
+
+        return out.str();
+    }
+
+    // Skips anything malformed; keeps the first max_apps entries.
+    static store_t parse(const std::string& text)
+    {
+        store_t store;
+        std::istringstream lines(text.substr(0, max_file));
+        std::string line;
+        while (std::getline(lines, line) && store.entries.size() < max_apps)
+        {
+            if (line.empty() || line[0] == '#')
+            {
+                continue;
+            }
+
+            std::istringstream fields(line);
+            std::string key, rest;
+            long n[4];
+            if (!std::getline(fields, key, '\t') || (app_key(key) != key) || key.empty() ||
+                !(fields >> n[0] >> n[1] >> n[2] >> n[3]) || (fields >> rest) || store.find(key))
+            {
+                continue;
+            }
+
+            bool ok = true;
+            for (long v : n)
+            {
+                ok &= v >= 0 && v <= max_side;
+            }
+
+            if (ok)
+            {
+                store.entries.push_back({key, bounded({int(n[0]), int(n[1])}), bounded({int(n[2]), int(n[3])})});
+            }
+        }
+
+        return store;
+    }
+};
+
+// $XDG_STATE_HOME/wayfire/window-sizes, or under ~/.local/state; empty if
+// neither is an absolute path.
+inline std::string state_path(const char *state_home, const char *home)
+{
+    if (state_home && state_home[0] == '/')
+    {
+        return std::string(state_home) + "/wayfire/window-sizes";
+    }
+
+    if (home && home[0] == '/')
+    {
+        return std::string(home) + "/.local/state/wayfire/window-sizes";
+    }
+
+    return "";
+}
+
+// At most `limit` bytes of a regular file; empty if missing or unreadable.
+inline std::string read_bounded(const std::string& path, size_t limit = max_file)
+{
+    std::string text;
+    int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
+    struct stat st;
+    if (fd < 0)
+    {
+        return text;
+    }
+
+    if ((fstat(fd, &st) == 0) && S_ISREG(st.st_mode))
+    {
+        char buf[4096];
+        ssize_t n;
+        while (text.size() < limit && (n = read(fd, buf, std::min(sizeof(buf), limit - text.size()))) > 0)
+        {
+            text.append(buf, n);
+        }
+    }
+
+    close(fd);
+    return text;
+}
+
+// Makes the missing directories of `dir` (mode 0700).
+inline bool make_dirs(const std::string& dir)
+{
+    for (size_t at = 1; at <= dir.size(); at++)
+    {
+        if ((at == dir.size()) || (dir[at] == '/'))
+        {
+            auto part = dir.substr(0, at);
+            if ((mkdir(part.c_str(), 0700) != 0) && (errno != EEXIST))
+            {
+                return false;
+            }
+        }
+    }
+
+    return true;
+}
+
+// Replaces `path` with `text` atomically (temporary file, fsync, rename),
+// readable only by the owner.
+inline bool write_atomic(const std::string& path, const std::string& text)
+{
+    auto slash = path.rfind('/');
+    if ((slash == std::string::npos) || !make_dirs(path.substr(0, slash)))
+    {
+        return false;
+    }
+
+    std::string tmp = path + ".XXXXXX";
+    int fd = mkostemp(tmp.data(), O_CLOEXEC);
+    if (fd < 0)
+    {
+        return false;
+    }
+
+    bool ok = fchmod(fd, 0600) == 0;
+    for (size_t done = 0; ok && done < text.size();)
+    {
+        ssize_t n = write(fd, text.data() + done, text.size() - done);
+        ok = n > 0 || (n < 0 && errno == EINTR);
+        done += n > 0 ? n : 0;
+    }
+
+    ok = (fsync(fd) == 0) && ok;
+    ok = (close(fd) == 0) && ok;
+    ok = ok && (rename(tmp.c_str(), path.c_str()) == 0);
+    if (!ok)
+    {
+        unlink(tmp.c_str());
+    }
+
+    return ok;
+}
+}
diff --git a/plugins/open-here/src/plugin.cpp b/plugins/open-here/src/plugin.cpp
new file mode 100644
index 0000000..9dbc9c2
--- /dev/null
+++ b/plugins/open-here/src/plugin.cpp
@@ -0,0 +1,392 @@
+// open-here: a new window opens on the monitor you're working on (under the
+// pointer, else where the focused window is), at the size its app had when its
+// last window closed. Dialogs, fixed-size windows and windows that ask to be
+// maximized or fullscreen are left alone. Sizes live in
+// $XDG_STATE_HOME/wayfire/window-sizes, written off the main thread.
+#include "placement.hpp"
+#include <wayfire/core.hpp>
+#include <wayfire/option-wrapper.hpp>
+#include <wayfire/output.hpp>
+#include <wayfire/output-layout.hpp>
+#include <wayfire/output-stitch.hpp>
+#include <wayfire/plugin.hpp>
+#include <wayfire/seat.hpp>
+#include <wayfire/signal-definitions.hpp>
+#include <wayfire/toplevel-view.hpp>
+#include <wayfire/util.hpp>
+#include <wayfire/window-scope.hpp>
+#include <wayfire/config/config-manager.hpp>
+#include <wayfire/txn/transaction-manager.hpp>
+// For view_pre_map_signal; the header names this type without the generated
+// protocol header that declares it.
+struct wlr_xdg_surface;
+#include <wayfire/unstable/wlr-view-events.hpp>
+#include <atomic>
+#include <condition_variable>
+#include <mutex>
+#include <thread>
+
+namespace
+{
+using namespace open_here;
+
+// Writes the newest text it was given, one file write at a time.
+class writer_t
+{
+    std::string path;
+    std::mutex mutex;
+    std::condition_variable wake;
+    std::optional<std::string> next;
+    bool done = false;
+    std::thread thread;
+
+    void run()
+    {
+        std::unique_lock lock(mutex);
+        while (true)
+        {
+            wake.wait(lock, [&] { return done || next; });
+            if (!next)
+            {
+                return;
+            }
+
+            auto text = std::move(*next);
+            next.reset();
+            lock.unlock();
+            if (!write_atomic(path, text))
+            {
+                failed = true;
+            }
+
+            lock.lock();
+        }
+    }
+
+  public:
+    std::atomic<bool> failed{false};
+
+    explicit writer_t(std::string path) : path(std::move(path)), thread([this] { run(); })
+    {}
+
+    void submit(std::string text)
+    {
+        {
+            std::lock_guard lock(mutex);
+            next = std::move(text);
+        }
+
+        wake.notify_one();
+    }
+
+    // Finishes the pending write first.
+    ~writer_t()
+    {
+        {
+            std::lock_guard lock(mutex);
+            done = true;
+        }
+
+        wake.notify_one();
+        thread.join();
+    }
+};
+
+struct tracked_t : public wf::custom_data_t
+{
+    std::string key;
+    dims_t floating; // content size the last time it was neither tiled nor fullscreen
+};
+
+std::string config_value(const std::string& name)
+{
+    auto option = wf::get_core().config->get_option(name);
+    return option ? option->get_value_str() : "";
+}
+
+rect_t rect(wf::geometry_t g)
+{
+    return {g.x, g.y, g.width, g.height};
+}
+
+dims_t content(wf::geometry_t g, const wf::decoration_margins_t& m)
+{
+    auto c = wf::shrink_geometry_by_margins(g, m);
+    return {int(std::lround(c.width)), int(std::lround(c.height))};
+}
+
+bool fixed_size(wayfire_toplevel_view view)
+{
+    auto min = view->toplevel()->get_min_size(), max = view->toplevel()->get_max_size();
+    return max.width > 0 && max.height > 0 && min.width == max.width && min.height == max.height;
+}
+
+// Ordinary windows of an app: not dialogs or other transients, not menus or
+// panels, and not windows that place themselves.
+bool ordinary(wayfire_toplevel_view view)
+{
+    return view && (view->role == wf::VIEW_ROLE_TOPLEVEL) && !view->parent &&
+           !view->has_property("startup-x") && !view->has_property("startup-y");
+}
+
+bool has_other_window(wayfire_toplevel_view view, const std::string& key)
+{
+    for (auto& other : wf::get_core().get_all_views())
+    {
+        auto tracked = other->get_data<tracked_t>();
+        if ((other != view) && tracked && (tracked->key == key) && other->is_mapped())
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+class open_here_plugin_t : public wf::plugin_interface_t
+{
+    wf::option_wrapper_t<bool> follow_pointer{"open-here/follow_pointer"};
+    wf::option_wrapper_t<bool> remember_size{"open-here/remember_size"};
+    store_t store;
+    std::string path;
+    std::unique_ptr<writer_t> writer;
+    bool dirty = false;
+    wf::wl_timer<false> save_timer;
+
+    void changed()
+    {
+        dirty = true;
+        if (writer && !save_timer.is_connected())
+        {
+            save_timer.set_timeout(1000, [this] { save(); });
+        }
+    }
+
+    void save()
+    {
+        if (writer && dirty)
+        {
+            if (writer->failed.exchange(false))
+            {
+                LOGW("open-here: could not save window sizes to ", path);
+            }
+
+            writer->submit(store.serialize());
+            dirty = false;
+        }
+    }
+
+    // Before a window maps: move it to the monitor you're working on, so the
+    // place plugin centres it there.
+    wf::signal::connection_t<wf::view_pre_map_signal> on_pre_map = [=] (wf::view_pre_map_signal *ev)
+    {
+        auto view = wf::toplevel_cast(wayfire_view{ev->view});
+        if (!follow_pointer || !ordinary(view) || !view->get_output())
+        {
+            return;
+        }
+
+        // An app rule that names a monitor wins; with the combined desktop
+        // scope, a stitched output counts as one monitor.
+        auto scope = wf::window_scope_policy(view);
+        if ((scope != "physical") && (scope != "virtual"))
+        {
+            return;
+        }
+
+        // An explicit core/default_output wins.
+        auto& core = wf::get_core();
+        auto fixed_output = config_value("core/default_output");
+        if (!fixed_output.empty() && core.output_layout->find_output(fixed_output))
+        {
+            return;
+        }
+
+        struct monitor_t
+        {
+            wf::output_t *output;
+            std::string zone;
+        };
+        std::vector<monitor_t> monitors;
+        std::vector<rect_t> areas;
+        for (auto output : core.output_layout->get_outputs())
+        {
+            auto box = output->get_layout_geometry();
+            auto stitch = output->get_data<wf::output_stitch_layout_t>();
+            if (!stitch || stitch->zones.empty() || (scope == "virtual"))
+            {
+                monitors.push_back({output, ""});
+                areas.push_back(rect(box));
+                continue;
+            }
+
+            for (auto& zone : stitch->zones)
+            {
+                monitors.push_back({output, zone.name});
+                areas.push_back({box.x + zone.geometry.x, box.y + zone.geometry.y, zone.geometry.width,
+                    zone.geometry.height});
+            }
+        }
+
+        std::optional<point_t> pointer;
+        if (core.get_current_seat()->capabilities & WL_SEAT_CAPABILITY_POINTER)
+        {
+            auto p = core.get_cursor_position();
+            pointer = point_t{p.x, p.y};
+        }
+
+        std::optional<rect_t> focused;
+        auto active = wf::toplevel_cast(core.seat->get_active_view());
+        if (active && (active != view) && active->is_mapped() && active->get_output())
+        {
+            auto g = active->get_geometry();
+            auto origin = active->get_output()->get_layout_geometry();
+            focused = rect_t{g.x + origin.x, g.y + origin.y, g.width, g.height};
+        }
+
+        int chosen = choose_monitor(areas, pointer, focused);
+        if (chosen < 0)
+        {
+            return;
+        }
+
+        auto& target = monitors[chosen];
+        if (view->get_output() != target.output)
+        {
+            view->set_output(target.output);
+        }
+
+        if (!target.zone.empty())
+        {
+            wf::select_window_scope_monitor(view, target.zone);
+        }
+    };
+
+    // As a window maps (after decorations and the place plugin): give it the
+    // size its app had last time, if the app opened at its usual size.
+    wf::signal::connection_t<wf::txn::new_transaction_signal> on_new_tx = [=] (wf::txn::new_transaction_signal *ev)
+    {
+        for (const auto& object : ev->tx->get_objects())
+        {
+            auto toplevel = std::dynamic_pointer_cast<wf::toplevel_t>(object);
+            if (!toplevel || toplevel->current().mapped || !toplevel->pending().mapped)
+            {
+                continue;
+            }
+
+            auto view = wf::find_view_for_toplevel(toplevel);
+            auto key  = view ? app_key(view->get_app_id()) : "";
+            if (!remember_size || !ordinary(view) || key.empty() || !view->get_output())
+            {
+                continue;
+            }
+
+            // A window that opens maximized or fullscreen has no size of its
+            // own until it is restored.
+            auto& pending = toplevel->pending();
+            auto natural  = content(pending.geometry, pending.margins);
+            bool tiled    = pending.fullscreen || pending.tiled_edges;
+            auto tracked  = view->get_data_safe<tracked_t>();
+            tracked->key  = key;
+            tracked->floating = tiled ? dims_t{} : natural;
+            if (fixed_size(view) || tiled)
+            {
+                continue;
+            }
+
+            // The app's usual size is that of its first window; later ones
+            // (a second window, a parentless tool window) don't change it.
+            auto size = remembered_size(store.find(key), natural);
+            if (!has_other_window(view, key))
+            {
+                store.opened(key, natural);
+                changed();
+            }
+
+            if (!size)
+            {
+                continue;
+            }
+
+            auto min = toplevel->get_min_size(), max = toplevel->get_max_size();
+            const auto& m = pending.margins;
+            auto box = fit(rect(pending.geometry), *size,
+                {int(m.left), int(m.right), int(m.top), int(m.bottom)}, rect(wf::window_scope_workarea(view)),
+                {min.width, min.height}, {max.width, max.height}, config_value("place/mode") == "cascade");
+            pending.geometry = {box.x, box.y, box.width, box.height};
+            tracked->floating = content(pending.geometry, pending.margins);
+        }
+    };
+
+    wf::signal::connection_t<wf::view_geometry_changed_signal> on_geometry = [=] (wf::view_geometry_changed_signal *ev)
+    {
+        auto tracked = ev->view ? ev->view->get_data<tracked_t>() : nullptr;
+        if (!tracked || !ev->view->is_mapped())
+        {
+            return;
+        }
+
+        auto& state = ev->view->toplevel()->current();
+        if (!state.tiled_edges && !state.fullscreen)
+        {
+            tracked->floating = content(state.geometry, state.margins);
+        }
+    };
+
+    wf::signal::connection_t<wf::view_pre_unmap_signal> on_pre_unmap = [=] (wf::view_pre_unmap_signal *ev)
+    {
+        auto view    = wf::toplevel_cast(ev->view);
+        auto tracked = view ? view->get_data<tracked_t>() : nullptr;
+        if (!tracked)
+        {
+            return;
+        }
+
+        auto& state = view->toplevel()->current();
+        auto size   = (state.tiled_edges || state.fullscreen) ? tracked->floating : content(state.geometry, state.margins);
+        // store.closed() ignores an empty size: never restored from maximized.
+        if (remember_size && ordinary(view) && !fixed_size(view))
+        {
+            store.closed(tracked->key, size);
+            changed();
+        }
+
+        view->erase_data<tracked_t>();
+    };
+
+  public:
+    // After the decoration and place plugins, so a map sees their result.
+    int get_order_hint() const override { return 100; }
+
+    void init() override
+    {
+        path = state_path(getenv("XDG_STATE_HOME"), getenv("HOME"));
+        if (!path.empty())
+        {
+            store  = store_t::parse(read_bounded(path));
+            writer = std::make_unique<writer_t>(path);
+        }
+
+        auto& core = wf::get_core();
+        core.connect(&on_pre_map);
+        core.tx_manager->connect(&on_new_tx);
+        core.connect(&on_geometry);
+        core.connect(&on_pre_unmap);
+    }
+
+    void fini() override
+    {
+        // The data's code goes away with the plugin.
+        for (auto& view : wf::get_core().get_all_views())
+        {
+            view->erase_data<tracked_t>();
+        }
+
+        save_timer.disconnect();
+        save();
+        writer.reset();
+    }
+};
+}
+
+DECLARE_WAYFIRE_PLUGIN(open_here_plugin_t);
diff --git a/plugins/open-here/tests/placement-test.cpp b/plugins/open-here/tests/placement-test.cpp
new file mode 100644
index 0000000..f037b52
--- /dev/null
+++ b/plugins/open-here/tests/placement-test.cpp
@@ -0,0 +1,150 @@
+// Unit test: app keys, monitor choice, the remembered-size decision, fitting
+// into the work area, and the state file.
+#include "../src/placement.hpp"
+#include <cstdio>
+#include <cstring>
+#include <dirent.h>
+
+using namespace open_here;
+
+static int failures = 0;
+#define CHECK(cond) do { if (!(cond)) { std::printf("FAIL line %d: %s\n", __LINE__, #cond); failures++; } } while (0)
+
+static bool same(rect_t a, rect_t b)
+{
+    return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
+}
+
+int main()
+{
+    // Per-instance suffixes are dropped, nothing else.
+    CHECK(app_key("org.wayfire.Files.s123") == "org.wayfire.Files");
+    CHECK(app_key("org.wayfire.Files.s" + std::string(64, 'a').replace(10, 1, "7")) == "org.wayfire.Files");
+    CHECK(app_key("org.wayfire.Files.Jobs.s1a2b3c4") == "org.wayfire.Files.Jobs");
+    CHECK(app_key("org.wayfire.Files") == "org.wayfire.Files");
+    CHECK(app_key("org.gnome.Settings") == "org.gnome.Settings");
+    CHECK(app_key("org.example.sadface") == "org.example.sadface"); // hex letters, no digit
+    CHECK(app_key("org.example.s") == "org.example.s");
+    CHECK(app_key("example.s12") == "example.s12"); // only two parts
+    CHECK(app_key("firefox") == "firefox");
+    CHECK(app_key("Alacritty") == "Alacritty");
+    CHECK(app_key("") == "");
+    CHECK(app_key("has space") == "");
+    CHECK(app_key("tab\tid") == "");
+    CHECK(app_key(std::string(256, 'a')) == "");
+
+    // Three monitors side by side, as when stitched.
+    std::vector<rect_t> three = {{0, 0, 1280, 720}, {1280, 0, 1280, 720}, {2560, 0, 1280, 720}};
+    CHECK(choose_monitor(three, point_t{3000, 300}, rect_t{100, 100, 400, 300}) == 2); // pointer wins
+    CHECK(choose_monitor(three, point_t{1280, 0}, {}) == 1);                           // left edge belongs
+    CHECK(choose_monitor(three, {}, rect_t{1200, 100, 400, 300}) == 1);                 // most of the window
+    CHECK(choose_monitor(three, point_t{-50, 300}, rect_t{2600, 0, 100, 100}) == 2);   // off-screen pointer
+    CHECK(choose_monitor(three, point_t{5000, 300}, {}) == 2);                          // nearest
+    CHECK(choose_monitor(three, {}, rect_t{-900, 0, 100, 100}) == 0);                   // window off-screen
+    CHECK(choose_monitor(three, {}, {}) == -1);
+    CHECK(choose_monitor({}, point_t{0, 0}, {}) == -1);
+
+    // The remembered size applies only when the app opened at its usual size.
+    entry_t files{"org.wayfire.Files", {900, 560}, {360, 200}};
+    CHECK(!remembered_size(nullptr, {360, 200}));
+    CHECK(remembered_size(&files, {360, 200})->width == 900);
+    CHECK(remembered_size(&files, {361, 199})->height == 560); // rounding
+    CHECK(!remembered_size(&files, {900, 560}));               // the app restored it itself
+    CHECK(!remembered_size(&files, {500, 300}));               // the app chose another size
+    entry_t fresh{"x", {}, {360, 200}};
+    CHECK(!remembered_size(&fresh, {360, 200}));
+    CHECK(!remembered_size(&files, {0, 0}));
+
+    // Fitting: centre kept, decorations added, limited to the work area.
+    rect_t area{1280, 38, 1280, 682};
+    rect_t placed{1740, 279, 360, 200};
+    CHECK(same(fit(placed, {900, 560}, {}, area, {}, {}, false), rect_t{1470, 99, 900, 560}));
+    CHECK(same(fit(placed, {900, 560}, {4, 4, 30, 4}, area, {}, {}, false), rect_t{1466, 82, 908, 594}));
+    CHECK(same(fit(placed, {3000, 3000}, {}, area, {}, {}, false), area));            // too big: the area
+    CHECK(same(fit(placed, {900, 560}, {}, area, {}, {}, true), rect_t{1660, 160, 900, 560})); // cascade: corner,
+    CHECK(same(fit(placed, {900, 560}, {}, area, {}, {700, 400}, false), rect_t{1570, 179, 700, 400})); // max
+    CHECK(same(fit(placed, {100, 50}, {}, area, {200, 100}, {}, false), rect_t{1820, 329, 200, 100}));  // min
+    CHECK(same(fit({2500, 600, 100, 100}, {400, 300}, {}, area, {}, {}, false), rect_t{2160, 420, 400, 300}));
+
+    // The store: most recent first, bounded, survives a round trip.
+    store_t store;
+    store.opened("org.wayfire.Files", {360, 200});
+    store.closed("org.wayfire.Files", {900, 560});
+    store.opened("", {1, 1});
+    store.closed("foot", {0, 0});
+    CHECK(store.size() == 1);
+    for (int i = 0; i < 150; i++)
+    {
+        store.closed("app" + std::to_string(i), {100 + i, 100});
+    }
+
+    CHECK(store.size() == max_apps);
+    CHECK(!store.find("org.wayfire.Files") && store.find("app149") && !store.find("app49"));
+    store.opened("app50", {300, 200});
+    auto text = store.serialize();
+    auto back = store_t::parse(text);
+    CHECK(back.serialize() == text);
+    CHECK(back.find("app50")->natural.width == 300 && back.find("app50")->last.width == 150);
+    CHECK(text.find("app50\t150\t100\t300\t200\n") != std::string::npos);
+    CHECK(text.find("app50") < text.find("app149")); // app50 now first
+
+    // Corrupt input: bad lines are skipped, good ones kept.
+    auto messy = store_t::parse(std::string("garbage\n\0\x01\n", 11) + "a.b\t1\t2\t3\t4\n" +
+        "neg\t-1\t2\t3\t4\nbig\t99999\t2\t3\t4\nextra\t1\t2\t3\t4\t5\nshort\t1\t2\n" +
+        "has space\t1\t2\t3\t4\na.b\t9\t9\t9\t9\nlast\t0\t0\t5\t6");
+    CHECK(messy.size() == 2 && messy.find("a.b")->last.width == 1 && messy.find("last")->natural.height == 6);
+    CHECK(store_t::parse("").size() == 0);
+    std::string huge;
+    for (int i = 0; i < 5000; i++)
+    {
+        huge += "app" + std::to_string(i) + "\t1\t1\t1\t1\n";
+    }
+
+    CHECK(store_t::parse(huge).size() == max_apps);
+
+    // Paths.
+    CHECK(state_path("/s", "/h") == "/s/wayfire/window-sizes");
+    CHECK(state_path("relative", "/h") == "/h/.local/state/wayfire/window-sizes");
+    CHECK(state_path(nullptr, nullptr).empty());
+
+    // The file: created with its directories, 0600, replaced whole, bounded on read.
+    auto base = std::string(getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") + "/open-here-test-XXXXXX";
+    char *dir = base.data();
+    CHECK(mkdtemp(dir));
+    auto file = std::string(dir) + "/state/wayfire/window-sizes";
+    CHECK(read_bounded(file).empty());
+    CHECK(write_atomic(file, text));
+    struct stat st;
+    CHECK(stat(file.c_str(), &st) == 0 && (st.st_mode & 0777) == 0600);
+    CHECK(read_bounded(file) == text);
+    CHECK(write_atomic(file, "short\n") && read_bounded(file) == "short\n");
+    CHECK(read_bounded(file, 3) == "sho");
+    CHECK(write_atomic(file, huge) && read_bounded(file).size() == max_file);
+    int leftovers = 0;
+    if (DIR *d = opendir((std::string(dir) + "/state/wayfire").c_str()))
+    {
+        while (auto *e = readdir(d))
+        {
+            leftovers += e->d_name[0] != '.' && std::strcmp(e->d_name, "window-sizes") != 0;
+        }
+
+        closedir(d);
+    }
+
+    CHECK(leftovers == 0);
+    CHECK(!write_atomic(std::string(dir) + "/state/wayfire/window-sizes/inside", "x")); // parent is a file
+    CHECK(read_bounded(dir).empty());                                                     // a directory
+    unlink(file.c_str());
+    rmdir((std::string(dir) + "/state/wayfire").c_str());
+    rmdir((std::string(dir) + "/state").c_str());
+    rmdir(dir);
+
+    if (failures)
+    {
+        std::printf("%d failures\n", failures);
+        return 1;
+    }
+
+    std::printf("open-here placement: all checks passed\n");
+    return 0;
+}