-
Notifications
You must be signed in to change notification settings - Fork 637
/
Copy pathstream_handler.zig
1533 lines (1315 loc) · 56.7 KB
/
stream_handler.zig
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 builtin = @import("builtin");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const xev = @import("xev");
const apprt = @import("../apprt.zig");
const build_config = @import("../build_config.zig");
const configpkg = @import("../config.zig");
const internal_os = @import("../os/main.zig");
const renderer = @import("../renderer.zig");
const termio = @import("../termio.zig");
const terminal = @import("../terminal/main.zig");
const terminfo = @import("../terminfo/main.zig");
const posix = std.posix;
const log = std.log.scoped(.io_handler);
/// True if we should disable the kitty keyboard protocol. We have to
/// disable this on GLFW because GLFW input events don't support the
/// correct granularity of events.
const disable_kitty_keyboard_protocol = apprt.runtime == apprt.glfw;
/// This is used as the handler for the terminal.Stream type. This is
/// stateful and is expected to live for the entire lifetime of the terminal.
/// It is NOT VALID to stop a stream handler, create a new one, and use that
/// unless all of the member fields are copied.
pub const StreamHandler = struct {
alloc: Allocator,
size: *renderer.Size,
terminal: *terminal.Terminal,
/// Mailbox for data to the termio thread.
termio_mailbox: *termio.Mailbox,
/// Mailbox for the surface.
surface_mailbox: apprt.surface.Mailbox,
/// The shared render state
renderer_state: *renderer.State,
/// The mailbox for notifying the renderer of things.
renderer_mailbox: *renderer.Thread.Mailbox,
/// A handle to wake up the renderer. This hints to the renderer that that
/// a repaint should happen.
renderer_wakeup: xev.Async,
/// The default cursor state. This is used with CSI q. This is
/// set to true when we're currently in the default cursor state.
default_cursor: bool = true,
default_cursor_style: terminal.CursorStyle,
default_cursor_blink: ?bool,
default_cursor_color: ?terminal.color.RGB,
/// Actual cursor color. This can be changed with OSC 12. If unset, falls
/// back to the default cursor color.
cursor_color: ?terminal.color.RGB,
/// The default foreground and background color are those set by the user's
/// config file.
default_foreground_color: terminal.color.RGB,
default_background_color: terminal.color.RGB,
/// The foreground and background color as set by an OSC 10 or OSC 11
/// sequence. If unset then the respective color falls back to the default
/// value.
foreground_color: ?terminal.color.RGB,
background_color: ?terminal.color.RGB,
/// The response to use for ENQ requests. The memory is owned by
/// whoever owns StreamHandler.
enquiry_response: []const u8,
/// The color reporting format for OSC requests.
osc_color_report_format: configpkg.Config.OSCColorReportFormat,
//---------------------------------------------------------------
// Internal state
/// The APC command handler maintains the APC state. APC is like
/// CSI or OSC, but it is a private escape sequence that is used
/// to send commands to the terminal emulator. This is used by
/// the kitty graphics protocol.
apc: terminal.apc.Handler = .{},
/// The DCS handler maintains DCS state. DCS is like CSI or OSC,
/// but requires more stateful parsing. This is used by functionality
/// such as XTGETTCAP.
dcs: terminal.dcs.Handler = .{},
/// This is set to true when a message was written to the termio
/// mailbox. This can be used by callers to determine if they need
/// to wake up the termio thread.
termio_messaged: bool = false,
/// This is set to true when we've seen a title escape sequence. We use
/// this to determine if we need to default the window title.
seen_title: bool = false,
pub fn deinit(self: *StreamHandler) void {
self.apc.deinit();
self.dcs.deinit();
}
/// This queues a render operation with the renderer thread. The render
/// isn't guaranteed to happen immediately but it will happen as soon as
/// practical.
pub inline fn queueRender(self: *StreamHandler) !void {
try self.renderer_wakeup.notify();
}
/// Change the configuration for this handler.
pub fn changeConfig(self: *StreamHandler, config: *termio.DerivedConfig) void {
self.osc_color_report_format = config.osc_color_report_format;
self.enquiry_response = config.enquiry_response;
self.default_foreground_color = config.foreground.toTerminalRGB();
self.default_background_color = config.background.toTerminalRGB();
self.default_cursor_style = config.cursor_style;
self.default_cursor_blink = config.cursor_blink;
self.default_cursor_color = if (!config.cursor_invert and config.cursor_color != null)
config.cursor_color.?.toTerminalRGB()
else
null;
// If our cursor is the default, then we update it immediately.
if (self.default_cursor) self.setCursorStyle(.default) catch |err| {
log.warn("failed to set default cursor style: {}", .{err});
};
// The config could have changed any of our colors so update mode 2031
self.surfaceMessageWriter(.{ .report_color_scheme = false });
}
inline fn surfaceMessageWriter(
self: *StreamHandler,
msg: apprt.surface.Message,
) void {
// See messageWriter which has similar logic and explains why
// we may have to do this.
if (self.surface_mailbox.push(msg, .{ .instant = {} }) == 0) {
self.renderer_state.mutex.unlock();
defer self.renderer_state.mutex.lock();
_ = self.surface_mailbox.push(msg, .{ .forever = {} });
}
}
inline fn messageWriter(self: *StreamHandler, msg: termio.Message) void {
self.termio_mailbox.send(msg, self.renderer_state.mutex);
self.termio_messaged = true;
}
/// Send a renderer message and unlock the renderer state mutex
/// if necessary to ensure we don't deadlock.
///
/// This assumes the renderer state mutex is locked.
inline fn rendererMessageWriter(
self: *StreamHandler,
msg: renderer.Message,
) void {
// See termio.Mailbox.send for more details on how this works.
// Try instant first. If it works then we can return.
if (self.renderer_mailbox.push(msg, .{ .instant = {} }) > 0) {
return;
}
// Instant would have blocked. Release the renderer mutex,
// wake up the renderer to allow it to process the message,
// and then try again.
self.renderer_state.mutex.unlock();
defer self.renderer_state.mutex.lock();
self.renderer_wakeup.notify() catch |err| {
// This is an EXTREMELY unlikely case. We still don't return
// and attempt to send the message because its most likely
// that everything is fine, but log in case a freeze happens.
log.warn(
"failed to notify renderer, may deadlock err={}",
.{err},
);
};
_ = self.renderer_mailbox.push(msg, .{ .forever = {} });
}
pub fn dcsHook(self: *StreamHandler, dcs: terminal.DCS) !void {
var cmd = self.dcs.hook(self.alloc, dcs) orelse return;
defer cmd.deinit();
try self.dcsCommand(&cmd);
}
pub fn dcsPut(self: *StreamHandler, byte: u8) !void {
var cmd = self.dcs.put(byte) orelse return;
defer cmd.deinit();
try self.dcsCommand(&cmd);
}
pub fn dcsUnhook(self: *StreamHandler) !void {
var cmd = self.dcs.unhook() orelse return;
defer cmd.deinit();
try self.dcsCommand(&cmd);
}
fn dcsCommand(self: *StreamHandler, cmd: *terminal.dcs.Command) !void {
// log.warn("DCS command: {}", .{cmd});
switch (cmd.*) {
.tmux => |tmux| {
// TODO: process it
log.warn("tmux control mode event unimplemented cmd={}", .{tmux});
},
.xtgettcap => |*gettcap| {
const map = comptime terminfo.ghostty.xtgettcapMap();
while (gettcap.next()) |key| {
const response = map.get(key) orelse continue;
self.messageWriter(.{ .write_stable = response });
}
},
.decrqss => |decrqss| {
var response: [128]u8 = undefined;
var stream = std.io.fixedBufferStream(&response);
const writer = stream.writer();
// Offset the stream position to just past the response prefix.
// We will write the "payload" (if any) below. If no payload is
// written then we send an invalid DECRPSS response.
const prefix_fmt = "\x1bP{d}$r";
const prefix_len = std.fmt.comptimePrint(prefix_fmt, .{0}).len;
stream.pos = prefix_len;
switch (decrqss) {
// Invalid or unhandled request
.none => {},
.sgr => {
const buf = try self.terminal.printAttributes(stream.buffer[stream.pos..]);
// printAttributes wrote into our buffer, so adjust the stream
// position
stream.pos += buf.len;
try writer.writeByte('m');
},
.decscusr => {
const blink = self.terminal.modes.get(.cursor_blinking);
const style: u8 = switch (self.terminal.screen.cursor.cursor_style) {
.block => if (blink) 1 else 2,
.underline => if (blink) 3 else 4,
.bar => if (blink) 5 else 6,
// Below here, the cursor styles aren't represented by
// DECSCUSR so we map it to some other style.
.block_hollow => if (blink) 1 else 2,
};
try writer.print("{d} q", .{style});
},
.decstbm => {
try writer.print("{d};{d}r", .{
self.terminal.scrolling_region.top + 1,
self.terminal.scrolling_region.bottom + 1,
});
},
.decslrm => {
// We only send a valid response when left and right
// margin mode (DECLRMM) is enabled.
if (self.terminal.modes.get(.enable_left_and_right_margin)) {
try writer.print("{d};{d}s", .{
self.terminal.scrolling_region.left + 1,
self.terminal.scrolling_region.right + 1,
});
}
},
}
// Our response is valid if we have a response payload
const valid = stream.pos > prefix_len;
// Write the terminator
try writer.writeAll("\x1b\\");
// Write the response prefix into the buffer
_ = try std.fmt.bufPrint(response[0..prefix_len], prefix_fmt, .{@intFromBool(valid)});
const msg = try termio.Message.writeReq(self.alloc, response[0..stream.pos]);
self.messageWriter(msg);
},
}
}
pub fn apcStart(self: *StreamHandler) !void {
self.apc.start();
}
pub fn apcPut(self: *StreamHandler, byte: u8) !void {
self.apc.feed(self.alloc, byte);
}
pub fn apcEnd(self: *StreamHandler) !void {
var cmd = self.apc.end() orelse return;
defer cmd.deinit(self.alloc);
// log.warn("APC command: {}", .{cmd});
switch (cmd) {
.kitty => |*kitty_cmd| {
if (self.terminal.kittyGraphics(self.alloc, kitty_cmd)) |resp| {
var buf: [1024]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
try resp.encode(buf_stream.writer());
const final = buf_stream.getWritten();
if (final.len > 2) {
log.debug("kitty graphics response: {s}", .{std.fmt.fmtSliceHexLower(final)});
self.messageWriter(try termio.Message.writeReq(self.alloc, final));
}
}
},
}
}
pub fn print(self: *StreamHandler, ch: u21) !void {
try self.terminal.print(ch);
}
pub fn printRepeat(self: *StreamHandler, count: usize) !void {
try self.terminal.printRepeat(count);
}
pub fn bell(self: StreamHandler) !void {
_ = self;
log.info("BELL", .{});
}
pub fn backspace(self: *StreamHandler) !void {
self.terminal.backspace();
}
pub fn horizontalTab(self: *StreamHandler, count: u16) !void {
for (0..count) |_| {
const x = self.terminal.screen.cursor.x;
try self.terminal.horizontalTab();
if (x == self.terminal.screen.cursor.x) break;
}
}
pub fn horizontalTabBack(self: *StreamHandler, count: u16) !void {
for (0..count) |_| {
const x = self.terminal.screen.cursor.x;
try self.terminal.horizontalTabBack();
if (x == self.terminal.screen.cursor.x) break;
}
}
pub fn linefeed(self: *StreamHandler) !void {
// Small optimization: call index instead of linefeed because they're
// identical and this avoids one layer of function call overhead.
try self.terminal.index();
}
pub fn carriageReturn(self: *StreamHandler) !void {
self.terminal.carriageReturn();
}
pub fn setCursorLeft(self: *StreamHandler, amount: u16) !void {
self.terminal.cursorLeft(amount);
}
pub fn setCursorRight(self: *StreamHandler, amount: u16) !void {
self.terminal.cursorRight(amount);
}
pub fn setCursorDown(self: *StreamHandler, amount: u16, carriage: bool) !void {
self.terminal.cursorDown(amount);
if (carriage) self.terminal.carriageReturn();
}
pub fn setCursorUp(self: *StreamHandler, amount: u16, carriage: bool) !void {
self.terminal.cursorUp(amount);
if (carriage) self.terminal.carriageReturn();
}
pub fn setCursorCol(self: *StreamHandler, col: u16) !void {
self.terminal.setCursorPos(self.terminal.screen.cursor.y + 1, col);
}
pub fn setCursorColRelative(self: *StreamHandler, offset: u16) !void {
self.terminal.setCursorPos(
self.terminal.screen.cursor.y + 1,
self.terminal.screen.cursor.x + 1 +| offset,
);
}
pub fn setCursorRow(self: *StreamHandler, row: u16) !void {
self.terminal.setCursorPos(row, self.terminal.screen.cursor.x + 1);
}
pub fn setCursorRowRelative(self: *StreamHandler, offset: u16) !void {
self.terminal.setCursorPos(
self.terminal.screen.cursor.y + 1 +| offset,
self.terminal.screen.cursor.x + 1,
);
}
pub fn setCursorPos(self: *StreamHandler, row: u16, col: u16) !void {
self.terminal.setCursorPos(row, col);
}
pub fn eraseDisplay(self: *StreamHandler, mode: terminal.EraseDisplay, protected: bool) !void {
if (mode == .complete) {
// Whenever we erase the full display, scroll to bottom.
try self.terminal.scrollViewport(.{ .bottom = {} });
try self.queueRender();
}
self.terminal.eraseDisplay(mode, protected);
}
pub fn eraseLine(self: *StreamHandler, mode: terminal.EraseLine, protected: bool) !void {
self.terminal.eraseLine(mode, protected);
}
pub fn deleteChars(self: *StreamHandler, count: usize) !void {
self.terminal.deleteChars(count);
}
pub fn eraseChars(self: *StreamHandler, count: usize) !void {
self.terminal.eraseChars(count);
}
pub fn insertLines(self: *StreamHandler, count: usize) !void {
self.terminal.insertLines(count);
}
pub fn insertBlanks(self: *StreamHandler, count: usize) !void {
self.terminal.insertBlanks(count);
}
pub fn deleteLines(self: *StreamHandler, count: usize) !void {
self.terminal.deleteLines(count);
}
pub fn reverseIndex(self: *StreamHandler) !void {
self.terminal.reverseIndex();
}
pub fn index(self: *StreamHandler) !void {
try self.terminal.index();
}
pub fn nextLine(self: *StreamHandler) !void {
try self.terminal.index();
self.terminal.carriageReturn();
}
pub fn setTopAndBottomMargin(self: *StreamHandler, top: u16, bot: u16) !void {
self.terminal.setTopAndBottomMargin(top, bot);
}
pub fn setLeftAndRightMarginAmbiguous(self: *StreamHandler) !void {
if (self.terminal.modes.get(.enable_left_and_right_margin)) {
try self.setLeftAndRightMargin(0, 0);
} else {
try self.saveCursor();
}
}
pub fn setLeftAndRightMargin(self: *StreamHandler, left: u16, right: u16) !void {
self.terminal.setLeftAndRightMargin(left, right);
}
pub fn setModifyKeyFormat(self: *StreamHandler, format: terminal.ModifyKeyFormat) !void {
self.terminal.flags.modify_other_keys_2 = false;
switch (format) {
.other_keys => |v| switch (v) {
.numeric => self.terminal.flags.modify_other_keys_2 = true,
else => {},
},
else => {},
}
}
pub fn requestMode(self: *StreamHandler, mode_raw: u16, ansi: bool) !void {
// Get the mode value and respond.
const code: u8 = code: {
const mode = terminal.modes.modeFromInt(mode_raw, ansi) orelse break :code 0;
if (self.terminal.modes.get(mode)) break :code 1;
break :code 2;
};
var msg: termio.Message = .{ .write_small = .{} };
const resp = try std.fmt.bufPrint(
&msg.write_small.data,
"\x1B[{s}{};{}$y",
.{
if (ansi) "" else "?",
mode_raw,
code,
},
);
msg.write_small.len = @intCast(resp.len);
self.messageWriter(msg);
}
pub fn saveMode(self: *StreamHandler, mode: terminal.Mode) !void {
// log.debug("save mode={}", .{mode});
self.terminal.modes.save(mode);
}
pub fn restoreMode(self: *StreamHandler, mode: terminal.Mode) !void {
// For restore mode we have to restore but if we set it, we
// always have to call setMode because setting some modes have
// side effects and we want to make sure we process those.
const v = self.terminal.modes.restore(mode);
// log.debug("restore mode={} v={}", .{ mode, v });
try self.setMode(mode, v);
}
pub fn setMode(self: *StreamHandler, mode: terminal.Mode, enabled: bool) !void {
// Note: this function doesn't need to grab the render state or
// terminal locks because it is only called from process() which
// grabs the lock.
// If we are setting cursor blinking, we ignore it if we have
// a default cursor blink setting set. This is a really weird
// behavior so this comment will go deep into trying to explain it.
//
// There are two ways to set cursor blinks: DECSCUSR (CSI _ q)
// and DEC mode 12. DECSCUSR is the modern approach and has a
// way to revert to the "default" (as defined by the terminal)
// cursor style and blink by doing "CSI 0 q". DEC mode 12 controls
// blinking and is either on or off and has no way to set a
// default. DEC mode 12 is also the more antiquated approach.
//
// The problem is that if the user specifies a desired default
// cursor blink with `cursor-style-blink`, the moment a running
// program uses DEC mode 12, the cursor blink can never be reset
// to the default without an explicit DECSCUSR. But if a program
// is using mode 12, it is by definition not using DECSCUSR.
// This makes for somewhat annoying interactions where a poorly
// (or legacy) behaved program will stop blinking, and it simply
// never restarts.
//
// To get around this, we have a special case where if the user
// specifies some explicit default cursor blink desire, we ignore
// DEC mode 12. We allow DECSCUSR to still set the cursor blink
// because programs using DECSCUSR usually are well behaved and
// reset the cursor blink to the default when they exit.
//
// To be extra safe, users can also add a manual `CSI 0 q` to
// their shell config when they render prompts to ensure the
// cursor is exactly as they request.
if (mode == .cursor_blinking and
self.default_cursor_blink != null)
{
return;
}
// We first always set the raw mode on our mode state.
self.terminal.modes.set(mode, enabled);
// And then some modes require additional processing.
switch (mode) {
// Just noting here that autorepeat has no effect on
// the terminal. xterm ignores this mode and so do we.
// We know about just so that we don't log that it is
// an unknown mode.
.autorepeat => {},
// Schedule a render since we changed colors
.reverse_colors => {
self.terminal.flags.dirty.reverse_colors = true;
try self.queueRender();
},
// Origin resets cursor pos. This is called whether or not
// we're enabling or disabling origin mode and whether or
// not the value changed.
.origin => self.terminal.setCursorPos(1, 1),
.enable_left_and_right_margin => if (!enabled) {
// When we disable left/right margin mode we need to
// reset the left/right margins.
self.terminal.scrolling_region.left = 0;
self.terminal.scrolling_region.right = self.terminal.cols - 1;
},
.alt_screen => {
const opts: terminal.Terminal.AlternateScreenOptions = .{
.cursor_save = false,
.clear_on_enter = false,
};
if (enabled)
self.terminal.alternateScreen(opts)
else
self.terminal.primaryScreen(opts);
// Schedule a render since we changed screens
try self.queueRender();
},
.alt_screen_save_cursor_clear_enter => {
const opts: terminal.Terminal.AlternateScreenOptions = .{
.cursor_save = true,
.clear_on_enter = true,
};
if (enabled)
self.terminal.alternateScreen(opts)
else
self.terminal.primaryScreen(opts);
// Schedule a render since we changed screens
try self.queueRender();
},
// Force resize back to the window size
.enable_mode_3 => {
const grid_size = self.size.grid();
self.terminal.resize(
self.alloc,
grid_size.columns,
grid_size.rows,
) catch |err| {
log.err("error updating terminal size: {}", .{err});
};
},
.@"132_column" => try self.terminal.deccolm(
self.alloc,
if (enabled) .@"132_cols" else .@"80_cols",
),
// We need to start a timer to prevent the emulator being hung
// forever.
.synchronized_output => {
if (enabled) self.messageWriter(.{ .start_synchronized_output = {} });
try self.queueRender();
},
.linefeed => {
self.messageWriter(.{ .linefeed_mode = enabled });
},
.in_band_size_reports => if (enabled) self.messageWriter(.{
.size_report = .mode_2048,
}),
.focus_event => if (enabled) self.messageWriter(.{
.focused = self.terminal.flags.focused,
}),
.mouse_event_x10 => {
if (enabled) {
self.terminal.flags.mouse_event = .x10;
try self.setMouseShape(.default);
} else {
self.terminal.flags.mouse_event = .none;
try self.setMouseShape(.text);
}
},
.mouse_event_normal => {
if (enabled) {
self.terminal.flags.mouse_event = .normal;
try self.setMouseShape(.default);
} else {
self.terminal.flags.mouse_event = .none;
try self.setMouseShape(.text);
}
},
.mouse_event_button => {
if (enabled) {
self.terminal.flags.mouse_event = .button;
try self.setMouseShape(.default);
} else {
self.terminal.flags.mouse_event = .none;
try self.setMouseShape(.text);
}
},
.mouse_event_any => {
if (enabled) {
self.terminal.flags.mouse_event = .any;
try self.setMouseShape(.default);
} else {
self.terminal.flags.mouse_event = .none;
try self.setMouseShape(.text);
}
},
.mouse_format_utf8 => self.terminal.flags.mouse_format = if (enabled) .utf8 else .x10,
.mouse_format_sgr => self.terminal.flags.mouse_format = if (enabled) .sgr else .x10,
.mouse_format_urxvt => self.terminal.flags.mouse_format = if (enabled) .urxvt else .x10,
.mouse_format_sgr_pixels => self.terminal.flags.mouse_format = if (enabled) .sgr_pixels else .x10,
else => {},
}
}
pub fn setMouseShiftCapture(self: *StreamHandler, v: bool) !void {
self.terminal.flags.mouse_shift_capture = if (v) .true else .false;
}
pub fn setAttribute(self: *StreamHandler, attr: terminal.Attribute) !void {
switch (attr) {
.unknown => |unk| log.warn("unimplemented or unknown SGR attribute: {any}", .{unk}),
else => self.terminal.setAttribute(attr) catch |err|
log.warn("error setting attribute {}: {}", .{ attr, err }),
}
}
pub fn startHyperlink(self: *StreamHandler, uri: []const u8, id: ?[]const u8) !void {
try self.terminal.screen.startHyperlink(uri, id);
}
pub fn endHyperlink(self: *StreamHandler) !void {
self.terminal.screen.endHyperlink();
}
pub fn deviceAttributes(
self: *StreamHandler,
req: terminal.DeviceAttributeReq,
params: []const u16,
) !void {
_ = params;
// For the below, we quack as a VT220. We don't quack as
// a 420 because we don't support DCS sequences.
switch (req) {
.primary => self.messageWriter(.{
.write_stable = "\x1B[?62;22c",
}),
.secondary => self.messageWriter(.{
.write_stable = "\x1B[>1;10;0c",
}),
else => log.warn("unimplemented device attributes req: {}", .{req}),
}
}
pub fn deviceStatusReport(
self: *StreamHandler,
req: terminal.device_status.Request,
) !void {
switch (req) {
.operating_status => self.messageWriter(.{ .write_stable = "\x1B[0n" }),
.cursor_position => {
const pos: struct {
x: usize,
y: usize,
} = if (self.terminal.modes.get(.origin)) .{
.x = self.terminal.screen.cursor.x -| self.terminal.scrolling_region.left,
.y = self.terminal.screen.cursor.y -| self.terminal.scrolling_region.top,
} else .{
.x = self.terminal.screen.cursor.x,
.y = self.terminal.screen.cursor.y,
};
// Response always is at least 4 chars, so this leaves the
// remainder for the row/column as base-10 numbers. This
// will support a very large terminal.
var msg: termio.Message = .{ .write_small = .{} };
const resp = try std.fmt.bufPrint(&msg.write_small.data, "\x1B[{};{}R", .{
pos.y + 1,
pos.x + 1,
});
msg.write_small.len = @intCast(resp.len);
self.messageWriter(msg);
},
.color_scheme => self.surfaceMessageWriter(.{ .report_color_scheme = true }),
}
}
pub fn setCursorStyle(
self: *StreamHandler,
style: terminal.CursorStyleReq,
) !void {
// Assume we're setting to a non-default.
self.default_cursor = false;
switch (style) {
.default => {
self.default_cursor = true;
self.terminal.screen.cursor.cursor_style = self.default_cursor_style;
self.terminal.modes.set(
.cursor_blinking,
self.default_cursor_blink orelse true,
);
},
.blinking_block => {
self.terminal.screen.cursor.cursor_style = .block;
self.terminal.modes.set(.cursor_blinking, true);
},
.steady_block => {
self.terminal.screen.cursor.cursor_style = .block;
self.terminal.modes.set(.cursor_blinking, false);
},
.blinking_underline => {
self.terminal.screen.cursor.cursor_style = .underline;
self.terminal.modes.set(.cursor_blinking, true);
},
.steady_underline => {
self.terminal.screen.cursor.cursor_style = .underline;
self.terminal.modes.set(.cursor_blinking, false);
},
.blinking_bar => {
self.terminal.screen.cursor.cursor_style = .bar;
self.terminal.modes.set(.cursor_blinking, true);
},
.steady_bar => {
self.terminal.screen.cursor.cursor_style = .bar;
self.terminal.modes.set(.cursor_blinking, false);
},
else => log.warn("unimplemented cursor style: {}", .{style}),
}
}
pub fn setProtectedMode(self: *StreamHandler, mode: terminal.ProtectedMode) !void {
self.terminal.setProtectedMode(mode);
}
pub fn decaln(self: *StreamHandler) !void {
try self.terminal.decaln();
}
pub fn tabClear(self: *StreamHandler, cmd: terminal.TabClear) !void {
self.terminal.tabClear(cmd);
}
pub fn tabSet(self: *StreamHandler) !void {
self.terminal.tabSet();
}
pub fn tabReset(self: *StreamHandler) !void {
self.terminal.tabReset();
}
pub fn saveCursor(self: *StreamHandler) !void {
self.terminal.saveCursor();
}
pub fn restoreCursor(self: *StreamHandler) !void {
try self.terminal.restoreCursor();
}
pub fn enquiry(self: *StreamHandler) !void {
log.debug("sending enquiry response={s}", .{self.enquiry_response});
self.messageWriter(try termio.Message.writeReq(self.alloc, self.enquiry_response));
}
pub fn scrollDown(self: *StreamHandler, count: usize) !void {
self.terminal.scrollDown(count);
}
pub fn scrollUp(self: *StreamHandler, count: usize) !void {
self.terminal.scrollUp(count);
}
pub fn setActiveStatusDisplay(
self: *StreamHandler,
req: terminal.StatusDisplay,
) !void {
self.terminal.status_display = req;
}
pub fn configureCharset(
self: *StreamHandler,
slot: terminal.CharsetSlot,
set: terminal.Charset,
) !void {
self.terminal.configureCharset(slot, set);
}
pub fn invokeCharset(
self: *StreamHandler,
active: terminal.CharsetActiveSlot,
slot: terminal.CharsetSlot,
single: bool,
) !void {
self.terminal.invokeCharset(active, slot, single);
}
pub fn fullReset(
self: *StreamHandler,
) !void {
self.terminal.fullReset();
try self.setMouseShape(.text);
// Reset resets our palette so we report it for mode 2031.
self.surfaceMessageWriter(.{ .report_color_scheme = false });
}
pub fn queryKittyKeyboard(self: *StreamHandler) !void {
if (comptime disable_kitty_keyboard_protocol) return;
log.debug("querying kitty keyboard mode", .{});
var data: termio.Message.WriteReq.Small.Array = undefined;
const resp = try std.fmt.bufPrint(&data, "\x1b[?{}u", .{
self.terminal.screen.kitty_keyboard.current().int(),
});
self.messageWriter(.{
.write_small = .{
.data = data,
.len = @intCast(resp.len),
},
});
}
pub fn pushKittyKeyboard(
self: *StreamHandler,
flags: terminal.kitty.KeyFlags,
) !void {
if (comptime disable_kitty_keyboard_protocol) return;
log.debug("pushing kitty keyboard mode: {}", .{flags});
self.terminal.screen.kitty_keyboard.push(flags);
}
pub fn popKittyKeyboard(self: *StreamHandler, n: u16) !void {
if (comptime disable_kitty_keyboard_protocol) return;
log.debug("popping kitty keyboard mode n={}", .{n});
self.terminal.screen.kitty_keyboard.pop(@intCast(n));
}
pub fn setKittyKeyboard(
self: *StreamHandler,
mode: terminal.kitty.KeySetMode,
flags: terminal.kitty.KeyFlags,
) !void {
if (comptime disable_kitty_keyboard_protocol) return;
log.debug("setting kitty keyboard mode: {} {}", .{ mode, flags });
self.terminal.screen.kitty_keyboard.set(mode, flags);
}
pub fn reportXtversion(
self: *StreamHandler,
) !void {
log.debug("reporting XTVERSION: ghostty {s}", .{build_config.version_string});
var buf: [288]u8 = undefined;
const resp = try std.fmt.bufPrint(
&buf,
"\x1BP>|{s} {s}\x1B\\",
.{
"ghostty",
build_config.version_string,
},
);
const msg = try termio.Message.writeReq(self.alloc, resp);
self.messageWriter(msg);
}
//-------------------------------------------------------------------------
// OSC
pub fn changeWindowTitle(self: *StreamHandler, title: []const u8) !void {
var buf: [256]u8 = undefined;
if (title.len >= buf.len) {
log.warn("change title requested larger than our buffer size, ignoring", .{});
return;
}
@memcpy(buf[0..title.len], title);
buf[title.len] = 0;
// Special handling for the empty title. We treat the empty title
// as resetting to as if we never saw a title. Other terminals
// behave this way too (e.g. iTerm2).
if (title.len == 0) {
// If we have a pwd then we set the title as the pwd else
// we just set it to blank.
if (self.terminal.getPwd()) |pwd| pwd: {
if (pwd.len >= buf.len) break :pwd;
@memcpy(buf[0..pwd.len], pwd);
buf[pwd.len] = 0;
}
self.surfaceMessageWriter(.{ .set_title = buf });
self.seen_title = false;
return;
}
self.seen_title = true;
self.surfaceMessageWriter(.{ .set_title = buf });
}
pub fn setMouseShape(
self: *StreamHandler,