omk-tui 1.3.2 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/dist/components/box.d.ts +5 -0
- package/dist/components/box.d.ts.map +1 -1
- package/dist/components/box.js +50 -15
- package/dist/components/box.js.map +1 -1
- package/dist/components/editor.d.ts +3 -1
- package/dist/components/editor.d.ts.map +1 -1
- package/dist/components/editor.js +4 -7
- package/dist/components/editor.js.map +1 -1
- package/dist/components/image.d.ts +2 -0
- package/dist/components/image.d.ts.map +1 -1
- package/dist/components/image.js +4 -0
- package/dist/components/image.js.map +1 -1
- package/dist/components/markdown.d.ts +4 -0
- package/dist/components/markdown.d.ts.map +1 -1
- package/dist/components/markdown.js +14 -0
- package/dist/components/markdown.js.map +1 -1
- package/dist/components/spacer.d.ts +2 -0
- package/dist/components/spacer.d.ts.map +1 -1
- package/dist/components/spacer.js +8 -0
- package/dist/components/spacer.js.map +1 -1
- package/dist/components/text.d.ts +4 -0
- package/dist/components/text.d.ts.map +1 -1
- package/dist/components/text.js +14 -0
- package/dist/components/text.js.map +1 -1
- package/dist/editor-component.d.ts +2 -0
- package/dist/editor-component.d.ts.map +1 -1
- package/dist/editor-component.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/line-reset-memo.d.ts +27 -0
- package/dist/line-reset-memo.d.ts.map +1 -0
- package/dist/line-reset-memo.js +101 -0
- package/dist/line-reset-memo.js.map +1 -0
- package/dist/render-generation.d.ts +24 -0
- package/dist/render-generation.d.ts.map +1 -0
- package/dist/render-generation.js +48 -0
- package/dist/render-generation.js.map +1 -0
- package/dist/terminal-output.d.ts +20 -1
- package/dist/terminal-output.d.ts.map +1 -1
- package/dist/terminal-output.js +62 -1
- package/dist/terminal-output.js.map +1 -1
- package/dist/terminal-resize-log.d.ts +39 -0
- package/dist/terminal-resize-log.d.ts.map +1 -0
- package/dist/terminal-resize-log.js +57 -0
- package/dist/terminal-resize-log.js.map +1 -0
- package/dist/terminal-resync.d.ts +74 -0
- package/dist/terminal-resync.d.ts.map +1 -0
- package/dist/terminal-resync.js +112 -0
- package/dist/terminal-resync.js.map +1 -0
- package/dist/terminal.d.ts.map +1 -1
- package/dist/terminal.js +1 -1
- package/dist/terminal.js.map +1 -1
- package/dist/tui.d.ts +29 -9
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +65 -86
- package/dist/tui.js.map +1 -1
- package/dist/undo-stack.d.ts +8 -2
- package/dist/undo-stack.d.ts.map +1 -1
- package/dist/undo-stack.js +12 -2
- package/dist/undo-stack.js.map +1 -1
- package/dist/utils.d.ts +2 -4
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +2 -128
- package/dist/utils.js.map +1 -1
- package/dist/visible-width.d.ts +14 -0
- package/dist/visible-width.d.ts.map +1 -0
- package/dist/visible-width.js +163 -0
- package/dist/visible-width.js.map +1 -0
- package/dist/windowed-container.d.ts +120 -0
- package/dist/windowed-container.d.ts.map +1 -0
- package/dist/windowed-container.js +258 -0
- package/dist/windowed-container.js.map +1 -0
- package/dist/windowed-segments.d.ts +37 -0
- package/dist/windowed-segments.d.ts.map +1 -0
- package/dist/windowed-segments.js +133 -0
- package/dist/windowed-segments.js.map +1 -0
- package/package.json +1 -1
package/dist/terminal-output.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { errorMonitor } from "node:events";
|
|
2
2
|
import { appendFileSync, statSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
+
import { TerminalResizeLog } from "./terminal-resize-log.js";
|
|
4
5
|
function writeLogPath(value) {
|
|
5
6
|
if (!value)
|
|
6
7
|
return "";
|
|
@@ -16,6 +17,27 @@ function writeLogPath(value) {
|
|
|
16
17
|
}
|
|
17
18
|
return value;
|
|
18
19
|
}
|
|
20
|
+
/** The TerminalOutput of the running TUI: set on its first write, cleared by stop. */
|
|
21
|
+
let activeOutput;
|
|
22
|
+
/**
|
|
23
|
+
* Raw terminal bytes written from outside the render path (completion BEL,
|
|
24
|
+
* OSC 52 clipboard). While a TUI is writing they go through its
|
|
25
|
+
* TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets
|
|
26
|
+
* count them; otherwise straight to stdout. May throw like stream.write.
|
|
27
|
+
*/
|
|
28
|
+
export function writeTerminalRaw(data) {
|
|
29
|
+
if (activeOutput)
|
|
30
|
+
activeOutput.write(data);
|
|
31
|
+
else
|
|
32
|
+
process.stdout.write(data);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Final resize-log lines still owed at process exit, for exits that skip stop
|
|
36
|
+
* (a dead tty's EIO goes straight to process.exit). One exit listener serves
|
|
37
|
+
* every TerminalOutput; stop removes its own entry, the next write re-adds it.
|
|
38
|
+
*/
|
|
39
|
+
const finalOnExit = new Set();
|
|
40
|
+
let exitHooked = false;
|
|
19
41
|
/** Metadata-only observation. No paint queue, retries, or interception of error handling. */
|
|
20
42
|
export class TerminalOutput {
|
|
21
43
|
stream;
|
|
@@ -35,15 +57,50 @@ export class TerminalOutput {
|
|
|
35
57
|
onError = () => {
|
|
36
58
|
this.counters.errorCount++;
|
|
37
59
|
};
|
|
38
|
-
|
|
60
|
+
resizeLog;
|
|
61
|
+
constructor(stream, log = "", resizeLog = process.env.OMK_TUI_RESIZE_LOG || "") {
|
|
39
62
|
this.stream = stream;
|
|
40
63
|
this.logPath = writeLogPath(log);
|
|
64
|
+
this.resizeLog = resizeLog ? new TerminalResizeLog(resizeLog) : undefined;
|
|
65
|
+
if (this.resizeLog)
|
|
66
|
+
this.owesFinal();
|
|
67
|
+
}
|
|
68
|
+
finalLine = () => this.resizeLog?.final(this.counters.submittedBytes);
|
|
69
|
+
owesFinal() {
|
|
70
|
+
finalOnExit.add(this.finalLine);
|
|
71
|
+
if (exitHooked)
|
|
72
|
+
return;
|
|
73
|
+
exitHooked = true;
|
|
74
|
+
process.once("exit", () => {
|
|
75
|
+
for (const finalLine of finalOnExit)
|
|
76
|
+
finalLine();
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Wraps a resize handler so each resize first logs the bytes written so far
|
|
81
|
+
* (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler
|
|
82
|
+
* itself when the log is off, so an unset variable costs nothing per event.
|
|
83
|
+
*/
|
|
84
|
+
withResizeLog(onResize, size) {
|
|
85
|
+
const log = this.resizeLog;
|
|
86
|
+
if (!log)
|
|
87
|
+
return onResize;
|
|
88
|
+
let prev = size();
|
|
89
|
+
return () => {
|
|
90
|
+
const next = size();
|
|
91
|
+
log.resize(this.counters.submittedBytes, next.cols, next.rows, prev.cols, prev.rows);
|
|
92
|
+
prev = next;
|
|
93
|
+
onResize();
|
|
94
|
+
};
|
|
41
95
|
}
|
|
42
96
|
write(data, log = false) {
|
|
43
97
|
if (!this.observing) {
|
|
44
98
|
this.stream.on("drain", this.onDrain);
|
|
45
99
|
this.stream.on(errorMonitor, this.onError);
|
|
46
100
|
this.observing = true;
|
|
101
|
+
activeOutput = this;
|
|
102
|
+
if (this.resizeLog)
|
|
103
|
+
this.owesFinal();
|
|
47
104
|
}
|
|
48
105
|
this.counters.writeCalls++;
|
|
49
106
|
this.counters.submittedBytes += Buffer.byteLength(data, "utf8");
|
|
@@ -74,9 +131,13 @@ export class TerminalOutput {
|
|
|
74
131
|
};
|
|
75
132
|
}
|
|
76
133
|
stop() {
|
|
134
|
+
this.finalLine();
|
|
135
|
+
finalOnExit.delete(this.finalLine);
|
|
77
136
|
this.stream.off("drain", this.onDrain);
|
|
78
137
|
this.stream.off(errorMonitor, this.onError);
|
|
79
138
|
this.observing = false;
|
|
139
|
+
if (activeOutput === this)
|
|
140
|
+
activeOutput = undefined;
|
|
80
141
|
}
|
|
81
142
|
}
|
|
82
143
|
//# sourceMappingURL=terminal-output.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminal-output.js","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"terminal-output.js","sourceRoot":"","sources":["../src/terminal-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAc7D,SAAS,YAAY,CAAC,KAAa,EAAU;IAC5C,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,IAAI,CAAC;QACJ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,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ED,QAAQ,GAAwB;QAC/B,OAAO;YACN,GAAG,IAAI,CAAC,QAAQ;YAChB,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc;YAC1C,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,iBAAiB;SAC5C,CAAC;IAAA,CACF;IAED,IAAI,GAAS;QACZ,IAAI,CAAC,SAAS,EAAE,CAAC;QACjB,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,YAAY,KAAK,IAAI;YAAE,YAAY,GAAG,SAAS,CAAC;IAAA,CACpD;CACD","sourcesContent":["import { errorMonitor } from \"node:events\";\nimport { appendFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { TerminalResizeLog } from \"./terminal-resize-log.ts\";\n\nexport interface TerminalOutputStats {\n\treadonly writeCalls: number;\n\t/** Bytes offered to write, not a claim that the terminal displayed them. */\n\treadonly submittedBytes: number;\n\treadonly writeFalseCount: number;\n\treadonly drainCount: number;\n\treadonly errorCount: number;\n\treadonly peakWritableLength: number;\n\treadonly writableLength: number;\n\treadonly backpressured: boolean;\n}\n\nfunction writeLogPath(value: string): string {\n\tif (!value) return \"\";\n\ttry {\n\t\tif (statSync(value).isDirectory()) {\n\t\t\tconst now = new Date();\n\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\treturn join(value, `tui-${ts}-${process.pid}.log`);\n\t\t}\n\t} catch {\n\t\t// A non-existing path is a filename, matching the existing debug-log contract.\n\t}\n\treturn value;\n}\n\n/** The TerminalOutput of the running TUI: set on its first write, cleared by stop. */\nlet activeOutput: TerminalOutput | undefined;\n\n/**\n * Raw terminal bytes written from outside the render path (completion BEL,\n * OSC 52 clipboard). While a TUI is writing they go through its\n * TerminalOutput, so output stats and the OMK_TUI_RESIZE_LOG byte offsets\n * count them; otherwise straight to stdout. May throw like stream.write.\n */\nexport function writeTerminalRaw(data: string): void {\n\tif (activeOutput) activeOutput.write(data);\n\telse process.stdout.write(data);\n}\n\n/**\n * Final resize-log lines still owed at process exit, for exits that skip stop\n * (a dead tty's EIO goes straight to process.exit). One exit listener serves\n * every TerminalOutput; stop removes its own entry, the next write re-adds it.\n */\nconst finalOnExit = new Set<() => void>();\nlet exitHooked = false;\n\n/** Metadata-only observation. No paint queue, retries, or interception of error handling. */\nexport class TerminalOutput {\n\tprivate readonly stream: Writable;\n\tprivate readonly logPath: string;\n\tprivate observing = false;\n\tprivate readonly counters = {\n\t\twriteCalls: 0,\n\t\tsubmittedBytes: 0,\n\t\twriteFalseCount: 0,\n\t\tdrainCount: 0,\n\t\terrorCount: 0,\n\t\tpeakWritableLength: 0,\n\t};\n\tprivate readonly onDrain = () => {\n\t\tthis.counters.drainCount++;\n\t};\n\tprivate readonly onError = () => {\n\t\tthis.counters.errorCount++;\n\t};\n\n\tprivate readonly resizeLog: TerminalResizeLog | undefined;\n\n\tconstructor(stream: Writable, log = \"\", resizeLog = process.env.OMK_TUI_RESIZE_LOG || \"\") {\n\t\tthis.stream = stream;\n\t\tthis.logPath = writeLogPath(log);\n\t\tthis.resizeLog = resizeLog ? new TerminalResizeLog(resizeLog) : undefined;\n\t\tif (this.resizeLog) this.owesFinal();\n\t}\n\n\tprivate readonly finalLine = () => this.resizeLog?.final(this.counters.submittedBytes);\n\n\tprivate owesFinal(): void {\n\t\tfinalOnExit.add(this.finalLine);\n\t\tif (exitHooked) return;\n\t\texitHooked = true;\n\t\tprocess.once(\"exit\", () => {\n\t\t\tfor (const finalLine of finalOnExit) finalLine();\n\t\t});\n\t}\n\n\t/**\n\t * Wraps a resize handler so each resize first logs the bytes written so far\n\t * (OMK_TUI_RESIZE_LOG, see terminal-resize-log.ts). Returns the handler\n\t * itself when the log is off, so an unset variable costs nothing per event.\n\t */\n\twithResizeLog(onResize: () => void, size: () => { cols: number; rows: number }): () => void {\n\t\tconst log = this.resizeLog;\n\t\tif (!log) return onResize;\n\t\tlet prev = size();\n\t\treturn () => {\n\t\t\tconst next = size();\n\t\t\tlog.resize(this.counters.submittedBytes, next.cols, next.rows, prev.cols, prev.rows);\n\t\t\tprev = next;\n\t\t\tonResize();\n\t\t};\n\t}\n\n\twrite(data: string, log = false): void {\n\t\tif (!this.observing) {\n\t\t\tthis.stream.on(\"drain\", this.onDrain);\n\t\t\tthis.stream.on(errorMonitor, this.onError);\n\t\t\tthis.observing = true;\n\t\t\tactiveOutput = this;\n\t\t\tif (this.resizeLog) this.owesFinal();\n\t\t}\n\t\tthis.counters.writeCalls++;\n\t\tthis.counters.submittedBytes += Buffer.byteLength(data, \"utf8\");\n\t\ttry {\n\t\t\t// false still accepts the write. Never resend it.\n\t\t\tif (!this.stream.write(data)) this.counters.writeFalseCount++;\n\t\t} catch (error) {\n\t\t\tthis.counters.errorCount++;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.counters.peakWritableLength = Math.max(this.counters.peakWritableLength, this.stream.writableLength);\n\t\tif (log && this.logPath) {\n\t\t\ttry {\n\t\t\t\tappendFileSync(this.logPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t/* Explicit raw debug logging remains best-effort. */\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): TerminalOutputStats {\n\t\treturn {\n\t\t\t...this.counters,\n\t\t\twritableLength: this.stream.writableLength,\n\t\t\tbackpressured: this.stream.writableNeedDrain,\n\t\t};\n\t}\n\n\tstop(): void {\n\t\tthis.finalLine();\n\t\tfinalOnExit.delete(this.finalLine);\n\t\tthis.stream.off(\"drain\", this.onDrain);\n\t\tthis.stream.off(errorMonitor, this.onError);\n\t\tthis.observing = false;\n\t\tif (activeOutput === this) activeOutput = undefined;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture
|
|
3
|
+
* of omk's terminal output can be replayed with resizes at exact byte offsets
|
|
4
|
+
* (tmux `pipe-pane` file sizes lag by several KB).
|
|
5
|
+
*
|
|
6
|
+
* Resize line, written when omk handles the resize event, before it renders:
|
|
7
|
+
* {"bytes":N,"cols":C,"rows":R,"t":T,"prevCols":PC,"prevRows":PR}
|
|
8
|
+
* Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM
|
|
9
|
+
* paths that stop the TUI), and on process exit if no final line with the same
|
|
10
|
+
* byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):
|
|
11
|
+
* {"final":true,"bytes":N}
|
|
12
|
+
*
|
|
13
|
+
* `bytes` is the cumulative UTF-8 length of everything omk handed to stdout
|
|
14
|
+
* through its terminal writer so far, counted at the write() call: omk-side
|
|
15
|
+
* bytes, not pty bytes (no ONLCR `\n` → `\r\n` correction). It is an upper
|
|
16
|
+
* bound on where the resize hit the byte stream (written bytes the terminal had
|
|
17
|
+
* not read yet may be processed at the new size); the external pipe-pane
|
|
18
|
+
* offset is the lower bound. `t` is `performance.now()` in ms.
|
|
19
|
+
*
|
|
20
|
+
* Lines are appended synchronously so they land before exit. Write errors are
|
|
21
|
+
* ignored (debug output, best-effort). Unset: no log object exists and the
|
|
22
|
+
* resize handler is not wrapped (TerminalOutput.withResizeLog).
|
|
23
|
+
*
|
|
24
|
+
* Node emits `resize` only when the tty size actually changed, so the SIGWINCH
|
|
25
|
+
* omk sends itself on start (stale size after suspend) logs a line only if the
|
|
26
|
+
* size changed while omk was stopped; there are no same-size lines. A
|
|
27
|
+
* suspend/resume cycle (external editor) writes a final line per stop, so
|
|
28
|
+
* readers take the last final line.
|
|
29
|
+
*/
|
|
30
|
+
export declare class TerminalResizeLog {
|
|
31
|
+
private readonly path;
|
|
32
|
+
constructor(path: string);
|
|
33
|
+
resize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void;
|
|
34
|
+
private finalBytes;
|
|
35
|
+
/** Skipped when the previous final line already has these bytes (stop, then exit). */
|
|
36
|
+
final(bytes: number): void;
|
|
37
|
+
private append;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=terminal-resize-log.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal-resize-log.d.ts","sourceRoot":"","sources":["../src/terminal-resize-log.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAE9B,YAAY,IAAI,EAAE,MAAM,EAEvB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE1F;IAED,OAAO,CAAC,UAAU,CAAM;IAExB,sFAAsF;IACtF,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAIzB;IAED,OAAO,CAAC,MAAM;CAOd","sourcesContent":["import { appendFileSync } from \"node:fs\";\nimport { performance } from \"node:perf_hooks\";\n\n/**\n * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture\n * of omk's terminal output can be replayed with resizes at exact byte offsets\n * (tmux `pipe-pane` file sizes lag by several KB).\n *\n * Resize line, written when omk handles the resize event, before it renders:\n * {\"bytes\":N,\"cols\":C,\"rows\":R,\"t\":T,\"prevCols\":PC,\"prevRows\":PR}\n * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM\n * paths that stop the TUI), and on process exit if no final line with the same\n * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):\n * {\"final\":true,\"bytes\":N}\n *\n * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout\n * through its terminal writer so far, counted at the write() call: omk-side\n * bytes, not pty bytes (no ONLCR `\\n` → `\\r\\n` correction). It is an upper\n * bound on where the resize hit the byte stream (written bytes the terminal had\n * not read yet may be processed at the new size); the external pipe-pane\n * offset is the lower bound. `t` is `performance.now()` in ms.\n *\n * Lines are appended synchronously so they land before exit. Write errors are\n * ignored (debug output, best-effort). Unset: no log object exists and the\n * resize handler is not wrapped (TerminalOutput.withResizeLog).\n *\n * Node emits `resize` only when the tty size actually changed, so the SIGWINCH\n * omk sends itself on start (stale size after suspend) logs a line only if the\n * size changed while omk was stopped; there are no same-size lines. A\n * suspend/resume cycle (external editor) writes a final line per stop, so\n * readers take the last final line.\n */\nexport class TerminalResizeLog {\n\tprivate readonly path: string;\n\n\tconstructor(path: string) {\n\t\tthis.path = path;\n\t}\n\n\tresize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void {\n\t\tthis.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });\n\t}\n\n\tprivate finalBytes = -1;\n\n\t/** Skipped when the previous final line already has these bytes (stop, then exit). */\n\tfinal(bytes: number): void {\n\t\tif (bytes === this.finalBytes) return;\n\t\tthis.finalBytes = bytes;\n\t\tthis.append({ final: true, bytes });\n\t}\n\n\tprivate append(record: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tappendFileSync(this.path, `${JSON.stringify(record)}\\n`, { encoding: \"utf8\" });\n\t\t} catch {\n\t\t\t/* Best-effort debug log. */\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { appendFileSync } from "node:fs";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
/**
|
|
4
|
+
* `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture
|
|
5
|
+
* of omk's terminal output can be replayed with resizes at exact byte offsets
|
|
6
|
+
* (tmux `pipe-pane` file sizes lag by several KB).
|
|
7
|
+
*
|
|
8
|
+
* Resize line, written when omk handles the resize event, before it renders:
|
|
9
|
+
* {"bytes":N,"cols":C,"rows":R,"t":T,"prevCols":PC,"prevRows":PR}
|
|
10
|
+
* Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM
|
|
11
|
+
* paths that stop the TUI), and on process exit if no final line with the same
|
|
12
|
+
* byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):
|
|
13
|
+
* {"final":true,"bytes":N}
|
|
14
|
+
*
|
|
15
|
+
* `bytes` is the cumulative UTF-8 length of everything omk handed to stdout
|
|
16
|
+
* through its terminal writer so far, counted at the write() call: omk-side
|
|
17
|
+
* bytes, not pty bytes (no ONLCR `\n` → `\r\n` correction). It is an upper
|
|
18
|
+
* bound on where the resize hit the byte stream (written bytes the terminal had
|
|
19
|
+
* not read yet may be processed at the new size); the external pipe-pane
|
|
20
|
+
* offset is the lower bound. `t` is `performance.now()` in ms.
|
|
21
|
+
*
|
|
22
|
+
* Lines are appended synchronously so they land before exit. Write errors are
|
|
23
|
+
* ignored (debug output, best-effort). Unset: no log object exists and the
|
|
24
|
+
* resize handler is not wrapped (TerminalOutput.withResizeLog).
|
|
25
|
+
*
|
|
26
|
+
* Node emits `resize` only when the tty size actually changed, so the SIGWINCH
|
|
27
|
+
* omk sends itself on start (stale size after suspend) logs a line only if the
|
|
28
|
+
* size changed while omk was stopped; there are no same-size lines. A
|
|
29
|
+
* suspend/resume cycle (external editor) writes a final line per stop, so
|
|
30
|
+
* readers take the last final line.
|
|
31
|
+
*/
|
|
32
|
+
export class TerminalResizeLog {
|
|
33
|
+
path;
|
|
34
|
+
constructor(path) {
|
|
35
|
+
this.path = path;
|
|
36
|
+
}
|
|
37
|
+
resize(bytes, cols, rows, prevCols, prevRows) {
|
|
38
|
+
this.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });
|
|
39
|
+
}
|
|
40
|
+
finalBytes = -1;
|
|
41
|
+
/** Skipped when the previous final line already has these bytes (stop, then exit). */
|
|
42
|
+
final(bytes) {
|
|
43
|
+
if (bytes === this.finalBytes)
|
|
44
|
+
return;
|
|
45
|
+
this.finalBytes = bytes;
|
|
46
|
+
this.append({ final: true, bytes });
|
|
47
|
+
}
|
|
48
|
+
append(record) {
|
|
49
|
+
try {
|
|
50
|
+
appendFileSync(this.path, `${JSON.stringify(record)}\n`, { encoding: "utf8" });
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
/* Best-effort debug log. */
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=terminal-resize-log.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal-resize-log.js","sourceRoot":"","sources":["../src/terminal-resize-log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,OAAO,iBAAiB;IACZ,IAAI,CAAS;IAE9B,YAAY,IAAY,EAAE;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,MAAM,CAAC,KAAa,EAAE,IAAY,EAAE,IAAY,EAAE,QAAgB,EAAE,QAAgB,EAAQ;QAC3F,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,WAAW,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;IAAA,CAC7E;IAEO,UAAU,GAAG,CAAC,CAAC,CAAC;IAExB,sFAAsF;IACtF,KAAK,CAAC,KAAa,EAAQ;QAC1B,IAAI,KAAK,KAAK,IAAI,CAAC,UAAU;YAAE,OAAO;QACtC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CACpC;IAEO,MAAM,CAAC,MAA+B,EAAQ;QACrD,IAAI,CAAC;YACJ,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAChF,CAAC;QAAC,MAAM,CAAC;YACR,4BAA4B;QAC7B,CAAC;IAAA,CACD;CACD","sourcesContent":["import { appendFileSync } from \"node:fs\";\nimport { performance } from \"node:perf_hooks\";\n\n/**\n * `OMK_TUI_RESIZE_LOG=<path>`: one JSON line per terminal resize, so a capture\n * of omk's terminal output can be replayed with resizes at exact byte offsets\n * (tmux `pipe-pane` file sizes lag by several KB).\n *\n * Resize line, written when omk handles the resize event, before it renders:\n * {\"bytes\":N,\"cols\":C,\"rows\":R,\"t\":T,\"prevCols\":PC,\"prevRows\":PR}\n * Final line, written on terminal stop (TUI stop, including SIGINT/SIGTERM\n * paths that stop the TUI), and on process exit if no final line with the same\n * byte count was written yet (exits that skip stop, e.g. a dead tty's EIO):\n * {\"final\":true,\"bytes\":N}\n *\n * `bytes` is the cumulative UTF-8 length of everything omk handed to stdout\n * through its terminal writer so far, counted at the write() call: omk-side\n * bytes, not pty bytes (no ONLCR `\\n` → `\\r\\n` correction). It is an upper\n * bound on where the resize hit the byte stream (written bytes the terminal had\n * not read yet may be processed at the new size); the external pipe-pane\n * offset is the lower bound. `t` is `performance.now()` in ms.\n *\n * Lines are appended synchronously so they land before exit. Write errors are\n * ignored (debug output, best-effort). Unset: no log object exists and the\n * resize handler is not wrapped (TerminalOutput.withResizeLog).\n *\n * Node emits `resize` only when the tty size actually changed, so the SIGWINCH\n * omk sends itself on start (stale size after suspend) logs a line only if the\n * size changed while omk was stopped; there are no same-size lines. A\n * suspend/resume cycle (external editor) writes a final line per stop, so\n * readers take the last final line.\n */\nexport class TerminalResizeLog {\n\tprivate readonly path: string;\n\n\tconstructor(path: string) {\n\t\tthis.path = path;\n\t}\n\n\tresize(bytes: number, cols: number, rows: number, prevCols: number, prevRows: number): void {\n\t\tthis.append({ bytes, cols, rows, t: performance.now(), prevCols, prevRows });\n\t}\n\n\tprivate finalBytes = -1;\n\n\t/** Skipped when the previous final line already has these bytes (stop, then exit). */\n\tfinal(bytes: number): void {\n\t\tif (bytes === this.finalBytes) return;\n\t\tthis.finalBytes = bytes;\n\t\tthis.append({ final: true, bytes });\n\t}\n\n\tprivate append(record: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tappendFileSync(this.path, `${JSON.stringify(record)}\\n`, { encoding: \"utf8\" });\n\t\t} catch {\n\t\t\t/* Best-effort debug log. */\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How far back a clearing repair repaint may reach, in viewport screens.
|
|
3
|
+
* Bounds the scrollback churn of fixing rows that already scrolled off
|
|
4
|
+
* (see the repaint budget note in TUI.doRender's fullRender helper). Shared
|
|
5
|
+
* by the above-viewport repair and the height-resize resync below.
|
|
6
|
+
*/
|
|
7
|
+
export declare const REPAINT_BUDGET_SCREENS = 4;
|
|
8
|
+
/**
|
|
9
|
+
* Rows to write, relative to the cursor, before a height-change repaint.
|
|
10
|
+
*
|
|
11
|
+
* The height-change repaint homes the cursor and rewrites only the last
|
|
12
|
+
* `height` rows, which assumes the screen top is row `newLines.length - height`.
|
|
13
|
+
* A resize does not guarantee that: xterm.js drops the rows below the cursor
|
|
14
|
+
* (the editor footer) when the screen shrinks, and rows the stream appended
|
|
15
|
+
* since the last frame shift the tail down. Either way the screen top sits
|
|
16
|
+
* above the tail, and the repaint overwrote rows that never reached scrollback
|
|
17
|
+
* (scrollback-20 main-r4 lost `value1_3`..`value1_6`).
|
|
18
|
+
*
|
|
19
|
+
* What a resize does keep is the cursor's row and the rows above it (the
|
|
20
|
+
* terminal scrolls or pulls rows around the cursor, it does not move the
|
|
21
|
+
* cursor off its row). So walk up from the cursor's row to the first row that
|
|
22
|
+
* differs from the last frame and rewrite from there to the end with line
|
|
23
|
+
* feeds: rows that no longer fit scroll into scrollback in order, and the tail
|
|
24
|
+
* repaint that follows lands on a screen that already holds the same rows.
|
|
25
|
+
* If the walk up is clamped at the screen top (the first changed row already
|
|
26
|
+
* scrolled away), the changed rows print below their stale copies: duplicated,
|
|
27
|
+
* not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens
|
|
28
|
+
* above the end are not re-sent; the start never moves below the cursor row.
|
|
29
|
+
*
|
|
30
|
+
* Rows are compared without overlays (`previousBase`/`currentBase`, the
|
|
31
|
+
* rows the components rendered): a full-height overlay such as the pinned
|
|
32
|
+
* status rail shifts relative to the content when the screen scrolls, so the
|
|
33
|
+
* composited rows above the cursor would all look changed and be re-sent on
|
|
34
|
+
* every resize step. What is written is the composited frame (`newLines`).
|
|
35
|
+
*
|
|
36
|
+
* A frame that fits the new screen needs no resync: the tail repaint writes
|
|
37
|
+
* all of it from the top. Resyncing it anyway is harmful when the frame was
|
|
38
|
+
* padded to the screen height (an overlay taller than short content): its
|
|
39
|
+
* rows are screen rows, not scrollback-anchored rows, so after a grow pulled
|
|
40
|
+
* rows back from scrollback the cursor's row no longer maps to the same
|
|
41
|
+
* content row and the line feeds push the pulled-back rows into scrollback a
|
|
42
|
+
* second time.
|
|
43
|
+
*
|
|
44
|
+
* @param previousBase pre-overlay rows of the last frame
|
|
45
|
+
* @param newLines composited rows of the frame about to be painted
|
|
46
|
+
* @param cursorRow content row the hardware cursor was left on by the last frame
|
|
47
|
+
* @param height terminal rows after the resize
|
|
48
|
+
* @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)
|
|
49
|
+
*/
|
|
50
|
+
export declare function resyncAfterResize(previousBase: readonly string[], newLines: readonly string[], cursorRow: number, height: number, currentBase?: readonly string[]): string;
|
|
51
|
+
/**
|
|
52
|
+
* First row the resync rewrites, the first changed row at or above the cursor
|
|
53
|
+
* row, and whether the repaint budget moved the start down from it. Requires
|
|
54
|
+
* `length > 0`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function resyncStart(previousBase: readonly string[], currentBase: readonly string[], length: number, cursorRow: number, height: number): {
|
|
57
|
+
first: number;
|
|
58
|
+
changed: number;
|
|
59
|
+
capped: boolean;
|
|
60
|
+
};
|
|
61
|
+
/** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */
|
|
62
|
+
export declare class ResizeResync {
|
|
63
|
+
private previousBase;
|
|
64
|
+
private currentBase;
|
|
65
|
+
/** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */
|
|
66
|
+
track<T extends readonly string[]>(base: T): T;
|
|
67
|
+
/** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */
|
|
68
|
+
detail: string;
|
|
69
|
+
/** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */
|
|
70
|
+
after(newLines: readonly string[], cursorRow: number, height: number): string;
|
|
71
|
+
}
|
|
72
|
+
/** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */
|
|
73
|
+
export declare function isTermuxSession(): boolean;
|
|
74
|
+
//# sourceMappingURL=terminal-resync.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal-resync.d.ts","sourceRoot":"","sources":["../src/terminal-resync.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,IAAI,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,iBAAiB,CAChC,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,WAAW,GAAE,SAAS,MAAM,EAAa,GACvC,MAAM,CAUR;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAC1B,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,WAAW,EAAE,SAAS,MAAM,EAAE,EAC9B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,GACZ;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAerD;AAED,wFAAwF;AACxF,qBAAa,YAAY;IACxB,OAAO,CAAC,YAAY,CAAyB;IAC7C,OAAO,CAAC,WAAW,CAAyB;IAE5C,2GAA2G;IAC3G,KAAK,CAAC,CAAC,SAAS,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAI7C;IAED,uEAAuE;IACvE,MAAM,SAAM;IAEZ,qFAAqF;IACrF,KAAK,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAe5E;CACD;AAED,gHAAgH;AAChH,wBAAgB,eAAe,IAAI,OAAO,CAEzC","sourcesContent":["/**\n * How far back a clearing repair repaint may reach, in viewport screens.\n * Bounds the scrollback churn of fixing rows that already scrolled off\n * (see the repaint budget note in TUI.doRender's fullRender helper). Shared\n * by the above-viewport repair and the height-resize resync below.\n */\nexport const REPAINT_BUDGET_SCREENS = 4;\n\n/**\n * Rows to write, relative to the cursor, before a height-change repaint.\n *\n * The height-change repaint homes the cursor and rewrites only the last\n * `height` rows, which assumes the screen top is row `newLines.length - height`.\n * A resize does not guarantee that: xterm.js drops the rows below the cursor\n * (the editor footer) when the screen shrinks, and rows the stream appended\n * since the last frame shift the tail down. Either way the screen top sits\n * above the tail, and the repaint overwrote rows that never reached scrollback\n * (scrollback-20 main-r4 lost `value1_3`..`value1_6`).\n *\n * What a resize does keep is the cursor's row and the rows above it (the\n * terminal scrolls or pulls rows around the cursor, it does not move the\n * cursor off its row). So walk up from the cursor's row to the first row that\n * differs from the last frame and rewrite from there to the end with line\n * feeds: rows that no longer fit scroll into scrollback in order, and the tail\n * repaint that follows lands on a screen that already holds the same rows.\n * If the walk up is clamped at the screen top (the first changed row already\n * scrolled away), the changed rows print below their stale copies: duplicated,\n * not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens\n * above the end are not re-sent; the start never moves below the cursor row.\n *\n * Rows are compared without overlays (`previousBase`/`currentBase`, the\n * rows the components rendered): a full-height overlay such as the pinned\n * status rail shifts relative to the content when the screen scrolls, so the\n * composited rows above the cursor would all look changed and be re-sent on\n * every resize step. What is written is the composited frame (`newLines`).\n *\n * A frame that fits the new screen needs no resync: the tail repaint writes\n * all of it from the top. Resyncing it anyway is harmful when the frame was\n * padded to the screen height (an overlay taller than short content): its\n * rows are screen rows, not scrollback-anchored rows, so after a grow pulled\n * rows back from scrollback the cursor's row no longer maps to the same\n * content row and the line feeds push the pulled-back rows into scrollback a\n * second time.\n *\n * @param previousBase pre-overlay rows of the last frame\n * @param newLines composited rows of the frame about to be painted\n * @param cursorRow content row the hardware cursor was left on by the last frame\n * @param height terminal rows after the resize\n * @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)\n */\nexport function resyncAfterResize(\n\tpreviousBase: readonly string[],\n\tnewLines: readonly string[],\n\tcursorRow: number,\n\theight: number,\n\tcurrentBase: readonly string[] = newLines,\n): string {\n\tif (newLines.length === 0 || newLines.length <= height) return \"\";\n\tconst { first } = resyncStart(previousBase, currentBase, newLines.length, cursorRow, height);\n\tconst up = cursorRow - first;\n\tlet buffer = up > 0 ? `\\x1b[${up}A\\r` : \"\\r\";\n\tfor (let i = first; i < newLines.length; i++) {\n\t\tif (i > first) buffer += \"\\r\\n\";\n\t\tbuffer += `\\x1b[2K${newLines[i]}`;\n\t}\n\treturn buffer;\n}\n\n/**\n * First row the resync rewrites, the first changed row at or above the cursor\n * row, and whether the repaint budget moved the start down from it. Requires\n * `length > 0`.\n */\nexport function resyncStart(\n\tpreviousBase: readonly string[],\n\tcurrentBase: readonly string[],\n\tlength: number,\n\tcursorRow: number,\n\theight: number,\n): { first: number; changed: number; capped: boolean } {\n\tconst top = Math.min(cursorRow, length - 1);\n\tlet changed = top;\n\tfor (let i = 0; i < top; i++) {\n\t\tif (previousBase[i] !== currentBase[i]) {\n\t\t\tchanged = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t// The budget only limits how far UP already-printed rows are re-sent. It\n\t// must never push the start below the cursor: cursor-down stops at the\n\t// screen bottom, so the rows in between would never be written (a resize\n\t// frame that appended more than the budget lost them).\n\tconst first = Math.min(Math.max(changed, length - height * REPAINT_BUDGET_SCREENS, 0), top);\n\treturn { first, changed, capped: first > changed };\n}\n\n/** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */\nexport class ResizeResync {\n\tprivate previousBase: readonly string[] = [];\n\tprivate currentBase: readonly string[] = [];\n\n\t/** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */\n\ttrack<T extends readonly string[]>(base: T): T {\n\t\tthis.previousBase = this.currentBase;\n\t\tthis.currentBase = base;\n\t\treturn base;\n\t}\n\n\t/** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */\n\tdetail = \"\";\n\n\t/** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */\n\tafter(newLines: readonly string[], cursorRow: number, height: number): string {\n\t\tconst output = resyncAfterResize(this.previousBase, newLines, cursorRow, height, this.currentBase);\n\t\tif (!output) {\n\t\t\tthis.detail = `resync none (frame fits: new=${newLines.length} <= height=${height})`;\n\t\t\treturn output;\n\t\t}\n\t\tconst { first, changed, capped } = resyncStart(\n\t\t\tthis.previousBase,\n\t\t\tthis.currentBase,\n\t\t\tnewLines.length,\n\t\t\tcursorRow,\n\t\t\theight,\n\t\t);\n\t\tthis.detail = `resync first=${first} changed=${changed} cursorRow=${cursorRow} capped=${capped}`;\n\t\treturn output;\n\t}\n}\n\n/** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */\nexport function isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX_VERSION);\n}\n"]}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How far back a clearing repair repaint may reach, in viewport screens.
|
|
3
|
+
* Bounds the scrollback churn of fixing rows that already scrolled off
|
|
4
|
+
* (see the repaint budget note in TUI.doRender's fullRender helper). Shared
|
|
5
|
+
* by the above-viewport repair and the height-resize resync below.
|
|
6
|
+
*/
|
|
7
|
+
export const REPAINT_BUDGET_SCREENS = 4;
|
|
8
|
+
/**
|
|
9
|
+
* Rows to write, relative to the cursor, before a height-change repaint.
|
|
10
|
+
*
|
|
11
|
+
* The height-change repaint homes the cursor and rewrites only the last
|
|
12
|
+
* `height` rows, which assumes the screen top is row `newLines.length - height`.
|
|
13
|
+
* A resize does not guarantee that: xterm.js drops the rows below the cursor
|
|
14
|
+
* (the editor footer) when the screen shrinks, and rows the stream appended
|
|
15
|
+
* since the last frame shift the tail down. Either way the screen top sits
|
|
16
|
+
* above the tail, and the repaint overwrote rows that never reached scrollback
|
|
17
|
+
* (scrollback-20 main-r4 lost `value1_3`..`value1_6`).
|
|
18
|
+
*
|
|
19
|
+
* What a resize does keep is the cursor's row and the rows above it (the
|
|
20
|
+
* terminal scrolls or pulls rows around the cursor, it does not move the
|
|
21
|
+
* cursor off its row). So walk up from the cursor's row to the first row that
|
|
22
|
+
* differs from the last frame and rewrite from there to the end with line
|
|
23
|
+
* feeds: rows that no longer fit scroll into scrollback in order, and the tail
|
|
24
|
+
* repaint that follows lands on a screen that already holds the same rows.
|
|
25
|
+
* If the walk up is clamped at the screen top (the first changed row already
|
|
26
|
+
* scrolled away), the changed rows print below their stale copies: duplicated,
|
|
27
|
+
* not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens
|
|
28
|
+
* above the end are not re-sent; the start never moves below the cursor row.
|
|
29
|
+
*
|
|
30
|
+
* Rows are compared without overlays (`previousBase`/`currentBase`, the
|
|
31
|
+
* rows the components rendered): a full-height overlay such as the pinned
|
|
32
|
+
* status rail shifts relative to the content when the screen scrolls, so the
|
|
33
|
+
* composited rows above the cursor would all look changed and be re-sent on
|
|
34
|
+
* every resize step. What is written is the composited frame (`newLines`).
|
|
35
|
+
*
|
|
36
|
+
* A frame that fits the new screen needs no resync: the tail repaint writes
|
|
37
|
+
* all of it from the top. Resyncing it anyway is harmful when the frame was
|
|
38
|
+
* padded to the screen height (an overlay taller than short content): its
|
|
39
|
+
* rows are screen rows, not scrollback-anchored rows, so after a grow pulled
|
|
40
|
+
* rows back from scrollback the cursor's row no longer maps to the same
|
|
41
|
+
* content row and the line feeds push the pulled-back rows into scrollback a
|
|
42
|
+
* second time.
|
|
43
|
+
*
|
|
44
|
+
* @param previousBase pre-overlay rows of the last frame
|
|
45
|
+
* @param newLines composited rows of the frame about to be painted
|
|
46
|
+
* @param cursorRow content row the hardware cursor was left on by the last frame
|
|
47
|
+
* @param height terminal rows after the resize
|
|
48
|
+
* @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)
|
|
49
|
+
*/
|
|
50
|
+
export function resyncAfterResize(previousBase, newLines, cursorRow, height, currentBase = newLines) {
|
|
51
|
+
if (newLines.length === 0 || newLines.length <= height)
|
|
52
|
+
return "";
|
|
53
|
+
const { first } = resyncStart(previousBase, currentBase, newLines.length, cursorRow, height);
|
|
54
|
+
const up = cursorRow - first;
|
|
55
|
+
let buffer = up > 0 ? `\x1b[${up}A\r` : "\r";
|
|
56
|
+
for (let i = first; i < newLines.length; i++) {
|
|
57
|
+
if (i > first)
|
|
58
|
+
buffer += "\r\n";
|
|
59
|
+
buffer += `\x1b[2K${newLines[i]}`;
|
|
60
|
+
}
|
|
61
|
+
return buffer;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* First row the resync rewrites, the first changed row at or above the cursor
|
|
65
|
+
* row, and whether the repaint budget moved the start down from it. Requires
|
|
66
|
+
* `length > 0`.
|
|
67
|
+
*/
|
|
68
|
+
export function resyncStart(previousBase, currentBase, length, cursorRow, height) {
|
|
69
|
+
const top = Math.min(cursorRow, length - 1);
|
|
70
|
+
let changed = top;
|
|
71
|
+
for (let i = 0; i < top; i++) {
|
|
72
|
+
if (previousBase[i] !== currentBase[i]) {
|
|
73
|
+
changed = i;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// The budget only limits how far UP already-printed rows are re-sent. It
|
|
78
|
+
// must never push the start below the cursor: cursor-down stops at the
|
|
79
|
+
// screen bottom, so the rows in between would never be written (a resize
|
|
80
|
+
// frame that appended more than the budget lost them).
|
|
81
|
+
const first = Math.min(Math.max(changed, length - height * REPAINT_BUDGET_SCREENS, 0), top);
|
|
82
|
+
return { first, changed, capped: first > changed };
|
|
83
|
+
}
|
|
84
|
+
/** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */
|
|
85
|
+
export class ResizeResync {
|
|
86
|
+
previousBase = [];
|
|
87
|
+
currentBase = [];
|
|
88
|
+
/** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */
|
|
89
|
+
track(base) {
|
|
90
|
+
this.previousBase = this.currentBase;
|
|
91
|
+
this.currentBase = base;
|
|
92
|
+
return base;
|
|
93
|
+
}
|
|
94
|
+
/** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */
|
|
95
|
+
detail = "";
|
|
96
|
+
/** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */
|
|
97
|
+
after(newLines, cursorRow, height) {
|
|
98
|
+
const output = resyncAfterResize(this.previousBase, newLines, cursorRow, height, this.currentBase);
|
|
99
|
+
if (!output) {
|
|
100
|
+
this.detail = `resync none (frame fits: new=${newLines.length} <= height=${height})`;
|
|
101
|
+
return output;
|
|
102
|
+
}
|
|
103
|
+
const { first, changed, capped } = resyncStart(this.previousBase, this.currentBase, newLines.length, cursorRow, height);
|
|
104
|
+
this.detail = `resync first=${first} changed=${changed} cursorRow=${cursorRow} capped=${capped}`;
|
|
105
|
+
return output;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */
|
|
109
|
+
export function isTermuxSession() {
|
|
110
|
+
return Boolean(process.env.TERMUX_VERSION);
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=terminal-resync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal-resync.js","sourceRoot":"","sources":["../src/terminal-resync.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAM,UAAU,iBAAiB,CAChC,YAA+B,EAC/B,QAA2B,EAC3B,SAAiB,EACjB,MAAc,EACd,WAAW,GAAsB,QAAQ,EAChC;IACT,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,IAAI,QAAQ,CAAC,MAAM,IAAI,MAAM;QAAE,OAAO,EAAE,CAAC;IAClE,MAAM,EAAE,KAAK,EAAE,GAAG,WAAW,CAAC,YAAY,EAAE,WAAW,EAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IAC7F,MAAM,EAAE,GAAG,SAAS,GAAG,KAAK,CAAC;IAC7B,IAAI,MAAM,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IAC7C,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9C,IAAI,CAAC,GAAG,KAAK;YAAE,MAAM,IAAI,MAAM,CAAC;QAChC,MAAM,IAAI,UAAU,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IACnC,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd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,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACnG,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,IAAI,CAAC,MAAM,GAAG,gCAAgC,QAAQ,CAAC,MAAM,cAAc,MAAM,GAAG,CAAC;YACrF,OAAO,MAAM,CAAC;QACf,CAAC;QACD,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,WAAW,CAC7C,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,WAAW,EAChB,QAAQ,CAAC,MAAM,EACf,SAAS,EACT,MAAM,CACN,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,gBAAgB,KAAK,YAAY,OAAO,cAAc,SAAS,WAAW,MAAM,EAAE,CAAC;QACjG,OAAO,MAAM,CAAC;IAAA,CACd;CACD;AAED,gHAAgH;AAChH,MAAM,UAAU,eAAe,GAAY;IAC1C,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAAA,CAC3C","sourcesContent":["/**\n * How far back a clearing repair repaint may reach, in viewport screens.\n * Bounds the scrollback churn of fixing rows that already scrolled off\n * (see the repaint budget note in TUI.doRender's fullRender helper). Shared\n * by the above-viewport repair and the height-resize resync below.\n */\nexport const REPAINT_BUDGET_SCREENS = 4;\n\n/**\n * Rows to write, relative to the cursor, before a height-change repaint.\n *\n * The height-change repaint homes the cursor and rewrites only the last\n * `height` rows, which assumes the screen top is row `newLines.length - height`.\n * A resize does not guarantee that: xterm.js drops the rows below the cursor\n * (the editor footer) when the screen shrinks, and rows the stream appended\n * since the last frame shift the tail down. Either way the screen top sits\n * above the tail, and the repaint overwrote rows that never reached scrollback\n * (scrollback-20 main-r4 lost `value1_3`..`value1_6`).\n *\n * What a resize does keep is the cursor's row and the rows above it (the\n * terminal scrolls or pulls rows around the cursor, it does not move the\n * cursor off its row). So walk up from the cursor's row to the first row that\n * differs from the last frame and rewrite from there to the end with line\n * feeds: rows that no longer fit scroll into scrollback in order, and the tail\n * repaint that follows lands on a screen that already holds the same rows.\n * If the walk up is clamped at the screen top (the first changed row already\n * scrolled away), the changed rows print below their stale copies: duplicated,\n * not lost. Already-printed rows more than REPAINT_BUDGET_SCREENS screens\n * above the end are not re-sent; the start never moves below the cursor row.\n *\n * Rows are compared without overlays (`previousBase`/`currentBase`, the\n * rows the components rendered): a full-height overlay such as the pinned\n * status rail shifts relative to the content when the screen scrolls, so the\n * composited rows above the cursor would all look changed and be re-sent on\n * every resize step. What is written is the composited frame (`newLines`).\n *\n * A frame that fits the new screen needs no resync: the tail repaint writes\n * all of it from the top. Resyncing it anyway is harmful when the frame was\n * padded to the screen height (an overlay taller than short content): its\n * rows are screen rows, not scrollback-anchored rows, so after a grow pulled\n * rows back from scrollback the cursor's row no longer maps to the same\n * content row and the line feeds push the pulled-back rows into scrollback a\n * second time.\n *\n * @param previousBase pre-overlay rows of the last frame\n * @param newLines composited rows of the frame about to be painted\n * @param cursorRow content row the hardware cursor was left on by the last frame\n * @param height terminal rows after the resize\n * @param currentBase pre-overlay rows of the frame about to be painted (default: `newLines`)\n */\nexport function resyncAfterResize(\n\tpreviousBase: readonly string[],\n\tnewLines: readonly string[],\n\tcursorRow: number,\n\theight: number,\n\tcurrentBase: readonly string[] = newLines,\n): string {\n\tif (newLines.length === 0 || newLines.length <= height) return \"\";\n\tconst { first } = resyncStart(previousBase, currentBase, newLines.length, cursorRow, height);\n\tconst up = cursorRow - first;\n\tlet buffer = up > 0 ? `\\x1b[${up}A\\r` : \"\\r\";\n\tfor (let i = first; i < newLines.length; i++) {\n\t\tif (i > first) buffer += \"\\r\\n\";\n\t\tbuffer += `\\x1b[2K${newLines[i]}`;\n\t}\n\treturn buffer;\n}\n\n/**\n * First row the resync rewrites, the first changed row at or above the cursor\n * row, and whether the repaint budget moved the start down from it. Requires\n * `length > 0`.\n */\nexport function resyncStart(\n\tpreviousBase: readonly string[],\n\tcurrentBase: readonly string[],\n\tlength: number,\n\tcursorRow: number,\n\theight: number,\n): { first: number; changed: number; capped: boolean } {\n\tconst top = Math.min(cursorRow, length - 1);\n\tlet changed = top;\n\tfor (let i = 0; i < top; i++) {\n\t\tif (previousBase[i] !== currentBase[i]) {\n\t\t\tchanged = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t// The budget only limits how far UP already-printed rows are re-sent. It\n\t// must never push the start below the cursor: cursor-down stops at the\n\t// screen bottom, so the rows in between would never be written (a resize\n\t// frame that appended more than the budget lost them).\n\tconst first = Math.min(Math.max(changed, length - height * REPAINT_BUDGET_SCREENS, 0), top);\n\treturn { first, changed, capped: first > changed };\n}\n\n/** Per-TUI state for resyncAfterResize: the pre-overlay rows of the last two frames. */\nexport class ResizeResync {\n\tprivate previousBase: readonly string[] = [];\n\tprivate currentBase: readonly string[] = [];\n\n\t/** Records a frame's rows before overlays are composited; returns them unchanged. Call once per render. */\n\ttrack<T extends readonly string[]>(base: T): T {\n\t\tthis.previousBase = this.currentBase;\n\t\tthis.currentBase = base;\n\t\treturn base;\n\t}\n\n\t/** How the last after() call chose its start, for OMK_DEBUG_REDRAW. */\n\tdetail = \"\";\n\n\t/** resyncAfterResize for the frame last passed to track(), painted as `newLines`. */\n\tafter(newLines: readonly string[], cursorRow: number, height: number): string {\n\t\tconst output = resyncAfterResize(this.previousBase, newLines, cursorRow, height, this.currentBase);\n\t\tif (!output) {\n\t\t\tthis.detail = `resync none (frame fits: new=${newLines.length} <= height=${height})`;\n\t\t\treturn output;\n\t\t}\n\t\tconst { first, changed, capped } = resyncStart(\n\t\t\tthis.previousBase,\n\t\t\tthis.currentBase,\n\t\t\tnewLines.length,\n\t\t\tcursorRow,\n\t\t\theight,\n\t\t);\n\t\tthis.detail = `resync first=${first} changed=${changed} cursorRow=${cursorRow} capped=${capped}`;\n\t\treturn output;\n\t}\n}\n\n/** Termux changes height when the software keyboard shows or hides; those resizes skip the clearing repaint. */\nexport function isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX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AAuC;IA2B/C,OAAO,CAAC,oCAAoC;IAK5C,OAAO,CAAC,sCAAsC;IAK9C,OAAO,CAAC,6CAA6C;IAOrD,OAAO,CAAC,8CAA8C;IAQtD,OAAO,CAAC,gDAAgD;IAMxD,OAAO,CAAC,oBAAoB;IAW5B,OAAO,CAAC,qBAAqB;IAM7B,OAAO,CAAC,kCAAkC;IAM1C;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IA8BtB,UAAU,CAAC,KAAK,SAAO,EAAE,MAAM,SAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CA2CzD;IAED,IAAI,IAAI,IAAI,CAsDX;IAED,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAExB;IAED,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAM1B;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,SAAS,IAAI,IAAI,CAEhB;IAED,eAAe,IAAI,IAAI,CAEtB;IAED,WAAW,IAAI,IAAI,CAElB;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE5B;IAED,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAYjC;IAED,OAAO,CAAC,qBAAqB;CAM7B","sourcesContent":["import { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\nimport { TerminalOutput, type TerminalOutputStats } from \"./terminal-output.ts\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\nconst TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;\nconst TERMINAL_PROGRESS_ACTIVE_SEQUENCE = \"\\x1b]9;4;3\\x07\";\nconst TERMINAL_PROGRESS_CLEAR_SEQUENCE = \"\\x1b]9;4;0;\\x07\";\nconst APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS = 150;\nconst KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;\nconst KITTY_KEYBOARD_PROTOCOL_QUERY = `\\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\\x1b[?u\\x1b[c`;\n\nexport type KeyboardProtocolNegotiationSequence =\n\t| { type: \"kitty-flags\"; flags: number }\n\t| { type: \"device-attributes\" };\n\nexport function parseKeyboardProtocolNegotiationSequence(\n\tsequence: string,\n): KeyboardProtocolNegotiationSequence | undefined {\n\tconst kittyFlags = sequence.match(/^\\x1b\\[\\?(\\d+)u$/);\n\tif (kittyFlags) {\n\t\treturn { type: \"kitty-flags\", flags: Number.parseInt(kittyFlags[1]!, 10) };\n\t}\n\tif (/^\\x1b\\[\\?[\\d;]*c$/.test(sequence)) {\n\t\treturn { type: \"device-attributes\" };\n\t}\n\treturn undefined;\n}\n\nfunction isKeyboardProtocolNegotiationSequencePrefix(sequence: string, allowBareEscapePrefix: boolean): boolean {\n\treturn (allowBareEscapePrefix && sequence === \"\\x1b\") || sequence === \"\\x1b[\" || /^\\x1b\\[\\?[\\d;]*$/.test(sequence);\n}\n\nexport function isAppleTerminalSession(): boolean {\n\treturn process.platform === \"darwin\" && process.env.TERM_PROGRAM === \"Apple_Terminal\";\n}\n\nexport function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\tif (isAppleTerminal && data === \"\\r\" && isShiftPressed) return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;\n\treturn data;\n}\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\t/** Optional metadata-only output observations; unsupported terminals omit this. */\n\tgetOutputStats?(): TerminalOutputStats;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n\n\t// Progress indicator (OSC 9;4)\n\tsetProgress(active: boolean): void;\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate _modifyOtherKeysActive = false;\n\tprivate keyboardProtocolPushed = false;\n\tprivate keyboardProtocolNegotiationPending = false;\n\tprivate keyboardProtocolLateResponsePending = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolFallbackTimer?: ReturnType<typeof setTimeout>;\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate readonly output: TerminalOutput;\n\n\tconstructor(output: Writable = process.stdout) {\n\t\tthis.output = new TerminalOutput(output, process.env.OMK_TUI_WRITE_LOG || \"\");\n\t}\n\n\tgetOutputStats(): TerminalOutputStats {\n\t\treturn this.output.snapshot();\n\t}\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tthis.output.write(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query and enable Kitty keyboard protocol\n\t\t// The query handler intercepts input temporarily, then installs the user's handler\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ timeout: 10 });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\tif (this.keyboardProtocolNegotiationPending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, true);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\treturn; // Wait for the rest of a split negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.keyboardProtocolLateResponsePending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, false);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t\t\treturn; // Wait for the rest of a split late negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.forwardInputSequence(sequence);\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable it if available.\n\t *\n\t * Kitty's progressive enhancement detection requires requesting the desired\n\t * flags before querying them. The trailing DA query is a sentinel supported by\n\t * terminals that do not know Kitty keyboard protocol. A short timeout remains\n\t * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop\n\t * the DA response.\n\t *\n\t * The requested flags are:\n\t * - 1 = disambiguate escape codes\n\t * - 2 = report event types (press/repeat/release)\n\t * - 4 = report alternate keys (shifted key, base layout key)\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tthis.keyboardProtocolPushed = true;\n\t\tthis.keyboardProtocolNegotiationPending = true;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.output.write(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t\tthis.keyboardProtocolFallbackTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\tif (this.keyboardProtocolNegotiationBuffer === \"\\x1b\") {\n\t\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t\t} else {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t}\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}, KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0 && !this._kittyProtocolActive) {\n\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tthis.enableModifyOtherKeys();\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t\tallowBareEscapePrefix: boolean,\n\t): KeyboardProtocolNegotiationSequence | \"pending\" | undefined {\n\t\tif (this.keyboardProtocolNegotiationBuffer) {\n\t\t\tconst bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;\n\t\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);\n\t\t\tif (negotiationSequence) {\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\treturn negotiationSequence;\n\t\t\t}\n\t\t\tif (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence, allowBareEscapePrefix)) {\n\t\t\t\tthis.setKeyboardProtocolNegotiationBuffer(bufferedSequence);\n\t\t\t\treturn \"pending\";\n\t\t\t}\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}\n\n\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);\n\t\tif (negotiationSequence) return negotiationSequence;\n\t\tif (isKeyboardProtocolNegotiationSequencePrefix(sequence, allowBareEscapePrefix)) {\n\t\t\tthis.setKeyboardProtocolNegotiationBuffer(sequence);\n\t\t\treturn \"pending\";\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate setKeyboardProtocolNegotiationBuffer(sequence: string): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = sequence;\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBuffer(): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = \"\";\n\t}\n\n\tprivate flushKeyboardProtocolNegotiationBufferAsInput(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer) return;\n\t\tconst sequence = this.keyboardProtocolNegotiationBuffer;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.forwardInputSequence(sequence);\n\t}\n\n\tprivate scheduleKeyboardProtocolNegotiationBufferFlush(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;\n\t\tthis.keyboardProtocolBufferFlushTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBufferFlushTimer(): void {\n\t\tif (!this.keyboardProtocolBufferFlushTimer) return;\n\t\tclearTimeout(this.keyboardProtocolBufferFlushTimer);\n\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t}\n\n\tprivate forwardInputSequence(sequence: string): void {\n\t\tif (!this.inputHandler) return;\n\t\tconst isAppleTerminal = sequence === \"\\r\" && isAppleTerminalSession();\n\t\tconst input = normalizeAppleTerminalInput(\n\t\t\tsequence,\n\t\t\tisAppleTerminal,\n\t\t\tisAppleTerminal && isNativeModifierPressed(\"shift\"),\n\t\t);\n\t\tthis.inputHandler(input);\n\t}\n\n\tprivate enableModifyOtherKeys(): void {\n\t\tif (this._kittyProtocolActive || this._modifyOtherKeysActive) return;\n\t\tthis.output.write(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate clearKeyboardProtocolFallbackTimer(): void {\n\t\tif (!this.keyboardProtocolFallbackTimer) return;\n\t\tclearTimeout(this.keyboardProtocolFallbackTimer);\n\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\tconst arch = process.arch;\n\t\t\tif (arch !== \"x64\" && arch !== \"arm64\") return;\n\n\t\t\t// Dynamic require so non-Windows and bundled/browser paths never load the\n\t\t\t// native helper. In the npm package native/ is next to dist/; in compiled\n\t\t\t// binary archives native/ is copied next to the executable.\n\t\t\tconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tconst candidates = [\n\t\t\t\tpath.join(moduleDir, \"..\", nativePath),\n\t\t\t\tpath.join(moduleDir, nativePath),\n\t\t\t\tpath.join(path.dirname(process.execPath), nativePath),\n\t\t\t];\n\t\t\tfor (const modulePath of candidates) {\n\t\t\t\ttry {\n\t\t\t\t\tconst helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };\n\t\t\t\t\thelper.enableVirtualTerminalInput?.();\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// Try the next possible packaging location.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Native helper not available — Shift+Tab won't be distinguishable from Tab.\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tthis.output.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tthis.output.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.clearProgressInterval()) {\n\t\t\tthis.output.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tthis.output.write(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tthis.output.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tthis.output.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t}\n\t\tthis.output.stop();\n\t}\n\n\twrite(data: string): void {\n\t\tthis.output.write(data, true);\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || Number(process.env.COLUMNS) || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || Number(process.env.LINES) || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.output.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.output.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\thideCursor(): void {\n\t\tthis.output.write(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tthis.output.write(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tthis.output.write(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tthis.output.write(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tthis.output.write(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\tthis.output.write(`\\x1b]0;${title}\\x07`);\n\t}\n\n\tsetProgress(active: boolean): void {\n\t\tif (active) {\n\t\t\tthis.output.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tthis.output.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\t\t}, TERMINAL_PROGRESS_KEEPALIVE_MS);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.clearProgressInterval();\n\t\t\tthis.output.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\t}\n\n\tprivate clearProgressInterval(): boolean {\n\t\tif (!this.progressInterval) return false;\n\t\tclearInterval(this.progressInterval);\n\t\tthis.progressInterval = undefined;\n\t\treturn true;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK5C,OAAO,EAAkB,KAAK,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAahF,MAAM,MAAM,mCAAmC,GAC5C;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,mBAAmB,CA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,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAExB;IAED,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAM1B;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,SAAS,IAAI,IAAI,CAEhB;IAED,eAAe,IAAI,IAAI,CAEtB;IAED,WAAW,IAAI,IAAI,CAElB;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE5B;IAED,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAYjC;IAED,OAAO,CAAC,qBAAqB;CAM7B","sourcesContent":["import { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\nimport { TerminalOutput, type TerminalOutputStats } from \"./terminal-output.ts\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\nconst TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;\nconst TERMINAL_PROGRESS_ACTIVE_SEQUENCE = \"\\x1b]9;4;3\\x07\";\nconst TERMINAL_PROGRESS_CLEAR_SEQUENCE = \"\\x1b]9;4;0;\\x07\";\nconst APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS = 150;\nconst KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;\nconst KITTY_KEYBOARD_PROTOCOL_QUERY = `\\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\\x1b[?u\\x1b[c`;\n\nexport type KeyboardProtocolNegotiationSequence =\n\t| { type: \"kitty-flags\"; flags: number }\n\t| { type: \"device-attributes\" };\n\nexport function parseKeyboardProtocolNegotiationSequence(\n\tsequence: string,\n): KeyboardProtocolNegotiationSequence | undefined {\n\tconst kittyFlags = sequence.match(/^\\x1b\\[\\?(\\d+)u$/);\n\tif (kittyFlags) {\n\t\treturn { type: \"kitty-flags\", flags: Number.parseInt(kittyFlags[1]!, 10) };\n\t}\n\tif (/^\\x1b\\[\\?[\\d;]*c$/.test(sequence)) {\n\t\treturn { type: \"device-attributes\" };\n\t}\n\treturn undefined;\n}\n\nfunction isKeyboardProtocolNegotiationSequencePrefix(sequence: string, allowBareEscapePrefix: boolean): boolean {\n\treturn (allowBareEscapePrefix && sequence === \"\\x1b\") || sequence === \"\\x1b[\" || /^\\x1b\\[\\?[\\d;]*$/.test(sequence);\n}\n\nexport function isAppleTerminalSession(): boolean {\n\treturn process.platform === \"darwin\" && process.env.TERM_PROGRAM === \"Apple_Terminal\";\n}\n\nexport function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\tif (isAppleTerminal && data === \"\\r\" && isShiftPressed) return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;\n\treturn data;\n}\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\t/** Optional metadata-only output observations; unsupported terminals omit this. */\n\tgetOutputStats?(): TerminalOutputStats;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n\n\t// Progress indicator (OSC 9;4)\n\tsetProgress(active: boolean): void;\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate _modifyOtherKeysActive = false;\n\tprivate keyboardProtocolPushed = false;\n\tprivate keyboardProtocolNegotiationPending = false;\n\tprivate keyboardProtocolLateResponsePending = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolFallbackTimer?: ReturnType<typeof setTimeout>;\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate readonly output: TerminalOutput;\n\n\tconstructor(output: Writable = process.stdout) {\n\t\tthis.output = new TerminalOutput(output, process.env.OMK_TUI_WRITE_LOG || \"\");\n\t}\n\n\tgetOutputStats(): TerminalOutputStats {\n\t\treturn this.output.snapshot();\n\t}\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = this.output.withResizeLog(onResize, () => ({ cols: this.columns, rows: this.rows }));\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tthis.output.write(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query and enable Kitty keyboard protocol\n\t\t// The query handler intercepts input temporarily, then installs the user's handler\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ timeout: 10 });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\tif (this.keyboardProtocolNegotiationPending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, true);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\treturn; // Wait for the rest of a split negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.keyboardProtocolLateResponsePending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, false);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t\t\treturn; // Wait for the rest of a split late negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.forwardInputSequence(sequence);\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable it if available.\n\t *\n\t * Kitty's progressive enhancement detection requires requesting the desired\n\t * flags before querying them. The trailing DA query is a sentinel supported by\n\t * terminals that do not know Kitty keyboard protocol. A short timeout remains\n\t * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop\n\t * the DA response.\n\t *\n\t * The requested flags are:\n\t * - 1 = disambiguate escape codes\n\t * - 2 = report event types (press/repeat/release)\n\t * - 4 = report alternate keys (shifted key, base layout key)\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tthis.keyboardProtocolPushed = true;\n\t\tthis.keyboardProtocolNegotiationPending = true;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.output.write(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t\tthis.keyboardProtocolFallbackTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\tif (this.keyboardProtocolNegotiationBuffer === \"\\x1b\") {\n\t\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t\t} else {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t}\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}, KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0 && !this._kittyProtocolActive) {\n\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tthis.enableModifyOtherKeys();\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t\tallowBareEscapePrefix: boolean,\n\t): KeyboardProtocolNegotiationSequence | \"pending\" | undefined {\n\t\tif (this.keyboardProtocolNegotiationBuffer) {\n\t\t\tconst bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;\n\t\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);\n\t\t\tif (negotiationSequence) {\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\treturn negotiationSequence;\n\t\t\t}\n\t\t\tif (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence, allowBareEscapePrefix)) {\n\t\t\t\tthis.setKeyboardProtocolNegotiationBuffer(bufferedSequence);\n\t\t\t\treturn \"pending\";\n\t\t\t}\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}\n\n\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);\n\t\tif (negotiationSequence) return negotiationSequence;\n\t\tif (isKeyboardProtocolNegotiationSequencePrefix(sequence, allowBareEscapePrefix)) {\n\t\t\tthis.setKeyboardProtocolNegotiationBuffer(sequence);\n\t\t\treturn \"pending\";\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate setKeyboardProtocolNegotiationBuffer(sequence: string): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = sequence;\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBuffer(): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = \"\";\n\t}\n\n\tprivate flushKeyboardProtocolNegotiationBufferAsInput(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer) return;\n\t\tconst sequence = this.keyboardProtocolNegotiationBuffer;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.forwardInputSequence(sequence);\n\t}\n\n\tprivate scheduleKeyboardProtocolNegotiationBufferFlush(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;\n\t\tthis.keyboardProtocolBufferFlushTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBufferFlushTimer(): void {\n\t\tif (!this.keyboardProtocolBufferFlushTimer) return;\n\t\tclearTimeout(this.keyboardProtocolBufferFlushTimer);\n\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t}\n\n\tprivate forwardInputSequence(sequence: string): void {\n\t\tif (!this.inputHandler) return;\n\t\tconst isAppleTerminal = sequence === \"\\r\" && isAppleTerminalSession();\n\t\tconst input = normalizeAppleTerminalInput(\n\t\t\tsequence,\n\t\t\tisAppleTerminal,\n\t\t\tisAppleTerminal && isNativeModifierPressed(\"shift\"),\n\t\t);\n\t\tthis.inputHandler(input);\n\t}\n\n\tprivate enableModifyOtherKeys(): void {\n\t\tif (this._kittyProtocolActive || this._modifyOtherKeysActive) return;\n\t\tthis.output.write(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate clearKeyboardProtocolFallbackTimer(): void {\n\t\tif (!this.keyboardProtocolFallbackTimer) return;\n\t\tclearTimeout(this.keyboardProtocolFallbackTimer);\n\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\tconst arch = process.arch;\n\t\t\tif (arch !== \"x64\" && arch !== \"arm64\") return;\n\n\t\t\t// Dynamic require so non-Windows and bundled/browser paths never load the\n\t\t\t// native helper. In the npm package native/ is next to dist/; in compiled\n\t\t\t// binary archives native/ is copied next to the executable.\n\t\t\tconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tconst candidates = [\n\t\t\t\tpath.join(moduleDir, \"..\", nativePath),\n\t\t\t\tpath.join(moduleDir, nativePath),\n\t\t\t\tpath.join(path.dirname(process.execPath), nativePath),\n\t\t\t];\n\t\t\tfor (const modulePath of candidates) {\n\t\t\t\ttry {\n\t\t\t\t\tconst helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };\n\t\t\t\t\thelper.enableVirtualTerminalInput?.();\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// Try the next possible packaging location.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Native helper not available — Shift+Tab won't be distinguishable from Tab.\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tthis.output.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tthis.output.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.clearProgressInterval()) {\n\t\t\tthis.output.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tthis.output.write(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tthis.output.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tthis.output.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t}\n\t\tthis.output.stop();\n\t}\n\n\twrite(data: string): void {\n\t\tthis.output.write(data, true);\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || Number(process.env.COLUMNS) || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || Number(process.env.LINES) || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.output.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.output.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\thideCursor(): void {\n\t\tthis.output.write(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tthis.output.write(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tthis.output.write(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tthis.output.write(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tthis.output.write(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\tthis.output.write(`\\x1b]0;${title}\\x07`);\n\t}\n\n\tsetProgress(active: boolean): void {\n\t\tif (active) {\n\t\t\tthis.output.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tthis.output.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\t\t}, TERMINAL_PROGRESS_KEEPALIVE_MS);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.clearProgressInterval();\n\t\t\tthis.output.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\t}\n\n\tprivate clearProgressInterval(): boolean {\n\t\tif (!this.progressInterval) return false;\n\t\tclearInterval(this.progressInterval);\n\t\tthis.progressInterval = undefined;\n\t\treturn true;\n\t}\n}\n"]}
|
package/dist/terminal.js
CHANGED
|
@@ -65,7 +65,7 @@ export class ProcessTerminal {
|
|
|
65
65
|
}
|
|
66
66
|
start(onInput, onResize) {
|
|
67
67
|
this.inputHandler = onInput;
|
|
68
|
-
this.resizeHandler = onResize;
|
|
68
|
+
this.resizeHandler = this.output.withResizeLog(onResize, () => ({ cols: this.columns, rows: this.rows }));
|
|
69
69
|
// Save previous state and enable raw mode
|
|
70
70
|
this.wasRaw = process.stdin.isRaw || false;
|
|
71
71
|
if (process.stdin.setRawMode) {
|