Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion lib/renderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import { describe, expect, test } from 'bun:test';
import { DEFAULT_THEME } from './renderer';
import { DEFAULT_THEME, effectivePixelRatio } from './renderer';

describe('CanvasRenderer', () => {
describe('Default Theme', () => {
Expand Down Expand Up @@ -62,3 +62,28 @@ describe('CanvasRenderer', () => {
});
});
});

describe('effectivePixelRatio', () => {
test('whole ratios are kept', () => {
expect(effectivePixelRatio(1)).toBe(1);
expect(effectivePixelRatio(2)).toBe(2);
expect(effectivePixelRatio(3)).toBe(3);
});
test('fractional ratios round up (browser zoom, scaled displays)', () => {
expect(effectivePixelRatio(1.25)).toBe(2);
expect(effectivePixelRatio(1.36)).toBe(2);
expect(effectivePixelRatio(1.5)).toBe(2);
expect(effectivePixelRatio(2.2)).toBe(3);
});
test('float noise just above a whole ratio does not bump it', () => {
expect(effectivePixelRatio(2.0000001)).toBe(2);
expect(effectivePixelRatio(1.004)).toBe(1);
});
test('ratios below 1 and bad input fall back to 1', () => {
expect(effectivePixelRatio(0.5)).toBe(1);
expect(effectivePixelRatio(0)).toBe(1);
expect(effectivePixelRatio(Number.NaN)).toBe(1);
expect(effectivePixelRatio(undefined)).toBe(1);
expect(effectivePixelRatio(null)).toBe(1);
});
});
41 changes: 37 additions & 4 deletions lib/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ export interface FontMetrics {
// Default Theme
// ============================================================================

/**
* The pixel ratio the canvas is rendered at: the device ratio rounded **up** to a whole number.
*
* A fractional ratio (browser zoom, scaled displays: 1.25, 1.36, 2.2, ...) put cell edges on
* fractional device pixels, leaving hairline seams between cell backgrounds, and made the
* per-frame size check never match. Rendering at the next integer keeps text crisp (the browser
* scales the finished bitmap down) and every cell edge on a whole pixel. The small epsilon keeps a
* ratio like 2.0000001 at 2.
*/
export function effectivePixelRatio(dpr: number | undefined | null): number {
const raw = typeof dpr === 'number' && Number.isFinite(dpr) && dpr > 0 ? dpr : 1;
return Math.max(1, Math.ceil(raw - 0.01));
}

export const DEFAULT_THEME: Required<ITheme> = {
foreground: '#d4d4d4',
background: '#1e1e1e',
Expand Down Expand Up @@ -100,6 +114,8 @@ export class CanvasRenderer {
private cursorBlink: boolean;
private theme: Required<ITheme>;
private devicePixelRatio: number;
private lastCols = 0;
private lastRows = 0;
private metrics: FontMetrics;
private palette: string[];

Expand Down Expand Up @@ -152,7 +168,9 @@ export class CanvasRenderer {
this.cursorStyle = options.cursorStyle ?? 'block';
this.cursorBlink = options.cursorBlink ?? false;
this.theme = { ...DEFAULT_THEME, ...options.theme };
this.devicePixelRatio = options.devicePixelRatio ?? window.devicePixelRatio ?? 1;
this.devicePixelRatio = effectivePixelRatio(
options.devicePixelRatio ?? window.devicePixelRatio
);

// Build color palette (16 ANSI colors)
this.palette = [
Expand Down Expand Up @@ -230,10 +248,23 @@ export class CanvasRenderer {
// Canvas Sizing
// ==========================================================================

/**
* Update the pixel ratio after a browser zoom or a move to another display, and redraw at the
* new resolution. Takes the raw window.devicePixelRatio; it is normalised like the constructor's.
*/
public setDevicePixelRatio(dpr: number): void {
const next = effectivePixelRatio(dpr);
if (next === this.devicePixelRatio) return;
this.devicePixelRatio = next;
if (this.lastCols > 0 && this.lastRows > 0) this.resize(this.lastCols, this.lastRows);
}

/**
* Resize canvas to fit terminal dimensions
*/
public resize(cols: number, rows: number): void {
this.lastCols = cols;
this.lastRows = rows;
const cssWidth = cols * this.metrics.width;
const cssHeight = rows * this.metrics.height;

Expand Down Expand Up @@ -285,10 +316,12 @@ export class CanvasRenderer {
forceAll = true;
}

// Resize canvas if dimensions changed
// Resize canvas if dimensions changed. canvas.width/height are integers, so compare with the
// rounded target: with a fractional ratio the raw product never matched and this resized and
// fully repainted on every frame.
const needsResize =
this.canvas.width !== dims.cols * this.metrics.width * this.devicePixelRatio ||
this.canvas.height !== dims.rows * this.metrics.height * this.devicePixelRatio;
this.canvas.width !== Math.round(dims.cols * this.metrics.width * this.devicePixelRatio) ||
this.canvas.height !== Math.round(dims.rows * this.metrics.height * this.devicePixelRatio);

if (needsResize) {
this.resize(dims.cols, dims.rows);
Expand Down
24 changes: 24 additions & 0 deletions lib/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export class Terminal implements ITerminalCore {
// Lifecycle state
private isOpen = false;
private isDisposed = false;
private pixelRatioQuery?: MediaQueryList;
private animationFrameId?: number;
private writeQueue: Uint8Array[] = [];
private awaitingEcho = false;
Expand Down Expand Up @@ -429,6 +430,9 @@ export class Terminal implements ITerminalCore {
// Size canvas to terminal dimensions (use renderer.resize for proper DPI scaling)
this.renderer.resize(this.cols, this.rows);

// Follow browser zoom and moves to another display: re-render at the new pixel ratio.
this.watchPixelRatio();

// Create mouse tracking configuration
const canvas = this.canvas;
const renderer = this.renderer;
Expand Down Expand Up @@ -1088,6 +1092,24 @@ export class Terminal implements ITerminalCore {
// Lifecycle
// ==========================================================================

/**
* A `(resolution: Ndppx)` query for the current ratio fires when zoom or the display changes it;
* a ratio change alone fires no window resize event. Re-armed for the new ratio each time.
*/
private watchPixelRatio(): void {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
this.pixelRatioQuery?.removeEventListener('change', this.onPixelRatioChange);
this.pixelRatioQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
this.pixelRatioQuery.addEventListener('change', this.onPixelRatioChange);
}

private onPixelRatioChange = (): void => {
if (this.isDisposed || !this.renderer || !this.wasmTerm) return;
this.renderer.setDevicePixelRatio(window.devicePixelRatio);
this.renderer.render(this.wasmTerm, true, this.viewportY, this, this.scrollbarOpacity);
this.watchPixelRatio();
};

/**
* Dispose terminal and clean up resources
*/
Expand All @@ -1098,6 +1120,8 @@ export class Terminal implements ITerminalCore {

this.isDisposed = true;
this.isOpen = false;
this.pixelRatioQuery?.removeEventListener('change', this.onPixelRatioChange);
this.pixelRatioQuery = undefined;

// Stop render loop and clear write queue
this.cancelRenderLoop();
Expand Down