package matrix

  1. Overview
  2. Docs

Source file matrix_terminal.ml

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
(* Types *)

type mouse_mode =
  [ `Off
  | `X10
  | `Normal
  | `Button
  | `Any
  | `Sgr_normal
  | `Sgr_button
  | `Sgr_any ]

type cursor_position = { x : int; y : int; visible : bool }

module Caps = Caps

type capabilities = Caps.t

type cursor_state = {
  mutable x : int;
  mutable y : int;
  mutable visible : bool;
  mutable style : Ansi.cursor_style;
  mutable blinking : bool;
  mutable color : float * float * float * float;
}

type t = {
  output : string -> unit;
  tty : bool;
  mutable caps : Caps.t;
  mutable mouse_mode : mouse_mode;
  mutable bracketed_paste_enabled : bool;
  mutable focus_enabled : bool;
  mutable kitty_keyboard_enabled : bool;
  mutable kitty_keyboard_flags : int;
  mutable modify_other_keys_enabled : bool;
  mutable color_scheme_reports_enabled : bool;
  mutable resize_reports_enabled : bool;
  mutable meta_sends_escape_enabled : bool;
  mutable grapheme_mode_enabled : bool;
  (* [*_armed] is set before the enable sequence is written, and [*_enabled]
     only after. When the output callback raises during an enable, the
     sequence may have reached the terminal although the enable never
     completed. [reset_state] writes its disable sequences by armed, so a
     protocol enabled in part is still unwound, while the [*_enabled]
     accessors report the state confirmed. *)
  mutable mouse_armed : bool;
  mutable bracketed_paste_armed : bool;
  mutable focus_armed : bool;
  mutable kitty_keyboard_armed : bool;
  mutable modify_other_keys_armed : bool;
  mutable color_scheme_reports_armed : bool;
  mutable resize_reports_armed : bool;
  mutable meta_sends_escape_armed : bool;
  mutable grapheme_mode_armed : bool;
  mutable alt_screen_armed : bool;
  mutable scroll_region_armed : bool;
  cursor : cursor_state;
  mutable alt_screen : bool;
  mutable scroll_region : (int * int) option;
  mutable pixel_resolution : (int * int) option;
  (* Appearance the handle actually emitted. [reset_state] restores only what
     was touched: popping a title or resetting cursor colour/style the app
     never set would clobber user- or shell-configured terminal state. The
     title is pushed on the terminal's title stack while [title_sent]. *)
  mutable title_sent : bool;
  mutable cursor_style_sent : bool;
  mutable cursor_color_sent : bool;
}

(* Pre-computed escape sequences *)

let alternate_on = "\027[?1049h"
let alternate_off = "\027[?1049l"
let focus_on = "\027[?1004h"
let focus_off = "\027[?1004l"
let paste_on = "\027[?2004h"
let paste_off = "\027[?2004l"
let color_scheme_reports_on = "\027[?2031h"
let color_scheme_reports_off = "\027[?2031l"
let resize_reports_on = "\027[?2048h"
let resize_reports_off = "\027[?2048l"
let meta_sends_escape_on = "\027[?1036h"
let meta_sends_escape_off = "\027[?1036l"
let kitty_kb_push flags = Ansi.(to_string (csi_u_push ~flags))
let kitty_kb_pop = "\027[<u"
let modify_other_keys_on_seq = "\027[>4;1m"
let modify_other_keys_off_seq = "\027[>4;0m"
let cursor_show = "\027[?25h"
let cursor_hide = "\027[?25l"
let unicode_on = "\027[?2027h"
let unicode_off = "\027[?2027l"
let reset_sgr = "\027[0m"
let cursor_default = "\027[0 q"
let title_push = "\027[22;0t"
let title_pop = "\027[23;0t"

let reset_cursor_color_seq =
  Ansi.to_string (fun writer ->
      Ansi.reset_cursor_color_fallback writer;
      Ansi.reset_cursor_color writer)

let mouse_x10 = "\027[?9h"
let mouse_tracking = "\027[?1000h"
let mouse_button = "\027[?1002h"
let mouse_motion = "\027[?1003h"

let disable_all_mouse_seq =
  "\027[?9l\027[?1000l\027[?1002l\027[?1003l\027[?1015l\027[?1006l"

let sgr_normal_seq = "\027[?1006h\027[?1000h"
let sgr_button_seq = "\027[?1006h\027[?1000h\027[?1002h"
let sgr_any_seq = "\027[?1006h\027[?1000h\027[?1002h\027[?1003h"

(* Helpers *)

let clamp_color_component x =
  let x = if Float.is_nan x then 0. else x in
  int_of_float (Float.round (Float.max 0. (Float.min 1. x) *. 255.))

(* Core output *)

let send t seq = if t.tty then t.output seq
let tty t = t.tty

(* Constructor *)

let make ~output ?(tty = true) caps =
  {
    output;
    tty;
    caps;
    mouse_mode = `Off;
    bracketed_paste_enabled = false;
    focus_enabled = false;
    kitty_keyboard_enabled = false;
    kitty_keyboard_flags = 0b00101;
    modify_other_keys_enabled = false;
    color_scheme_reports_enabled = false;
    resize_reports_enabled = false;
    meta_sends_escape_enabled = false;
    grapheme_mode_enabled = false;
    mouse_armed = false;
    bracketed_paste_armed = false;
    focus_armed = false;
    kitty_keyboard_armed = false;
    modify_other_keys_armed = false;
    color_scheme_reports_armed = false;
    resize_reports_armed = false;
    meta_sends_escape_armed = false;
    grapheme_mode_armed = false;
    alt_screen_armed = false;
    scroll_region_armed = false;
    cursor =
      {
        x = 1;
        y = 1;
        visible = true;
        style = `Block;
        blinking = false;
        color = (1., 1., 1., 1.);
      };
    alt_screen = false;
    scroll_region = None;
    pixel_resolution = None;
    title_sent = false;
    cursor_style_sent = false;
    cursor_color_sent = false;
  }

(* Capability access *)

let capabilities t = t.caps
let set_capabilities t caps = t.caps <- caps
let pixel_resolution t = t.pixel_resolution
let set_pixel_resolution t res = t.pixel_resolution <- res

(* Mouse mode *)

let disable_all_mouse t = send t disable_all_mouse_seq

let set_mouse_mode t mode =
  if t.mouse_mode = mode then ()
  else (
    disable_all_mouse t;
    if mode <> `Off then t.mouse_armed <- true;
    (match mode with
    | `Off -> ()
    | `X10 -> send t mouse_x10
    | `Normal -> send t mouse_tracking
    | `Button -> send t mouse_button
    | `Any -> send t mouse_motion
    | `Sgr_normal -> send t sgr_normal_seq
    | `Sgr_button -> send t sgr_button_seq
    | `Sgr_any -> send t sgr_any_seq);
    t.mouse_mode <- mode;
    if mode = `Off then t.mouse_armed <- false)

let mouse_mode t = t.mouse_mode

(* Bracketed paste *)

let enable_bracketed_paste t enable =
  if t.bracketed_paste_enabled = enable then ()
  else if enable then (
    t.bracketed_paste_armed <- true;
    send t paste_on;
    t.bracketed_paste_enabled <- true)
  else (
    send t paste_off;
    t.bracketed_paste_enabled <- false;
    t.bracketed_paste_armed <- false)

let bracketed_paste_enabled t = t.bracketed_paste_enabled

(* Focus reporting *)

let enable_focus_reporting t enable =
  if t.focus_enabled = enable then ()
  else if enable then (
    t.focus_armed <- true;
    send t focus_on;
    t.focus_enabled <- true)
  else (
    send t focus_off;
    t.focus_enabled <- false;
    t.focus_armed <- false)

let focus_reporting_enabled t = t.focus_enabled

(* Kitty keyboard *)

let enable_kitty_keyboard ?(flags = 0b00101) t enable =
  if enable then (
    if (not t.kitty_keyboard_enabled) || t.kitty_keyboard_flags <> flags then (
      (* Pop the previous entry before pushing replacement flags so the
         terminal's keyboard stack never holds more than one entry from this
         handle; the single pop in disable and [reset_state] then fully
         unwinds it (the same dance as [restore_modes]). *)
      if t.kitty_keyboard_enabled then send t kitty_kb_pop;
      t.kitty_keyboard_armed <- true;
      send t (kitty_kb_push flags);
      t.kitty_keyboard_enabled <- true;
      t.kitty_keyboard_flags <- flags))
  else if t.kitty_keyboard_enabled then (
    send t kitty_kb_pop;
    t.kitty_keyboard_enabled <- false;
    t.kitty_keyboard_armed <- false)

let kitty_keyboard_enabled t = t.kitty_keyboard_enabled

(* Modify other keys *)

let enable_modify_other_keys t enable =
  if t.modify_other_keys_enabled = enable then ()
  else if enable then (
    t.modify_other_keys_armed <- true;
    send t modify_other_keys_on_seq;
    t.modify_other_keys_enabled <- true)
  else (
    send t modify_other_keys_off_seq;
    t.modify_other_keys_enabled <- false;
    t.modify_other_keys_armed <- false)

let modify_other_keys_enabled t = t.modify_other_keys_enabled

(* Color scheme reports, resize reports and metaSendsEscape: a mode is armed
   before its enable sequence is written, as above. *)

let enable_color_scheme_reports t enable =
  if t.color_scheme_reports_enabled <> enable then
    if enable then (
      t.color_scheme_reports_armed <- true;
      send t color_scheme_reports_on;
      t.color_scheme_reports_enabled <- true)
    else (
      send t color_scheme_reports_off;
      t.color_scheme_reports_enabled <- false;
      t.color_scheme_reports_armed <- false)

let enable_resize_reports t enable =
  if t.resize_reports_enabled <> enable then
    if enable then (
      t.resize_reports_armed <- true;
      send t resize_reports_on;
      t.resize_reports_enabled <- true)
    else (
      send t resize_reports_off;
      t.resize_reports_enabled <- false;
      t.resize_reports_armed <- false)

let enable_meta_sends_escape t enable =
  if t.meta_sends_escape_enabled <> enable then
    if enable then (
      t.meta_sends_escape_armed <- true;
      send t meta_sends_escape_on;
      t.meta_sends_escape_enabled <- true)
    else (
      send t meta_sends_escape_off;
      t.meta_sends_escape_enabled <- false;
      t.meta_sends_escape_armed <- false)

(* Unicode width, the alternate screen and the scrolling region: armed
   before the change is written, as above. *)

let enable_grapheme_mode t enable =
  if t.grapheme_mode_enabled <> enable then
    if enable then (
      t.grapheme_mode_armed <- true;
      send t unicode_on;
      t.grapheme_mode_enabled <- true)
    else (
      send t unicode_off;
      t.grapheme_mode_enabled <- false;
      t.grapheme_mode_armed <- false)

let enter_alternate_screen t =
  if not t.alt_screen then (
    t.alt_screen_armed <- true;
    send t alternate_on;
    t.alt_screen <- true)

let leave_alternate_screen t =
  if t.alt_screen then (
    send t alternate_off;
    t.alt_screen <- false;
    t.alt_screen_armed <- false)

let alt_screen t = t.alt_screen

let set_scroll_region t ~top ~bottom =
  if t.scroll_region <> Some (top, bottom) then (
    let seq = Ansi.(to_string (set_scrolling_region ~top ~bottom)) in
    t.scroll_region_armed <- true;
    send t seq;
    t.scroll_region <- Some (top, bottom))

let clear_scroll_region t =
  if t.scroll_region <> None then (
    send t Ansi.(to_string reset_scrolling_region);
    t.scroll_region <- None;
    t.scroll_region_armed <- false)

let scroll_region t = t.scroll_region

(* Cursor *)

let set_cursor_visible t visible =
  if t.cursor.visible <> visible then (
    send t (if visible then cursor_show else cursor_hide);
    t.cursor.visible <- visible)

let cursor_visible t = t.cursor.visible

let cursor_position t =
  { x = t.cursor.x; y = t.cursor.y; visible = t.cursor.visible }

let move_cursor ?(visible = true) t ~row ~col =
  let row = max 1 row in
  let col = max 1 col in
  if visible <> t.cursor.visible then set_cursor_visible t visible;
  t.cursor.x <- col;
  t.cursor.y <- row;
  send t Ansi.(to_string (cursor_position ~row ~col))

let cursor_style_state t = (t.cursor.style, t.cursor.blinking)
let cursor_color t = t.cursor.color

let write_cursor_style t ~shape writer =
  t.cursor_style_sent <- true;
  Ansi.cursor_style ~shape writer

let write_cursor_color t color writer =
  match color with
  | Some (r, g, b) ->
      t.cursor_color_sent <- true;
      Ansi.cursor_color ~r ~g ~b writer
  | None ->
      (* A queued reset may never reach the terminal. Keep restoration armed
         until [reset_cursor_color] confirms the output succeeded. *)
      Ansi.Writer.write_string writer reset_cursor_color_seq

(* Each writes what it sets alone. The terminal keeps the style and the color
   while the cursor is hidden and shows them with it. *)
let set_cursor_style t style ~blinking =
  t.cursor.style <- style;
  t.cursor.blinking <- blinking;
  let shape = Ansi.cursor_shape_of_style ~style ~blinking in
  send t (Ansi.to_string (fun writer -> write_cursor_style t ~shape writer))

let set_cursor_color t ~r ~g ~b ~a =
  t.cursor.color <- (r, g, b, a);
  let color =
    Some
      (clamp_color_component r, clamp_color_component g, clamp_color_component b)
  in
  send t (Ansi.to_string (fun writer -> write_cursor_color t color writer))

let reset_cursor_color t =
  t.cursor.color <- (1., 1., 1., 1.);
  send t reset_cursor_color_seq;
  t.cursor_color_sent <- false

(* The first title pushes the one it replaces on xterm's title stack
   (XTWINOPS, "CSI 22 ; 0 t": "Save xterm icon and window title on stack"),
   and [reset_state] pops it ("CSI 23 ; 0 t"), so the shell's title comes
   back. *)
let set_title t title =
  if not t.title_sent then (
    t.title_sent <- true;
    send t title_push);
  send t Ansi.(to_string (set_title ~title))

let copy_to_clipboard t text =
  let seq = Ansi.set_clipboard ~text in
  match t.caps.multiplexer with
  | Some `Tmux -> send t (Ansi.to_string (Ansi.tmux_passthrough seq))
  | Some `Screen ->
      (* Screen forwards at most 252 payload bytes per DCS envelope. OSC 52
       uses BEL so its terminator cannot close the enclosing DCS early. *)
      let seq = Ansi.to_string seq in
      let len = String.length seq in
      let buf = Buffer.create (len + (4 * ((len + 251) / 252))) in
      let off = ref 0 in
      while !off < len do
        let count = min 252 (len - !off) in
        Buffer.add_string buf "\027P";
        Buffer.add_substring buf seq !off count;
        Buffer.add_string buf "\027\\";
        off := !off + count
      done;
      send t (Buffer.contents buf)
  | None -> send t (Ansi.to_string seq)

let notify t ~title ~body =
  let seq = Ansi.notify t.caps.notification ~title ~body in
  let seq =
    if t.caps.multiplexer = Some `Tmux then Ansi.tmux_passthrough seq else seq
  in
  send t (Ansi.to_string seq)

let bell t = send t Ansi.(to_string bell)
let query_color_scheme t = send t Ansi.(to_string (query Color_scheme_report))
let query_pixel_resolution t = send t Ansi.(to_string (query Pixel_size))

(* Mode restoration *)

let restore_modes ?(skip_focus = false) t =
  (match t.mouse_mode with
  | `Off -> ()
  | `X10 -> send t mouse_x10
  | `Normal -> send t mouse_tracking
  | `Button -> send t mouse_button
  | `Any -> send t mouse_motion
  | `Sgr_normal -> send t sgr_normal_seq
  | `Sgr_button -> send t sgr_button_seq
  | `Sgr_any -> send t sgr_any_seq);
  if t.focus_enabled && not skip_focus then send t focus_on;
  if t.bracketed_paste_enabled then send t paste_on;
  if t.kitty_keyboard_enabled then (
    send t kitty_kb_pop;
    send t (kitty_kb_push t.kitty_keyboard_flags));
  if t.modify_other_keys_enabled then send t modify_other_keys_on_seq;
  if t.color_scheme_reports_enabled then send t color_scheme_reports_on;
  if t.resize_reports_enabled then send t resize_reports_on;
  if t.meta_sends_escape_enabled then send t meta_sends_escape_on

(* Reset and close *)

let reset_state t =
  send t cursor_show;
  send t reset_sgr;
  if t.cursor_color_sent then reset_cursor_color t;
  if t.cursor_style_sent then (
    send t cursor_default;
    t.cursor_style_sent <- false);
  if t.kitty_keyboard_armed then send t kitty_kb_pop;
  t.kitty_keyboard_enabled <- false;
  t.kitty_keyboard_armed <- false;
  t.kitty_keyboard_flags <- 0b00101;
  if t.modify_other_keys_armed then send t modify_other_keys_off_seq;
  t.modify_other_keys_enabled <- false;
  t.modify_other_keys_armed <- false;
  if t.mouse_armed || t.mouse_mode <> `Off then disable_all_mouse t;
  t.mouse_mode <- `Off;
  t.mouse_armed <- false;
  if t.bracketed_paste_armed then send t paste_off;
  t.bracketed_paste_enabled <- false;
  t.bracketed_paste_armed <- false;
  if t.focus_armed then send t focus_off;
  t.focus_enabled <- false;
  t.focus_armed <- false;
  if t.color_scheme_reports_armed then send t color_scheme_reports_off;
  t.color_scheme_reports_enabled <- false;
  t.color_scheme_reports_armed <- false;
  if t.resize_reports_armed then send t resize_reports_off;
  t.resize_reports_enabled <- false;
  t.resize_reports_armed <- false;
  if t.meta_sends_escape_armed then send t meta_sends_escape_off;
  t.meta_sends_escape_enabled <- false;
  t.meta_sends_escape_armed <- false;
  if t.grapheme_mode_armed then send t unicode_off;
  t.grapheme_mode_enabled <- false;
  t.grapheme_mode_armed <- false;
  if t.scroll_region_armed then send t Ansi.(to_string reset_scrolling_region);
  t.scroll_region <- None;
  t.scroll_region_armed <- false;
  if t.alt_screen_armed then send t alternate_off;
  t.alt_screen <- false;
  t.alt_screen_armed <- false;
  (* A terminal without the stack keeps the empty title. *)
  if t.title_sent then (
    send t Ansi.(to_string (set_title ~title:""));
    send t title_pop;
    t.title_sent <- false);
  send t cursor_show;
  t.cursor.visible <- true;
  t.cursor.style <- `Block;
  t.cursor.blinking <- false;
  t.cursor.color <- (1., 1., 1., 1.)

let close t = reset_state t