// SPDX-License-Identifier: GPL-3.0-or-later // Copyright (C) 2026 ZiroEDA and contributors. // Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md. /** * SVG_PLOTTER, the SVG 1.1 plot back-end, transcribed from * common/plotters/SVG_plotter.cpp. It derives from PSLIKE_PLOTTER * (PS_plotter.ts) and so from PLOTTER (plotter.ts), which carry SetColor, the * device transform, the dash lengths, the pen wrappers, the three-point Arc and * Text's glyph stroking, as upstream's base classes do. * * The plotter is an append-only text emitter with a *lazy graphics context*. * Pen colour, brush colour and alpha, fill mode, pen width and dash style live * in members; touching any of them only raises `m_graphics_changed`, and the * next drawing primitive flushes it by writing `\n`. Nothing * is buffered or reordered, so a port has to make the same calls in the same * order or the group balance — and hence the whole document — differs. * * Three things dominate byte-level fidelity. * * 1. Precision is per call site. Most numbers use fmt's `{:.{}f}` with * `m_precision` (4), but *five* places use a bare `{:f}`, which is a * hard-coded six decimals: ``'s x/y/width/height/rx, ``'s x/y, * the `translate()` of mirrored hidden text, `Text`'s `rotate()` angle, and * the DOT/DASHDOT/DASHDOTDOT dasharrays — DASH alone uses m_precision. (The * port spec lists only four; `rotate()` is the fifth, SVG_plotter.cpp:904.) * A single shared formatter would quietly normalise all of them. * 2. `fixed()` below rounds ties to even on the exact binary value, because * that is what fmt and printf do. `Number.toFixed` rounds ties away from * zero and drops the sign of negative zero, so it is not a drop-in. * 3. Separators differ by element and are copied literally: PenTo writes * `M{x} {y}` / `L{x} {y}`, PlotPoly writes `M {x},{y}`, BezierCurve writes * `M{x},{y} C…`, Arc writes spaces. So is the stray whitespace — ` \n`, `Z" /> \n`, ` \n\n`, the space before `` and * ``. * * Faithfully reproduced oddities, none of which is to be "fixed": Circle * flushes the style *before* the thin-circle branch switches to FILLED_SHAPE, * so the enlarged circle comes out stroked and hollow and the fill state leaks * to the next primitive; PlotPoly hands setSVGPlotStyle the raw `aWidth`, so a * caller passing a sentinel gets `stroke:none`; PlotPoly asks for a non-group * style, which does *not* clear the dirty flag, so the next primitive re-emits * one; a hatch fill still emits `fill:#RRGGBB` and is only overridden by the * `fill:none` appended after it in CSS source order; `Arc` with a non-positive * radius passes the *width* where Circle expects a *diameter*; `flg_sweep` is * hard-coded to 0; emitSetRGBColor truncates `255*channel` rather than * rounding; StartLayer/EndLayer have no caller anywhere in KiCad and do not * escape the layer name; and KiCad's base64 encoder emits no `=` padding, so * the `` data URI is unpadded. * * Deliberate gaps, each modelled as an injected dependency rather than * approximated: the font (PLOTTER's `PLOTTER_FONT`, standing in for * KIFONT::FONT; SVG needs its `GRTextWidth` too) and the raster image * (`SvgImage`, standing in for wxImage). `@{…}` expression evaluation is skipped, as is the * outline-font polygon callback; both are noted where they would have run. */ import type { Vec2 } from '@ziroeda/kimath/src/math/vector2.js'; import { type EDA_ANGLE, ANGLE_180 } from '@ziroeda/kimath/src/geometry/eda_angle.js'; import { RotatePointD } from '@ziroeda/kimath/src/trigo.js'; import { GR_TEXT_H_ALIGN_T, GR_TEXT_V_ALIGN_T } from '../eda_text.js'; import type { Color4d } from '../gal/color4d.js'; import type { PlotterRenderSettings } from '../render_settings.js'; import { DO_NOT_SET_LINE_WIDTH, FILL_T, LINE_STYLE, PLOT_FORMAT, PLOT_TEXT_MODE, type PLOTTER_FONT, type PLOTTER_TEXT_ATTRIBUTES, type PEN_PLUME, toVector2I, USE_DEFAULT_LINE_WIDTH, } from './plotter.js'; import { PSLIKE_PLOTTER } from './PS_plotter.js'; /** * `wxImage`, reduced to what PlotImage uses. `SaveFilePng` is * `SaveFile(stream, wxBITMAP_TYPE_PNG)`; the greyscale conversion is a separate * call because upstream re-encodes a *converted* image, so the two paths do not * share bytes. */ export interface SvgImage { GetWidth(): number; GetHeight(): number; SaveFilePng(): Uint8Array; ConvertToGreyscale(): SvgImage; } // =========================================================================== // Number formatting // =========================================================================== import { fixed } from './fmt.js'; /** fmt's bare `{:f}`: a hard-coded six decimals, whatever m_precision says. */ export const DEFAULT_FMT_PRECISION = 6; /** fmt's `{:06X}`: uppercase hex, zero-padded to at least six digits. */ export function hex6(aValue: number): string { return (aValue >>> 0).toString(16).toUpperCase().padStart(6, '0'); } // =========================================================================== // Free functions // =========================================================================== /** * `XmlEsc` (SVG_plotter.cpp:109). Carriage return is escaped in *both* modes, * which is why it sits above the isAttribute switch; the apostrophe is escaped * in neither. Every call from the SVG plotter leaves isAttribute false, so the * quote/tab/newline arm is unreachable from here — it is ported because the * function is the unit, not the call site. */ export function XmlEsc(aStr: string, aIsAttribute = false): string { let escaped = ''; for (const c of aStr) { switch (c) { case '<': escaped += '<'; break; case '>': escaped += '>'; break; case '&': escaped += '&'; break; case '\r': escaped += ' '; break; default: if (aIsAttribute) { switch (c) { case '"': escaped += '"'; break; case '\t': escaped += ' '; break; case '\n': escaped += ' '; break; default: escaped += c; } } else { escaped += c; } } } return escaped; } const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; /** * `base64::encode` (libs/core/base64.cpp). KiCad's encoder emits **no `=` * padding** — encode_length works out to 2 or 3 characters for a 1- or 2-byte * tail — so the `` data URI in a KiCad SVG is unpadded base64. `btoa` * pads, so it cannot be used here. */ export function base64Encode(aInput: Uint8Array): string { const end = Math.trunc(aInput.length / 3) * 3; let out = ''; for (let i = 0; i < end; i += 3) { const value = (aInput[i]! << 16) | (aInput[i + 1]! << 8) | aInput[i + 2]!; out += BASE64_ALPHABET[(value >> 18) & 0x3f]; out += BASE64_ALPHABET[(value >> 12) & 0x3f]; out += BASE64_ALPHABET[(value >> 6) & 0x3f]; out += BASE64_ALPHABET[value & 0x3f]; } const remainder = aInput.length - end; if (remainder) { let value = aInput[end]!; if (remainder === 2) { value = (value << 10) | (aInput[end + 1]! << 2); out += BASE64_ALPHABET[(value >> 12) & 0x3f]; } else { value <<= 4; } out += BASE64_ALPHABET[(value >> 6) & 0x3f]; out += BASE64_ALPHABET[value & 0x3f]; } return out; } /** * `GetISO8601CurrentDateTime` (string_utils.cpp:815), i.e. * `wxDateTime::Now().FormatISOCombined('T')` — *local* time, second precision, * no zone suffix. */ export function GetISO8601CurrentDateTime(aNow: Date = new Date()): string { const pad = (aValue: number, aWidth = 2): string => String(aValue).padStart(aWidth, '0'); return ( `${pad(aNow.getFullYear(), 4)}-${pad(aNow.getMonth() + 1)}-${pad(aNow.getDate())}` + `T${pad(aNow.getHours())}:${pad(aNow.getMinutes())}:${pad(aNow.getSeconds())}` ); } /** `wxFileName( … ).GetFullName()`: the last path component, separator agnostic. */ function fullName(aPath: string): string { const cut = Math.max(aPath.lastIndexOf('/'), aPath.lastIndexOf('\\')); return cut < 0 ? aPath : aPath.slice(cut + 1); } /** * `SVG_PLOTTER` (include/plotters/plotters_pslike.h, * common/plotters/SVG_plotter.cpp). * * Drive it exactly as upstream does: OpenFile / SetCreator / SetPageSettings / * SetColorMode / SetViewport, then StartPlot, then geometry, then EndPlot, and * read the document back with `text()`. Write it to disk as UTF-8 — every * string that reaches the file goes through upstream's TO_UTF8. */ export class SVG_PLOTTER extends PSLIKE_PLOTTER { // ---- SVG_PLOTTER state --------------------------------------------------- private m_fillMode: FILL_T = FILL_T.NO_FILL; private m_pen_rgb_color = 0; private m_brush_rgb_color = 0; private m_brush_alpha = 1.0; private m_graphics_changed = true; private m_dashed: LINE_STYLE = LINE_STYLE.SOLID; private m_precision = 4; /** The emitted document. UTF-8 on the way to disk, a JS string in memory. */ private out = ''; constructor(aRenderSettings: PlotterRenderSettings | null = null) { super(); this.m_renderSettings = aRenderSettings; // SVG_PLOTTER's constructor body, in order. PSLIKE_PLOTTER's m_textMode // is set here and never read again. this.m_graphics_changed = true; this.SetTextMode(PLOT_TEXT_MODE.STROKE); this.m_fillMode = FILL_T.NO_FILL; this.m_pen_rgb_color = 0; this.m_brush_rgb_color = 0; this.m_brush_alpha = 1.0; this.m_dashed = LINE_STYLE.SOLID; this.m_precision = 4; } static GetDefaultFileExtension(): string { return 'svg'; } override GetPlotterType(): PLOT_FORMAT { return PLOT_FORMAT.SVG; } // ========================================================================= // Output buffer // ========================================================================= private emit(aText: string): void { this.out += aText; } /** The plotted document. */ text(): string { return this.out; } /** The document as the bytes that should be written to disk. */ bytes(): Uint8Array { return new TextEncoder().encode(this.out); } // ========================================================================= // Setup // ========================================================================= /** * `SetViewport`. SVG is the one back-end that reverses the Y axis, and the * paper size is computed here with *two* truncations: the mils are a VECTOR2D * assigned into a VECTOR2I member, and each `int *= double` truncates again. * That is why an A4 page comes out as 297.0022 mm wide in every file rather * than 297. * * `iusPerMM` is derived from aIusPerDecimil alone, so for pcbnew's 2540 the * device unit is exactly one millimetre. */ SetViewport(aOffset: Vec2, aIusPerDecimil: number, aScale: number, aMirror: boolean): void { this.m_plotMirror = aMirror; this.m_yaxisReversed = true; // unlike other plotters, SVG has Y axis reversed this.m_plotOffset = aOffset; this.m_plotScale = aScale; this.m_IUsPerDecimil = aIusPerDecimil; // Compute the paper size in IUs. for historical reasons the page size is in mils // Two truncations, and only the first is observable. `PAGE_INFO::SetWidthMM` // stores mils as `mm * 1000 / 25.4`, so the mils really can be fractional // and dropping this one changes the emitted page size — a test pins it. // The second is upstream's `int *= double`: by then the value is integral // and every caller passes an integer `aIusPerDecimil` (pcbnew 2540, // eeschema 100, gerbview 1000), so it can never fire. Mutation testing // confirms it. Kept as upstream's arithmetic, not on the strength of a test. const paperSize = toVector2I(this.PageSettings().GetSizeMils()); this.m_paperSize = { x: Math.trunc(paperSize.x * (10.0 * aIusPerDecimil)), y: Math.trunc(paperSize.y * (10.0 * aIusPerDecimil)), }; const iusPerMM = (this.m_IUsPerDecimil / 2.54) * 1000; this.m_iuPerDeviceUnit = 1 / iusPerMM; this.SetSvgCoordinatesFormat(4); } /** `SetSvgCoordinatesFormat`. SVG units are always mm; only the digits move. */ override SetSvgCoordinatesFormat(aPrecision: number): void { this.m_precision = aPrecision; } GetPrecision(): number { return this.m_precision; } // ========================================================================= // Coordinates // ========================================================================= // ========================================================================= // Graphics context // ========================================================================= /** `setFillMode`. Only a *change* dirties the context. */ private setFillMode(aFill: FILL_T): void { if (this.m_fillMode !== aFill) { this.m_graphics_changed = true; this.m_fillMode = aFill; } } /** * `setSVGPlotStyle`. With aIsGroup (the default) this closes the open group * and opens a new one, and only then is the context clean again; PlotPoly * passes false, writes the style straight onto its own `` element, and * so leaves the context dirty for whatever comes next. * * The dash geometry is recomputed from *this call's* width, not from the * width SetDash was given — SetDash discards its width argument entirely. */ private setSVGPlotStyle(aLineWidth: number, aIsGroup = true, aExtraStyle = ''): void { if (aIsGroup) this.emit('\n'); this.m_graphics_changed = false; } this.emit('\n'); } /** * `SetCurrentLineWidth`. DO_NOT_SET_LINE_WIDTH is an early *return*: the pen * keeps its old value and the context is not dirtied. Width 0 is legal and * means "filled shape with no outline", which setSVGPlotStyle renders as * `stroke:none`. * * Any *other* negative width only trips a `wxASSERT_MSG`, which is compiled * out of a release build and merely logs in a debug one — execution continues * and the negative value is stored. Text relies on that: it hands * SetCurrentLineWidth the raw stroke width before PLOTTER::Text takes the * magnitude, so a caller with a negative stroke width transiently sets a * negative pen and gets one `stroke:none` style out of it. Throwing here * would turn a logged warning into a failed plot. */ SetCurrentLineWidth(aWidth: number, _aData?: unknown): void { let width = aWidth; if (width === DO_NOT_SET_LINE_WIDTH) return; else if (width === USE_DEFAULT_LINE_WIDTH) width = this.renderSettings().GetDefaultPenWidth(); if (width !== this.m_currentPenWidth) { this.m_graphics_changed = true; this.m_currentPenWidth = width; } } /** * `emitSetRGBColor`. The channels are *truncated*, not rounded, so r = 0.5 * gives 0x7F. Pen and brush always carry the same triple; only the brush * carries the alpha. */ protected override emitSetRGBColor(r: number, g: number, b: number, a: number): void { const red = Math.trunc(255.0 * r); const green = Math.trunc(255.0 * g); const blue = Math.trunc(255.0 * b); const rgb_color = ((red << 16) | (green << 8) | blue) >>> 0; if (this.m_pen_rgb_color !== rgb_color || this.m_brush_alpha !== a) { this.m_graphics_changed = true; this.m_pen_rgb_color = rgb_color; // Currently, use the same color for brush and pen. this.m_brush_rgb_color = rgb_color; this.m_brush_alpha = a; } } /** `SetDash`. The width argument is ignored; only a *change* dirties. */ SetDash(_aLineWidth: number, aLineStyle: LINE_STYLE): void { if (this.m_dashed !== aLineStyle) { this.m_graphics_changed = true; this.m_dashed = aLineStyle; } } /** * `StartBlock` / `EndBlock`. Deliberately empty: `` is already spoken for * by the lazy graphics context, which leaves its last group open, so a block * cannot nest inside it. */ override StartBlock(_aData?: unknown): void { // Intentionally empty, as upstream is. } override EndBlock(_aData?: unknown): void { // Intentionally empty, as upstream is. } /** * `StartLayer`. Flushes any pending context first so the layer group is a * sibling of the style group rather than a child of a half-written one. The * layer name is *not* escaped, so a name containing `&` or `"` produces * invalid XML — upstream's behaviour, and it has no callers in the KiCad tree * to have noticed. */ StartLayer(aLayerName: string): void { if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); this.emit(`\n`); } /** `EndLayer`: closes the context group and the layer group, then dirties. */ EndLayer(): void { this.emit('\n'); this.emit('\n'); this.m_graphics_changed = true; // Force new graphics context on next draw } // ========================================================================= // File skeleton // ========================================================================= /** * `StartPlot`. The header opens a `` that nothing ever closes on purpose: * m_graphics_changed is left true, so the first primitive emits `` * and the balance works out to the single `` EndPlot writes. * * `origin` is upstream's zero-initialised VECTOR2D with a "TODO set to actual * value" beside it, so the viewBox always starts at 0 0. */ StartPlot(_aPageNumber = '', aNow: Date = new Date()): boolean { const header = '\n' + ' \n' + '\n`, ); const date = GetISO8601CurrentDateTime(aNow); this.emit( `SVG Image created as ${XmlEsc(fullName(this.m_filename))} date ${date} \n`, ); this.emit(` Image generated by ${XmlEsc(this.m_creator)} \n`); // output the pen and brush color (RVB values in hex) and opacity const opacity = 1.0; // 0.0 (transparent) to 1.0 (solid) this.emit( `\n'); return true; } /** `EndPlot`. Mind the space between `` and the newline. */ EndPlot(): boolean { this.emit(' \n\n'); return true; } // ========================================================================= // Entities // ========================================================================= /** * `Rect`. Normalised twice — once in user space, once in device space — * because the transform can flip the sign of an extent and Inkscape refuses a * negative or zero width. For SVG it is the *horizontal mirror* that does the * flipping, not Y: the reversed axis cancels the paper flip, so an unmirrored * plot never needs the second pass and only a mirrored one shows it working. * * The zero test is an exact float compare on the *device* size, and a * degenerate rectangle degrades to a `` at m_precision while the real * `` uses six decimals throughout. */ Rect(p1: Vec2, p2: Vec2, fill: FILL_T, width: number, aCornerRadius = 0): void { const rect = normalizedBox(p1, { x: p2.x - p1.x, y: p2.y - p1.y }); const org_dev = this.userToDeviceCoordinates(rect.pos); const end_dev = this.userToDeviceCoordinates({ x: rect.pos.x + rect.size.x, y: rect.pos.y + rect.size.y, }); const size_dev = { x: end_dev.x - org_dev.x, y: end_dev.y - org_dev.y }; const rect_dev = normalizedBox(org_dev, size_dev); this.setFillMode(fill); this.SetCurrentLineWidth(width); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); const p = this.m_precision; const d = DEFAULT_FMT_PRECISION; if (rect_dev.size.x === 0.0 || rect_dev.size.y === 0.0) { // Rectangles with a zero side are not drawn by Inkscape, so draw a line. this.emit( `\n`, ); } else { this.emit( `\n`, ); } } /** * `Circle`. The thin-circle branch is subtle and its subtlety is the point: * the style is flushed *before* the branch runs, so switching to FILLED_SHAPE * and a zero pen there changes nothing about the element being written — it * still comes out stroked and unfilled, just with the radius grown to * `d/2 + w/2`. Both state changes leak to the next primitive, which is where * they finally take effect. */ Circle(pos: Vec2, diametre: number, fill: FILL_T, width: number): void { const pos_dev = this.userToDeviceCoordinates(pos); let radius = this.userToDeviceSize(diametre / 2.0); this.setFillMode(fill); this.SetCurrentLineWidth(width); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); // If diameter is less than width, switch to filled mode if (fill === FILL_T.NO_FILL && diametre < this.GetCurrentLineWidth()) { this.setFillMode(FILL_T.FILLED_SHAPE); const w = this.GetCurrentLineWidth(); this.SetCurrentLineWidth(0); radius = this.userToDeviceSize(diametre / 2.0 + w / 2.0); } const p = this.m_precision; this.emit( ` \n`, ); } /** * `Arc`. A non-positive radius is turned into a *filled circle whose diameter * is the line width* — `Circle( aCenter, aWidth, … )` really does pass the * width into the diameter slot. * * The horizontal-mirror branch swaps the angles and then reflects each about * 180 degrees; the vertical branch negates both without swapping, which can * leave endAngle behind startAngle. The theta normalisation below is what * rescues that, and it is also what decides flg_arc. flg_sweep is a constant * zero, so a clockwise arc is expressed purely through the angle ordering. * * A filled arc emits *two* paths: the pie wedge with a zero pen, then the * stroked arc with no fill. */ override Arc( aCenter: Vec2, aStartAngle: EDA_ANGLE, aAngle: EDA_ANGLE, aRadius: number, aFill: FILL_T, aWidth: number, ): void { if (aRadius <= 0) { this.Circle(toVector2I(aCenter), aWidth, FILL_T.FILLED_SHAPE, 0); return; } let startAngle = aStartAngle.negate(); let endAngle = startAngle.sub(aAngle); if (endAngle.lt(startAngle)) [startAngle, endAngle] = [endAngle, startAngle]; const centre_device = this.userToDeviceCoordinates(toVector2I(aCenter)); const radius_device = this.userToDeviceSize(aRadius); if (this.m_plotMirror) { if (this.m_mirrorIsHorizontal) { [startAngle, endAngle] = [endAngle, startAngle]; startAngle = ANGLE_180.sub(startAngle); endAngle = ANGLE_180.sub(endAngle); } else { startAngle = startAngle.negate(); endAngle = endAngle.negate(); } } let start = { x: radius_device, y: 0 }; start = RotatePointD(start, startAngle); let end = { x: radius_device, y: 0 }; end = RotatePointD(end, endAngle); start = { x: start.x + centre_device.x, y: start.y + centre_device.y }; end = { x: end.x + centre_device.x, y: end.y + centre_device.y }; let theta1 = startAngle.AsRadians(); if (theta1 < 0) theta1 = theta1 + Math.PI * 2; let theta2 = endAngle.AsRadians(); if (theta2 < 0) theta2 = theta2 + Math.PI * 2; if (theta2 < theta1) theta2 = theta2 + Math.PI * 2; let flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees if (Math.abs(theta2 - theta1) > Math.PI) flg_arc = 1; const flg_sweep = 0; // flag for sweep always 0 const p = this.m_precision; if (aFill !== FILL_T.NO_FILL) { // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on // the arc, so they need two elements. this.setFillMode(aFill); this.SetCurrentLineWidth(0); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); this.emit( `\n`, ); } this.setFillMode(FILL_T.NO_FILL); this.SetCurrentLineWidth(aWidth); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); this.emit( `\n`, ); } /** * `BezierCurve`. Upstream keeps the flattening fallback behind an `#if 1`, so * aTolerance is dead and a real cubic goes out; the `C` command takes three * points because the current point is the start. */ override BezierCurve( aStart: Vec2, aControl1: Vec2, aControl2: Vec2, aEnd: Vec2, _aTolerance: number, aLineThickness: number, ): void { this.setFillMode(FILL_T.NO_FILL); this.SetCurrentLineWidth(aLineThickness); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); const start = this.userToDeviceCoordinates(aStart); const ctrl1 = this.userToDeviceCoordinates(aControl1); const ctrl2 = this.userToDeviceCoordinates(aControl2); const end = this.userToDeviceCoordinates(aEnd); const p = this.m_precision; this.emit( `\n`, ); } /** * `PlotPoly( const std::vector& )`. Three things here look wrong and * are not: the style is emitted with the *raw* aWidth, so a caller passing a * sentinel gets `stroke:none` even though the pen was set correctly; it asks * for a non-group style, which leaves the context dirty so the next primitive * still opens a group; and the vertex loop stops one short of the end, the * last point being either replaced by `Z` (on an exact integer match with the * first) or written after the loop. * * A hatch fill still calls setFillMode, so the style opens with * `fill:#RRGGBB` and is only countermanded by the `fill:none` appended after * it — CSS source order is doing the work. */ PlotPoly(aCornerList: readonly Vec2[], aFill: FILL_T, aWidth: number, _aData?: unknown): void { if (aCornerList.length <= 1) return; this.setFillMode(aFill); this.SetCurrentLineWidth(aWidth); this.emit(' \n'); } else { pos = this.userToDeviceCoordinates(last); this.emit(`${fixed(pos.x, p)},${fixed(pos.y, p)}\n" /> \n`); } } /** * `PlotImage`. The start corner is computed in *doubles* and then truncated * into a VECTOR2I, which is not the same as the base class's integer halving * — see plotterPlotImage below, which the degenerate branch falls back to. * * The x/y of the `` use six decimals while its width/height use * m_precision, and the base64 payload is broken with a newline after every * 64th character (i.e. after index 63, 127, …). The element is left without a * trailing newline, exactly as upstream leaves it. */ override PlotImage(aImage: SvgImage, aPos: Vec2, aScaleFactor: number): void { const pix_size = { x: aImage.GetWidth(), y: aImage.GetHeight() }; // Requested size (in IUs) const drawsize = { x: aScaleFactor * pix_size.x, y: aScaleFactor * pix_size.y, }; // calculate the bitmap start position const start = toVector2I({ x: aPos.x - drawsize.x / 2, y: aPos.y - drawsize.y / 2, }); if (drawsize.x === 0.0 || drawsize.y === 0.0) { // Rectangles with a zero side are not drawn by Inkscape, so draw a line. this.plotterPlotImage(aImage, aPos, aScaleFactor); } else { const png = this.m_colorMode ? aImage.SaveFilePng() : aImage.ConvertToGreyscale().SaveFilePng(); const encoded = base64Encode(png); const pos = this.userToDeviceCoordinates(start); const d = DEFAULT_FMT_PRECISION; this.emit( ``, ); } } /** * `PLOTTER::PlotImage`, the degenerate fallback: an outline rectangle at the * default pen width. Its halving is *integer* division on an already * truncated size, so it can land one IU away from the override's corner. */ private plotterPlotImage(aImage: SvgImage, aPos: Vec2, aScaleFactor: number): void { const size = toVector2I({ x: aImage.GetWidth() * aScaleFactor, y: aImage.GetHeight() * aScaleFactor, }); const start = { x: aPos.x - Math.trunc(size.x / 2), y: aPos.y - Math.trunc(size.y / 2), }; const end = { x: start.x + size.x, y: start.y + size.y }; this.Rect(start, end, FILL_T.NO_FILL, USE_DEFAULT_LINE_WIDTH, 0); } // ========================================================================= // Pen // ========================================================================= /** * `PenTo`. There is no mid-path moveto: once a path is open a 'U' plume emits * an `L`, exactly like a 'D' would, so two disjoint polylines need an explicit * PenFinish between them. 'Z' closes the element and parks the pen at * (-1,-1), which is what makes the *next* 'U' open a fresh path. * * Opening a path forces NO_FILL first — an open contour must not be filled — * and that fill change is what dirties the context, so the style group is * emitted before the `` rather than after. */ PenTo(pos: Vec2, plume: PEN_PLUME): void { const p = this.m_precision; if (plume === 'Z') { if (this.m_penState !== 'Z') { this.emit('" />\n'); this.m_penState = 'Z'; this.m_penLastpos = { x: -1, y: -1 }; } return; } if (this.m_penState === 'Z') { // here plume = 'D' or 'U' const pos_dev = this.userToDeviceCoordinates(pos); // Ensure we do not use a fill mode when moving the pen: in SVG mode we // are plotting only basic lines, not a filled area. if (this.m_fillMode !== FILL_T.NO_FILL) this.setFillMode(FILL_T.NO_FILL); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); this.emit(`` with a `` for screen readers. * m_textMode is never consulted. * * Two asymmetries are load bearing. The `rotate()` transform pivots on the * *original* position while the `` element's x/y are the * vertically-justified one, and the rotation angle is negated unless the plot * is mirrored. The mirror test is an XOR — `m_plotMirror !== (aSize.x < 0)` — * because a negative width is how a mirrored string is encoded, so a mirrored * string on a mirrored plot is upright again. * * `text_size.y` is computed from `aSize.x`, not aSize.y: four thirds of the * *width*, as integer arithmetic, converting Hershey height to em size. */ override Text( aPos: Vec2, aColor: Color4d, aText: string, aOrient: EDA_ANGLE, aSize: Vec2, aH_justify: GR_TEXT_H_ALIGN_T, aV_justify: GR_TEXT_V_ALIGN_T, aWidth: number, aItalic: boolean, aBold: boolean, aMultilineAllowed: boolean, aFont: PLOTTER_FONT | null, aFontMetrics?: unknown, _aData?: unknown, ): void { this.setFillMode(FILL_T.NO_FILL); this.SetColor(aColor); this.SetCurrentLineWidth(aWidth); if (this.m_graphics_changed) this.setSVGPlotStyle(this.GetCurrentLineWidth()); const text_pos = { x: aPos.x, y: aPos.y }; let hjust = 'start'; switch (aH_justify) { case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_CENTER: hjust = 'middle'; break; case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_RIGHT: hjust = 'end'; break; case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_LEFT: hjust = 'start'; break; } switch (aV_justify) { case GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_CENTER: text_pos.y += Math.trunc(aSize.y / 2); break; case GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break; case GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_BOTTOM: break; } if (!aFont?.GRTextWidth) throw new Error('SVG Text needs a font (KIFONT::FONT::GetFont is not wired)'); // aSize.x or aSize.y is < 0 for mirrored texts; the size is the magnitude. const text_size = { x: Math.abs(aFont.GRTextWidth(aText, aSize, this.GetCurrentLineWidth(), aBold, aItalic)), // Hershey font height to em size conversion, on the WIDTH. y: Math.abs(Math.trunc((aSize.x * 4) / 3)), }; const anchor_pos_dev = this.userToDeviceCoordinates(aPos); const text_pos_dev = this.userToDeviceCoordinates(text_pos); const sz_dev = this.userToDeviceSizeV(text_size); const p = this.m_precision; const d = DEFAULT_FMT_PRECISION; // Output the text as a hidden string (opacity = 0), so that WYSIWYG search // can highlight roughly the right area and later processes can edit it. if (!aOrient.IsZero()) { this.emit( `\n`, ); } this.emit(`\n`, ); if (!aOrient.IsZero()) this.emit('\n'); // Output the text again as graphics with a tag (for non-WYSIWYG // search and for screen readers). this.emit(`${XmlEsc(aText)}\n`); super.Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, this.GetCurrentLineWidth(), aItalic, aBold, aMultilineAllowed, aFont, aFontMetrics, ); this.emit(''); } /** * `PlotText`. A mirrored run is handed to Text as a *negative width*, which is * the encoding Text's XOR mirror test then reads back out. */ override PlotText( aPos: Vec2, aColor: Color4d, aText: string, aAttributes: PLOTTER_TEXT_ATTRIBUTES, aFont: PLOTTER_FONT | null, aFontMetrics?: unknown, aData?: unknown, ): void { const size = { x: aAttributes.m_Size.x, y: aAttributes.m_Size.y }; if (aAttributes.m_Mirrored) size.x = -size.x; this.Text( aPos, aColor, aText, aAttributes.m_Angle, size, aAttributes.m_Halign, aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic, aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData, ); } } /** * `BOX2::Normalize` folded into the constructor, which already calls it — so * `BOX2I rect( p1, size ); rect.Normalize();` normalises once, not twice. The * origin moves by the *negated* size, which is why a box built from a * bottom-right corner and a negative extent still ends up anchored top-left. */ function normalizedBox(aPos: Vec2, aSize: Vec2): { pos: Vec2; size: Vec2 } { const pos = { x: aPos.x, y: aPos.y }; const size = { x: aSize.x, y: aSize.y }; if (size.y < 0) { size.y = -size.y; pos.y = pos.y - size.y; } if (size.x < 0) { size.x = -size.x; pos.x = pos.x - size.x; } return { pos, size }; }