Public: anyone can read this; the crew can change it.

A .psd file shows its flattened preview and its layer list in the browser #12715

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/12677-a-psd-file-shows-its-flattened-preview-a → main 7 commits fork 6 threads · 6 unresolved

  • Merged. scout/12677-a-psd-file-shows-its-flattened-preview-a was merged into main as 33ef6c5.

Review

Sign in to review this change.
15 files changed +651 −3
docs/design/areas/render.md +4
@@ -26,6 +26,10 @@ Backgrounds, 256-colour above 15 and truecolour are dropped; so are cursor moves
2626
2727 A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the existing `.table` alone, with no `.card` around it (path, size, modified; `data-dense`), and a `tfoot` for the count and unpacked size. No new class: `.archive-view` is only a hook on the table and has no rule. How it works: `docs/features/archive-listing.md`. A list that cannot be read falls back to the Download card with the reason as its one sentence.
2828
29 ## Photoshop file (.psd)
30
31 `src/web/render/psd.ts` draws the facts as the existing `.status-rows` `dl`, the preview in the existing `.imgview-pane`, and the layers as a second `.status-rows` (name, Visible or Hidden). No card and no new class: `.psd-view` is only a hook and has no rule. How it works: `docs/features/psd.md`.
32
2933 ## GPS track (.gpx)
3034
3135 `src/web/render/gpx.ts` draws the route as one inline SVG in `.gpx-view`: no fixed width or height, `max-width: 100%` and `height: auto` (tokens only, `currentColor` stroke, no accent), so it fits a 360px phone. Its facts (track, distance, climb, points) are the existing `.status-rows` / `.status-row`, with no box. How it works: `docs/features/gpx.md`.
docs/features/README.md +1
@@ -217,6 +217,7 @@ Read with the guide page [Your apps](../guide-your-apps.md).
217217 ### Files in the browser
218218
219219 - [A .dxf file as a picture](file-dxf.md)
220 - [A .psd file: facts, preview and layers](psd.md)
220221 - [A .har file as a request waterfall](file-har.md)
221222 - [A .sarif file opens as its findings](file-sarif.md)
222223 - [A `.env.example` opens as the variables an app needs](file-env.md)
docs/features/psd.md added +22
@@ -0,0 +1,22 @@
1 # A .psd file
2
3 A Photoshop file (`.psd`, version 1) shows its facts, its flattened preview and its layer list, read from the bytes with no tool and no unpacking to disk. Code: `src/web/render/psd-read.ts` (`readPsd`, `readPsdHeader`, pure), `src/web/render/psd.ts` (the page `psd`), `src/tui/ui/psd-note.ts` (the terminal `psdNote`).
4
5 ## What is shown
6
7 - **Page:** a `dl` of size, mode, channels and layer count; the flattened preview when it can be drawn; then the layers as rows (name, Visible or Hidden). Names are escaped; control and bidi characters show as `�`.
8 - **Terminal:** in the workspace, the file's note is the same facts and the layer list as rows. No picture.
9
10 ## Limits
11
12 | Limit | Value | Why |
13 |---|---|---|
14 | Read whole | 5 MB (`READ_CEILING`) | The preview is an inline PNG data URI, up to 4 MP × 4 bytes of page, so the page stays light. |
15 | Preview | 8-bit RGB, up to 4 megapixels (`MAX_PIXELS`) | No buffer is allocated until the body holds the bytes the header and the RLE table claim. The worst honest file, 4 MP of one colour in about 200 KB, costs 28 MB of buffers and a 4 MP PNG encode per view. |
16 | Layers listed | 200 (`LAYER_CAP`) | The rest are walked and counted; the count is the records that parse, never the file's claim. |
17
18 A file over 5 MB is not sent to the binary view: only its first bytes are read, the 26-byte header gives size, mode and channels, and the page says no preview and no layer list. Download streams at any size.
19
20 ## Fallbacks
21
22 A file that is not version 1, has an impossible header, or is cut short keeps the binary view. Layers stop at the first record that does not parse, and the count says how many did; the header facts still show. Every length is checked against what is left before it is read.
src/tui/screens/workspace.ts +7 −1
@@ -106,9 +106,10 @@ import {
106106 import { fill, len, split } from "../ui/layout.ts";
107107 import { renderMarkdown, type Line } from "../ui/markdown.ts";
108108 import { archiveNote } from "../ui/archive-note.ts";
109 import { psdNote } from "../ui/psd-note.ts";
109110 import { mediaNote } from "../ui/media-note.ts";
110111 import { tokColor, type Tokens } from "../ui/theme.ts";
111 import { card, emptyState, input, scrollbar } from "../ui/widgets.ts";
112 import { card, emptyState, input, noteLines, scrollbar } from "../ui/widgets.ts";
112113 import type { Session } from "../session.ts";
113114 import { aboutScreen } from "./about.ts";
114115 import {
@@ -1266,6 +1267,7 @@ export function workspaceScreen(
12661267 else
12671268 note =
12681269 archiveNote(t.path, read.value.body, read.value.size, formatSize) ??
1270 (kindByName(t.path) === "psd" ? psdNote(read.value.body, read.value.size, formatSize) : undefined) ??

No test reaches this wiring. Add a workspace test that opens a .psd and sees the layer rows. Also psdNote belongs beside archiveNote in src/tui/ui/, not imported from src/web/render.

12691271 `Binary file, ${formatSize(read.value.size)}.`;
12701272 } else raw = read.value.body; // .html included: source here, the page preview is web-only
12711273 }
@@ -2831,6 +2833,10 @@ export function workspaceScreen(
28312833 drawPicture(s, r, c, t, t.image);
28322834 return;
28332835 }
2836 if (t.note.includes("\n")) {
2837 noteLines(s, r, c, { title: t.noteTitle, lines: t.note.split("\n") });
2838 return;
2839 }
28342840 if (t.note !== "") {
28352841 emptyState(s, r, c, {
28362842 title: t.noteTitle,
src/tui/ui/psd-note.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * What the terminal says for a .psd: its facts and layers as lines, no
3 * picture. Read through `readPsd`, as the page is; `undefined` for a file
4 * that is not a readable Photoshop file.
5 */
6
7 import { modeName, type PsdHeader, READ_CEILING, readPsd, readPsdHeader } from "../../web/render/psd-read.ts";
8
9 /** What the terminal says for a .psd: its facts and layers as rows, no picture. */
10 export function psdNote(body: Uint8Array, size: number, fmt: (bytes: number) => string): string | undefined {
11 const whole = body.length >= size;
12 const full = whole ? readPsd(body) : undefined;
13 const p: PsdHeader | undefined = full ?? (whole ? undefined : readPsdHeader(body));
14 if (p === undefined) return undefined;
15 const lines = [`${fmt(size)} · Photoshop · ${p.width} × ${p.height} · ${p.depth}-bit ${modeName(p.mode)} · ${p.channels} ${p.channels === 1 ? "channel" : "channels"}`];
16 if (full === undefined) return `${lines[0]}\nOver ${fmt(READ_CEILING)}: only the header is read.`;
17 lines.push(full.layerCount === 0 ? "No layers" : `${full.layerCount} ${full.layerCount === 1 ? "layer" : "layers"}`);
18 for (const l of full.layers) lines.push(` ${l.name === "" ? "(unnamed)" : l.name}${l.visible ? "" : " (hidden)"}`);
19 if (full.layerCount > full.layers.length) lines.push(` ${full.layerCount - full.layers.length} more not listed`);
20 return lines.join("\n");
21 }
src/tui/ui/widgets.ts +17
@@ -942,6 +942,23 @@ export function emptyState(
942942 );
943943 }
944944
945 /**
946 * `noteLines` — an empty state whose body is several lines (a file's facts,
947 * then its parts as rows): the headline centred, the lines left-aligned in a
948 * centred block, and what does not fit counted on the last row.
949 */
950 export function noteLines(s: Screen, r: Rect, c: Tokens, o: { title: string; lines: readonly string[] }): void {
951 if (r.w <= 0 || r.h < 3) return;
952 const w = Math.min(r.w, Math.max(44, ...o.lines.map((l) => displayWidth(l))));
953 const inner = center(r, w, Math.min(r.h, o.lines.length + 2));
954 s.line(inner, 0, truncate(o.title, w), style(c.fg, c.bg, BOLD), "center");
955 const room = inner.h - 2;
956 const shown = o.lines.length > room ? o.lines.slice(0, Math.max(0, room - 1)) : o.lines;
957 shown.forEach((l, i) => s.text(inner.x, inner.y + 2 + i, truncate(l, w), style(c.mutedFg, c.bg)));
958 if (shown.length < o.lines.length && room > 0)
959 s.text(inner.x, inner.y + 1 + room, `… ${o.lines.length - shown.length} more`, style(c.faint, c.bg));
960 }
961
945962 /**
946963 * `scrollbar` — one column. Drawn only when there is something to scroll, so
947964 * a short list never grows a decoration it does not need.
src/web/pages/repo.ts +3
@@ -94,6 +94,7 @@ import { csvJs, isCsvPath } from "../render/csv.ts";
9494 import { fontJs } from "../render/font.ts";
9595 import { INLINE_MAX, keepGcode, keptGcode, layerCount } from "../render/gcode.ts";
9696 import { hasTable } from "../render/sqlite.ts";
97 import { READ_CEILING } from "../render/psd-read.ts";
9798 import { fileKind, HEAD_BYTES, kindByName, needsPaths, RENDER_CAP } from "../render/kinds.ts";
9899 import { RENDERERS, rendererFor } from "../render/renderers.ts";
99100 import { downloadHref, mediaHref } from "./media.ts";
@@ -1909,6 +1910,8 @@ export function capped(blob: Blob, path = ""): Blob {
19091910 return blob;
19101911 if (blob.kind !== "too_large" && blob.size <= RENDER_CAP.gcode && fileKind(path, blob.body.subarray(0, HEAD_BYTES)) === "gcode")
19111912 return blob;
1913 if (blob.kind !== "too_large" && blob.size <= READ_CEILING && fileKind(path, blob.body.subarray(0, HEAD_BYTES)) === "psd")
1914 return blob;
19121915 return blob.kind !== "too_large" && blob.size > MAX_RENDER_BYTES
19131916 ? { kind: "too_large", size: blob.size, head: blob.body.slice(0, HEAD_BYTES) }
19141917 : blob;
src/web/render/kinds.ts +4
@@ -25,6 +25,7 @@ export type FileKind =
2525 | "model3d"
2626 | "archive"
2727 | "font"
28 | "psd"
2829 | "config"
2930 | "markdown"
3031 | "notebook"
@@ -74,6 +75,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
7475 model3d: 100 * MB,
7576 archive: 50 * MB,
7677 font: 20 * MB,
78 // Read whole up to 5 MB; above that the header alone gives the facts.
79 psd: 4_000 * MB,
outdated

A 5 MB cap sends bigger files to the binary view. Issue box 3 asks for a facts card for files larger than the cap. Read the header only above the pixel limit.

7780 config: 1 * MB,
7881 markdown: 1 * MB,
7982 notebook: 1 * MB,
@@ -161,6 +164,7 @@ const MEDIA: Readonly<Record<string, Media>> = {
161164 avif: { kind: "image", name: "AVIF", type: "image/avif", magic: (h) => ftyp(h) && (at(h, 8, "avif") || at(h, 8, "avis")) },
162165 bmp: { kind: "image", name: "BMP", type: "image/bmp", magic: ascii("BM") },
163166 ico: { kind: "image", name: "ICO", type: "image/x-icon", magic: bytes(0x00, 0x00, 0x01, 0x00) },
167 psd: { kind: "psd", name: "Photoshop", type: "image/vnd.adobe.photoshop", magic: (h) => at(h, 0, "8BPS") && h[4] === 0 && h[5] === 1 },
164168 svg: { kind: "svg", name: "SVG", type: "image/svg+xml", magic: svgRoot },
165169 html: { kind: "html", name: "HTML", type: "text/html; charset=utf-8", magic: textHead },
166170 htm: { kind: "html", name: "HTML", type: "text/html; charset=utf-8", magic: textHead },
src/web/render/psd-read.ts added +268
@@ -0,0 +1,268 @@
1 /**
2 * Reading a Photoshop file (`.psd`, version 1): its header, its layer names
3 * with visibility, and the merged image of an 8-bit RGB file as RGBA. Pure:
4 * bytes in, plain data out, no markup, so the page and the terminal share it.
5 *
6 * The file is untrusted, so every length is checked against what is left
7 * before it is read, and no buffer is allocated for the picture until the
8 * body is known to hold the bytes it claims. The worst a file can then ask
9 * is an honest one: `MAX_PIXELS` decoded (16 MB of RGBA) and encoded as a
10 * PNG, which a 4 MP picture of one colour can ask for from about 200 KB of
11 * RLE rows. Only names up to `LAYER_CAP` are kept; the rest are counted.
12 */
13
14 export const LAYER_CAP = 200;
15 /** A file over this is read for its header only (the preview is an inline data URI). */
16 export const READ_CEILING = 5_000_000;
17 /** The most pixels decoded for the preview (4096 × 4096 would be 16.8 M). */
18 export const MAX_PIXELS = 4_000_000;
19
20 export interface PsdLayer {
21 readonly name: string;
22 readonly visible: boolean;
23 }
24
25 export interface Psd {
26 readonly width: number;
27 readonly height: number;
28 readonly channels: number;
29 readonly depth: number;
30 readonly mode: number;
31 readonly layers: readonly PsdLayer[];
32 /** The layers the file holds, which may be more than are listed. */
33 readonly layerCount: number;
34 /** RGBA, width × height × 4; absent when the file is not 8-bit RGB or is too large. */
35 readonly pixels?: Uint8Array | undefined;
36 }
37
38 const MODES: Readonly<Record<number, string>> = {
39 0: "Bitmap", 1: "Grayscale", 2: "Indexed", 3: "RGB", 4: "CMYK", 7: "Multichannel", 8: "Duotone", 9: "Lab",
40 };
41 export const modeName = (mode: number): string => MODES[mode] ?? `mode ${mode}`;
42
43 /** A cursor that refuses to read past its end. */
44 class Reader {
45 readonly v: DataView;
46 constructor(readonly b: Uint8Array, public at = 0, readonly end = b.length) {
47 this.v = new DataView(b.buffer, b.byteOffset, b.byteLength);
48 }
49 left(): number {
50 return this.end - this.at;
51 }
52 need(n: number): void {
53 if (!Number.isInteger(n) || n < 0 || n > this.left()) throw new RangeError("psd: length past the end");
54 }
55 u8(): number {
56 this.need(1);
57 return this.b[this.at++]!;
58 }
59 u16(): number {
60 this.need(2);
61 const x = this.v.getUint16(this.at);
62 this.at += 2;
63 return x;
64 }
65 i16(): number {
66 this.need(2);
67 const x = this.v.getInt16(this.at);
68 this.at += 2;
69 return x;
70 }
71 u32(): number {
72 this.need(4);
73 const x = this.v.getUint32(this.at);
74 this.at += 4;
75 return x;
76 }
77 skip(n: number): void {
78 this.need(n);
79 this.at += n;
80 }
81 /** A sub-reader over the next `n` bytes, which are skipped here. */
82 take(n: number): Reader {
83 this.need(n);
84 const r = new Reader(this.b, this.at, this.at + n);
85 this.at += n;
86 return r;
87 }
88 }
89
90 const clean = (s: string): string => s.replace(/[\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩]/g, "�").slice(0, 200);
91
92 /** One layer record: its name and visibility, the cursor left after it. */
93 function readLayer(info: Reader): PsdLayer {
94 info.skip(16); // top, left, bottom, right
95 const channels = info.u16();
96 info.skip(channels * 6); // each channel: id (2) and data length (4)
97 info.skip(4); // "8BIM"
98 info.skip(4); // blend mode key
99 info.skip(2); // opacity, clipping
100 const flags = info.u8();
101 info.skip(1);
102 const extra = info.take(info.u32());
103 extra.skip(extra.u32()); // layer mask
104 extra.skip(extra.u32()); // blending ranges
105 const pascal = extra.take(Math.min(extra.u8(), extra.left()));
106 let name = clean(new TextDecoder("latin1").decode(pascal.b.subarray(pascal.at, pascal.end)));
107 // The padded Pascal name is a multiple of four bytes with its length byte.
108 extra.skip(Math.min((4 - ((1 + pascal.end - pascal.at) % 4)) % 4, extra.left()));
109 // A Unicode name (`luni`) is the better one when the file carries it.
110 while (extra.left() >= 12) {
111 const sig = String.fromCharCode(...extra.b.subarray(extra.at, extra.at + 4));
112 if (sig !== "8BIM" && sig !== "8B64") break;
113 const key = String.fromCharCode(...extra.b.subarray(extra.at + 4, extra.at + 8));
114 extra.skip(8);
115 const body = extra.take(Math.min(extra.u32(), extra.left()));
116 if (key === "luni" && body.left() >= 4) {
117 const n = Math.min(body.u32(), (body.left() / 2) | 0, 200);
118 let s = "";
119 for (let k = 0; k < n; k++) s += String.fromCharCode(body.u16());
120 if (s !== "") name = clean(s);
121 }
122 }
123 return { name, visible: (flags & 2) === 0 };
124 }
125
126 /**
127 * The layer records of the layer section. `count` is the records that
128 * parsed, never the file's claim: a record that runs past the end stops the
129 * walk there. At most `LAYER_CAP` are kept; the rest are walked and counted.
130 */
131 function readLayers(sec: Reader): { layers: PsdLayer[]; count: number } {
132 if (sec.left() === 0) return { layers: [], count: 0 };
133 const info = sec.take(sec.u32());
134 if (info.left() < 2) return { layers: [], count: 0 };
135 const claimed = Math.abs(info.i16());
136 const layers: PsdLayer[] = [];
137 let count = 0;
138 for (; count < claimed; count++) {
139 let l: PsdLayer;
140 try {
141 l = readLayer(info);
142 } catch {
143 break;
144 }
145 if (layers.length < LAYER_CAP) layers.push(l);
146 }
147 return { layers, count };
148 }
149
150 /** PackBits: exactly `width` bytes of one row, or a throw when the data runs out or overshoots. */
151 function unpackRow(r: Reader, out: Uint8Array, at: number, width: number): void {
152 let o = 0;
153 while (o < width) {
154 const n = r.u8() << 24 >> 24;
155 if (n === -128) continue;
156 if (n >= 0) {
157 const len = n + 1;
158 r.need(len);
159 if (o + len > width) throw new RangeError("psd: row overruns");
160 out.set(r.b.subarray(r.at, r.at + len), at + o);
161 r.at += len;
162 o += len;
163 } else {
164 const len = 1 - n;
165 if (o + len > width) throw new RangeError("psd: row overruns");
166 out.fill(r.u8(), at + o, at + o + len);
167 o += len;
168 }
169 }
170 }
171
172 /** The merged image of an 8-bit RGB file as RGBA, or undefined when it cannot be read. */
173 function readMerged(r: Reader, width: number, height: number, channels: number): Uint8Array | undefined {
174 const compression = r.u16();
175 const planes = Math.min(channels, 3);
176 const plane = width * height;
177 if (compression === 0) r.need(plane * channels);
178 else if (compression === 1) {
179 // The byte-count table and the rows it names must all be present before
180 // a byte of the picture is allocated.
181 const sizes = new Reader(r.b, r.at, r.end).take(height * channels * 2);
182 let total = 0;
183 while (sizes.left() > 0) total += sizes.u16();
184 r.need(height * channels * 2 + total);
185 } else return undefined;
186 const data = new Uint8Array(plane * 3);
187 if (compression === 0) {
188 for (let c = 0; c < planes; c++) data.set(r.b.subarray(r.at + c * plane, r.at + (c + 1) * plane), c * plane);
189 } else if (compression === 1) {
190 const table = r.take(height * channels * 2);
191 const rows = new Reader(r.b, r.at, r.end);
192 // Rows are stored in order; the byte-count table is checked, not trusted.
193 for (let c = 0; c < channels; c++)
194 for (let y = 0; y < height; y++) {
195 const size = table.u16();
196 const row = rows.take(size);
197 if (c < planes) unpackRow(row, data, c * plane + y * width, width);
198 }
199 }
200 const rgba = new Uint8Array(plane * 4);
201 for (let i = 0; i < plane; i++) {
202 rgba[i * 4] = data[i]!;
203 rgba[i * 4 + 1] = data[plane + i]!;
204 rgba[i * 4 + 2] = data[2 * plane + i]!;
205 rgba[i * 4 + 3] = 255;
206 }
207 return rgba;
208 }
209
210 export interface PsdHeader {
211 readonly width: number;
212 readonly height: number;
213 readonly channels: number;
214 readonly depth: number;
215 readonly mode: number;
216 }
217
218 function readHeader(r: Reader): PsdHeader | undefined {
219 if (r.u32() !== 0x38425053 || r.u16() !== 1) return undefined;
220 r.skip(6);
221 const channels = r.u16();
222 const height = r.u32();
223 const width = r.u32();
224 const depth = r.u16();
225 const mode = r.u16();
226 if (channels < 1 || channels > 56 || width < 1 || height < 1 || width > 30000 || height > 30000) return undefined;
227 return { width, height, channels, depth, mode };
228 }
229
230 /** Only the 26-byte header: all a file too large to read whole is shown from. */
231 export function readPsdHeader(body: Uint8Array): PsdHeader | undefined {
232 try {
233 return readHeader(new Reader(body));
234 } catch {
235 return undefined;
236 }
237 }
238
239 /** A PSD header, layers and 8-bit RGB merged image; undefined when no PSD or cut short. */
240 export function readPsd(body: Uint8Array): Psd | undefined {
241 try {
242 const r = new Reader(body);
243 const head = readHeader(r);
244 if (head === undefined) return undefined;
245 const { channels, height, width, depth, mode } = head;
246 r.skip(r.u32()); // colour mode data
247 r.skip(r.u32()); // image resources
248 const layerSection = r.take(r.u32());
249 let found: { layers: PsdLayer[]; count: number } = { layers: [], count: 0 };
250 try {
251 found = readLayers(layerSection);
252 } catch {
253 // Layers that do not parse are left out; the header is still good.
254 }
255 let pixels: Uint8Array | undefined;
256 if (mode === 3 && depth === 8 && channels >= 3 && width * height <= MAX_PIXELS) {
257 try {
258 pixels = readMerged(r, width, height, channels);
259 } catch {
260 pixels = undefined;
261 }
262 }
263 return { width, height, channels, depth, mode, layers: found.layers, layerCount: found.count, pixels };
264 } catch {
265 return undefined;
266 }
267 }
268
src/web/render/psd.ts added +64
@@ -0,0 +1,64 @@
1 /**

Principles 3, 6, 7: the renderer puts everything in card(...), a box, and facts as a muted paragraph. Use a dl row for facts and plain rows for layers. Also add the terminal door and docs/features/psd.md.

2 * A Photoshop file on the blob page: its facts as rows, its layers as rows,
3 * and, for an 8-bit RGB file, the flattened preview as an inline PNG (the
4 * repository's own encoder). A file over `READ_CEILING` is its header facts
5 * only; a file that does not parse falls back to source. Reading is in
6 * `psd-read.ts`.
7 */
8
9 import { encodePng } from "../../design/image/png.ts";
10 import { html, when } from "../html.ts";
11 import { fileSize } from "../ui.ts";
12 import { LAYER_CAP, MAX_PIXELS, modeName, type PsdHeader, READ_CEILING, readPsd, readPsdHeader } from "./psd-read.ts";
13 import type { Rendered, RenderInput } from "./renderers.ts";
14
15 const row = (k: string, v: string) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`;
16
17 export function psd(input: RenderInput): Rendered {
18 // A file over the page's read ceiling arrives as its first bytes only.
19 const whole = input.body.length >= input.size;
20 const full = whole ? readPsd(input.body) : undefined;
21 const p: PsdHeader | undefined = full ?? (whole ? undefined : readPsdHeader(input.body));
22 if (p === undefined) return { content: html``, lines: 0, fallback: "not a readable Photoshop file" };
23 const name = input.path.slice(input.path.lastIndexOf("/") + 1);
24 const pixels = full?.pixels;
25 const layers = full?.layers ?? [];
26 const layerCount = full?.layerCount ?? 0;
27 const png = pixels === undefined ? undefined : encodePng(p.width, p.height, pixels);
28 const uri = png === undefined ? "" : `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
29 const more = layerCount - layers.length;
30 const facts = [
31 row("Size", `${p.width} × ${p.height}`),
32 row("Mode", `${p.depth}-bit ${modeName(p.mode)}`),
33 row("Channels", String(p.channels)),
34 ...(whole ? [row("Layers", String(layerCount))] : []),
35 ];
36 // The Mode row already says when a file is not 8-bit RGB; the sentence is
37 // only for a reason the rows do not show.
38 const drawable = p.mode === 3 && p.depth === 8 && p.channels >= 3;
39 const why = !whole
40 ? `This file is over ${fileSize(READ_CEILING)}, so only its header is read: no preview and no layer list.`
41 : !drawable
42 ? ""
43 : p.width * p.height > MAX_PIXELS
44 ? `No preview: the picture is over ${String(MAX_PIXELS / 1_000_000)} megapixels.`
45 : "No preview: the merged image does not read.";
46 return {
47 lines: 0,
48 summary: `${fileSize(input.size)} · PSD · ${p.width} × ${p.height}`,
49 content: html`<div class="psd-view">
50 <dl class="status-rows" aria-label="${`${name} facts`}">${facts}</dl>
51 ${when(
52 png !== undefined,
53 () => html`<div class="imgview-pane"><img class="imgview-img" src="${uri}" width="${String(p.width)}" height="${String(p.height)}" alt="${`Flattened preview of ${name}`}" decoding="async" /></div>`,
54 )}
55 ${when(png === undefined && why !== "", () => html`<p class="muted small">${why}</p>`)}
56 ${when(
57 layers.length > 0,
58 () => html`<dl class="status-rows" aria-label="Layers">${layers.map((l) => row(l.name === "" ? "(unnamed)" : l.name, l.visible ? "Visible" : "Hidden"))}</dl>`,
59 )}
60 ${when(more > 0, () => html`<p class="muted small">${String(more)} more not listed (the page shows the first ${String(LAYER_CAP)}).</p>`)}
61 </div>`,
62 };
63 }
64
src/web/render/renderers.ts +6 −2
@@ -34,6 +34,7 @@ import { model3d } from "./model3d.ts";
3434 import { notebook } from "./notebook.ts";
3535 import { packageJson, readPackage } from "./package-json.ts";
3636 import { patch } from "./patch.ts";
37 import { psd } from "./psd.ts";
3738 import { pdf } from "./pdf.ts";
3839 import { dockerfile } from "./dockerfile.ts";
3940 import { workflow } from "./workflow.ts";
@@ -124,6 +125,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
124125 mail: eml,
125126 archive,
126127 font,
128 psd,
127129 };
128130
129131 /**
@@ -165,7 +167,7 @@ export function rendererFor(
165167 : kindByName(path);
166168 if (blob.size > RENDER_CAP[kind]) return undefined;
167169 if (MEDIA_KINDS.has(kind) && !where.media) return undefined;
168 if (blob.kind === "too_large" && !MEDIA_KINDS.has(kind)) return undefined;
170 if (blob.kind === "too_large" && !MEDIA_KINDS.has(kind) && kind !== "psd") return undefined;
169171 // A kind may draw only some of its files: `config` draws JSON, YAML and
170172 // TOML as a form, and leaves the rest (INI, .env …) their source.
171173 // A log with no escape in it keeps the source view, exactly as plain text.
@@ -176,5 +178,7 @@ export function rendererFor(
176178 (kind === "package" && blob.kind !== "too_large" && readPackage(blob.body) === undefined);
177179 const render = declined ? undefined : renderers[kind];
178180 if (render === undefined) return undefined;
179 return { render, body: blob.kind === "too_large" ? NO_BYTES : blob.body };
181 // A PSD over the read ceiling is drawn from its head: the header holds the facts.
182 const body = blob.kind === "too_large" ? (kind === "psd" ? (blob.head ?? NO_BYTES) : NO_BYTES) : blob.body;
183 return { render, body };
180184 }
test/render-kinds.test.ts +1
@@ -59,6 +59,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
5959 ttf: [of(0, 1, 0, 0, 0, 0), "font", "font/ttf"],
6060 otf: [enc("OTTO\0\0"), "font", "font/otf"],
6161 woff: [enc("wOFF\0\0"), "font", "font/woff"],
62 psd: [of(0x38, 0x42, 0x50, 0x53, 0, 1), "psd", "image/vnd.adobe.photoshop"],

Fine as a sample, but the psd test in render-psd.test.ts titled 'version 2 ... not psd' never builds a version-2 header; add one.

6263 woff2: [enc("wOF2\0\0"), "font", "font/woff2"],
6364 zip: [of(0x50, 0x4b, 3, 4, 0), "archive", "application/octet-stream"],
6465 tar: [enc("x".repeat(257) + "ustar\0"), "archive", "application/octet-stream"],
test/render-psd.test.ts added +186
@@ -0,0 +1,186 @@
1 /** A .psd on the blob page: header, layers, an 8-bit RGB preview, and no trust in its lengths. */
2
3 import { describe, expect, test } from "bun:test";
4 import { fileKind } from "../src/web/render/kinds.ts";
5 import { psdNote } from "../src/tui/ui/psd-note.ts";
6 import { psd } from "../src/web/render/psd.ts";
7 import { LAYER_CAP, readPsd } from "../src/web/render/psd-read.ts";
8 import { rendererFor } from "../src/web/render/renderers.ts";
9
10 const enc = (t: string): Uint8Array => new TextEncoder().encode(t);
11 const u16 = (n: number): number[] => [(n >> 8) & 255, n & 255];
12 const u32 = (n: number): number[] => [(n >>> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255];
13
14 function layer(name: string, hidden = false): number[] {
15 const pascal = [name.length, ...[...name].map((c) => c.charCodeAt(0))];
16 while (pascal.length % 4 !== 0) pascal.push(0);
17 const extra = [...u32(0), ...u32(0), ...pascal];
18 return [
19 ...u32(0), ...u32(0), ...u32(1), ...u32(1), ...u16(0),
20 ...[..."8BIM"].map((c) => c.charCodeAt(0)), ...[..."norm"].map((c) => c.charCodeAt(0)),
21 255, 0, hidden ? 2 : 0, 0, ...u32(extra.length), ...extra,
22 ];
23 }
24
25 interface Opts { w?: number; h?: number; mode?: number; depth?: number; layers?: [string, boolean?][]; rle?: boolean }
26
27 /** A 2 × 1 file: pixel one red, pixel two blue. */
28 function make(o: Opts = {}): Uint8Array {
29 const w = o.w ?? 2, h = o.h ?? 1;
30 const header = [..."8BPS"].map((c) => c.charCodeAt(0)).concat(u16(1), [0, 0, 0, 0, 0, 0], u16(3), u32(h), u32(w), u16(o.depth ?? 8), u16(o.mode ?? 3));
31 const recs = (o.layers ?? []).flatMap(([n, hid]) => layer(n, hid));
32 const info = o.layers?.length ? [...u16(o.layers.length), ...recs] : [];
33 const section = info.length ? [...u32(info.length), ...info] : [];
34 const planes = [[255, 0], [0, 0], [0, 255]];
35 const image = o.rle
36 ? [...u16(1), ...planes.flatMap(() => u16(3)), ...planes.flatMap((p) => [1, p[0]!, p[1]!])]
37 : [...u16(0), ...planes.flat()];
38 return new Uint8Array([...header, ...u32(0), ...u32(0), ...u32(section.length), ...section, ...image]);
39 }
40
41 describe("psd", () => {
42 test("kind by name and magic; version 2 and a renamed file are not psd", () => {
43 expect(fileKind("a.psd", make())).toBe("psd");
44 const v2 = make();
45 v2[5] = 2; // version 2 is a .psb
46 expect(fileKind("a.psd", v2)).not.toBe("psd");
47 expect(readPsd(v2)).toBeUndefined();
48 expect(fileKind("a.psd", new TextEncoder().encode("hello"))).toBe("text");
49 });
50
51 test("header, layers with visibility, and the merged image (raw and RLE)", () => {
52 for (const rle of [false, true]) {
53 const p = readPsd(make({ rle, layers: [["Sky"], ["Hidden", true]] }))!;
54 expect([p.width, p.height, p.channels, p.depth, p.mode]).toEqual([2, 1, 3, 8, 3]);
55 expect(p.layers).toEqual([{ name: "Sky", visible: true }, { name: "Hidden", visible: false }]);
56 expect([...p.pixels!]).toEqual([255, 0, 0, 255, 0, 0, 255, 255]);
57 }
58 });
59
60 test("renders a PNG data URI and escapes layer names", () => {
61 const out = psd({ path: "a.psd", size: 10, body: make({ layers: [["<b>x"]] }), media: "", download: "" });
62 const text = String(out.content);
63 expect(text).toContain("data:image/png;base64,");
64 expect(text).toContain("&lt;b&gt;x");
65 expect(text).not.toContain("<b>x");
66 });
67
68 test("other modes and depths show facts without a preview, not an error", () => {
69 for (const o of [{ mode: 4 }, { depth: 16 }]) {
70 const out = psd({ path: "a.psd", size: 10, body: make({ ...o, layers: [["L"]] }), media: "", download: "" });
71 expect(out.fallback).toBeUndefined();
72 expect(String(out.content)).not.toContain("data:image");
73 expect(String(out.content)).toContain("<dt>Layers</dt><dd>1</dd>");
74 }
75 const big = readPsd(make({ w: 3000, h: 3000 }))!;
76 expect(big.pixels).toBeUndefined();
77 expect(big.width).toBe(3000);
78 });
79
80 test("layers are capped", () => {
81 const p = readPsd(make({ layers: Array.from({ length: LAYER_CAP + 5 }, (_, i) => [`l${i}`] as [string]) }))!;
82 expect(p.layers.length).toBe(LAYER_CAP);
83 expect(p.layerCount).toBe(LAYER_CAP + 5);
84 });
85
86 test("the layer count is the records that parse, never the claim", () => {
87 const body = make({ layers: [["Sky"], ["Ink"]] });
88 const at = 26 + 4 + 4 + 4 + 4; // the claimed layer count
89 new DataView(body.buffer).setInt16(at, 30000);
90 const p = readPsd(body)!;
91 expect(p.layers.map((l) => l.name)).toEqual(["Sky", "Ink"]);
92 expect(p.layerCount).toBe(2);
93 const out = String(psd({ path: "a.psd", size: body.length, body, media: "", download: "" }).content);
94 expect(out).not.toContain("more not listed");
95 });
96
97 test("a header claiming a big picture over a tiny body allocates nothing", () => {
98 // 2000 × 2000 RGB with nothing after the header: raw and RLE both refused.
99 const Real = globalThis.Uint8Array;
100 let biggest = 0;
101 globalThis.Uint8Array = new Proxy(Real, {
102 construct(target, args) {
103 if (typeof args[0] === "number") biggest = Math.max(biggest, args[0]);
104 return Reflect.construct(target, args);
105 },
106 });
107 try {
108 for (const comp of [0, 1]) {
109 const head = make({ w: 2000, h: 2000 }).subarray(0, 26 + 12);
110 const body = new Real([...head, 0, comp, 0, 2]);
111 expect(readPsd(body)?.pixels).toBeUndefined();
112 }
113 } finally {
114 globalThis.Uint8Array = Real;
115 }
116 expect(biggest).toBeLessThan(1000);
117 // An RLE table whose rows claim more than the body holds.
118 const rle = make({ rle: true });
119 rle[rle.length - 9 - 6 + 1] = 200; // the first row's byte count
120 expect(readPsd(rle)?.pixels).toBeUndefined();
121 });
122
123 test("no sentence repeats the Mode row; a reason the rows do not show is said once", () => {
124 const cmyk = String(psd({ path: "a.psd", size: 10, body: make({ mode: 4 }), media: "", download: "" }).content);
125 expect(cmyk).toContain("<dt>Mode</dt><dd>8-bit CMYK</dd>");
126 expect(cmyk).not.toContain("No preview");
127 const short = make().subarray(0, make().length - 3);
128 const cut = String(psd({ path: "a.psd", size: short.length, body: short, media: "", download: "" }).content);
129 expect(cut).toContain("No preview: the merged image does not read.");
130 });
131
132 test("truncated files never throw; hostile lengths are refused", () => {
133 const whole = make({ rle: true, layers: [["Sky"]] });
134 for (let n = 0; n < whole.length; n++) expect(() => readPsd(whole.subarray(0, n))).not.toThrow();
135 expect(readPsd(whole.subarray(0, 20))).toBeUndefined();
136 // Hostile colour-mode length.
137 const hostile = whole.slice();
138 new DataView(hostile.buffer).setUint32(26, 0xffffffff);
139 expect(readPsd(hostile)).toBeUndefined();
140 // Hostile layer length: the header survives, the layers are dropped, the picture still reads.
141 const bad = make({ layers: [["Sky"]] });
142 const at = 26 + 4 + 4 + 4; // the layer info length
143 new DataView(bad.buffer).setUint32(at, 0x7fffffff);
144 expect(readPsd(bad)?.layers).toEqual([]);
145 // A raw image that is shorter than its header claims has no preview.
146 const short = make().subarray(0, make().length - 3);
147 expect(readPsd(short)?.pixels).toBeUndefined();
148 // An RLE row that overruns its width.
149 const rle = make({ rle: true });
150 rle[rle.length - 3 * 3] = 200;
151 expect(readPsd(rle)?.pixels).toBeUndefined();
152 });
153
154 test("the blob page draws facts and layers as rows, no card", () => {
155 const body = make({ layers: [["Sky"], ["Hidden one", true]] });
156 const r = rendererFor("a.psd", { kind: "binary", size: body.length, body });
157 expect(r).toBeDefined();
158 const out = String(r!.render({ path: "a.psd", size: body.length, body: r!.body, media: "", download: "" }).content);
159 expect(out).toContain('<dt>Size</dt><dd>2 × 1</dd>');
160 expect(out).toContain("<dt>Sky</dt><dd>Visible</dd>");
161 expect(out).toContain("<dt>Hidden one</dt><dd>Hidden</dd>");
162 expect(out).toContain("data:image/png;base64,");
163 expect(out).not.toContain("card");
164 });
165
166 test("a file over the read ceiling is its header facts from the head", () => {
167 const head = make();
168 const r = rendererFor("big.psd", { kind: "too_large", size: 400_000_000, head });
169 expect(r).toBeDefined();
170 const out = r!.render({ path: "big.psd", size: 400_000_000, body: r!.body, media: "", download: "" });
171 const text = String(out.content);
172 expect(text).toContain("<dt>Size</dt><dd>2 × 1</dd>");
173 expect(text).not.toContain("data:image");
174 expect(text).toContain("only its header is read");
175 expect(out.fallback).toBeUndefined();
176 });
177
178 test("the terminal note lists facts and layers", () => {
179 const body = make({ layers: [["Sky"], ["Ink", true]] });
180 const note = psdNote(body, body.length, (n) => `${n} B`)!;
181 expect(note).toContain("Photoshop · 2 × 1 · 8-bit RGB");
182 expect(note).toContain("2 layers\n Sky\n Ink (hidden)");
183 expect(psdNote(make(), 400_000_000, (n) => `${n} B`)).toContain("only the header is read");
184 expect(psdNote(enc("nope"), 4, (n) => `${n}`)).toBeUndefined();
185 });
186 });
test/tui-widgets.test.ts +14
@@ -33,6 +33,7 @@ import {
3333 table,
3434 tabs,
3535 timelineItem,
36 noteLines,
3637 } from "../src/tui/ui/widgets.ts";
3738 import { ago, plural } from "../src/tui/screens/common.ts";
3839 import { galleryFrame } from "../src/tui/gallery.ts";
@@ -615,3 +616,16 @@ describe("counted nouns", () => {
615616 expect(ago("not a date")).toBe("");
616617 });
617618 });
619
620 describe("noteLines", () => {
621 const c = theme("dark").c;
622 test("lines are drawn in order and what does not fit is counted", () => {
623 const s = new Screen(60, 8);
624 noteLines(s, { x: 0, y: 0, w: 60, h: 8 }, c, { title: "Not shown", lines: ["facts", "a", "b", "c", "d", "e", "f", "g"] });
625 const text = s.toText();
626 expect(text).toContain("Not shown");
627 expect(text).toContain("facts\n a\n b");
628 expect(text).toContain("… 3 more");
629 expect(text).not.toContain("g");
630 });
631 });
test/tui-workspace-kinds.test.ts +33
@@ -22,6 +22,22 @@ import { logLevel } from "../src/web/render/log.ts";
2222 import { jsonlTable, kindView, logLines, LINE_CAP, notebookLines, ROW_CAP } from "../src/tui/screens/workspace_kinds.ts";
2323
2424 quietLogs();
25
26 /** A 1 × 1 8-bit RGB .psd with the named layers, the second hidden. */
27 function psdFile(names: string[]): Uint8Array {
28 const u16 = (n: number): number[] => [(n >> 8) & 255, n & 255];
29 const u32 = (n: number): number[] => [(n >>> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255];
30 const ascii = (t: string): number[] => [...t].map((ch) => ch.charCodeAt(0));
31 const recs = names.flatMap((name, i) => {
32 const pascal = [name.length, ...ascii(name)];
33 while (pascal.length % 4 !== 0) pascal.push(0);
34 const extra = [...u32(0), ...u32(0), ...pascal];
35 return [...u32(0), ...u32(0), ...u32(1), ...u32(1), ...u16(0), ...ascii("8BIMnorm"), 255, 0, i === 1 ? 2 : 0, 0, ...u32(extra.length), ...extra];
36 });
37 const info = [...u16(names.length), ...recs];
38 const head = [...ascii("8BPS"), ...u16(1), 0, 0, 0, 0, 0, 0, ...u16(3), ...u32(1), ...u32(1), ...u16(8), ...u16(3)];
39 return new Uint8Array([...head, ...u32(0), ...u32(0), ...u32(info.length + 4), ...u32(info.length), ...info, ...u16(0), 9, 8, 7]);
40 }
2541 const c = theme("dark").c;
2642
2743 const NB = JSON.stringify({
@@ -171,6 +187,7 @@ describe("the workspace opens each kind", () => {
171187 { path: "run.log", content: "INFO started\n\x1b[32mERROR kaboom\x1b[0m\n" },
172188 { path: "empty.log", content: "" },
173189 { path: "nul.log", content: "a\x00b\nline two\n" },
190 { path: "art.psd", content: psdFile(["Sky", "Ink"]) },
174191 ],
175192 });
176193 });
@@ -246,4 +263,20 @@ describe("the workspace opens each kind", () => {
246263 h.stop();
247264 }
248265 });
266
267 test("a .psd opens as its facts and layer rows", async () => {
268 const h = boot();
269 try {
270 await h.settle();
271 await open(h, "kinds");
272 await openFile(h, "art.psd");
273 await h.until("2 layers");
274 expect(h.text()).toContain("Photoshop · 1 × 1 · 8-bit RGB");
275 expect(h.text()).toContain("Sky");
276 expect(h.text()).toContain("Ink (hidden)");
277 expect(h.text()).not.toContain("Binary file");
278 } finally {
279 h.stop();
280 }
281 });
249282 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs