@h-rig/cli 0.0.6-alpha.85 → 0.0.6-alpha.86

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.
@@ -1300,98 +1300,6 @@ var COLOR = {
1300
1300
  // packages/cli/src/app-opentui/render/graphics.ts
1301
1301
  import { FrameBufferRenderable, RGBA as RGBA4 } from "@opentui/core";
1302
1302
 
1303
- // packages/cli/src/app-opentui/render/ascii-fleet.ts
1304
- var LEAD_DRONE = [
1305
- " .-=-. .-=-. ",
1306
- " ( !!! ) ( !!! ) ",
1307
- " '-=-'._ _.'-=-' ",
1308
- " '._ _.' ",
1309
- " '=$$$$$$$=.' ",
1310
- " =$$$$$$$$$$$= ",
1311
- " $$$@@@@@@@@@@$$$ ",
1312
- " $$$@@ @@$$$ ",
1313
- " $$@ ? @$$$ ",
1314
- " $$$@ '-' @$$$ ",
1315
- " $$$@@ @@$$$ ",
1316
- " $$$@@@@@@@@@@$$$ ",
1317
- " =$$$$$$$$$$$= ",
1318
- " '=$$$$$$$=.' ",
1319
- " _.' '._ ",
1320
- " .-=-.' '.-=-. ",
1321
- " ( !!! ) ( !!! ) ",
1322
- " '-=-' '-=-' "
1323
- ];
1324
- var MINI_DRONE = [
1325
- "(!!!) (!!!)",
1326
- " \\%==%/ ",
1327
- " %%?%% ",
1328
- " /%==%\\ ",
1329
- "(!!!) (!!!)"
1330
- ];
1331
- var ROTORS = ["---", "\\\\\\", "|||", "///"];
1332
- var FLEET_GRID_WIDTH = 52;
1333
- var FLEET_GRID_HEIGHT = 27;
1334
- var FLEET = [
1335
- { art: MINI_DRONE, x: 0, y: 2, amp: 1, speed: 0.05, phase: 0, dx: 1, driftSpeed: 0.02 },
1336
- { art: MINI_DRONE, x: 39, y: 2, amp: 1, speed: 0.044, phase: 2.1, dx: 1, driftSpeed: 0.017 },
1337
- { art: MINI_DRONE, x: 1, y: 20, amp: 1, speed: 0.048, phase: 4.2, dx: 1, driftSpeed: 0.023 },
1338
- { art: MINI_DRONE, x: 38, y: 20, amp: 1, speed: 0.041, phase: 1.3, dx: 1, driftSpeed: 0.015 },
1339
- { art: LEAD_DRONE, x: 10, y: 5, amp: 2, speed: 0.04, phase: 0, dx: 0, driftSpeed: 0.011 }
1340
- ];
1341
- function fleetRows(tick, options = {}) {
1342
- const animate = options.animate ?? true;
1343
- const t2 = animate ? tick : 0;
1344
- const blade = ROTORS[Math.floor(t2 / 4) % ROTORS.length];
1345
- const pulse = Math.sin(t2 * 0.07);
1346
- const eye = pulse > 0.45 ? "@" : pulse > -0.1 ? "o" : ".";
1347
- const grid = Array.from({ length: FLEET_GRID_HEIGHT }, () => Array.from({ length: FLEET_GRID_WIDTH }, () => " "));
1348
- for (const drone of FLEET) {
1349
- const yOffset = drone.y + Math.round(drone.amp * Math.sin(t2 * drone.speed + drone.phase));
1350
- const xOffset = drone.x + Math.round(drone.dx * Math.sin(t2 * drone.driftSpeed + drone.phase));
1351
- for (let row = 0;row < drone.art.length; row += 1) {
1352
- const source = drone.art[row];
1353
- const targetY = yOffset + row;
1354
- if (targetY < 0 || targetY >= FLEET_GRID_HEIGHT)
1355
- continue;
1356
- for (let col = 0;col < source.length; col += 1) {
1357
- let char = source[col];
1358
- if (char === " ")
1359
- continue;
1360
- const targetX = xOffset + col;
1361
- if (targetX < 0 || targetX >= FLEET_GRID_WIDTH)
1362
- continue;
1363
- if (source.slice(col, col + 3) === "!!!") {
1364
- for (let rotorIndex = 0;rotorIndex < 3; rotorIndex += 1) {
1365
- if (targetX + rotorIndex < FLEET_GRID_WIDTH)
1366
- grid[targetY][targetX + rotorIndex] = blade[rotorIndex];
1367
- }
1368
- col += 2;
1369
- continue;
1370
- }
1371
- if (char === "?")
1372
- char = eye;
1373
- grid[targetY][targetX] = char;
1374
- }
1375
- }
1376
- }
1377
- return grid.map((row) => row.join("").replace(/\s+$/, ""));
1378
- }
1379
-
1380
- // packages/cli/src/app-opentui/render/panel-layout.ts
1381
- function panelPixelPlacement(layout, panel, size, minPixels = 8) {
1382
- const cellW = size.width / layout.width;
1383
- const cellH = size.height / layout.height;
1384
- const leftCells = layout.centerLeft + (panel.left ?? 0);
1385
- const topCells = layout.centerTop + panel.top;
1386
- const widthCells = panel.width ?? layout.centerWidth;
1387
- const heightCells = panel.height;
1388
- const left = Math.round(leftCells * cellW);
1389
- const top = Math.round(topCells * cellH);
1390
- const width = Math.round(widthCells * cellW);
1391
- const height = Math.round(heightCells * cellH);
1392
- return width > minPixels && height > minPixels ? { left, top, width, height, leftCells, topCells, widthCells, heightCells } : null;
1393
- }
1394
-
1395
1303
  // packages/cli/src/app-opentui/render/constants.ts
1396
1304
  var LCG_MULTIPLIER = 1664525;
1397
1305
  var LCG_INCREMENT = 1013904223;
@@ -1423,7 +1331,6 @@ var RAIL_YS_LOOP = [0.18, 0.5, 0.82];
1423
1331
  var RAIL_YS_CARRIER = [0.24, 0.54, 0.82];
1424
1332
  var RAIL_YS_DISPATCH = [0.18, 0.58, 0.82];
1425
1333
  var GLOW_FALLOFF_EXP_ASCII = 2.2;
1426
- var GLOW_FALLOFF_EXP_IMAGE = 2.4;
1427
1334
 
1428
1335
  // packages/cli/src/app-opentui/render/graphics.ts
1429
1336
  var BRAILLE_SAMPLES_X = 2;
@@ -1838,952 +1745,6 @@ var ACTIVE_STATUSES = new Set([
1838
1745
  "loading"
1839
1746
  ]);
1840
1747
 
1841
- // packages/cli/src/app-opentui/render/image-visual-layer.ts
1842
- import { Worker } from "worker_threads";
1843
- import { deflateSync } from "zlib";
1844
- import { allocateImageId, deleteKittyImage } from "@earendil-works/pi-tui";
1845
-
1846
- // packages/cli/src/app-opentui/terminal-capabilities.ts
1847
- import { getCapabilities } from "@earendil-works/pi-tui";
1848
- function getRigTerminalCapabilities() {
1849
- const imageProtocol = getCapabilities().images;
1850
- const supportsKittyImages = imageProtocol === "kitty";
1851
- return {
1852
- imageProtocol,
1853
- supportsKittyImages,
1854
- visualMode: supportsKittyImages ? "kitty-images" : "framebuffer-fallback"
1855
- };
1856
- }
1857
-
1858
- // packages/cli/src/app-opentui/render/image-visual-layer.ts
1859
- var PANEL_MASK_RADIUS_MIN = 14;
1860
- var PANEL_MASK_RADIUS_MAX = 34;
1861
- var PANEL_MASK_RADIUS_FACTOR = 0.035;
1862
- var PANEL_BLUR_RADIUS_MIN = 8;
1863
- var PANEL_BLUR_RADIUS_MAX = 28;
1864
- var PANEL_BLUR_RADIUS_FACTOR = 0.018;
1865
- var BG = [7, 8, 9, 255];
1866
- var PANEL = [16, 17, 21, 184];
1867
- var PANEL_HEADER = [16, 17, 21, 190];
1868
- var PANEL_LINE2 = [255, 255, 255, 24];
1869
- var LIME = [204, 255, 77, 255];
1870
- var LIME_DIM = [169, 214, 63, 255];
1871
- var CYAN = [86, 216, 255, 255];
1872
- var MAGENTA = [255, 121, 176, 255];
1873
- var INK_DIM = [108, 110, 121, 255];
1874
- var PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
1875
- var CRC_TABLE = makeCrcTable();
1876
- var MAX_IMAGE_BYTES = 48 * 1024 * 1024;
1877
- var KITTY_CHUNK_SIZE = 4096;
1878
- var PANEL_BLUR_SCALE = 1;
1879
- var PANEL_MASK_CACHE_LIMIT = 16;
1880
- var ZLIB_LEVEL = 1;
1881
- var LOAD_BUCKETS = 5;
1882
- function loadBucket(load) {
1883
- if (!Number.isFinite(load ?? NaN))
1884
- return 0;
1885
- return Math.max(0, Math.min(LOAD_BUCKETS, Math.round((load ?? 0) * LOAD_BUCKETS)));
1886
- }
1887
- var panelMaskCache = new Map;
1888
- var BG_WORD = rgbaWord(BG);
1889
- function imageTransport() {
1890
- const forced = process.env.RIG_OPENTUI_IMAGE_TRANSPORT;
1891
- if (forced === "rgba-zlib")
1892
- return "rgba-zlib";
1893
- return "png";
1894
- }
1895
- function rgbaWord(color) {
1896
- return (color[3] << 24 | color[2] << 16 | color[1] << 8 | color[0]) >>> 0;
1897
- }
1898
- function fillRgba(data, color, word = rgbaWord(color)) {
1899
- if (data.byteOffset % 4 === 0 && data.byteLength % 4 === 0) {
1900
- new Uint32Array(data.buffer, data.byteOffset, data.byteLength / 4).fill(word);
1901
- return;
1902
- }
1903
- for (let i = 0;i < data.length; i += 4) {
1904
- data[i] = color[0];
1905
- data[i + 1] = color[1];
1906
- data[i + 2] = color[2];
1907
- data[i + 3] = color[3];
1908
- }
1909
- }
1910
- var ASCII_GLYPHS = {
1911
- ".": ["00000", "00000", "00000", "00000", "00000", "00100", "00100"],
1912
- "'": ["00100", "00100", "00000", "00000", "00000", "00000", "00000"],
1913
- "-": ["00000", "00000", "00000", "11111", "00000", "00000", "00000"],
1914
- _: ["00000", "00000", "00000", "00000", "00000", "00000", "11111"],
1915
- "=": ["00000", "11111", "00000", "00000", "11111", "00000", "00000"],
1916
- "|": ["00100", "00100", "00100", "00100", "00100", "00100", "00100"],
1917
- "/": ["00001", "00010", "00010", "00100", "01000", "01000", "10000"],
1918
- "\\": ["10000", "01000", "01000", "00100", "00010", "00010", "00001"],
1919
- "(": ["00010", "00100", "01000", "01000", "01000", "00100", "00010"],
1920
- ")": ["01000", "00100", "00010", "00010", "00010", "00100", "01000"],
1921
- "!": ["00100", "00100", "00100", "00100", "00100", "00000", "00100"],
1922
- "%": ["11001", "11010", "00100", "01000", "10110", "00110", "00000"],
1923
- $: ["00100", "11110", "10100", "11110", "00101", "11110", "00100"],
1924
- "@": ["01110", "10001", "10111", "10101", "10111", "10000", "01111"],
1925
- o: ["00000", "01110", "10001", "10001", "10001", "01110", "00000"],
1926
- "*": ["00100", "10101", "01110", "11111", "01110", "10101", "00100"]
1927
- };
1928
- function sceneStaticTick(scene) {
1929
- let hash = 0;
1930
- for (let index = 0;index < scene.length; index += 1)
1931
- hash = hash * 33 + scene.charCodeAt(index) >>> 0;
1932
- return 11 + hash % 97;
1933
- }
1934
- function charColor(char, row, totalRows) {
1935
- if (char === "@" || char === "$" || char === "o")
1936
- return LIME;
1937
- if (char === "%" || char === "!" || char === "/" || char === "\\" || char === "|")
1938
- return CYAN;
1939
- if (char === "." || char === "'" || char === "_" || row < 3 || row > totalRows - 4)
1940
- return INK_DIM;
1941
- if (char === "-" || char === "=" || char === "(" || char === ")")
1942
- return LIME_DIM;
1943
- return MAGENTA;
1944
- }
1945
- function fillRectAlpha(data, width, height, left, top, rectWidth, rectHeight, color, alpha) {
1946
- const x0 = Math.max(0, Math.floor(left));
1947
- const y0 = Math.max(0, Math.floor(top));
1948
- const x1 = Math.min(width, Math.ceil(left + rectWidth));
1949
- const y1 = Math.min(height, Math.ceil(top + rectHeight));
1950
- for (let y = y0;y < y1; y += 1) {
1951
- for (let x = x0;x < x1; x += 1)
1952
- blendOver(data, (y * width + x) * 4, color, alpha);
1953
- }
1954
- }
1955
- function drawAsciiGlyph(data, width, height, x, y, cellWidth, cellHeight, char, color, alpha) {
1956
- const pattern = ASCII_GLYPHS[char] ?? ASCII_GLYPHS["*"];
1957
- const glyphWidth = Math.max(1, cellWidth * 0.56);
1958
- const glyphHeight = Math.max(1, cellHeight * 0.7);
1959
- const originX = x + (cellWidth - glyphWidth) * 0.5;
1960
- const originY = y + (cellHeight - glyphHeight) * 0.5;
1961
- const pixelWidth = Math.max(1, glyphWidth / pattern[0].length);
1962
- const pixelHeight = Math.max(1, glyphHeight / pattern.length);
1963
- for (let row = 0;row < pattern.length; row += 1) {
1964
- const bits = pattern[row];
1965
- for (let col = 0;col < bits.length; col += 1) {
1966
- if (bits[col] !== "1")
1967
- continue;
1968
- fillRectAlpha(data, width, height, originX + col * pixelWidth, originY + row * pixelHeight, pixelWidth * 0.72, pixelHeight * 0.72, color, alpha);
1969
- }
1970
- }
1971
- }
1972
- function drawStaticAsciiFleetBackground(data, width, height, scene, layout, load, activeRuns) {
1973
- const rows = fleetRows(sceneStaticTick(scene), { animate: true });
1974
- const cellWidth = width / Math.max(1, layout.width);
1975
- const cellHeight = height / Math.max(1, layout.height);
1976
- const sideBySide = layout.width >= FLEET_GRID_WIDTH * 1.9;
1977
- const leftCells = sideBySide ? Math.max(1, Math.floor(layout.width * 0.3 - FLEET_GRID_WIDTH / 2)) : Math.floor((layout.width - FLEET_GRID_WIDTH) / 2);
1978
- const topCells = Math.floor((layout.height - FLEET_GRID_HEIGHT) / 2);
1979
- const fleetLeft = leftCells * cellWidth;
1980
- const fleetTop = topCells * cellHeight;
1981
- drawGlow2(data, width, height, width * 0.5, height * 0.5, Math.min(width, height) * 0.4, LIME, 0.022 + load * 0.03);
1982
- drawGlow2(data, width, height, width * 0.18, height * 0.22, Math.min(width, height) * 0.28, CYAN, 0.018 + load * 0.012);
1983
- drawGlow2(data, width, height, width * 0.82, height * 0.78, Math.min(width, height) * 0.22, MAGENTA, 0.012 + load * 0.008);
1984
- let droneTotal = 0;
1985
- for (const line2 of rows)
1986
- for (const char of line2)
1987
- if (char === "@" || char === "$" || char === "%")
1988
- droneTotal += 1;
1989
- const litTarget = Math.max(0, Math.min(droneTotal, activeRuns));
1990
- let droneIndex = 0;
1991
- for (let row = 0;row < rows.length; row += 1) {
1992
- const line2 = rows[row];
1993
- for (let col = 0;col < line2.length; col += 1) {
1994
- const char = line2[col];
1995
- if (char === " ")
1996
- continue;
1997
- const x = fleetLeft + col * cellWidth;
1998
- const y = fleetTop + row * cellHeight;
1999
- const color = charColor(char, row, rows.length);
2000
- const isDrone = char === "@" || char === "$" || char === "%";
2001
- const lit = isDrone && droneIndex < litTarget;
2002
- drawAsciiGlyph(data, width, height, x + cellWidth * 0.07, y + cellHeight * 0.05, cellWidth, cellHeight, char, color, lit ? 0.72 : 0.46);
2003
- if (isDrone) {
2004
- droneIndex += 1;
2005
- drawGlow2(data, width, height, x + cellWidth * 0.5, y + cellHeight * 0.5, Math.max(cellWidth, cellHeight) * 0.95, color, lit ? 0.044 : 0.014);
2006
- }
2007
- }
2008
- }
2009
- }
2010
- function applyStaticAtmosphere(data, width, height, load) {
2011
- const cx = width * 0.5;
2012
- const cy = height * 0.42;
2013
- const radius = Math.max(width, height) * 0.78;
2014
- const minVignette = 0.1 - load * 0.02;
2015
- for (let y = 0;y < height; y += 1) {
2016
- for (let x = 0;x < width; x += 1) {
2017
- const distance = Math.hypot(x - cx, y - cy) / radius;
2018
- const alpha = Math.max(minVignette, Math.min(0.82, 0.12 + Math.pow(distance, 1.65) * 0.62));
2019
- blendOver(data, (y * width + x) * 4, BG, alpha);
2020
- }
2021
- }
2022
- drawGlow2(data, width, height, width * 0.82, height * 0.04, Math.min(width, height) * 0.2, LIME, 0.024 + load * 0.012);
2023
- drawGlow2(data, width, height, width * 0.12, height * 0.18, Math.min(width, height) * 0.16, CYAN, 0.018 + load * 0.008);
2024
- }
2025
- function makeCrcTable() {
2026
- const table = new Uint32Array(256);
2027
- for (let n = 0;n < 256; n += 1) {
2028
- let c = n;
2029
- for (let k = 0;k < 8; k += 1)
2030
- c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
2031
- table[n] = c >>> 0;
2032
- }
2033
- return table;
2034
- }
2035
- function crc32(bytes) {
2036
- let c = 4294967295;
2037
- for (let i = 0;i < bytes.length; i += 1)
2038
- c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ c >>> 8;
2039
- return (c ^ 4294967295) >>> 0;
2040
- }
2041
- function chunk(type, data) {
2042
- const out = new Uint8Array(12 + data.length);
2043
- const view = new DataView(out.buffer);
2044
- view.setUint32(0, data.length);
2045
- out[4] = type.charCodeAt(0);
2046
- out[5] = type.charCodeAt(1);
2047
- out[6] = type.charCodeAt(2);
2048
- out[7] = type.charCodeAt(3);
2049
- out.set(data, 8);
2050
- view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
2051
- return out;
2052
- }
2053
- function encodePng(width, height, rgba) {
2054
- const ihdr = new Uint8Array(13);
2055
- const ihdrView = new DataView(ihdr.buffer);
2056
- ihdrView.setUint32(0, width);
2057
- ihdrView.setUint32(4, height);
2058
- ihdr[8] = 8;
2059
- ihdr[9] = 6;
2060
- ihdr[10] = 0;
2061
- ihdr[11] = 0;
2062
- ihdr[12] = 0;
2063
- const stride = width * 4;
2064
- const raw = new Uint8Array((stride + 1) * height);
2065
- for (let y = 0;y < height; y += 1) {
2066
- const rawOffset = y * (stride + 1);
2067
- raw[rawOffset] = 0;
2068
- raw.set(rgba.subarray(y * stride, y * stride + stride), rawOffset + 1);
2069
- }
2070
- const compressed = deflateSync(raw, { level: ZLIB_LEVEL });
2071
- return Buffer.concat([
2072
- Buffer.from(PNG_SIGNATURE),
2073
- Buffer.from(chunk("IHDR", ihdr)),
2074
- Buffer.from(chunk("IDAT", compressed)),
2075
- Buffer.from(chunk("IEND", new Uint8Array(0)))
2076
- ]);
2077
- }
2078
- function kittyImageSequence(base64, options) {
2079
- const params = [`a=T`, `f=${options.format}`, `q=2`, `C=1`, `c=${options.columns}`, `r=${options.rows}`, `i=${options.imageId}`, `z=${options.zIndex}`];
2080
- if (options.format === 32) {
2081
- params.push(`s=${options.pixelWidth ?? 1}`, `v=${options.pixelHeight ?? 1}`);
2082
- if (options.compressed)
2083
- params.push("o=z");
2084
- }
2085
- if (base64.length <= KITTY_CHUNK_SIZE)
2086
- return `\x1B_G${params.join(",")};${base64}\x1B\\`;
2087
- const chunks = [];
2088
- for (let offset = 0;offset < base64.length; offset += KITTY_CHUNK_SIZE) {
2089
- const part = base64.slice(offset, offset + KITTY_CHUNK_SIZE);
2090
- const last = offset + KITTY_CHUNK_SIZE >= base64.length;
2091
- chunks.push(`\x1B_G${offset === 0 ? `${params.join(",")},` : ""}m=${last ? 0 : 1};${part}\x1B\\`);
2092
- }
2093
- return chunks.join("");
2094
- }
2095
- function clampByte(value) {
2096
- return Math.max(0, Math.min(255, Math.round(value)));
2097
- }
2098
- function blendOver(data, index, color, alphaScale = 1) {
2099
- const alpha = color[3] / 255 * alphaScale;
2100
- const inv = 1 - alpha;
2101
- data[index] = clampByte(color[0] * alpha + data[index] * inv);
2102
- data[index + 1] = clampByte(color[1] * alpha + data[index + 1] * inv);
2103
- data[index + 2] = clampByte(color[2] * alpha + data[index + 2] * inv);
2104
- data[index + 3] = 255;
2105
- }
2106
- function drawDisc(data, width, height, cx, cy, radius, color, alpha = 1) {
2107
- const minX = Math.max(0, Math.floor(cx - radius));
2108
- const maxX = Math.min(width - 1, Math.ceil(cx + radius));
2109
- const minY = Math.max(0, Math.floor(cy - radius));
2110
- const maxY = Math.min(height - 1, Math.ceil(cy + radius));
2111
- for (let y = minY;y <= maxY; y += 1) {
2112
- for (let x = minX;x <= maxX; x += 1) {
2113
- const dx = x + 0.5 - cx;
2114
- const dy = y + 0.5 - cy;
2115
- const d = Math.sqrt(dx * dx + dy * dy);
2116
- if (d > radius)
2117
- continue;
2118
- const edge = Math.max(0, Math.min(1, radius - d));
2119
- blendOver(data, (y * width + x) * 4, color, alpha * Math.min(1, 0.35 + edge));
2120
- }
2121
- }
2122
- }
2123
- function drawGlow2(data, width, height, cx, cy, radius, color, alpha = 0.18) {
2124
- const minX = Math.max(0, Math.floor(cx - radius));
2125
- const maxX = Math.min(width - 1, Math.ceil(cx + radius));
2126
- const minY = Math.max(0, Math.floor(cy - radius));
2127
- const maxY = Math.min(height - 1, Math.ceil(cy + radius));
2128
- for (let y = minY;y <= maxY; y += 1) {
2129
- for (let x = minX;x <= maxX; x += 1) {
2130
- const dx = x + 0.5 - cx;
2131
- const dy = y + 0.5 - cy;
2132
- const d = Math.sqrt(dx * dx + dy * dy);
2133
- if (d > radius)
2134
- continue;
2135
- const falloff = Math.pow(1 - d / Math.max(1, radius), GLOW_FALLOFF_EXP_IMAGE);
2136
- blendOver(data, (y * width + x) * 4, color, alpha * falloff);
2137
- }
2138
- }
2139
- }
2140
- function drawLine2(data, width, height, x0, y0, x1, y1, color, alpha = 0.5, thickness = 1.4) {
2141
- const dx = x1 - x0;
2142
- const dy = y1 - y0;
2143
- const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) * 1.2));
2144
- for (let i = 0;i <= steps; i += 1) {
2145
- const t2 = i / steps;
2146
- drawDisc(data, width, height, x0 + dx * t2, y0 + dy * t2, thickness, color, alpha);
2147
- }
2148
- }
2149
- function roundRectAlpha(px, py, x, y, w, h, r) {
2150
- const rx = Math.max(x + r, Math.min(px, x + w - r));
2151
- const ry = Math.max(y + r, Math.min(py, y + h - r));
2152
- const dx = px - rx;
2153
- const dy = py - ry;
2154
- const dist = Math.sqrt(dx * dx + dy * dy);
2155
- return Math.max(0, Math.min(1, r + 0.75 - dist));
2156
- }
2157
- function panelRect(layout, panel, size) {
2158
- return panelPixelPlacement(layout, panel, size);
2159
- }
2160
- function downsampleRegion(data, canvasW, canvasH, rect, scale) {
2161
- const w = Math.max(1, Math.ceil(rect.width / scale));
2162
- const h = Math.max(1, Math.ceil(rect.height / scale));
2163
- const out = new Uint8ClampedArray(w * h * 3);
2164
- for (let y = 0;y < h; y += 1) {
2165
- for (let x = 0;x < w; x += 1) {
2166
- let r = 0, g = 0, b = 0, count = 0;
2167
- const sx0 = rect.left + x * scale;
2168
- const sy0 = rect.top + y * scale;
2169
- for (let yy = 0;yy < scale; yy += 1) {
2170
- const sy = sy0 + yy;
2171
- if (sy < 0 || sy >= canvasH)
2172
- continue;
2173
- for (let xx = 0;xx < scale; xx += 1) {
2174
- const sx = sx0 + xx;
2175
- if (sx < 0 || sx >= canvasW)
2176
- continue;
2177
- const i = (sy * canvasW + sx) * 4;
2178
- r += data[i];
2179
- g += data[i + 1];
2180
- b += data[i + 2];
2181
- count += 1;
2182
- }
2183
- }
2184
- const oi = (y * w + x) * 3;
2185
- out[oi] = count ? r / count : BG[0];
2186
- out[oi + 1] = count ? g / count : BG[1];
2187
- out[oi + 2] = count ? b / count : BG[2];
2188
- }
2189
- }
2190
- return { pixels: out, width: w, height: h };
2191
- }
2192
- function blurRgb(buffer, width, height, radius) {
2193
- const tmp = new Uint8ClampedArray(buffer.length);
2194
- const out = new Uint8ClampedArray(buffer.length);
2195
- const window = radius * 2 + 1;
2196
- for (let y = 0;y < height; y += 1) {
2197
- let r = 0, g = 0, b = 0;
2198
- for (let x = -radius;x <= radius; x += 1) {
2199
- const sx = Math.max(0, Math.min(width - 1, x));
2200
- const i = (y * width + sx) * 3;
2201
- r += buffer[i];
2202
- g += buffer[i + 1];
2203
- b += buffer[i + 2];
2204
- }
2205
- for (let x = 0;x < width; x += 1) {
2206
- const oi = (y * width + x) * 3;
2207
- tmp[oi] = r / window;
2208
- tmp[oi + 1] = g / window;
2209
- tmp[oi + 2] = b / window;
2210
- const removeX = Math.max(0, x - radius);
2211
- const addX = Math.min(width - 1, x + radius + 1);
2212
- const ri = (y * width + removeX) * 3;
2213
- const ai = (y * width + addX) * 3;
2214
- r += tmp.length ? buffer[ai] - buffer[ri] : 0;
2215
- g += tmp.length ? buffer[ai + 1] - buffer[ri + 1] : 0;
2216
- b += tmp.length ? buffer[ai + 2] - buffer[ri + 2] : 0;
2217
- }
2218
- }
2219
- for (let x = 0;x < width; x += 1) {
2220
- let r = 0, g = 0, b = 0;
2221
- for (let y = -radius;y <= radius; y += 1) {
2222
- const sy = Math.max(0, Math.min(height - 1, y));
2223
- const i = (sy * width + x) * 3;
2224
- r += tmp[i];
2225
- g += tmp[i + 1];
2226
- b += tmp[i + 2];
2227
- }
2228
- for (let y = 0;y < height; y += 1) {
2229
- const oi = (y * width + x) * 3;
2230
- out[oi] = r / window;
2231
- out[oi + 1] = g / window;
2232
- out[oi + 2] = b / window;
2233
- const removeY = Math.max(0, y - radius);
2234
- const addY = Math.min(height - 1, y + radius + 1);
2235
- const ri = (removeY * width + x) * 3;
2236
- const ai = (addY * width + x) * 3;
2237
- r += tmp[ai] - tmp[ri];
2238
- g += tmp[ai + 1] - tmp[ri + 1];
2239
- b += tmp[ai + 2] - tmp[ri + 2];
2240
- }
2241
- }
2242
- return out;
2243
- }
2244
- function panelMaskKey(width, height, rect, headerPx, blurScale) {
2245
- return `${width}x${height}:${rect.left},${rect.top},${rect.width},${rect.height}:${Math.round(headerPx * 100) / 100}:${blurScale}`;
2246
- }
2247
- function getPanelMask(width, height, rect, headerPx, blurScale) {
2248
- const key = panelMaskKey(width, height, rect, headerPx, blurScale);
2249
- const cached = panelMaskCache.get(key);
2250
- if (cached)
2251
- return cached;
2252
- const radius = Math.max(PANEL_MASK_RADIUS_MIN, Math.min(PANEL_MASK_RADIUS_MAX, Math.round(Math.min(rect.width, rect.height) * PANEL_MASK_RADIUS_FACTOR)));
2253
- const sampledWidth = Math.max(1, Math.ceil(rect.width / blurScale));
2254
- const sampledHeight = Math.max(1, Math.ceil(rect.height / blurScale));
2255
- const x0 = Math.max(0, rect.left);
2256
- const y0 = Math.max(0, rect.top);
2257
- const x1 = Math.min(width - 1, rect.left + rect.width - 1);
2258
- const y1 = Math.min(height - 1, rect.top + rect.height - 1);
2259
- const indices = [];
2260
- const sampleIndices = [];
2261
- const panelAlpha = [];
2262
- const edgeAlpha = [];
2263
- const headerFlags = [];
2264
- const dividerIndices = [];
2265
- for (let y = y0;y <= y1; y += 1) {
2266
- for (let x = x0;x <= x1; x += 1) {
2267
- const a = roundRectAlpha(x + 0.5, y + 0.5, rect.left, rect.top, rect.width, rect.height, radius);
2268
- if (a <= 0)
2269
- continue;
2270
- const edge = roundRectAlpha(x + 0.5, y + 0.5, rect.left + 1.2, rect.top + 1.2, rect.width - 2.4, rect.height - 2.4, Math.max(1, radius - 1.2));
2271
- const sx = Math.max(0, Math.min(sampledWidth - 1, Math.floor((x - rect.left) / blurScale)));
2272
- const sy = Math.max(0, Math.min(sampledHeight - 1, Math.floor((y - rect.top) / blurScale)));
2273
- indices.push((y * width + x) * 4);
2274
- sampleIndices.push((sy * sampledWidth + sx) * 3);
2275
- panelAlpha.push(a);
2276
- edgeAlpha.push(edge < 0.96 ? Math.min(1, (1 - edge) * 0.7) : 0);
2277
- headerFlags.push(y < rect.top + headerPx ? 1 : 0);
2278
- }
2279
- }
2280
- const dividerY = Math.round(rect.top + headerPx);
2281
- if (dividerY > y0 && dividerY < y1) {
2282
- for (let x = x0 + radius;x <= x1 - radius; x += 1) {
2283
- dividerIndices.push((dividerY * width + x) * 4);
2284
- }
2285
- }
2286
- const mask = {
2287
- key,
2288
- indices: Uint32Array.from(indices),
2289
- sampleIndices: Uint32Array.from(sampleIndices),
2290
- panelAlpha: Float32Array.from(panelAlpha),
2291
- edgeAlpha: Float32Array.from(edgeAlpha),
2292
- headerFlags: Uint8Array.from(headerFlags),
2293
- dividerIndices: Uint32Array.from(dividerIndices)
2294
- };
2295
- panelMaskCache.set(key, mask);
2296
- while (panelMaskCache.size > PANEL_MASK_CACHE_LIMIT) {
2297
- const oldest = panelMaskCache.keys().next().value;
2298
- if (!oldest)
2299
- break;
2300
- panelMaskCache.delete(oldest);
2301
- }
2302
- return mask;
2303
- }
2304
- function compositePanel(data, width, height, rect, headerPx) {
2305
- const blurScale = PANEL_BLUR_SCALE;
2306
- const sampled = downsampleRegion(data, width, height, rect, blurScale);
2307
- const blurRadius = Math.max(PANEL_BLUR_RADIUS_MIN, Math.min(PANEL_BLUR_RADIUS_MAX, Math.round(Math.min(rect.width, rect.height) * PANEL_BLUR_RADIUS_FACTOR)));
2308
- const blurred = blurRgb(sampled.pixels, sampled.width, sampled.height, blurRadius);
2309
- const mask = getPanelMask(width, height, rect, headerPx, blurScale);
2310
- for (let i = 0;i < mask.indices.length; i += 1) {
2311
- const idx = mask.indices[i];
2312
- const sampleIdx = mask.sampleIndices[i];
2313
- data[idx] = blurred[sampleIdx];
2314
- data[idx + 1] = blurred[sampleIdx + 1];
2315
- data[idx + 2] = blurred[sampleIdx + 2];
2316
- data[idx + 3] = 255;
2317
- blendOver(data, idx, mask.headerFlags[i] ? PANEL_HEADER : PANEL, mask.panelAlpha[i]);
2318
- const edge = mask.edgeAlpha[i];
2319
- if (edge > 0)
2320
- blendOver(data, idx, PANEL_LINE2, edge);
2321
- }
2322
- for (let i = 0;i < mask.dividerIndices.length; i += 1) {
2323
- blendOver(data, mask.dividerIndices[i], PANEL_LINE2, 0.28);
2324
- }
2325
- }
2326
- var RIG_GLYPH_STROKES = {
2327
- R: [[0, 0, 0, 1], [0, 0, 0.82, 0], [0.82, 0, 0.82, 0.5], [0, 0.5, 0.82, 0.5], [0.36, 0.5, 0.92, 1]],
2328
- I: [[0.5, 0, 0.5, 1], [0.18, 0, 0.82, 0], [0.18, 1, 0.82, 1]],
2329
- G: [[0.92, 0.08, 0.12, 0], [0.12, 0, 0.12, 1], [0.12, 1, 0.92, 1], [0.92, 0.5, 0.92, 1], [0.5, 0.5, 0.92, 0.5]]
2330
- };
2331
- function drawBigRigWordmark(data, width, height, layout, load) {
2332
- const sideBySide = layout.width >= FLEET_GRID_WIDTH * 1.9;
2333
- if (!sideBySide)
2334
- return;
2335
- const letters = "RIG";
2336
- const min = Math.min(width, height);
2337
- const glyphH = height * 0.42;
2338
- const glyphW = width * 0.13;
2339
- const gap = glyphW * 0.3;
2340
- const totalW = letters.length * glyphW + (letters.length - 1) * gap;
2341
- const centerX = width * 0.71;
2342
- const startX = centerX - totalW / 2;
2343
- const top = (height - glyphH) / 2;
2344
- const stroke = Math.max(2, min * 0.013);
2345
- drawGlow2(data, width, height, centerX, top + glyphH / 2, Math.max(glyphW, glyphH) * 0.9, LIME, 0.022 + load * 0.02);
2346
- const strokeAlpha = 0.1 + load * 0.06;
2347
- letters.split("").forEach((letter, index) => {
2348
- const segments = RIG_GLYPH_STROKES[letter];
2349
- if (!segments)
2350
- return;
2351
- const ox = startX + index * (glyphW + gap);
2352
- for (const [x0, y0, x1, y1] of segments) {
2353
- drawLine2(data, width, height, ox + x0 * glyphW, top + y0 * glyphH, ox + x1 * glyphW, top + y1 * glyphH, LIME_DIM, strokeAlpha, stroke);
2354
- }
2355
- });
2356
- }
2357
- function drawBackground(data, width, height, _tick, scene, layout, load, activeRuns) {
2358
- fillRgba(data, BG, BG_WORD);
2359
- drawStaticAsciiFleetBackground(data, width, height, scene, layout, load, activeRuns);
2360
- drawBigRigWordmark(data, width, height, layout, load);
2361
- applyStaticAtmosphere(data, width, height, load);
2362
- }
2363
- function imageVisualFrameKey(input) {
2364
- const width = Math.max(1, Math.floor(input.pixelSize.width));
2365
- const height = Math.max(1, Math.floor(input.pixelSize.height));
2366
- const layer = "layer" in input ? input.layer ?? "full" : "full";
2367
- const load = loadBucket(input.load);
2368
- return `${layer}:${width}x${height}:${input.layout.width}x${input.layout.height}:${input.scene}:${input.tick}:l${load}:${input.panels.map((panel) => `${panel.id}:${panel.top}:${panel.height}:${panel.width ?? ""}:${panel.left ?? ""}:${panel.headerHeight ?? ""}`).join("|")}`;
2369
- }
2370
- function encodeKittyFrame(width, height, data, input) {
2371
- if (input.transport === "png") {
2372
- const png = encodePng(width, height, data);
2373
- return kittyImageSequence(png.toString("base64"), { columns: input.layout.width, rows: input.layout.height, imageId: input.imageId, zIndex: input.zIndex, format: 100 });
2374
- }
2375
- const compressed = deflateSync(data, { level: ZLIB_LEVEL });
2376
- return kittyImageSequence(compressed.toString("base64"), {
2377
- columns: input.layout.width,
2378
- rows: input.layout.height,
2379
- imageId: input.imageId,
2380
- zIndex: input.zIndex,
2381
- format: 32,
2382
- pixelWidth: width,
2383
- pixelHeight: height,
2384
- compressed: true
2385
- });
2386
- }
2387
- function cropRgba(data, sourceWidth, rect) {
2388
- const out = new Uint8ClampedArray(rect.width * rect.height * 4);
2389
- for (let y = 0;y < rect.height; y += 1) {
2390
- const sourceStart = ((rect.top + y) * sourceWidth + rect.left) * 4;
2391
- out.set(data.subarray(sourceStart, sourceStart + rect.width * 4), y * rect.width * 4);
2392
- }
2393
- return out;
2394
- }
2395
- function encodePanelPatch(data, sourceWidth, placement, imageId, zIndex) {
2396
- const patch = cropRgba(data, sourceWidth, placement);
2397
- const png = encodePng(placement.width, placement.height, patch);
2398
- const sequence = kittyImageSequence(png.toString("base64"), {
2399
- columns: Math.max(1, Math.round(placement.widthCells)),
2400
- rows: Math.max(1, Math.round(placement.heightCells)),
2401
- imageId,
2402
- zIndex,
2403
- format: 100
2404
- });
2405
- return `\x1B[${Math.max(1, Math.round(placement.topCells) + 1)};${Math.max(1, Math.round(placement.leftCells) + 1)}H${sequence}`;
2406
- }
2407
- function renderImageVisualFrame(input) {
2408
- const width = Math.max(1, Math.floor(input.pixelSize.width));
2409
- const height = Math.max(1, Math.floor(input.pixelSize.height));
2410
- const byteCount = width * height * 4;
2411
- if (byteCount > MAX_IMAGE_BYTES)
2412
- return null;
2413
- const layer = input.layer ?? "full";
2414
- const data = new Uint8ClampedArray(byteCount);
2415
- const load = loadBucket(input.load) / LOAD_BUCKETS;
2416
- const activeRuns = Math.max(0, Math.floor(input.activeRuns ?? 0));
2417
- drawBackground(data, width, height, 0, input.scene, input.layout, load, activeRuns);
2418
- if (layer === "split") {
2419
- const sequences = [encodeKittyFrame(width, height, data, input)];
2420
- let panelIndex = 0;
2421
- for (const panel of input.panels) {
2422
- if (panel.chrome !== "ad-terminal")
2423
- continue;
2424
- const placement = panelPixelPlacement(input.layout, panel, { width, height });
2425
- if (!placement)
2426
- continue;
2427
- const cellH = height / input.layout.height;
2428
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
2429
- compositePanel(data, width, height, placement, headerPx);
2430
- const imageId = input.imageIds?.[panelIndex] ?? (input.imageId + 1000 + panelIndex >>> 0 || panelIndex + 1);
2431
- sequences.push(encodePanelPatch(data, width, placement, imageId, -12));
2432
- panelIndex += 1;
2433
- }
2434
- return { key: imageVisualFrameKey(input), sequence: sequences.join("") };
2435
- }
2436
- if (layer === "panel-chrome")
2437
- return { key: imageVisualFrameKey(input), sequence: "" };
2438
- if (layer === "background") {
2439
- return { key: imageVisualFrameKey(input), sequence: encodeKittyFrame(width, height, data, input) };
2440
- }
2441
- if (layer === "panel-patches") {
2442
- const sequences = [];
2443
- let panelIndex = 0;
2444
- for (const panel of input.panels) {
2445
- if (panel.chrome !== "ad-terminal")
2446
- continue;
2447
- const placement = panelPixelPlacement(input.layout, panel, { width, height });
2448
- if (!placement)
2449
- continue;
2450
- const cellH = height / input.layout.height;
2451
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
2452
- compositePanel(data, width, height, placement, headerPx);
2453
- const imageId = input.imageIds?.[panelIndex] ?? (input.imageId + 1000 + panelIndex >>> 0 || panelIndex + 1);
2454
- sequences.push(encodePanelPatch(data, width, placement, imageId, input.zIndex));
2455
- panelIndex += 1;
2456
- }
2457
- return { key: imageVisualFrameKey(input), sequence: sequences.join("") };
2458
- }
2459
- for (const panel of input.panels) {
2460
- if (panel.chrome !== "ad-terminal")
2461
- continue;
2462
- const rect = panelRect(input.layout, panel, { width, height });
2463
- if (!rect)
2464
- continue;
2465
- const cellH = height / input.layout.height;
2466
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
2467
- compositePanel(data, width, height, rect, headerPx);
2468
- }
2469
- return { key: imageVisualFrameKey(input), sequence: encodeKittyFrame(width, height, data, input) };
2470
- }
2471
- function shouldRenderImagesInline() {
2472
- return process.env.RIG_OPENTUI_IMAGE_WORKER === "0" || import.meta.url.includes("$bunfs");
2473
- }
2474
- function createImageWorker() {
2475
- if (shouldRenderImagesInline())
2476
- return null;
2477
- const isTypeScriptRuntime = import.meta.url.endsWith(".ts");
2478
- const workerUrl = new URL(isTypeScriptRuntime ? "./image-visual-layer-worker.ts" : "./image-visual-layer-worker.js", import.meta.url);
2479
- try {
2480
- return new Worker(workerUrl);
2481
- } catch {
2482
- if (typeof process.versions.bun === "string") {
2483
- try {
2484
- return new Worker("./src/app-opentui/render/image-visual-layer-worker.ts");
2485
- } catch {}
2486
- }
2487
- return null;
2488
- }
2489
- }
2490
- var RECENT_WRITTEN_LIMIT = 24;
2491
- var DEFAULT_IMAGE_OUTPUT_BACKLOG_BYTES = 256 * 1024;
2492
- var DEFAULT_IMAGE_OUTPUT_BYTES_PER_SECOND = 850 * 1024;
2493
- function imageOutputBacklogBytes() {
2494
- const raw = Number.parseInt(process.env.RIG_OPENTUI_IMAGE_BACKLOG_BYTES ?? "", 10);
2495
- if (Number.isFinite(raw) && raw > 0)
2496
- return Math.max(64 * 1024, Math.min(2 * 1024 * 1024, raw));
2497
- return DEFAULT_IMAGE_OUTPUT_BACKLOG_BYTES;
2498
- }
2499
- function imageOutputBytesPerSecond() {
2500
- const raw = Number.parseInt(process.env.RIG_OPENTUI_IMAGE_BYTES_PER_SECOND ?? "", 10);
2501
- if (Number.isFinite(raw) && raw > 0)
2502
- return Math.max(128 * 1024, Math.min(2 * 1024 * 1024, raw));
2503
- return DEFAULT_IMAGE_OUTPUT_BYTES_PER_SECOND;
2504
- }
2505
- function pendingLayerKey(key) {
2506
- return key.split(":", 1)[0] || "full";
2507
- }
2508
-
2509
- class ImageVisualLayer {
2510
- imageId = allocateImageId();
2511
- panelImageIds = Array.from({ length: 8 }, () => allocateImageId());
2512
- panelChromeImageIds = Array.from({ length: 8 }, () => allocateImageId());
2513
- stdout;
2514
- onFrameReady;
2515
- protocol;
2516
- transport = imageTransport();
2517
- maxOutputBacklogBytes = imageOutputBacklogBytes();
2518
- outputBytesPerSecond = imageOutputBytesPerSecond();
2519
- outputBudgetBytes = imageOutputBytesPerSecond();
2520
- lastBudgetAtMs = Date.now();
2521
- motionSlot = this.createSlot();
2522
- workersStarted = false;
2523
- pendingFrames = new Map;
2524
- recentWrittenKeys = [];
2525
- imagesVisible = false;
2526
- flushPaused = false;
2527
- requestId = 0;
2528
- lastBackgroundKey = "";
2529
- fatalWorkerError = null;
2530
- destroyed = false;
2531
- constructor(stdout = process.stdout, onFrameReady) {
2532
- this.stdout = stdout;
2533
- this.onFrameReady = onFrameReady;
2534
- this.protocol = getRigTerminalCapabilities().imageProtocol;
2535
- }
2536
- get enabled() {
2537
- return this.protocol === "kitty";
2538
- }
2539
- clear() {
2540
- if (this.enabled) {
2541
- if (this.imagesVisible)
2542
- this.stdout.write([this.imageId, ...this.panelImageIds, ...this.panelChromeImageIds].map((id) => deleteKittyImage(id)).join("") + "\x1B[?25h");
2543
- this.imagesVisible = false;
2544
- this.pendingFrames.clear();
2545
- this.recentWrittenKeys.length = 0;
2546
- this.resetSlot(this.motionSlot);
2547
- this.lastBackgroundKey = "";
2548
- this.outputBudgetBytes = this.outputBytesPerSecond;
2549
- this.lastBudgetAtMs = Date.now();
2550
- this.motionSlot.clearedThroughRequestId = this.requestId;
2551
- }
2552
- }
2553
- destroy() {
2554
- if (this.destroyed)
2555
- return;
2556
- this.clear();
2557
- this.destroyed = true;
2558
- const workers = [this.motionSlot.worker];
2559
- this.motionSlot.worker = null;
2560
- for (const worker of workers)
2561
- if (worker)
2562
- worker.terminate().catch(() => {
2563
- return;
2564
- });
2565
- }
2566
- setFlushPaused(paused) {
2567
- this.flushPaused = paused;
2568
- }
2569
- isReady(input) {
2570
- if (!this.enabled || this.destroyed)
2571
- return true;
2572
- this.throwIfFatal();
2573
- const splitKey = imageVisualFrameKey({ ...input, tick: 0, layer: "split" });
2574
- return this.recentWrittenKeys.includes(splitKey) || Array.from(this.pendingFrames.values()).some((frame) => frame.key === splitKey);
2575
- }
2576
- render(input) {
2577
- if (!this.enabled || this.destroyed)
2578
- return;
2579
- this.throwIfFatal();
2580
- if (this.transport !== "png")
2581
- this.failWorker("renderer", new Error("OpenTUI image visuals require PNG transport for static-background rendering."));
2582
- this.ensureWorkersStarted();
2583
- const width = Math.max(1, Math.floor(input.pixelSize.width));
2584
- const height = Math.max(1, Math.floor(input.pixelSize.height));
2585
- if (width * height * 4 > MAX_IMAGE_BYTES)
2586
- return;
2587
- if (this.isOutputBackedUp())
2588
- return;
2589
- this.refillOutputBudget();
2590
- const splitInput = { ...input, tick: 0, layer: "split" };
2591
- const splitKey = imageVisualFrameKey(splitInput);
2592
- if (input.force || splitKey !== this.lastBackgroundKey) {
2593
- this.scheduleRender(this.motionSlot, splitInput, this.imageId, -30, input.force, this.panelImageIds);
2594
- this.lastBackgroundKey = splitKey;
2595
- }
2596
- }
2597
- flush() {
2598
- this.throwIfFatal();
2599
- if (this.flushPaused)
2600
- return false;
2601
- if (this.pendingFrames.size === 0)
2602
- return false;
2603
- this.refillOutputBudget();
2604
- if (this.isOutputBackedUp()) {
2605
- const retainedSplit = this.pendingFrames.get("split");
2606
- this.pendingFrames.clear();
2607
- if (retainedSplit)
2608
- this.pendingFrames.set("split", retainedSplit);
2609
- return false;
2610
- }
2611
- const framePriority = (frame) => {
2612
- const layer = pendingLayerKey(frame.key);
2613
- if (layer === "split")
2614
- return 1;
2615
- return 4;
2616
- };
2617
- const frames = Array.from(this.pendingFrames.values()).sort((a, b) => framePriority(a) - framePriority(b));
2618
- const prefix = "\x1B[?25l\x1B7\x1B[s\x1B[H";
2619
- const suffix = "\x1B[u\x1B8";
2620
- const selected = [];
2621
- const retained = new Map;
2622
- let sequence = "";
2623
- let byteLength = Buffer.byteLength(prefix + suffix);
2624
- for (const frame of frames) {
2625
- const candidate = sequence + frame.sequence;
2626
- const candidateBytes = Buffer.byteLength(prefix + candidate + suffix);
2627
- const layer = pendingLayerKey(frame.key);
2628
- const allowOneStaticFrame = selected.length === 0 && layer === "split";
2629
- if (candidateBytes <= this.outputBudgetBytes || allowOneStaticFrame) {
2630
- selected.push(frame);
2631
- sequence = candidate;
2632
- byteLength = candidateBytes;
2633
- } else if (layer === "split") {
2634
- retained.set(layer, frame);
2635
- }
2636
- }
2637
- this.pendingFrames.clear();
2638
- for (const [layer, frame] of retained)
2639
- this.pendingFrames.set(layer, frame);
2640
- if (!sequence || selected.length === 0)
2641
- return false;
2642
- const payload = `${prefix}${sequence}${suffix}`;
2643
- for (const frame of selected)
2644
- this.markWritten(frame.key);
2645
- this.outputBudgetBytes -= byteLength;
2646
- this.stdout.cork?.();
2647
- const accepted = this.stdout.write(payload);
2648
- this.stdout.uncork?.();
2649
- this.imagesVisible = true;
2650
- return accepted;
2651
- }
2652
- createSlot() {
2653
- return { worker: null, busy: false, queuedRequest: null, inFlightKey: "", queuedKey: "", clearedThroughRequestId: 0, latestRequestId: 0 };
2654
- }
2655
- resetSlot(slot) {
2656
- slot.busy = false;
2657
- slot.queuedRequest = null;
2658
- slot.inFlightKey = "";
2659
- slot.queuedKey = "";
2660
- }
2661
- markWritten(key) {
2662
- this.recentWrittenKeys.push(key);
2663
- while (this.recentWrittenKeys.length > RECENT_WRITTEN_LIMIT)
2664
- this.recentWrittenKeys.shift();
2665
- }
2666
- refillOutputBudget() {
2667
- const now = Date.now();
2668
- const elapsedMs = Math.max(0, now - this.lastBudgetAtMs);
2669
- this.lastBudgetAtMs = now;
2670
- this.outputBudgetBytes = Math.min(this.outputBytesPerSecond, this.outputBudgetBytes + elapsedMs / 1000 * this.outputBytesPerSecond);
2671
- }
2672
- isOutputBackedUp() {
2673
- return Boolean(this.stdout.writableNeedDrain) || this.stdout.writableLength > this.maxOutputBacklogBytes;
2674
- }
2675
- stageFrame(frame) {
2676
- this.pendingFrames.set(pendingLayerKey(frame.key), frame);
2677
- }
2678
- isKnownKey(slot, key) {
2679
- return this.recentWrittenKeys.includes(key) || Array.from(this.pendingFrames.values()).some((frame) => frame.key === key) || key === slot.inFlightKey || key === slot.queuedKey;
2680
- }
2681
- ensureWorkersStarted() {
2682
- if (this.workersStarted)
2683
- return;
2684
- this.workersStarted = true;
2685
- this.startWorker(this.motionSlot, "static-visuals");
2686
- }
2687
- failWorker(name, error) {
2688
- const detail = error instanceof Error ? error.message : String(error);
2689
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} failed: ${detail}`);
2690
- throw this.fatalWorkerError;
2691
- }
2692
- throwIfFatal() {
2693
- if (this.fatalWorkerError)
2694
- throw this.fatalWorkerError;
2695
- }
2696
- scheduleRender(slot, input, imageId, zIndex, force, imageIds) {
2697
- this.throwIfFatal();
2698
- const key = imageVisualFrameKey(input);
2699
- if (!force && this.isKnownKey(slot, key))
2700
- return;
2701
- const request = {
2702
- ...input,
2703
- imageId,
2704
- ...imageIds ? { imageIds } : {},
2705
- zIndex,
2706
- transport: this.transport,
2707
- requestId: ++this.requestId,
2708
- key
2709
- };
2710
- slot.latestRequestId = request.requestId;
2711
- if (!slot.worker) {
2712
- this.renderInline(slot, request);
2713
- return;
2714
- }
2715
- this.enqueueWorkerRender(slot, request);
2716
- }
2717
- startWorker(slot, name) {
2718
- const worker = createImageWorker();
2719
- if (!worker)
2720
- return;
2721
- slot.worker = worker;
2722
- worker.on("message", (message) => this.handleWorkerMessage(slot, message));
2723
- worker.once("error", (error) => {
2724
- if (!this.destroyed)
2725
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} failed: ${error instanceof Error ? error.message : String(error)}`);
2726
- });
2727
- worker.once("exit", (code) => {
2728
- if (!this.destroyed)
2729
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} exited unexpectedly with code ${code}.`);
2730
- });
2731
- }
2732
- renderInline(slot, request) {
2733
- try {
2734
- const result = renderImageVisualFrame(request);
2735
- if (result?.sequence && !this.isKnownKey(slot, result.key) && (!this.isOutputBackedUp() || pendingLayerKey(result.key) === "split")) {
2736
- this.stageFrame({ key: result.key, sequence: result.sequence });
2737
- this.onFrameReady?.();
2738
- }
2739
- } catch (error) {
2740
- this.failWorker(String(request.layer ?? "visual"), error);
2741
- }
2742
- }
2743
- enqueueWorkerRender(slot, request) {
2744
- this.throwIfFatal();
2745
- if (slot.busy) {
2746
- slot.queuedRequest = request;
2747
- slot.queuedKey = request.key;
2748
- return;
2749
- }
2750
- this.dispatchWorkerRender(slot, request);
2751
- }
2752
- dispatchWorkerRender(slot, request) {
2753
- this.throwIfFatal();
2754
- if (!slot.worker)
2755
- this.failWorker(String(request.layer ?? "visual"), new Error("worker is unavailable"));
2756
- slot.busy = true;
2757
- slot.inFlightKey = request.key;
2758
- try {
2759
- slot.worker.postMessage(request);
2760
- } catch (error) {
2761
- this.failWorker(String(request.layer ?? "visual"), error);
2762
- }
2763
- }
2764
- handleWorkerMessage(slot, message) {
2765
- if (this.destroyed || !message || typeof message !== "object")
2766
- return;
2767
- const response = message;
2768
- slot.busy = false;
2769
- slot.inFlightKey = "";
2770
- const isStale = response.requestId <= slot.clearedThroughRequestId || response.requestId < slot.latestRequestId;
2771
- if (!isStale) {
2772
- if (response.error)
2773
- this.failWorker(pendingLayerKey(response.key), new Error(response.error));
2774
- if (response.sequence && !this.isKnownKey(slot, response.key) && (!this.isOutputBackedUp() || pendingLayerKey(response.key) === "split")) {
2775
- this.stageFrame({ key: response.key, sequence: response.sequence });
2776
- this.onFrameReady?.();
2777
- }
2778
- }
2779
- const next = slot.queuedRequest;
2780
- slot.queuedRequest = null;
2781
- slot.queuedKey = "";
2782
- if (next && !this.isKnownKey(slot, next.key))
2783
- this.dispatchWorkerRender(slot, next);
2784
- }
2785
- }
2786
-
2787
1748
  // packages/cli/src/app-opentui/render/text.ts
2788
1749
  import { RGBA as RGBA5, TextAttributes as TextAttributes4, TextRenderable as TextRenderable2 } from "@opentui/core";
2789
1750
  var TRANSPARENT2 = RGBA5.fromInts(0, 0, 0, 0);