Skip to content

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

pdf viewer fixes

oxydizer25ee1e7a0d44
diff --git a/TESTING.md b/TESTING.md
index b7e5278..da72cbc 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -206,12 +206,13 @@ caret blinking and idle wakeups, and title glyph dimensions across resizes
`REDIWM_TEST_RENDERER`, and `REDIWM_EDITOR_PREVIEW=/tmp/editor.png`.
**PDF viewer**: `zig build test-pdf`, `pdf_viewer.py` (rendering, navigation,
-tiled fit width, and printing through a fake Print portal on a private bus; run
+text selection/copying, tiled fit width, and print dismissal/failure through a
+fake Print portal on a private bus; run
it with `REDIWM_SCALE=2` too, where tiles split differently), `pdf_sandbox.py`
(a test-only parser hook checks file, syscall, inherited-FD, environment and
Wayland restrictions, that the print helper's socket cannot pass descriptors,
plus failure to install the sandbox). Requires Poppler GLib, libseccomp, Linux
-Landlock ABI 3+, Python Cairo, and `dbus-daemon`.
+Landlock ABI 3+, Python Cairo, `wl-paste`, and `dbus-daemon`.
**Browsers**: `brave_input.py` (optional; `REDIWM_TEST_BRAVE=/path`), a smoke
test of focus, clipboard, navigation and scrolling in a fresh profile.
diff --git a/src/pdf/app.zig b/src/pdf/app.zig
index 99fd437..c015c0e 100644
--- a/src/pdf/app.zig
+++ b/src/pdf/app.zig
@@ -5,6 +5,7 @@ const std = @import("std");
const c = @import("c.zig");
const document = @import("document.zig");
const layout = @import("layout.zig");
+const selection = @import("selection.zig");
const cache = @import("cache.zig");
const worker = @import("worker.zig");
const shell_ui = @import("ui").cairo;
@@ -121,10 +122,12 @@ pub const SearchMatch = struct {
pub const PageContent = struct {
page_index: usize,
text: ?[:0]u8 = null,
+ text_rects: []const layout.Rect = &[_]layout.Rect{},
links: []document.Link = &[_]document.Link{},
pub fn deinit(self: *PageContent) void {
if (self.text) |t| a.free(t);
+ a.free(self.text_rects);
for (self.links) |l| l.deinit(a);
if (self.links.len > 0) a.free(self.links);
self.* = undefined;
@@ -202,6 +205,7 @@ pub const App = struct {
// Page content & links
page_contents: std.AutoHashMap(usize, PageContent),
+ hover_text: bool = false,
hover_link: ?document.Link = null,
// Text selection & Wayland clipboard
@@ -210,7 +214,7 @@ pub const App = struct {
selection_page: ?usize = null,
selection_start: layout.Point = .{ .x = 0, .y = 0 },
selection_end: layout.Point = .{ .x = 0, .y = 0 },
- selection_box: ?layout.Rect = null,
+ selection_range: ?selection.Range = null,
selected_text: ?[:0]u8 = null,
clipboard_text: ?[:0]u8 = null,
clipboard_request: bool = false,
@@ -304,6 +308,11 @@ pub const App = struct {
self.thumb_cache.clearGeneration(self.generation);
self.clearOutline();
self.clearPageContents();
+ self.clearSelectionText();
+ self.selection_page = null;
+ self.selection_range = null;
+ self.selection_active = false;
+ self.selection_dragging = false;
self.search_matches.clearRetainingCapacity();
self.current_page = 0;
@@ -456,9 +465,12 @@ pub const App = struct {
entry.value_ptr.* = .{
.page_index = ce.page_index,
.text = ce.text,
+ .text_rects = ce.text_rects,
.links = ce.links,
};
ce.text = null;
+ ce.text_rects = &[_]layout.Rect{};
+ if (self.selection_page == ce.page_index) self.updateSelection();
ce.links = &[_]document.Link{};
self.dirty = true;
},
@@ -952,19 +964,15 @@ pub const App = struct {
const page_y = cv.y + p.y_offset - self.scroll_y;
const view_pt = layout.Point{ .x = px - page_x, .y = py - page_y };
self.selection_end = layout.viewPointToPage(view_pt, p.pts_size, self.rotation, self.zoom);
- const min_x = @min(self.selection_start.x, self.selection_end.x);
- const max_x = @max(self.selection_start.x, self.selection_end.x);
- const min_y = @min(self.selection_start.y, self.selection_end.y);
- const max_y = @max(self.selection_start.y, self.selection_end.y);
- self.selection_box = .{ .x = min_x, .y = min_y, .w = max_x - min_x, .h = max_y - min_y };
- self.selection_active = true;
+ self.updateSelection();
self.dirty = true;
return;
}
}
- // Link hover detection
+ // Text and link hover detection
self.hover_link = null;
+ self.hover_text = false;
if (self.doc_layout) |dl| {
const cv = self.canvasRect();
if (cv.contains(px, py)) {
@@ -977,6 +985,12 @@ pub const App = struct {
if (px >= page_x and px <= page_x + p.logical_width and py >= page_y and py <= page_y + p.logical_height) {
if (self.page_contents.get(i)) |content| {
const pt = layout.viewPointToPage(.{ .x = px - page_x, .y = py - page_y }, p.pts_size, self.rotation, self.zoom);
+ for (content.text_rects) |r| {
+ if (r.w > 0 and r.h > 0 and r.contains(pt)) {
+ self.hover_text = true;
+ break;
+ }
+ }
for (content.links) |lnk| {
if (lnk.area.contains(pt)) {
self.hover_link = lnk;
@@ -1101,8 +1115,10 @@ pub const App = struct {
self.selection_page = i;
self.selection_start = pt;
self.selection_end = pt;
- self.selection_box = null;
+ self.clearSelectionText();
+ self.selection_range = null;
self.selection_active = false;
+ self.dirty = true;
return;
}
}
@@ -1124,23 +1140,34 @@ pub const App = struct {
}
if (self.selection_dragging) {
self.selection_dragging = false;
- if (self.selection_box != null and self.selection_box.?.w > 2.0 and self.selection_box.?.h > 2.0) {
- self.selection_active = true;
- // Build text for clipboard
- if (self.selection_page) |p_idx| {
- if (self.page_contents.get(p_idx)) |content| {
- if (content.text) |txt| {
- if (self.selected_text) |t| a.free(t);
- self.selected_text = a.dupeZ(u8, txt) catch null;
- }
- }
- }
- }
+ self.updateSelection();
}
}
}
}
+ fn clearSelectionText(self: *App) void {
+ if (self.selected_text) |t| a.free(t);
+ self.selected_text = null;
+ }
+
+ fn updateSelection(self: *App) void {
+ self.dirty = true;
+ self.clearSelectionText();
+ self.selection_range = null;
+ self.selection_active = false;
+ const page = self.selection_page orelse return;
+ const content = self.page_contents.get(page) orelse return;
+ const range = selection.between(content.text_rects, self.selection_start, self.selection_end) orelse return;
+ const text = content.text orelse return;
+ const selected = range.text(text);
+ if (selected.len == 0) return;
+ self.selected_text = a.dupeZ(u8, selected) catch return;
+ self.selection_range = range;
+ self.selection_active = true;
+ self.dirty = true;
+ }
+
fn handleToolbarClick(self: *App) void {
// Page number editor field click: x=124..204
if (self.px >= 124.0 and self.px <= 204.0 and self.py >= 6.0 and self.py <= 38.0) {
@@ -1316,9 +1343,12 @@ pub const App = struct {
} else if (self.search_open) {
self.search_open = false;
self.focus = .none;
- } else if (self.selection_active) {
+ } else if (self.selection_active or self.selection_dragging) {
self.selection_active = false;
- self.selection_box = null;
+ self.selection_dragging = false;
+ self.selection_page = null;
+ self.selection_range = null;
+ self.clearSelectionText();
}
self.dirty = true;
return;
@@ -1388,7 +1418,7 @@ pub const App = struct {
self.dirty = true;
},
'c', 'C' => {
- if (self.selected_text) |txt| {
+ if (if (self.selection_active) self.selected_text else null) |txt| {
if (self.clipboard_text) |c_prev| a.free(c_prev);
self.clipboard_text = a.dupeZ(u8, txt) catch null;
self.clipboard_request = true;
@@ -1454,7 +1484,7 @@ pub const App = struct {
pub fn cursorName(self: *const App) [*:0]const u8 {
if (self.hover_link != null) return "pointer";
- if (self.selection_active or self.selection_dragging) return "text";
+ if (self.hover_text or self.selection_dragging) return "text";
if (self.focus != .none) return "text";
return "default";
}
@@ -1607,12 +1637,17 @@ pub const App = struct {
}
// Paint text selection highlight on this page
- if (self.selection_page == i and self.selection_box != null) {
- const sbox = self.selection_box.?;
- const vr = layout.pageRectToView(sbox, p.pts_size, self.rotation, self.zoom);
- shell_ui.setSource(cr, ui_theme.shellPalette().selectionColor());
- c.api.cairo_rectangle(cr, page_x + vr.x, page_y + vr.y, vr.w, vr.h);
- c.api.cairo_fill(cr);
+ if (self.selection_page == i) {
+ if (self.selection_range) |range| {
+ if (self.page_contents.get(i)) |content| {
+ shell_ui.setSource(cr, ui_theme.shellPalette().selectionColor());
+ for (content.text_rects[range.start..range.end]) |r| {
+ const vr = layout.pageRectToView(r, p.pts_size, self.rotation, self.zoom);
+ c.api.cairo_rectangle(cr, page_x + vr.x, page_y + vr.y, vr.w, vr.h);
+ }
+ c.api.cairo_fill(cr);
+ }
+ }
}
}
diff --git a/src/pdf/document.zig b/src/pdf/document.zig
index 1a3d29f..2c9a499 100644
--- a/src/pdf/document.zig
+++ b/src/pdf/document.zig
@@ -276,6 +276,22 @@ pub const Document = struct {
return try allocator.dupeZ(u8, std.mem.span(text_ptr.?));
}
+ /// One rectangle per Unicode character, in top-left page coordinates.
+ pub fn getTextLayout(self: Document, page_index: usize, allocator: std.mem.Allocator) Error![]layout.Rect {
+ if (page_index >= self.n_pages) return error.PageNotFound;
+ const page = c.poppler_document_get_page(self.doc, @intCast(page_index)) orelse return error.PageNotFound;
+ defer c.g_object_unref(page);
+ var rectangles: ?[*]c.PopplerRectangle = null;
+ var count: c_uint = 0;
+ _ = c.poppler_page_get_text_layout(page, &rectangles, &count);
+ defer if (rectangles) |rs| c.g_free(rs);
+ const rects = try allocator.alloc(layout.Rect, if (rectangles != null) count else 0);
+ if (rectangles) |rs| for (rects, rs[0..count]) |*dest, src| {
+ dest.* = .{ .x = src.x1, .y = src.y1, .w = src.x2 - src.x1, .h = src.y2 - src.y1 };
+ };
+ return rects;
+ }
+
pub fn findText(self: Document, page_index: usize, query: [:0]const u8, allocator: std.mem.Allocator) Error![]layout.Rect {
if (page_index >= self.n_pages) return error.PageNotFound;
const page = c.poppler_document_get_page(self.doc, @intCast(page_index)) orelse return error.PageNotFound;
diff --git a/src/pdf/print.c b/src/pdf/print.c
index 317ca02..de34b86 100644
--- a/src/pdf/print.c
+++ b/src/pdf/print.c
@@ -32,6 +32,7 @@ typedef struct {
GDBusConnection *bus;
// While a print dialog is open: its request object and Response watch.
gboolean busy;
+ gboolean preparing;
char *request;
guint response;
unsigned serial;
@@ -39,6 +40,12 @@ typedef struct {
gboolean closing;
} helper;
+// Responses may arrive before the method reply. Do not let an old reply
+// replace the subscription for the next phase or the next request.
+typedef struct { helper *h; unsigned serial; } pending_call;
+
+static void submit_print(helper *h, guint32 token);
+
static void reply(helper *h, char code) {
ssize_t n;
do n = write(h->peer, &code, 1);
@@ -59,9 +66,24 @@ static void on_response(GDBusConnection *bus, const char *sender, const char *pa
helper *h = data;
guint32 code = 2;
if (g_variant_is_of_type(params, G_VARIANT_TYPE("(ua{sv})"))) g_variant_get_child(params, 0, "u", &code);
- // 0 sent to the printer, 1 cancelled in the dialog, 2 failed.
- if (code == 2) reply(h, REPLY_FAILED);
- finish(h);
+ if (h->preparing) {
+ guint32 token = 0;
+ if (code == 0) {
+ GVariant *results = g_variant_get_child_value(params, 1);
+ g_variant_lookup(results, "token", "u", &token);
+ g_variant_unref(results);
+ }
+ finish(h);
+ // A dismissed settings dialog has not submitted a job. Portals may
+ // report either cancellation (1) or an otherwise ended interaction (2).
+ if (code == 0 && !h->closing) {
+ if (token) submit_print(h, token);
+ else reply(h, REPLY_FAILED);
+ }
+ } else {
+ if (code != 0 && code != 1) reply(h, REPLY_FAILED);
+ finish(h);
+ }
}
static void watch_request(helper *h, const char *path) {
@@ -84,14 +106,17 @@ static void on_closed(GDBusConnection *bus, gboolean vanished, GError *error, gp
}
static void on_called(GObject *source, GAsyncResult *result, gpointer data) {
- helper *h = data;
+ pending_call *call = data;
+ helper *h = call->h;
+ gboolean current = h->busy && call->serial == h->serial;
+ g_free(call);
GError *error = NULL;
GVariant *ret = g_dbus_connection_call_with_unix_fd_list_finish(G_DBUS_CONNECTION(source), NULL, result, &error);
if (!ret) {
fprintf(stderr, "rediwm-pdf: print portal: %s\n", error->message);
g_error_free(error);
// Already reported if the bus closed under the call.
- if (h->busy) {
+ if (current) {
reply(h, REPLY_UNAVAILABLE);
finish(h);
}
@@ -100,10 +125,29 @@ static void on_called(GObject *source, GAsyncResult *result, gpointer data) {
const char *handle = NULL;
g_variant_get(ret, "(&o)", &handle);
// A portal that ignored handle_token answers on a path of its own.
- if (h->busy && g_strcmp0(handle, h->request) != 0) watch_request(h, handle);
+ if (current && g_strcmp0(handle, h->request) != 0) watch_request(h, handle);
g_variant_unref(ret);
}
+static void begin_request(helper *h) {
+ // Subscribe before calling: the request path is known from the token.
+ char token[32];
+ snprintf(token, sizeof token, "rediwm_pdf%u", ++h->serial);
+ char *sender = g_strdup(g_dbus_connection_get_unique_name(h->bus) + 1);
+ g_strdelimit(sender, ".", '_');
+ char *path = g_strdup_printf(PORTAL_PATH "/request/%s/%s", sender, token);
+ watch_request(h, path);
+ g_free(path);
+ g_free(sender);
+ h->busy = TRUE;
+}
+
+static pending_call *new_call(helper *h) {
+ pending_call *call = g_new(pending_call, 1);
+ *call = (pending_call){ h, h->serial };
+ return call;
+}
+
static void start_print(helper *h) {
GError *error = NULL;
if (h->bus && g_dbus_connection_is_closed(h->bus)) g_clear_object(&h->bus);
@@ -119,6 +163,24 @@ static void start_print(helper *h) {
g_signal_connect(h->bus, "closed", G_CALLBACK(on_closed), h);
}
+ begin_request(h);
+ h->preparing = TRUE;
+ GVariantBuilder settings, page_setup, options;
+ g_variant_builder_init(&settings, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_init(&page_setup, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_add(&options, "{sv}", "handle_token",
+ g_variant_new_string(strrchr(h->request, '/') + 1));
+ const char *formats[] = { "pdf", NULL };
+ g_variant_builder_add(&options, "{sv}", "supported_output_file_formats",
+ g_variant_new_strv(formats, -1));
+ g_dbus_connection_call_with_unix_fd_list(
+ h->bus, PORTAL_NAME, PORTAL_PATH, "org.freedesktop.portal.Print", "PreparePrint",
+ g_variant_new("(ssa{sv}a{sv}a{sv})", "", h->title, &settings, &page_setup, &options),
+ G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, on_called, new_call(h));
+}
+
+static void submit_print(helper *h, guint32 token) {
// A new open file description, so the print system reads from offset 0
// independently of the parser's reads.
char proc[64];
@@ -131,25 +193,18 @@ static void start_print(helper *h) {
}
GUnixFDList *fds = g_unix_fd_list_new_from_array(&fd, 1);
- // Subscribe before calling: the request path is known from the token.
- char token[32];
- snprintf(token, sizeof token, "rediwm_pdf%u", ++h->serial);
- char *sender = g_strdup(g_dbus_connection_get_unique_name(h->bus) + 1);
- g_strdelimit(sender, ".", '_');
- char *path = g_strdup_printf(PORTAL_PATH "/request/%s/%s", sender, token);
- watch_request(h, path);
- g_free(path);
- g_free(sender);
- h->busy = TRUE;
+ begin_request(h);
+ h->preparing = FALSE;
GVariantBuilder options;
g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
- g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(token));
+ g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(strrchr(h->request, '/') + 1));
+ g_variant_builder_add(&options, "{sv}", "token", g_variant_new_uint32(token));
// RediWM has no xdg-foreign, so the dialog cannot name a parent window.
g_dbus_connection_call_with_unix_fd_list(
h->bus, PORTAL_NAME, PORTAL_PATH, "org.freedesktop.portal.Print", "Print",
g_variant_new("(ssha{sv})", "", h->title, 0, &options), G_VARIANT_TYPE("(o)"),
- G_DBUS_CALL_FLAGS_NONE, -1, fds, NULL, on_called, h);
+ G_DBUS_CALL_FLAGS_NONE, -1, fds, NULL, on_called, new_call(h));
g_object_unref(fds);
}
diff --git a/src/pdf/selection.zig b/src/pdf/selection.zig
new file mode 100644
index 0000000..3a950d1
--- /dev/null
+++ b/src/pdf/selection.zig
@@ -0,0 +1,42 @@
+//! Character ranges shared by selection hit testing, painting and copying.
+const std = @import("std");
+const layout = @import("layout.zig");
+
+pub const Range = struct {
+ start: usize,
+ end: usize,
+
+ pub fn text(self: Range, utf8: []const u8) []const u8 {
+ var it = (std.unicode.Utf8View.init(utf8) catch return "").iterator();
+ var index: usize = 0;
+ while (index < self.start) : (index += 1) _ = it.nextCodepointSlice() orelse return "";
+ const first = it.i;
+ while (index < self.end) : (index += 1) _ = it.nextCodepointSlice() orelse break;
+ return utf8[first..it.i];
+ }
+};
+
+/// Nearest insertion position. Zero-area rectangles (line breaks) are not
+/// pointer targets, but remain in the copied range between visible glyphs.
+pub fn position(rects: []const layout.Rect, pt: layout.Point) ?usize {
+ var best: ?usize = null;
+ var distance = std.math.inf(f64);
+ for (rects, 0..) |r, i| {
+ if (r.w <= 0 or r.h <= 0) continue;
+ const dx = pt.x - std.math.clamp(pt.x, r.x, r.x + r.w);
+ const dy = pt.y - std.math.clamp(pt.y, r.y, r.y + r.h);
+ const d = dx * dx + dy * dy;
+ if (d < distance) {
+ distance = d;
+ best = i + @as(usize, if (pt.x >= r.x + r.w / 2) 1 else 0);
+ }
+ }
+ return best;
+}
+
+pub fn between(rects: []const layout.Rect, from: layout.Point, to: layout.Point) ?Range {
+ const start = position(rects, from) orelse return null;
+ const end = position(rects, to) orelse return null;
+ if (start == end) return null;
+ return .{ .start = @min(start, end), .end = @max(start, end) };
+}
diff --git a/src/pdf/worker.zig b/src/pdf/worker.zig
index 1e0b4ac..a44c7b5 100644
--- a/src/pdf/worker.zig
+++ b/src/pdf/worker.zig
@@ -93,6 +93,7 @@ pub const PageSizesBatch = struct {
pub const ContentExtracted = struct {
page_index: usize,
text: ?[:0]u8,
+ text_rects: []const layout.Rect,
links: []document.Link,
};
@@ -129,6 +130,7 @@ pub const Result = struct {
.page_sizes_batch => |b| a.free(b.sizes),
.content_extracted => |ce| {
if (ce.text) |t| a.free(t);
+ a.free(ce.text_rects);
for (ce.links) |l| l.deinit(a);
a.free(ce.links);
},
@@ -619,12 +621,14 @@ pub const Worker = struct {
_ = c.api.pthread_mutex_unlock(&self.mutex);
const text = doc.getPageText(p_idx, a) catch null;
+ const text_rects = doc.getTextLayout(p_idx, a) catch &[_]layout.Rect{};
const links = doc.getPageLinks(p_idx, a) catch a.alloc(document.Link, 0) catch null;
_ = c.api.pthread_mutex_lock(&self.mutex);
if (self.stop or self.generation != current_gen) {
if (text) |t| a.free(t);
+ a.free(text_rects);
if (links) |ls| {
for (ls) |l| l.deinit(a);
a.free(ls);
@@ -639,9 +643,13 @@ pub const Worker = struct {
.payload = .{ .content_extracted = .{
.page_index = p_idx,
.text = text,
+ .text_rects = text_rects,
.links = ls,
} },
});
+ } else {
+ if (text) |t| a.free(t);
+ a.free(text_rects);
}
job.deinit();
},
diff --git a/src/pdf_tests.zig b/src/pdf_tests.zig
index 4de6678..1d8faa0 100644
--- a/src/pdf_tests.zig
+++ b/src/pdf_tests.zig
@@ -2,6 +2,7 @@ const std = @import("std");
const c = @import("pdf/c.zig");
const layout = @import("pdf/layout.zig");
const document = @import("pdf/document.zig");
+const selection = @import("pdf/selection.zig");
const cache = @import("pdf/cache.zig");
const worker = @import("pdf/worker.zig");
@@ -207,6 +208,12 @@ test "document: opening, page sizes, rendering and text extraction" {
try testing.expect(text0 != null);
try testing.expect(std.mem.indexOf(u8, text0.?, "Page 1 Test") != null);
+ const text_rects = try doc.getTextLayout(0, a);
+ defer a.free(text_rects);
+ try testing.expectEqual(try std.unicode.utf8CountCodepoints(text0.?), text_rects.len);
+ const range = selection.between(text_rects, .{ .x = text_rects[0].x, .y = text_rects[0].y + text_rects[0].h / 2 }, .{ .x = text_rects[3].x + text_rects[3].w, .y = text_rects[3].y + text_rects[3].h / 2 }).?;
+ try testing.expectEqualStrings("Page", range.text(text0.?));
+
// Text search
const matches = try doc.findText(0, "Test", a);
defer a.free(matches);
@@ -410,3 +417,23 @@ test "worker: background open, render, and result delivery" {
}
try testing.expect(got_render);
}
+
+test "selection: horizontal and reverse drags, multiple lines and Unicode byte boundaries" {
+ const rects = [_]layout.Rect{
+ .{ .x = 10, .y = 10, .w = 10, .h = 12 },
+ .{ .x = 20, .y = 10, .w = 10, .h = 12 },
+ .{ .x = 30, .y = 10, .w = 0, .h = 0 }, // newline
+ .{ .x = 10, .y = 30, .w = 10, .h = 12 },
+ .{ .x = 20, .y = 30, .w = 10, .h = 12 },
+ };
+ const from = layout.Point{ .x = 10, .y = 16 };
+ const to = layout.Point{ .x = 30, .y = 16 };
+ const forward = selection.between(&rects, from, to).?;
+ try testing.expectEqualStrings("é猫", forward.text("é猫\nAB"));
+ const reverse = selection.between(&rects, to, from).?;
+ try testing.expectEqualStrings("é猫", reverse.text("é猫\nAB"));
+ const multiline = selection.between(&rects, from, .{ .x = 30, .y = 36 }).?;
+ try testing.expectEqualStrings("é猫\nAB", multiline.text("é猫\nAB"));
+ try testing.expect(selection.between(&rects, from, from) == null);
+ try testing.expect(selection.between(&.{}, from, to) == null);
+}
diff --git a/tests/pdf_viewer.py b/tests/pdf_viewer.py
index 0dca9ff..45e2ac6 100755
--- a/tests/pdf_viewer.py
+++ b/tests/pdf_viewer.py
@@ -9,7 +9,7 @@ import time
import sys
import warnings
import cairo
-from PIL import Image
+from PIL import Image, ImageChops
from ipc_client import IPCClient, ROOT
from files_browser import wait_for
@@ -59,9 +59,12 @@ def generate_tall_pdf(path: Path):
class FakePrintPortal:
"""org.freedesktop.portal.Print on a private bus. Records each document it
- is handed, then answers the request with `response` (0 printed, 2 failed)."""
+ is handed. PreparePrint dismissal and submitted job failures are separate."""
XML = """<node><interface name="org.freedesktop.portal.Print">
+ <method name="PreparePrint"><arg type="s" direction="in"/><arg type="s" direction="in"/>
+ <arg type="a{sv}" direction="in"/><arg type="a{sv}" direction="in"/>
+ <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
<method name="Print"><arg type="s" direction="in"/><arg type="s" direction="in"/>
<arg type="h" direction="in"/><arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
</interface></node>"""
@@ -72,6 +75,8 @@ class FakePrintPortal:
self.GLib = GLib
self.jobs = []
self.response = 0
+ self.prepare_response = 0
+ self.dialogs = []
self.daemon = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"],
stdout=subprocess.PIPE, text=True)
self.address = self.daemon.stdout.readline().strip()
@@ -87,17 +92,30 @@ class FakePrintPortal:
self.loop = GLib.MainLoop()
threading.Thread(target=self.loop.run, daemon=True).start()
- def call(self, conn, sender, _path, _interface, _method, params, invocation):
- parent, title, index, options = params.unpack()
- fd = invocation.get_message().get_unix_fd_list().get(index)
- with os.fdopen(fd, "rb") as document:
- data = document.read()
+ def call(self, conn, sender, _path, _interface, method, params, invocation):
+ args = params.unpack()
+ options = args[-1]
request = "/org/freedesktop/portal/desktop/request/%s/%s" % (
sender[1:].replace(".", "_"), options.get("handle_token", "t"))
- invocation.return_value(self.GLib.Variant("(o)", (request,)))
- self.jobs.append({"parent": parent, "title": title, "data": data, "options": options})
+ results = {}
+ if method == "PreparePrint":
+ self.dialogs.append(args)
+ response = self.prepare_response
+ if response == 0:
+ results = {"token": self.GLib.Variant("u", 42)}
+ else:
+ parent, title, index, options = args
+ assert options.get("token") == 42, "Print must use the confirmed dialog token"
+ fd = invocation.get_message().get_unix_fd_list().get(index)
+ with os.fdopen(fd, "rb") as document:
+ data = document.read()
+ self.jobs.append({"parent": parent, "title": title, "data": data, "options": options})
+ response = self.response
conn.emit_signal(sender, request, "org.freedesktop.portal.Request", "Response",
- self.GLib.Variant("(ua{sv})", (self.response, {})))
+ self.GLib.Variant("(ua{sv})", (response, results)))
+ # Exercise a response arriving before the method reply, including the
+ # transition from PreparePrint to Print with another watch installed.
+ invocation.return_value(self.GLib.Variant("(o)", (request,)))
def close(self):
self.loop.quit()
@@ -245,6 +263,54 @@ def run(scale: int = 1):
assert any(r > 200 and b > 200 and g < 60 for n, (r, g, b) in canvas_colors), \
"Page 1 bottom edge is clipped on open"
+ # A horizontal drag selects characters, not the entire page.
+ # Test forward/reverse, rotation, and Escape clearing copy state.
+ box = ipc.get_window_debug(win["id"])["client_box"]
+ page_scale = min(4 / 3, (box["width"] - 180 - 48) / 300,
+ (box["height"] - 44 - 48) / 400)
+ page_x = box["x"] + 180 + (box["width"] - 180 - 300 * page_scale) / 2
+ page_y = box["y"] + 44 + 16
+ measure = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
+ measure.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
+ measure.set_font_size(16)
+
+ def clipboard():
+ return subprocess.check_output(["wl-paste", "--no-newline"],
+ env=dict(env, WAYLAND_DISPLAY=display), timeout=5).decode()
+
+ def select_word(reverse=False, copy=True, word="Page", rotated=False):
+ prefix = "" if word == "Page" else "Page 1 "
+ first = 30 + measure.text_extents(prefix)[4]
+ last = first + measure.text_extents(word)[4]
+ if rotated:
+ fitted = min(4 / 3, (box["width"] - 180 - 48) / 400,
+ (box["height"] - 44 - 48) / 300)
+ left = box["x"] + 180 + (box["width"] - 180 - 400 * fitted) / 2
+ points = [(left + (400 - 154) * fitted, page_y + first * fitted),
+ (left + (400 - 154) * fitted, page_y + last * fitted)]
+ else:
+ points = [(page_x + first * page_scale, page_y + 154 * page_scale),
+ (page_x + last * page_scale, page_y + 154 * page_scale)]
+ if reverse:
+ points.reverse()
+ ipc.move_cursor(round(points[0][0]), round(points[0][1]))
+ time.sleep(.08)
+ ipc.action("pointer_button", {"button": 272, "pressed": True})
+ ipc.move_cursor(round(points[1][0]), round(points[1][1]))
+ time.sleep(.08)
+ ipc.action("pointer_button", {"button": 272, "pressed": False})
+ if copy:
+ key(46, ctrl=True)
+ assert clipboard() == word, "drag copied more than the selected text"
+
+ select_word()
+ select_word(reverse=True)
+ select_word(word="Content", copy=False)
+ key(1)
+ # Copying after Escape must leave the clipboard unchanged.
+ key(46, ctrl=True)
+ assert clipboard() == "Page"
+
# Next page via keyboard shortcut (PageDown = keycode 109)
key(109)
time.sleep(0.3)
@@ -259,6 +325,9 @@ def run(scale: int = 1):
key(19)
time.sleep(0.3)
+ key(102, ctrl=True) # Start of the rotated document.
+ select_word(rotated=True)
+
# Close via Ctrl+W (keycode 17 = W)
key(17, ctrl=True)
wait_for(lambda: len(windows("rediwm-pdf")) == 0, "PDF viewer did not close")
@@ -287,6 +356,45 @@ def run(scale: int = 1):
key(25, ctrl=True)
wait_for(lambda: len(portal.jobs) == 2, "Ctrl+P did not print again")
assert portal.jobs[1]["data"] == job["data"]
+ def dialog_pixels():
+ shot = tmp / "print-dialog-check.png"
+ shot.unlink(missing_ok=True)
+ ipc.screenshot(path=str(shot))
+ with Image.open(shot) as im:
+ cx = box["x"] + box["width"] / 2
+ cy = box["y"] + box["height"] / 2
+ return im.convert("RGB").crop(tuple(round(v * scale) for v in
+ (cx - 210, cy - 85, cx + 210, cy + 85)))
+
+ baseline = dialog_pixels()
+ # Both cancellation and otherwise dismissed dialogs submit
+ # no job and leave the viewer usable without an error modal.
+ for response in (1, 2):
+ portal.prepare_response = response
+ dialogs = len(portal.dialogs)
+ key(25, ctrl=True)
+ wait_for(lambda: len(portal.dialogs) == dialogs + 1, "print dialog not requested")
+ time.sleep(.2)
+ assert len(portal.jobs) == 2, "dismissed print dialog submitted a job"
+ assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is None, \
+ "dismissing the print dialog displayed an error"
+ key(109)
+ expect_title("(2/2)")
+ key(104)
+ expect_title("(1/2)")
+ # A submitted job failure still displays an error dialog.
+ portal.prepare_response = 0
+ portal.response = 2
+ key(25, ctrl=True)
+ wait_for(lambda: len(portal.jobs) == 3, "failed job not submitted")
+ time.sleep(.2)
+ assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is not None, \
+ "a failed submitted job did not show an error"
+ key(1)
+ assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is None, \
+ "Escape did not dismiss the job error"
+ key(109)
+ expect_title("(2/2)")
key(17, ctrl=True)
wait_for(lambda: not viewer(), "printing viewer did not close")
assert print_proc.wait(timeout=5) == 0