-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer_manager.zig
More file actions
1717 lines (1409 loc) · 59.5 KB
/
Copy pathbuffer_manager.zig
File metadata and controls
1717 lines (1409 loc) · 59.5 KB
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
const std = @import("std");
const EditorState = @import("../core/state.zig").EditorState;
const PieceTable = @import("../core/piece_table.zig").PieceTable;
const protocol = @import("protocol.zig");
const test_utils = @import("../test_utils.zig");
const TestIo = @import("../test_utils.zig").TestIo;
const MemoryTestUtils = test_utils.MemoryTestUtils;
const PerformanceTestUtils = test_utils.PerformanceTestUtils;
pub const Buffer = struct {
id: u32,
state: EditorState,
name: []const u8,
file_path: ?[]const u8,
not_loaded: bool = false,
/// mtime of `file_path` the last time we read or wrote it, in
/// nanoseconds since the Unix epoch. Used by the external-change
/// watcher: if the on-disk mtime is newer than this, somebody else
/// modified the file behind our back. 0 means "not yet stat'd."
last_disk_mtime_ns: i96 = 0,
/// "Large-file mode" flag — set at open time when the buffer's
/// byte size or line count exceeds the configured thresholds. Once
/// true, callers MUST treat it as sticky for the lifetime of the
/// buffer: tree-sitter, brackets, LSP and auto-pair are all
/// skipped. Editing a 5 MB log shouldn't choke the editor.
is_large: bool = false,
/// Rendering surface for the buffer. Disk-backed buffers remain
/// editable text; virtual report buffers may render as polished
/// presentation views.
presentation: protocol.BufferPresentation = .text,
/// True if the user asked to force-load (e.g. by re-trying past
/// the soft threshold). Lets the status bar distinguish "auto-
/// degraded" from "user-overrode".
large_overridden: bool = false,
/// Where this buffer was opened *from*. Populated by
/// `openVirtualBuffer` so closing a [References] / [Help] /
/// [Diagnostics] / [Bookmarks] / [Git Diff] etc. buffer can
/// jump the caller back to the trigger location instead of
/// dropping them wherever the next-active buffer last sat.
/// `null` for buffers opened directly from disk or scratch.
opened_from: ?OpenedFrom = null,
pub const OpenedFrom = struct {
buffer_id: u32,
row: usize,
col: usize,
};
pub fn isPresentationReadOnly(self: *const Buffer) bool {
return self.presentation == .markdown_view;
}
pub fn deinit(self: *Buffer, allocator: std.mem.Allocator) void {
self.state.deinit();
allocator.free(self.name);
if (self.file_path) |path| {
allocator.free(path);
}
}
};
/// Decision result from `classifyContent`. Carries the human-readable
/// reason so the toast on open can explain why the buffer degraded.
pub const LargeFileDecision = struct {
is_large: bool,
/// 0 = "below threshold". Otherwise the offending count
/// (bytes or lines) so callers can format a message.
triggered_by_bytes: usize = 0,
triggered_by_lines: usize = 0,
};
/// Decide whether content should open in large-file mode given the
/// configured thresholds. Lines are counted by scanning '\n' — cheap
/// even at 100MB because it's a single linear pass.
pub fn classifyContent(content: []const u8, threshold_bytes: usize, threshold_lines: usize) LargeFileDecision {
if (content.len > threshold_bytes) {
return .{ .is_large = true, .triggered_by_bytes = content.len };
}
// Skip the line count if even 1 byte per line would already be under
// the limit — cheap short-circuit on the common small-file path.
if (content.len < threshold_lines) return .{ .is_large = false };
var lines: usize = 1;
for (content) |b| {
if (b == '\n') {
lines += 1;
if (lines > threshold_lines) {
return .{ .is_large = true, .triggered_by_lines = lines };
}
}
}
return .{ .is_large = false };
}
pub fn classifyVirtualPresentation(name: []const u8, content: []const u8) protocol.BufferPresentation {
if (std.mem.eql(u8, name, "[LOGS]")) return .text;
if (isGeneratedReportBufferName(name)) return .markdown_view;
var score: usize = 0;
var heading_count: usize = 0;
var list_count: usize = 0;
var table_count: usize = 0;
var line_iter = std.mem.splitScalar(u8, content, '\n');
var scanned: usize = 0;
while (line_iter.next()) |line| {
if (scanned >= 96) break;
scanned += 1;
const trimmed = std.mem.trim(u8, line, " \t\r");
if (trimmed.len == 0) continue;
if (std.mem.startsWith(u8, trimmed, "# ") or
std.mem.startsWith(u8, trimmed, "## ") or
std.mem.startsWith(u8, trimmed, "### "))
{
heading_count += 1;
score += 4;
continue;
}
if (std.mem.startsWith(u8, trimmed, "diff --git") or
std.mem.startsWith(u8, trimmed, "@@"))
{
score += 4;
continue;
}
if (std.mem.startsWith(u8, trimmed, "```")) {
score += 3;
continue;
}
if (std.mem.eql(u8, trimmed, "---") or
std.mem.eql(u8, trimmed, "***") or
std.mem.eql(u8, trimmed, "___"))
{
score += 2;
continue;
}
if (std.mem.startsWith(u8, trimmed, "- ") or
std.mem.startsWith(u8, trimmed, "* "))
{
list_count += 1;
score += 1;
continue;
}
if (trimmed.len >= 3 and trimmed[0] == '|' and trimmed[trimmed.len - 1] == '|') {
table_count += 1;
score += 2;
continue;
}
if (std.mem.indexOfScalar(u8, trimmed, '`') != null) {
score += 1;
}
}
if (heading_count > 0) return .markdown_view;
if (table_count >= 2) return .markdown_view;
if (list_count >= 3) return .markdown_view;
return if (score >= 4) .markdown_view else .text;
}
pub fn isGeneratedReportBufferName(name: []const u8) bool {
const exact = [_][]const u8{
"[HELP]",
"[PLUGINS]",
"[Plugins]",
"[Plugin Stats]",
"[Git Status]",
"[Git Diff]",
"[Git Diff Staged]",
"[Plugin Manager]",
"[Plugin Permissions]",
"[Plugin Storage]",
"[Plugin Load]",
"[Plugin Unload]",
"[Plugin Reload]",
"[STATS]",
"[CONTROL CENTER]",
"[PROJECT BRAIN]",
"[TASKS]",
"[TASK OUTPUT]",
"[Jobs]",
"[LSP Status]",
"[Diagnostics]",
"[References]",
"[Bookmarks]",
"[Recovery Backups]",
"[Build]",
"[Zig Build]",
"[Zig Test]",
"[Zig Run]",
"[Error]",
};
for (exact) |candidate| {
if (std.mem.eql(u8, name, candidate)) return true;
}
return false;
}
pub const BufferManager = struct {
allocator: std.mem.Allocator,
io: std.Io,
buffers: std.ArrayListUnmanaged(Buffer),
active_index: usize,
next_id: u32,
untitled_counter: u32,
picker_selected: usize,
picker_scroll_offset: usize,
/// Thresholds copied from `EditorConfig` at construction. Mutable so
/// `setLargeFileThresholds` can refresh them when the user edits
/// `~/.stem/config.json`. Defaults match the schema defaults — kept
/// in sync there.
large_file_threshold_bytes: usize = 5 * 1024 * 1024,
large_file_threshold_lines: usize = 50_000,
large_file_hard_limit_bytes: usize = 100 * 1024 * 1024,
/// Optional edit hook applied to every `EditorState` this
/// manager creates. Core sets this once at boot, pointed at a
/// trampoline that forwards edits into `SyntaxManager.recordEdit`
/// — without it, tree-sitter falls back to content-match
/// subtree reuse on the parse worker (still correct, just less
/// efficient on large files).
default_edit_hook: ?EditorState.EditHook = null,
/// Construct a fresh `EditorState` with `default_edit_hook` already
/// attached. Use this everywhere a buffer's state field is
/// initialised — keeps the hook plumbing in one place instead of
/// requiring every construction site to remember the assignment.
fn newState(self: *BufferManager, initial: []const u8) !EditorState {
var s = try EditorState.init(self.allocator, self.io, initial);
s.edit_hook = self.default_edit_hook;
return s;
}
/// Re-attach the current `default_edit_hook` to every existing
/// buffer's state. Idempotent. Called by Core after wiring its
/// trampoline so buffers created before the hook was set still
/// pick it up.
pub fn refreshEditHooks(self: *BufferManager) void {
for (self.buffers.items) |*buf| {
buf.state.edit_hook = self.default_edit_hook;
}
}
pub fn init(allocator: std.mem.Allocator, io: std.Io) BufferManager {
var mgr = BufferManager{
.allocator = allocator,
.io = io,
.buffers = .empty,
.active_index = 0,
.next_id = 1,
.untitled_counter = 1,
.picker_selected = 0,
.picker_scroll_offset = 0,
};
_ = mgr.createUntitled() catch null;
return mgr;
}
/// Refresh the size thresholds used by `openFile` /
/// `loadBufferContent`. Called by `Core` whenever the config is
/// re-read so the next file open honours the new value.
pub fn setLargeFileThresholds(self: *BufferManager, threshold_bytes: u32, threshold_lines: u32, hard_limit_bytes: u32) void {
self.large_file_threshold_bytes = threshold_bytes;
self.large_file_threshold_lines = threshold_lines;
// A hard limit smaller than the soft threshold would be a
// nonsensical configuration — clamp to keep the invariant
// (soft ≤ hard) so we never reject a file we'd otherwise allow.
self.large_file_hard_limit_bytes = @max(hard_limit_bytes, threshold_bytes);
}
pub fn deinit(self: *BufferManager) void {
for (self.buffers.items) |*buf| {
buf.deinit(self.allocator);
}
self.buffers.deinit(self.allocator);
}
pub fn createUntitled(self: *BufferManager) !*Buffer {
const name = try std.fmt.allocPrint(self.allocator, "untitled-{d}", .{self.untitled_counter});
self.untitled_counter += 1;
const buffer = Buffer{
.id = self.next_id,
.state = try self.newState(""),
.name = name,
.file_path = null,
};
self.next_id += 1;
try self.buffers.append(self.allocator, buffer);
self.active_index = self.buffers.items.len - 1;
return &self.buffers.items[self.active_index];
}
pub fn openFile(self: *BufferManager, path: []const u8) !*Buffer {
for (self.buffers.items, 0..) |*buf, i| {
if (buf.file_path) |existing_path| {
if (std.mem.eql(u8, existing_path, path)) {
self.active_index = i;
return buf;
}
}
}
const file = try std.Io.Dir.openFileAbsolute(self.io, path, .{});
defer file.close(self.io);
const size = try file.length(self.io);
if (size > self.large_file_hard_limit_bytes) return error.FileTooLarge;
const content = try self.allocator.alloc(u8, @intCast(size));
defer self.allocator.free(content);
// Capture actual bytes read; never trust that we got `size` back.
// A short read (concurrent truncate, EOF before expected) would
// otherwise leave trailing uninitialized bytes in `content`.
const read_n = try file.readPositionalAll(self.io, content, 0);
const content_slice = content[0..read_n];
const decision = classifyContent(content_slice, self.large_file_threshold_bytes, self.large_file_threshold_lines);
const name = try self.allocator.dupe(u8, std.fs.path.basename(path));
errdefer self.allocator.free(name);
const file_path = try self.allocator.dupe(u8, path);
errdefer self.allocator.free(file_path);
var state = try self.newState(content_slice);
errdefer state.deinit();
if (state.file_path) |old| self.allocator.free(old);
state.file_path = try self.allocator.dupe(u8, path);
state.modified = false;
const buffer = Buffer{
.id = self.next_id,
.state = state,
.name = name,
.file_path = file_path,
.is_large = decision.is_large,
};
try self.buffers.append(self.allocator, buffer);
self.next_id += 1;
self.active_index = self.buffers.items.len - 1;
return &self.buffers.items[self.active_index];
}
pub fn openFileLazy(self: *BufferManager, path: []const u8) !*Buffer {
for (self.buffers.items, 0..) |*buf, i| {
if (buf.file_path) |existing_path| {
if (std.mem.eql(u8, existing_path, path)) {
self.active_index = i;
return buf;
}
}
}
const name = try self.allocator.dupe(u8, std.fs.path.basename(path));
errdefer self.allocator.free(name);
var state = try self.newState("");
errdefer state.deinit();
if (state.file_path) |old| self.allocator.free(old);
state.file_path = try self.allocator.dupe(u8, path);
state.modified = false;
const buf_file_path = try self.allocator.dupe(u8, path);
errdefer self.allocator.free(buf_file_path);
const buffer = Buffer{
.id = self.next_id,
.state = state,
.name = name,
.file_path = buf_file_path,
.not_loaded = true,
};
try self.buffers.append(self.allocator, buffer);
self.next_id += 1;
self.active_index = self.buffers.items.len - 1;
return &self.buffers.items[self.active_index];
}
/// Same as `openFileLazy` but does NOT change `active_index`. Used by the
/// background directory scanner so streaming-in buffers don't pull focus
/// away from whatever the user is looking at. No-op if a buffer for this
/// path already exists.
pub fn addFileLazyBackground(self: *BufferManager, path: []const u8) !void {
for (self.buffers.items) |buf| {
if (buf.file_path) |existing_path| {
if (std.mem.eql(u8, existing_path, path)) return;
}
}
const name = try self.allocator.dupe(u8, std.fs.path.basename(path));
errdefer self.allocator.free(name);
var state = try self.newState("");
errdefer state.deinit();
if (state.file_path) |old| self.allocator.free(old);
state.file_path = try self.allocator.dupe(u8, path);
state.modified = false;
const buffer = Buffer{
.id = self.next_id,
.state = state,
.name = name,
.file_path = try self.allocator.dupe(u8, path),
.not_loaded = true,
};
try self.buffers.append(self.allocator, buffer);
self.next_id += 1;
}
pub fn loadBufferContent(self: *BufferManager, buffer: *Buffer) !void {
if (!buffer.not_loaded) return;
const path = buffer.file_path orelse return;
const file = try std.Io.Dir.openFileAbsolute(self.io, path, .{});
defer file.close(self.io);
const size = try file.length(self.io);
if (size > self.large_file_hard_limit_bytes) return error.FileTooLarge;
const content = try self.allocator.alloc(u8, @intCast(size));
defer self.allocator.free(content);
const read_n = try file.readPositionalAll(self.io, content, 0);
const decision = classifyContent(content[0..read_n], self.large_file_threshold_bytes, self.large_file_threshold_lines);
buffer.state.deinit();
buffer.state = try self.newState(content[0..read_n]);
if (buffer.state.file_path) |old| self.allocator.free(old);
buffer.state.file_path = try self.allocator.dupe(u8, path);
buffer.state.modified = false;
// Record mtime so the external-change watcher has a baseline.
if (file.stat(self.io)) |st| {
buffer.last_disk_mtime_ns = st.mtime.toNanoseconds();
} else |_| {}
buffer.is_large = decision.is_large;
buffer.not_loaded = false;
}
pub fn openVirtual(self: *BufferManager, name: []const u8, content: []const u8) !void {
const presentation = classifyVirtualPresentation(name, content);
for (self.buffers.items, 0..) |*buf, i| {
if (std.mem.eql(u8, buf.name, name)) {
const cursor_row = buf.state.cursor_row;
const cursor_col = buf.state.cursor_col;
const scroll_offset = buf.state.scroll_offset;
const opened_from = buf.opened_from;
buf.state.deinit();
buf.state = try self.newState(content);
buf.state.modified = false;
const line_count = buf.state.buffer.lineCount();
const max_row = if (line_count == 0) 0 else line_count - 1;
buf.state.cursor_row = @min(cursor_row, max_row);
buf.state.cursor_col = @min(cursor_col, buf.state.getLineLength(buf.state.cursor_row));
buf.state.scroll_offset = @min(scroll_offset, max_row);
buf.presentation = presentation;
buf.opened_from = opened_from;
self.active_index = i;
return;
}
}
const buf_name = try self.allocator.dupe(u8, name);
errdefer self.allocator.free(buf_name);
var state = try self.newState(content);
errdefer state.deinit();
state.modified = false;
const buffer = Buffer{
.id = self.next_id,
.state = state,
.name = buf_name,
.file_path = null,
.presentation = presentation,
};
try self.buffers.append(self.allocator, buffer);
self.next_id += 1;
self.active_index = self.buffers.items.len - 1;
}
pub fn closeActive(self: *BufferManager) bool {
// True iff a buffer was actually removed — matches the
// historical contract: single-buffer "close" resets that
// buffer to untitled rather than removing it, and returns
// false so callers know there's still something on screen.
return self.closeActiveReturningId() != null;
}
/// Same as `closeActive` but returns the closed buffer's stable
/// `id` so callers (Core) can evict matching state from other
/// subsystems (syntax tree cache, decoration markers, etc.).
/// Returns null when there was nothing to close (single-buffer
/// case, which reuses the slot via `resetBufferToUntitled`).
pub fn closeActiveReturningId(self: *BufferManager) ?u32 {
if (self.buffers.items.len <= 1) {
if (self.buffers.items.len == 1) {
self.resetBufferToUntitled(&self.buffers.items[0]);
}
return null;
}
const closed_id = self.buffers.items[self.active_index].id;
var buf = self.buffers.orderedRemove(self.active_index);
buf.deinit(self.allocator);
if (self.active_index >= self.buffers.items.len) {
self.active_index = self.buffers.items.len - 1;
}
return closed_id;
}
fn resetBufferToUntitled(self: *BufferManager, buf: *Buffer) void {
// Build the fresh empty state first; if that fails there's no
// sane way to recover (the old state's allocations are still
// valid), so leave the buffer as-is.
var new_state = self.newState("") catch |err| {
std.log.warn("Failed to allocate empty buffer state during reset: {}", .{err});
return;
};
errdefer new_state.deinit();
const new_name = std.fmt.allocPrint(self.allocator, "untitled-{d}", .{self.untitled_counter}) catch |err| {
std.log.warn("Failed to allocate buffer name during reset: {}", .{err});
buf.state.deinit();
buf.state = new_state;
if (buf.file_path) |path| {
self.allocator.free(path);
buf.file_path = null;
}
return;
};
buf.state.deinit();
buf.state = new_state;
self.allocator.free(buf.name);
buf.name = new_name;
self.untitled_counter += 1;
if (buf.file_path) |path| {
self.allocator.free(path);
buf.file_path = null;
}
}
pub fn closeOthers(self: *BufferManager) void {
if (self.buffers.items.len <= 1) return;
const active_buf = self.buffers.orderedRemove(self.active_index);
for (self.buffers.items) |*buf| {
buf.deinit(self.allocator);
}
self.buffers.clearRetainingCapacity();
self.buffers.append(self.allocator, active_buf) catch unreachable;
self.active_index = 0;
}
pub fn getActive(self: *BufferManager) *Buffer {
return &self.buffers.items[self.active_index];
}
pub fn switchTo(self: *BufferManager, index: usize) void {
if (index < self.buffers.items.len) {
self.active_index = index;
}
}
/// Look up a buffer's current index by its stable `id`.
/// Returns null when the id no longer matches any buffer
/// (e.g. it was closed since the caller cached it).
pub fn indexOfId(self: *const BufferManager, id: u32) ?usize {
for (self.buffers.items, 0..) |buf, i| {
if (buf.id == id) return i;
}
return null;
}
pub fn nextBuffer(self: *BufferManager) void {
if (self.buffers.items.len > 1) {
self.active_index = (self.active_index + 1) % self.buffers.items.len;
}
}
pub fn prevBuffer(self: *BufferManager) void {
if (self.buffers.items.len > 1) {
if (self.active_index == 0) {
self.active_index = self.buffers.items.len - 1;
} else {
self.active_index -= 1;
}
}
}
pub fn pickerMoveUp(self: *BufferManager) void {
if (self.picker_selected > 0) {
self.picker_selected -= 1;
}
}
pub fn pickerMoveDown(self: *BufferManager) void {
if (self.picker_selected < self.buffers.items.len - 1) {
self.picker_selected += 1;
}
}
pub fn pickerSelect(self: *BufferManager) void {
self.switchTo(self.picker_selected);
}
pub fn pickerReset(self: *BufferManager) void {
self.picker_selected = self.active_index;
self.picker_scroll_offset = 0;
}
};
test "buffer manager initialization" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try std.testing.expectEqual(@as(usize, 1), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
try std.testing.expectEqual(@as(u32, 2), mgr.next_id);
try std.testing.expectEqual(@as(u32, 2), mgr.untitled_counter);
const buf = mgr.getActive();
try std.testing.expect(buf.file_path == null);
try std.testing.expect(std.mem.startsWith(u8, buf.name, "untitled-"));
}
test "buffer manager create untitled" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
const buf2 = try mgr.createUntitled();
try std.testing.expectEqual(@as(usize, 2), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
try std.testing.expect(buf2.file_path == null);
const buf2_name = buf2.name;
const buf3 = try mgr.createUntitled();
try std.testing.expectEqual(@as(usize, 3), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 2), mgr.active_index);
try std.testing.expect(!std.mem.eql(u8, buf2_name, buf3.name));
}
test "buffer manager unique buffer IDs" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
const initial_id = mgr.buffers.items[0].id;
const buf2 = try mgr.createUntitled();
const buf2_id = buf2.id;
const buf3 = try mgr.createUntitled();
try std.testing.expect(initial_id != buf2_id);
try std.testing.expect(buf2_id != buf3.id);
try std.testing.expect(initial_id != buf3.id);
}
test "buffer manager open virtual buffer" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("test-buffer", "Hello, World!");
try std.testing.expectEqual(@as(usize, 2), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
const buf = mgr.getActive();
try std.testing.expectEqualStrings("test-buffer", buf.name);
try std.testing.expect(buf.file_path == null);
try std.testing.expect(!buf.state.modified);
}
test "buffer manager open virtual updates existing" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("my-buffer", "Initial content");
try std.testing.expectEqual(@as(usize, 2), mgr.buffers.items.len);
try mgr.openVirtual("my-buffer", "Updated content");
try std.testing.expectEqual(@as(usize, 2), mgr.buffers.items.len);
const buf = mgr.getActive();
try std.testing.expectEqualStrings("my-buffer", buf.name);
}
test "buffer manager open virtual update preserves viewport state" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("[STATS]", "line 1\nline 2\nline 3\nline 4\nline 5\n");
mgr.getActive().state.cursor_row = 3;
mgr.getActive().state.cursor_col = 2;
mgr.getActive().state.scroll_offset = 2;
try mgr.openVirtual("[STATS]", "line 1 updated\nline 2 updated\nline 3 updated\nline 4 updated\nline 5 updated\n");
const buf = mgr.getActive();
try std.testing.expectEqualStrings("[STATS]", buf.name);
try std.testing.expectEqual(@as(usize, 3), buf.state.cursor_row);
try std.testing.expectEqual(@as(usize, 2), buf.state.cursor_col);
try std.testing.expectEqual(@as(usize, 2), buf.state.scroll_offset);
}
test "buffer manager marks markdown virtual buffers for presentation rendering" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("[Plugin Manager]", "# Plugin Manager\n\n- Loaded: 4\n");
const buf = mgr.getActive();
try std.testing.expectEqual(.markdown_view, buf.presentation);
try std.testing.expect(buf.isPresentationReadOnly());
}
test "buffer manager keeps plain virtual buffers as editable-style text presentation" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("[RAW]", "plain output\nwithout markdown markers\n");
const buf = mgr.getActive();
try std.testing.expectEqual(.text, buf.presentation);
try std.testing.expect(!buf.isPresentationReadOnly());
}
test "buffer manager treats diff virtual buffers as presentation rendering" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("[Git Diff]", "diff --git a/src/main.zig b/src/main.zig\n@@ -1 +1 @@\n-old\n+new\n");
const buf = mgr.getActive();
try std.testing.expectEqual(.markdown_view, buf.presentation);
}
test "buffer manager refreshes virtual presentation on update" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try mgr.openVirtual("[Report]", "plain output\n");
try std.testing.expectEqual(.text, mgr.getActive().presentation);
try mgr.openVirtual("[Report]", "# Report\n\n- Ready: yes\n");
try std.testing.expectEqual(.markdown_view, mgr.getActive().presentation);
}
test "buffer manager marks every known generated report buffer as presentation" {
const Case = struct {
name: []const u8,
content: []const u8,
};
const cases = [_]Case{
.{ .name = "[HELP]", .content = "Stem help text\n\nUse Space for commands.\n" },
.{ .name = "[PLUGINS]", .content = "Plugin Manager\nLoaded plugins: 4\n" },
.{ .name = "[Plugins]", .content = "Plugin inspection\nRuntime: wasm\n" },
.{ .name = "[Git Status]", .content = "On branch main\nStaged: 0 Unstaged: 0 Untracked: 0\nWorking tree clean.\n" },
.{ .name = "[Git Diff]", .content = "No unstaged changes.\n" },
.{ .name = "[Git Diff Staged]", .content = "No staged changes.\n" },
.{ .name = "[Plugin Manager]", .content = "Plugin Manager dashboard unavailable.\n" },
.{ .name = "[Plugin Permissions]", .content = "Permission dashboard unavailable.\n" },
.{ .name = "[Plugin Storage]", .content = "plugin_manager storage:\ndashboard.opens: 1\n" },
.{ .name = "[Plugin Load]", .content = "Plugin loading is managed through the stem plugin CLI.\n" },
.{ .name = "[Plugin Unload]", .content = "Plugin removal instructions.\n" },
.{ .name = "[Plugin Reload]", .content = "Reloading installed plugins...\n" },
.{ .name = "[STATS]", .content = "Vigil\nTelemetry bridge: initialized\n" },
.{ .name = "[CONTROL CENTER]", .content = "Control Center\nBuild status: idle\n" },
.{ .name = "[PROJECT BRAIN]", .content = "Project Brain\nWorkspace: stem\n" },
.{ .name = "[TASKS]", .content = "Project Tasks\nzig.build zig build build.zig\n" },
.{ .name = "[TASK OUTPUT]", .content = "Task Output\nStarted background task #1.\n" },
.{ .name = "[Jobs]", .content = "Background Jobs\nActive: 0\n" },
.{ .name = "[LSP Status]", .content = "LSP Status\nServers: 2 running\n" },
.{ .name = "[Diagnostics]", .content = "=== Diagnostics ===\n\nLn 4: [WARN] unused local\n" },
.{ .name = "[References]", .content = "Symbol: WorkerState\nLn 12: pub const WorkerState\n" },
.{ .name = "[Bookmarks]", .content = "Bookmarks\nSlot Line File\n" },
.{ .name = "[Recovery Backups]", .content = "Recovery backups in /tmp\n(no backups present)\n" },
.{ .name = "[Build]", .content = "Could not find build.zig in any parent directory.\n" },
.{ .name = "[Zig Build]", .content = "BUILD SUCCESSFUL\nDuration: 10ms\n" },
.{ .name = "[Zig Test]", .content = "ALL TESTS PASSED\nDuration: 10ms\n" },
.{ .name = "[Zig Run]", .content = "RUN COMPLETED\nDuration: 10ms\n" },
.{ .name = "[Error]", .content = "Reload failed: FileNotFound\n" },
};
for (cases) |case| {
try std.testing.expectEqual(.markdown_view, classifyVirtualPresentation(case.name, case.content));
}
}
test "buffer manager keeps document-like virtual buffers editable text" {
try std.testing.expectEqual(.text, classifyVirtualPresentation("[Scratch]", ""));
try std.testing.expectEqual(.text, classifyVirtualPresentation("Scratch-2", ""));
try std.testing.expectEqual(.text, classifyVirtualPresentation("[HEAD] main.zig", "const std = @import(\"std\");\n"));
try std.testing.expectEqual(.text, classifyVirtualPresentation("[Plugin JSON]", "{\"loaded\":true}\n"));
try std.testing.expectEqual(.text, classifyVirtualPresentation("plain-buffer", "plain output\n"));
}
test "buffer manager switch to buffer" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
_ = try mgr.createUntitled();
_ = try mgr.createUntitled();
try std.testing.expectEqual(@as(usize, 3), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 2), mgr.active_index);
mgr.switchTo(0);
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
mgr.switchTo(1);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
mgr.switchTo(100);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
}
test "buffer manager next and prev buffer" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
_ = try mgr.createUntitled();
_ = try mgr.createUntitled();
mgr.prevBuffer();
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
mgr.prevBuffer();
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
mgr.prevBuffer();
try std.testing.expectEqual(@as(usize, 2), mgr.active_index);
mgr.nextBuffer();
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
mgr.nextBuffer();
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
}
test "buffer manager next prev single buffer" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try std.testing.expectEqual(@as(usize, 1), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
mgr.nextBuffer();
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
mgr.prevBuffer();
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
}
test "buffer manager close active" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
_ = try mgr.createUntitled();
_ = try mgr.createUntitled();
try std.testing.expectEqual(@as(usize, 3), mgr.buffers.items.len);
const closed = mgr.closeActive();
try std.testing.expect(closed);
try std.testing.expectEqual(@as(usize, 2), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
const closed2 = mgr.closeActive();
try std.testing.expect(closed2);
try std.testing.expectEqual(@as(usize, 1), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 0), mgr.active_index);
}
test "buffer manager close last buffer clears it" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
try std.testing.expectEqual(@as(usize, 1), mgr.buffers.items.len);
const closed = mgr.closeActive();
try std.testing.expect(!closed);
try std.testing.expectEqual(@as(usize, 1), mgr.buffers.items.len);
const buf = mgr.getActive();
try std.testing.expect(buf.file_path == null);
try std.testing.expect(std.mem.startsWith(u8, buf.name, "untitled-"));
}
test "buffer manager close active from middle" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
_ = try mgr.createUntitled();
_ = try mgr.createUntitled();
_ = try mgr.createUntitled();
mgr.switchTo(1);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
_ = mgr.closeActive();
try std.testing.expectEqual(@as(usize, 3), mgr.buffers.items.len);
try std.testing.expectEqual(@as(usize, 1), mgr.active_index);
}
test "buffer manager close others" {
const allocator = std.testing.allocator;
var io_ctx = TestIo.init(allocator);
defer io_ctx.deinit();
const io = io_ctx.io();
var mgr = BufferManager.init(allocator, io);
defer mgr.deinit();
_ = try mgr.createUntitled();
try mgr.openVirtual("keep-this", "content");
_ = try mgr.createUntitled();
mgr.switchTo(2);
const active_name = mgr.getActive().name;