From e23b6ee6c425fcdef3c48fe691a53ead9ccd2438 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Thu, 19 Nov 2026 17:14:22 -0700 Subject: [PATCH] Add rotation calibration and millimetre rulers on the calibration sheet A new rotation setting turns the whole print about the sheet centre, in steps of 0.01 degree, on card sheets and the calibration sheet. The calibration sheet now has millimetre rulers at every card edge; the four lettered ones (A to D) are typed into Settings, which converts them into corrected offsets and rotation. A simulation test checks the conversion against modelled printer errors. Co-Authored-By: Claude Fable 5.2 --- src/server/app.test.ts | 14 ++-- src/server/app.ts | 11 +-- src/server/db.test.ts | 25 ++++++- src/server/db.ts | 2 +- src/server/pdf/layout.test.ts | 117 +++++++++++++++++++++++++++++--- src/server/pdf/layout.ts | 39 +++++++---- src/server/pdf/render.test.ts | 4 +- src/server/pdf/render.ts | 97 ++++++++++++++++++++++---- src/shared/calibration.ts | 23 +++++++ src/shared/sheet.ts | 83 ++++++++++++++++++++++ src/shared/types.ts | 3 +- src/web/components/Settings.tsx | 44 ++++++++++-- src/web/styles.css | 2 + 13 files changed, 410 insertions(+), 54 deletions(-) create mode 100644 src/shared/calibration.ts create mode 100644 src/shared/sheet.ts diff --git a/src/server/app.test.ts b/src/server/app.test.ts index 5d43bbb..ac45934 100644 --- a/src/server/app.test.ts +++ b/src/server/app.test.ts @@ -148,10 +148,16 @@ test('print passes cards in shelf order and honours start; confirm clears queue' test('settings clamp and calibration pdf', async () => { const { req } = setup(); - assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 0, offsetYmm: 0 }); - const s = await (await req('PUT', '/api/settings', { offsetXmm: 50, offsetYmm: -50 })).json(); - assert.deepEqual(s, { offsetXmm: 10, offsetYmm: -10 }); - assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 10, offsetYmm: -10 }); + assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 }); + const s = await (await req('PUT', '/api/settings', { offsetXmm: 50, offsetYmm: -50, rotationDeg: 9 })).json(); + assert.deepEqual(s, { offsetXmm: 10, offsetYmm: -10, rotationDeg: 3 }); + assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 10, offsetYmm: -10, rotationDeg: 3 }); + assert.deepEqual(await (await req('PUT', '/api/settings', { offsetXmm: 0.05, offsetYmm: 0, rotationDeg: -0.01 })).json(), + { offsetXmm: 0.05, offsetYmm: 0, rotationDeg: -0.01 }); + assert.equal((await (await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 2, rotationDeg: -7 })).json() as any).rotationDeg, -3); + // a body without rotationDeg leaves the stored rotation alone + assert.deepEqual(await (await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 2 })).json(), { offsetXmm: 1, offsetYmm: 2, rotationDeg: -3 }); + assert.equal((await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 1, rotationDeg: 'x' })).status, 400); assert.equal((await req('PUT', '/api/settings', { offsetXmm: 'a', offsetYmm: 1 })).status, 400); assert.equal(await (await req('GET', '/api/calibration.pdf')).text(), '%PDF-cal'); }); diff --git a/src/server/app.ts b/src/server/app.ts index 8c71d1b..1f9efb3 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { Hono } from 'hono'; import type { Context } from 'hono'; import { displayAuthors } from '../shared/names.ts'; +import { OFFSET_LIMIT_MM, ROTATION_LIMIT_DEG } from '../shared/sheet.ts'; import type { Book, CardData, Hierarchy, SearchResult, Settings } from '../shared/types.ts'; import { normalizeIsbn } from '../shared/isbn.ts'; import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts'; @@ -310,11 +311,13 @@ export function createApp(deps: AppDeps): Hono { app.put('/api/settings', async (c) => { const b = await body(c); - const clamp = (v: unknown): number => { - if (typeof v !== 'number' || !Number.isFinite(v)) throw new HttpError(400, 'Offsets must be numbers'); - return Math.max(-10, Math.min(10, v)); + const clamp = (v: unknown, limit: number): number => { + if (typeof v !== 'number' || !Number.isFinite(v)) throw new HttpError(400, 'Offsets and rotation must be numbers'); + return Math.max(-limit, Math.min(limit, v)); }; - const s: Settings = { offsetXmm: clamp(b.offsetXmm), offsetYmm: clamp(b.offsetYmm) }; + // A body without rotationDeg leaves the stored rotation unchanged. + const rotationDeg = b.rotationDeg === undefined ? db.getSettings().rotationDeg : clamp(b.rotationDeg, ROTATION_LIMIT_DEG); + const s: Settings = { offsetXmm: clamp(b.offsetXmm, OFFSET_LIMIT_MM), offsetYmm: clamp(b.offsetYmm, OFFSET_LIMIT_MM), rotationDeg }; db.putSettings(s); return c.json(s); }); diff --git a/src/server/db.test.ts b/src/server/db.test.ts index 60f7b27..afdab12 100644 --- a/src/server/db.test.ts +++ b/src/server/db.test.ts @@ -51,15 +51,34 @@ test('updateBook round-trips fields', () => { test('settings and cache', () => { const db = openDb(':memory:'); - assert.deepEqual(db.getSettings(), { offsetXmm: 0, offsetYmm: 0 }); - db.putSettings({ offsetXmm: 1.5, offsetYmm: -2 }); - assert.deepEqual(db.getSettings(), { offsetXmm: 1.5, offsetYmm: -2 }); + assert.deepEqual(db.getSettings(), { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 }); + db.putSettings({ offsetXmm: 1.5, offsetYmm: -2.05, rotationDeg: 0.37 }); + assert.deepEqual(db.getSettings(), { offsetXmm: 1.5, offsetYmm: -2.05, rotationDeg: 0.37 }); assert.equal(db.cache.get('k'), null); db.cache.set('k', 'v'); db.cache.set('k', 'w'); assert.equal(db.cache.get('k'), 'w'); }); +test('settings saved before rotation existed read rotation as 0', async () => { + const { DatabaseSync } = await import('node:sqlite'); + const { mkdtempSync, rmSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'booksorter-settings-')); + try { + const path = join(dir, 'old.db'); + const first = openDb(path); + first.close(); + const raw = new DatabaseSync(path); + raw.prepare("INSERT INTO settings (key, value) VALUES ('settings', ?)").run(JSON.stringify({ offsetXmm: -2.7, offsetYmm: 0.5 })); + raw.close(); + const db = openDb(path); + assert.deepEqual(db.getSettings(), { offsetXmm: -2.7, offsetYmm: 0.5, rotationDeg: 0 }); + db.close(); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + test('a database made before the hierarchy tail gets the column; old books read as not looked for', async () => { const { DatabaseSync } = await import('node:sqlite'); const { mkdtempSync, rmSync } = await import('node:fs'); diff --git a/src/server/db.ts b/src/server/db.ts index 334b1fb..4430047 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -70,7 +70,7 @@ function toBook(r: Row): Book { }; } -const DEFAULT_SETTINGS: Settings = { offsetXmm: 0, offsetYmm: 0 }; +const DEFAULT_SETTINGS: Settings = { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 }; export function openDb(path: string): Db { if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true }); diff --git a/src/server/pdf/layout.test.ts b/src/server/pdf/layout.test.ts index b46e9a7..d9d0673 100644 --- a/src/server/pdf/layout.test.ts +++ b/src/server/pdf/layout.test.ts @@ -1,15 +1,18 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { cardMatrix, CARD } from './layout.ts'; +import { cardMatrix, cropMarks, CARD, RULERS, rulerById, rulerPoint, placePoint, SHEET } from './layout.ts'; +import { applyReadings } from '../../shared/calibration.ts'; +import { DEG_PER_MM_AB, DISTANCE_AB_MM } from '../../shared/sheet.ts'; +import type { Settings } from '../../shared/types.ts'; -const zero = { offsetXmm: 0, offsetYmm: 0 }; +const zero = { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 }; const mm = 72 / 25.4; test('matrix values and offsets', () => { assert.deepEqual(cardMatrix(1, zero), [0, 1, -1, 0, 486, 504]); assert.equal(cardMatrix(3, zero)[5], 72); - assert.ok(Math.abs(cardMatrix(1, { offsetXmm: 1, offsetYmm: 0 })[4] - (486 + mm)) < 1e-9); - assert.ok(Math.abs(cardMatrix(1, { offsetXmm: 0, offsetYmm: 1 })[5] - (504 - mm)) < 1e-9); + assert.ok(Math.abs(cardMatrix(1, { ...zero, offsetXmm: 1 })[4] - (486 + mm)) < 1e-9); + assert.ok(Math.abs(cardMatrix(1, { ...zero, offsetYmm: 1 })[5] - (504 - mm)) < 1e-9); }); test('corners map to the sheet rectangles', () => { @@ -29,7 +32,7 @@ test('corners map to the sheet rectangles', () => { test('cropMarks: 12 segments at the expected places with zero offsets', async () => { const { cropMarks } = await import('./layout.ts'); - const m = cropMarks({ offsetXmm: 0, offsetYmm: 0 }); + const m = cropMarks(zero); assert.equal(m.length, 12); assert.equal(m.filter((s) => s.y1 === s.y2).length, 8); assert.equal(m.filter((s) => s.x1 === s.x2).length, 4); @@ -41,10 +44,10 @@ test('cropMarks: 12 segments at the expected places with zero offsets', async () test('cropMarks move with the offsets like the cards, and never enter a card', async () => { const { cropMarks, cardMatrix } = await import('./layout.ts'); - const s = { offsetXmm: 1.5, offsetYmm: -2.25 }; - const z = cropMarks({ offsetXmm: 0, offsetYmm: 0 }); + const s = { ...zero, offsetXmm: 1.5, offsetYmm: -2.25 }; + const z = cropMarks(zero); const o = cropMarks(s); - const [, , , , ex0, ey0] = cardMatrix(1, { offsetXmm: 0, offsetYmm: 0 }); + const [, , , , ex0, ey0] = cardMatrix(1, zero); const [, , , , ex1, ey1] = cardMatrix(1, s); z.forEach((a, i) => { assert.ok(Math.abs(o[i].x1 - a.x1 - (ex1 - ex0)) < 1e-9); @@ -59,3 +62,101 @@ test('cropMarks move with the offsets like the cards, and never enter a card', a assert.ok(!(inX && inY)); } }); + +test('rotation 0 leaves the matrix and crop marks exactly as before', () => { + const s = { offsetXmm: 1.25, offsetYmm: -0.75, rotationDeg: 0 }; + assert.deepEqual(cardMatrix(2, s), [0, 1, -1, 0, 486 + 1.25 * mm, 288 + 0.75 * mm]); + const m = cropMarks(s); + assert.deepEqual(m[0], { x1: 104 + 1.25 * mm, y1: 72 + 0.75 * mm, x2: 122 + 1.25 * mm, y2: 72 + 0.75 * mm }); + assert.deepEqual(m[8], { x1: 126 + 1.25 * mm, y1: 50 + 0.75 * mm, x2: 126 + 1.25 * mm, y2: 68 + 0.75 * mm }); +}); + +test('a positive rotation turns the print clockwise: right of centre goes down, top goes right', () => { + const s = { ...zero, rotationDeg: 1 }; + const [rx, ry] = placePoint(s, 406, 396); + assert.ok(ry < 396 && rx < 406 && rx > 405.9); + const [tx, ty] = placePoint(s, 306, 496); + assert.ok(tx > 306 && ty < 496); + assert.deepEqual(placePoint(s, 306, 396).map(Math.round), [306, 396]); + // the card matrix agrees with the sheet transform: card corner (0,0) lands where its plain place lands + const [, , , , e, f] = cardMatrix(1, s); + const [px, py] = placePoint(s, 486, 504); + assert.ok(Math.abs(e - px) < 1e-9 && Math.abs(f - py) < 1e-9); +}); + +test('ruler geometry: A and B are the two ends of the card-top line, C and D of one boundary', () => { + const [A, B, C, D] = (['A', 'B', 'C', 'D'] as const).map(rulerById); + assert.equal(A!.edge, 126); assert.equal(B!.edge, 126); + assert.ok(A!.centre.y > 720 && B!.centre.y < 72); + assert.equal(C!.edge, 288); assert.equal(D!.edge, 288); + assert.ok(C!.centre.x < 126 && D!.centre.x > 486); + assert.equal(RULERS.length, 12); + assert.ok(Math.abs(DISTANCE_AB_MM - 237.8) < 0.1); + assert.ok(Math.abs(DEG_PER_MM_AB - 0.241) < 0.001); +}); + +// ---- Simulation: does a printer error get corrected by the readings? ---- +// Printer error E: the whole printed page is turned clockwise by phi (degrees) about `pivot`, then shifted by (sx, sy) mm +// (sheet x right, y up). Written out here from first principles, independent of the layout code. +interface Err { phi: number; pivot: [number, number]; sx: number; sy: number } +function printed(e: Err, [x, y]: [number, number]): [number, number] { + const t = -e.phi * Math.PI / 180; // clockwise with y up is a negative mathematical angle + const px = x - e.pivot[0], py = y - e.pivot[1]; + return [e.pivot[0] + px * Math.cos(t) - py * Math.sin(t) + e.sx * mm, e.pivot[1] + px * Math.sin(t) + py * Math.cos(t) + e.sy * mm]; +} + +/** Reading on a printed ruler: the label where the fixed perforation line crosses the printed ruler's centre line. */ +function reading(s: Settings, e: Err, id: 'A' | 'B' | 'C' | 'D'): number { + const r = rulerById(id); + const coord = (k: number) => printed(e, placePoint(s, ...rulerPoint(r, k)))[r.axis === 'x' ? 0 : 1]; + const c0 = coord(0), c1 = coord(1); // affine in k + return (r.edge - c0) / (c1 - c0); +} + +function cornersAfter(s: Settings, e: Err): [number, number][] { + const out: [number, number][] = []; + for (const p of [1, 2, 3] as const) { + const [a, b, c, d, tx, ty] = cardMatrix(p, s); + for (const [x, y] of [[0, 0], [CARD.width, 0], [0, CARD.height], [CARD.width, CARD.height]] as const) { + out.push(printed(e, [a * x + c * y + tx, b * x + d * y + ty])); + } + } + return out; +} + +const cases: [string, Settings, Err][] = [ + ['shift only', zero, { phi: 0, pivot: [306, 396], sx: 1.3, sy: -0.8 }], + ['shift only, other way', zero, { phi: 0, pivot: [306, 396], sx: -2.1, sy: 1.6 }], + ['rotation only, clockwise', zero, { phi: 0.35, pivot: [306, 396], sx: 0, sy: 0 }], + ['rotation only, anticlockwise', zero, { phi: -0.35, pivot: [306, 396], sx: 0, sy: 0 }], + ['rotation and shift, pivot off centre', zero, { phi: 0.3, pivot: [40, 700], sx: 0.7, sy: -1.1 }], + ['rotation and shift, other pivot', zero, { phi: -0.4, pivot: [580, 90], sx: -1.5, sy: 0.9 }], + ['non-zero current settings', { offsetXmm: -2.7, offsetYmm: 0.4, rotationDeg: 0.1 }, { phi: 0.35, pivot: [100, 300], sx: -2.7, sy: 0.9 }], + ['non-zero current settings, opposite', { offsetXmm: 1.8, offsetYmm: -1.2, rotationDeg: -0.2 }, { phi: -0.25, pivot: [500, 650], sx: 1.8, sy: -1.2 }], +]; + +for (const [name, current, err] of cases) { + test(`readings-to-settings simulation: ${name}`, () => { + const r = { a: reading(current, err, 'A'), b: reading(current, err, 'B'), c: reading(current, err, 'C'), d: reading(current, err, 'D') }; + const next = applyReadings(current, r); + const truth = cornersAfter(zero, { phi: 0, pivot: [0, 0], sx: 0, sy: 0 }); + const got = cornersAfter(next, err); + got.forEach(([x, y], i) => { + assert.ok(Math.hypot(x - truth[i]![0], y - truth[i]![1]) < 0.2 * mm, `corner ${i}: off by ${(Math.hypot(x - truth[i]![0], y - truth[i]![1]) / mm).toFixed(3)} mm`); + }); + // and a second round converges further + const again = applyReadings(next, { a: reading(next, err, 'A'), b: reading(next, err, 'B'), c: reading(next, err, 'C'), d: reading(next, err, 'D') }); + cornersAfter(again, err).forEach(([x, y], i) => assert.ok(Math.hypot(x - truth[i]![0], y - truth[i]![1]) < 0.2 * mm)); + }); +} + +test('applyReadings rounds, clamps, and signs the rotation', () => { + const out = applyReadings({ offsetXmm: 9.9, offsetYmm: 0, rotationDeg: 2.99 }, { a: 1, b: 1, c: 0.1, d: 0.12 }); + assert.equal(out.offsetXmm, 10); + assert.equal(out.offsetYmm, 0.1); + assert.equal(out.rotationDeg, 2.99); + const turned = applyReadings(zero, { a: -1, b: 1, c: 0, d: 0 }); // print turned clockwise: A reads low, B high + assert.equal(turned.offsetXmm, 0); + assert.equal(turned.rotationDeg, -0.48); + assert.ok(SHEET.width > 0); +}); diff --git a/src/server/pdf/layout.ts b/src/server/pdf/layout.ts index ecb10ea..e6b1dd8 100644 --- a/src/server/pdf/layout.ts +++ b/src/server/pdf/layout.ts @@ -1,38 +1,49 @@ import type { Settings } from '../../shared/types.ts'; +import { PT_PER_MM, placePoint, sheetMatrix } from '../../shared/sheet.ts'; +import type { Matrix } from '../../shared/sheet.ts'; + +export { sheetMatrix, placePoint, RULERS, rulerById, rulerPoint } from '../../shared/sheet.ts'; +export type { Matrix } from '../../shared/sheet.ts'; export const SHEET = { width: 612, height: 792 }; export const CARD = { width: 216, height: 360 }; // card-local, upright const Y_BOTTOM = { 1: 504, 2: 288, 3: 72 } as const; -const PT_PER_MM = 72 / 25.4; -export type Matrix = [number, number, number, number, number, number]; - -/** Quarter turn anticlockwise: card-local (x, y) maps to sheet (486 + dx - y, yBottom - dy + x). */ +/** + * Card-local (x, y) maps to sheet (486 - y, yBottom + x) (a quarter turn anticlockwise), and then the sheet transform + * (rotation about the sheet centre, then the offsets) is applied to that. + */ export function cardMatrix(position: 1 | 2 | 3, s: Settings): Matrix { - const dx = s.offsetXmm * PT_PER_MM; - const dy = s.offsetYmm * PT_PER_MM; - return [0, 1, -1, 0, 486 + dx, Y_BOTTOM[position] - dy]; + if (!s.rotationDeg) { + return [0, 1, -1, 0, 486 + s.offsetXmm * PT_PER_MM, Y_BOTTOM[position] - s.offsetYmm * PT_PER_MM]; + } + const [a, b, c, d, e, f] = sheetMatrix(s); + // total = sheet matrix after the plain quarter turn [0 1 -1 0 486 yb] + return [c, d, -a, -b, a * 486 + c * Y_BOTTOM[position] + e, b * 486 + d * Y_BOTTOM[position] + f]; } export interface Segment { x1: number; y1: number; x2: number; y2: number } /** - * Crop marks in sheet coordinates, shifted by the calibration offsets exactly like the cards. + * Crop marks in sheet coordinates, moved by the sheet transform exactly like the cards. * Horizontal ticks sit in the left and right strips at each card boundary; vertical ticks sit in the * bottom and top strips at each card edge. Every tick is 18 pt long and ends 4 pt short of the card area. */ export function cropMarks(s: Settings): Segment[] { - const dx = s.offsetXmm * PT_PER_MM; - const dy = s.offsetYmm * PT_PER_MM; + const seg = (x1: number, y1: number, x2: number, y2: number): Segment => { + const [px1, py1] = placePoint(s, x1, y1); + const [px2, py2] = placePoint(s, x2, y2); + return { x1: px1, y1: py1, x2: px2, y2: py2 }; + }; const out: Segment[] = []; for (const y of [72, 288, 504, 720]) { - out.push({ x1: 104 + dx, y1: y - dy, x2: 122 + dx, y2: y - dy }); - out.push({ x1: 490 + dx, y1: y - dy, x2: 508 + dx, y2: y - dy }); + out.push(seg(104, y, 122, y)); + out.push(seg(490, y, 508, y)); } for (const x of [126, 486]) { - out.push({ x1: x + dx, y1: 50 - dy, x2: x + dx, y2: 68 - dy }); - out.push({ x1: x + dx, y1: 724 - dy, x2: x + dx, y2: 742 - dy }); + out.push(seg(x, 50, x, 68)); + out.push(seg(x, 724, x, 742)); } return out; } diff --git a/src/server/pdf/render.test.ts b/src/server/pdf/render.test.ts index 378e05a..cdb308e 100644 --- a/src/server/pdf/render.test.ts +++ b/src/server/pdf/render.test.ts @@ -4,7 +4,7 @@ import { PDFDocument, PrintScaling } from 'pdf-lib'; import { renderCardsPdf, renderCalibrationPdf } from './render.ts'; import type { CardData } from '../../shared/types.ts'; -const zero = { offsetXmm: 0, offsetYmm: 0 }; +const zero = { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 }; const card: CardData = { callNumber: 'QA76.73.R87 K53 2018', hierarchy: { outline: ['Science', 'Mathematics'], tail: [] }, title: 'The Rust Programming Language', authors: ['Steve Klabnik'], publisher: 'No Starch Press', @@ -26,7 +26,7 @@ test('unsupported characters render without throwing', async () => { }); test('calibration page renders one page', async () => { - const bytes = await renderCalibrationPdf({ offsetXmm: 0.5, offsetYmm: -0.3 }); + const bytes = await renderCalibrationPdf({ offsetXmm: 0.5, offsetYmm: -0.3, rotationDeg: 0.35 }); assert.equal((await PDFDocument.load(bytes)).getPageCount(), 1); }); diff --git a/src/server/pdf/render.ts b/src/server/pdf/render.ts index e94adfc..6617fc3 100644 --- a/src/server/pdf/render.ts +++ b/src/server/pdf/render.ts @@ -1,12 +1,14 @@ import { readFile } from 'node:fs/promises'; import { createRequire } from 'node:module'; import path from 'node:path'; -import { PDFDocument, PrintScaling, rgb, pushGraphicsState, popGraphicsState, concatTransformationMatrix } from 'pdf-lib'; +import { PDFDocument, PrintScaling, degrees, rgb, pushGraphicsState, popGraphicsState, concatTransformationMatrix } from 'pdf-lib'; import type { PDFFont, PDFPage } from 'pdf-lib'; import fontkit from '@pdf-lib/fontkit'; import type { CardData, Settings } from '../../shared/types.ts'; import { layoutCard, MARGIN_X, TEXT_WIDTH } from './card.ts'; -import { SHEET, CARD, cardMatrix, cropMarks } from './layout.ts'; +import { SHEET, CARD, cardMatrix, cropMarks, sheetMatrix, RULERS } from './layout.ts'; +import { PT_PER_MM, RULER_HASH, RULER_RANGE_MM } from '../../shared/sheet.ts'; +import type { Ruler } from '../../shared/sheet.ts'; interface Fonts { regular: PDFFont; bold: PDFFont; has: (cp: number) => boolean } @@ -121,6 +123,65 @@ function drawScaleCheck(page: PDFPage, fonts: Fonts) { page.drawText(line, { x: x0, y: ty, size: 8, font: fonts.regular }); } +const NUM_SIZE = 5, LETTER_SIZE = 10, CAP = 0.73; + +function signed(n: number): string { + return n === 0 ? '0' : (n > 0 ? '+' : '\u2212') + Math.abs(n); +} + +/** + * One millimetre ruler in nominal sheet coordinates (the caller has applied the sheet transform). Text runs upward + * on the sheet, like the card text, so it reads upright when the cards are held upright. + */ +function drawRuler(page: PDFPage, r: Ruler, fonts: Fonts) { + const black = rgb(0, 0, 0); + const base = { x: r.centre.x + r.outward.x * RULER_HASH.zero / 2, y: r.centre.y + r.outward.y * RULER_HASH.zero / 2 }; + const point = (k: number) => ({ x: r.centre.x + r.dir.x * k * PT_PER_MM, y: r.centre.y + r.dir.y * k * PT_PER_MM }); + for (let h = -2 * RULER_RANGE_MM; h <= 2 * RULER_RANGE_MM; h++) { + const k = h / 2; + const len = k === 0 ? RULER_HASH.zero : Math.abs(k) === 5 ? RULER_HASH.five : h % 2 === 0 ? RULER_HASH.mm : RULER_HASH.half; + const p = point(k); + const hx = p.x + (r.dir.x === 0 ? base.x - r.centre.x : 0), hy = p.y + (r.dir.y === 0 ? base.y - r.centre.y : 0); + page.drawLine({ + start: { x: hx, y: hy }, end: { x: hx - r.outward.x * len, y: hy - r.outward.y * len }, thickness: 0.3, color: black, + }); + } + const up = degrees(90); + for (const k of [-5, 0, 5]) { + const text = signed(k); + const w = fonts.regular.widthOfTextAtSize(text, NUM_SIZE); + const p = point(k), cap = NUM_SIZE * CAP; + if (r.axis === 'x') { + // Hashes are vertical lines; the number sits just outside the base, centred on the hash. + page.drawText(text, { x: p.x + cap / 2, y: r.outward.y > 0 ? base.y + 2 : base.y - 2 - w, size: NUM_SIZE, font: fonts.regular, rotate: up }); + } else { + page.drawText(text, { x: r.outward.x < 0 ? base.x - 2 : base.x + 2 + cap, y: p.y - w / 2, size: NUM_SIZE, font: fonts.regular, rotate: up }); + } + } + if (r.id) { + const w = fonts.bold.widthOfTextAtSize(r.id, LETTER_SIZE), cap = LETTER_SIZE * CAP; + const reach = RULER_RANGE_MM * PT_PER_MM + 5; + if (r.axis === 'x') { + page.drawText(r.id, { x: r.centre.x - reach, y: r.centre.y - w / 2, size: LETTER_SIZE, font: fonts.bold, rotate: up }); + } else { + page.drawText(r.id, { x: r.centre.x + cap / 2, y: r.centre.y + reach, size: LETTER_SIZE, font: fonts.bold, rotate: up }); + } + } +} + +function wrap(fonts: Fonts, text: string, size: number, width: number): string[] { + const lines: string[] = []; + let line = ''; + for (const w of text.split(' ')) { + const next = line ? line + ' ' + w : w; + if (fonts.regular.widthOfTextAtSize(next, size) > width && line) { lines.push(line); line = w; } else line = next; + } + lines.push(line); + return lines; +} + +const trim = (n: number, digits: number) => String(+n.toFixed(digits)); + export async function renderCalibrationPdf(s: Settings): Promise { const { doc, fonts } = await setup(); const page = doc.addPage([SHEET.width, SHEET.height]); @@ -133,20 +194,30 @@ export async function renderCalibrationPdf(s: Settings): Promise { page.drawLine({ start: { x: cx - 8, y: cy }, end: { x: cx + 8, y: cy }, thickness: 0.5, color: rgb(0, 0, 0) }); page.drawLine({ start: { x: cx, y: cy - 8 }, end: { x: cx, y: cy + 8 }, thickness: 0.5, color: rgb(0, 0, 0) }); if (pos === 1) { - // Wrapped to fit the 188 pt text width; the message text itself is unchanged. - const msg = `Calibration: hold against an Avery 5388 sheet. Offset X ${s.offsetXmm} mm, Y ${s.offsetYmm} mm.`; - const words = msg.split(' '); - let line = '', y = CARD.height - 30; - for (const w of words) { - const next = line ? line + ' ' + w : w; - if (fonts.regular.widthOfTextAtSize(next, 8) > TEXT_WIDTH && line) { - page.drawText(line, { x: MARGIN_X, y, size: 8, font: fonts.regular }); y -= 10; line = w; - } else line = next; - } - page.drawText(line, { x: MARGIN_X, y, size: 8, font: fonts.regular }); + const steps = [ + 'Calibration page', + '1. Print at 100% scale (Actual size).', + '2. Hold this page over a card sheet against a light, or print it on a card sheet.', + '3. At each lettered ruler (A, B, C, D) read the number where the perforation crosses it, to the nearest quarter millimetre.', + '4. Type A, B, C and D into Settings and press Apply readings.', + '5. Print this page again to check.', + ]; + let y = CARD.height - 30; + steps.forEach((step, i) => { + for (const line of wrap(fonts, step, 8, TEXT_WIDTH)) { + page.drawText(line, { x: MARGIN_X, y, size: 8, font: i === 0 ? fonts.bold : fonts.regular }); y -= 10; + } + y -= 2; + }); + const now = `Printed with Offset X ${trim(s.offsetXmm, 3)} mm, Offset Y ${trim(s.offsetYmm, 3)} mm, Rotation ${s.rotationDeg.toFixed(2)}\u00b0`; + let ty = 40; + for (const line of wrap(fonts, now, 8, TEXT_WIDTH)) { page.drawText(line, { x: MARGIN_X, y: ty, size: 8, font: fonts.regular }); ty -= 10; } } }); } + page.pushOperators(pushGraphicsState(), concatTransformationMatrix(...sheetMatrix(s))); + for (const r of RULERS) drawRuler(page, r, fonts); + page.pushOperators(popGraphicsState()); drawScaleCheck(page, fonts); return doc.save(); } diff --git a/src/shared/calibration.ts b/src/shared/calibration.ts new file mode 100644 index 0000000..0741317 --- /dev/null +++ b/src/shared/calibration.ts @@ -0,0 +1,23 @@ +import { DEG_PER_MM_AB, OFFSET_LIMIT_MM, ROTATION_LIMIT_DEG } from './sheet.ts'; +import type { Settings } from './types.ts'; + +export interface Readings { a: number; b: number; c: number; d: number } + +function snap(v: number, step: number, limit: number): number { + const r = Number((Math.round(v / step) * step).toFixed(4)); + return Math.max(-limit, Math.min(limit, r)) + 0; // + 0 turns -0 into 0 +} + +/** + * Turn four ruler readings from the calibration sheet into corrected settings. The sheet was printed with `settings` + * applied, so each reading is the amount still to add. A (top end) and B (bottom end) of the card-top line measure + * Offset X; the print is turned clockwise exactly when A reads lower than B, so rotation grows by (a - b) * F. + * C and D are the two ends of one card boundary and measure Offset Y. + */ +export function applyReadings(settings: Settings, r: Readings): Settings { + return { + offsetXmm: snap(settings.offsetXmm + (r.a + r.b) / 2, 0.05, OFFSET_LIMIT_MM), + offsetYmm: snap(settings.offsetYmm + (r.c + r.d) / 2, 0.05, OFFSET_LIMIT_MM), + rotationDeg: snap(settings.rotationDeg + (r.a - r.b) * DEG_PER_MM_AB, 0.01, ROTATION_LIMIT_DEG), + }; +} diff --git a/src/shared/sheet.ts b/src/shared/sheet.ts new file mode 100644 index 0000000..d391231 --- /dev/null +++ b/src/shared/sheet.ts @@ -0,0 +1,83 @@ +import type { Settings } from './types.ts'; + +/** Geometry of the Avery 5388 sheet in PDF points (y points up), shared by the PDF code and the calibration maths. */ +export const PT_PER_MM = 72 / 25.4; +export const SHEET_CENTRE = { x: 306, y: 396 }; +export const OFFSET_LIMIT_MM = 10; +export const ROTATION_LIMIT_DEG = 3; + +export type Matrix = [number, number, number, number, number, number]; + +/** + * The one sheet transform: turn the whole page by `rotationDeg` about the sheet centre (positive = clockwise as seen on + * the printed sheet, which is a negative mathematical angle with y up), then shift by the offsets (dx added to x, + * dy subtracted from y). Returned as a PDF matrix. + */ +export function sheetMatrix(s: Settings): Matrix { + const dx = s.offsetXmm * PT_PER_MM; + const dy = s.offsetYmm * PT_PER_MM; + if (!s.rotationDeg) return [1, 0, 0, 1, dx, -dy]; + const th = -s.rotationDeg * Math.PI / 180; + const cos = Math.cos(th), sin = Math.sin(th); + const { x: cx, y: cy } = SHEET_CENTRE; + return [cos, sin, -sin, cos, cx - (cos * cx - sin * cy) + dx, cy - (sin * cx + cos * cy) - dy]; +} + +export function applyMatrix(m: Matrix, x: number, y: number): [number, number] { + return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]; +} + +/** Where a nominal sheet point ends up once the settings are applied. */ +export function placePoint(s: Settings, x: number, y: number): [number, number] { + return applyMatrix(sheetMatrix(s), x, y); +} + +/** + * A millimetre ruler on the calibration sheet. `centre` is the middle of its longest (zero) hash, nominal sheet + * coordinates. The hash for reading k sits at `centre + dir * k` millimetres and runs parallel to the card edge it + * measures (the line x = edge for axis 'x', y = edge for axis 'y'). `dir` is the sheet direction in which the printed + * numbers grow: the number is the amount to ADD to the matching setting. `outward` points at the nearest sheet edge. + */ +export interface Ruler { + id: 'A' | 'B' | 'C' | 'D' | null; + axis: 'x' | 'y'; + edge: number; + centre: { x: number; y: number }; + dir: { x: number; y: number }; + outward: { x: number; y: number }; +} + +/** Hash lengths in points: the zero hash, the +-5 hashes, other whole millimetres, and half millimetres. */ +export const RULER_HASH = { zero: 18, five: 13, mm: 9, half: 5 }; +export const RULER_RANGE_MM = 6; + +export const RULERS: Ruler[] = (() => { + const out: Ruler[] = []; + // Offset X rulers: on the card-top (x = 126) and card-bottom (x = 486) lines, in the top and bottom strips. + for (const edge of [126, 486]) { + const top = { id: edge === 126 ? 'A' as const : null, centre: { x: edge, y: 733 }, outward: { x: 0, y: 1 } }; + const bottom = { id: edge === 126 ? 'B' as const : null, centre: { x: edge, y: 59 }, outward: { x: 0, y: -1 } }; + for (const r of [top, bottom]) out.push({ ...r, axis: 'x', edge, dir: { x: 1, y: 0 } }); + } + // Offset Y rulers: on the four card boundaries, in the left and right strips. dy is subtracted from y, so labels grow downward. + for (const edge of [72, 288, 504, 720]) { + out.push({ id: edge === 288 ? 'C' : null, axis: 'y', edge, centre: { x: 69, y: edge }, dir: { x: 0, y: -1 }, outward: { x: -1, y: 0 } }); + out.push({ id: edge === 288 ? 'D' : null, axis: 'y', edge, centre: { x: 543, y: edge }, dir: { x: 0, y: -1 }, outward: { x: 1, y: 0 } }); + } + return out; +})(); + +export function rulerById(id: 'A' | 'B' | 'C' | 'D'): Ruler { + return RULERS.find((r) => r.id === id)!; +} + +/** Nominal sheet position of the point at reading `k` mm on a ruler's centre line. */ +export function rulerPoint(r: Ruler, k: number): [number, number] { + return [r.centre.x + r.dir.x * k * PT_PER_MM, r.centre.y + r.dir.y * k * PT_PER_MM]; +} + +const distAB = Math.hypot( + rulerById('A').centre.x - rulerById('B').centre.x, rulerById('A').centre.y - rulerById('B').centre.y); +/** Degrees of rotation that one millimetre of disagreement between readings A and B stands for. */ +export const DEG_PER_MM_AB = Math.atan(1 / (distAB / PT_PER_MM)) * 180 / Math.PI; +export const DISTANCE_AB_MM = distAB / PT_PER_MM; diff --git a/src/shared/types.ts b/src/shared/types.ts index 3ef3234..cd8f605 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -38,4 +38,5 @@ export interface CardData { title: string; authors: string[]; publisher: string | null; year: number | null; subjects: string[]; isbn13: string | null; approximate: boolean; } -export interface Settings { offsetXmm: number; offsetYmm: number } +/** Print position: offsets in mm, and a turn of the whole print in degrees (positive = clockwise as seen on the printed sheet). */ +export interface Settings { offsetXmm: number; offsetYmm: number; rotationDeg: number } diff --git a/src/web/components/Settings.tsx b/src/web/components/Settings.tsx index f18431a..281b01a 100644 --- a/src/web/components/Settings.tsx +++ b/src/web/components/Settings.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'preact/hooks'; import { api } from '../api.ts'; +import { applyReadings } from '../../shared/calibration.ts'; import { chooseCamera, useCamera } from '../camera.ts'; import { showError, showToast } from '../toast-store.ts'; import { Panel } from './Panel.tsx'; @@ -8,12 +9,18 @@ export function Settings({ onClose }: { onClose: () => void }) { const cam = useCamera(); const [x, setX] = useState('0'); const [y, setY] = useState('0'); + const [rot, setRot] = useState('0'); + const [reads, setReads] = useState({ a: '', b: '', c: '', d: '' }); const [loaded, setLoaded] = useState(false); const [busy, setBusy] = useState(false); + function show(s: { offsetXmm: number; offsetYmm: number; rotationDeg: number }) { + setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setRot(String(s.rotationDeg)); + } + useEffect(() => { api.getSettings() - .then(s => { setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setLoaded(true); }) + .then(s => { show(s); setLoaded(true); }) .catch(e => showError(`Could not load the printer settings: ${(e as Error).message}`)); }, []); @@ -21,13 +28,31 @@ export function Settings({ onClose }: { onClose: () => void }) { ev.preventDefault(); setBusy(true); try { - const s = await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0 }); - setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); + show(await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0, rotationDeg: Number(rot) || 0 })); showToast('Printer alignment saved'); } catch (e) { showError(`Could not save the alignment: ${(e as Error).message}`); } setBusy(false); } + async function applyRuler() { + setBusy(true); + try { + const n = (v: string) => Number(v) || 0; + const current = await api.getSettings(); + const next = applyReadings(current, { a: n(reads.a), b: n(reads.b), c: n(reads.c), d: n(reads.d) }); + show(await api.putSettings(next)); + setReads({ a: '', b: '', c: '', d: '' }); + showToast('Readings applied; print the calibration page again to check'); + } catch (e) { showError(`Could not apply the readings: ${(e as Error).message}`); } + setBusy(false); + } + + const reading = (k: 'a' | 'b' | 'c' | 'd') => ( + + ); + return (
@@ -52,12 +77,23 @@ export function Settings({ onClose }: { onClose: () => void }) { + +
+ Readings from the calibration sheet +
{reading('a')}{reading('b')}
+
{reading('c')}{reading('d')}
+
+ +
+
-

Print the calibration page on plain paper, hold it over a real sheet up to a light, and enter how far the lines are off, up to 10 mm. Always print at 100% scale ("Actual size"), not "Fit to page"; the calibration page has a 6 inch line to check it. A positive Offset X moves everything toward the bottom of the cards (a negative one toward the top, where the call number is). A positive Offset Y moves everything toward the left of the cards, a negative one toward the right. The small marks around the cards on every printed sheet should point exactly at the perforations.

+

Print the calibration page and hold it over a real sheet up to a light. Read the numbers A to D off its rulers where the perforations cross them, enter them above and press Apply readings, then print it again to check. Positive rotation turns the print clockwise. Always print at 100% scale ("Actual size"), not "Fit to page"; the calibration page has a 6 inch line to check it. A positive Offset X moves everything toward the bottom of the cards (a negative one toward the top, where the call number is). A positive Offset Y moves everything toward the left of the cards, a negative one toward the right.

); diff --git a/src/web/styles.css b/src/web/styles.css index 0ccfe92..a0b456f 100644 --- a/src/web/styles.css +++ b/src/web/styles.css @@ -283,6 +283,8 @@ main { max-width: var(--page-max); margin: 0 auto; padding: var(--space-6) var(- .confirm-text { margin-right: var(--space-2); font-weight: 600; } .settings-block { display: grid; gap: var(--space-3); } .settings-block h3 { font-size: var(--text-md); font-weight: 600; } +fieldset.settings-block { border: 0; padding: 0; margin: 0; min-width: 0; } +fieldset.settings-block legend { padding: 0; font-weight: 600; margin-bottom: var(--space-2); } /* Toasts */ .toasts { position: fixed; left: 50%; bottom: var(--space-6); z-index: 50; display: grid; gap: var(--space-2); width: min(32rem, calc(100vw - 2 * var(--gutter))); transform: translateX(-50%); pointer-events: none; }