1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
|
//! Panes between windows, as a browser's tabs go between its windows. A
//! pane's grip, or a column's, released past the window's edge carries it
//! out: dumped alone (`Carried`, each pane as dump.savePane makes it), it
//! opens in a new window of its own, `pardes-gui -l` of that dump. The pane
//! closes here only once
//! the new window answers on its 9P socket, so its text is never in no
//! window at all; a failed handover leaves it where it was, and a pane
//! edited while it was on its way stays here too (both then have it).
//! Let go over another pardes window, the pane goes there instead: the
//! worker finds the window under the pointer among the registry's sessions
//! (each says in /status whether the pointer is over it) and writes it
//! `adopt <dump>` (ninep/ctl.zig), which takes the pane in where the pointer
//! is (`adopt`) before the write is answered.
//!
//! The core only dumps, and closes or keeps when told (`finish`); the host
//! writes the dump, and its worker (`carry`, an io.concurrent job on the
//! shell's Io, as every background job is) spawns the window and waits for
//! it, posting how it went into host_io.Inbox.
const Handover = @This();
const std = @import("std");
const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const layout = @import("layout.zig");
const dump = @import("dump.zig");
const ninep_io = @import("9p_io.zig");
const panes = @import("panes.zig");
const tagline = @import("tagline.zig");
const walk = @import("walk.zig");
const Pardes = pardes.Pardes;
const MAX_PANES = pardes.MAX_PANES;
const libc = std.c;
/// What a grip carries out of its window: one pane with the panes attached
/// to it, or a whole column.
pub const Kind = enum { pane, column };
/// A handover's dump: `carried_magic`, then this.
const Carried = struct {
kind: Kind,
/// A carried column's tag.
tag: ?[]const u8 = null,
/// Each pane as dump.savePane makes it, top to bottom.
panes: []const []const u8,
weights: []const f32,
/// Which of them each one is attached to (layout.zig, "Attached panes").
owners: []const ?u32,
};
pub const carried_magic = "pardes-carried\n";
/// The handover in flight, one at a time: its number, what it carries,
/// and each carried pane's serial and revision as it was dumped.
seq: u32 = 0,
flying: bool = false,
carried: Kind = .pane,
column_serial: u32 = 0,
count: usize = 0,
serials: [MAX_PANES]u32 = @splat(0),
revisions: [MAX_PANES]u32 = @splat(0),
/// The dump the host sends, gpa-owned while the handover flies.
bytes: ?[]u8 = null,
/// The carrier (`carry`) while it flies, on the shell's Io: awaited when
/// its answer comes in (`finish`), cancelled at the session's end.
task: ?struct { future: std.Io.Future(void), io: std.Io } = null,
/// The dump in flight and its carrier are the host's errand, not the
/// session's (src/walk.zig).
pub const replica = .{ .authority = .{ "bytes", "task" } };
pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void {
// The session ends with the carrier still out: it stops at its next
// wait (a 9P call it is in finishes first, within its own budget).
if (h.task) |t| {
h.task = null;
var future = t.future;
pardes.turn.yield();
future.cancel(t.io);
pardes.turn.back();
}
if (h.bytes) |b| gpa.free(b);
h.bytes = null;
}
/// Pane slot `at` (with what is attached to it, or alone when it is itself
/// an attachment), or column `at`, released past the window's edge: dumped,
/// and the host asked to carry it. Only text panes travel: a terminal's
/// shell is this process's child and would die with the pane here.
pub fn begin(h: *Handover, p: *Pardes, carried: Kind, at: usize) void {
var ids: [MAX_PANES]usize = undefined;
var n: usize = 0;
switch (carried) {
.pane => {
const f = layout.findPane(p, at) orelse return;
const end = if (layout.ownerOf(p, at) == null) layout.groupEnd(p, f.col, f.idx) else f.idx + 1;
for (p.col_panes[f.col][f.idx..end]) |id| {
ids[n] = id;
n += 1;
}
},
.column => {
if (at >= p.ncol or p.col_n[at] == 0) return;
for (p.col_panes[at][0..p.col_n[at]]) |id| {
ids[n] = id;
n += 1;
}
},
}
const said = if (carried == .pane) at else ids[0];
if (h.flying) return p.setMessage(said, "a pane is already on its way to another window");
for (ids[0..n]) |id| {
const pane = p.panes[id] orelse return;
if (pane.file == null) return p.setMessage(said, if (pane.isTerminal())
"a terminal stays in its window: its shell is this window's child"
else
"only text panes go to another window, for now");
}
const bytes = dumpCarried(p, carried, at, ids[0..n]) catch |err| return p.reportError(said, "handover", err);
h.deinit(p.gpa);
h.bytes = bytes;
h.seq +%= 1;
h.flying = true;
h.carried = carried;
h.column_serial = if (carried == .column) layout.columnSerial(p, at) else 0;
h.count = n;
for (ids[0..n], 0..) |id, i| {
const pane = p.panes[id].?;
h.serials[i] = pane.serial;
h.revisions[i] = pane.file.?.revision;
}
p.setMessage(said, if (carried == .pane) "to a new window…" else "the column, to a new window…");
p.emit(.{ .hand_over = .{ .seq = h.seq } });
}
/// How the host's handover `seq` went: taken by `to` (failure null), or
/// not. Taken, its panes close here, unless one was edited since it was
/// dumped: that one stays, so neither window loses the edit.
pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]const u8) void {
if (!h.flying or seq != h.seq) return;
h.flying = false;
// Its answer is the carrier's last word: what is left of it is freeing.
if (h.task) |t| {
h.task = null;
var future = t.future;
pardes.turn.yield();
future.await(t.io);
pardes.turn.back();
}
h.deinit(p.gpa);
var buf: [320]u8 = undefined;
if (failure) |why| {
const at = p.paneBySerial(h.serials[0]) orelse p.active;
return p.reportFailure(at, std.fmt.bufPrint(&buf, "handover: {s}; the pane stays here", .{why}) catch "handover failed; the pane stays here");
}
var kept: usize = 0;
// Moved, not closed: the other window has them now (Store.away).
p.store.away = true;
defer p.store.away = false;
for (h.serials[0..h.count], h.revisions[0..h.count]) |serial, revision| {
const id = p.paneBySerial(serial) orelse continue; // closed with its owner
const pane = p.panes[id].?;
if (pane.file == null or pane.file.?.revision != revision) {
// Out of its group, or the owner's close would take it along.
pane.attached_to = null;
kept += 1;
continue;
}
p.removePane(id, null) catch |err| {
kept += 1;
p.reportError(id, "handover", err);
};
}
if (h.carried == .column) if (layout.columnBySerial(p, h.column_serial)) |c| {
if (p.col_n[c] == 0 and p.ncol > 1) layout.dropColumn(p, c);
};
layout.compute(p);
p.setMessage(p.active, if (kept == 0)
std.fmt.bufPrint(&buf, "moved to {s}", .{to}) catch "moved"
else
std.fmt.bufPrint(&buf, "copied to {s}; edited on the way, kept here too", .{to}) catch "copied");
}
/// The dump of panes `ids` (gpa's), carried as `kind` from column `at`'s
/// (a pane's, `at` is its slot).
fn dumpCarried(p: *Pardes, kind: Kind, at: usize, ids: []const usize) ![]u8 {
const arena = p.scratch.allocator();
const bytes = try arena.alloc([]const u8, ids.len);
const weights = try arena.alloc(f32, ids.len);
const owners = try arena.alloc(?u32, ids.len);
for (ids, 0..) |id, i| {
const pane = p.panes[id].?;
bytes[i] = try dump.savePane(arena, pane, false);
weights[i] = pane.vweight;
const owner = layout.ownerOf(p, id);
owners[i] = if (owner) |o| if (std.mem.indexOfScalar(usize, ids, o)) |k| @intCast(k) else null else null;
}
const value: Carried = .{
.kind = kind,
.tag = if (kind == .column) p.col_tags[at].own else null,
.panes = bytes,
.weights = weights,
.owners = owners,
};
const body = try walk.save(Carried, arena, &value);
return std.mem.concat(p.gpa, u8, &.{ carried_magic, body });
}
// ---- the receiving window ----
/// A carried dump (`begin`'s) taken into this window where the pointer is:
/// a pane under the pane the pointer is over, out of that pane's rows
/// alone; a column beside the column the pointer is over, out of its width
/// alone. Every other pane stays where it was. Answers the slot of the
/// first pane taken; on an error nothing of it is left here.
pub fn adopt(p: *Pardes, bytes: []const u8) !usize {
if (!std.mem.startsWith(u8, bytes, carried_magic)) return error.NotCarried;
var arena: std.heap.ArenaAllocator = .init(p.gpa);
defer arena.deinit();
const st = try walk.load(Carried, arena.allocator(), bytes[carried_magic.len..], null);
const carried = st.kind;
if (st.panes.len == 0 or st.weights.len != st.panes.len or st.owners.len != st.panes.len) return error.NotCarried;
// Where the pointer is, else the middle of the pane with the keyboard.
layout.compute(p);
const here = p.rects[p.active];
const x = if (p.pointer_inside) p.hover_col else here.x + here.w / 2;
const y = if (p.pointer_inside) p.hover_row else here.y + here.h / 2;
var slots: [MAX_PANES]usize = undefined;
var n: usize = 0;
errdefer for (slots[0..n]) |slot| p.removePane(slot, null) catch {};
for (st.panes) |one| {
const slot = p.freeSlot() orelse return error.TooManyPanes;
const pane = try dump.loadPane(p, slot, one);
slots[n] = slot;
n += 1;
if (pane.file == null) return error.NotText;
}
// An attachment names its owner by its place in the dump.
for (st.owners, 0..) |owner, k| {
const at = owner orelse continue;
if (at >= n) continue;
p.panes[slots[k]].?.attached_to = p.panes[slots[at]].?.serial;
}
const tc = layout.targetColumn(p, x);
var heights: [MAX_PANES]u16 = @splat(0);
if (carried == .column or p.ncol == 0) {
const c = if (p.ncol == 0) layout.insertColumn(p, 0, false) else layout.insertColumn(p, tc, x < p.col_x[tc] + p.col_w[tc] / 2);
const col = c orelse return error.NoRoom;
if (carried == .column) if (st.tag) |tag| {
p.col_tags[col].own = try p.gpa.dupe(u8, tag);
};
for (slots[0..n], 0..) |slot, k| {
layout.insert(p, col, k, slot);
p.panes[slot].?.vweight = st.weights[k];
}
p.active = slots[0];
p.setActiveColumn(col);
p.sync();
return slots[0];
}
for (0..p.ncol) |c| for (p.col_panes[c][0..p.col_n[c]]) |id| {
heights[id] = p.rects[id].h;
};
// The group under the pointer (a pane with what is attached to it): the
// new panes go under all of it, out of its owner's rows.
var after: usize = p.col_n[tc];
var root: ?usize = null;
var k: usize = 0;
while (k < p.col_n[tc]) {
const end = layout.groupEnd(p, tc, k);
const first = p.col_panes[tc][k];
const last = p.col_panes[tc][end - 1];
root = first;
after = end;
if (y < p.rects[last].y + p.rects[last].h) break;
k = end;
}
if (root) |owner| {
const r = p.rects[owner];
// Down to the pointer's row; let go over one of its attachments,
// half of it.
const keeps = @max(layout.minRows(p, owner), if (y >= r.y and y < r.y + r.h) (y - r.y) + 1 else r.h / 2);
const give = heights[owner] -| keeps;
if (give < 1 + layout.min_body_rows) return error.NoRoom;
heights[owner] = keeps;
// The carried share what was given as they shared their old rows.
var total: f32 = 0;
for (st.weights) |w| total += w;
var left = give;
for (slots[0..n], 0..) |slot, j| {
const share: u16 = if (j + 1 == n) left else @intFromFloat(@max(1, @floor(@as(f32, @floatFromInt(give)) * st.weights[j] / @max(total, 1))));
heights[slot] = @min(share, left);
left -|= share;
}
} else for (slots[0..n]) |slot| {
heights[slot] = 1;
}
for (slots[0..n], 0..) |slot, j| layout.insert(p, tc, after + j, slot);
layout.setColumnWeights(p, tc, &heights);
p.active = slots[0];
p.setActiveColumn(tc);
p.sync();
return slots[0];
}
// ---- the host's half: a worker that carries the dump ----
/// A handover for a worker: the dump's file, and the window's geometry for
/// a new one. The worker owns it and frees it with `gpa`.
pub const Job = struct {
gpa: std.mem.Allocator,
seq: u32,
path: [:0]u8,
/// `--geometry=` for a new window: `WxH`, `+X+Y` when the host can place it.
geometry: [64]u8 = undefined,
geometry_len: usize = 0,
/// Where it says how it went: (seq, true, where) or (seq, false, why);
/// the words are borrowed for the call.
post: *const fn (ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void,
post_ctx: ?*anyopaque,
/// This window's 9P socket, which its registry entry links to: the one
/// window never asked whether the pointer is over it.
own: [512]u8 = undefined,
own_len: usize = 0,
};
/// The file a handover's dump goes in: the runtime directory, the user's
/// alone, else the dump directory. Null-terminated, `gpa`'s.
pub fn dumpPath(gpa: std.mem.Allocator, seq: u32) ![:0]u8 {
var dir_buf: [1024]u8 = undefined;
const dir: []const u8 = if (libc.getenv("XDG_RUNTIME_DIR")) |x| std.mem.span(x) else dump.defaultDirectory(&dir_buf) orelse return error.NoDirectory;
return std.fmt.allocPrintSentinel(gpa, "{s}/pardes-handover-{d}-{d}.dump", .{ dir, libc.getpid(), seq }, 0);
}
/// Runs the handover's carrier on `io` (io.concurrent), kept in `h.task`
/// until its answer: it owns `job`, and removes the dump's file once
/// someone has it, or nobody will.
pub fn start(h: *Handover, io: std.Io, job: *Job) !void {
h.task = .{ .future = try io.concurrent(carry, .{ io, job }), .io = io };
}
fn carry(io: std.Io, job: *Job) void {
// Cancelled while a new window is coming up: it may still be reading
// the dump, so the file stays for it.
var for_child = false;
defer {
if (!for_child) _ = libc.unlink(job.path);
job.gpa.free(job.path);
job.gpa.destroy(job);
}
var words: [256]u8 = undefined;
// Let go over another window: it takes the dump in, where the pointer
// is, before its `adopt` answers. A refusal (no room there, too many
// panes) leaves the pane here: no new window instead, the user aimed.
var dial_buf: [512]u8 = undefined;
const under = windowUnderPointer(io, job, &dial_buf) catch return;
if (under) |dial| {
var line_buf: [600]u8 = undefined;
const line = std.fmt.bufPrint(&line_buf, "adopt {s}\n", .{job.path}) catch return job.post(job.post_ctx, job.seq, false, "its dump's name is too long");
const name = std.fs.path.basename(dial);
if (ninep_io.Client.write(job.gpa, dial, "ctl", line)) {
return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "pardes/{s}", .{name}) catch "another window");
} else |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "pardes/{s} would not take it: {s}", .{
name, if (err == error.Remote) ninep_io.Client.lastSaid() else @errorName(err),
}) catch "the window would not take it");
}
const pid = spawnWindow(job) catch |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: {s}", .{@errorName(err)}) catch "no new window");
// Up when its registry entry answers: it read the dump before it
// listened (gui.localSession), so the file is no longer needed.
var entry_buf: [512]u8 = undefined;
const run = libc.getenv("XDG_RUNTIME_DIR") orelse "";
const entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ std.mem.span(run), pid }) catch "";
var waited: u32 = 0;
while (waited < 15_000) : (waited += 50) {
if (libc.kill(pid, @enumFromInt(0)) != 0)
return job.post(job.post_ctx, job.seq, false, "the new window ended before it was up");
if (ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256)) |status| {
job.gpa.free(status);
return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "a new window (pardes/{d})", .{pid}) catch "a new window");
} else |_| {}
io.sleep(.fromMilliseconds(50), .awake) catch {
for_child = true;
return;
};
}
_ = libc.kill(pid, libc.SIG.TERM);
job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s");
}
extern "c" fn readdir(dir: *libc.DIR) ?*libc.dirent;
/// The registry entry of the window the pointer was let go over, asked of
/// every window by its `status` (`pointer in`): Wayland tells no client
/// where any window is, only whether the pointer is over its own, and the
/// window let go over learns it a moment after the release (the grab ends,
/// then it is entered), so it is asked a few times. None answering with a
/// pointer line at all (no other window, or an older pardes) ends it at once.
fn windowUnderPointer(io: std.Io, job: *Job, out: *[512]u8) std.Io.Cancelable!?[]const u8 {
const run = std.mem.span(libc.getenv("XDG_RUNTIME_DIR") orelse return null);
var reg_buf: [512:0]u8 = undefined;
const reg = std.fmt.bufPrintSentinel(®_buf, "{s}/9p/pardes", .{run}, 0) catch return null;
const own = job.own[0..job.own_len];
var round: u32 = 0;
while (round < 10) : (round += 1) {
if (round > 0) try io.sleep(.fromMilliseconds(40), .awake);
const dir = libc.opendir(reg) orelse return null;
defer _ = libc.closedir(dir);
var windows: usize = 0;
while (readdir(dir)) |ent| {
const name = std.mem.sliceTo(&ent.name, 0);
if (name.len == 0 or name[0] == '.') continue;
const entry = std.fmt.bufPrintSentinel(out, "{s}/{s}", .{ reg, name }, 0) catch continue;
var link: [512]u8 = undefined;
const n = libc.readlink(entry, &link, link.len);
if (n > 0 and std.mem.eql(u8, link[0..@intCast(n)], own)) continue;
const status = ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256) catch continue;
defer job.gpa.free(status);
if (std.mem.indexOf(u8, status, "\npointer ") == null) continue;
windows += 1;
if (std.mem.indexOf(u8, status, "\npointer in\n") != null) return entry;
}
if (windows == 0) return null;
}
return null;
}
/// This program again, `-l` the dump: a new window, in a session of its own
/// (setsid) and not this one's child (forked twice), so it outlives this
/// window and leaves no zombie. Answers its pid.
fn spawnWindow(job: *Job) !libc.pid_t {
if (comptime builtin.os.tag != .linux) return error.Unsupported;
var exe_buf: [4096:0]u8 = undefined;
const n = libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len - 1);
if (n <= 0) return error.NoExecutable;
exe_buf[@intCast(n)] = 0;
var geometry_z: [80:0]u8 = undefined;
const geometry = try std.fmt.bufPrintSentinel(&geometry_z, "--geometry={s}", .{job.geometry[0..job.geometry_len]}, 0);
const argv = [_:null]?[*:0]const u8{ &exe_buf, "-l", job.path, if (job.geometry_len > 0) geometry else null, null };
var fds: [2]c_int = undefined;
if (libc.pipe(&fds) != 0) return error.NoPipe;
defer _ = libc.close(fds[0]);
const first = libc.fork();
if (first < 0) {
_ = libc.close(fds[1]);
return error.NoFork;
}
if (first == 0) {
// Only async-signal-safe calls between fork and exec.
_ = libc.setsid();
const second = libc.fork();
if (second == 0) {
_ = libc.close(fds[1]);
_ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ));
libc._exit(127);
}
_ = libc.write(fds[1], std.mem.asBytes(&second), @sizeOf(libc.pid_t));
libc._exit(0);
}
_ = libc.close(fds[1]);
_ = libc.waitpid(first, null, 0);
var pid: libc.pid_t = 0;
if (libc.read(fds[0], std.mem.asBytes(&pid), @sizeOf(libc.pid_t)) != @sizeOf(libc.pid_t) or pid <= 0) return error.NoFork;
return pid;
}
// ---- tests ----
/// Two text panes in one column, the lower one `/test.txt`'s twin made by
/// New, and the grip of pane `id` let go past the window's edge.
fn twoPanes(gpa: std.mem.Allocator) !*Pardes {
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30 });
errdefer p.deinit();
_ = try p.setTestFile("alpha\nbeta\n");
try std.testing.expect(p.executeBuiltinLine(p.active, "New"));
p.sync();
return p;
}
fn releaseOutside(p: *Pardes, id: usize) void {
const r = p.rects[id];
p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x, .row = p.tagTop(p.panes[id].?, r) } });
p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = p.screen_w - 1, .row = r.y + 1 } });
p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = p.screen_w - 1, .row = r.y + 1, .outside = true } });
}
test "a grip let go past the window's edge dumps its pane alone, and closes it only once another window has it" {
const p = try twoPanes(std.testing.allocator);
defer p.deinit();
const f = layout.findPane(p, 0).?;
try std.testing.expect(p.col_n[f.col] == 2);
const other = p.col_panes[f.col][1 - f.idx];
const before = p.rects[other];
releaseOutside(p, 0);
// Dumped and asked for; nothing moved yet.
try std.testing.expect(p.handover.flying);
try std.testing.expect(p.drag == .none);
try std.testing.expect(p.panes[0] != null);
try std.testing.expectEqual(before, p.rects[other]);
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const carried = try walk.load(Carried, arena.allocator(), p.handover.bytes.?[carried_magic.len..], null);
try std.testing.expectEqual(Kind.pane, carried.kind);
try std.testing.expectEqual(@as(usize, 1), carried.panes.len);
const pane = try walk.load(pardes.Pane, arena.allocator(), carried.panes[0], null);
try std.testing.expectEqualStrings("/test.txt", pane.file.?.path);
// A second one waits for the first.
releaseOutside(p, other);
try std.testing.expect(p.panes[other] != null);
// Refused (no window took it): it stays.
p.update(.{ .handed = .{ .seq = p.handover.seq, .failure = "no window" } });
try std.testing.expect(!p.handover.flying);
try std.testing.expect(p.panes[0] != null);
// Taken: it closes, and the pane beside it takes its rows (Del's rule).
releaseOutside(p, 0);
const serial = p.panes[0].?.serial;
p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } });
try std.testing.expect(p.paneBySerial(serial) == null);
// Open in the other window, so not one of this session's closed panes
// (Store.zig): Panes does not offer it back here.
try std.testing.expect(p.store.closedBySerial(serial) == null);
p.sync();
try std.testing.expectEqual(@as(usize, 1), p.col_n[layout.findPane(p, other).?.col]);
}
test "a pane edited while it is on its way to another window stays here too" {
const p = try twoPanes(std.testing.allocator);
defer p.deinit();
releaseOutside(p, 0);
const pane = p.panes[0].?;
pane.file.?.revision += 1; // an edit after the dump
p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } });
try std.testing.expect(p.panes[0] == pane);
}
test "a terminal's grip let go past the edge stays: its shell is this window's" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30, .shells = 3 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 100, .rows = 30 } });
const id = p.col_panes[1][0];
try std.testing.expect(p.panes[id].?.isTerminal());
releaseOutside(p, id);
try std.testing.expect(!p.handover.flying);
try std.testing.expect(p.panes[id] != null);
}
test "a pane let go over another window goes under the pane the pointer is over, out of its rows alone, unsaved text and all" {
const gpa = std.testing.allocator;
const from = try twoPanes(gpa);
defer from.deinit();
_ = pardes.ctlfs.pane.spliceBody(from, from.panes[0].?, 0, 0, "unsaved ").?;
releaseOutside(from, 0);
const to = try twoPanes(gpa);
defer to.deinit();
to.sync();
const before = to.rects;
const c = layout.findPane(to, 0).?.col;
const upper = to.col_panes[c][0];
const lower = to.col_panes[c][1];
// The pointer over the upper pane, six rows into it.
to.pointer_inside = true;
to.hover_col = to.rects[upper].x + 5;
to.hover_row = to.rects[upper].y + 6;
const id = try adopt(to, from.handover.bytes.?);
to.sync();
const pane = to.panes[id].?;
try std.testing.expectEqualStrings("unsaved alpha\nbeta\n", pane.file.?.content);
try std.testing.expect(tagline.dirty(pane));
try std.testing.expectEqual(upper, to.col_panes[c][0]);
try std.testing.expectEqual(id, to.col_panes[c][1]);
try std.testing.expectEqual(lower, to.col_panes[c][2]);
// The pane under the pointer keeps its top and gives its rows below
// the pointer; the new one is just there; every other pane is where it was.
try std.testing.expectEqual(before[upper].y, to.rects[upper].y);
try std.testing.expectEqual(@as(u16, 7), to.rects[upper].h);
try std.testing.expectEqual(before[upper].y + 7, to.rects[id].y);
try std.testing.expectEqual(before[upper].h - 7, to.rects[id].h);
for (to.panes, 0..) |slot, k| if (slot != null and k != upper and k != id)
try std.testing.expectEqual(before[k], to.rects[k]);
try std.testing.expectEqual(id, to.active);
}
test "a column let go over another window goes beside the column the pointer is over, out of its width alone" {
const gpa = std.testing.allocator;
const from = try twoPanes(gpa);
defer from.deinit();
const r = from.rects[0];
const c = layout.findPane(from, 0).?.col;
from.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = from.col_x[c], .row = from.topBarHeight() } });
from.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = from.screen_w - 1, .row = r.y } });
from.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = from.screen_w - 1, .row = r.y, .outside = true } });
try std.testing.expect(from.handover.flying);
try std.testing.expectEqual(Kind.column, from.handover.carried);
const to = try Pardes.init(gpa, .{ .tty_only = true, .cols = 120, .rows = 30 });
defer to.deinit();
_ = try to.setTestFile("x\n");
try std.testing.expect(to.executeBuiltinLine(to.active, "Newcol"));
to.sync();
const ncol = to.ncol;
const widths = to.col_w;
const xs = to.col_x;
// Over the right half of the last column: the new one goes after it.
to.pointer_inside = true;
to.hover_col = to.col_x[ncol - 1] + to.col_w[ncol - 1] - 2;
to.hover_row = 10;
const id = try adopt(to, from.handover.bytes.?);
to.sync();
try std.testing.expectEqual(ncol + 1, to.ncol);
try std.testing.expectEqual(ncol, layout.findPane(to, id).?.col);
try std.testing.expectEqual(@as(usize, 2), to.col_n[ncol]);
for (0..ncol - 1) |k| {
try std.testing.expectEqual(widths[k], to.col_w[k]);
try std.testing.expectEqual(xs[k], to.col_x[k]);
}
// The finish here: both panes and their column gone from the window.
from.update(.{ .handed = .{ .seq = from.handover.seq, .to = "pardes/2" } });
try std.testing.expect(from.ncol == 1 or from.col_n[c] == 0 or layout.findPane(from, 0) == null);
}
|