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 @@
+
+
+
+ <_short>Open Here
+ <_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.
+ Window Management
+
+
+
+
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
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+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& monitors, std::optional pointer,
+ std::optional 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 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 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(w, min.width);
+ h = std::max(h, min.height);
+ if (max.width > 0)
+ {
+ w = std::min(w, max.width);
+ }
+
+ if (max.height > 0)
+ {
+ h = std::min(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 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
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+// For view_pre_map_signal; the header names this type without the generated
+// protocol header that declares it.
+struct wlr_xdg_surface;
+#include
+#include
+#include
+#include
+#include
+
+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 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 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();
+ 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 follow_pointer{"open-here/follow_pointer"};
+ wf::option_wrapper_t remember_size{"open-here/remember_size"};
+ store_t store;
+ std::string path;
+ std::unique_ptr writer;
+ bool dirty = false;
+ wf::wl_timer 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 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 monitors;
+ std::vector areas;
+ for (auto output : core.output_layout->get_outputs())
+ {
+ auto box = output->get_layout_geometry();
+ auto stitch = output->get_data();
+ 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 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 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 on_new_tx = [=] (wf::txn::new_transaction_signal *ev)
+ {
+ for (const auto& object : ev->tx->get_objects())
+ {
+ auto toplevel = std::dynamic_pointer_cast(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->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 on_geometry = [=] (wf::view_geometry_changed_signal *ev)
+ {
+ auto tracked = ev->view ? ev->view->get_data() : 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 on_pre_unmap = [=] (wf::view_pre_unmap_signal *ev)
+ {
+ auto view = wf::toplevel_cast(ev->view);
+ auto tracked = view ? view->get_data() : 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();
+ };
+
+ 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(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();
+ }
+
+ 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
+#include
+#include
+
+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 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;
+}