ntk 8.26.2 → 8.27.0

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.
@@ -24,7 +24,7 @@
24
24
  import { parseDocument } from 'htmlparser2';
25
25
 
26
26
  import { cssColorStraight } from '../color.js';
27
- import { MAT_IDENTITY, Path2D, flattenPath, matIsIdentity, matMultiply } from '../path.js';
27
+ import { MAT_IDENTITY, Path2D, flattenPath, matInvert, matIsIdentity, matMultiply } from '../path.js';
28
28
 
29
29
  const INHERITED = {
30
30
  fill: '#000',
@@ -1073,13 +1073,13 @@ export default class SvgView {
1073
1073
  * every gradient that uses them as one line with an `xlink:href` to it:
1074
1074
  * read without it, each had no stops, and what it filled was not drawn.
1075
1075
  */
1076
- _gradientChain(node) {
1076
+ _gradientChain(node, kind = null) {
1077
1077
  const chain = [node];
1078
1078
  for (let at = node; chain.length < 32;) {
1079
1079
  const href = attr(at, 'href') || attr(at, 'xlink:href') || '';
1080
1080
  const next = href.startsWith('#') ? this._ids.get(href.slice(1)) : null;
1081
1081
  if (!next || chain.includes(next)) break;
1082
- if (tag(next) !== 'lineargradient' && tag(next) !== 'radialgradient') break;
1082
+ if (kind ? tag(next) !== kind : tag(next) !== 'lineargradient' && tag(next) !== 'radialgradient') break;
1083
1083
  chain.push(next);
1084
1084
  at = next;
1085
1085
  }
@@ -1162,6 +1162,193 @@ export default class SvgView {
1162
1162
  return gradient;
1163
1163
  }
1164
1164
 
1165
+ /** The `<pattern>` a paint names by its `url()`, or null where it names
1166
+ * none. */
1167
+ _patternOf(value) {
1168
+ const url = /^url\(['"]?#([^'")]+)['"]?\)/.exec(value || '');
1169
+ const node = url ? this._ids.get(url[1]) : null;
1170
+ return node && tag(node) === 'pattern' ? node : null;
1171
+ }
1172
+
1173
+ /**
1174
+ * Fill a path with a pattern (SVG 2, 14.3): a tile `width` by `height` at
1175
+ * `x`,`y` of its `patternUnits`, repeated across the plane and moved by
1176
+ * its `patternTransform`, each a copy of what the pattern holds — set
1177
+ * from the tile's corner, in `patternContentUnits`, or fitted in by its
1178
+ * `viewBox` — cut to the tile. What a pattern does not set itself it
1179
+ * takes from the patterns its `href` names, its content from the first
1180
+ * of them that has some, as a gradient does (`_gradientChain`).
1181
+ *
1182
+ * The tile is drawn once on a surface, at about the size the context
1183
+ * draws it, then a row of tiles from it and a block of rows, and the
1184
+ * block is drawn across the path: a grid of dots a window across is a
1185
+ * few dozen draws, where a tile at a time is thousands. With no surface
1186
+ * to draw on, or inside a luminance mask, each tile is drawn where it
1187
+ * goes. A path that would take more than `MAX_PATTERN_TILES` of either
1188
+ * is tiled as far as the box the drawing is drawn into, and not at all
1189
+ * where that is too many as well.
1190
+ */
1191
+ _fillPattern(ctx, node, path, rule, alpha, depth) {
1192
+ if ((this._patterning ??= new Set()).has(node)) return;
1193
+ const chain = this._gradientChain(node, 'pattern');
1194
+ const own = (name) => {
1195
+ for (const from of chain) {
1196
+ const value = attr(from, name);
1197
+ if (value !== undefined) return value;
1198
+ }
1199
+ return undefined;
1200
+ };
1201
+ const content = chain.find((from) => (from.children || []).some((child) => child.type === 'tag'));
1202
+ if (!content) return;
1203
+ const byBox = (own('patternUnits') || '').trim() !== 'userSpaceOnUse';
1204
+ const contentByBox = (own('patternContentUnits') || '').trim() === 'objectBoundingBox';
1205
+ const bbox = byBox || contentByBox ? pathBBox(path) : null;
1206
+ if (bbox && !(bbox.w > 0 && bbox.h > 0)) return;
1207
+ // in the user space, a percentage of the viewport; by the bounding
1208
+ // box, a fraction of it from its corner
1209
+ const [pw, ph] = this._viewport;
1210
+ const length = (name, size, origin) => {
1211
+ const raw = String(own(name) ?? '').trim();
1212
+ const n = parseFloat(raw);
1213
+ if (!Number.isFinite(n)) return origin;
1214
+ const part = raw.endsWith('%') ? n / 100 : n;
1215
+ return byBox ? origin + part * size : raw.endsWith('%') ? part * size : n;
1216
+ };
1217
+ const x = length('x', byBox ? bbox.w : pw, byBox ? bbox.x : 0);
1218
+ const y = length('y', byBox ? bbox.h : ph, byBox ? bbox.y : 0);
1219
+ const w = length('width', byBox ? bbox.w : pw, 0);
1220
+ const h = length('height', byBox ? bbox.h : ph, 0);
1221
+ if (!(w > 0 && h > 0)) return;
1222
+ // pattern space to the path's user space, and what the tile's content
1223
+ // is set in, from the tile's corner
1224
+ const placed = matrixOf(parseSvgTransform(own('patternTransform')));
1225
+ const vb = chain.map(parseViewBox).find(Boolean);
1226
+ let inner = MAT_IDENTITY;
1227
+ if (vb && vb[2] > 0 && vb[3] > 0) {
1228
+ const [sx, sy, tx, ty] = viewBoxFit(vb, 0, 0, w, h, own('preserveAspectRatio'));
1229
+ inner = [sx, 0, 0, sy, tx, ty];
1230
+ } else if (contentByBox) {
1231
+ inner = [bbox.w, 0, 0, bbox.h, 0, 0];
1232
+ }
1233
+ const style = this._inheritedStyle(content);
1234
+ const drawTile = (c) => {
1235
+ this._patterning.add(node);
1236
+ const viewport = this._viewport;
1237
+ try {
1238
+ if (vb) this._viewport = [vb[2], vb[3]];
1239
+ c.transform(...inner);
1240
+ this._renderChildren(content, c, style, 1, depth + 1);
1241
+ } finally {
1242
+ this._viewport = viewport;
1243
+ this._patterning.delete(node);
1244
+ }
1245
+ };
1246
+
1247
+ // the tiles that cover the path, in pattern space
1248
+ const m = ctx.getTransform?.();
1249
+ const device = m ? [m.a, m.b, m.c, m.d, m.e, m.f] : null;
1250
+ const along = device ? matMultiply(device, placed) : placed;
1251
+ const toPattern = matInvert(along);
1252
+ if (!toPattern) return;
1253
+ const span = (reach) => {
1254
+ const i0 = Math.floor((reach.x - x) / w);
1255
+ const j0 = Math.floor((reach.y - y) / h);
1256
+ const i1 = Math.ceil((reach.x + reach.w - x) / w);
1257
+ const j1 = Math.ceil((reach.y + reach.h - y) / h);
1258
+ return reach.w > 0 && reach.h > 0 && i1 > i0 && j1 > j0 ? { i0, j0, i1, j1 } : null;
1259
+ };
1260
+ const reach = matrixBox(asMatrix(matInvert(placed) ?? MAT_IDENTITY), pathBBox(path));
1261
+ let tiles = span(reach);
1262
+ if (!tiles) return;
1263
+ // the tile at about the size it is drawn at: a whole number of pixels a
1264
+ // side, so that tiles side by side on a surface meet exactly
1265
+ const tw = Math.max(1, Math.min(MAX_TILE, Math.round(w * Math.hypot(along[0], along[1]))));
1266
+ const th = Math.max(1, Math.min(MAX_TILE, Math.round(h * Math.hypot(along[2], along[3]))));
1267
+ const make = !this._luminance && !this._silhouetting && ctx.drawImage ? this._surface : null;
1268
+ const nx = Math.max(1, Math.floor(BLOCK / tw));
1269
+ const ny = Math.max(1, Math.floor(BLOCK / th));
1270
+ const count = ({ i0, j0, i1, j1 }) =>
1271
+ make ? Math.ceil((i1 - i0) / nx) * Math.ceil((j1 - j0) / ny) : (i1 - i0) * (j1 - j0);
1272
+ if (count(tiles) > MAX_PATTERN_TILES && device && this._bounds) {
1273
+ // a shape too large to tile all of: as far as the box the drawing is
1274
+ // drawn into, which is what of it a caller mostly shows
1275
+ const seen = matrixBox(asMatrix(toPattern), this._bounds);
1276
+ const x0 = Math.max(reach.x, seen.x);
1277
+ const y0 = Math.max(reach.y, seen.y);
1278
+ tiles = span({
1279
+ x: x0,
1280
+ y: y0,
1281
+ w: Math.min(reach.x + reach.w, seen.x + seen.w) - x0,
1282
+ h: Math.min(reach.y + reach.h, seen.y + seen.h) - y0
1283
+ });
1284
+ }
1285
+ if (!tiles || count(tiles) > MAX_PATTERN_TILES) return;
1286
+ const { i0, j0, i1, j1 } = tiles;
1287
+
1288
+ ctx.save();
1289
+ try {
1290
+ ctx.clip(path, rule);
1291
+ ctx.transform(...placed);
1292
+ ctx.globalAlpha = alpha;
1293
+ const block = { x, y, w, h, tw, th, nx: Math.min(i1 - i0, nx), ny: Math.min(j1 - j0, ny), i0, j0, i1, j1 };
1294
+ if (make && this._fillBlocks(ctx, make, drawTile, block)) return;
1295
+ if ((i1 - i0) * (j1 - j0) > MAX_PATTERN_TILES) return;
1296
+ for (let j = j0; j < j1; j++) {
1297
+ for (let i = i0; i < i1; i++) {
1298
+ ctx.save();
1299
+ ctx.translate(x + i * w, y + j * h);
1300
+ const cut = new Path2D();
1301
+ cut.rect(0, 0, w, h);
1302
+ ctx.clip(cut);
1303
+ drawTile(ctx);
1304
+ ctx.restore();
1305
+ }
1306
+ }
1307
+ } finally {
1308
+ ctx.restore();
1309
+ }
1310
+ }
1311
+
1312
+ /** The tiles of a pattern drawn from a surface (`_fillPattern`): one
1313
+ * tile, a row of `nx` of them, a block of `ny` rows, and the block
1314
+ * across the tiles `i0`…`i1` by `j0`…`j1`, in pattern space. False where
1315
+ * a surface could not be made, and nothing is drawn. */
1316
+ _fillBlocks(ctx, make, drawTile, { x, y, w, h, tw, th, nx, ny, i0, j0, i1, j1 }) {
1317
+ let tile = null;
1318
+ let row = null;
1319
+ let block = null;
1320
+ const contexts = [];
1321
+ const context = (surface) => {
1322
+ const c = surface.getContext('2d');
1323
+ contexts.push(c);
1324
+ return c;
1325
+ };
1326
+ try {
1327
+ tile = make(tw, th);
1328
+ row = tile && make(tw * nx, th);
1329
+ block = row && make(tw * nx, th * ny);
1330
+ if (!block) return false;
1331
+ const tctx = context(tile);
1332
+ tctx.scale(tw / w, th / h);
1333
+ drawTile(tctx);
1334
+ const rctx = context(row);
1335
+ for (let i = 0; i < nx; i++) rctx.drawImage(tile, i * tw, 0);
1336
+ const bctx = context(block);
1337
+ for (let j = 0; j < ny; j++) bctx.drawImage(row, 0, j * th);
1338
+ for (let j = j0; j < j1; j += ny) {
1339
+ for (let i = i0; i < i1; i += nx) {
1340
+ ctx.drawImage(block, x + i * w, y + j * h, nx * w, ny * h);
1341
+ }
1342
+ }
1343
+ return true;
1344
+ } finally {
1345
+ for (const c of contexts) c?.destroy?.();
1346
+ block?.destroy?.();
1347
+ row?.destroy?.();
1348
+ tile?.destroy?.();
1349
+ }
1350
+ }
1351
+
1165
1352
  _renderChildren(node, ctx, style, alpha, depth) {
1166
1353
  for (const child of node.children || []) {
1167
1354
  if (child.type !== 'tag') continue;
@@ -1292,7 +1479,9 @@ export default class SvgView {
1292
1479
  if (!path) break;
1293
1480
  if (name !== 'line' && style.fill !== 'none') {
1294
1481
  const rule = style.fillRule === 'evenodd' ? 'evenodd' : 'nonzero';
1295
- this._ink(ctx, 'fill', style.fill, style, path, nodeAlpha * style.fillOpacity, () => ctx.fill(path, rule));
1482
+ const pattern = this._patternOf(style.fill);
1483
+ if (pattern) this._fillPattern(ctx, pattern, path, rule, nodeAlpha * style.fillOpacity, depth);
1484
+ else this._ink(ctx, 'fill', style.fill, style, path, nodeAlpha * style.fillOpacity, () => ctx.fill(path, rule));
1296
1485
  }
1297
1486
  if (style.stroke !== 'none' && style.strokeWidth > 0) {
1298
1487
  ctx.lineWidth = style.strokeWidth;
@@ -2442,6 +2631,21 @@ const EMPTY = Symbol('empty');
2442
2631
  /** The largest surface a mask is drawn on: 4096 by 4096. */
2443
2632
  const MAX_SURFACE = 4096 * 4096;
2444
2633
 
2634
+ /** The most tiles of a pattern drawn one at a time, or blocks of them
2635
+ * (`_fillPattern`): past it, the pattern is not drawn. */
2636
+ const MAX_PATTERN_TILES = 4096;
2637
+
2638
+ /** About how many pixels a side a block of a pattern's tiles is. */
2639
+ const BLOCK = 256;
2640
+
2641
+ /** The most pixels a side a pattern's tile is drawn at. */
2642
+ const MAX_TILE = 2048;
2643
+
2644
+ /** A matrix as an array, as the `{ a, b, … }` `matrixBox` takes. */
2645
+ function asMatrix([a, b, c, d, e, f]) {
2646
+ return { a, b, c, d, e, f };
2647
+ }
2648
+
2445
2649
  /**
2446
2650
  * The device-pixel rectangle a mask's region lands in, under `m` and
2447
2651
  * inside what the drawing can show, whole pixels out: `EMPTY` where none of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ntk",
3
- "version": "8.26.2",
3
+ "version": "8.27.0",
4
4
  "description": "Desktop UI toolkit for X11 with canvas-like 2d and OpenGL rendering",
5
5
  "author": "Andrey Sidorov <sidorares@yandex.ru>",
6
6
  "license": "MIT",