diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts
index a05fbae9784..eb63ab09b28 100644
--- a/packages/app/component-tests/browser-pane-restore.spec.ts
+++ b/packages/app/component-tests/browser-pane-restore.spec.ts
@@ -851,6 +851,30 @@ story("holds every restored tab's box, label and icon from the reopen until its
expect(first.map((tab) => tab.icon)).toEqual([expect.any(String), previewIcon, docsIcon])
})
+// A page's icon arrives after its tab is drawn: Chromium lists it once the document's head has parsed, and main loads
+// it. The tab draws the globe until then. A site's SVG is drawn as an image, never put in the window as markup.
+story("a tab draws its page's icon in the globe's place as an image, and no tab moves", async ({ page }) => {
+ const root = page.getByTestId("browser-region-fixture")
+ const tabs = root.getByRole("tab")
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
+ await send(root, inventory(reported({ id: preview, url: "http://localhost:4173/", title: "Preview" }), reported({ id: docs, url: "https://example.com/docs", title: "Docs" })))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"])
+ await page.evaluate(() => document.fonts.ready.then(() => undefined))
+ const globes = await drawn(tabs)
+ expect(globes.slice(1).map((tab) => tab.icon)).toEqual(["none", "none"])
+
+ // A site's own SVG that would run as markup: a script, and a handler on the element itself.
+ const hostile = `data:image/svg+xml;base64,${Buffer.from(``).toString("base64")}`
+ const image = root.getByRole("tab", { name: "Docs", exact: true }).locator("img")
+ await send(root, details(preview, previewIcon))
+ await send(root, details(docs, hostile))
+ await expect(image).toHaveAttribute("src", hostile)
+ await expect.poll(() => image.evaluate((node: HTMLImageElement) => node.complete && node.naturalWidth > 0)).toBe(true)
+ expect(await page.evaluate(() => "iconRan" in window)).toBe(false)
+ expect(await drawn(tabs)).toEqual([globes[0], { ...globes[1], icon: previewIcon }, { ...globes[2], icon: hostile }])
+})
+
// A server without a browser left its restored tabs on a loader with no end.
story("a restored tab on a server without a browser says that the browser could not open, and keeps its box", async ({ page }) => {
const { root, stable } = await reopen(page)
diff --git a/packages/gui-plugins/src/browser/electron-icon.fixture.ts b/packages/gui-plugins/src/browser/electron-icon.fixture.ts
new file mode 100644
index 00000000000..81fa01bdc7b
--- /dev/null
+++ b/packages/gui-plugins/src/browser/electron-icon.fixture.ts
@@ -0,0 +1,145 @@
+import { createServer } from "node:http"
+import electron from "electron"
+import { icoSample, pngSample, svgSample, type Pixel } from "./icon-samples"
+
+// The Electron main process of `electron-icon.test.ts`, bundled and run by the pinned Electron. It loads the page of
+// each made-up site below in a hidden window and prints, as one JSON line, the icons Chromium listed for it and the
+// icon the pane makes of that list: a PNG's size in pixels, its length as a data URL and the color in its middle, or
+// an SVG's text.
+
+// A site's page lists its icons; the files beside it are what its server answers.
+type Site = { links: readonly string[]; files?: Readonly> }
+
+const solid = (...color: readonly [number, number, number]) => (): Pixel => [...color, 255]
+
+// Pixels no encoder can shrink: at 32px, the longest data URL an icon can have.
+const noise = (x: number, y: number): Pixel => {
+ const first = Math.imul(x + y * 300 + 1, 0x9e3779b1)
+ const second = Math.imul(first ^ (first >>> 15), 0x85ebca6b)
+ const third = Math.imul(second ^ (second >>> 13), 0xc2b2ae35)
+ const value = (third ^ (third >>> 16)) >>> 0
+
+ return [value & 255, (value >>> 8) & 255, (value >>> 16) & 255, 128 | (value >>> 24)]
+}
+
+const page = (title: string, links: readonly string[]) =>
+ `${title}${links.map((href) => ``).join("")}
${title}
`
+
+void electron.app.whenReady().then(async () => {
+ const { loadIcon } = await import("./icon")
+ const { createDirectNetwork } = await import("./network")
+
+ // Another origin, as a site's static host is. Its icon is a JPEG.
+ const elsewhere = createServer((_request, response) => {
+ response.writeHead(200, { "content-type": "image/jpeg" })
+ response.end(electron.nativeImage.createFromBuffer(pngSample(64, solid(250, 250, 250))).toJPEG(90))
+ })
+
+ await new Promise((resolve) => elsewhere.listen(0, "127.0.0.1", resolve))
+ const other = elsewhere.address()
+ const host = `http://127.0.0.1:${other instanceof Object ? other.port : 0}`
+
+ const sites = new Map(Object.entries({
+ // 16, 32 and 48px bitmaps in one 15,086-byte file, the commonest favicon.ico. The 32px one is green.
+ ico: {
+ links: ["site.ico"],
+ files: {
+ "site.ico": {
+ type: "image/x-icon",
+ body: icoSample([
+ { size: 16, bits: 32, paint: solid(255, 0, 0) },
+ { size: 32, bits: 32, paint: solid(10, 200, 60) },
+ { size: 48, bits: 32, paint: solid(0, 0, 255) },
+ ]),
+ },
+ },
+ },
+ png: { links: ["icon-180.png"], files: { "icon-180.png": { type: "image/png", body: pngSample(180, solid(240, 90, 30)) } } },
+ // Only SVG icons, as a Vite app has: one too long to report, then a short one.
+ svg: {
+ links: ["b.svg", "a.svg"],
+ files: {
+ "a.svg": { type: "image/svg+xml", body: svgSample.replace("", ``) },
+ "b.svg": { type: "image/svg+xml", body: svgSample },
+ },
+ },
+ // No : Chromium asks for /favicon.ico, which this server has.
+ unlisted: { links: [] },
+ // A redirect to the other origin.
+ moved: { links: ["icon"], files: { icon: { type: "text/plain", body: "", status: 302, location: `${host}/icon.jpg` } } },
+ // Nothing to draw: a page in the icon's place, a missing file and a picture past the size limit.
+ refused: {
+ links: ["a", "b.png", "c.png"],
+ files: { a: { type: "text/html", body: page("Not an icon", []) }, "c.png": { type: "image/png", body: pngSample(300, noise) } },
+ },
+ }))
+
+ const server = createServer((request, response) => {
+ const [, site = "", file = ""] = (request.url ?? "").split("/")
+
+ if (site === "favicon.ico")
+ return void response.writeHead(200, { "content-type": "image/x-icon" }).end(icoSample([{ size: 32, bits: 32, paint: noise }]))
+ const found = sites.get(site)
+
+ if (!found) return void response.writeHead(404).end()
+
+ if (!file) return void response.writeHead(200, { "content-type": "text/html" }).end(page(site, found.links))
+ const answer = found.files?.[file]
+
+ if (!answer) return void response.writeHead(404).end()
+ response.writeHead(answer.status ?? 200, { "content-type": answer.type, ...(answer.location && { location: answer.location }) })
+ response.end(answer.body)
+ })
+
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
+ const address = server.address()
+ const origin = `http://127.0.0.1:${address instanceof Object ? address.port : 0}`
+ // The pane loads an icon through its page's own session, without that session's cookies.
+ const partition = electron.session.fromPartition("icon-fixture")
+ const network = createDirectNetwork(partition)
+ const win = new electron.BrowserWindow({ show: false, webPreferences: { session: partition } })
+
+ const describe = (icon: string | undefined) => {
+ if (!icon) return null
+ const type = /^data:([^;,]+)/.exec(icon)?.[1] ?? ""
+
+ if (type !== "image/png") return { type, text: Buffer.from(icon.slice(icon.indexOf(",") + 1), "base64").toString() }
+ const image = electron.nativeImage.createFromDataURL(icon)
+ const size = image.getSize()
+ const middle = (Math.floor(size.height / 2) * size.width + Math.floor(size.width / 2)) * 4
+ // Chromium's bitmaps hold blue first.
+ const [blue = 0, green = 0, red = 0] = image.toBitmap().subarray(middle, middle + 3)
+
+ return { type, width: size.width, height: size.height, length: icon.length, color: "#" + [red, green, blue].map((value) => value.toString(16).padStart(2, "0")).join("") }
+ }
+
+ // Loads a site's page and returns the icons Chromium listed for it, as the pane's page hears them, and their icon.
+ const visit = async (site: string) => {
+ const url = `${origin}/${site}/`
+ const listed = Promise.withResolvers()
+
+ const heard = (_event: Electron.Event, favicons: string[]) => {
+ // A list that arrives late for the page before this one is not this page's.
+ if (favicons.length > 0 && win.webContents.getURL() === url) listed.resolve(favicons)
+ }
+
+ win.webContents.on("page-favicon-updated", heard)
+ await win.loadURL(url)
+ const favicons = await listed.promise
+ win.webContents.off("page-favicon-updated", heard)
+
+ return [site, { listed: favicons, icon: describe(await loadIcon(favicons, network)) }] as const
+ }
+
+ const results = await [...sites.keys()].reduce>(
+ async (done, site) => [...(await done), await visit(site)],
+ Promise.resolve([]),
+ )
+
+ process.stdout.write(`${JSON.stringify(Object.fromEntries(results)).replaceAll(origin, "").replaceAll(host, "//elsewhere")}\n`)
+ server.closeAllConnections()
+ server.close()
+ elsewhere.closeAllConnections()
+ elsewhere.close()
+ electron.app.quit()
+})
diff --git a/packages/gui-plugins/src/browser/electron-icon.test.ts b/packages/gui-plugins/src/browser/electron-icon.test.ts
new file mode 100644
index 00000000000..155448a0450
--- /dev/null
+++ b/packages/gui-plugins/src/browser/electron-icon.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from "bun:test"
+import path from "node:path"
+import { runElectronFixture } from "./electron-run"
+import { svgSample } from "./icon-samples"
+
+type Reported = {
+ /** The page's icons as Chromium listed them. */
+ readonly listed: readonly string[]
+ /** The icon the pane makes of that list, as the strip draws it. */
+ readonly icon: { readonly type: string; readonly length?: number; readonly text?: string } | null
+}
+
+const png = (color: string) => ({ type: "image/png", width: 32, height: 32, length: expect.any(Number), color })
+
+// A tab's icon rests on three things Electron decides: which icons Chromium lists for a page, what a request for one
+// returns, and which files `nativeImage` decodes, which is PNG and JPEG only. Most sites serve an `.ico` file, and
+// those tabs drew the globe. This loads a few kinds of site in the pinned Electron, so an upgrade that changes any of
+// the three fails here. `icon-image.test.ts` covers what an `.ico` file can hold, and `page-machine.test.ts` how a
+// tab takes the list and reports the icon.
+test(
+ "a page's icon is a small PNG, or the site's SVG as it is, and none for what is not a picture",
+ async () => {
+ const result: Record = JSON.parse(await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-icon.fixture.ts") }))
+
+ expect(Object.fromEntries(Object.entries(result).map(([site, reported]) => [site, reported.icon]))).toEqual({
+ // The file's 32px bitmap, and a 180px PNG reduced.
+ ico: png("#0ac83c"),
+ png: png("#f05a1e"),
+ // The window draws a site's SVG as an image; one too long to report gives way to the next.
+ svg: { type: "image/svg+xml", text: svgSample },
+ unlisted: png(expect.any(String)),
+ // A JPEG on another origin, behind a redirect.
+ moved: png(expect.any(String)),
+ refused: null,
+ })
+ // Chromium lists a page's icons by address, and asks for /favicon.ico when the page lists none.
+ expect(result.svg?.listed).toEqual(["/svg/a.svg", "/svg/b.svg"])
+ expect(result.unlisted?.listed).toEqual(["/favicon.ico"])
+ // That one is 32px no encoder can shrink: the longest PNG fits the 6,000 characters the history and saved tabs keep.
+ expect(result.unlisted?.icon?.length).toBeGreaterThan(4_000)
+ expect(result.unlisted?.icon?.length).toBeLessThanOrEqual(6_000)
+ },
+ // Starting Electron takes seconds on a loaded runner.
+ 60_000,
+)
diff --git a/packages/gui-plugins/src/browser/icon-image.test.ts b/packages/gui-plugins/src/browser/icon-image.test.ts
new file mode 100644
index 00000000000..cc12983fd55
--- /dev/null
+++ b/packages/gui-plugins/src/browser/icon-image.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test } from "bun:test"
+import { inflateSync } from "node:zlib"
+import { iconImage } from "./icon-image"
+import { icoSample, pngSample, svgSample, type Pixel } from "./icon-samples"
+
+const solid = (...color: readonly [number, number, number]) => (): Pixel => [...color, 255]
+
+// A picture with a transparent corner, a half-transparent pixel and a few colors.
+const drawing = (x: number, y: number): Pixel =>
+ x + y < 3 ? [0, 0, 0, 0] : x === 5 && y === 5 ? [200, 100, 50, 128] : (x + y) % 2 ? [220, 30, 30, 255] : [20, 60, 200, 255]
+
+// The same without the half-transparent pixel, as a bitmap with a mask holds it.
+const masked = (x: number, y: number): Pixel => (x === 5 && y === 5 ? [20, 60, 200, 255] : drawing(x, y))
+
+// The pixels of a PNG as `iconImage` writes one: a header, then one block of unfiltered RGBA rows.
+const pixels = (png: Buffer | undefined) => {
+ if (!png) return undefined
+ const width = png.readUInt32BE(16)
+ const rows = inflateSync(png.subarray(41, 41 + png.readUInt32BE(33)))
+
+ return Array.from({ length: png.readUInt32BE(20) }, (_, y) =>
+ Array.from({ length: width }, (_, x) => [...rows.subarray(y * (width * 4 + 1) + 1 + x * 4, y * (width * 4 + 1) + 5 + x * 4)]),
+ )
+}
+
+const painted = (size: number, paint: (x: number, y: number) => Pixel) =>
+ Array.from({ length: size }, (_, y) => Array.from({ length: size }, (_, x) => [...paint(x, y)]))
+
+// Transparent pixels have no color worth comparing.
+const visible = (rows: number[][][] | undefined) => rows?.map((row) => row.map((pixel) => (pixel[3] === 0 ? [0, 0, 0, 0] : pixel)))
+
+describe("an .ico file's bitmap becomes a PNG of the same pixels", () => {
+ test("32 bits a pixel keeps each pixel's own transparency", () => {
+ expect(visible(pixels(iconImage(icoSample([{ size: 16, bits: 32, paint: drawing }]))))).toEqual(painted(16, drawing))
+ })
+
+ test.each([24, 8, 4] as const)("%d bits a pixel takes its transparency from the mask", (bits) => {
+ expect(visible(pixels(iconImage(icoSample([{ size: 16, bits, paint: masked }]))))).toEqual(painted(16, masked))
+ })
+
+ test("two colors, and a width whose rows are padded", () => {
+ const paint = (x: number, y: number): Pixel => (x === y ? [0, 0, 0, 0] : x > y ? [255, 255, 255, 255] : [0, 0, 0, 255])
+
+ expect(visible(pixels(iconImage(icoSample([{ size: 20, bits: 1, paint }]))))).toEqual(painted(20, paint))
+ })
+
+ // Tools that predate transparency wrote 32 bits with that byte zero throughout: the mask says what shows.
+ test("32 bits with no transparency written is as opaque as its mask says", () => {
+ const file = icoSample([{ size: 16, bits: 32, paint: masked }])
+ // The pixels follow the 6-byte file header, one 16-byte entry and the bitmap's 40-byte header.
+ Array.from({ length: 16 * 16 }, (_, index) => 62 + index * 4 + 3).forEach((at) => (file[at] = 0))
+
+ expect(visible(pixels(iconImage(file)))).toEqual(painted(16, masked))
+ })
+})
+
+describe("the image of an .ico file that is kept", () => {
+ const sizes = (...images: readonly (readonly [number, 4 | 32, number])[]) =>
+ icoSample(images.map(([size, bits, red]) => ({ size, bits, paint: solid(red, 0, 0) })))
+
+ const kept = (file: Buffer) => {
+ const rows = pixels(iconImage(file))
+
+ return [rows?.length, rows?.[0]?.[0]?.[0]]
+ }
+
+ test.each([
+ ["the 32px image", sizes([16, 32, 1], [32, 32, 2], [48, 32, 3]), [32, 2]],
+ ["else the smallest larger one", sizes([16, 32, 1], [64, 32, 2], [48, 32, 3]), [48, 3]],
+ ["else the largest", sizes([16, 32, 1], [24, 32, 2], [20, 32, 3]), [24, 2]],
+ ["of two the same size, the one with more colors", sizes([32, 4, 1], [32, 32, 2]), [32, 2]],
+ ["a single small one", sizes([16, 32, 1]), [16, 1]],
+ ["a size no icon usually has", sizes([150, 32, 1]), [150, 1]],
+ [
+ "a bitmap nearer the kept size than the PNG beside it",
+ icoSample([{ size: 16, bits: 32, paint: solid(1, 0, 0) }, { size: 64, bits: 32, paint: solid(2, 0, 0) }, { size: 256, png: pngSample(256, solid(3, 0, 0)) }]),
+ [64, 2],
+ ],
+ ])("%s", (_name, file, expected) => {
+ expect(kept(file)).toEqual(expected)
+ })
+
+ test("a PNG inside is kept as it is", () => {
+ const png = pngSample(64, solid(1, 2, 3))
+
+ expect(iconImage(icoSample([{ size: 16, bits: 32, paint: solid(9, 9, 9) }, { size: 64, png }]))).toEqual(png)
+ })
+
+ test("an image the file does not hold in full gives way to the next", () => {
+ const file = sizes([16, 32, 1], [32, 32, 2])
+
+ // The 32px image is last in the file: without its final rows, the 16px one is the icon.
+ expect(kept(file.subarray(0, file.length - 2_000))).toEqual([16, 1])
+ })
+})
+
+// Whatever a server calls the file: a PNG named favicon.ico is common.
+test("a PNG or a JPEG is its own image", () => {
+ const png = pngSample(180, solid(4, 5, 6))
+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46])
+
+ expect(iconImage(png)).toBe(png)
+ expect(iconImage(jpeg)).toBe(jpeg)
+})
+
+test.each([
+ // An SVG is reported by its type as it is, and never read here.
+ ["an SVG", Buffer.from(svgSample)],
+ ["an SVG after an XML declaration", Buffer.from(`${svgSample}`)],
+ ["a page", Buffer.from("Not found")],
+ ["a GIF", Buffer.from("GIF89a\u0001\u0000\u0001\u0000", "latin1")],
+ ["nothing", Buffer.alloc(0)],
+ ["bytes of no format", Buffer.from(Array.from({ length: 4096 }, (_, index) => (index * 37) & 255))],
+ ["an .ico file with no image", icoSample([])],
+ ["an .ico file cut inside its list of images", icoSample([{ size: 16, bits: 32, paint: solid(1, 1, 1) }]).subarray(0, 20)],
+ ["an .ico file cut inside its only image", icoSample([{ size: 32, bits: 32, paint: solid(1, 1, 1) }]).subarray(0, 900)],
+ [
+ "an .ico file whose bitmap is compressed",
+ (() => {
+ const file = icoSample([{ size: 16, bits: 8, paint: solid(1, 1, 1) }])
+ // The bitmap header's compression field: run-length encoding.
+ file.writeUInt32LE(1, 22 + 16)
+
+ return file
+ })(),
+ ],
+ [
+ "an .ico file whose bitmap claims a size no icon has",
+ (() => {
+ const file = icoSample([{ size: 16, bits: 32, paint: solid(1, 1, 1) }])
+ file.writeInt32LE(100_000, 22 + 4)
+
+ return file
+ })(),
+ ],
+])("%s is no image nativeImage reads", (_name, file) => {
+ expect(iconImage(file)).toBeUndefined()
+})
diff --git a/packages/gui-plugins/src/browser/icon-image.ts b/packages/gui-plugins/src/browser/icon-image.ts
new file mode 100644
index 00000000000..5391a1b5d17
--- /dev/null
+++ b/packages/gui-plugins/src/browser/icon-image.ts
@@ -0,0 +1,110 @@
+import { crc32, deflateSync } from "node:zlib"
+
+const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+
+/** The size a page's icon is kept at: twice the 16px it is drawn at, so it stays sharp on a 2x display. */
+export const ICON_SIZE = 32
+
+/**
+ * An icon file as an image Electron's `nativeImage` reads, which is PNG and JPEG only: the file itself when it is one
+ * of those, else the best image of an `.ico` file, which is what most sites serve. Undefined for anything else: markup,
+ * a format read by neither (GIF, WebP, AVIF), or a file cut short. The bytes decide, never the type a server declared.
+ */
+export function iconImage(file: Buffer): Buffer | undefined {
+ if (starts(file, PNG) || starts(file, [0xff, 0xd8, 0xff])) return file
+
+ // An .ico file: a reserved zero, the type 1, the number of images, then 16 bytes for each.
+ if (!starts(file, [0, 0, 1, 0]) || file.length < 6) return
+
+ return Array.from({ length: Math.min(file.readUInt16LE(4), Math.floor((file.length - 6) / 16)) }, (_, index) => {
+ const entry = 6 + index * 16
+ const start = file.readUInt32LE(entry + 12)
+
+ // A width or height of 256 is written as 0. An image that runs past the file's end is empty.
+ return { size: Math.max(file[entry] || 256, file[entry + 1] || 256), data: file.subarray(start, start + file.readUInt32LE(entry + 8)) }
+ })
+ .sort((a, b) => rank(a.size) - rank(b.size) || depth(b.data) - depth(a.data))
+ .reduce((found, entry) => found ?? (starts(entry.data, PNG) ? entry.data : bitmap(entry.data)), undefined)
+}
+
+function starts(file: Buffer, bytes: readonly number[]) {
+ return bytes.every((byte, index) => file[index] === byte)
+}
+
+// The image at the kept size first, then larger ones from the smallest, which are reduced, then smaller ones from the
+// largest.
+function rank(size: number) {
+ return size >= ICON_SIZE ? size - ICON_SIZE : 256 + ICON_SIZE - size
+}
+
+// Bits a pixel, which says how many colors an image of the same size has.
+function depth(data: Buffer) {
+ return starts(data, PNG) ? 32 : data.length >= 16 ? data.readUInt16LE(14) : 0
+}
+
+/**
+ * An icon's Windows bitmap as a PNG: its header, a color table for 8 bits a pixel or fewer, the pixel rows from the
+ * bottom up, then a mask of one bit a pixel that is set where the icon is transparent. Undefined for a compressed
+ * bitmap, a size no icon has, or rows the file does not hold.
+ */
+function bitmap(data: Buffer) {
+ if (data.length < 40) return
+ const header = data.readUInt32LE(0)
+ const width = data.readInt32LE(4)
+ // The header counts the pixel rows and the mask rows together.
+ const height = data.readInt32LE(8) >> 1
+ const bits = data.readUInt16LE(14)
+
+ if (header < 40 || width < 1 || width > 256 || height < 1 || height > 256 || data.readUInt32LE(16) !== 0) return
+
+ if (![1, 4, 8, 24, 32].includes(bits)) return
+ const colors = bits <= 8 ? data.readUInt32LE(32) || 1 << bits : 0
+ const pixels = header + colors * 4
+ // Every row is padded to four bytes.
+ const stride = ((width * bits + 31) >> 5) << 2
+ const mask = pixels + stride * height
+ const maskStride = ((width + 31) >> 5) << 2
+
+ if (colors > 256 || mask > data.length) return
+ const masked = mask + maskStride * height <= data.length
+ // A 32-bit image carries its own transparency, unless a tool that wrote only the mask left that byte zero throughout.
+ const alpha = bits === 32 && Array.from({ length: width * height }, (_, index) => index).some((index) => data[pixels + index * 4 + 3] !== 0)
+ const line = width * 4 + 1
+ // PNG rows from the top down, each after a zero for "no filter", as red, green, blue and alpha.
+ const rows = Buffer.alloc(height * line)
+
+ for (let y = 0; y < height; y++) {
+ const row = pixels + (height - 1 - y) * stride
+ const maskRow = mask + (height - 1 - y) * maskStride
+
+ for (let x = 0; x < width; x++) {
+ const index = bits <= 8 ? ((data[row + ((x * bits) >> 3)] ?? 0) >> (8 - bits - ((x * bits) & 7))) & ((1 << bits) - 1) : 0
+ const color = bits <= 8 ? header + index * 4 : row + x * (bits >> 3)
+ const hidden = masked && ((data[maskRow + (x >> 3)] ?? 0) & (0x80 >> (x & 7))) !== 0
+
+ rows.set(
+ [data[color + 2] ?? 0, data[color + 1] ?? 0, data[color] ?? 0, alpha ? (data[color + 3] ?? 0) : hidden ? 0 : 255],
+ y * line + 1 + x * 4,
+ )
+ }
+ }
+
+ const size = Buffer.alloc(13)
+ size.writeUInt32BE(width, 0)
+ size.writeUInt32BE(height, 4)
+ // 8 bits a channel, with alpha.
+ size.set([8, 6, 0, 0, 0], 8)
+
+ return Buffer.concat([Buffer.from(PNG), chunk("IHDR", size), chunk("IDAT", deflateSync(rows)), chunk("IEND", Buffer.alloc(0))])
+}
+
+// A PNG chunk: its length, its name and data, and their checksum.
+function chunk(name: string, data: Buffer) {
+ const body = Buffer.concat([Buffer.from(name, "latin1"), data])
+ const length = Buffer.alloc(4)
+ length.writeUInt32BE(data.length)
+ const checksum = Buffer.alloc(4)
+ checksum.writeUInt32BE(crc32(body))
+
+ return Buffer.concat([length, body, checksum])
+}
diff --git a/packages/gui-plugins/src/browser/icon-samples.ts b/packages/gui-plugins/src/browser/icon-samples.ts
new file mode 100644
index 00000000000..5b9ed1cdfe3
--- /dev/null
+++ b/packages/gui-plugins/src/browser/icon-samples.ts
@@ -0,0 +1,110 @@
+import { crc32, deflateSync } from "node:zlib"
+
+// Icon files as sites serve them, for the tests of the page icon (`icon-image.test.ts`, `electron-icon.fixture.ts`).
+// They are written here byte by byte, apart from the product's own reader and writer, so neither can agree with a
+// mistake of the other.
+
+/** One pixel as red, green, blue and alpha, each 0–255. */
+export type Pixel = readonly [number, number, number, number]
+
+type Paint = (x: number, y: number) => Pixel
+
+/** A square PNG file of the pixels `paint` gives. */
+export function pngSample(size: number, paint: Paint) {
+ const header = Buffer.alloc(13)
+ header.writeUInt32BE(size, 0)
+ header.writeUInt32BE(size, 4)
+ // 8 bits a channel, RGBA.
+ header.set([8, 6, 0, 0, 0], 8)
+
+ const rows = Array.from({ length: size }, (_, y) => [0, ...Array.from({ length: size }, (_, x) => [...paint(x, y)]).flat()])
+
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk("IHDR", header),
+ chunk("IDAT", deflateSync(Buffer.from(rows.flat()))),
+ chunk("IEND", Buffer.alloc(0)),
+ ])
+}
+
+function chunk(type: string, data: Buffer) {
+ const body = Buffer.concat([Buffer.from(type, "latin1"), data])
+ const frame = Buffer.alloc(8)
+ frame.writeUInt32BE(data.length, 0)
+ frame.writeUInt32BE(crc32(body), 4)
+
+ return Buffer.concat([frame.subarray(0, 4), body, frame.subarray(4)])
+}
+
+/**
+ * An `.ico` file of several images. An image given as `png` is stored as that PNG file, as large icons are; any other
+ * is a Windows bitmap of `bits` a pixel with its transparency mask, as most sites' `favicon.ico` holds. A bitmap of 8
+ * bits or fewer keeps a color table, so `paint` may give at most that many colors.
+ */
+export function icoSample(images: readonly ({ size: number; png: Buffer } | { size: number; bits: 1 | 4 | 8 | 24 | 32; paint: Paint })[]) {
+ const files = images.map((image) => ("png" in image ? image.png : bitmap(image.size, image.bits, image.paint)))
+ const directory = Buffer.alloc(6 + images.length * 16)
+ directory.writeUInt16LE(1, 2)
+ directory.writeUInt16LE(images.length, 4)
+ images.forEach((image, index) => {
+ const entry = 6 + index * 16
+ const bits = "png" in image ? 32 : image.bits
+ // A width or height of 256 is written as 0.
+ directory.set([image.size & 255, image.size & 255, bits <= 8 ? (1 << bits) & 255 : 0, 0], entry)
+ directory.writeUInt16LE(1, entry + 4)
+ directory.writeUInt16LE(bits, entry + 6)
+ directory.writeUInt32LE(files[index]?.length ?? 0, entry + 8)
+ directory.writeUInt32LE(directory.length + files.slice(0, index).reduce((sum, file) => sum + file.length, 0), entry + 12)
+ })
+
+ return Buffer.concat([directory, ...files])
+}
+
+// A device-independent bitmap as an icon holds it: its header, color table, the pixel rows bottom-up, then one bit a
+// pixel that is set where the icon is transparent. Every row is padded to four bytes.
+function bitmap(size: number, bits: 1 | 4 | 8 | 24 | 32, paint: Paint) {
+ const pixels = Array.from({ length: size }, (_, row) => Array.from({ length: size }, (_, x) => paint(x, size - 1 - row)))
+ const colors = bits <= 8 ? [...new Set(pixels.flat().map((pixel) => pixel.slice(0, 3).join()))] : []
+ const header = Buffer.alloc(40)
+ header.writeUInt32LE(40, 0)
+ header.writeInt32LE(size, 4)
+ // The pixel rows and the mask rows together.
+ header.writeInt32LE(size * 2, 8)
+ header.writeUInt16LE(1, 12)
+ header.writeUInt16LE(bits, 14)
+ const table = Buffer.alloc(bits <= 8 ? (1 << bits) * 4 : 0)
+ colors.forEach((color, index) => {
+ const [red = 0, green = 0, blue = 0] = color.split(",").map(Number)
+ table.set([blue, green, red, 0], index * 4)
+ })
+
+ const rows = pixels.map((row) => {
+ const line = Buffer.alloc((((size * bits + 31) >> 5) << 2))
+ row.forEach((pixel, x) => {
+ const [red, green, blue, alpha] = pixel
+
+ if (bits === 32) return void line.set([blue, green, red, alpha], x * 4)
+
+ if (bits === 24) return void line.set([blue, green, red], x * 3)
+ const index = colors.indexOf(pixel.slice(0, 3).join())
+ const at = (x * bits) >> 3
+ line[at] = (line[at] ?? 0) | (index << (8 - bits - ((x * bits) & 7)))
+ })
+
+ return line
+ })
+
+ const mask = pixels.map((row) => {
+ const line = Buffer.alloc(((size + 31) >> 5) << 2)
+ row.forEach((pixel, x) => {
+ if (pixel[3] === 0) line[x >> 3] = (line[x >> 3] ?? 0) | (0x80 >> (x & 7))
+ })
+
+ return line
+ })
+
+ return Buffer.concat([header, table, ...rows, ...mask])
+}
+
+/** A page's own vector icon, as modern sites list one. */
+export const svgSample = ``
diff --git a/packages/gui-plugins/src/browser/icon.ts b/packages/gui-plugins/src/browser/icon.ts
index fbc0de2d42b..0a9dea7db9a 100644
--- a/packages/gui-plugins/src/browser/icon.ts
+++ b/packages/gui-plugins/src/browser/icon.ts
@@ -1,4 +1,5 @@
import { nativeImage } from "electron"
+import { ICON_SIZE, iconImage } from "./icon-image"
import { MAX_ICON_URL } from "./ipc"
import type { BrowserNetwork } from "./network"
@@ -6,7 +7,7 @@ type Fetched = { mime: string; data: Buffer }
/**
* The first of a page's icon candidates that loads, as a data URL small enough to report and store. An SVG stays as
- * it is; any other format is redrawn as a PNG of at most 32px, which also drops anything that is not an image. Never
+ * it is; a PNG, a JPEG or an `.ico` file is redrawn as a PNG of at most 32px, and anything else is no icon. Never
* rejects: a candidate that fails falls through to the next.
*/
export function loadIcon(candidates: readonly string[], network: BrowserNetwork | null) {
@@ -52,16 +53,18 @@ function encode(fetched: Fetched) {
return url.length <= MAX_ICON_URL ? url : undefined
}
- const image = nativeImage.createFromBuffer(fetched.data)
+ // `nativeImage` reads PNG and JPEG only, and most sites serve an .ico file.
+ const file = iconImage(fetched.data)
+ const image = file && nativeImage.createFromBuffer(file)
- if (image.isEmpty()) return
+ if (!image || image.isEmpty()) return
const size = image.getSize()
// The longer side fits 32px; resizing one side keeps the shape.
const fitted =
- Math.max(size.width, size.height) <= 32
+ Math.max(size.width, size.height) <= ICON_SIZE
? image
- : image.resize(size.width >= size.height ? { width: 32, quality: "best" } : { height: 32, quality: "best" })
+ : image.resize(size.width >= size.height ? { width: ICON_SIZE, quality: "best" } : { height: ICON_SIZE, quality: "best" })
const url = fitted.toDataURL()