Open History to see the last commit
1import {
2 GHOSTTY_CELL_WIDE,
3 ghosttyColorsEqual,
4 type GhosttyCell,
5 type GhosttyColor,
6 type GhosttySnapshot,
7} from "./core";
8
9export interface GhosttyCellMetrics {
10 readonly width: number;
11 readonly height: number;
12 readonly baseline: number;
13}
14
15export interface GhosttyCellRange {
16 readonly start: { readonly x: number; readonly y: number };
17 readonly end: { readonly x: number; readonly y: number };
18}
19
20const DEFAULT_SELECTION_BACKGROUND = "rgba(72, 122, 191, 0.35)";
21const POWERLINE_SOLID_RIGHT = "\ue0b0";
22const POWERLINE_SOLID_LEFT = "\ue0b2";
23
24function cssColor(color: GhosttyColor): string {
25 return `rgb(${color.r}, ${color.g}, ${color.b})`;
26}
27
28function sameTextStyle(left: GhosttyCell, right: GhosttyCell): boolean {
29 // Selection only tints the background; splitting text runs shifts glyph spacing when advances differ from cell width.
30 return (
31 ghosttyColorsEqual(left.foreground, right.foreground) &&
32 left.bold === right.bold &&
33 left.italic === right.italic &&
34 left.invisible === right.invisible
35 );
36}
37
38function isSolidPowerlineSeparator(text: string): boolean {
39 return text === POWERLINE_SOLID_RIGHT || text === POWERLINE_SOLID_LEFT;
40}
41
42// Fallback fonts inset or scale these private-use glyphs, leaving a gap where
43// the separator should meet the next cell. Fill the triangle from the cell's
44// own edges instead, as native terminals do.
45function fillSolidPowerlineSeparator(
46 context: CanvasRenderingContext2D,
47 text: string,
48 left: number,
49 top: number,
50 metrics: GhosttyCellMetrics,
51): void {
52 const right = left + metrics.width;
53 const [base, point] = text === POWERLINE_SOLID_RIGHT ? [left, right] : [right, left];
54 context.beginPath();
55 context.moveTo(base, top);
56 context.lineTo(point, top + metrics.height / 2);
57 context.lineTo(base, top + metrics.height);
58 context.closePath();
59 context.fill();
60}
61
62function ghosttyTextRunEnd(
63 cells: readonly GhosttyCell[],
64 start: number,
65 sameStyle: (cell: GhosttyCell) => boolean,
66): number {
67 let end = start + 1;
68 while (end < cells.length) {
69 const next = cells[end];
70 if (!next) break;
71 if (next.wide === GHOSTTY_CELL_WIDE.spacerTail) {
72 end += 1;
73 continue;
74 }
75 if (next.text.length === 0 || isSolidPowerlineSeparator(next.text) || !sameStyle(next)) break;
76 end += 1;
77 }
78 return end;
79}
80
81function fontForCell(cell: GhosttyCell, fontSize: number, fontFamily: string): string {
82 const style = cell.italic ? "italic" : "normal";
83 const weight = cell.bold ? "700" : "400";
84 return `${style} ${weight} ${fontSize}px ${fontFamily}`;
85}
86
87export function measureGhosttyCell(
88 context: CanvasRenderingContext2D,
89 fontSize: number,
90 fontFamily: string,
91): GhosttyCellMetrics {
92 context.font = `normal 400 ${fontSize}px ${fontFamily}`;
93 const widthMeasurement = context.measureText("M");
94 const verticalMeasurement = context.measureText("Mg");
95 const ascent = verticalMeasurement.actualBoundingBoxAscent || fontSize;
96 const descent = verticalMeasurement.actualBoundingBoxDescent;
97 const glyphHeight = ascent + descent;
98 const height = Math.max(1, Math.round(fontSize * 1.35), Math.ceil(glyphHeight));
99 return {
100 width: Math.max(1, widthMeasurement.width),
101 height,
102 baseline: Math.round((height - glyphHeight) / 2 + ascent),
103 };
104}
105
106export function terminalGridSize(
107 width: number,
108 height: number,
109 metrics: GhosttyCellMetrics,
110 padding: number,
111): { cols: number; rows: number } {
112 return {
113 cols: Math.max(1, Math.floor((width - padding * 2) / metrics.width)),
114 rows: Math.max(1, Math.floor((height - padding * 2) / metrics.height)),
115 };
116}
117
118export function renderGhosttySnapshot(options: {
119 readonly context: CanvasRenderingContext2D;
120 readonly snapshot: GhosttySnapshot;
121 readonly metrics: GhosttyCellMetrics;
122 readonly fontSize: number;
123 readonly fontFamily: string;
124 readonly padding: number;
125 readonly forceFull: boolean;
126 readonly cursorOn: boolean;
127 readonly previousCursorY?: number | null;
128 readonly focused?: boolean;
129 readonly selectionBackground?: string;
130 readonly hoveredLinkRange?: GhosttyCellRange | null;
131 readonly originY?: number;
132}): void {
133 const {
134 context,
135 snapshot,
136 metrics,
137 fontSize,
138 fontFamily,
139 padding,
140 forceFull,
141 cursorOn,
142 previousCursorY,
143 } = options;
144 const focused = options.focused ?? true;
145 const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
146 const hoveredLinkRange = options.hoveredLinkRange ?? null;
147 const originY = options.originY ?? padding;
148 const rowsToDraw = forceFull
149 ? Array.from({ length: snapshot.rows }, (_, index) => index)
150 : [...snapshot.dirtyRows];
151 if (
152 previousCursorY !== null &&
153 previousCursorY !== undefined &&
154 previousCursorY >= 0 &&
155 !rowsToDraw.includes(previousCursorY)
156 ) {
157 rowsToDraw.push(previousCursorY);
158 }
159 if (snapshot.cursorVisible && snapshot.cursorY >= 0 && !rowsToDraw.includes(snapshot.cursorY)) {
160 rowsToDraw.push(snapshot.cursorY);
161 }
162
163 if (forceFull) {
164 context.save();
165 context.resetTransform();
166 context.fillStyle = cssColor(snapshot.background);
167 context.fillRect(0, 0, context.canvas.width, context.canvas.height);
168 context.restore();
169 }
170
171 context.textBaseline = "alphabetic";
172 for (const rowIndex of rowsToDraw) {
173 const row = snapshot.rowData[rowIndex];
174 if (!row) continue;
175 const top = originY + rowIndex * metrics.height;
176
177 context.fillStyle = cssColor(snapshot.background);
178 context.fillRect(padding, top, snapshot.cols * metrics.width, metrics.height);
179
180 let backgroundStart = 0;
181 while (backgroundStart < row.cells.length) {
182 const first = row.cells[backgroundStart];
183 if (!first) break;
184 let backgroundEnd = backgroundStart + 1;
185 while (backgroundEnd < row.cells.length) {
186 const next = row.cells[backgroundEnd];
187 if (
188 !next ||
189 next.selected !== first.selected ||
190 !ghosttyColorsEqual(next.background, first.background)
191 ) {
192 break;
193 }
194 backgroundEnd += 1;
195 }
196 if (first.selected || !ghosttyColorsEqual(first.background, snapshot.background)) {
197 const left = padding + backgroundStart * metrics.width;
198 const width = (backgroundEnd - backgroundStart) * metrics.width;
199 if (!ghosttyColorsEqual(first.background, snapshot.background)) {
200 context.fillStyle = cssColor(first.background);
201 context.fillRect(left, top, width, metrics.height);
202 }
203 if (first.selected) {
204 context.fillStyle = selectionBackground;
205 context.fillRect(left, top, width, metrics.height);
206 }
207 }
208 backgroundStart = backgroundEnd;
209 }
210
211 let runStart = 0;
212 while (runStart < row.cells.length) {
213 const first = row.cells[runStart];
214 if (!first) break;
215 if (first.text.length === 0) {
216 runStart += 1;
217 continue;
218 }
219 if (isSolidPowerlineSeparator(first.text)) {
220 if (!first.invisible) {
221 context.fillStyle = cssColor(first.foreground);
222 fillSolidPowerlineSeparator(
223 context,
224 first.text,
225 padding + runStart * metrics.width,
226 top,
227 metrics,
228 );
229 }
230 runStart += 1;
231 continue;
232 }
233 const runEnd = ghosttyTextRunEnd(row.cells, runStart, (cell) => sameTextStyle(cell, first));
234 const text = row.cells
235 .slice(runStart, runEnd)
236 .map((cell) => cell.text)
237 .join("");
238 if (!first.invisible && text.trim().length > 0) {
239 context.save();
240 context.beginPath();
241 context.rect(
242 padding + runStart * metrics.width,
243 top,
244 (runEnd - runStart) * metrics.width,
245 metrics.height,
246 );
247 context.clip();
248 context.font = fontForCell(first, fontSize, fontFamily);
249 context.fillStyle = cssColor(first.foreground);
250 context.fillText(
251 text,
252 padding + runStart * metrics.width,
253 top + metrics.baseline,
254 (runEnd - runStart) * metrics.width,
255 );
256 context.restore();
257 }
258 runStart = runEnd;
259 }
260
261 for (let column = 0; column < row.cells.length; column += 1) {
262 const cell = row.cells[column];
263 const hoveredLink =
264 hoveredLinkRange !== null &&
265 rowIndex >= hoveredLinkRange.start.y &&
266 rowIndex <= hoveredLinkRange.end.y &&
267 (rowIndex > hoveredLinkRange.start.y || column >= hoveredLinkRange.start.x) &&
268 (rowIndex < hoveredLinkRange.end.y || column <= hoveredLinkRange.end.x);
269 if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline && !hoveredLink)) {
270 continue;
271 }
272 context.fillStyle = cssColor(cell.foreground);
273 const left = padding + column * metrics.width;
274 if (cell.underline || hoveredLink) {
275 context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
276 }
277 if (cell.strikethrough) {
278 context.fillRect(left, top + Math.floor(metrics.height * 0.55), metrics.width, 1);
279 }
280 if (cell.overline) context.fillRect(left, top + 1, metrics.width, 1);
281 }
282 }
283
284 if (cursorOn && snapshot.cursorVisible && snapshot.cursorX >= 0 && snapshot.cursorY >= 0) {
285 const left = padding + snapshot.cursorX * metrics.width;
286 const top = originY + snapshot.cursorY * metrics.height;
287 context.fillStyle = cssColor(snapshot.cursor);
288 if (!focused) {
289 context.strokeStyle = cssColor(snapshot.cursor);
290 context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
291 } else if (snapshot.cursorStyle === 0) {
292 context.fillRect(left, top, 2, metrics.height);
293 } else if (snapshot.cursorStyle === 2) {
294 context.fillRect(left, top + metrics.height - 2, metrics.width, 2);
295 } else if (snapshot.cursorStyle === 3) {
296 context.strokeStyle = cssColor(snapshot.cursor);
297 context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
298 } else {
299 context.fillRect(left, top, metrics.width, metrics.height);
300 const cell = snapshot.rowData[snapshot.cursorY]?.cells[snapshot.cursorX];
301 if (cell?.text) {
302 context.fillStyle = cssColor(snapshot.background);
303 if (isSolidPowerlineSeparator(cell.text)) {
304 fillSolidPowerlineSeparator(context, cell.text, left, top, metrics);
305 } else {
306 context.font = fontForCell(cell, fontSize, fontFamily);
307 context.fillText(cell.text, left, top + metrics.baseline, metrics.width);
308 }
309 }
310 }
311 }
312}