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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
|
//! The session's messages (pick-ui SPEC §10): each a kind, its cause as a
//! word a Look understands, its text, the places it names and the lines
//! that explain it, kept in a fixed list while it lives; the log of
//! everything said behind them (the history, `SPC h m`, and 9P `/log`);
//! the notice row at the window's foot that indexes them; and the
//! transient band a pane shows over its body's top rows (a prompt waiting
//! for input).
const pardes = @import("root.zig");
const memory = @import("memory.zig");
const std = @import("std");
const layout = @import("layout.zig");
const ctlfs = @import("ninep/tree.zig");
const panes = @import("panes.zig");
const limits = memory.limits;
const config = @import("config.zig");
const platform = pardes.platform;
const Pane = panes.Pane;
const MAX_PANES = pardes.MAX_PANES;
const BOX_H = pardes.BOX_H;
const Key = pardes.Key;
const Rect = layout.Rect;
const Pardes = pardes.Pardes;
const Buf = pardes.Kind.Buf;
const Messages = @This();
/// Where its ring's next line goes and how many it holds, held to the ring
/// where a dump is read back (walk.zig `.place`); the live messages as far
/// as they go.
pub const replica = .{ .place = .{ .{ "head", "lastSlot" }, .{ "len", "size" } }, .len = .{.{ "live", "live_len" }} };
/// The message-row log: a fixed ring, never allocated, never grown. See
/// `logMessage` and the `Messages` builtin.
log: [limits.message_log]LoggedMessage = @splat(.{}),
/// Next slot to write. `len` saturates at the ring's size.
head: usize = 0,
len: usize = 0,
/// The messages that live, oldest first: what the notice row, the marks
/// and the ghosts at a cause's line are drawn from each frame.
live: [max_live]Said = undefined,
live_len: u8 = 0,
/// How many messages live at once: past it the oldest that is no
/// question goes (a burst of distinct ones; a repeat only counts).
pub const max_live = 16;
pub fn lastSlot(m: *const Messages) usize {
return m.log.len - 1;
}
pub fn size(m: *const Messages) usize {
return m.log.len;
}
/// What a message is, which says how long it lives (SPEC §10.1): an echo
/// and a notice until the next message, bright for `MessageLinger`; a
/// warning bright twice that, until Esc; an error until Esc or the next
/// error; a question until it is answered; progress while it runs, at the
/// right end of its tag rather than on the notice row.
pub const Kind = enum(u8) {
echo,
notice,
warn,
@"error",
question,
progress,
pub fn glyph(k: Kind) []const u8 {
return switch (k) {
.echo => "\u{2713}",
.notice => "\u{b7}",
.warn => "!",
.@"error" => "\u{2717}",
.question => "?",
.progress => "\u{22ef}",
};
}
/// Which wins the notice row and a mark: error, question, warning,
/// notice, echo; progress never.
pub fn rank(k: Kind) u8 {
return switch (k) {
.progress => 0,
.echo => 1,
.notice => 2,
.warn => 3,
.question => 4,
.@"error" => 5,
};
}
};
/// A place a message names: a file's line and column, and what it says
/// there (a compiler's `error: ...`), which the body shows at that line.
pub const Place = struct {
path: Buf(256) = .{},
line: u32 = 1,
col: u32 = 1,
text: Buf(128) = .{},
};
/// The questions the session asks in the background, and their answers.
pub const Ask = enum(u8) {
none,
/// A file changed on disk under unsaved text.
disk,
/// Its answers, as its pane's tag offers them: the key that gives one,
/// and its word (an Exec of the word's first word gives it too).
pub fn answers(a: Ask) []const Answer {
return switch (a) {
.none => &.{},
.disk => &.{ .{ .key = 'r', .word = "Reload" }, .{ .key = 'k', .word = "Keep mine" }, .{ .key = 'd', .word = "Diff" } },
};
}
};
pub const Answer = struct { key: u8, word: []const u8 };
/// One live message.
pub const Said = struct {
pub const replica = .{ .len = .{ .{ "places", "places_len" }, .{ "detail", "detail_len" } } };
pub const max_places = 4;
pub const max_detail = 4;
kind: Kind = .notice,
/// Its cause, first, as a word a Look understands: a file's path, a
/// pane's `@pN` (and its command), a server's name.
src: Buf(96) = .{},
text: Buf(256) = .{},
places: [max_places]Place = undefined,
places_len: u8 = 0,
/// The lines that explain it, shown under its first place's line while
/// the caret is on it.
detail: [max_detail]Buf(128) = undefined,
detail_len: u8 = 0,
/// The serial of the pane it is about, 0 for none in particular.
pane: u32 = 0,
asks: Ask = .none,
/// Its detail shown under its first place's line whatever the caret
/// (a question's Diff).
open: bool = false,
/// How many times in a row it was said.
n: u16 = 1,
/// When it was last said, on the core's clock (`Pardes.clock.now_ns`).
t: u64 = 0,
/// Its words without the clock a host stamped on them (Message.stamp).
pub fn words(s: *const Said) []const u8 {
return Message.body(s.text.slice());
}
/// Whether it has dimmed: an echo or a notice past `linger_ms`, a
/// warning past twice that.
pub fn faded(s: *const Said, now_ns: u64, linger_ms: u16) bool {
const bright: u64 = switch (s.kind) {
.echo, .notice => linger_ms,
.warn => 2 * @as(u64, linger_ms),
else => return false,
};
return now_ns -| s.t >= bright * std.time.ns_per_ms;
}
/// Whether it is about `pane`: said of it, or naming its file (as its
/// cause or among its places).
pub fn about(s: *const Said, pane: *const Pane) bool {
if (s.pane != 0 and s.pane == pane.serial) return true;
const f = pane.file orelse return false;
if (std.mem.eql(u8, s.src.slice(), f.path)) return true;
for (s.places[0..s.places_len]) |*place| if (std.mem.eql(u8, place.path.slice(), f.path)) return true;
return false;
}
};
pub const LoggedMessage = struct {
pub const cap = 256;
pub const replica = .{ .len = .{.{ "text", "len" }} };
text: [cap]u8 = undefined,
len: u16 = 0,
/// The serial of the pane that said it, or 0 for none in particular. A
/// serial, not a slot: slots are reused, so an old line would name
/// whichever pane took the slot since.
serial: u32 = 0,
/// How many times in a row. Saturating: a key held down against the same
/// refusal is one event, not four hundred.
repeats: u16 = 0,
kind: Kind = .notice,
pub fn slice(m: *const LoggedMessage) []const u8 {
return m.text[0..m.len];
}
};
pub const Message = struct {
const libc = std.c;
const Tm = extern struct {
sec: c_int,
min: c_int,
hour: c_int,
mday: c_int,
mon: c_int,
year: c_int,
wday: c_int,
yday: c_int,
isdst: c_int,
gmtoff: c_long,
zone: ?[*:0]const u8,
};
extern "c" fn localtime_r(timep: *const libc.time_t, result: *Tm) ?*Tm;
/// PARDES_NOTIME set (the tests, a snapshot run): every clock reads
/// `--:--:--`. A host's (`stamp`, dev/lsp): no step reads it, the text
/// it stamps crossing as a setMessage's.
pub fn noTime() bool {
const v = libc.getenv("PARDES_NOTIME") orelse return false;
return std.mem.span(v).len != 0;
}
/// `HH:MM:SS` of `seconds` since the epoch in a zone `gmtoff` seconds
/// east of UTC: the message row's time of day, and a replica's guess
/// of the session's (core/tape.zig).
pub fn clockText(seconds: i64, gmtoff: i64) [8]u8 {
var text: [8]u8 = "--:--:--".*;
if (noTime()) return text;
const day: std.time.epoch.DaySeconds = .{ .secs = @intCast(@mod(seconds + gmtoff, 86400)) };
_ = std.fmt.bufPrint(&text, "{d:0>2}:{d:0>2}:{d:0>2}", .{ day.getHoursIntoDay(), day.getMinutesIntoHour(), day.getSecondsIntoMinute() }) catch unreachable; // a u5 and two u6s: two digits each
return text;
}
fn timeOfDay() [8]u8 {
var ts: libc.timespec = undefined;
_ = libc.clock_gettime(.REALTIME, &ts);
var tm: Tm = undefined;
if (localtime_r(&ts.sec, &tm) == null) return "--:--:--".*;
return clockText(ts.sec, tm.gmtoff);
}
pub fn body(text: []const u8) []const u8 {
if (text.len < 10) return text;
if (text[2] != ':' or text[5] != ':' or text[8] != ' ' or text[9] != ' ') return text;
for ([_]usize{ 0, 1, 3, 4, 6, 7 }) |i| {
if (!std.ascii.isDigit(text[i]) and text[i] != '-') return text;
}
return text[10..];
}
pub fn stamp(buf: []u8, verb: []const u8, subject: []const u8) []const u8 {
// The time of day of the host that stamps it, in its zone: only a
// host stamps a message (a file reloaded, a save, a language
// server's status), between steps, and the message it then hands
// the core (`setMessage`, an input) is what the tape carries.
const clock = timeOfDay();
const head = std.fmt.bufPrint(buf, "{s} {s} ", .{ &clock, verb }) catch return buf[0..0];
const room = buf.len - head.len;
const tail = if (subject.len <= room) subject else subject[subject.len - room ..];
@memcpy(buf[head.len..][0..tail.len], tail);
return buf[0 .. head.len + tail.len];
}
};
/// A status updates its line in place (a progress count does not pile up),
/// and is not logged; a message is an event.
pub const setStatus = pardes.tape.taped(setStatusInner);
fn setStatusInner(p: *Pardes, id: Pane.Id, text: []const u8) void {
// No text: the pane's progress is over, and goes.
if (text.len == 0) {
const serial: u32 = if (id.index() < MAX_PANES) if (p.panes[id.index()]) |pane| pane.serial else 0 else 0;
const m = &p.messages;
for (m.live[0..m.live_len], 0..) |*s, i| if (s.kind == .progress and s.pane == serial) {
m.remove(i);
p.needs_frame = true;
break;
};
return;
}
_ = say(p, .progress, id.index(), text);
}
pub const setMessage = pardes.tape.taped(setMessageInner);
fn setMessageInner(p: *Pardes, id: Pane.Id, text: []const u8) void {
_ = say(p, .notice, id.index(), text);
}
/// Say `text`, a message of `kind` about pane `id` (MAX_PANES and up:
/// none in particular), its cause first: logged (progress is not), and
/// live (`keep`); the message, for the places it names.
pub fn say(p: *Pardes, kind: Kind, id: usize, text: []const u8) *Said {
if (kind != .progress) logMessage(p, id, kind, text);
const pane: ?*Pane = if (id < MAX_PANES and !p.fs.session_write) p.panes[id] else null;
var src: Buf(96) = .{};
if (pane) |cause| causeWord(cause, &src);
return keep(p, kind, if (pane) |cause| cause.serial else 0, src.slice(), text);
}
/// A pane as a message names its cause: a file's path (a kind's too), else
/// `@pN` and the command it runs.
fn causeWord(pane: *const Pane, out: *Buf(96)) void {
if (pane.file) |f| return out.set(f.path);
if (pane.addon) |k| if (k.path.len > 0) return out.set(k.path);
const line = pane.command orelse {
_ = out.print(config.pane_addr ++ "{d}", .{pane.serial});
return;
};
const first = line[0 .. std.mem.indexOfAny(u8, line, "\r\n") orelse line.len];
var cut = @min(first.len, 64);
while (cut < first.len and cut > 0 and first[cut] & 0xC0 == 0x80) cut -= 1;
_ = out.print(config.pane_addr ++ "{d} {s}", .{ pane.serial, first[0..cut] });
}
/// Make a message live, and return it (for its places and its detail):
/// a new message retires every echo and notice, a new error the error
/// before it; the same message again right after itself is counted. The
/// list is in the order things were said.
pub fn keep(p: *Pardes, kind: Kind, serial: u32, src: []const u8, text: []const u8) *Said {
const m = &p.messages;
p.needs_frame = true;
// One row of printable text: a language server's multi-line report
// reads as one line, and the cut never leaves half a glyph behind.
var row: [256]u8 = undefined;
var n: usize = @min(text.len, row.len);
if (n < text.len) {
while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1;
}
for (text[0..n], row[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c;
const line = row[0..n];
const now = p.clock.now_ns;
// Progress from the same cause is updated, and is the newest said.
if (kind == .progress) for (m.live[0..m.live_len], 0..) |*s, i| {
if (s.kind != .progress or s.pane != serial or !std.mem.eql(u8, s.src.slice(), src)) continue;
const kept = s.*;
m.remove(i);
const last = &m.live[m.live_len];
m.live_len += 1;
last.* = kept;
last.text.set(line);
last.t = now;
return last;
};
if (m.live_len > 0) {
// The NEWEST wording wins, so it carries the latest clock.
const last = &m.live[m.live_len - 1];
if (last.kind == kind and last.pane == serial and std.mem.eql(u8, last.src.slice(), src) and
std.mem.eql(u8, Message.body(last.text.slice()), Message.body(line)))
{
last.n +|= 1;
last.t = now;
last.text.set(line);
return last;
}
}
if (kind != .progress) {
var i: usize = 0;
while (i < m.live_len) {
const old = m.live[i].kind;
if (old == .echo or old == .notice or (kind == .@"error" and old == .@"error")) m.remove(i) else i += 1;
}
}
if (m.live_len == max_live) {
var oldest: usize = 0;
while (oldest + 1 < m.live_len and m.live[oldest].kind == .question) oldest += 1;
m.remove(oldest);
}
const s = &m.live[m.live_len];
m.live_len += 1;
s.* = .{ .kind = kind, .pane = serial, .t = now };
s.src.set(src);
s.text.set(line);
return s;
}
pub fn remove(m: *Messages, i: usize) void {
std.mem.copyForwards(Said, m.live[i .. m.live_len - 1], m.live[i + 1 .. m.live_len]);
m.live_len -= 1;
}
/// Retire every live message of `kinds` (Esc: the warnings and errors);
/// how many went.
pub fn retire(m: *Messages, kinds: []const Kind) usize {
var gone: usize = 0;
var i: usize = 0;
while (i < m.live_len) {
if (std.mem.indexOfScalar(Kind, kinds, m.live[i].kind) != null) {
m.remove(i);
gone += 1;
} else i += 1;
}
return gone;
}
/// The message the notice row leads with: the highest-ranked, the newest
/// within a rank; progress never.
pub fn headline(m: *const Messages) ?*const Said {
var best: ?*const Said = null;
for (m.live[0..m.live_len]) |*s| {
if (s.kind == .progress) continue;
if (best == null or s.kind.rank() >= best.?.kind.rank()) best = s;
}
return best;
}
/// The kind a pane's mark shows, one cell after its box (SPEC §10.2): the
/// most important live error, question, warning or progress about it (an
/// echo or a notice marks nothing); null for none.
pub fn markOf(m: *const Messages, pane: *const Pane) ?Kind {
var best: ?Kind = null;
for (m.live[0..m.live_len]) |*s| {
if (s.kind == .echo or s.kind == .notice or !s.about(pane)) continue;
if (best == null or s.kind.rank() > best.?.rank()) best = s.kind;
}
return best;
}
/// A kind's ink, for its glyph, its mark and its words at a line.
pub fn ink(chrome: *const pardes.colors.ChromeTheme, kind: Kind) [3]u8 {
return switch (kind) {
.@"error" => chrome.roles.err,
.warn => chrome.roles.warn,
.question => chrome.roles.question,
else => chrome.roles.hint,
};
}
/// The places a compiler's report names put on `s`: each
/// `path:line:col: error|warning|note: words` row (a relative path is
/// `dir`'s), its words there, and the rows after the first error, up to
/// the next place, its detail. How many it found; none without an error.
pub fn readPlaces(s: *Said, dir: []const u8, rows: []const []const u8) usize {
var errors: usize = 0;
var detailing = false;
for (rows) |raw| {
const row = std.mem.trimEnd(u8, raw, " \t\r\n");
const found = placeOf(row) orelse {
if (detailing and row.len > 0 and s.detail_len < Said.max_detail) {
s.detail[s.detail_len] = .{};
s.detail[s.detail_len].set(row);
s.detail_len += 1;
}
continue;
};
detailing = false;
const is_error = std.mem.startsWith(u8, found.text, "error");
if (is_error) {
detailing = errors == 0;
errors += 1;
}
if (s.places_len == Said.max_places) continue;
const place = &s.places[s.places_len];
place.* = .{ .line = found.line, .col = found.col };
if (std.Io.Dir.path.isAbsolute(found.path)) place.path.set(found.path) else _ = place.path.print("{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), found.path });
place.text.set(if (std.mem.startsWith(u8, found.text, "error: ")) found.text["error: ".len..] else found.text);
s.places_len += 1;
}
if (errors == 0) s.places_len = 0;
return s.places_len;
}
/// A compiler's place row: `path:line:col: error|warning|note...`.
fn placeOf(row: []const u8) ?struct { path: []const u8, line: u32, col: u32, text: []const u8 } {
const a = std.mem.indexOfScalar(u8, row, ':') orelse return null;
const path = row[0..a];
if (path.len == 0 or std.mem.indexOfAny(u8, path, " \t") != null) return null;
var rest = row[a + 1 ..];
const b = std.mem.indexOfScalar(u8, rest, ':') orelse return null;
const line = std.fmt.parseInt(u32, rest[0..b], 10) catch return null;
rest = rest[b + 1 ..];
const c = std.mem.indexOfScalar(u8, rest, ':') orelse return null;
const col = std.fmt.parseInt(u32, rest[0..c], 10) catch return null;
const text = std.mem.trim(u8, rest[c + 1 ..], " ");
for ([_][]const u8{ "error", "warning", "note" }) |word| {
if (std.mem.startsWith(u8, text, word)) return .{ .path = path, .line = line, .col = col, .text = text };
}
return null;
}
/// The question waiting on `pane`, an index into `live`; null for none.
pub fn waiting(m: *const Messages, pane: *const Pane) ?usize {
for (m.live[0..m.live_len], 0..) |*s, i| if (s.kind == .question and s.pane == pane.serial) return i;
return null;
}
/// The answers of the question waiting on `pane`: what a `:` lists first
/// (pick-ui SPEC §10.4); none without one.
pub fn waitingAnswers(m: *const Messages, pane: *const Pane) []const Answer {
const i = m.waiting(pane) orelse return &.{};
return m.live[i].asks.answers();
}
/// Answer live question `i` with `key`: `r` reads the file again over its
/// unsaved text, `k` keeps the text and lets the disk's be, `d` shows (or
/// hides again) the disk's lines where they differ, as ghosts in its
/// body. False for a key that is none of its answers.
pub fn answer(p: *Pardes, i: usize, key: u8) bool {
const m = &p.messages;
const s = &m.live[i];
const a = for (s.asks.answers()) |a| {
if (a.key == key) break a;
} else return false;
p.needs_frame = true;
const id = p.paneBySerial(s.pane) orelse {
m.remove(i);
return true;
};
var said: Buf(256) = .{};
if (key == 'd') {
if (s.open) {
s.open = false;
return true;
}
diskDiff(p, s, id);
return true;
}
logMessage(p, id, .echo, said.print("{s} {s} \u{b7} answered {s}", .{ s.src.slice(), s.words(), a.word }));
m.remove(i);
if (key == 'r') {
const pane = p.panes[id].?;
// The answer is the consent Get would ask for.
if (pane.file) |f| pane.discard_warned = .{ .revision = f.revision, .by = .get };
pardes.exec.runBuiltin(p, .Get, id, "", null);
} else _ = say(p, .echo, id, "kept yours; the disk's is not read");
return true;
}
/// SPC e (the Message word, SPEC §10.4), on the message the notice row
/// leads with: an error that names places lands them as a list in pane
/// `id`'s walk (Pick's `list`, its word `✗ <cause>` in the trail), the
/// first landed on, n and N walking the rest, and the error goes (a
/// +Search under the pane where jumps do not walk, or for a 9P script:
/// Pick.asked); a question takes the keyboard in its pane's tag; anything
/// else, or nothing, opens the history.
pub fn act(p: *Pardes, id: usize) void {
const m = &p.messages;
const lead = m.headline() orelse return history(p, id);
if (lead.kind == .question) {
p.view().answering = lead.pane;
p.needs_frame = true;
return;
}
if (lead.kind != .@"error" or lead.places_len == 0 or id >= MAX_PANES) return history(p, id);
const pane = p.panes[id] orelse return;
var rows: std.Io.Writer.Allocating = .init(p.gpa);
errdefer rows.deinit();
for (lead.places[0..lead.places_len]) |*place| rows.writer.print("{s}:{d}:{d} {s}\n", .{ place.path.slice(), place.line, place.col, place.text.slice() }) catch |err| return reportError(p, .at(id), "Message", err);
const cause = lead.src;
const lead_at = for (m.live[0..m.live_len], 0..) |*s, k| {
if (s == lead) break k;
} else return;
m.remove(lead_at);
const content = rows.toOwnedSlice() catch |err| return reportError(p, .at(id), "Message", err);
if (pardes.Pick.asked(p)) {
defer p.gpa.free(content);
// The cause cut at a character's start to the word's room.
const src = cause.slice();
var cut = @min(src.len, 24 - "\u{2717} ".len);
while (cut > 0 and cut < src.len and src[cut] & 0xC0 == 0x80) cut -= 1;
var word: Buf(24) = .{};
pardes.Pick.open(p, id, .list, word.print("\u{2717} {s}", .{src[0..cut]}), "", content);
return pardes.Pick.landHere(p);
}
pardes.panes.Output.fillResults(p, id, pardes.panes.paneDir(pane), .search, cause.slice(), content, null) catch |err| return reportError(p, .at(id), "Message", err);
_ = @import("look.zig").searchStep(p, id, 1);
}
/// The history (SPC h m, the Messages word; SPC e with nothing to act on):
/// where jumps walk a picker over it in pane `id`'s tag (Pick's
/// `messages`), the newest first, Enter Looking a row, C-q keeping it as
/// a +Messages; else (or for a 9P script, Pick.asked) the +Messages.
pub fn history(p: *Pardes, id: usize) void {
if (pardes.Pick.asked(p) and id < MAX_PANES and p.panes[id] != null) return pardes.Pick.open(p, id, .messages, "", "", "");
pardes.panes.Output.openMessages(p, id) catch |err| reportError(p, .at(id), "messages", err);
}
/// An Exec of an answer's word in the tag of a pane a question waits on
/// (B2 on `Reload`): that answer. False for any other word.
pub fn answerWord(p: *Pardes, id: usize, word: []const u8) bool {
if (id >= MAX_PANES) return false;
const pane = p.panes[id] orelse return false;
const i = p.messages.waiting(pane) orelse return false;
const typed = std.mem.trim(u8, word, " \t\r\n");
for (p.messages.live[i].asks.answers()) |a| {
const first = a.word[0 .. std.mem.indexOfScalar(u8, a.word, ' ') orelse a.word.len];
if (std.mem.eql(u8, typed, first)) return answer(p, i, a.key);
}
return false;
}
/// A question's Diff: the disk's text read (the host's read, taped) and
/// set against the buffer's, the lines they share at either end left out;
/// where they part, its place, and up to `Said.max_detail` of the lines
/// there, the disk's `+` and then the buffer's `-`, its detail, shown.
fn diskDiff(p: *Pardes, s: *Said, id: usize) void {
const pane = p.panes[id].?;
const f = if (pane.file) |*file| file else return;
const disk = @import("fs.zig").read(p, f.path) catch |err| return pardes.Messages.reportError(p, .at(id), "Diff", err);
defer p.gpa.free(disk);
const mine = pardes.panes.File.fileText(f, p.scratch.allocator()) catch return;
var a = std.mem.splitScalar(u8, mine, '\n');
var b = std.mem.splitScalar(u8, disk, '\n');
var line: u32 = 1;
var ours: []const u8 = "";
var theirs: []const u8 = "";
while (true) : (line += 1) {
const x = a.next();
const y = b.next();
if (x == null and y == null) return;
if (x != null and y != null and std.mem.eql(u8, x.?, y.?)) continue;
ours = if (x) |l| mine[@intFromPtr(l.ptr) - @intFromPtr(mine.ptr) ..] else "";
theirs = if (y) |l| disk[@intFromPtr(l.ptr) - @intFromPtr(disk.ptr) ..] else "";
break;
}
// The lines both end with, left out.
var ours_end = ours.len;
var theirs_end = theirs.len;
while (ours_end > 0 and theirs_end > 0) {
const ol = std.mem.lastIndexOfScalar(u8, ours[0 .. ours_end - 1], '\n');
const tl = std.mem.lastIndexOfScalar(u8, theirs[0 .. theirs_end - 1], '\n');
const o_line = ours[if (ol) |nl| nl + 1 else 0..ours_end];
const t_line = theirs[if (tl) |nl| nl + 1 else 0..theirs_end];
if (!std.mem.eql(u8, o_line, t_line)) break;
ours_end = if (ol) |nl| nl + 1 else 0;
theirs_end = if (tl) |nl| nl + 1 else 0;
}
s.places[0] = .{ .line = line, .col = 1 };
s.places[0].path.set(f.path);
s.places[0].text.set("the disk's differs here");
s.places_len = 1;
s.detail_len = 0;
// The disk's first: it is what the answer shows.
for ([_]struct { []const u8, []const u8 }{ .{ "+", theirs[0..theirs_end] }, .{ "-", ours[0..ours_end] } }) |side| {
var rows = std.mem.splitScalar(u8, std.mem.trimEnd(u8, side[1], "\n"), '\n');
while (rows.next()) |row| {
if (side[1].len == 0 or s.detail_len == Said.max_detail) break;
s.detail[s.detail_len] = .{};
_ = s.detail[s.detail_len].print("{s}{s}", .{ side[0], row });
s.detail_len += 1;
}
}
s.open = true;
}
/// The words the newest live message said of `pane` has, "" for none:
/// what its band shows, and what a write that failed on it answers.
pub fn saidBy(m: *const Messages, pane: *const Pane) []const u8 {
var i = m.live_len;
while (i > 0) {
i -= 1;
if (m.live[i].pane == pane.serial) return m.live[i].text.slice();
}
return "";
}
/// When the next live message dims, on the core's clock; null for none.
pub fn dimDue(p: *const Pardes) ?u64 {
const m = &p.messages;
if (p.settings.message_linger_ms == 0) return null;
var soonest: ?u64 = null;
for (m.live[0..m.live_len]) |*s| {
const bright: u64 = switch (s.kind) {
.echo, .notice => p.settings.message_linger_ms,
.warn => 2 * @as(u64, p.settings.message_linger_ms),
else => continue,
};
const due = s.t + bright * std.time.ns_per_ms;
if (due <= p.clock.stepped_ns) continue;
soonest = if (soonest) |first| @min(first, due) else due;
}
return soonest;
}
/// The notice row's line (SPEC §10.3), `width` columns: on the left the
/// message the row leads with (`headline`), its glyph, its cause, its
/// words, `×n` and the places it names; on the right how many more live,
/// the questions waiting, or the way to the history. With nothing live the
/// left says where the focused pane's caret is. Built each frame from the
/// state, in `out`.
pub const Row = struct {
/// The left part's end and the right part's start, in bytes of `text`.
left: usize = 0,
right: usize = 0,
text: []const u8 = "",
/// The message the left says, when it says one.
lead: ?*const Said = null,
/// The left in the dim ink (a picker's sentence, UX D7), but for the
/// bytes `word` (an address, in the text's).
quiet_left: bool = false,
word: [2]usize = .{ 0, 0 },
};
/// Room for the notice row's line: the widest window's at the tagline's
/// pitch (Layer.capacity) is cut to it.
pub const notice_row_cap = 1024;
pub fn noticeRow(p: *const Pardes, width: usize, out: *[notice_row_cap]u8) Row {
const m = &p.messages;
const tab = p.settings.tab;
// A rolled level's last leaf, while the level shows: what it does, the
// whole row (SPEC §3.7's first mockup).
if (pardes.TagState.lastUsed(p, p.view(), out)) |used| {
var end = @min(used.len, panes.File.rawAtDisplay(tab, used, width));
while (end > 0 and panes.File.displayWidth(tab, used[0..end]) > width) end -= 1;
while (end > 0 and end < used.len and used[end] & 0xC0 == 0x80) end -= 1;
return .{ .left = end, .right = end, .text = used[0..end] };
}
var w: std.Io.Writer = .fixed(out);
var live: usize = 0;
var questions: usize = 0;
for (m.live[0..m.live_len]) |*s| {
if (s.kind == .progress) continue;
live += 1;
if (s.kind == .question) questions += 1;
}
// While a picker previews, its sentence (UX D7), before any message.
const said = pardes.Pick.sentence(p, &w);
const lead = if (said == null) m.headline() else null;
if (said != null) {} else if (lead) |s| {
w.print("{s} ", .{s.kind.glyph()}) catch {};
// Its cause first, unless its words name it already.
const words = s.words();
if (s.src.len > 0 and std.mem.indexOf(u8, words, s.src.slice()) == null) w.print("{s} ", .{s.src.slice()}) catch {};
w.writeAll(words) catch {};
if (s.n > 1) w.print(" \u{d7}{d}", .{s.n}) catch {};
for (s.places[0..s.places_len], 0..) |*place, i| w.print("{s} {s}:{d}:{d}", .{ if (i > 0) " \u{b7}" else "", place.path.slice(), place.line, place.col }) catch {};
} else if (p.panes[p.view().active]) |pane| {
if (pane.file) |f| w.print("{s}:{d}", .{ f.path, pane.body.cur_row + 1 }) catch {} else w.writeAll(pane.cwdSlice()) catch {};
}
const left_end = w.end;
var right: [64]u8 = undefined;
var r: std.Io.Writer = .fixed(&right);
if (live > 1) r.print("+{d} \u{b7} ", .{live - 1}) catch {};
if (questions > 0)
r.print("{d} question{s} \u{b7} SPC e", .{ questions, if (questions == 1) "" else "s" }) catch {}
else if (lead != null and lead.?.kind == .@"error" and lead.?.places_len > 0)
r.writeAll("SPC e walk") catch {}
else if (m.len > 0)
r.print("{d} message{s} \u{b7} SPC h m", .{ m.len, if (m.len == 1) "" else "s" }) catch {};
// The keys of a root whose level waits for its delay, at once (UX D12:
// vim's showcmd; the tag stays at rest until the level shows).
var keys: [64]u8 = undefined;
if (pardes.TagState.pending(p, p.view(), &keys)) |typed| r.print("{s}{s}", .{ if (r.end > 0) " " else "", typed }) catch {};
const tail = r.buffered();
// The left cut with `…` to make room for the right, two blanks between
// them at least (UX D2): the pane's path from the left, so its name
// and line stay (`…core/Store.zig:12`), anything else from the right.
const tail_w = panes.File.displayWidth(tab, tail);
const room = width -| (if (tail_w > 0) tail_w + 2 else 0);
var cut = left_end;
if (panes.File.displayWidth(tab, out[0..cut]) > room) {
if (said == null and lead == null) {
var from: usize = 0;
while (from < left_end and panes.File.displayWidth(tab, out[from..left_end]) > room -| 1) {
from += 1;
while (from < left_end and out[from] & 0xC0 == 0x80) from += 1;
}
var kept: [notice_row_cap]u8 = undefined;
const name = kept[0 .. left_end - from];
@memcpy(name, out[from..left_end]);
w.end = 0;
w.writeAll(if (room > 0) "…" else "") catch {};
w.writeAll(name) catch {};
cut = w.end;
} else {
cut = panes.File.rawAtDisplay(tab, out[0..left_end], room -| 1);
while (cut > 0 and panes.File.displayWidth(tab, out[0..cut]) > room -| 1) {
cut -= 1;
while (cut > 0 and out[cut] & 0xC0 == 0x80) cut -= 1;
}
w.end = cut;
w.writeAll(if (room > 0) "…" else "") catch {};
cut = w.end;
}
}
w.end = cut;
const gap = width -| (panes.File.displayWidth(tab, out[0..cut]) + tail_w);
for (0..gap) |_| w.writeByte(' ') catch {};
const right_at = w.end;
w.writeAll(tail) catch {};
return .{ .left = cut, .right = right_at, .text = w.buffered(), .lead = lead, .quiet_left = said != null, .word = said orelse .{ 0, 0 } };
}
/// What notice band `i` says. The grid pass and the band layers both
/// read it here, so a terminal and a pixel shell show the same line.
pub fn noticeText(pane: *const Pane, i: usize) []const u8 {
return switch (pane.notices.kinds[i]) {
.prompt => pane.promptText() orelse "",
};
}
fn logMessage(p: *Pardes, id: usize, kind: Kind, text: []const u8) void {
if (text.len == 0) return;
const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0;
const kept = text[0..@min(text.len, LoggedMessage.cap)];
// /log hears every one (a failure of a ctl write as its err record).
if (!p.fs.unlogged) ctlfs.events.noteMessage(p, serial, text);
if (p.messages.len > 0) {
const last = &p.messages.log[(p.messages.head + limits.message_log - 1) % limits.message_log];
if (last.serial == serial and
std.mem.eql(u8, Message.body(last.slice()), Message.body(kept)))
{
// The NEWEST wording wins, so the row carries the latest clock
// rather than the moment the run started.
last.len = @intCast(kept.len);
@memcpy(last.text[0..last.len], kept);
last.repeats +|= 1;
return;
}
}
const slot = &p.messages.log[p.messages.head];
slot.len = @intCast(kept.len);
@memcpy(slot.text[0..slot.len], kept);
slot.serial = serial;
slot.repeats = 1;
slot.kind = kind;
p.messages.head = (p.messages.head + 1) % limits.message_log;
p.messages.len = @min(p.messages.len + 1, limits.message_log);
}
/// The log oldest-first, which is reading order.
pub fn at(m: *const Messages, i: usize) ?*const LoggedMessage {
if (i >= m.len) return null;
const first = (m.head + limits.message_log - m.len) % limits.message_log;
return &m.log[(first + i) % limits.message_log];
}
/// What a route that would open a pane says when every slot is taken.
/// "no space": 9ns's word for ENOSPC (it has none for ENFILE).
pub const no_pane_slots = "no space for a pane: {d} max";
/// ...and when the column it would go in has no rows for one.
pub const no_pane_room = "no space for a pane in that column: each keeps its tag and {d} rows";
/// `<operation>: <the error in words>`: FileNotFound reads "file not found".
/// Why a peer could not be reached, in words, for an error of a 9P dial
/// (runtime/9p_io.zig, Client); null for any other error.
pub fn dialReason(err: anyerror) ?[]const u8 {
return switch (err) {
error.Dial => "no answer",
error.Timeout => "timed out",
error.Hangup => "hung up",
error.Botch => "protocol botch",
else => null,
};
}
pub const reportError = pardes.tape.taped(reportErrorInner);
fn reportErrorInner(p: *Pardes, id: Pane.Id, operation: []const u8, err: anyerror) void {
// Room for an operation naming the longest path and the reason after
// it: a shorter one cut the reason off (`Save /long…`), and the reason
// is what a failure is for. Where it must be shorter, the path gives.
var buf: [@max(256, limits.host_path_cap + 128)]u8 = undefined;
var w = std.Io.Writer.fixed(&buf);
w.print("{s}: ", .{operation}) catch {};
// A peer out of reach says so, not the error's name (`dial`).
if (dialReason(err)) |why| {
w.print("dial failed: {s}", .{why}) catch {};
return reportFailure(p, id.index(), w.buffered());
}
// Every route that opens a pane says the cap the same way.
if (err == error.NoPaneSlots or err == error.NoPaneRoom) {
if (err == error.NoPaneSlots)
w.print(no_pane_slots, .{pardes.MAX_PANES}) catch {}
else
w.print(no_pane_room, .{pardes.layout.min_body_rows}) catch {};
// A 9P look or exec that would open the pane fails with it too.
p.fs.no_pane_slot = true;
@memcpy(p.fs.ename[0..w.buffered().len], w.buffered());
p.fs.no_pane_slot_len = @intCast(w.buffered().len);
return reportFailure(p, id.index(), w.buffered());
}
var words: [128]u8 = undefined;
w.writeAll(errorWords(err, &words)) catch {};
reportFailure(p, id.index(), w.buffered());
}
/// An error in a person's words, never its Zig name: the few that read
/// badly spaced out said plainly, the rest spaced and lower case
/// (`FileNotFound`, "file not found").
pub fn errorWords(err: anyerror, buf: []u8) []const u8 {
return switch (err) {
error.FileTooLarge => "too large",
error.NoTerminal => pardes.Term.none,
error.NotAFile => "not a regular file",
// In the words a mount turns into EISDIR and EACCES (cloud9.fs.enameErrno).
error.IsDirectory => "is a directory",
error.PermissionDenied, error.AccessDenied => "permission denied",
error.ReadFailed => "could not be read",
error.ParseZon => "not valid ZON",
error.ThemeFileTooLarge => "too large: a theme file is at most 1 MiB",
error.InvalidThemeName => "its name is empty or over 255 bytes",
else => {
var w = std.Io.Writer.fixed(buf);
for (@errorName(err), 0..) |c, i| {
if (std.ascii.isUpper(c) and i > 0) w.writeByte(' ') catch break;
w.writeByte(std.ascii.toLower(c)) catch break;
}
return w.buffered();
},
};
}
/// A ZON parse failure in a person's words: the first error the parser
/// found and its line, `line 3: expected ','`.
pub fn zonWhy(diag: *const std.zon.parse.Diagnostics, buf: []u8) []const u8 {
if (diag.errors.len == 0) return "not valid ZON";
const first = diag.errors[0];
var w: std.Io.Writer = .fixed(buf);
w.print("line {d}: {s}", .{ first.loc.line + 1, first.msg }) catch {}; // a long message is cut at the room's end
return w.buffered();
}
/// The longest start of `text` that fits `max` bytes and ends between
/// words (or, with no space to cut at, between characters).
pub fn clip(text: []const u8, max: usize) []const u8 {
if (text.len <= max) return text;
if (std.mem.lastIndexOfScalar(u8, text[0 .. max + 1], ' ')) |sp| return text[0..sp];
var n = max;
while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1;
return text[0..n];
}
/// reportError with the words already chosen.
pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void {
p.fs.failures +%= 1;
var fitted: @TypeOf(p.fs.said) = undefined;
const said = pardes.ctlfs.fitErr(text, &fitted);
@memcpy(p.fs.said[0..said.len], said);
p.fs.said_len = @intCast(said.len);
p.fs.said_at = p.fs.failures;
// A builtin a ctl write runs: its first error is also the write's, its
// path shortened in the middle if it must be, never its reason.
const failing_write = p.fs.no_prompt or p.fs.capturing or p.fs.write_waits;
if (failing_write and p.fs.failure_len == 0) {
var room: @TypeOf(p.fs.failure) = undefined;
const kept = pardes.ctlfs.fitErr(text, &room);
@memcpy(p.fs.failure[0..kept.len], kept);
p.fs.failure_len = @intCast(kept.len);
}
// The write fails with it, and its err record says it: no msg for it,
// so the same failure again is the same record again, counted
// (events.pushCounting).
if (failing_write) {
p.fs.unlogged = true;
defer p.fs.unlogged = false;
_ = say(p, .@"error", id, text);
return;
}
_ = say(p, .@"error", id, text);
}
/// The one place that decides which transient lines a pane is showing and
/// in what order. Everything downstream reads the answer: the body layer
/// so it does not paint under them, and the paint pass so it can stack
/// them instead of letting the last one win the row.
pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect) void {
pane.notices = bands(p, pane, pane.tag_rows, r);
// A message's detail under the caret's line, where the body draws it
// and a click's row is read (Pane.textRow): the step's, as the bands.
const under = if (r.h > pane.tag_rows) detailUnder(p, pane, p.panes[p.view().active] == pane, r.h - pane.tag_rows) else null;
pane.ghost_at = if (under) |d| d.row else 0;
pane.ghost_rows = if (under) |d| d.rows else 0;
// Each band's chip at the right edge, as wide as its own text and a
// blank cell either side, the pane's width at most: a click finds it
// whether or not a frame has drawn it. An overlay over the body's top
// rows, not a row taken from them, it is counted in GRID columns, not
// the tagline face it is drawn in: the grid is what a terminal client
// draws, and a chip narrower than its text there would clip it.
const tx = r.x + config.GUTTER;
const tw = r.w -| config.GUTTER;
for (0..pane.notices.len) |i| {
const chip = panes.File.displayWidth(p.settings.tab, noticeText(pane, i)) + 2;
pane.notices.left[i] = if (tw == 0) std.math.maxInt(u16) else tx + tw - @as(u16, @intCast(@min(chip, tw)));
}
}
/// A message's detail under the caret's line (SPEC §10.2), as a body of
/// `body_h` rows shows it: the row of that line's last row, how many of the
/// detail's lines fit under it, the message (the first naming the line, as
/// the words after it are); only in the pane with the keyboard, in its body.
/// Bounded by the live messages' places and the rows shown.
pub fn detailUnder(p: *const Pardes, pane: *Pane, active: bool, body_h: u16) ?struct { row: u16, rows: u16, said: *const Said } {
if (!active or pane.focus != .body or p.messages.live_len == 0) return null;
const f = pane.file orelse return null;
const caret = @max(0, pane.body.cur_row);
const said = found: for (p.messages.live[0..p.messages.live_len]) |*s| {
for (s.places[0..s.places_len]) |*place| if (place.line == caret + 1 and std.mem.eql(u8, place.path.slice(), f.path)) break :found s;
} else return null;
if (said.detail_len == 0) return null;
var row: u16 = 0;
while (row < body_h) : (row += 1) {
if (pane.wrapAt(p.settings.tab, row).line != caret) continue;
if (row + 1 < body_h and pane.wrapAt(p.settings.tab, row + 1).line == caret) continue;
const k: u16 = @intCast(@min(said.detail_len, body_h - row - 1));
return if (k == 0) null else .{ .row = row, .rows = k, .said = said };
}
return null;
}
/// The bands a pane shows over `r` below its `tag_rows`: the live view's
/// each step, and any view's for its kind's facts (Kind.viewOf), made from
/// what a dump keeps (the bands are derived).
pub fn bands(p: *const Pardes, pane: *const Pane, tag_rows: u16, r: Rect) Pane.Notices {
var n: Pane.Notices = .{};
if (r.w <= config.GUTTER or r.h <= tag_rows) return n;
// Del's question shows once its delay is up: answered before that, it
// was never there.
const del_waiting = pane.prompt == .del_side and pane.question_due_ns > p.clock.now_ns;
if (pane.promptText()) |text| if (text.len > 0 and !del_waiting) n.push(.prompt);
// A pane only has so many rows to give. When they do not all fit the
// LAST ones survive, because the prompt is last and it is the one
// carrying the cursor: a prompt you cannot see is a prompt you type
// into blind. A two-row pane spends its only body row on one notice,
// which is what the single shared row used to do anyway.
const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - tag_rows));
if (n.len <= room) return n;
// Too short for them all: the top bands go.
const drop = n.len - room;
for (0..room) |k| {
n.kinds[k] = n.kinds[k + drop];
n.row[k] = @intCast(k);
}
n.len = room;
return n;
}
test "errors are said in words, and a ZON failure names its line" {
var buf: [128]u8 = undefined;
try std.testing.expectEqualStrings("file not found", errorWords(error.FileNotFound, &buf));
try std.testing.expectEqualStrings("too large", errorWords(error.FileTooLarge, &buf));
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var diag: std.zon.parse.Diagnostics = undefined;
const T = struct { a: u8 };
try std.testing.expectError(error.ParseZon, std.zon.parse.fromSlice(T, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = ".{\n .a = 1,\n .b = 2 }", .diagnostics = &diag }));
try std.testing.expect(std.mem.startsWith(u8, zonWhy(&diag, &buf), "line 3: "));
}
test "an error reads as words and a failure is cut between them" {
try std.testing.expectEqualStrings("go", clip("go haskell", 4));
try std.testing.expectEqualStrings("go haskell", clip("go haskell", 10));
try std.testing.expectEqualStrings("\u{e9}", clip("\u{e9}\u{e9}", 3));
}
test "the message log keeps what the row forgets, and collapses repeats" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
setMessage(p, .at(0), "14:32:07 saved /x.zig");
setMessage(p, .at(0), "14:32:09 saved /x.zig"); // same event, later clock
setMessage(p, .at(0), "save: AccessDenied");
try std.testing.expectEqual(@as(usize, 2), p.messages.len);
const first = p.messages.at(0).?;
try std.testing.expectEqual(@as(u16, 2), first.repeats);
// ...and the NEWEST wording is what survives, so the row carries the last
// time it happened rather than the first.
try std.testing.expectEqualStrings("14:32:09 saved /x.zig", first.slice());
try std.testing.expectEqualStrings("save: AccessDenied", p.messages.at(1).?.slice());
try std.testing.expect(p.messages.at(2) == null);
// The same text from a DIFFERENT pane is a different event: one pane's
// failure must not be recorded as another's.
p.newScratchBelow(0);
const other = p.view().active;
setMessage(p, .at(other), "save: AccessDenied");
try std.testing.expectEqual(@as(usize, 3), p.messages.len);
try std.testing.expectEqual(p.panes[other].?.serial, p.messages.at(2).?.serial);
// Progress is NOT logged: it arrives several times a second for a whole
// index and would push everything else out (`setStatus`).
setStatus(p, .at(0), "14:32:10 lsp rust-analyzer: Indexing 47%");
try std.testing.expectEqual(@as(usize, 3), p.messages.len);
// The ring wraps rather than grows, and still reads oldest-first.
for (0..limits.message_log + 5) |i| {
var buf: [32]u8 = undefined;
setMessage(p, .at(0), std.fmt.bufPrint(&buf, "line {d}", .{i}) catch unreachable);
}
try std.testing.expectEqual(@as(usize, limits.message_log), p.messages.len);
try std.testing.expectEqualStrings("line 5", p.messages.at(0).?.slice());
var last_buf: [32]u8 = undefined;
const want_last = std.fmt.bufPrint(&last_buf, "line {d}", .{limits.message_log + 4}) catch unreachable;
try std.testing.expectEqualStrings(want_last, p.messages.at(limits.message_log - 1).?.slice());
}
test "Msg says a notice by hand, bare or with text, and the next message retires it" {
if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
// the whole tail, spaces and all: the row is a sentence, not a word
try std.testing.expect(p.executeBuiltinLine(2, "Msg saved /etc/hosts"));
try std.testing.expectEqualStrings("saved /etc/hosts", p.messages.saidBy(p.panes[2].?));
// ...of the pane that ran it, its cause that pane's address
try std.testing.expectEqualStrings("", p.messages.saidBy(p.panes[0].?));
var want: [16]u8 = undefined;
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "@p{d}", .{p.panes[2].?.serial}), p.messages.headline().?.src.slice());
// Bare, it reports ITSELF through reportError — the `<operation>: <error in words>`
// every failed save and refused Look arrives in: an error.
try std.testing.expect(p.executeBuiltinLine(2, "Msg"));
try std.testing.expectEqualStrings("Msg: no message", p.messages.saidBy(p.panes[2].?));
try std.testing.expectEqual(Kind.@"error", p.messages.headline().?.kind);
// Input takes nothing away; the next message does what the notice
// was, and the error stays until Esc.
p.update(.{ .key = .{ .cp = 'h' } });
for (0..200) |_| p.update(.tick);
try std.testing.expectEqualStrings("Msg: no message", p.messages.saidBy(p.panes[2].?));
try std.testing.expect(p.executeBuiltinLine(2, "Msg next"));
try std.testing.expectEqual(@as(u8, 2), p.messages.live_len);
try std.testing.expectEqual(Kind.@"error", p.messages.headline().?.kind);
// Longer than a message's room is CUT, never refused and never overrun:
// this word is the only way to reach that boundary without a 300-byte path.
var long: [600]u8 = @splat('x');
var line: [608]u8 = undefined;
const cmd = try std.fmt.bufPrint(&line, "Msg {s}", .{&long});
try std.testing.expect(p.executeBuiltinLine(2, cmd));
try std.testing.expectEqual(@as(usize, 256), p.messages.saidBy(p.panes[2].?).len);
}
test "an echo or a notice retires those before it, an error the error before it, a repeat counts and progress runs in place" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 });
defer p.deinit();
_ = try p.setTestFile("text\n");
const id = p.view().active;
const m = &p.messages;
m.live_len = 0;
_ = say(p, .notice, id, "first");
_ = say(p, .echo, id, "second");
try std.testing.expectEqual(@as(u8, 1), m.live_len);
try std.testing.expectEqualStrings("second", m.headline().?.text.slice());
_ = say(p, .@"error", id, "broke");
_ = say(p, .warn, id, "careful");
// The echo went with the error; the warning stands beside it.
try std.testing.expectEqual(@as(u8, 2), m.live_len);
try std.testing.expectEqual(Kind.@"error", m.headline().?.kind);
_ = say(p, .@"error", id, "broke again");
try std.testing.expectEqual(@as(u8, 2), m.live_len);
try std.testing.expectEqualStrings("broke again", m.headline().?.text.slice());
// The same again right after itself: one message, counted, its newest
// wording (and clock) kept.
for (0..9) |_| _ = say(p, .@"error", id, "broke again");
try std.testing.expectEqual(@as(u8, 2), m.live_len);
try std.testing.expectEqual(@as(u16, 10), m.headline().?.n);
// Progress updates its line in place and retires nothing.
_ = say(p, .progress, id, "Changes: jj 1/4");
_ = say(p, .progress, id, "Changes: jj 3/4");
try std.testing.expectEqual(@as(u8, 3), m.live_len);
try std.testing.expectEqualStrings("Changes: jj 3/4", m.saidBy(p.panes[id].?));
try std.testing.expectEqual(Kind.@"error", m.headline().?.kind);
// Esc in normal mode takes the warnings and errors.
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(@as(u8, 1), m.live_len);
try std.testing.expectEqual(Kind.progress, m.live[0].kind);
try std.testing.expect(m.headline() == null);
// Past the room, the oldest that is no question goes.
m.live_len = 0;
for (0..max_live + 3) |i| {
var buf: [16]u8 = undefined;
_ = say(p, .warn, id, std.fmt.bufPrint(&buf, "w{d}", .{i}) catch unreachable);
}
try std.testing.expectEqual(@as(u8, max_live), m.live_len);
try std.testing.expectEqualStrings("w3", m.live[0].text.slice());
}
test "a builtin announces itself on the notice row, an echo, and Verbose silences it" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal's tag row
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const pane = p.panes[p.view().active].?;
p.sync();
try std.testing.expect(p.settings.verbose);
// Wrap, not Collapse: a builtin that folds its own pane away is not
// what this is testing.
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap"));
try std.testing.expectEqualStrings("Wrap", p.messages.saidBy(pane));
try std.testing.expectEqual(Kind.echo, p.messages.headline().?.kind);
// A value it does not take is said, an error, and leads the row.
const wrapped = p.settings.wrap;
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap maybe"));
try std.testing.expectEqualStrings("Wrap: takes on, off", p.messages.saidBy(pane));
try std.testing.expectEqual(wrapped, p.settings.wrap);
// ...on the window's foot row, a tagline-shaped layer, not on a chip
// over the pane's body.
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const s = try p.render(frame.allocator());
try std.testing.expectEqual(@as(u8, 0), pane.notices.len);
const row = for (s.tagLayers()) |*layer| {
if (layer.rows != 0 and layer.kind == .notice_row) break layer;
} else return error.NoNoticeRow;
try std.testing.expectEqual(@as(u16, 1), row.viewport.h);
try std.testing.expectEqual(p.view().screen_h - 1, row.viewport.y);
var want: [64]u8 = undefined;
const said = try std.fmt.bufPrint(&want, "\u{2717} @p{d} Wrap: takes on, off", .{pane.serial});
const grid = s.cells[@as(usize, row.viewport.y) * s.cols ..][0..s.cols];
var text: std.ArrayList(u8) = .empty;
defer text.deinit(std.testing.allocator);
for (grid) |cell| try text.appendSlice(std.testing.allocator, cell.grapheme());
try std.testing.expect(std.mem.indexOf(u8, text.items, said) != null);
// Msg owns the row itself, so it does not announce over its own text.
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello"));
try std.testing.expectEqualStrings("hello", p.messages.saidBy(pane));
p.messages.live_len = 0;
p.settings.verbose = false;
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap"));
try std.testing.expectEqual(@as(usize, 0), p.messages.saidBy(pane).len);
}
test "the notice row leads with the most important live message, its count and places, and says how many more; with none, where the caret is" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 });
defer p.deinit();
const pane = try p.setTestFile("one\ntwo\nthree\n");
const id = p.view().active;
p.messages.live_len = 0;
p.messages.len = 0;
pane.body.cur_row = 1;
var buf: [notice_row_cap]u8 = undefined;
var row = noticeRow(p, 60, &buf);
try std.testing.expectEqualStrings("/test.txt:2", row.text[0..row.left]);
try std.testing.expectEqual(@as(usize, 60), panes.File.displayWidth(p.settings.tab, row.text));
// A notice, then an error and a warning: the error leads, newest first
// within a rank; the others are counted.
_ = say(p, .notice, id, "indexed");
_ = say(p, .warn, id, "careful");
_ = say(p, .@"error", id, "broke");
row = noticeRow(p, 60, &buf);
try std.testing.expectEqualStrings("\u{2717} /test.txt broke", row.text[0..row.left]);
try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} 3 messages \u{b7} SPC h m"));
// A burst of the same: one message, counted; the row keeps its width.
for (0..9) |_| _ = say(p, .@"error", id, "broke");
row = noticeRow(p, 60, &buf);
try std.testing.expectEqualStrings("\u{2717} /test.txt broke \u{d7}10", row.text[0..row.left]);
try std.testing.expectEqual(@as(usize, 60), panes.File.displayWidth(p.settings.tab, row.text));
// An error that names places offers the walk, its places as words.
const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1");
err.places[0] = .{ .line = 25, .col = 12 };
err.places[0].path.set("core/pick.zig");
err.places_len = 1;
row = noticeRow(p, 80, &buf);
try std.testing.expectEqualStrings("\u{2717} @p9 zig build exit 1 core/pick.zig:25:12", row.text[0..row.left]);
try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} SPC e walk"));
// Too narrow: the left gives way, the right stays whole.
row = noticeRow(p, 30, &buf);
try std.testing.expect(std.mem.endsWith(u8, row.text, "+1 \u{b7} SPC e walk"));
try std.testing.expect(panes.File.displayWidth(p.settings.tab, row.text) <= 30);
// A question outranks a warning, not an error; it is counted on the right.
_ = keep(p, .question, pane.serial, "/test.txt", "changed on disk");
row = noticeRow(p, 80, &buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "\u{2717} @p9"));
try std.testing.expect(std.mem.endsWith(u8, row.text, "+2 \u{b7} 1 question \u{b7} SPC e"));
}
test "a rolled level's last leaf is said on the notice row, the whole row, never in a chip over the body; at rest the row is the messages' again" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile("one\n");
p.messages.live_len = 0;
p.clock.now_ns = 5 * std.time.ns_per_s;
p.clock.stepped_ns = p.clock.now_ns;
// SPC t w: Wrap, run from SPC t; then SPC t again, shown.
for (" tw t") |c| p.update(.{ .key = .{ .cp = c } });
p.advance(p.clock.now_ns);
p.clock.now_ns = p.view().tag_state.due_ns;
p.sync();
_ = try p.render(p.scratch.allocator());
var buf: [notice_row_cap]u8 = undefined;
var row = noticeRow(p, 110, &buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "w Wrap: "));
try std.testing.expect(std.mem.endsWith(u8, row.text, " (last used here)"));
try std.testing.expectEqual(row.text.len, row.right);
try std.testing.expect(row.lead == null);
try std.testing.expectEqual(@as(u8, 0), pane.notices.len);
// Narrower than the line: cut to the width, never past it.
row = noticeRow(p, 12, &buf);
try std.testing.expectEqualStrings("w Wrap: Long", row.text);
// Esc: at rest, the messages' (Wrap's echo), and with none where the
// caret is.
p.update(.{ .key = .{ .cp = pardes.Key.escape } });
row = noticeRow(p, 110, &buf);
try std.testing.expect(row.lead != null);
p.messages.live_len = 0;
row = noticeRow(p, 110, &buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "/test.txt:1"));
}
test "an idle core wants no wake, and a message wakes it once, when it dims" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
while (p.nextEffect()) |_| {}
p.advance(1_000_000);
p.messages.live_len = 0;
try std.testing.expectEqual(@as(?u64, null), p.nextWake());
try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 160"));
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Msg hello"));
const said = p.messages.headline().?;
try std.testing.expect(!said.faded(p.clock.now_ns, p.settings.message_linger_ms));
// The core sleeps to its dimming, not a frame at a time.
const frame = pardes.frame_ns;
const due = said.t + 160 * std.time.ns_per_ms;
const woken = p.nextWake().?;
try std.testing.expect(woken >= due and woken < due + frame);
p.advance(woken);
try std.testing.expect(said.faded(p.clock.now_ns, p.settings.message_linger_ms));
try std.testing.expectEqual(@as(?u64, null), p.nextWake());
// A warning is bright twice as long; with no linger nothing wakes.
try std.testing.expect(p.executeBuiltinLine(p.view().active, "MessageLinger 0"));
_ = say(p, .warn, p.view().active, "careful");
try std.testing.expectEqual(@as(?u64, null), p.nextWake());
}
test "a compiler's report names its places: each place's words, the first error's rows after it its detail, a relative path the run's directory's" {
var s: Said = .{};
const rows = [_][]const u8{
"install",
"+- compile exe pardes Debug native 1 errors",
"core/pick.zig:25:12: error: expected 2 argument(s), found 3",
" const best = rank(q, name, 3) orelse continue;",
" ^~~~",
"core/look.zig:14:5: note: function declared here",
"pub fn rank(q: []const u8, name: []const u8) ?u32 {",
"error: the following command failed with 1 compilation errors:",
};
try std.testing.expectEqual(@as(usize, 2), readPlaces(&s, "/src/pardes/", &rows));
try std.testing.expectEqualStrings("/src/pardes/core/pick.zig", s.places[0].path.slice());
try std.testing.expectEqual(@as(u32, 25), s.places[0].line);
try std.testing.expectEqual(@as(u32, 12), s.places[0].col);
try std.testing.expectEqualStrings("expected 2 argument(s), found 3", s.places[0].text.slice());
try std.testing.expectEqualStrings("note: function declared here", s.places[1].text.slice());
try std.testing.expectEqual(@as(u8, 2), s.detail_len);
try std.testing.expectEqualStrings(" const best = rank(q, name, 3) orelse continue;", s.detail[0].slice());
try std.testing.expectEqualStrings(" ^~~~", s.detail[1].slice());
// No error among them: no places.
var none: Said = .{};
try std.testing.expectEqual(@as(usize, 0), readPlaces(&none, "/", &.{ "x.zig:1:1: note: only a note", "grep: nothing" }));
}
test "a burst of the same message is one message, counted, and moves nothing on the screen" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 20 });
defer p.deinit();
const pane = try p.setTestFile("text\n");
const id = p.view().active;
_ = say(p, .@"error", id, "workspace/didChangeWatchedFiles: 3 files");
p.sync();
const rects = p.view().rects;
const tag_rows = pane.tag_rows;
for (0..9) |_| _ = say(p, .@"error", id, "workspace/didChangeWatchedFiles: 3 files");
p.sync();
try std.testing.expectEqual(@as(u8, 1), p.messages.live_len);
try std.testing.expectEqual(@as(u16, 10), p.messages.headline().?.n);
try std.testing.expectEqual(rects, p.view().rects);
try std.testing.expectEqual(tag_rows, pane.tag_rows);
var buf: [notice_row_cap]u8 = undefined;
const row = noticeRow(p, 78, &buf);
try std.testing.expect(std.mem.endsWith(u8, row.text[0..row.left], "3 files \u{d7}10"));
}
test "a question never adds a row to its tag: at every width the asking tag takes the rows the tag takes at rest, its answers always shown, the question cut before them" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile("one\n");
const id = p.view().active;
// A short name: the tag's rows have room for it and the answers.
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/t/c.zig");
const f = &pane.file.?;
f.saved_hash = panes.File.fileHash(f);
for ([_]u21{ 'G', 'o', 'f', Key.escape }) |cp| p.update(.{ .key = .{ .cp = cp } });
// The tag's own words cut to one, so the question is the longer.
pane.tag.own = try p.gpa.dupe(u8, " Put");
p.update(.{ .file_changed = .{ .pane = .at(id), .bytes = "zero\n" } });
_ = p.messages.waiting(pane) orelse return error.NotAsked;
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
for (56..161) |cols| {
p.update(.{ .resize = .{ .cols = @intCast(cols), .rows = 30 } });
p.sync();
const rest = pardes.layout.wantedTagRows(p, id);
try std.testing.expect(pane.tag_rows <= @max(rest, 1));
const shown = try pardes.tagline.tagText(p, frame.allocator(), pane);
for ([_][]const u8{ "r Reload", "k Keep mine", "d Diff" }) |word| try std.testing.expect(std.mem.indexOf(u8, shown, word) != null);
_ = frame.reset(.retain_capacity);
}
}
test "a file changed on disk under unsaved text asks in its tag and never takes the keyboard: SPC e's keyboard answers, d shows the disk's lines as ghosts, Esc leaves it waiting, B2 on Reload reads it again" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 });
defer p.deinit();
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = "one\ntwo\nthree\n" });
var dir: [4096]u8 = undefined;
const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/c.zig", .{dir[0..try tmp.dir.realPath(std.testing.io, &dir)]});
defer std.testing.allocator.free(path);
const pane = try p.setTestFile("one\ntwo\nthree\n");
const id = p.view().active;
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, path);
const f = &pane.file.?;
f.saved_hash = panes.File.fileHash(f);
// Unsaved: a line typed at the end.
for ([_]u21{ 'G', 'o', 'f', 'o', 'u', 'r', Key.escape }) |cp| p.update(.{ .key = .{ .cp = cp } });
try std.testing.expect(f.revision != f.saved_revision);
const disk = "zero\none\ntwo\nthree\n";
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = disk });
p.update(.{ .file_changed = .{ .pane = .at(id), .bytes = disk } });
const i = p.messages.waiting(pane) orelse return error.NotAsked;
try std.testing.expectEqual(Kind.question, p.messages.live[i].kind);
// In its tag at rest, its answers offered in place of the tag's own
// words (the head, walk UI R1), read-only; its mark `?`.
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const shown = try pardes.tagline.tagText(p, frame.allocator(), pane);
try std.testing.expect(std.mem.endsWith(u8, shown, " changed on disk \u{25b8} r Reload k Keep mine d Diff \u{b7} SPC e to answer"));
try std.testing.expect(std.mem.startsWith(u8, shown, path));
try std.testing.expectEqual(Kind.question, p.messages.markOf(pane).?);
try std.testing.expect(std.mem.indexOf(u8, shown, "Save") == null);
const prefix = try pardes.tagline.tagPrefix(p, pane);
try std.testing.expect(std.mem.indexOf(u8, prefix, "changed on disk") == null);
// The tag's own text is no one's to edit meanwhile.
try std.testing.expect((try pardes.TagState.head(p, frame.allocator(), pane)) != null);
// Out of rest (SPC's level shown) the level's head, not the question;
// at rest again, the question.
p.update(.{ .key = .{ .cp = ' ' } });
p.advance(p.clock.now_ns);
p.clock.now_ns = p.view().tag_state.due_ns;
try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "changed on disk") == null);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "changed on disk") != null);
try std.testing.expectEqualStrings("Reload", p.messages.waitingAnswers(pane)[0].word);
// The keyboard is not its: `r` is the body's (helix's replace).
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expect(p.messages.waiting(pane) != null);
// Given the keyboard: `d` shows the disk's lines and keeps asking; Esc
// leaves it waiting.
p.view().answering = pane.serial;
p.update(.{ .key = .{ .cp = 'd' } });
const asked = &p.messages.live[p.messages.waiting(pane).?];
try std.testing.expect(asked.open);
try std.testing.expectEqual(@as(u32, 1), asked.places[0].line);
try std.testing.expectEqualStrings("+zero", asked.detail[0].slice());
try std.testing.expectEqual(pane.serial, p.view().answering);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(@as(u32, 0), p.view().answering);
try std.testing.expect(p.messages.waiting(pane) != null);
// B2 on `Reload` in its tag: read again, the question gone.
try std.testing.expectEqual(@as(?usize, null), pardes.exec.execute(p, id, "Reload"));
while (p.nextEffect()) |_| {}
try std.testing.expect(p.messages.waiting(pane) == null);
try std.testing.expectEqualStrings(disk, p.panes[id].?.file.?.content);
}
test "SPC e on an error that names places lists them under the pane and lands on the first, on a question gives its tag the keyboard, and on anything else opens the history, the newest first" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 });
defer p.deinit();
// About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
p.settings.jumps = .@"new-pane";
const pane = try p.setTestFile("one\ntwo\nthree\nfour\nfive\n");
const serial = pane.serial;
p.messages.live_len = 0;
const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1");
for ([_]u32{ 2, 4 }, 0..) |line, k| {
err.places[k] = .{ .line = line, .col = 1 };
err.places[k].path.set("/test.txt");
err.places[k].text.set("bad");
}
err.places_len = 2;
p.update(.{ .key = .{ .cp = ' ' } });
p.update(.{ .key = .{ .cp = 'e' } });
while (p.nextEffect()) |_| {}
try std.testing.expect(p.messages.headline() == null);
const here = p.paneBySerial(serial).?;
const list = p.panes[p.panes[here].?.search_pane orelse return error.NoList].?;
try std.testing.expect(std.mem.indexOf(u8, list.file.?.content, "/test.txt:4:1") != null);
try std.testing.expectEqual(@as(i32, 1), p.panes[here].?.body.cur_row);
// A question: its tag gets the keyboard.
keep(p, .question, serial, "/test.txt", "changed on disk").asks = .disk;
try std.testing.expect(p.executeBuiltinLine(here, "Message"));
try std.testing.expectEqual(serial, p.view().answering);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(@as(u32, 0), p.view().answering);
// Anything else: the history, the newest first, each with its glyph.
p.messages.live_len = 0;
_ = say(p, .notice, here, "older words");
_ = say(p, .warn, here, "newer words");
try std.testing.expect(p.executeBuiltinLine(here, "Message"));
const said_so_far = for (p.panes) |slot| {
const shown = slot orelse continue;
const f = shown.file orelse continue;
if (std.mem.endsWith(u8, f.path, config.messages_buffer)) break f.content;
} else return error.NoHistory;
const newer = std.mem.indexOf(u8, said_so_far, "! ") orelse return error.NoGlyph;
try std.testing.expect(newer < std.mem.indexOf(u8, said_so_far, "older words").?);
}
test "where jumps walk, SPC e lands an error's places as a list in the pane's walk, n walking them; SPC h m is a picker over the history in the pane's tag, the newest first, Enter on a message going to its cause, C-q keeping it as a +Messages" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 });
defer p.deinit();
p.settings.jumps = .walk;
const pane = try p.setTestFile("one\ntwo\nthree\nfour\nfive\n");
const id = p.view().active;
p.messages.live_len = 0;
const err = keep(p, .@"error", 0, "@p9 zig build", "exit 1");
for ([_]u32{ 2, 4 }, 0..) |line, k| {
err.places[k] = .{ .line = line, .col = 1 };
err.places[k].path.set("/test.txt");
err.places[k].text.set("bad");
}
err.places_len = 2;
var panes_before: usize = 0;
for (p.panes) |slot| panes_before += @intFromBool(slot != null);
for (" e") |c| p.update(.{ .key = .{ .cp = c } });
while (p.nextEffect()) |_| {}
try std.testing.expect(p.messages.headline() == null);
// Landed in this reading pane, no pane made: on the first place, the
// list's word in its trail.
var panes_now: usize = 0;
for (p.panes) |slot| panes_now += @intFromBool(slot != null);
try std.testing.expectEqual(panes_before, panes_now);
try std.testing.expectEqual(id, p.view().active);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "\u{2717} @p9 zig build 1/2") != null);
// n: the next place, the word saying so.
p.update(.{ .key = .{ .cp = 'n' } });
try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row);
try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, frame.allocator(), pane), "\u{2717} @p9 zig build 2/2") != null);
// SPC h m: the history in this pane's tag, a row a message, the newest
// first; no pane made.
_ = say(p, .echo, id, "older");
_ = say(p, .warn, id, "newest");
for (" hm") |c| p.update(.{ .key = .{ .cp = c } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(pardes.TagState.Kind.pick, p.view().tag_state.kind);
const pk = pardes.Pick.live(p).?;
try std.testing.expectEqual(pardes.Pick.Source.messages, pk.source);
var marks: [256]u16 = undefined;
var nmarks: usize = 0;
// (Row 0 is the word's own echo, `Messages`, said as it ran.)
try std.testing.expect(std.mem.indexOf(u8, pk.names.row(1, &marks, &nmarks), "newest") != null);
try std.testing.expect(std.mem.indexOf(u8, pk.names.row(2, &marks, &nmarks), "older") != null);
// Enter on a message: its cause's pane has the keyboard, the picker
// rolled up; then the history again.
p.update(.{ .key = .{ .cp = Key.down } });
p.update(.{ .key = .{ .cp = Key.enter } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(pardes.TagState.Kind.rest, p.view().tag_state.kind);
try std.testing.expectEqual(id, p.view().active);
for (" hm") |c| p.update(.{ .key = .{ .cp = c } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(pardes.TagState.Kind.pick, p.view().tag_state.kind);
// C-q: kept as the +Messages, the picker rolled up.
p.update(.{ .key = .{ .cp = 'q', .ctrl = true } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(pardes.TagState.Kind.rest, p.view().tag_state.kind);
panes_now = 0;
for (p.panes) |slot| panes_now += @intFromBool(slot != null);
try std.testing.expectEqual(panes_before + 1, panes_now);
const kept = p.panes[p.view().active].?;
try std.testing.expect(std.mem.endsWith(u8, kept.file.?.path, config.messages_buffer));
}
test "Esc at rest takes a search's tints first, then the warnings and errors, and only then goes back" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 });
defer p.deinit();
const pane = try p.setTestFile("alpha beta alpha\n");
const id = p.view().active;
p.messages.live_len = 0;
p.update(.{ .key = .{ .cp = '*' } });
p.update(.{ .key = .{ .cp = 'n' } });
while (p.nextEffect()) |_| {}
if (pane.places.pattern.len == 0 and pane.places.hits.items.len == 0) return error.NoTints;
_ = say(p, .@"error", id, "broke");
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(pane.places.pattern.len == 0 and pane.places.hits.items.len == 0);
try std.testing.expectEqual(@as(u8, 1), p.messages.live_len);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(@as(u8, 0), p.messages.live_len);
try std.testing.expectEqual(id, p.view().active);
}
test "the notice row's left is cut with `…` two blanks before its right block at least: the pane's path from the left, its name and line kept; a message from the right" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const pane = try p.setTestFile("one\ntwo\n");
const id = p.view().active;
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/home/someone/projects/a/long/way/down/core/Store.zig");
p.messages.live_len = 0;
p.messages.len = 0;
_ = say(p, .notice, id, "saved");
p.messages.live_len = 0;
var buf: [notice_row_cap]u8 = undefined;
const tab = p.settings.tab;
// The path and `1 message · SPC h m`: 40 cells.
var row = noticeRow(p, 40, &buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "…") and std.mem.endsWith(u8, row.text[0..row.left], "/Store.zig:1"));
try std.testing.expect(std.mem.endsWith(u8, row.text, "1 message \u{b7} SPC h m"));
try std.testing.expect(row.right - row.left >= 2);
try std.testing.expectEqual(@as(usize, 40), panes.File.displayWidth(tab, row.text));
// A live message: cut from the right, `…` at its end.
_ = say(p, .@"error", id, "the build failed because something somewhere went badly wrong");
row = noticeRow(p, 40, &buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "\u{2717} ") and std.mem.endsWith(u8, row.text[0..row.left], "…"));
try std.testing.expect(row.right - row.left >= 2);
try std.testing.expect(panes.File.displayWidth(tab, row.text) <= 40);
// Room for it all: nothing cut, no `…`.
row = noticeRow(p, 200, &buf);
try std.testing.expect(std.mem.indexOf(u8, row.text, "…") == null);
}
|