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
|
//! Search thread that handles searching a terminal for a string match.
//! This is expected to run on a dedicated thread to try to prevent too much
//! overhead to other terminal read/write operations.
//!
//! The current architecture of search does acquire global locks for accessing
//! terminal data, so there's still added contention, but we do our best to
//! minimize this by trading off memory usage (copying data to minimize lock
//! time).
pub const Thread = @This();
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Mutex = std.Io.Mutex;
const global = @import("../../global.zig");
const xev = global.xev;
const internal_os = @import("../../os/main.zig");
const BlockingQueue = @import("../../datastruct/main.zig").BlockingQueue;
const MessageData = @import("../../datastruct/main.zig").MessageData;
const point = @import("../point.zig");
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const UntrackedHighlight = @import("../highlight.zig").Untracked;
const ScreenSet = @import("../ScreenSet.zig");
const Terminal = @import("../Terminal.zig");
const ScreenSearch = @import("screen.zig").ScreenSearch;
const TerminalSearch = @import("terminal.zig").TerminalSearch;
const log = std.log.scoped(.search_thread);
// TODO: Some stuff that could be improved:
// - pause the refresh timer when the terminal isn't focused
// - we probably want to know our progress through the search
// for viewport matches so we can show n/total UI.
// - notifications should be coalesced to avoid spamming a massive
// amount of events if the terminal is changing rapidly.
/// The interval at which we refresh the terminal state to check if
/// there are any changes that require us to re-search. This should be
/// balanced to be fast enough to be responsive but not so fast that
/// we hold the terminal lock too often.
const REFRESH_INTERVAL = 24; // 40 FPS
/// Allocator used for some state
alloc: std.mem.Allocator,
/// The mailbox that can be used to send this thread messages. Note
/// this is a blocking queue so if it is full you will get errors (or block).
mailbox: *Mailbox,
/// The event loop for the search thread.
loop: xev.Loop,
/// This can be used to wake up the renderer and force a render safely from
/// any thread.
wakeup: xev.Async,
wakeup_c: xev.Completion = .{},
/// This can be used to stop the thread on the next loop iteration.
stop: xev.Async,
stop_c: xev.Completion = .{},
/// The timer used for refreshing the terminal state to determine if
/// we have a stale active area, viewport, screen change, etc. This is
/// CPU intensive so we stop doing this under certain conditions.
refresh: xev.Timer,
refresh_c: xev.Completion = .{},
refresh_active: bool = false,
/// Search state. Starts as null and is populated when a search is
/// started (a needle is given).
search: ?TerminalSearch = null,
/// The last-notified values used to diff search state into events.
notify_state: NotifyState = .{},
/// The options used to initialize this thread.
opts: Options,
/// Initialize the thread. This does not START the thread. This only sets
/// up all the internal state necessary prior to starting the thread. It
/// is up to the caller to start the thread with the threadMain entrypoint.
pub fn init(alloc: Allocator, opts: Options) !Thread {
// The mailbox for messaging this thread
var mailbox = try Mailbox.create(alloc);
errdefer mailbox.destroy(alloc);
// Create our event loop.
var loop = try xev.Loop.init(.{});
errdefer loop.deinit();
// This async handle is used to "wake up" the renderer and force a render.
var wakeup_h = try xev.Async.init();
errdefer wakeup_h.deinit();
// This async handle is used to stop the loop and force the thread to end.
var stop_h = try xev.Async.init();
errdefer stop_h.deinit();
// Refresh timer, see comments.
var refresh_h = try xev.Timer.init();
errdefer refresh_h.deinit();
return .{
.alloc = alloc,
.mailbox = mailbox,
.loop = loop,
.wakeup = wakeup_h,
.stop = stop_h,
.refresh = refresh_h,
.opts = opts,
};
}
/// Clean up the thread. This is only safe to call once the thread
/// completes executing; the caller must join prior to this.
pub fn deinit(self: *Thread) void {
self.refresh.deinit();
self.wakeup.deinit();
self.stop.deinit();
self.loop.deinit();
// Nothing can possibly access the mailbox anymore, destroy it.
self.mailbox.destroy(self.alloc);
if (self.search) |*s| {
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
s.deinit(self.opts.terminal);
}
}
/// The main entrypoint for the thread.
pub fn threadMain(self: *Thread) void {
// Call child function so we can use errors...
self.threadMain_() catch |err| {
// In the future, we should expose this on the thread struct.
log.warn("search thread err={}", .{err});
};
}
fn threadMain_(self: *Thread) !void {
defer log.debug("search thread exited", .{});
// Right now, on Darwin, `std.Thread.setName` can only name the current
// thread, and we have no way to get the current thread from within it,
// so instead we use this code to name the thread instead.
if (comptime builtin.os.tag.isDarwin()) {
internal_os.macos.pthread_setname_np(&"search".*);
// We can run with lower priority than other threads.
const class: internal_os.macos.QosClass = .utility;
if (internal_os.macos.setQosClass(class)) {
log.debug("thread QoS class set class={}", .{class});
} else |err| {
log.warn("error setting QoS class err={}", .{err});
}
}
// Start the async handlers
self.wakeup.wait(&self.loop, &self.wakeup_c, Thread, self, wakeupCallback);
self.stop.wait(&self.loop, &self.stop_c, Thread, self, stopCallback);
// Send an initial wakeup so we drain our mailbox immediately.
try self.wakeup.notify();
// Start the refresh timer
self.startRefreshTimer();
// Run
log.debug("starting search thread", .{});
defer {
log.debug("starting search thread shutdown", .{});
// Send the quit message
if (self.opts.event_cb) |cb| {
cb(.quit, self.opts.event_userdata);
}
}
// Unlike some of our other threads, we interleave search work
// with our xev loop so that we can try to make forward search progress
// while also listening for messages.
while (true) {
// If our loop is canceled then we drain our messages and quit.
if (self.loop.stopped()) {
while (self.mailbox.pop(global.io())) |message| {
log.debug("mailbox message ignored during shutdown={}", .{message});
}
return;
}
const s: *TerminalSearch = if (self.search) |*s| s else {
// If we're not actively searching, we can block the loop
// until it does some work.
try self.loop.run(.once);
continue;
};
// If we have an active search, we always send any pending
// notifications. Even if the search is complete, there may be
// notifications to send.
if (self.opts.event_cb) |cb| {
self.notify(s, cb, self.opts.event_userdata);
}
if (s.isComplete()) {
// If our search is complete, there's no more work to do, we
// can block until we have an xev action.
try self.loop.run(.once);
continue;
}
// Tick the search. This will trigger any event callbacks, lock
// for data loading, etc.
switch (s.tick()) {
// We're complete now when we were not before. Notify!
.complete => {},
// Forward progress was made.
.progress => {},
// All searches are blocked. Let's grab the lock and feed data.
.blocked => {
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
self.feedLocked(s);
},
}
// We have an active search, so we only want to process messages
// we have but otherwise return immediately so we can continue the
// search. If the above completed the search, we still want to
// go around the loop as quickly as possible to send notifications,
// and then we'll block on the loop next time.
try self.loop.run(.no_wait);
}
}
/// Feed the search from the terminal state. The terminal mutex must
/// be held by the caller.
fn feedLocked(self: *Thread, s: *TerminalSearch) void {
const t = self.opts.terminal;
// See the `search_viewport_dirty` flag on the terminal to know
// what exactly this is for. But, if this is set, we know the renderer
// found the viewport/active area dirty, so the active area must be
// re-scanned.
const active_dirty = t.flags.search_viewport_dirty;
t.flags.search_viewport_dirty = false;
s.feed(t, active_dirty);
}
/// Drain the mailbox.
fn drainMailbox(self: *Thread) !void {
while (self.mailbox.pop(global.io())) |message| {
log.debug("mailbox message={}", .{message});
switch (message) {
.change_needle => |v| {
defer v.deinit();
try self.changeNeedle(v.slice());
},
.select => |v| try self.select(v),
}
}
}
fn select(self: *Thread, sel: ScreenSearch.Select) !void {
const s = if (self.search) |*s| s else return;
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
if (try s.select(self.opts.terminal, sel, .if_needed)) {
// No matter what we reset our selected match cache. This will
// trigger a callback which will trigger the renderer to wake up
// so it can be notified the screen scrolled.
self.notify_state.selected = null;
}
}
/// Change the search term to the given value.
fn changeNeedle(self: *Thread, needle: []const u8) !void {
log.debug("changing search needle to '{s}'", .{needle});
// Stop the previous search
if (self.search) |*s| {
// If our search is unchanged, do nothing.
if (std.ascii.eqlIgnoreCase(s.needle(), needle)) return;
{
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
s.deinit(self.opts.terminal);
}
self.search = null;
self.notify_state = .{};
// When the search changes then we need to emit that it stopped.
if (self.opts.event_cb) |cb| {
cb(
.{ .total_matches = 0 },
self.opts.event_userdata,
);
cb(
.{ .selected_match = null },
self.opts.event_userdata,
);
cb(
.{ .viewport_matches = &.{} },
self.opts.event_userdata,
);
}
}
// No needle means stop the search.
if (needle.len == 0) return;
// Setup our search state.
self.search = try .init(self.alloc, needle);
self.notify_state = .{};
// We need to grab the terminal lock and do an initial feed.
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
self.feedLocked(&self.search.?);
}
/// Notify about any changes to the search state by diffing against
/// the last-notified values.
///
/// This doesn't require any locking as it only reads search-owned state.
fn notify(
self: *Thread,
s: *TerminalSearch,
cb: EventCallback,
ud: ?*anyopaque,
) void {
const state = &self.notify_state;
// A screen switch makes all previously notified per-screen state
// stale, so reset it to force recalculations and notifications.
if (state.key != s.active_key) {
state.key = s.active_key;
state.total = null;
state.selected = null;
}
const screen_search = s.activeScreenSearch() orelse return;
// Check our total match data
const total = screen_search.matchesLen();
if (total != state.total) {
log.debug("notifying total matches={}", .{total});
state.total = total;
cb(.{ .total_matches = total }, ud);
}
// Check our viewport matches. If they're stale, we collect them
// now. We do this as part of notify and not tick because the
// viewport search is very fast and doesn't require ticked progress
// or feeds.
if (s.stale_viewport_matches) viewport: {
const matches = s.viewportMatches() catch |err| {
log.warn("error collecting viewport matches err={}", .{err});
break :viewport;
};
log.debug("notifying viewport matches len={}", .{matches.len});
cb(.{ .viewport_matches = matches }, ud);
}
// Check our last selected match data.
if (screen_search.selected) |m| match: {
const flattened = screen_search.selectedMatch() orelse break :match;
const untracked = flattened.untracked();
if (state.selected) |prev| {
if (prev.idx == m.idx and prev.highlight.eql(untracked)) {
// Same selection, don't update it.
break :match;
}
}
// New selection, notify!
state.selected = .{
.idx = m.idx,
.highlight = untracked,
};
log.debug("notifying selection updated idx={}", .{m.idx});
cb(
.{ .selected_match = .{
.idx = m.idx,
.highlight = flattened,
} },
ud,
);
} else if (state.selected != null) {
log.debug("notifying selection cleared", .{});
state.selected = null;
cb(
.{ .selected_match = null },
ud,
);
}
// Send our complete notification if we just completed.
if (!state.complete and s.isComplete()) {
log.debug("notifying search complete", .{});
state.complete = true;
cb(.complete, ud);
}
}
fn startRefreshTimer(self: *Thread) void {
// Set our active state so it knows we're running. We set this before
// even checking the active state in case we have a pending shutdown.
self.refresh_active = true;
// If our timer is already active, then we don't have to do anything.
if (self.refresh_c.state() == .active) return;
// Start the timer which loops
self.refresh.run(
&self.loop,
&self.refresh_c,
REFRESH_INTERVAL,
Thread,
self,
refreshCallback,
);
}
fn stopRefreshTimer(self: *Thread) void {
// This will stop the refresh on the next iteration.
self.refresh_active = false;
}
fn wakeupCallback(
self_: ?*Thread,
_: *xev.Loop,
_: *xev.Completion,
r: xev.Async.WaitError!void,
) xev.CallbackAction {
_ = r catch |err| {
log.warn("error in wakeup err={}", .{err});
return .rearm;
};
const self = self_.?;
// When we wake up, we drain the mailbox. Mailbox producers should
// wake up our thread after publishing.
self.drainMailbox() catch |err|
log.warn("error draining mailbox err={}", .{err});
return .rearm;
}
fn stopCallback(
self_: ?*Thread,
_: *xev.Loop,
_: *xev.Completion,
r: xev.Async.WaitError!void,
) xev.CallbackAction {
_ = r catch unreachable;
self_.?.loop.stop();
return .disarm;
}
fn refreshCallback(
self_: ?*Thread,
_: *xev.Loop,
_: *xev.Completion,
r: xev.Timer.RunError!void,
) xev.CallbackAction {
_ = r catch unreachable;
const self: *Thread = self_ orelse {
// This shouldn't happen so we log it.
log.warn("refresh callback fired without data set", .{});
return .disarm;
};
// Run our feed if we have a search active.
if (self.search) |*s| {
self.opts.mutex.lockUncancelable(global.io());
defer self.opts.mutex.unlock(global.io());
self.feedLocked(s);
}
// Only continue if we're still active
if (self.refresh_active) self.refresh.run(
&self.loop,
&self.refresh_c,
REFRESH_INTERVAL,
Thread,
self,
refreshCallback,
);
return .disarm;
}
pub const Options = struct {
/// Mutex that must be held while reading/writing the terminal.
mutex: *Mutex,
/// The terminal data to search.
terminal: *Terminal,
/// The callback for events from the search thread along with optional
/// userdata. This can be null if you don't want to receive events,
/// which could be useful for a one-time search (although, odd, you
/// should use our search structures directly then).
event_cb: ?EventCallback = null,
event_userdata: ?*anyopaque = null,
};
pub const EventCallback = *const fn (event: Event, userdata: ?*anyopaque) void;
/// The type used for sending messages to the thread.
pub const Mailbox = BlockingQueue(Message, 64);
/// The messages that can be sent to the thread.
pub const Message = union(enum) {
/// Represents a write request. Magic number comes from the max size
/// we want this union to be.
pub const WriteReq = MessageData(u8, 255);
/// Change the search term. If no prior search term is given this
/// will start a search. If an existing search term is given this will
/// stop the prior search and start a new one.
change_needle: WriteReq,
/// Select a search result.
select: ScreenSearch.Select,
};
/// Events that can be emitted from the search thread. The caller
/// chooses to handle these as they see fit.
pub const Event = union(enum) {
/// Search is quitting. The search thread is exiting.
quit,
/// Search is complete for the given needle on all screens.
complete,
/// Total matches on the current active screen have changed.
total_matches: usize,
/// Selected match changed.
selected_match: ?SelectedMatch,
/// Matches in the viewport have changed. The memory is owned by the
/// search thread and is only valid during the callback.
viewport_matches: []const FlattenedHighlight,
pub const SelectedMatch = struct {
idx: usize,
highlight: FlattenedHighlight,
};
};
/// The last-notified values used by `notify` to diff search state
/// into events.
const NotifyState = struct {
/// The active screen key the state below was captured against.
key: ScreenSet.Key = .primary,
/// Last notified total matches count
total: ?usize = null,
/// Last notified selected match
selected: ?Selected = null,
/// True if we sent the complete notification yet.
complete: bool = false,
const Selected = struct {
idx: usize,
highlight: UntrackedHighlight,
};
};
const TestUserData = struct {
const Self = @This();
reset: std.Io.Event = .unset,
total: usize = 0,
selected: ?Event.SelectedMatch = null,
viewport: []FlattenedHighlight = &.{},
fn deinit(self: *Self) void {
for (self.viewport) |*hl| hl.deinit(testing.allocator);
testing.allocator.free(self.viewport);
}
fn callback(event: Event, userdata: ?*anyopaque) void {
const ud: *Self = @ptrCast(@alignCast(userdata.?));
switch (event) {
.quit => {},
.complete => ud.reset.set(global.io()),
.total_matches => |v| ud.total = v,
.selected_match => |v| ud.selected = v,
.viewport_matches => |v| {
for (ud.viewport) |*hl| hl.deinit(testing.allocator);
testing.allocator.free(ud.viewport);
ud.viewport = testing.allocator.alloc(
FlattenedHighlight,
v.len,
) catch unreachable;
for (ud.viewport, v) |*dst, src| {
dst.* = src.clone(testing.allocator) catch unreachable;
}
},
}
}
};
test {
const alloc = testing.allocator;
const io = testing.io;
var mutex: std.Io.Mutex = .init;
var t: Terminal = try .init(io, alloc, .{ .cols = 20, .rows = 2 });
defer t.deinit(alloc);
var stream = t.vtStream();
defer stream.deinit();
stream.nextSlice("Hello, world");
var ud: TestUserData = .{};
defer ud.deinit();
var thread: Thread = try .init(alloc, .{
.mutex = &mutex,
.terminal = &t,
.event_cb = &TestUserData.callback,
.event_userdata = &ud,
});
defer thread.deinit();
var os_thread = try std.Thread.spawn(
.{},
threadMain,
.{&thread},
);
// Start our search
_ = thread.mailbox.push(
io,
.{ .change_needle = try .init(
alloc,
@as([]const u8, "world"),
) },
.forever,
);
try thread.wakeup.notify();
// Wait for completion
try ud.reset.waitTimeout(testing.io, .{ .duration = .{ .clock = .awake, .raw = .fromMilliseconds(100) } });
// Stop the thread
try thread.stop.notify();
os_thread.join();
// 1 total matches
try testing.expectEqual(1, ud.total);
try testing.expectEqual(1, ud.viewport.len);
{
const sel = ud.viewport[0].untracked();
try testing.expectEqual(point.Point{ .screen = .{
.x = 7,
.y = 0,
} }, t.screens.active.pages.pointFromPin(.screen, sel.start).?);
try testing.expectEqual(point.Point{ .screen = .{
.x = 11,
.y = 0,
} }, t.screens.active.pages.pointFromPin(.screen, sel.end).?);
}
}
|