Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

added drag files to trash can in redi files

oxydizer1a3d40967012
diff --git a/src/files/AGENTS.md b/src/files/AGENTS.md
index 9c9c0e9..33afa0a 100644
--- a/src/files/AGENTS.md
+++ b/src/files/AGENTS.md
@@ -220,6 +220,10 @@ control bytes are refused because terminal paste would alter them.
state; reject a folder dropped into itself or a descendant, including
through symlinks. Pins take their gap from `pin_drop`.
* Ctrl-click deselection waits for release so Ctrl-drag keeps the selection.
+* The sidebar's Trash row (`trashDropAt`, `trash_drop` outline) takes
+ *move* only, like the dock's Trash: `trashDropped` runs `ops.trashItems`
+ with no dialog and skips what is in the Trash already. Copy-only sources
+ (Files' Trash view, most browsers) are refused. `tests/files_drag.py --trash`.
## BitTorrent transfers
diff --git a/src/files/Client.zig b/src/files/Client.zig
index 6c676d2..12f8c8f 100644
--- a/src/files/Client.zig
+++ b/src/files/Client.zig
@@ -51,6 +51,7 @@ drop_offer: ?*Offer = null,
drop_receiving: ?transfer.Receive = null,
drop_slot: ?usize = null,
drop_terminal: bool = false,
+drop_trash: bool = false,
drop_move: bool = false,
clipboard_source: ?*ClipboardSource = null,
drag_source: ?*ClipboardSource = null,
diff --git a/src/files/app.zig b/src/files/app.zig
index 3edfd1a..8d94c95 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -155,6 +155,8 @@ pub const App = struct {
/// While a drag hovers PLACES: the gap, among the pins, where a drop lands.
pin_drop: ?usize = null,
folder_drop: ?usize = null,
+ /// While a drag hovers the sidebar's Trash row (a drop there trashes).
+ trash_drop: bool = false,
// Removable and external volumes (see volumes.zig), listed under DEVICES.
// The monitor starts once the window exists; without it the list is empty.
@@ -592,6 +594,10 @@ pub const App = struct {
pub const refreshTrashRestorable = app_trash.refreshTrashRestorable;
pub const restoreSelected = app_trash.restoreSelected;
pub const restoreAll = app_trash.restoreAll;
+ pub const trashDropAt = app_trash.trashDropAt;
+ pub const setTrashDrop = app_trash.setTrashDrop;
+ pub const takeTrashDrop = app_trash.takeTrashDrop;
+ pub const trashDropped = app_trash.trashDropped;
// app_chooser.zig
pub const configureChooser = app_chooser.configureChooser;
@@ -689,6 +695,8 @@ pub const App = struct {
pub const place_labels = [_]i18n.Message{ i18n.msg("Home"), i18n.msg("Trash"), i18n.msg("Recent"), i18n.msg("Desktop"), i18n.msg("Documents"), i18n.msg("Downloads"), i18n.msg("Pictures"), i18n.msg("Music"), i18n.msg("Videos"), i18n.msg("Projects") };
pub const places_start = 3;
+ /// The built-in Trash row's index among the places.
+ pub const trash_place = 1;
/// Where the pins start: the built-in places come first.
pub const pin_base = places.len;
diff --git a/src/files/app_places.zig b/src/files/app_places.zig
index 27d9297..e524871 100644
--- a/src/files/app_places.zig
+++ b/src/files/app_places.zig
@@ -277,6 +277,7 @@ pub fn highlightDrop(self: *App, x: f64, y: f64, accepted: bool) void {
pub fn dropLeave(self: *App) void {
self.highlightDrop(0, 0, false);
self.setPinDrop(null);
+ self.setTrashDrop(false);
}
/// The drop happened: the gap it chose, with the line gone.
diff --git a/src/files/app_sidebar_paint.zig b/src/files/app_sidebar_paint.zig
index c4da993..5dd967d 100644
--- a/src/files/app_sidebar_paint.zig
+++ b/src/files/app_sidebar_paint.zig
@@ -220,6 +220,14 @@ pub fn renderSidebar(self: *App, cr: *c.cairo_t) void {
}
self.renderDevices(cr, content_width);
self.renderPinDrop(cr);
+ if (self.trash_drop) {
+ // The drop target outline, as on a folder in the content area.
+ const row = self.placeRect(App.trash_place);
+ roundedRect(cr, row.x, row.y, row.w, row.h, 6);
+ setSource(cr, ui_theme.shellPalette().accent);
+ c.cairo_set_line_width(cr, 2);
+ c.cairo_stroke(cr);
+ }
}
/// The line a drag shows between pins: where a drop would put its pin.
diff --git a/src/files/app_sidebar_tests.zig b/src/files/app_sidebar_tests.zig
index eafa973..bac8b2f 100644
--- a/src/files/app_sidebar_tests.zig
+++ b/src/files/app_sidebar_tests.zig
@@ -188,6 +188,21 @@ test "pins sit after Projects, take drops by gap and keep the rows in drawn orde
try std.testing.expectEqual(@as(?usize, null), app.pin_drop);
try std.testing.expect(!app.dropMotion(400, desktop));
+ // The Trash row is a drop target of its own, above the pins' gaps.
+ const trash_row: f64 = @floatFromInt(app.placeY(App.trash_place) + 10);
+ try std.testing.expect(app.trashDropAt(70, trash_row));
+ try std.testing.expect(!app.trashDropAt(70, @floatFromInt(app.placeY(0) + 10)));
+ try std.testing.expect(!app.trashDropAt(70, desktop));
+ try std.testing.expectEqual(@as(?usize, null), app.pinSlotAt(70, trash_row));
+ app.dirty = false;
+ app.setTrashDrop(true);
+ try std.testing.expect(app.dirty);
+ try std.testing.expect(app.takeTrashDrop());
+ try std.testing.expect(!app.trash_drop);
+ app.setTrashDrop(true);
+ app.dropLeave();
+ try std.testing.expect(!app.trash_drop);
+
// Dropping on a gap inserts there; what is listed already, built in or
// gone is refused.
app.pinDropped(1, &.{"/etc"});
diff --git a/src/files/app_trash.zig b/src/files/app_trash.zig
index 069e687..c647448 100644
--- a/src/files/app_trash.zig
+++ b/src/files/app_trash.zig
@@ -6,6 +6,8 @@ const i18n = @import("i18n");
const tr = i18n.tr;
const App = @import("app.zig").App;
const trash = @import("trash.zig");
+const ops = @import("ops.zig");
+const header = @import("header.zig");
/// Where the current location lies relative to the home trash.
pub fn trashRelation(self: *const App) trash.Relation {
@@ -73,6 +75,54 @@ pub fn restoreAll(self: *App) void {
restore(self, view);
}
+/// Whether a drag at (`x`, `y`) is over the sidebar's Trash row, where a
+/// drop moves the items to the Trash at once, without the delete dialog.
+pub fn trashDropAt(self: *App, x: f64, y: f64) bool {
+ if (self.chooser != null or self.dialog != null or self.menu != null) return false;
+ return self.placeAt(x, y) == App.trash_place;
+}
+
+pub fn setTrashDrop(self: *App, on: bool) void {
+ if (self.trash_drop == on) return;
+ self.trash_drop = on;
+ const area: header.Rect = .{ .x = 0, .y = @floatFromInt(self.contentTop()), .w = @floatFromInt(self.sidebarWidth()), .h = @floatFromInt(self.h - self.contentTop() - self.sidebarFooter()) };
+ var row = self.placeRect(App.trash_place);
+ row.x -= 2;
+ row.y -= 2;
+ row.w += 4;
+ row.h += 4;
+ self.damageHighlight(area, row, null);
+}
+
+/// The drop happened: whether it was on the Trash row, with the outline gone.
+pub fn takeTrashDrop(self: *App) bool {
+ const on = self.trash_drop;
+ setTrashDrop(self, false);
+ return on;
+}
+
+/// Moves what was dropped on the Trash row to the Trash. What is in the
+/// Trash already stays where it is.
+pub fn trashDropped(self: *App, paths: []const []const u8) void {
+ var kept: std.ArrayList([]const u8) = .empty;
+ defer kept.deinit(self.allocator);
+ for (paths) |path| {
+ if (self.trash_dir) |dir| if (trash.relation(dir, path) != .none) continue;
+ kept.append(self.allocator, path) catch {
+ self.setStatusNotice(tr("Could not move all items to Trash"), true);
+ return;
+ };
+ }
+ if (kept.items.len == 0) return;
+ ops.trashItems(self.io, kept.items) catch |err| {
+ self.setStatusNotice(if (err == error.GioNotAvailable) tr("Trash unavailable (gio not installed)") else tr("Could not move all items to Trash"), true);
+ self.refresh();
+ return;
+ };
+ self.setStatusNotice(tr("Items moved to Trash"), false);
+ self.refresh();
+}
+
fn restore(self: *App, names: []const []const u8) void {
const summary = trash.restoreMany(self.allocator, self.trash_dir.?, names);
reportRestore(self, summary);
diff --git a/src/files/client_dnd.zig b/src/files/client_dnd.zig
index 8704519..f328e50 100644
--- a/src/files/client_dnd.zig
+++ b/src/files/client_dnd.zig
@@ -74,13 +74,19 @@ pub fn dragOver(self: *Client, x: f64, y: f64, entered: bool) void {
self.drag_x = x;
self.drag_y = y - @as(f64, @floatFromInt(self.titlebarHeight()));
const available = offer.uri and self.drop_receiving == null;
- const pin = available and self.app.dropMotion(x, self.drag_y);
- const terminal = available and !pin and self.app.terminalDropAt(x, self.drag_y);
- const folder = available and !pin and !terminal and self.app.dropDirectoryAt(x, self.drag_y) != null;
+ // The Trash row takes moves only, like the dock's Trash: a source that
+ // can only copy (Files' own Trash view among them) is refused.
+ const trash = available and offer.proxy.getVersion() >= 3 and self.app.trashDropAt(x, self.drag_y);
+ const trash_changed = trash != self.app.trash_drop;
+ self.app.setTrashDrop(trash);
+ const pin = available and !trash and self.app.dropMotion(x, self.drag_y);
+ if (trash) self.app.setPinDrop(null);
+ const terminal = available and !pin and !trash and self.app.terminalDropAt(x, self.drag_y);
+ const folder = available and !pin and !terminal and !trash and self.app.dropDirectoryAt(x, self.drag_y) != null;
self.app.highlightDrop(x, self.drag_y, folder);
- const wanted = pin or folder or terminal;
- const moving = folder and offer.files and !self.app.ctrl;
- if (!entered and wanted == self.drag_accepting and moving == self.drag_moving) return;
+ const wanted = pin or folder or terminal or trash;
+ const moving = trash or (folder and offer.files and !self.app.ctrl);
+ if (!entered and !trash_changed and wanted == self.drag_accepting and moving == self.drag_moving) return;
self.drag_accepting = wanted;
self.drag_moving = moving;
offer.proxy.accept(self.drag_enter_serial, if (wanted) "text/uri-list" else null);
@@ -88,7 +94,7 @@ pub fn dragOver(self: *Client, x: f64, y: f64, entered: bool) void {
// Files performs filesystem moves in the receiving job, never in
// the source's finished callback. Other sources, pins and terminal
// path insertion use copy only.
- offer.proxy.setActions(.{ .copy = wanted, .move = moving }, if (moving) .{ .move = true } else .{ .copy = wanted });
+ offer.proxy.setActions(.{ .copy = wanted and !trash, .move = moving }, if (moving) .{ .move = true } else .{ .copy = wanted });
}
}
@@ -98,16 +104,18 @@ pub fn dragDropped(self: *Client) void {
defer self.app.dropLeave();
const accepted = self.drag_accepting;
self.drag_accepting = false;
+ const trash = self.app.takeTrashDrop();
const slot = self.app.takePinDrop();
- const terminal = slot == null and self.app.terminalDropAt(self.drag_x, self.drag_y);
- const directory = if (slot != null or terminal) "" else self.app.dropDirectoryAt(self.drag_x, self.drag_y) orelse {
+ const terminal = !trash and slot == null and self.app.terminalDropAt(self.drag_x, self.drag_y);
+ const directory = if (trash or slot != null or terminal) "" else self.app.dropDirectoryAt(self.drag_x, self.drag_y) orelse {
self.discardOffer(offer);
return;
};
- if (!accepted or (offer.proxy.getVersion() >= 3 and !offer.action.copy and !offer.action.move)) {
+ if (!accepted or (offer.proxy.getVersion() >= 3 and !offer.action.copy and !offer.action.move) or (trash and !offer.action.move)) {
self.discardOffer(offer);
return;
}
+ self.drop_trash = trash;
self.startDropReceive(offer, slot, directory, terminal) catch {
self.app.setStatusNotice(@import("i18n").tr("Could not read the dropped items"), true);
self.discardOffer(offer);
@@ -130,7 +138,7 @@ pub fn startDropReceive(self: *Client, offer: *Offer, slot: ?usize, target: []co
self.drop_offer = offer;
self.drop_slot = slot;
self.drop_terminal = terminal;
- self.drop_move = slot == null and !terminal and offer.action.move;
+ self.drop_move = slot == null and !terminal and !self.drop_trash and offer.action.move;
offer.proxy.receive("text/uri-list", fds[1]);
}
@@ -161,7 +169,9 @@ pub fn receiveDrop(self: *Client) void {
return;
};
defer decoded.deinit(a);
- if (self.drop_terminal) {
+ if (self.drop_trash) {
+ self.app.trashDropped(decoded.paths);
+ } else if (self.drop_terminal) {
// Like clipboard paste, an asynchronous drop must not type into a
// different editor or a restarted session after focus changes.
if (receive.revision == self.app.edit_revision and self.app.focus == .terminal) self.app.terminalDropPaths(decoded.paths);
@@ -196,6 +206,7 @@ pub fn receiveDrop(self: *Client) void {
pub fn finishDrop(self: *Client) void {
if (self.drop_receiving) |*receive| receive.deinit();
self.drop_receiving = null;
+ self.drop_trash = false;
const offer = self.drop_offer orelse return;
self.drop_offer = null;
self.endDrop(offer);
diff --git a/tests/files_drag.py b/tests/files_drag.py
index 73a7e37..6312153 100644
--- a/tests/files_drag.py
+++ b/tests/files_drag.py
@@ -222,9 +222,8 @@ def run_pin():
return any(r > 180 and g < 90 and b < 110 for r, g, b in pixels)
def drag(card, x, y, line_at=None):
sx = 250 + 252 * card
- click(sx, 158)
- # The press that starts the drag must not read as a double click.
- time.sleep(.7)
+ # A click on an icon opens it (single-click open): the
+ # press alone selects the card the drag carries.
move(sx, 158)
button(True)
time.sleep(.1)
@@ -291,6 +290,110 @@ def run_pin():
log.close()
+def run_trash():
+ """Drag files onto the sidebar's Trash row: an outline marks it, a release trashes at once."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-files-trash-drop-") as directory:
+ tmp = Path(directory)
+ home = tmp / "home"
+ home.mkdir()
+ for name in ("keep folder", "trash folder"):
+ (home / name).mkdir()
+ (home / "note.txt").write_text("trash me")
+ trash = tmp / "data/Trash/files"
+ calls = tmp / "gio-calls"
+ helpers = tmp / "bin"
+ helpers.mkdir()
+ # A stand-in for gio: real trashing refuses the tmpfs this test lives on.
+ gio = helpers / "gio"
+ gio.write_text("#!/usr/bin/python3\n"
+ "import pathlib, shutil, sys\n"
+ f"pathlib.Path({str(calls)!r}).open('a').write(repr(sys.argv[1:]) + '\\n')\n"
+ "assert sys.argv[1:3] == ['trash', '--'], sys.argv\n"
+ f"dest = pathlib.Path({str(trash)!r})\n"
+ "dest.mkdir(parents=True, exist_ok=True)\n"
+ "for path in sys.argv[3:]: shutil.move(path, dest / pathlib.Path(path).name)\n")
+ gio.chmod(0o755)
+ comp, log = spawn_compositor(tmp, config_content="[compositor]\nxwayland = false\n",
+ renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
+ env_extra={"HOME": str(home)})
+ files = None
+ try:
+ with IPCClient(tmp).connect() as ipc:
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),
+ XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),
+ REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
+ DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0",
+ PATH=f"{helpers}:{os.environ['PATH']}")
+ for key in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):
+ env.pop(key, None)
+ with (tmp / "files.log").open("w") as out:
+ files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], env=env, stdout=out, stderr=out)
+ win = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None), "Files did not map")
+ ipc.action('set_window_size', {"id": win["id"], "width": 1000, "height": 588})
+ ipc.action('move_window_to', {"id": win["id"], "x": 10, "y": 30})
+ ipc.action('focus_window', {"id": win["id"]})
+ time.sleep(.6)
+ box = ipc.get_window_debug(win["id"])["client_box"]
+
+ # Window coordinates as in run_pin: Home is centred at 142,
+ # Trash at 174 (its outline's top edge at 158).
+ def move(x, y):
+ ipc.action('move_cursor', {"x": round(box["x"] + x), "y": round(box["y"] + y)})
+ def button(pressed):
+ ipc.action('pointer_button', {"button": 272, "pressed": pressed})
+ def accent_at(y):
+ path = tmp / "hover.png"
+ path.unlink(missing_ok=True)
+ ipc.screenshot(path=str(path))
+ with Image.open(path) as image:
+ pixels = [image.convert("RGB").getpixel((round(box["x"] + 100), round(box["y"] + y + d))) for d in range(-3, 4)]
+ return any(r > 180 and g < 90 and b < 110 for r, g, b in pixels)
+ def drag(card, x, y, outline=False):
+ sx = 250 + 252 * card
+ # A click on an icon opens it (single-click open): the
+ # press alone selects the card the drag carries.
+ move(sx, 158)
+ button(True)
+ time.sleep(.1)
+ for step in range(1, 11):
+ move(sx + (x - sx) * step / 10, 158 + (y - 158) * step / 10)
+ time.sleep(.04)
+ time.sleep(.25)
+ if outline:
+ wait_for(lambda: accent_at(158), "no outline on the Trash row while hovering it")
+ button(False)
+ time.sleep(.5)
+ def gio_calls():
+ return calls.read_text().splitlines() if calls.exists() else []
+
+ # Cards: keep folder, trash folder, note.txt.
+ drag(2, 80, 174, outline=True)
+ wait_for(lambda: (trash / "note.txt").exists(), "the dropped file was not trashed")
+ assert not (home / "note.txt").exists()
+ assert gio_calls() == [repr(["trash", "--", str(home / "note.txt")])], gio_calls()
+ assert not accent_at(158), "the Trash outline outlived the drop"
+ drag(1, 80, 174)
+ wait_for(lambda: (trash / "trash folder").is_dir(), "the dropped folder was not trashed")
+ # Home is not a target: nothing more is trashed.
+ drag(0, 80, 142)
+ time.sleep(.3)
+ assert len(gio_calls()) == 2, gio_calls()
+ assert (home / "keep folder").is_dir()
+ assert files.poll() is None
+ print("PASS Files drag onto the Trash row trashes without a dialog; other rows do not")
+ except Exception:
+ for name in ("files.log", "compositor.log"):
+ if (tmp / name).exists():
+ print(name, (tmp / name).read_text()[-5000:])
+ raise
+ finally:
+ if files:
+ stop_process(files)
+ stop_process(comp)
+ log.close()
+
+
def run_transfer(same_window=False, copy=False, list_view=False, folder=True, ctrl_changes=()):
expected_copy = ctrl_changes[-1] if ctrl_changes else copy
with tempfile.TemporaryDirectory(prefix="rediwm-files-transfer-") as directory:
@@ -417,4 +520,7 @@ if __name__ == "__main__":
if "--pin" in sys.argv:
run_pin()
sys.exit(0)
+ if "--trash" in sys.argv:
+ run_trash()
+ sys.exit(0)
run("--browser" in sys.argv, "--select" in sys.argv, "--list" in sys.argv)