virtual-terminal.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { readFileSync } from 'node:fs';
  2. import { createRequire } from 'node:module';
  3. import { CellFlags, Ghostty, type GhosttyCell, type GhosttyTerminal } from 'ghostty-web';
  4. const require = createRequire(import.meta.url);
  5. const ghosttyModule = new WebAssembly.Module(
  6. readFileSync(require.resolve('ghostty-web/ghostty-vt.wasm')),
  7. );
  8. export class VirtualTerminalScreen {
  9. private readonly terminal: GhosttyTerminal;
  10. constructor(columns = 80, rows = 24, scrollbackBytes = 1024 * 1024) {
  11. const ghostty = new Ghostty(
  12. new WebAssembly.Instance(ghosttyModule, {
  13. env: { log: () => undefined },
  14. }),
  15. );
  16. this.terminal = ghostty.createTerminal(columns, rows, { scrollbackLimit: scrollbackBytes });
  17. }
  18. feed(output: string): void {
  19. this.terminal.write(output);
  20. }
  21. resize(columns: number, rows: number): void {
  22. this.terminal.resize(columns, rows);
  23. }
  24. text(): string {
  25. const lines: string[] = [];
  26. for (let row = 0; row < this.terminal.getScrollbackLength(); row += 1) {
  27. lines.push(cellsToText(this.terminal.getScrollbackLine(row)));
  28. }
  29. for (let row = 0; row < this.terminal.rows; row += 1) {
  30. lines.push(cellsToText(this.terminal.getLine(row)));
  31. }
  32. while (lines.at(-1) === '') lines.pop();
  33. return lines.join('\n');
  34. }
  35. viewportText(): string {
  36. const lines = Array.from({ length: this.terminal.rows }, (_, row) =>
  37. cellsToText(this.terminal.getLine(row)),
  38. );
  39. return lines.join('\n');
  40. }
  41. cursor(): { x: number; y: number; visible: boolean } {
  42. return this.terminal.getCursor();
  43. }
  44. isItalic(row: number, column: number): boolean {
  45. const cell = this.terminal.getLine(row)?.[column];
  46. return Boolean(cell && (cell.flags & CellFlags.ITALIC) !== 0);
  47. }
  48. isUnderline(row: number, column: number): boolean {
  49. const cell = this.terminal.getLine(row)?.[column];
  50. return Boolean(cell && (cell.flags & CellFlags.UNDERLINE) !== 0);
  51. }
  52. backgroundRgb(row: number, column: number): { r: number; g: number; b: number } | undefined {
  53. const cell = this.terminal.getLine(row)?.[column];
  54. return cell ? { r: cell.bg_r, g: cell.bg_g, b: cell.bg_b } : undefined;
  55. }
  56. dispose(): void {
  57. this.terminal.free();
  58. }
  59. }
  60. function cellsToText(cells: GhosttyCell[] | null): string {
  61. if (!cells) return '';
  62. let line = '';
  63. for (const cell of cells) {
  64. if (cell.codepoint === 0) {
  65. if (cell.width > 0) line += ' ';
  66. continue;
  67. }
  68. line += String.fromCodePoint(cell.codepoint);
  69. }
  70. return line.replace(/\s+$/u, '');
  71. }