@ggraphic/editor 0.1.0-alpha.5 → 0.1.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/CanvasEditorProvider.d.ts +6 -1
  2. package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
  3. package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
  4. package/dist/components/CanvasEditor/types.d.ts +28 -0
  5. package/dist/components/GenericCanvas.d.ts +19 -2
  6. package/dist/components/GenericCanvas.js +28 -3
  7. package/dist/components/GenericCanvasElement.js +15 -1
  8. package/dist/components/PagePreview.d.ts +8 -1
  9. package/dist/components/PagePreview.js +4 -1
  10. package/dist/components/TopBar/ContextControls.js +1 -1
  11. package/dist/components/TopBar/DownloadSection.d.ts +24 -3
  12. package/dist/components/TopBar/DownloadSection.js +45 -7
  13. package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
  14. package/dist/components/TopBar/ShareDropdown.js +2 -2
  15. package/dist/components/TopBar/modules/FloatingFontSizeControl.d.ts +3 -1
  16. package/dist/components/TopBar/modules/FloatingFontSizeControl.js +46 -4
  17. package/dist/components/kindRenderers.js +10 -1
  18. package/dist/entries/export.d.ts +14 -1
  19. package/dist/entries/export.js +14 -1
  20. package/dist/entries/services.d.ts +1 -1
  21. package/dist/export/fonts/fontFiles.d.ts +100 -0
  22. package/dist/export/fonts/fontFiles.js +333 -0
  23. package/dist/export/fonts/glyphs.d.ts +113 -0
  24. package/dist/export/fonts/glyphs.js +120 -0
  25. package/dist/export/fonts/variation.d.ts +23 -0
  26. package/dist/export/fonts/variation.js +43 -0
  27. package/dist/export/pdf/pdfContent.d.ts +108 -0
  28. package/dist/export/pdf/pdfContent.js +566 -0
  29. package/dist/export/pdf/pdfFontkit.d.ts +54 -0
  30. package/dist/export/pdf/pdfFontkit.js +159 -0
  31. package/dist/export/pdf/pdfGeometry.d.ts +54 -0
  32. package/dist/export/pdf/pdfGeometry.js +228 -0
  33. package/dist/export/pdf/pdfResources.d.ts +109 -0
  34. package/dist/export/pdf/pdfResources.js +314 -0
  35. package/dist/export/pdf/writePdf.d.ts +34 -0
  36. package/dist/export/pdf/writePdf.js +165 -0
  37. package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
  38. package/dist/export/pptx/exportPptxDeck.js +5 -2
  39. package/dist/export/pptx/svgPicture.d.ts +19 -0
  40. package/dist/export/pptx/svgPicture.js +64 -0
  41. package/dist/export/pptx/vectorizeElement.d.ts +9 -0
  42. package/dist/export/pptx/vectorizeElement.js +118 -0
  43. package/dist/export/pptx/writePptx.d.ts +13 -0
  44. package/dist/export/pptx/writePptx.js +17 -0
  45. package/dist/export/printPdf.d.ts +1 -0
  46. package/dist/export/printPdf.js +1 -1
  47. package/dist/export/scene/browserDeps.d.ts +32 -0
  48. package/dist/export/scene/browserDeps.js +174 -0
  49. package/dist/export/scene/imageBytes.d.ts +79 -0
  50. package/dist/export/scene/imageBytes.js +330 -0
  51. package/dist/export/scene/itemBounds.d.ts +9 -0
  52. package/dist/export/scene/itemBounds.js +40 -0
  53. package/dist/export/scene/matrix.d.ts +13 -0
  54. package/dist/export/scene/matrix.js +32 -0
  55. package/dist/export/scene/rasterLimit.d.ts +13 -0
  56. package/dist/export/scene/rasterLimit.js +24 -0
  57. package/dist/export/scene/rebaseOps.d.ts +8 -0
  58. package/dist/export/scene/rebaseOps.js +51 -0
  59. package/dist/export/scene/recordPageScene.d.ts +28 -0
  60. package/dist/export/scene/recordPageScene.js +224 -0
  61. package/dist/export/scene/recordingCanvas.d.ts +55 -0
  62. package/dist/export/scene/recordingCanvas.js +71 -0
  63. package/dist/export/scene/recordingContext.d.ts +162 -0
  64. package/dist/export/scene/recordingContext.js +1031 -0
  65. package/dist/export/scene/replayScene.d.ts +31 -0
  66. package/dist/export/scene/replayScene.js +213 -0
  67. package/dist/export/scene/resolveScene.d.ts +48 -0
  68. package/dist/export/scene/resolveScene.js +236 -0
  69. package/dist/export/scene/trustedSvgImages.d.ts +3 -0
  70. package/dist/export/scene/trustedSvgImages.js +21 -0
  71. package/dist/export/scene/types.d.ts +241 -0
  72. package/dist/export/scene/types.js +38 -0
  73. package/dist/export/slidesPdf.d.ts +10 -2
  74. package/dist/export/slidesPdf.js +8 -4
  75. package/dist/export/svg/__fixtures__/barChart.svg +1 -0
  76. package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
  77. package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
  78. package/dist/export/svg/inlineSvg.d.ts +10 -0
  79. package/dist/export/svg/inlineSvg.js +119 -0
  80. package/dist/export/svg/scopeCss.d.ts +45 -0
  81. package/dist/export/svg/scopeCss.js +214 -0
  82. package/dist/export/svg/svgColor.d.ts +8 -0
  83. package/dist/export/svg/svgColor.js +46 -0
  84. package/dist/export/svg/svgImageScene.d.ts +41 -0
  85. package/dist/export/svg/svgImageScene.js +128 -0
  86. package/dist/export/svg/svgPathData.d.ts +31 -0
  87. package/dist/export/svg/svgPathData.js +466 -0
  88. package/dist/export/svg/svgToScene.d.ts +19 -0
  89. package/dist/export/svg/svgToScene.js +1183 -0
  90. package/dist/export/svg/writeSvg.d.ts +33 -0
  91. package/dist/export/svg/writeSvg.js +594 -0
  92. package/dist/export/svg/xml.d.ts +23 -0
  93. package/dist/export/svg/xml.js +49 -0
  94. package/dist/export/vectorDeps.d.ts +27 -0
  95. package/dist/export/vectorDeps.js +37 -0
  96. package/dist/export/vectorExport.d.ts +85 -0
  97. package/dist/export/vectorExport.js +287 -0
  98. package/dist/hooks/useLiveFontSize.d.ts +6 -0
  99. package/dist/hooks/useLiveFontSize.js +26 -0
  100. package/dist/hostServices.d.ts +15 -0
  101. package/dist/i18n/de.d.ts +27 -9
  102. package/dist/i18n/de.js +27 -10
  103. package/dist/i18n/en.js +25 -0
  104. package/dist/page/actions.js +8 -2
  105. package/dist/primitives/AssetPrimitive.js +7 -2
  106. package/dist/primitives/CanvasIcons.js +6 -0
  107. package/dist/primitives/CanvasImage.js +86 -12
  108. package/dist/primitives/CanvasRichText.js +10 -5
  109. package/dist/primitives/CanvasStage.js +2 -2
  110. package/dist/primitives/CanvasText.d.ts +8 -1
  111. package/dist/primitives/CanvasText.js +25 -5
  112. package/dist/primitives/ChartPrimitive.d.ts +11 -1
  113. package/dist/primitives/ChartPrimitive.js +73 -19
  114. package/dist/primitives/IconPrimitive.js +3 -0
  115. package/dist/primitives/IllustrationPrimitive.js +14 -1
  116. package/dist/primitives/chartFont.d.ts +30 -0
  117. package/dist/primitives/chartFont.js +127 -0
  118. package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
  119. package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
  120. package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
  121. package/dist/sidebar/sections/assets/assetAudience.js +18 -0
  122. package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
  123. package/dist/styles/compiled.css +1 -1
  124. package/dist/utils/canvasAssets.d.ts +11 -1
  125. package/dist/utils/canvasAssets.js +8 -0
  126. package/dist/utils/canvasIcons.js +5 -3
  127. package/dist/utils/captureStage.d.ts +19 -0
  128. package/dist/utils/captureStage.js +14 -1
  129. package/dist/utils/cropGhost.d.ts +3 -2
  130. package/dist/utils/cropGhost.js +4 -3
  131. package/dist/utils/externalIcons.d.ts +7 -0
  132. package/dist/utils/externalIcons.js +70 -3
  133. package/dist/utils/filteredPan.d.ts +22 -0
  134. package/dist/utils/filteredPan.js +36 -0
  135. package/dist/utils/illustrations/svgCache.js +6 -1
  136. package/dist/utils/imageFilters.d.ts +13 -0
  137. package/dist/utils/imageFilters.js +11 -0
  138. package/dist/utils/zipPageImages.d.ts +8 -0
  139. package/dist/utils/zipPageImages.js +16 -4
  140. package/package.json +6 -2
  141. package/skills/ggraphic-embed/SKILL.md +33 -1
@@ -0,0 +1,108 @@
1
+ import { type PageResources, type PdfAssets } from './pdfResources.js';
2
+ import type { FontFileSet } from '../fonts/fontFiles.js';
3
+ import type { ExportReport, Matrix, SceneOp } from '../scene/types.js';
4
+ import type { SvgToSceneDefaults } from '../svg/svgToScene.js';
5
+ /** A box of the page in px. */
6
+ export interface RasterBox {
7
+ x: number;
8
+ y: number;
9
+ width: number;
10
+ height: number;
11
+ }
12
+ /**
13
+ * Draws `ops` (in page px, each with its own state) on a canvas that shows `box` at `pixelRatio`
14
+ * and returns it as PNG, transparent where nothing is drawn; null if it cannot. See `rebaseOps`.
15
+ */
16
+ export type RasterizeOps = (ops: SceneOp[], box: RasterBox, pixelRatio: number) => Promise<Uint8Array | null>;
17
+ /** What the writer of one page needs from the document. */
18
+ export interface PageEnv {
19
+ assets: PdfAssets;
20
+ resources: PageResources;
21
+ /** The page's number in the report (1-based). */
22
+ page: number;
23
+ width: number;
24
+ height: number;
25
+ fonts: ReadonlyMap<string, FontFileSet>;
26
+ /** The entries this writer adds; the caller merges them with the scenes' own. */
27
+ report: ExportReport;
28
+ rasterize: RasterizeOps;
29
+ pixelRatio: number;
30
+ svgDefaults: SvgToSceneDefaults;
31
+ /** The item being written, for the report. */
32
+ elementId: string | null;
33
+ }
34
+ export declare class ContentWriter {
35
+ private readonly env;
36
+ private readonly base;
37
+ private readonly lines;
38
+ /**
39
+ * @param base maps the page px space the ops are in to the default space of the stream this
40
+ * writes: the page flip for the page, the identity inside a form drawn after that flip.
41
+ */
42
+ constructor(env: PageEnv, base: Matrix);
43
+ raw(line: string): void;
44
+ text(): string;
45
+ ops(ops: readonly SceneOp[]): Promise<void>;
46
+ op(op: SceneOp): Promise<void>;
47
+ /** `q`, the clips, and the matrix. Every `begin` has an `end`. */
48
+ private begin;
49
+ private end;
50
+ /** The clip path in page px: its own matrix applied here, so it needs no `cm` of its own. */
51
+ private clip;
52
+ private alpha;
53
+ private strokeState;
54
+ /**
55
+ * The operators that set alpha and the colour of a fill or a stroke, or null if the paint draws
56
+ * nothing. `matrix` is the op's, `bounds` the area it touches in its user space (a soft mask is
57
+ * as large as that and no larger).
58
+ */
59
+ private paint;
60
+ /**
61
+ * The operator that sets a fill or stroke colour: DeviceCMYK with the brand's exact values if it
62
+ * has them for this colour, else RGB (which `report.rgbBrandColors` is made from).
63
+ */
64
+ private colour;
65
+ /**
66
+ * An SVG tile cannot be a PDF image: it is drawn once, at its size, by the rasteriser. Once per
67
+ * document, however many paints use it; it is an island only if there is a picture.
68
+ */
69
+ private rasterTile;
70
+ private missing;
71
+ private path;
72
+ /** `commands` painted with the op's paint, in the op's space; `pad` is how far a stroke reaches. */
73
+ private paintPath;
74
+ private textOp;
75
+ /** Real text: the glyphs of `run` in the embedded subset of `file`, each at its measured x. */
76
+ private textRun;
77
+ /** A font whose licence forbids embedding: its glyph shapes as paths, crisp but not selectable. */
78
+ private outlineRun;
79
+ /** The run as a picture: what no font file covers, drawn by whoever has a font for it. */
80
+ private rasterRun;
81
+ /**
82
+ * A shadow is a picture under the op, which stays vector. The picture holds the shadow alone:
83
+ * the op is replayed 'big' px to the left with its shadow offset by 'big' to the right, so the
84
+ * shape lands off the picture and only its shadow stays (a canvas draws the shadow of a shape
85
+ * wherever it is). The op's own alpha and clips are part of the picture.
86
+ */
87
+ private shadowIsland;
88
+ /** The part of `rect` (page px) the clips and the page let through. */
89
+ private visible;
90
+ /** Asks for the picture, places it, reports it; if there is none, reports that instead. */
91
+ private island;
92
+ /** An image XObject over a rect of the (y down) page: the unit square, y up, stood on its head. */
93
+ private picture;
94
+ private image;
95
+ /**
96
+ * An SVG source is drawn as the ops `svgToScene` makes of it, with the image op's alpha, clips
97
+ * and a crop around them as a group (`svgImageGroup`). A source it cannot reproduce completely
98
+ * is one raster island, as a whole.
99
+ */
100
+ private svgImage;
101
+ private raster;
102
+ /**
103
+ * The children in the group's clips. A group is composited from a buffer, so its alpha applies
104
+ * to all of it at once: a transparency group when there are several children and an alpha. One
105
+ * child takes the alpha itself, which comes out the same.
106
+ */
107
+ private group;
108
+ }
@@ -0,0 +1,566 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Writes scene ops as the operators of a PDF content stream.
4
+ *
5
+ * - Every op is its own `q ... Q`: clips (in page px, each mapped by its own matrix, `W n`), then
6
+ * the op's matrix as `cm`, then the graphics state and the paint. Nothing leaks to the next op.
7
+ * - Content is page px with y down. The page's single `cm` flips it; `base` is what maps that
8
+ * flipped space to the default space of the stream being written, which a pattern matrix needs.
9
+ * - Alpha is an `ExtGState` (`ca` and `CA`). A gradient with stops of different alpha adds a
10
+ * luminosity soft mask. A group with several children and an alpha is a transparency group
11
+ * (a form XObject), so the alpha applies to the group as one picture.
12
+ * - Text is real text: embedded subset fonts, one `Tm` per run and `TJ` adjustments that put every
13
+ * glyph at the x the browser measured. A font that may not be embedded is drawn as outlines;
14
+ * what no font file covers becomes a raster island.
15
+ * - Raster islands are asked for through `rasterize`; an island nobody could make is reported in
16
+ * `missingElements`, never left out quietly.
17
+ */
18
+ import { advanceOf, fakeBoldWidth, glyphOutline, splitRuns, } from '../fonts/glyphs.js';
19
+ import { IDENTITY, invert, multiply } from '../scene/matrix.js';
20
+ import { fitPixelRatio } from '../scene/rasterLimit.js';
21
+ import { svgImageGroup } from '../svg/svgImageScene.js';
22
+ import { formatNumber } from '../svg/xml.js';
23
+ import { commandsBounds, growRect, intersectRect, isDegenerate, isIdentity, matrixOperands, num, opBounds, pathOperators, strokePad, textBounds, transformRect, unionRect, unit, } from './pdfGeometry.js';
24
+ const PLAIN_STROKE = {
25
+ width: 1,
26
+ cap: 'butt',
27
+ join: 'miter',
28
+ miterLimit: 10,
29
+ dash: [],
30
+ dashOffset: 0,
31
+ };
32
+ const CAP = { butt: 0, round: 1, square: 2 };
33
+ const JOIN = { miter: 0, round: 1, bevel: 2 };
34
+ /** Nothing to see in a run of these: no island for a zero-width space. */
35
+ const SOFT_HYPHEN = 0xad;
36
+ const INVISIBLE = /^[\p{Cc}\p{Cf}\p{Zs}]*$/u;
37
+ const rgb = (hex) => [1, 3, 5].map((at) => unit(Number.parseInt(hex.slice(at, at + 2), 16) / 255)).join(' ');
38
+ const faceKey = (op) => `${op.font.family}|${op.font.weight}|${op.font.style}`;
39
+ export class ContentWriter {
40
+ env;
41
+ base;
42
+ lines = [];
43
+ /**
44
+ * @param base maps the page px space the ops are in to the default space of the stream this
45
+ * writes: the page flip for the page, the identity inside a form drawn after that flip.
46
+ */
47
+ constructor(env, base) {
48
+ this.env = env;
49
+ this.base = base;
50
+ }
51
+ raw(line) {
52
+ this.lines.push(line);
53
+ }
54
+ text() {
55
+ return this.lines.join('\n');
56
+ }
57
+ async ops(ops) {
58
+ for (const op of ops)
59
+ await this.op(op);
60
+ }
61
+ async op(op) {
62
+ if (op.clips.some((clip) => clip.commands.length === 0))
63
+ return; // clips everything away
64
+ if (isDegenerate(op.matrix))
65
+ return;
66
+ if (op.shadow)
67
+ await this.shadowIsland(op, op.shadow);
68
+ switch (op.kind) {
69
+ case 'path':
70
+ return this.path(op);
71
+ case 'text':
72
+ return this.textOp(op);
73
+ case 'image':
74
+ return this.image(op);
75
+ case 'group':
76
+ return this.group(op);
77
+ case 'raster':
78
+ return this.raster(op);
79
+ }
80
+ }
81
+ // -- graphics state ----------------------------------------------------------------------
82
+ /** `q`, the clips, and the matrix. Every `begin` has an `end`. */
83
+ begin(op, matrix = op.matrix) {
84
+ this.raw('q');
85
+ for (const clip of op.clips)
86
+ this.clip(clip);
87
+ if (!isIdentity(matrix))
88
+ this.raw(`${matrixOperands(matrix)} cm`);
89
+ }
90
+ end() {
91
+ this.raw('Q');
92
+ }
93
+ /** The clip path in page px: its own matrix applied here, so it needs no `cm` of its own. */
94
+ clip(clip) {
95
+ this.raw(`${pathOperators(clip.commands, clip.matrix)} ${clip.rule === 'evenodd' ? 'W*' : 'W'} n`);
96
+ }
97
+ alpha(alpha, softMask = null) {
98
+ return alpha >= 0.99995 && !softMask
99
+ ? []
100
+ : [`${this.env.resources.extGState(alpha, softMask)} gs`];
101
+ }
102
+ strokeState(stroke) {
103
+ const s = stroke ?? PLAIN_STROKE;
104
+ const dashed = s.dash.length > 0 &&
105
+ s.dash.every((length) => Number.isFinite(length) && length >= 0) &&
106
+ s.dash.some((length) => length > 0);
107
+ return [
108
+ `${num(s.width)} w`,
109
+ `${CAP[s.cap]} J`,
110
+ `${JOIN[s.join]} j`,
111
+ ...(s.join === 'miter' ? [`${num(s.miterLimit)} M`] : []),
112
+ `[${dashed ? s.dash.map(num).join(' ') : ''}] ${dashed ? num(s.dashOffset) : 0} d`,
113
+ ];
114
+ }
115
+ // -- paint -------------------------------------------------------------------------------
116
+ /**
117
+ * The operators that set alpha and the colour of a fill or a stroke, or null if the paint draws
118
+ * nothing. `matrix` is the op's, `bounds` the area it touches in its user space (a soft mask is
119
+ * as large as that and no larger).
120
+ */
121
+ async paint(mode, paint, op, bounds) {
122
+ const { assets, resources } = this.env;
123
+ const stroke = mode === 'stroke';
124
+ switch (paint.type) {
125
+ case 'solid':
126
+ return [...this.alpha(op.alpha * paint.alpha), this.colour(paint.hex, stroke)];
127
+ case 'linear':
128
+ case 'radial': {
129
+ // Every stop in the brand's CMYK map: a CMYK shading. One that is not: RGB, all of it.
130
+ const mapped = paint.stops.length > 0 &&
131
+ paint.stops.every((stop) => assets.cmyk.has(stop.hex.toLowerCase()));
132
+ const shading = assets.shading(paint, mapped ? 'cmyk' : 'rgb');
133
+ if (!shading)
134
+ return null; // canvas paints nothing for these
135
+ if (!mapped)
136
+ for (const stop of paint.stops)
137
+ assets.rgbHexes.add(stop.hex.toLowerCase());
138
+ const first = paint.stops[0]?.alpha ?? 1;
139
+ const uniform = paint.stops.every((stop) => stop.alpha === first);
140
+ const mask = uniform ? null : assets.alphaMask(paint, growRect(bounds, 1));
141
+ const pattern = assets.shadingPattern(shading, multiply(this.base, op.matrix));
142
+ return [
143
+ ...this.alpha(op.alpha * (uniform ? first : 1), mask),
144
+ `/Pattern ${stroke ? 'CS' : 'cs'} ${resources.pattern(pattern)} ${stroke ? 'SCN' : 'scn'}`,
145
+ ];
146
+ }
147
+ case 'pattern': {
148
+ const tile = paint.image;
149
+ const image = tile.kind === 'bitmap'
150
+ ? await assets.bitmap(tile)
151
+ : tile.kind === 'svg'
152
+ ? await this.rasterTile(tile)
153
+ : null;
154
+ if (!image) {
155
+ this.missing();
156
+ return null;
157
+ }
158
+ const matrix = multiply(this.base, multiply(op.matrix, paint.matrix));
159
+ const pattern = assets.tilingPattern(image, tile.width, tile.height, matrix);
160
+ return [
161
+ ...this.alpha(op.alpha),
162
+ `/Pattern ${stroke ? 'CS' : 'cs'} ${resources.pattern(pattern)} ${stroke ? 'SCN' : 'scn'}`,
163
+ ];
164
+ }
165
+ }
166
+ }
167
+ /**
168
+ * The operator that sets a fill or stroke colour: DeviceCMYK with the brand's exact values if it
169
+ * has them for this colour, else RGB (which `report.rgbBrandColors` is made from).
170
+ */
171
+ colour(hex, stroke) {
172
+ const key = hex.toLowerCase();
173
+ const ink = this.env.assets.cmyk.get(key);
174
+ if (ink)
175
+ return `${ink.map(unit).join(' ')} ${stroke ? 'K' : 'k'}`;
176
+ this.env.assets.rgbHexes.add(key);
177
+ return `${rgb(key)} ${stroke ? 'RG' : 'rg'}`;
178
+ }
179
+ /**
180
+ * An SVG tile cannot be a PDF image: it is drawn once, at its size, by the rasteriser. Once per
181
+ * document, however many paints use it; it is an island only if there is a picture.
182
+ */
183
+ rasterTile(tile) {
184
+ return this.env.assets.once(tile, async () => {
185
+ const ops = [
186
+ {
187
+ matrix: IDENTITY,
188
+ alpha: 1,
189
+ clips: [],
190
+ shadow: null,
191
+ kind: 'image',
192
+ image: tile,
193
+ sx: 0,
194
+ sy: 0,
195
+ sw: tile.width,
196
+ sh: tile.height,
197
+ dx: 0,
198
+ dy: 0,
199
+ dw: tile.width,
200
+ dh: tile.height,
201
+ },
202
+ ];
203
+ const { assets, report, page } = this.env;
204
+ const png = await this.env.rasterize(ops, { x: 0, y: 0, width: tile.width, height: tile.height }, this.env.pixelRatio);
205
+ const image = png ? await assets.image(tile, png, 'image/png') : null;
206
+ if (image) {
207
+ report.rasterIslands.push({
208
+ page,
209
+ elementId: this.env.elementId,
210
+ reason: 'unsupported-pattern',
211
+ });
212
+ }
213
+ return image;
214
+ });
215
+ }
216
+ missing() {
217
+ const { report, page } = this.env;
218
+ report.missingElements.push({
219
+ page,
220
+ elementId: this.env.elementId,
221
+ reason: 'image-unreadable',
222
+ });
223
+ }
224
+ // -- paths -------------------------------------------------------------------------------
225
+ async path(op) {
226
+ if (op.commands.length === 0)
227
+ return;
228
+ const bounds = commandsBounds(op.commands);
229
+ if (!bounds)
230
+ return;
231
+ await this.paintPath(op, op.commands, bounds, op.mode === 'stroke' ? strokePad(op.stroke) : 0);
232
+ }
233
+ /** `commands` painted with the op's paint, in the op's space; `pad` is how far a stroke reaches. */
234
+ async paintPath(op, commands, bounds, pad) {
235
+ const paint = await this.paint(op.mode, op.paint, op, growRect(bounds, pad));
236
+ if (!paint)
237
+ return;
238
+ this.begin(op);
239
+ for (const line of paint)
240
+ this.raw(line);
241
+ if (op.mode === 'stroke')
242
+ for (const line of this.strokeState(op.stroke))
243
+ this.raw(line);
244
+ this.raw(typeof commands === 'string' ? commands : pathOperators(commands));
245
+ this.raw(op.mode === 'stroke' ? 'S' : op.rule === 'evenodd' ? 'f*' : 'f');
246
+ this.end();
247
+ }
248
+ // -- text --------------------------------------------------------------------------------
249
+ async textOp(op) {
250
+ if (op.text === '' || !(op.font.size > 0))
251
+ return;
252
+ const set = this.env.fonts.get(faceKey(op));
253
+ const runs = set
254
+ ? splitRuns(set, op.text, op.xs)
255
+ : [{ file: null, text: op.text, xs: op.xs }];
256
+ const hasFiles = !!set && set.files.length > 0;
257
+ for (const run of runs) {
258
+ if (run.file?.variation === 'default-only') {
259
+ const { defaultInstanceFonts } = this.env.report;
260
+ if (!defaultInstanceFonts.includes(op.font.family))
261
+ defaultInstanceFonts.push(op.font.family);
262
+ }
263
+ if (run.file === null) {
264
+ await this.rasterRun(op, run, hasFiles ? 'missing-glyph' : 'font-unavailable');
265
+ }
266
+ else if (run.file.embeddable === 'bitmap-only') {
267
+ await this.rasterRun(op, run, 'bitmap-only-font');
268
+ }
269
+ else if (run.file.embeddable === 'outlines-only') {
270
+ await this.outlineRun(op, run, run.file);
271
+ }
272
+ else {
273
+ await this.textRun(op, run, run.file, set);
274
+ }
275
+ }
276
+ }
277
+ /** Real text: the glyphs of `run` in the embedded subset of `file`, each at its measured x. */
278
+ async textRun(op, run, file, set) {
279
+ const { assets, resources } = this.env;
280
+ const font = await assets.font(file, set.face, set.files.indexOf(file));
281
+ const size = op.font.size;
282
+ const perEm = 1000 / file.font.unitsPerEm;
283
+ // Pen position in user space after each glyph; a number in `TJ` moves it by -n/1000 em.
284
+ const x0 = run.xs[0] ?? 0;
285
+ let pen = x0;
286
+ let hex = '';
287
+ const parts = [];
288
+ Array.from(run.text).forEach((char, index) => {
289
+ const codePoint = char.codePointAt(0) ?? 0;
290
+ // A soft hyphen is not drawn and 0 wide in a canvas (it only shows at a line break, which
291
+ // the recorded text never has): no glyph, and the pen stays where it is.
292
+ if (codePoint === SOFT_HYPHEN)
293
+ return;
294
+ const x = run.xs[index];
295
+ if (index > 0 && x !== undefined) {
296
+ const shift = Number(formatNumber(((pen - x) * 1000) / size, 2));
297
+ if (Math.abs(shift) >= 0.05) {
298
+ if (hex)
299
+ parts.push(`<${hex}>`);
300
+ hex = '';
301
+ parts.push(shift);
302
+ pen -= (shift * size) / 1000;
303
+ }
304
+ }
305
+ // `encodeText` is what makes pdf-lib keep this glyph in the subset.
306
+ hex += font.encodeText(char).toString().slice(1, -1);
307
+ // The advance of the glyphs `encodeText` wrote (it shapes), which is the width in `/W`.
308
+ pen += advanceOf(file.font, codePoint) * perEm * (size / 1000);
309
+ });
310
+ if (hex)
311
+ parts.push(`<${hex}>`);
312
+ if (parts.length === 0)
313
+ return;
314
+ const bounds = textBounds({ ...op, xs: run.xs });
315
+ if (!bounds)
316
+ return;
317
+ const paint = await this.paint(op.mode, op.paint, op, bounds);
318
+ if (!paint)
319
+ return;
320
+ // A regular cut standing in for a bold: filled and stroked in the fill's colour (mode 2), the
321
+ // outline growing by a line of `fakeBoldWidth`.
322
+ const bold = file.fakeBold && op.mode === 'fill';
323
+ const boldStroke = bold ? await this.paint('stroke', op.paint, op, bounds) : null;
324
+ this.begin(op);
325
+ for (const line of paint)
326
+ this.raw(line);
327
+ if (boldStroke) {
328
+ for (const line of boldStroke)
329
+ this.raw(line);
330
+ this.raw(`${num(fakeBoldWidth(size))} w`);
331
+ this.raw(`${JOIN.round} j`);
332
+ }
333
+ if (op.mode === 'stroke')
334
+ for (const line of this.strokeState(op.stroke))
335
+ this.raw(line);
336
+ this.raw('BT');
337
+ if (op.mode === 'stroke')
338
+ this.raw('1 Tr');
339
+ else if (bold)
340
+ this.raw('2 Tr');
341
+ this.raw(`${resources.font(font)} ${num(size)} Tf`);
342
+ // The page is y down, text is y up: a flipped text matrix stands the glyphs up again. An
343
+ // upright cut standing in for an italic is sheared by the `c` term (top of the glyph to the right).
344
+ this.raw(`1 0 ${num(file.slant)} -1 ${num(x0)} ${num(op.y)} Tm`);
345
+ this.raw(`[${parts.join(' ')}] TJ`);
346
+ this.raw('ET');
347
+ this.end();
348
+ }
349
+ /** A font whose licence forbids embedding: its glyph shapes as paths, crisp but not selectable. */
350
+ async outlineRun(op, run, file) {
351
+ const glyphs = glyphOutline(file, run.text, op.font.size);
352
+ const commands = glyphs
353
+ .map((glyph, index) => pathOperators(glyph.path, [1, 0, 0, 1, run.xs[index] ?? 0, op.y]))
354
+ .filter((operators) => operators !== '')
355
+ .join(' ');
356
+ if (commands === '')
357
+ return;
358
+ const { outlinedForLicence } = this.env.report;
359
+ if (!outlinedForLicence.includes(op.font.family))
360
+ outlinedForLicence.push(op.font.family);
361
+ const bounds = textBounds({ ...op, xs: run.xs });
362
+ if (!bounds)
363
+ return;
364
+ await this.paintPath({ ...op, rule: 'nonzero' }, commands, bounds, op.mode === 'stroke' ? strokePad(op.stroke) : 0);
365
+ }
366
+ /** The run as a picture: what no font file covers, drawn by whoever has a font for it. */
367
+ async rasterRun(op, run, reason) {
368
+ if (INVISIBLE.test(run.text))
369
+ return;
370
+ const { report, page } = this.env;
371
+ report.missingGlyphs.push({ page, elementId: this.env.elementId, text: run.text });
372
+ const bounds = textBounds({ ...op, xs: run.xs });
373
+ const box = bounds && this.visible(transformRect(bounds, op.matrix), op.clips);
374
+ if (!box)
375
+ return;
376
+ await this.island([{ ...op, text: run.text, xs: run.xs, shadow: null }], box, reason);
377
+ }
378
+ // -- shadows and islands -----------------------------------------------------------------
379
+ /**
380
+ * A shadow is a picture under the op, which stays vector. The picture holds the shadow alone:
381
+ * the op is replayed 'big' px to the left with its shadow offset by 'big' to the right, so the
382
+ * shape lands off the picture and only its shadow stays (a canvas draws the shadow of a shape
383
+ * wherever it is). The op's own alpha and clips are part of the picture.
384
+ */
385
+ async shadowIsland(op, shadow) {
386
+ if (!(shadow.alpha > 0))
387
+ return;
388
+ if (shadow.blur === 0 && shadow.offsetX === 0 && shadow.offsetY === 0)
389
+ return; // none is drawn
390
+ const shape = opBounds({ ...op, clips: [] });
391
+ if (!shape)
392
+ return;
393
+ const reach = 1.5 * shadow.blur + 1; // three sigma of the Gaussian, and a pixel
394
+ const moved = growRect({
395
+ x0: shape.x0 + shadow.offsetX,
396
+ y0: shape.y0 + shadow.offsetY,
397
+ x1: shape.x1 + shadow.offsetX,
398
+ y1: shape.y1 + shadow.offsetY,
399
+ }, reach);
400
+ const box = this.visible(moved, op.clips);
401
+ if (!box)
402
+ return;
403
+ const big = Math.ceil(Math.max(0, shape.x1 - box.x0)) + 8;
404
+ const shadowOnly = {
405
+ ...op,
406
+ matrix: multiply([1, 0, 0, 1, -big, 0], op.matrix),
407
+ shadow: { ...shadow, offsetX: shadow.offsetX + big },
408
+ };
409
+ await this.island([shadowOnly], box, 'shadow');
410
+ }
411
+ /** The part of `rect` (page px) the clips and the page let through. */
412
+ visible(rect, clips) {
413
+ let result = intersectRect(rect, {
414
+ x0: 0,
415
+ y0: 0,
416
+ x1: this.env.width,
417
+ y1: this.env.height,
418
+ });
419
+ for (const clip of clips) {
420
+ const box = commandsBounds(clip.commands);
421
+ if (!result || !box)
422
+ return null;
423
+ result = intersectRect(result, transformRect(box, clip.matrix));
424
+ }
425
+ return result;
426
+ }
427
+ /** Asks for the picture, places it, reports it; if there is none, reports that instead. */
428
+ async island(ops, box, reason) {
429
+ const { assets, resources, report, page } = this.env;
430
+ // A page-sized island at print resolution is more pixels than a canvas may have.
431
+ const fitted = fitPixelRatio(box.x1 - box.x0, box.y1 - box.y0, this.env.pixelRatio);
432
+ const pixelRatio = fitted.pixelRatio;
433
+ // Whole device px, so the picture and the box it is placed in are the same size.
434
+ const snapped = {
435
+ x0: Math.floor(box.x0 * pixelRatio) / pixelRatio,
436
+ y0: Math.floor(box.y0 * pixelRatio) / pixelRatio,
437
+ x1: Math.ceil(box.x1 * pixelRatio) / pixelRatio,
438
+ y1: Math.ceil(box.y1 * pixelRatio) / pixelRatio,
439
+ };
440
+ const png = await this.env.rasterize(ops, {
441
+ x: snapped.x0,
442
+ y: snapped.y0,
443
+ width: snapped.x1 - snapped.x0,
444
+ height: snapped.y1 - snapped.y0,
445
+ }, pixelRatio);
446
+ const image = png ? await assets.image(png, png, 'image/png') : null;
447
+ if (!image) {
448
+ this.missing(); // not an island: there is no picture
449
+ return;
450
+ }
451
+ report.rasterIslands.push({ page, elementId: this.env.elementId, reason });
452
+ if (fitted.reduced)
453
+ report.reducedRasters.push({ page, elementId: this.env.elementId });
454
+ this.picture(resources.xobject(image.ref), snapped.x0, snapped.y0, snapped.x1 - snapped.x0, snapped.y1 - snapped.y0);
455
+ }
456
+ /** An image XObject over a rect of the (y down) page: the unit square, y up, stood on its head. */
457
+ picture(name, x, y, width, height) {
458
+ this.raw(`q ${matrixOperands([width, 0, 0, -height, x, y + height])} cm ${name} Do Q`);
459
+ }
460
+ // -- images ------------------------------------------------------------------------------
461
+ async image(op) {
462
+ const source = op.image;
463
+ if (op.sw === 0 || op.sh === 0 || op.dw === 0 || op.dh === 0)
464
+ return;
465
+ if (source.kind === 'element') {
466
+ this.missing(); // `resolveScene` leaves none; an unresolved one is not drawn, so it is said
467
+ return;
468
+ }
469
+ if (source.kind === 'svg')
470
+ return this.svgImage(op, source);
471
+ const image = await this.env.assets.bitmap(source);
472
+ if (!image) {
473
+ this.missing();
474
+ return;
475
+ }
476
+ // The canvas draws the source rect stretched onto the destination rect: the whole picture
477
+ // goes where it would land, and anything of it outside the destination rect is clipped.
478
+ const kx = op.dw / op.sw;
479
+ const ky = op.dh / op.sh;
480
+ const whole = num(op.sx) === '0' &&
481
+ num(op.sy) === '0' &&
482
+ num(op.sw) === num(source.width) &&
483
+ num(op.sh) === num(source.height);
484
+ this.begin(op);
485
+ for (const line of this.alpha(op.alpha))
486
+ this.raw(line);
487
+ if (!whole)
488
+ this.raw(`${num(op.dx)} ${num(op.dy)} ${num(op.dw)} ${num(op.dh)} re W n`);
489
+ this.picture(this.env.resources.xobject(image.ref), op.dx - op.sx * kx, op.dy - op.sy * ky, source.width * kx, source.height * ky);
490
+ this.end();
491
+ }
492
+ /**
493
+ * An SVG source is drawn as the ops `svgToScene` makes of it, with the image op's alpha, clips
494
+ * and a crop around them as a group (`svgImageGroup`). A source it cannot reproduce completely
495
+ * is one raster island, as a whole.
496
+ */
497
+ async svgImage(op, source) {
498
+ const { group, unsupported } = svgImageGroup(op, source, this.env.svgDefaults, op.clips);
499
+ if (unsupported.length > 0) {
500
+ const bounds = opBounds({ ...op, clips: [] });
501
+ const box = bounds && this.visible(bounds, op.clips);
502
+ if (box)
503
+ await this.island([{ ...op, shadow: null }], box, 'svg-unsupported');
504
+ return;
505
+ }
506
+ await this.group(group);
507
+ }
508
+ async raster(op) {
509
+ if (!op.png) {
510
+ // No pixels: what the island was made of, each op with its own state.
511
+ if (op.source)
512
+ await this.ops(op.source);
513
+ return;
514
+ }
515
+ const image = await this.env.assets.image(op.png, op.png, 'image/png');
516
+ if (!image) {
517
+ this.missing();
518
+ return;
519
+ }
520
+ this.begin(op);
521
+ for (const line of this.alpha(op.alpha))
522
+ this.raw(line);
523
+ this.picture(this.env.resources.xobject(image.ref), op.x, op.y, op.width, op.height);
524
+ this.end();
525
+ }
526
+ // -- groups ------------------------------------------------------------------------------
527
+ /**
528
+ * The children in the group's clips. A group is composited from a buffer, so its alpha applies
529
+ * to all of it at once: a transparency group when there are several children and an alpha. One
530
+ * child takes the alpha itself, which comes out the same.
531
+ */
532
+ async group(op) {
533
+ if (op.ops.length === 0)
534
+ return;
535
+ const alone = op.ops.length === 1 ? op.ops[0] : null;
536
+ const flat = op.alpha >= 0.99995 || alone !== null;
537
+ const needsState = op.clips.length > 0 || !isIdentity(op.matrix);
538
+ if (flat) {
539
+ const children = alone ? [{ ...alone, alpha: alone.alpha * op.alpha }] : op.ops;
540
+ if (!needsState)
541
+ return this.ops(children);
542
+ // The children are drawn under the group's `cm`, so what maps their space to the stream's
543
+ // default space (a pattern matrix) has the group's matrix in it.
544
+ const inner = new ContentWriter(this.env, multiply(this.base, op.matrix));
545
+ await inner.ops(children);
546
+ this.begin(op);
547
+ // Not `push(...lines)`: the spread of a huge group overflows the stack.
548
+ for (const line of inner.lines)
549
+ this.lines.push(line);
550
+ this.end();
551
+ return;
552
+ }
553
+ const inner = new ContentWriter(this.env, IDENTITY);
554
+ await inner.ops(op.ops);
555
+ // The children are page px; the group's matrix moves the whole picture, so the form's box has
556
+ // to reach wherever the page lands under it.
557
+ const page = { x0: 0, y0: 0, x1: this.env.width, y1: this.env.height };
558
+ const bbox = unionRect(page, transformRect(page, invert(op.matrix)));
559
+ const form = this.env.assets.form(inner.text(), bbox, this.env.resources.snapshot(), {});
560
+ this.begin(op);
561
+ for (const line of this.alpha(op.alpha))
562
+ this.raw(line);
563
+ this.raw(`${this.env.resources.xobject(form)} Do`);
564
+ this.end();
565
+ }
566
+ }