Skip to content

Commit 7c34b99

Browse files
authored
native: restart a WSLg clipboard read when focus leaves its helper (#1849)
On WSLg the clipboard reads through the core Wayland data device, which only sends the selection to a focused surface, so OpenTUI maps a 1×1 helper surface for each read. When keyboard focus left that surface while the read waited, for example because another window took focus, the read failed with "Wayland clipboard protocol failed". The user sees an image paste that does nothing (part of anomalyco/opencode#49895). The read now maps a new helper, which takes focus again and gets the current selection, and reads that offer. It does this at most twice per acquisition, the same bound as the stale-image retry, so a compositor that keeps taking focus still ends the read as `failed`. A seat that loses its keyboard still fails the connection; the next read reconnects. Stacked on #1845, which retries an unsupported Wayland connection and tries the WSLg socket. A native test replays focus losses on the connection and checks the fresh offer and the bound. On WSLg, with a second clipboard client taking focus during reads, failed reads went from 3–11 of 48 to 0 of 48. Source +7 lines, tests +51.
1 parent 87562e7 commit 7c34b99

2 files changed

Lines changed: 69 additions & 11 deletions

File tree

‎packages/native/src/clipboard/host.zig‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,6 @@ pub const ShutdownStatus = enum(u8) {
7676

7777
const READ_MIME_COUNT_MAX: u32 = 64;
7878
const READ_MIME_ESSENCE_BYTES_MAX: u32 = 255;
79-
// Bounds within-operation restarts when a chosen offer's source vanishes mid-read.
80-
const WAYLAND_READ_STALE_RETRY_MAX: u8 = 2;
8179
const OPERATIONS_MAX_DEFAULT: u32 = 16;
8280
const PROVIDER_TRANSFERS_MAX_DEFAULT: u32 = 16;
8381
const ResultKind = enum { mime, data, diagnostic };
@@ -1063,7 +1061,7 @@ pub const Service = struct {
10631061
if (operation.result_mime.len > 0) operation.allocator.free(operation.result_mime);
10641062
operation.result_mime = &.{};
10651063
operation.transfer_data.clearRetainingCapacity();
1066-
if (operation.wayland_stale_retry_count < WAYLAND_READ_STALE_RETRY_MAX) {
1064+
if (operation.wayland_stale_retry_count < clipboard_wayland.READ_RETRY_MAX) {
10671065
operation.wayland_stale_retry_count += 1;
10681066
operation.wayland_barrier_serial = 0;
10691067
operation.preference_offset = 4;
@@ -2441,7 +2439,7 @@ test "clipboard Wayland BMP worker cancellation beats late conversion publicatio
24412439
try std.testing.expectEqual(@as(usize, 0), operation.result.len);
24422440
}
24432441

2444-
test "clipboard failed core selection progress releases operation focus" {
2442+
test "clipboard core selection releases focus on failure and skips data-control reads" {
24452443
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
24462444
var symbols: clipboard_linux.WaylandSymbols = undefined;
24472445
var wayland = clipboard_wayland.Connection.init(std.testing.allocator, &symbols, "", "", 1);
@@ -2472,6 +2470,12 @@ test "clipboard failed core selection progress releases operation focus" {
24722470
try std.testing.expectEqual(clipboard_linux.Mechanism.wayland, operation.mechanism.?);
24732471
try std.testing.expect(!operation.wayland_core_focus_acquired);
24742472
try std.testing.expectEqual(@as(u32, 1), wayland.core_focus_users);
2473+
2474+
// A data-control read takes no helper: it stays on Wayland and waits for its barrier.
2475+
wayland.core_data_device = false;
2476+
operation.wayland_barrier_serial = 1;
2477+
try std.testing.expectEqual(OperationStatus.pending, service.driveWaylandRead(&operation));
2478+
try std.testing.expectEqual(clipboard_linux.Mechanism.wayland, operation.mechanism.?);
24752479
}
24762480

24772481
test "clipboard drain closes the Wayland connection only when nothing needs it" {

‎packages/native/src/clipboard/wayland.zig‎

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ const PROVIDER_TRANSFER_IDLE_TIMEOUT_NS = 30 * std.time.ns_per_s;
2121
// One drive call dispatches at most this many queued events, enough to settle a
2222
// selection-change backlog in one call while keeping per-call work bounded.
2323
const DISPATCH_EVENTS_PER_DRIVE_MAX = 64;
24+
// Bounds the restarts of a read whose offer went stale: its source vanished, or focus left the helper.
25+
pub const READ_RETRY_MAX: u8 = 2;
2426

2527
pub const Progress = enum { pending, ready, unsupported, failed };
2628
pub const SelectionResult = enum { ok, pending, committed, unsupported, failed };
@@ -134,6 +136,7 @@ pub const Connection = struct {
134136
core_focus_lost: bool = false,
135137
core_selection_seen: bool = false,
136138
core_focus_users: u32 = 0,
139+
core_focus_restart_count: u8 = 0,
137140
offers: [MAX_OFFERS]Offer = undefined,
138141
offer_count: u8 = 0,
139142
clipboard_offer: ?*WlProxy = null,
@@ -323,8 +326,8 @@ pub const Connection = struct {
323326
std.debug.assert(self.core_focus_users < std.math.maxInt(u32));
324327
self.core_focus_users += 1;
325328
if (self.core_focus_users > 1) return .pending;
326-
self.core_selection_seen = false;
327-
self.core_focus_lost = false;
329+
std.debug.assert(!self.core_focus_lost and !self.core_selection_seen);
330+
self.core_focus_restart_count = 0;
328331
if (self.clipboard_offer) |offer| self.removeOffer(offer);
329332
self.clipboard_offer = null;
330333
if (!self.createCoreHelper()) {
@@ -334,11 +337,18 @@ pub const Connection = struct {
334337
return .pending;
335338
}
336339

337-
pub fn coreSelectionProgress(self: *const Connection) Progress {
340+
// Focus can leave the helper while a read waits (WSLg), which invalidates its offer. A new
341+
// helper takes focus again, and the compositor sends it the current selection.
342+
pub fn coreSelectionProgress(self: *Connection) Progress {
338343
if (!self.core_data_device) return .unsupported;
339344
if (self.phase == .failed) return .failed;
340-
if (self.core_focus_users == 0 or self.helper_surface == null) return .failed;
341-
if (self.core_focus_lost) return .failed;
345+
std.debug.assert(self.core_focus_users > 0);
346+
if (self.core_focus_lost and self.core_focus_restart_count < READ_RETRY_MAX) {
347+
self.core_focus_restart_count += 1;
348+
self.destroyCoreHelper();
349+
_ = self.createCoreHelper();
350+
}
351+
if (self.helper_surface == null or self.core_focus_lost) return .failed;
342352
return if (self.core_focus_entered and self.core_selection_seen) .ready else .pending;
343353
}
344354

@@ -1044,7 +1054,6 @@ pub const Connection = struct {
10441054
seat.capabilities = capabilities;
10451055
const has_keyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD != 0;
10461056
if (self.core_data_device and self.bound_seat_global == seat.global_name and had_keyboard and !has_keyboard) {
1047-
self.core_focus_lost = true;
10481057
_ = self.fail(.protocol);
10491058
}
10501059
return;
@@ -1131,7 +1140,7 @@ pub const Connection = struct {
11311140

11321141
fn keyboardLeave(data: ?*anyopaque, _: ?*WlProxy, _: u32, surface: ?*WlProxy) callconv(.c) void {
11331142
const self: *Connection = @ptrCast(@alignCast(data.?));
1134-
if (surface != self.helper_surface) return;
1143+
if (surface == null or surface != self.helper_surface) return;
11351144
self.core_focus_entered = false;
11361145
self.core_selection_seen = false;
11371146
self.core_focus_lost = true;
@@ -1967,6 +1976,10 @@ test "Wayland core focus lifecycle rejects stale and unfocused offers" {
19671976
Connection.deviceSelection(&connection, null, offer);
19681977
try std.testing.expectEqual(@as(u8, 0), connection.offer_count);
19691978
try std.testing.expect(connection.clipboard_offer == null);
1979+
// A leave for the destroyed helper arrives with a nil surface and must not mark the next read.
1980+
connection.core_focus_lost = false;
1981+
Connection.keyboardLeave(&connection, null, 1, null);
1982+
try std.testing.expect(!connection.core_focus_lost);
19701983

19711984
connection.core_focus_entered = true;
19721985
connection.core_focus_lost = false;
@@ -2014,6 +2027,47 @@ test "Wayland core selection becomes ready after focus and selection in either o
20142027
try std.testing.expectEqual(Progress.ready, connection.coreSelectionProgress());
20152028
}
20162029

2030+
test "Wayland core read restarts after focus loss a bounded number of times" {
2031+
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
2032+
const Fake = struct {
2033+
var helpers: u8 = 0;
2034+
fn marshal(proxy: *WlProxy, opcode: u32, _: [*]WlArgument, _: ?*const WlInterface, _: u32) callconv(.c) ?*WlProxy {
2035+
if (@intFromPtr(proxy) == 5 and opcode == 0) helpers += 1;
2036+
return @ptrFromInt(4);
2037+
}
2038+
};
2039+
var symbols = testSymbols();
2040+
symbols.wl_proxy_marshal_array_constructor_versioned = Fake.marshal;
2041+
var connection = testReadyConnection(&symbols, .{ .result = 0, .errno = .SUCCESS });
2042+
defer connection.deinit();
2043+
connection.core_data_device = true;
2044+
connection.compositor = @ptrFromInt(5);
2045+
connection.shell = @ptrFromInt(6);
2046+
connection.shm = @ptrFromInt(7);
2047+
// The rows share the connection, so each acquisition must start with the full budget.
2048+
for ([_]u8{ 0, READ_RETRY_MAX, READ_RETRY_MAX + 1 }) |losses| {
2049+
errdefer std.debug.print("losses: {d}\n", .{losses});
2050+
Fake.helpers = 0;
2051+
try std.testing.expectEqual(Progress.pending, connection.acquireCoreSelection());
2052+
var progress = Progress.pending;
2053+
for (0..losses + 1) |loss| {
2054+
// Each focus brings a fresh offer after a replaced selection; a leave invalidates it.
2055+
const offer: *WlProxy = @ptrFromInt(0x100 + loss);
2056+
Connection.keyboardEnter(&connection, null, 0, connection.helper_surface, null);
2057+
Connection.deviceDataOffer(&connection, null, offer);
2058+
Connection.deviceSelection(&connection, null, null);
2059+
Connection.deviceSelection(&connection, null, offer);
2060+
if (loss < losses) Connection.keyboardLeave(&connection, null, 0, connection.helper_surface);
2061+
progress = connection.coreSelectionProgress();
2062+
}
2063+
const restarted = losses <= READ_RETRY_MAX;
2064+
try std.testing.expectEqual(if (restarted) Progress.ready else Progress.failed, progress);
2065+
try std.testing.expectEqual(@min(losses, READ_RETRY_MAX) + 1, Fake.helpers);
2066+
if (restarted) try std.testing.expectEqual(0x100 + @as(usize, losses), @intFromPtr(connection.currentOffer(false).?.proxy));
2067+
connection.releaseCoreSelection();
2068+
}
2069+
}
2070+
20172071
test "Wayland bound core seat keyboard loss fails active and future acquisitions" {
20182072
const seat_proxy: *WlProxy = @ptrFromInt(1);
20192073
var connection: Connection = undefined;

0 commit comments

Comments
 (0)