Skip to content

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

Drop files on the dock's Trash to trash them, without a confirmation

oxydizer1b6a5185c00d
diff --git a/docs/agent-notes/dock.md b/docs/agent-notes/dock.md
index 3a23306..cf0237d 100644
--- a/docs/agent-notes/dock.md
+++ b/docs/agent-notes/dock.md
@@ -59,3 +59,16 @@ taskbar, OSD and input integration. General rules remain in
before the menu's own Escape) abandons it. A dock
holds resolved pins as copies (`pin_arena`); `config_index` maps a slot back
into `dock_pinned_apps`, which also lists apps no longer installed.
+
+* **Files dropped on the dock's Trash item** (`trash_drop.zig`, field
+ `Input.trash_drop`) are trashed with no question, as the desktop Trash icon
+ does. It is a `desktop_drop.Target` too, so only a text/uri-list source that
+ allows *move* can drop (a copy-only drag is refused: nothing the user meant
+ to copy is deleted). `Dock.trashAt` picks the item; the motion `.dock` branch
+ must use the grab-aware `pointerNotifyClearFocus` while `seat.drag` is set,
+ or the drag stays focused on the last client and a release drops there. The
+ URI list is read on the event loop (nonblocking fd, 5 s deadline timer, 256 KiB
+ cap), then `gio trash -- <paths>` runs and the drag is finished (`dnd_finish`)
+ when it exits; a failure cancels the drag and posts a notification. An
+ auto-hiding dock reveals for a file drag (`draggingFiles` in `input/motion.zig`).
+ Covered by `tests/dock_trash_drop.py`.
diff --git a/src/Dock.zig b/src/Dock.zig
index a6c6925..c8f3c69 100644
--- a/src/Dock.zig
+++ b/src/Dock.zig
@@ -329,6 +329,7 @@ pub const leave = dock_pointer.leave;
pub const repaint = dock_pointer.repaint;
pub const press = dock_pointer.press;
pub const buttonAt = dock_pointer.buttonAt;
+pub const trashAt = dock_pointer.trashAt;
pub const clickPin = dock_pointer.clickPin;
pub const contextMenu = dock_pointer.contextMenu;
pub const removeShortcut = dock_pointer.removeShortcut;
diff --git a/src/Input.zig b/src/Input.zig
index 2870508..0fe1cc5 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -187,6 +187,8 @@ move_snap: MoveSnap = .{},
tiling_grab: ?@import("tiling_grab.zig") = null,
/// An application being dragged from the start menu to the dock.
dock_drag: @import("dock_drag.zig") = .{},
+/// Files from a client's drag, dropped on the dock's Trash.
+trash_drop: @import("trash_drop.zig") = .{},
/// The last titlebar press, for double-click-to-maximize.
title_press: ?TitlePress = null,
/// Pointer presses so far: a double-click is two presses in a row.
@@ -392,6 +394,7 @@ pub fn deinit(input: *Input) void {
input.pointer_constraints.deinit();
input.shortcuts_inhibit.deinit();
input.drag_dodge.deinit();
+ input.trash_drop.deinit();
input.lid.deinit();
input.tablet.deinit();
input.touch.deinit();
diff --git a/src/desktop_drop.zig b/src/desktop_drop.zig
index 4875e4d..556c0df 100644
--- a/src/desktop_drop.zig
+++ b/src/desktop_drop.zig
@@ -56,6 +56,13 @@ pub const Target = struct {
} else if (source.accepted) source.accept(0, null);
}
+ /// Tells a drag over something that takes no drops that a drop would do
+ /// nothing, undoing what `hover` said over the target.
+ pub fn refuse(_: *const Target, seat: *wlr.Seat) void {
+ const source = dragSource(seat) orelse return;
+ if (source.accepted) source.accept(0, null);
+ }
+
/// Takes over the drag as its target. Call on the grab button's release,
/// before `pointerNotifyButton`. Returns the read end of the URI list and
/// the negotiated action, or null (leaving the drag untouched, so wlroots
diff --git a/src/dock/pointer.zig b/src/dock/pointer.zig
index 0c51ff4..1616e91 100644
--- a/src/dock/pointer.zig
+++ b/src/dock/pointer.zig
@@ -144,6 +144,12 @@ pub fn buttonAt(self: *const Self, x: f32, y: f32) ?usize {
return null;
}
+/// The point (`x`, `y`), in the coordinates `motion` takes, is on the Trash item.
+pub fn trashAt(self: *const Self, x: f64, y: f64) bool {
+ const index = self.buttonAt(@floatCast(x), @floatCast(y)) orelse return false;
+ return self.shortcuts[index] == .trash;
+}
+
/// A pinned icon was pressed and released without being dragged: its click,
/// if the pointer (at layout position `x`, `y`) is still on that icon.
pub fn clickPin(self: *Self, x: f64, y: f64, app_id: []const u8) void {
diff --git a/src/input/buttons.zig b/src/input/buttons.zig
index e6adbce..17999fa 100644
--- a/src/input/buttons.zig
+++ b/src/input/buttons.zig
@@ -266,8 +266,12 @@ pub fn processClientButton(
if (input.server.desktop) |desktop| desktop.pointerButton(button, false);
if (input.active_buttons == 0) input.desktop_grab = false;
}
- if (input.seat.drag != null) if (input.server.desktop) |desktop| {
- if (scene_data.hitTest(input.server, input.cursor.x, input.cursor.y) == .desktop) _ = desktop.drop(button);
+ if (input.seat.drag != null) switch (scene_data.hitTest(input.server, input.cursor.x, input.cursor.y)) {
+ .desktop => if (input.server.desktop) |desktop| {
+ _ = desktop.drop(button);
+ },
+ .dock => |res| _ = input.trash_drop.drop(res.dock, res.sx, res.sy, button),
+ else => {},
};
_ = input.seat.pointerNotifyButton(time_msec, button, state);
// A move grab ends here, and `grabbed_toplevel` must be dropped with the
diff --git a/src/input/motion.zig b/src/input/motion.zig
index eaac7a9..2d3a464 100644
--- a/src/input/motion.zig
+++ b/src/input/motion.zig
@@ -171,11 +171,19 @@ pub fn warpCursor(input: *Input, x: f64, y: f64, time_msec: u32) void {
}
}
+/// A client's pointer drag carrying a list of files is under way.
+fn draggingFiles(input: *const Input) bool {
+ const drag = input.seat.drag orelse return false;
+ const source = drag.source orelse return false;
+ return drag.grab_type == .keyboard_pointer and @import("../desktop_drop.zig").offersUriList(source);
+}
+
/// An auto-hiding dock shows when the pointer reaches its edge. Moving or
/// resizing a window, or holding a button for a client (a selection dragged to
-/// the edge), must not raise it; dragging an app from the start menu does.
+/// the edge), must not raise it; dragging an app from the start menu does, and
+/// so does dragging files from a client, which can be dropped on the Trash.
pub fn updateDockReveal(input: *Input) void {
- const engaged = input.cursor_mode == .passthrough and (input.active_buttons == 0 or input.dock_drag.active());
+ const engaged = input.cursor_mode == .passthrough and (input.active_buttons == 0 or input.dock_drag.active() or draggingFiles(input));
var it = input.server.outputs.iterator(.forward);
while (it.next()) |output| output.dock.pointerAt(input.cursor.x, input.cursor.y, engaged);
}
@@ -349,7 +357,12 @@ pub fn passthroughMotion(input: *Input, time_msec: u32) void {
input.setHover(null, null);
res.dock.motion(res.sx, res.sy);
input.setDefaultCursor();
- input.seat.pointerClearFocus();
+ if (input.seat.drag != null) {
+ // The grab-aware clear: a drag must leave the client it was over,
+ // or a release here would still drop on it.
+ input.seat.pointerNotifyClearFocus();
+ input.trash_drop.hover(res.dock.trashAt(res.sx, res.sy));
+ } else input.seat.pointerClearFocus();
},
.taskbar => |res| {
input.hovered_resize_edges = null;
diff --git a/src/trash_drop.zig b/src/trash_drop.zig
new file mode 100644
index 0000000..a26a27a
--- /dev/null
+++ b/src/trash_drop.zig
@@ -0,0 +1,198 @@
+//! Files dragged onto the dock's Trash item go to the Trash, with no question
+//! asked (the Trash is where a deleted file can still be got back from).
+//!
+//! This is the desktop Trash icon's drop (`desktop_drop.zig`) for the dock: the
+//! compositor is the target of a wl_data_device drag. Only a source that offers
+//! text/uri-list and allows *move* may drop here; a copy-only drag (a link, an
+//! archive member) is refused rather than deleting what the user meant to copy.
+//! The list is read on the event loop, because a client writes it at its own
+//! pace (a stalled one is dropped after `read_timeout_ms`); `gio trash` does the
+//! moving, as Files and the desktop do. The drag is finished when `gio` exits,
+//! so the source learns whether it worked.
+const std = @import("std");
+const wl = @import("wayland").server.wl;
+const wlr = @import("wlroots");
+const i18n = @import("i18n");
+const Input = @import("Input.zig");
+const Server = @import("Server.zig");
+const Dock = @import("Dock.zig");
+const Child = @import("session/child.zig");
+const app_scope = @import("session/app_scope.zig");
+const DropTarget = @import("desktop_drop.zig").Target;
+const dnd = @import("desktop/dnd.zig");
+const gpa = @import("main.zig").gpa;
+const Self = @This();
+
+/// A URI list longer than this is not a selection of files: the drop is refused.
+const max_list = 256 * 1024;
+const read_timeout_ms = 5000;
+
+target: DropTarget = .{},
+/// The read end of the URI list and what has come through it, until the writer closes.
+fd: i32 = -1,
+data: std.ArrayList(u8) = .empty,
+source: ?*wl.EventSource = null,
+timer: ?*wl.EventSource = null,
+/// The `gio trash` run that the drag waits for.
+child: ?*Child = null,
+
+pub fn deinit(self: *Self) void {
+ self.stopReading();
+ if (self.timer) |timer| timer.remove();
+ self.timer = null;
+ // The process runs on, reaped by its watch; nothing may call back into us.
+ if (self.child) |child| child.detach();
+ self.child = null;
+ self.data.deinit(gpa);
+}
+
+fn input(self: *Self) *Input {
+ return @fieldParentPtr("trash_drop", self);
+}
+
+/// A file drag is over the dock: the Trash item takes it, the rest of the dock
+/// does not. Tells the source, so it can show what a drop would do.
+pub fn hover(self: *Self, over_trash: bool) void {
+ const in = self.input();
+ if (over_trash and in.server.locker == null) self.target.hover(in.seat, .move, false) else self.target.refuse(in.seat);
+}
+
+/// A drag was released over `dock` at (`x`, `y`) in the dock's own coordinates.
+/// True when the Trash took it; false leaves it to wlroots, which cancels it.
+/// Call before the release reaches the seat (`desktop_drop.Target.take`).
+pub fn drop(self: *Self, dock: *Dock, x: f64, y: f64, button: u32) bool {
+ const in = self.input();
+ if (in.server.locker != null or !dock.trashAt(x, y)) return false;
+ const taken = self.target.take(in.seat, button, .move, false) orelse return false;
+ self.receive(taken.fd);
+ return true;
+}
+
+fn receive(self: *Self, fd: i32) void {
+ const loop = self.input().server.wl_server.getEventLoop();
+ const flags = std.c.fcntl(fd, std.c.F.GETFL, @as(c_int, 0));
+ if (flags < 0 or std.c.fcntl(fd, std.c.F.SETFL, flags | @as(c_int, @bitCast(std.posix.O{ .NONBLOCK = true }))) < 0) {
+ _ = std.c.close(fd);
+ return self.failed();
+ }
+ self.fd = fd;
+ self.data.clearRetainingCapacity();
+ self.source = loop.addFd(*Self, fd, .{ .readable = true }, readable, self) catch return self.abandon();
+ if (self.timer == null) self.timer = loop.addTimer(*Self, timedOut, self) catch return self.abandon();
+ self.timer.?.timerUpdate(read_timeout_ms) catch self.abandon();
+}
+
+fn readable(fd: c_int, _: wl.EventMask, self: *Self) c_int {
+ // Bounded per dispatch, so a fast writer cannot starve input.
+ var budget: usize = 64 * 1024;
+ while (budget > 0) {
+ var buffer: [4096]u8 = undefined;
+ const n = std.c.read(fd, &buffer, buffer.len);
+ if (n > 0) {
+ const len: usize = @intCast(n);
+ budget -|= len;
+ if (self.data.items.len + len > max_list) {
+ self.abandon();
+ return 0;
+ }
+ self.data.appendSlice(gpa, buffer[0..len]) catch {
+ self.abandon();
+ return 0;
+ };
+ continue;
+ }
+ if (n == 0) {
+ self.received();
+ return 0;
+ }
+ switch (std.posix.errno(n)) {
+ .INTR => continue,
+ .AGAIN => return 0,
+ else => {
+ self.abandon();
+ return 0;
+ },
+ }
+ }
+ return 0;
+}
+
+fn timedOut(self: *Self) c_int {
+ self.abandon();
+ return 0;
+}
+
+fn stopReading(self: *Self) void {
+ if (self.source) |source| source.remove();
+ self.source = null;
+ if (self.timer) |timer| timer.timerUpdate(0) catch {};
+ if (self.fd >= 0) _ = std.c.close(self.fd);
+ self.fd = -1;
+}
+
+/// The writer closed its end: the list is complete.
+fn received(self: *Self) void {
+ self.stopReading();
+ defer self.data.clearRetainingCapacity();
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const paths = parse(arena.allocator(), self.data.items) catch &.{};
+ if (paths.len == 0) return self.target.finish(false);
+ self.trash(arena.allocator(), paths);
+}
+
+/// The local files in a text/uri-list; other URIs and comments are skipped.
+fn parse(a: std.mem.Allocator, list: []const u8) ![]const []const u8 {
+ var paths: std.ArrayList([]const u8) = .empty;
+ var lines = std.mem.splitScalar(u8, list, '\n');
+ while (lines.next()) |raw| {
+ const uri = std.mem.trim(u8, raw, " \t\r");
+ if (uri.len == 0 or uri[0] == '#') continue;
+ try paths.append(a, dnd.localPath(a, uri) catch continue);
+ }
+ return paths.items;
+}
+
+/// Starts `gio trash`. There is no prompt to answer: `gio` reads no input.
+fn trash(self: *Self, a: std.mem.Allocator, paths: []const []const u8) void {
+ const server = self.input().server;
+ var argv: std.ArrayList([]const u8) = .empty;
+ argv.appendSlice(a, &.{ "gio", "trash", "--" }) catch return self.failed();
+ argv.appendSlice(a, paths) catch return self.failed();
+ var env = server.environ.createMap(gpa) catch return self.failed();
+ defer env.deinit();
+ server.applyChildEnv(&env) catch return self.failed();
+ const started = std.process.spawn(server.io, .{ .argv = argv.items, .environ_map = &env, .stdin = .ignore }) catch |err| {
+ std.log.warn("could not run gio trash: {}", .{err});
+ return self.failed();
+ };
+ const pid = started.id orelse return self.failed();
+ app_scope.place(server, pid, "gio");
+ self.child = Child.watch(gpa, server.wl_server.getEventLoop(), pid, self, exited) catch {
+ // Nobody would collect it.
+ _ = std.os.linux.kill(pid, .KILL);
+ var status: u32 = 0;
+ while (std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
+ return self.failed();
+ };
+}
+
+fn exited(owner: ?*anyopaque, _: *Child, status: ?u32) void {
+ const self: *Self = @ptrCast(@alignCast(owner.?));
+ self.child = null;
+ const ok = if (status) |value| std.os.linux.W.IFEXITED(value) and std.os.linux.W.EXITSTATUS(value) == 0 else false;
+ if (ok) self.target.finish(true) else self.failed();
+}
+
+/// The list never arrived whole.
+fn abandon(self: *Self) void {
+ self.stopReading();
+ self.failed();
+}
+
+/// Nothing (or not everything) was moved: say so, and cancel the drag.
+fn failed(self: *Self) void {
+ self.target.finish(false);
+ const manager = self.input().server.notifications orelse return;
+ _ = manager.postNotification(i18n.tr("Trash"), 0, "user-trash", i18n.tr("Could not move all items to Trash"), "", &.{}, 1, false, false, 0, "", null) catch {};
+}
diff --git a/tests/dock_trash_drop.py b/tests/dock_trash_drop.py
new file mode 100644
index 0000000..08d44db
--- /dev/null
+++ b/tests/dock_trash_drop.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Files dragged from a client onto the dock's Trash item are moved to the Trash, unasked.
+
+A real wl_data_device source (tests/desktop_transfer.c) drags a URI list onto the
+dock. `gio` is a stand-in on PATH (real trashing depends on the mount the temporary
+directory is on) that logs its arguments, so the check is what the compositor ran.
+"""
+import os
+import subprocess
+import tempfile
+import time
+from pathlib import Path
+
+from desktop_zoom import build_client, wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from ui_driver import UIDriver
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def run(auto_hide):
+ scale = float(os.environ.get('REDIWM_TEST_SCALE', '1'))
+ with tempfile.TemporaryDirectory(prefix='rediwm-dock-trash-drop-') as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ sender_bin = tmp / 'transfer-client'
+ subprocess.run(['cc', '-Wall', '-Wextra', f'-I{tmp}', str(ROOT / 'tests/desktop_transfer.c'),
+ str(tmp / 'xdg-shell-protocol.c'), str(tmp / 'xdg-decoration-protocol.c'),
+ '-lwayland-client', '-o', str(sender_bin)], check=True)
+ trash = tmp / 'data/Trash/files'
+ failure = tmp / 'fail-trash'
+ calls = tmp / 'gio-calls'
+ helpers = tmp / 'bin'
+ helpers.mkdir()
+ 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'
+ f'if pathlib.Path({str(failure)!r}).exists(): sys.exit(1)\n'
+ f'dest = pathlib.Path({str(trash)!r})\n'
+ 'dest.mkdir(parents=True, exist_ok=True)\n'
+ 'assert sys.argv[1:3] == ["trash", "--"], sys.argv\n'
+ 'for path in sys.argv[3:]: shutil.move(path, dest / pathlib.Path(path).name)\n')
+ gio.chmod(0o755)
+ process, log = spawn_compositor(tmp, scale=scale, outputs='1',
+ config_content='[compositor]\nxwayland = false\ndock_enabled = true\n'
+ f'dock_auto_hide = {"true" if auto_hide else "false"}\n[animations]\nenabled = false\n',
+ env_extra={'DBUS_SESSION_BUS_ADDRESS': '', 'XDG_CONFIG_HOME': str(tmp / 'config'),
+ 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'PATH': f'{helpers}:{os.environ["PATH"]}'})
+ senders = []
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)
+ ui = UIDriver(ipc)
+ display = wait_for(lambda: next((p.name for p in tmp.glob('wayland-*') if not p.name.endswith('.lock')), None), 'display')
+
+ def dock():
+ return ui.widgets('dock')
+
+ def center(name):
+ b = next(w for w in dock() if w['name'] == name)['global_box']
+ return round(b['x'] + b['width'] / 2), round(b['y'] + b['height'] / 2)
+
+ def drag_to(files, name, aim):
+ """Starts a drag of `files` from a fixture window, then `aim` moves the pointer and it is released."""
+ log_path = tmp / f'{name}.log'
+ with log_path.open('w') as sender_log:
+ sender = subprocess.Popen([str(sender_bin)], stdout=sender_log, stderr=sender_log,
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ REDIWM_TEST_TRANSFER=''.join(f.as_uri() + '\r\n' for f in files)))
+ senders.append(sender)
+ window = wait_for(lambda: next(iter(ipc.get_windows()), None), 'sender window')
+ ipc.action('move_window_to', {'id': window['id'], 'x': 200, 'y': 150})
+ ipc.wait_for('window_geometry_settled', window_id=window['id'], timeout_ms=5000)
+ ipc.move_cursor(240, 240)
+ ipc.wait_for_frame()
+ ipc.pointer_button(0x110, True)
+ time.sleep(.15)
+ aim()
+ ipc.wait_for_frame()
+ ipc.pointer_button(0x110, False)
+ return sender, log_path
+
+ def finish_sender(sender):
+ sender.terminate()
+ sender.wait()
+ wait_for(lambda: not ipc.get_windows(), 'sender window gone')
+
+ def reach(name):
+ """Moves onto dock item `name`; an auto-hiding dock first needs the pointer at its edge."""
+ if auto_hide:
+ ipc.move_cursor(960, edge)
+ wait_for(lambda: any(w['name'] == name for w in dock()), 'dock revealed for the drag')
+ ipc.move_cursor(*center(name))
+
+ edge = ipc.get_outputs()[0]['logical_height'] - 1
+ if auto_hide:
+ # Away: nothing is built to aim at until the pointer reaches the edge.
+ assert not any(w['name'] for w in dock()), 'auto-hidden dock showed'
+ else:
+ wait_for(lambda: any(w['name'] == 'trash' for w in dock()), 'dock Trash')
+
+ # A drop on the Trash item moves every dropped file, without a dialog.
+ first, second = tmp / 'Drop me.txt', tmp / 'and me #2.txt'
+ first.write_text('one')
+ second.write_text('two')
+ sender, sender_log = drag_to([first, second], 'trash', lambda: reach('trash'))
+ wait_for(lambda: 'transfer-finished' in sender_log.read_text(), 'the drag was not finished')
+ assert not first.exists() and not second.exists(), 'dropped files were not moved'
+ assert (trash / first.name).read_text() == 'one' and (trash / second.name).read_text() == 'two'
+ assert eval(calls.read_text().splitlines()[-1]) == ['trash', '--', str(first), str(second)]
+ finish_sender(sender)
+
+ # Anywhere else on the dock a drop does nothing.
+ keep = tmp / 'Keep me.txt'
+ keep.write_text('kept')
+ before = calls.read_text()
+ sender, sender_log = drag_to([keep], 'elsewhere', lambda: reach('files'))
+ time.sleep(.5)
+ assert keep.exists() and calls.read_text() == before, 'a drop beside the Trash trashed a file'
+ assert 'transfer-finished' not in sender_log.read_text()
+ finish_sender(sender)
+
+ # When gio fails the files stay where they are, and the source is told it was cancelled.
+ failure.write_text('')
+ sender, sender_log = drag_to([keep], 'failure', lambda: reach('trash'))
+ wait_for(lambda: calls.read_text() != before, 'gio was not run')
+ time.sleep(.3)
+ assert keep.exists(), 'a failed trash moved the file'
+ assert 'transfer-finished' not in sender_log.read_text()
+ finish_sender(sender)
+ finally:
+ for sender in senders:
+ stop_process(sender)
+ stop_process(process)
+ log.close()
+
+
+if __name__ == '__main__':
+ run(auto_hide=False)
+ run(auto_hide=True)
+ print('Dock Trash drops passed')