swf2js 0.1.1 → 0.1.2

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 (50) hide show
  1. package/README.md +9 -9
  2. package/package.json +2 -1
  3. package/src/cli.js +15 -6
  4. package/src/emitter/bundle-emitter.js +56 -16
  5. package/src/runtime/avm1-runtime.js +329 -84
  6. package/src/runtime/avm2-runtime.js +56 -6
  7. package/src/runtime/embedded-movie-runtime.js +6 -1
  8. package/src/runtime/index.js +2 -6
  9. package/src/runtime/movie-runtime.js +2 -1
  10. package/src/runtime/swflib/assemble.js +34 -0
  11. package/src/runtime/swflib/bitmap-image.js +4 -0
  12. package/src/runtime/swflib/bitmap.js +1004 -0
  13. package/src/runtime/swflib/builtins.js +156 -0
  14. package/src/runtime/swflib/bytearray.js +949 -0
  15. package/src/runtime/swflib/compiled-swf.js +3 -0
  16. package/src/runtime/swflib/context-menu.js +245 -0
  17. package/src/runtime/swflib/cursor-flag.js +12 -0
  18. package/src/runtime/swflib/dictionary.js +121 -0
  19. package/src/runtime/swflib/display.js +823 -0
  20. package/src/runtime/swflib/events.js +754 -0
  21. package/src/runtime/swflib/filters.js +298 -0
  22. package/src/runtime/swflib/flash.js +130 -0
  23. package/src/runtime/swflib/geom.js +759 -0
  24. package/src/runtime/swflib/glyph-metrics.js +14 -0
  25. package/src/runtime/swflib/graphics.js +735 -0
  26. package/src/runtime/swflib/host.js +2 -0
  27. package/src/runtime/swflib/inherit.js +22 -0
  28. package/src/runtime/swflib/input.js +1085 -0
  29. package/src/runtime/swflib/loader.js +687 -0
  30. package/src/runtime/swflib/marks.js +16 -0
  31. package/src/runtime/swflib/matrix3d.js +144 -0
  32. package/src/runtime/swflib/pointer-bridge.js +8 -0
  33. package/src/runtime/swflib/projection.js +158 -0
  34. package/src/runtime/swflib/render.js +1240 -0
  35. package/src/runtime/swflib/sound.js +1166 -0
  36. package/src/runtime/swflib/sprite-drag.js +116 -0
  37. package/src/runtime/swflib/stage-ref.js +9 -0
  38. package/src/runtime/swflib/stage.js +484 -0
  39. package/src/runtime/swflib/system.js +987 -0
  40. package/src/runtime/swflib/text-field.js +519 -0
  41. package/src/runtime/swflib/text-paint.js +797 -0
  42. package/src/runtime/swflib/text.js +1387 -0
  43. package/src/runtime/swflib/transform.js +133 -0
  44. package/src/runtime/swflib/xml.js +268 -0
  45. package/src/transpiler/avm1/avm1-ir.js +2 -1
  46. package/src/transpiler/avm1/avm1-rewrite.js +23 -2
  47. package/src/transpiler/avm1/avm1-transpiler.js +4 -1
  48. package/src/transpiler/avm2/avm2-transpiler.js +38 -7
  49. package/src/transpiler/timeline/timeline-codegen.js +366 -123
  50. package/src/runtime/swflib.js +0 -14050
@@ -0,0 +1,797 @@
1
+ import { cssColor } from './display.js';
2
+ import { Event, TextFieldType } from './events.js';
3
+ import { TextField, commitAvm1TextFieldScroll, decodeTextEntities, fixedTextFieldSizes, textFieldColorRanges, textFieldFitsContent, textFieldUsesCenteredAutoSize, textRunAdvance } from './text-field.js';
4
+ import { fontOutlineScale, layoutAdvancePixels } from './glyph-metrics.js';
5
+ import { flashDeviceFontAlias } from './text.js';
6
+
7
+ export function applyHtmlTextStyle(sheet, tag, classes, style) {
8
+ var rule = sheet._styles.get(tag);
9
+ for (var name of String(classes || '').split(/\s+/)) {
10
+ var classRule = sheet._styles.get('.' + name);
11
+ if (classRule) rule = { ...rule, ...classRule };
12
+ }
13
+ if (!rule) return;
14
+ var format = sheet.transform({ ...rule });
15
+ if (!format) return;
16
+ for (var key of ['size', 'color', 'bold', 'italic', 'underline', 'letterSpacing', 'kerning']) {
17
+ if (format[key] != null) style[key] = format[key];
18
+ }
19
+ if (format.font) {
20
+ style.font = format.font;
21
+ style.explicitFace = true;
22
+ }
23
+ var paragraphFormat;
24
+ for (var key of ['align', 'leftMargin', 'rightMargin', 'indent', 'leading']) {
25
+ if (format[key] == null) continue;
26
+ if (!paragraphFormat) paragraphFormat = { ...style.paragraphFormat };
27
+ paragraphFormat[key] = format[key];
28
+ }
29
+ if (paragraphFormat) style.paragraphFormat = paragraphFormat;
30
+ }
31
+
32
+ export function parseHtmlTextLines(markup, baseStyle, sheet, condenseWhite) {
33
+ var align, listStyle, lines = [{ runs: [] }], style = Object.assign({}, baseStyle), stack = [], trailingParagraph = false;
34
+ var paragraphStart, lastContentLine = -1, hasEmptyParagraphs = false, pendingWhite;
35
+ function newLine(continuation) {
36
+ pendingWhite = null;
37
+ lines.push({ runs: [], align: align, listStyle: listStyle, format: style.paragraphFormat, continuation: continuation });
38
+ }
39
+ function syncEmptyLineFormat() {
40
+ var line = lines[lines.length - 1];
41
+ if (!line.runs.length) line.format = style.paragraphFormat;
42
+ }
43
+ function addRun(text, style) {
44
+ trailingParagraph = false;
45
+ lastContentLine = lines.length - 1;
46
+ var runs = lines[lines.length - 1].runs, last = runs[runs.length - 1];
47
+ if (last && !last.tab && last.style.bold === style.bold && last.style.italic === style.italic &&
48
+ last.style.underline === style.underline && last.style.font === style.font &&
49
+ last.style.explicitFace === style.explicitFace &&
50
+ last.style.size === style.size && last.style.color === style.color &&
51
+ last.style.letterSpacing === style.letterSpacing && last.style.kerning === style.kerning &&
52
+ last.style.href === style.href && last.style.target === style.target) last.text += text;
53
+ else runs.push({ text: text, style: Object.assign({}, style) });
54
+ }
55
+ function flushWhite() {
56
+ if (pendingWhite) addRun(' ', pendingWhite);
57
+ pendingWhite = null;
58
+ }
59
+ function addText(value) {
60
+ value = decodeTextEntities(value);
61
+ if (condenseWhite) {
62
+ value = value.replace(/[ \t\f\r\n]+/g, ' ');
63
+ if (value.startsWith(' ')) {
64
+ if (!pendingWhite && lines[lines.length - 1].runs.length) pendingWhite = style;
65
+ value = value.slice(1);
66
+ }
67
+ if (!value) return;
68
+ flushWhite();
69
+ if (value.endsWith(' ')) {
70
+ pendingWhite = style;
71
+ value = value.slice(0, -1);
72
+ }
73
+ addRun(value, style);
74
+ return;
75
+ }
76
+ var parts = value.split(/\r\n|\r|\n/);
77
+ for (var i = 0; i < parts.length; i++) {
78
+ if (parts[i]) addRun(parts[i], style);
79
+ if (i < parts.length - 1) { newLine(true); trailingParagraph = false; }
80
+ }
81
+ }
82
+ function attrsFrom(source) {
83
+ var attrs = Object.create(null), re = /([a-z-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi, match;
84
+ while ((match = re.exec(source))) attrs[match[1].toLowerCase()] = match[2] == null ? (match[3] == null ? match[4] : match[3]) : match[2];
85
+ return attrs;
86
+ }
87
+ var tokens = String(markup || '').match(/<[^>]*>|[^<]+/g) || [];
88
+ for (var ti = 0; ti < tokens.length; ti++) {
89
+ var token = tokens[ti];
90
+ if (token.charAt(0) !== '<') { addText(token); continue; }
91
+ var tagMatch = /^<\s*(\/)?\s*([a-z0-9]+)\b([^>]*)>/i.exec(token);
92
+ if (!tagMatch) continue;
93
+ var closing = !!tagMatch[1], tag = tagMatch[2].toLowerCase();
94
+ if (tag === 'br' || tag === 'sbr') { newLine(true); trailingParagraph = false; continue; }
95
+ if (tag === 'tab') {
96
+ if (!closing) {
97
+ flushWhite();
98
+ lines[lines.length - 1].runs.push({ text: '\t', tab: true, style: Object.assign({}, style) });
99
+ trailingParagraph = false;
100
+ lastContentLine = lines.length - 1;
101
+ }
102
+ continue;
103
+ }
104
+ if (tag === 'p' || tag === 'div' || tag === 'li') {
105
+ var paragraphAlign = closing ? '' : String(attrsFrom(tagMatch[3]).align || '').toLowerCase();
106
+ align = ['left', 'center', 'right'].includes(paragraphAlign) ? paragraphAlign : undefined;
107
+ listStyle = tag === 'li' && !closing ? style : null;
108
+ var line = lines[lines.length - 1];
109
+ var emptyParagraph = closing && tag === 'p' && paragraphStart === line && !line.runs.length && lastContentLine >= 0;
110
+ if (emptyParagraph) {
111
+ line.emptyParagraph = true;
112
+ hasEmptyParagraphs = true;
113
+ newLine();
114
+ } else if (line.runs.length) {
115
+ newLine();
116
+ trailingParagraph = closing;
117
+ } else {
118
+ line.align = align;
119
+ line.listStyle = listStyle;
120
+ line.continuation = false;
121
+ }
122
+ paragraphStart = tag === 'p' && !closing ? lines[lines.length - 1] : null;
123
+ if (!sheet) continue;
124
+ }
125
+ if (tag !== 'b' && tag !== 'strong' && tag !== 'i' && tag !== 'em' && tag !== 'u' &&
126
+ tag !== 'font' && tag !== 'a' && tag !== 'textformat' && !sheet) continue;
127
+ if (closing) {
128
+ for (var si = stack.length - 1; si >= 0; si--) if (stack[si].tag === tag) {
129
+ style = stack[si].previous;
130
+ stack.length = si;
131
+ syncEmptyLineFormat();
132
+ break;
133
+ }
134
+ continue;
135
+ }
136
+ var next = Object.assign({}, style), attrs = attrsFrom(tagMatch[3]);
137
+ if (tag === 'b' || tag === 'strong') next.bold = true;
138
+ else if (tag === 'i' || tag === 'em') next.italic = true;
139
+ else if (tag === 'u') next.underline = true;
140
+ else if (tag === 'font') {
141
+ if (attrs.color) {
142
+ next.color = attrs.color;
143
+ next.explicitFontColor = true;
144
+ }
145
+ if (attrs.face) {
146
+ next.font = attrs.face;
147
+ next.explicitFace = true;
148
+ }
149
+ if (attrs.kerning === '0' || attrs.kerning === '1') next.kerning = attrs.kerning === '1';
150
+ if (attrs.letterspacing?.trim() && Number.isFinite(+attrs.letterspacing)) next.letterSpacing = +attrs.letterspacing;
151
+ if (attrs.size) {
152
+ var parsedSize = parseFloat(attrs.size);
153
+ if (/^\s*[+-]/.test(attrs.size)) parsedSize += style.size || 12;
154
+ if (Number.isFinite(parsedSize) && parsedSize > 0) next.size = parsedSize;
155
+ }
156
+ } else if (tag === 'a') {
157
+ next.href = attrs.href || '';
158
+ next.target = attrs.target || '';
159
+ if (next.href) {
160
+ if (!next.explicitFontColor) next.color = '#0000ee';
161
+ next.underline = true;
162
+ }
163
+ } else if (tag === 'textformat') {
164
+ next.paragraphFormat = Object.assign({}, style.paragraphFormat);
165
+ for (var key of ['leftMargin', 'rightMargin', 'indent', 'blockIndent', 'leading']) {
166
+ var attribute = attrs[key.toLowerCase()];
167
+ if (attribute?.trim() && Number.isFinite(+attribute)) next.paragraphFormat[key] = +attribute / 20;
168
+ }
169
+ if (attrs.tabstops) {
170
+ var stops = attrs.tabstops.split(',').filter(function (value) { return value.trim(); })
171
+ .map(function (value) { return +value / 20; })
172
+ .filter(function (value) { return Number.isFinite(value) && value >= 0; });
173
+ if (stops.length) next.paragraphFormat.tabStops = [...new Set(stops)].sort(function (a, b) { return a - b; });
174
+ }
175
+ }
176
+ if (sheet) applyHtmlTextStyle(sheet, tag, attrs.class, next);
177
+ stack.push({ tag: tag, previous: style });
178
+ style = next;
179
+ if (tag === 'textformat' || sheet) syncEmptyLineFormat();
180
+ }
181
+ if (trailingParagraph) lines.pop();
182
+ if (hasEmptyParagraphs) lines = lines.filter(function (line, index) {
183
+ return index <= lastContentLine || !line.emptyParagraph;
184
+ });
185
+ return lines;
186
+ }
187
+
188
+ export var textMeasurementContext;
189
+ export function getTextMeasurementContext() {
190
+ if (textMeasurementContext) return textMeasurementContext;
191
+ try {
192
+ var canvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(1, 1)
193
+ : typeof document !== 'undefined' ? document.createElement('canvas') : null;
194
+ textMeasurementContext = canvas && canvas.getContext('2d');
195
+ } catch (_) {}
196
+ return textMeasurementContext;
197
+ }
198
+
199
+ export function setTextRunFont(ctx, style) {
200
+ var name = String(style.font || 'Arial');
201
+ var family = flashDeviceFontAlias(name) || '"' + name.replace(/["\\]/g, '\\$&') + '"';
202
+ ctx.font = (style.italic ? 'italic ' : '') + (style.bold ? 'bold ' : '') + style.size + 'px ' + family;
203
+ if ('letterSpacing' in ctx) ctx.letterSpacing = style.letterSpacing + 'px';
204
+ if ('fontKerning' in ctx) ctx.fontKerning = style.kerning == null ? 'auto' : style.kerning ? 'normal' : 'none';
205
+ }
206
+
207
+ export var embeddedFontLookups = new WeakMap();
208
+ export var embeddedFontFamilies = new WeakMap();
209
+ export var embeddedGlyphPaths = new WeakMap();
210
+ export function embeddedFontStyle(font) {
211
+ return (font.bold ? 1 : 0) | (font.italic ? 2 : 0);
212
+ }
213
+
214
+ export function embeddedTextFont(style) {
215
+ var definitions = style.embeddedFontDefinitions;
216
+ var exportedId = style.embeddedFontAliases?.[style.font];
217
+ var linked = exportedId == null ? null : definitions?.[exportedId];
218
+ if (linked?.type === 'font' && linked.codes?.length && linked.layout) return linked;
219
+ var name = style.font.toLowerCase();
220
+ var font = style.embeddedFont;
221
+ var primary = font?.codes && font.layout && name === String(font.name).toLowerCase() ? font : null;
222
+ var requestedStyle = embeddedFontStyle(style);
223
+ if (primary && ((!style.explicitFace && !requestedStyle) || embeddedFontStyle(primary) === requestedStyle)) return primary;
224
+ if (!definitions) return primary;
225
+ var families = embeddedFontFamilies.get(definitions);
226
+ if (!families) {
227
+ families = new Map();
228
+ for (var candidate of Object.values(definitions)) {
229
+ if (candidate?.type !== 'font' || !candidate.name || !candidate.codes?.length || !candidate.layout) continue;
230
+ var family = candidate.name.toLowerCase();
231
+ if (!families.has(family)) families.set(family, new Map());
232
+ var faces = families.get(family), key = embeddedFontStyle(candidate);
233
+ if (!faces.has(key)) faces.set(key, candidate);
234
+ }
235
+ embeddedFontFamilies.set(definitions, families);
236
+ }
237
+ var variants = families.get(name);
238
+ return variants?.get(requestedStyle) || primary || variants?.values().next().value;
239
+ }
240
+
241
+ export function measureEmbeddedTextRun(text, style) {
242
+ var font = embeddedTextFont(style);
243
+ if (!font) return null;
244
+ var lookup = embeddedFontLookups.get(font);
245
+ if (!lookup) {
246
+ lookup = { codes: new Map(), pairs: new Map() };
247
+ font.codes.forEach(function (code, index) { lookup.codes.set(code, index); });
248
+ for (var pair of font.layout.kerning || []) lookup.pairs.set(pair[0] * 65536 + pair[1], pair[2]);
249
+ embeddedFontLookups.set(font, lookup);
250
+ }
251
+ var scale = fontOutlineScale(font, style.size);
252
+ var advance = 0, index = 0, previous = -1, glyphs = [];
253
+ for (var character of text) {
254
+ var code = character.codePointAt(0);
255
+ var glyphIndex = lookup.codes.get(code);
256
+ if (glyphIndex === undefined) return null;
257
+ var outline = font.glyphs[glyphIndex];
258
+ if (!outline?.path?.length && /\S/u.test(character)) return null;
259
+ if (style.kerning && previous >= 0) advance += lookup.pairs.get(previous * 65536 + code) || 0;
260
+ glyphs.push({ outline: outline, index: index, x: layoutAdvancePixels(advance, scale) + style.letterSpacing * glyphs.length });
261
+ advance += font.layout.advances[glyphIndex] || 0;
262
+ index += character.length;
263
+ previous = code;
264
+ }
265
+ return { text: text, style: style, width: layoutAdvancePixels(advance, scale) + style.letterSpacing * glyphs.length, ascent: font.layout.ascent * scale,
266
+ descent: font.layout.descent * scale, embeddedGlyphs: glyphs, embeddedScale: scale };
267
+ }
268
+
269
+ export function paintEmbeddedTextRun(ctx, run, x, baseline, colorRanges, color) {
270
+ if (!run.embeddedGlyphs || typeof Path2D === 'undefined') return false;
271
+ for (var glyph of run.embeddedGlyphs) {
272
+ if (!glyph.outline?.path?.length) continue;
273
+ var path = embeddedGlyphPaths.get(glyph.outline);
274
+ if (!path) {
275
+ path = new Path2D();
276
+ for (var command of glyph.outline.path) {
277
+ if (command[0] === 'M') path.moveTo(command[1], command[2]);
278
+ else if (command[0] === 'L') path.lineTo(command[1], command[2]);
279
+ else if (command[0] === 'Q') path.quadraticCurveTo(command[1], command[2], command[3], command[4]);
280
+ else if (command[0] === 'Z') path.closePath();
281
+ }
282
+ embeddedGlyphPaths.set(glyph.outline, path);
283
+ }
284
+ ctx.save();
285
+ if (colorRanges) ctx.fillStyle = textPaintColor(colorRanges, run.start + glyph.index, color);
286
+ ctx.translate(x + glyph.x, baseline);
287
+ ctx.scale(run.embeddedScale, run.embeddedScale);
288
+ ctx.fill(path, 'nonzero');
289
+ ctx.restore();
290
+ }
291
+ return true;
292
+ }
293
+
294
+ export function measureTextRun(ctx, text, style) {
295
+ var displayText = style.password ? '*'.repeat(Array.from(text).length) : text;
296
+ var embedded = measureEmbeddedTextRun(displayText, style);
297
+ if (embedded) {
298
+ if (style.password) {
299
+ embedded.displayText = displayText;
300
+ embedded.text = text;
301
+ // Map the masked glyphs back to the input's UTF-16 positions.
302
+ var index = 0;
303
+ for (var glyph of embedded.embeddedGlyphs) {
304
+ glyph.index = index;
305
+ index += text.codePointAt(index) > 0xffff ? 2 : 1;
306
+ }
307
+ }
308
+ return embedded;
309
+ }
310
+ var metrics = null;
311
+ var canMeasure = ctx && typeof ctx.measureText === 'function';
312
+ if (canMeasure) {
313
+ setTextRunFont(ctx, style);
314
+ metrics = ctx.measureText(displayText);
315
+ }
316
+ var width = metrics && Number.isFinite(metrics.width) ? metrics.width : Array.from(text).length * style.size * 0.5;
317
+ var spacedGlyphs;
318
+ if (style.letterSpacing && (!canMeasure || !('letterSpacing' in ctx))) {
319
+ spacedGlyphs = [];
320
+ width = 0;
321
+ var index = 0;
322
+ for (var character of displayText) {
323
+ spacedGlyphs.push({ text: character, index: index, x: width });
324
+ var advance = canMeasure ? ctx.measureText(character).width : NaN;
325
+ width += (Number.isFinite(advance) ? advance : style.size * 0.5) + style.letterSpacing;
326
+ index += text.codePointAt(index) > 0xffff ? 2 : 1;
327
+ }
328
+ }
329
+ return {
330
+ text: text, displayText: displayText, style: style, width: width, spacedGlyphs: spacedGlyphs,
331
+ ascent: metrics && Number.isFinite(metrics.fontBoundingBoxAscent) ? metrics.fontBoundingBoxAscent : style.size * 0.9,
332
+ descent: metrics && Number.isFinite(metrics.fontBoundingBoxDescent) ? metrics.fontBoundingBoxDescent : style.size * 0.3,
333
+ };
334
+ }
335
+
336
+ export function styledTextParagraphs(field, baseStyle) {
337
+ if (field._htmlTextExplicit) {
338
+ return parseHtmlTextLines(field.htmlText, baseStyle, field.styleSheet, field._htmlCondenseWhite)
339
+ .map(function (line, index, lines) {
340
+ return Object.assign({}, line, { terminator: index + 1 < lines.length ? '\n' : '' });
341
+ });
342
+ }
343
+ var parts = String(field.text || '').split(/(\r\n|\r|\n)/), paragraphs = [];
344
+ for (var i = 0; i < parts.length; i += 2) {
345
+ paragraphs.push({ runs: parts[i] ? [{ text: parts[i], style: baseStyle }] : [], terminator: parts[i + 1] || '' });
346
+ }
347
+ return paragraphs;
348
+ }
349
+
350
+ export function measureHtmlTab(style, position, tabStops, measure) {
351
+ var stop = tabStops?.find(function (value) { return value > position; });
352
+ if (stop == null) {
353
+ var last = tabStops?.[tabStops.length - 1] ?? 0;
354
+ var interval = measure(' ', style).width || style.size * 2;
355
+ stop = last + (Math.floor((position - last) / interval) + 1) * interval;
356
+ }
357
+ var run = measure('', style);
358
+ run.text = '\t';
359
+ run.tab = true;
360
+ run.width = stop - position;
361
+ return run;
362
+ }
363
+
364
+ export function wrapTextParagraph(paragraph, measure, availableWidth, tabStops) {
365
+ var tokens = [], offset = 0;
366
+ for (var run of paragraph.runs) {
367
+ if (run.tab && !run.style.password) {
368
+ tokens.push({ start: offset++, tab: run });
369
+ continue;
370
+ }
371
+ // Keep nonbreaking spaces in the word on either side.
372
+ var pieces = run.style.password ? [run.text] : run.text.match(/[^\t \f\v]+|[\t \f\v]+/g) || [];
373
+ for (var piece of pieces) {
374
+ var space = !run.style.password && /^[\t \f\v]/.test(piece);
375
+ var last = tokens[tokens.length - 1];
376
+ if (!last || last.space !== space) {
377
+ last = { start: offset, space: space, runs: [], width: 0 };
378
+ tokens.push(last);
379
+ }
380
+ var measured = measure(piece, run.style);
381
+ measured.start = offset;
382
+ last.runs.push(measured);
383
+ last.width += measured.width;
384
+ offset += piece.length;
385
+ }
386
+ }
387
+
388
+ var rows = [], current = [], start = 0, currentWidth = 0;
389
+ function finish(end) {
390
+ while (current.length && !current[current.length - 1].tab && !current[current.length - 1].style.password &&
391
+ /^[\t \f\v]+$/.test(current[current.length - 1].text)) current.pop();
392
+ rows.push({ runs: current, start: start, end: end });
393
+ current = [];
394
+ start = end;
395
+ currentWidth = 0;
396
+ }
397
+ function append(run) {
398
+ current.push(run);
399
+ currentWidth += run.width;
400
+ }
401
+ for (var token of tokens) {
402
+ if (token.tab) {
403
+ var tab = measureHtmlTab(token.tab.style, currentWidth, tabStops, measure);
404
+ tab.start = token.start;
405
+ append(tab);
406
+ continue;
407
+ }
408
+ var room = availableWidth(rows.length);
409
+ if (token.space && current.length === 0) continue;
410
+ if (!token.space && current.length && currentWidth + token.width > room) {
411
+ finish(token.start);
412
+ room = availableWidth(rows.length);
413
+ }
414
+ if (token.space || token.width <= room || room <= 0) {
415
+ token.runs.forEach(append);
416
+ continue;
417
+ }
418
+ // Split an overlong word on Unicode code points, keeping UTF-16 offsets.
419
+ var position = token.start;
420
+ for (var part of token.runs) {
421
+ var chunk = null;
422
+ for (var character of part.text) {
423
+ var candidate = measure((chunk ? chunk.text : '') + character, part.style);
424
+ if ((current.length || chunk) && currentWidth + candidate.width > availableWidth(rows.length)) {
425
+ if (chunk) append(chunk);
426
+ finish(position);
427
+ candidate = measure(character, part.style);
428
+ }
429
+ chunk = candidate;
430
+ position += character.length;
431
+ chunk.start = position - chunk.text.length;
432
+ }
433
+ if (chunk) append(chunk);
434
+ }
435
+ }
436
+ finish(offset + paragraph.terminator.length);
437
+ return rows;
438
+ }
439
+
440
+ export function justifyTextRow(runs, extraWidth) {
441
+ if (!(extraWidth > 0) || runs.some(function (run) { return run.tab; })) return 0;
442
+ var spaces = runs.filter(function (run) { return /^ +$/.test(run.text); });
443
+ var count = spaces.reduce(function (sum, run) { return sum + run.text.length; }, 0);
444
+ if (!count) return 0;
445
+ var addedSpacing = extraWidth / count;
446
+ for (var run of spaces) {
447
+ run.justifiedSpacing = addedSpacing;
448
+ run.width += run.text.length * addedSpacing;
449
+ }
450
+ return extraWidth;
451
+ }
452
+
453
+ export function alignTextRow(line, align, width, rightMargin) {
454
+ if (align === 'center') {
455
+ var room = Math.max(0, width - rightMargin - line.x);
456
+ line.x += Math.max(0, room - line.width) / 2;
457
+ } else if (align === 'right' || align === 'end') line.x = width - rightMargin - line.width;
458
+ }
459
+
460
+ /** Build the same rows and metrics for the script API and Canvas paint. */
461
+ export function layoutTextField(field, ctx, fitAuthoredField = false) {
462
+ var fixedSize = fixedTextFieldSizes.get(field), baseSize = fixedSize || field;
463
+ var width = Math.max(0, +baseSize.width || 0), height = Math.max(0, +baseSize.height || 0);
464
+ var fitHeight = fitAuthoredField || (!!fixedSize && textFieldFitsContent(field));
465
+ var fitWidth = fitHeight && !field.wordWrap;
466
+ var format = field.defaultTextFormat || {};
467
+ var letterSpacing = +format.letterSpacing;
468
+ var baseStyle = {
469
+ size: +format.size > 0 ? +format.size : 12,
470
+ font: String(format.font || 'Arial'),
471
+ bold: !!format.bold, italic: !!format.italic, underline: !!format.underline,
472
+ kerning: format.kerning == null ? null : !!format.kerning,
473
+ embeddedFont: field.embedFonts ? field._swoofEmbeddedFont : null,
474
+ embeddedFontDefinitions: field.embedFonts ? field._swoofEmbeddedFontDefinitions : null,
475
+ embeddedFontAliases: field.embedFonts ? field._swoofEmbeddedFontAliases : null,
476
+ letterSpacing: Number.isFinite(letterSpacing) ? letterSpacing : 0,
477
+ color: format.color != null ? format.color : field.textColor,
478
+ password: !!(field.displayAsPassword || field.password),
479
+ };
480
+ var align = String(format.align || 'left').toLowerCase();
481
+ var margin = Math.max(0, +format.leftMargin || 0), right = Math.max(0, +format.rightMargin || 0);
482
+ var indent = +format.indent || 0, leading = +format.leading || 0;
483
+ var state = [field.text, field._htmlTextExplicit && field.htmlText, field._htmlCondenseWhite, field.wordWrap, width, height, fitHeight,
484
+ baseStyle.size, baseStyle.font, baseStyle.bold, baseStyle.italic, baseStyle.underline, baseStyle.color,
485
+ baseStyle.kerning, baseStyle.embeddedFont, baseStyle.embeddedFontDefinitions, baseStyle.embeddedFontAliases, baseStyle.letterSpacing,
486
+ align, margin, right, indent, leading, baseStyle.password, field.styleSheet, field.styleSheet?._revision];
487
+ var cached = field._swoofTextLayout;
488
+ if (!ctx && cached && state.every(function (value, i) { return value === cached.state[i]; })) return cached;
489
+ ctx = ctx || getTextMeasurementContext();
490
+ if (ctx) ctx.textBaseline = 'alphabetic';
491
+ var paragraphs = styledTextParagraphs(field, baseStyle);
492
+ var lines = [], position = 0, y = 0, widestLine = 0, horizontalOverflow = 0;
493
+ var fittedWidth = 0, fittedAlignments = [];
494
+ function measure(text, style) { return measureTextRun(ctx, text, style); }
495
+ for (var paragraph of paragraphs) {
496
+ var paragraphFormat = paragraph.format || {};
497
+ var bullet = !baseStyle.password && paragraph.listStyle ? measure('\u2022', paragraph.listStyle) : null;
498
+ var bulletAdvance = bullet ? bullet.width + measure(' ', bullet.style).width : 0;
499
+ var leftMargin = Math.max(0, paragraphFormat.leftMargin ?? margin) + (paragraphFormat.blockIndent || 0) + bulletAdvance;
500
+ var rightMargin = Math.max(0, paragraphFormat.rightMargin ?? right);
501
+ var firstIndent = paragraph.continuation ? 0 : (paragraphFormat.indent ?? indent);
502
+ var lineLeading = paragraphFormat.leading ?? leading;
503
+ var lineAlign = width > 0 || fitWidth ? paragraph.align || paragraphFormat.align || align : 'left';
504
+ var availableWidth = function (index) {
505
+ return width > 0 ? Math.max(0, width - leftMargin - rightMargin - (index === 0 ? firstIndent : 0)) : Infinity;
506
+ };
507
+ var source = paragraph.runs.map(function (run) { return run.text; }).join('') + paragraph.terminator;
508
+ var offset = 0, lineAdvance = 0;
509
+ var rows = field.wordWrap && width > 0 ? wrapTextParagraph(paragraph, measure, availableWidth, paragraphFormat.tabStops)
510
+ : [{ runs: paragraph.runs.map(function (run) {
511
+ var measured = run.tab && !run.style.password ? measureHtmlTab(run.style, lineAdvance, paragraphFormat.tabStops, measure)
512
+ : measure(run.text, run.style);
513
+ measured.start = offset;
514
+ offset += run.text.length;
515
+ lineAdvance += measured.width;
516
+ return measured;
517
+ }), start: 0, end: source.length }];
518
+ for (var ri = 0; ri < rows.length; ri++) {
519
+ var row = rows[ri], lineWidth = 0, ascent = 0, descent = 0;
520
+ var marker = ri === 0 && !paragraph.continuation ? bullet : null;
521
+ var metrics = row.runs.length ? row.runs : [measure('', baseStyle)];
522
+ for (var run of metrics) {
523
+ lineWidth += run.width;
524
+ ascent = Math.max(ascent, run.ascent);
525
+ descent = Math.max(descent, run.descent);
526
+ }
527
+ if (marker) {
528
+ ascent = Math.max(ascent, marker.ascent);
529
+ descent = Math.max(descent, marker.descent);
530
+ }
531
+ for (var painted of row.runs) painted.start += position;
532
+ var room = availableWidth(ri), x = leftMargin + (ri === 0 ? firstIndent : 0);
533
+ if (lineAlign === 'justify' && ri + 1 < rows.length && !baseStyle.password) {
534
+ lineWidth += justifyTextRow(row.runs, room - lineWidth);
535
+ }
536
+ var lineHeight = Math.max(1, ascent + descent + lineLeading);
537
+ var line = { runs: row.runs, text: source.slice(row.start, row.end), start: position + row.start,
538
+ paragraphStart: position, paragraphEnd: position + source.length,
539
+ marker: marker, markerAdvance: bulletAdvance, x: x, y: y, width: lineWidth,
540
+ height: lineHeight, ascent: ascent, descent: descent, leading: lineLeading };
541
+ lines.push(line);
542
+ if (fitWidth) {
543
+ fittedWidth = Math.max(fittedWidth, x + lineWidth + rightMargin);
544
+ if (lineAlign !== 'left') fittedAlignments.push({ line: line, align: lineAlign, rightMargin: rightMargin });
545
+ } else alignTextRow(line, lineAlign, width, rightMargin);
546
+ y += lineHeight;
547
+ widestLine = Math.max(widestLine, lineWidth + (marker ? bulletAdvance : 0));
548
+ horizontalOverflow = Math.max(horizontalOverflow, lineWidth - room);
549
+ }
550
+ position += source.length;
551
+ }
552
+ if (fitWidth) {
553
+ width = fittedWidth;
554
+ for (var entry of fittedAlignments) alignTextRow(entry.line, entry.align, width, entry.rightMargin);
555
+ }
556
+ if (fitHeight) height = y;
557
+ var firstAtEnd = height > 0 ? lines.length - 1 : 0;
558
+ while (firstAtEnd > 0 && lines[lines.length - 1].y - lines[firstAtEnd - 1].y < height) firstAtEnd--;
559
+ return field._swoofTextLayout = {
560
+ state: state, lines: lines, width: width, height: height,
561
+ textWidth: widestLine, textHeight: y, maxScrollV: firstAtEnd + 1,
562
+ maxScrollH: fitWidth || field.wordWrap ? 0 : Math.max(0, Math.ceil(horizontalOverflow)),
563
+ };
564
+ }
565
+
566
+ export function textFirstVisibleLine(field, layout) {
567
+ return Math.max(0, Math.min(layout.maxScrollV - 1, ((+field.scrollV || 1) | 0) - 1));
568
+ }
569
+
570
+ export function textHorizontalScroll(field, layout) {
571
+ return Math.max(0, Math.min(layout.maxScrollH, +field._scrollH || 0));
572
+ }
573
+
574
+ export function commitAvm1CanvasTextViewport(field) {
575
+ if (field._swoofDetached) return;
576
+ var authored = authoredCanvasTextViewports.get(field);
577
+ if (authored) {
578
+ // Input or a pointer callback can write a new offset after this field was painted.
579
+ var vertical, horizontal;
580
+ if (Object.is(field.scrollV, authored.requestedV)) vertical = field.scrollV = authored.scrollV;
581
+ if (Object.is(field.scrollH, authored.requestedH)) horizontal = field.scrollH = authored.scrollH;
582
+ commitAvm1TextFieldScroll(field, vertical, horizontal);
583
+ } else if (field._swoofTextLayout) {
584
+ var layout = field._swoofTextLayout;
585
+ commitAvm1TextFieldScroll(field, textFirstVisibleLine(field, layout) + 1, textHorizontalScroll(field, layout));
586
+ }
587
+ }
588
+
589
+ export function scrollCanvasText(field, delta) {
590
+ if (field.type !== TextFieldType.DYNAMIC || !field.multiline || !field.mouseWheelEnabled || field.selectable === false) return false;
591
+ var limit = authoredCanvasTextViewports.get(field)?.maxScrollV ?? field._swoofTextLayout?.maxScrollV;
592
+ if (!(limit > 1)) return false;
593
+ var previous = Math.max(1, Math.min(limit, (+field.scrollV || 1) | 0));
594
+ var next = Math.max(1, Math.min(limit, previous - delta));
595
+ if (next === previous) return false;
596
+ field.scrollV = next;
597
+ if (field._swoofAvm1TextField) commitAvm1TextFieldScroll(field, next);
598
+ else {
599
+ try { field.dispatchEvent(new Event(Event.SCROLL, false, false)); } catch (_) {}
600
+ }
601
+ return true;
602
+ }
603
+
604
+ /** AIR mouseWheelHorizontal → scrollH (pixels). One Flash notch ≈ 40 CSS px. */
605
+ export function scrollCanvasTextHorizontal(field, delta) {
606
+ if (field.type !== TextFieldType.DYNAMIC || field.wordWrap || !field.mouseWheelEnabled || field.selectable === false) {
607
+ return false;
608
+ }
609
+ var authored = authoredCanvasTextViewports.get(field);
610
+ var limit = authored?.maxScrollH;
611
+ if (limit == null) limit = (field._swoofTextLayout || layoutTextField(field)).maxScrollH;
612
+ if (!(limit > 0)) return false;
613
+ var step = 40;
614
+ var previous = Math.max(0, Math.min(limit, +field._scrollH || 0));
615
+ var next = Math.max(0, Math.min(limit, previous - delta * step));
616
+ if (next === previous) return false;
617
+ field.scrollH = next;
618
+ if (field._swoofAvm1TextField) commitAvm1TextFieldScroll(field, undefined, next);
619
+ else {
620
+ try { field.dispatchEvent(new Event(Event.SCROLL, false, false)); } catch (_) {}
621
+ }
622
+ return true;
623
+ }
624
+
625
+ export function textPaintColor(ranges, index, color) {
626
+ var low = 0, high = ranges?.length || 0;
627
+ while (low < high) {
628
+ var middle = (low + high) >>> 1, range = ranges[middle];
629
+ if (index < range.start) high = middle;
630
+ else if (index >= range.end) low = middle + 1;
631
+ else { color = range.color; break; }
632
+ }
633
+ return typeof color === 'string' ? color : cssColor(color, 1);
634
+ }
635
+
636
+ export function paintRangedDeviceText(ctx, run, x, y, ranges, color) {
637
+ var start = 0, index = 0, segment = '', segmentColor = textPaintColor(ranges, run.start, color);
638
+ for (var character of run.text) {
639
+ var characterColor = textPaintColor(ranges, run.start + index, color);
640
+ if (characterColor !== segmentColor) {
641
+ ctx.fillStyle = segmentColor;
642
+ ctx.fillText(segment, x + textRunAdvance(run, start, ctx), y);
643
+ start = index;
644
+ segment = '';
645
+ segmentColor = characterColor;
646
+ }
647
+ segment += run.style.password ? '*' : character;
648
+ index += character.length;
649
+ }
650
+ ctx.fillStyle = segmentColor;
651
+ ctx.fillText(segment, x + textRunAdvance(run, start, ctx), y);
652
+ }
653
+
654
+ export function paintTextGlyphRun(ctx, run, x, baseline, appliedColor, colorRanges) {
655
+ var color = appliedColor ?? run.style.color;
656
+ ctx.fillStyle = textPaintColor(null, 0, color);
657
+ if (run.tab || paintEmbeddedTextRun(ctx, run, x, baseline, colorRanges, color)) return;
658
+ setTextRunFont(ctx, run.style);
659
+ if (run.spacedGlyphs) {
660
+ for (var glyph of run.spacedGlyphs) {
661
+ if (colorRanges) ctx.fillStyle = textPaintColor(colorRanges, run.start + glyph.index, color);
662
+ ctx.fillText(glyph.text, x + glyph.x, baseline - run.ascent);
663
+ }
664
+ } else if (colorRanges && run.text.length) {
665
+ paintRangedDeviceText(ctx, run, x, baseline - run.ascent, colorRanges, color);
666
+ } else ctx.fillText(run.displayText ?? run.text, x, baseline - run.ascent);
667
+ }
668
+
669
+ /** Paint plain or a small supported htmlText subset into the Canvas display tree. */
670
+ export function paintTextField(ctx, field, fitAuthoredField, appliedColor, colorRanges = textFieldColorRanges.get(field)) {
671
+ field._swoofLinkRegions = [];
672
+ ctx.save();
673
+ var layout = layoutTextField(field, ctx, fitAuthoredField);
674
+ var width = layout.width, height = layout.height;
675
+ if (field.background && width && height) { ctx.fillStyle = cssColor(field.backgroundColor, 1); ctx.fillRect(0, 0, width, height); }
676
+ if (field.border && width && height) { ctx.strokeStyle = cssColor(field.borderColor, 1); ctx.lineWidth = 1; ctx.strokeRect(0.5, 0.5, Math.max(0, width - 1), Math.max(0, height - 1)); }
677
+ ctx.textBaseline = 'top';
678
+ if (width > 0 && height > 0) { ctx.beginPath(); ctx.rect(0, 0, width, height); ctx.clip(); }
679
+ var first = textFirstVisibleLine(field, layout);
680
+ field.scrollV = first + 1;
681
+ field.scrollH = textHorizontalScroll(field, layout);
682
+ for (var i = first; i < layout.lines.length; i++) {
683
+ var line = layout.lines[i];
684
+ var y = line.y - layout.lines[first].y;
685
+ if (height > 0 && y >= height) break;
686
+ var x = line.x - field.scrollH;
687
+ var baseline = y + line.ascent;
688
+ if (line.marker) paintTextGlyphRun(ctx, line.marker, x - line.markerAdvance, baseline, appliedColor);
689
+ for (var run of line.runs) {
690
+ var runY = baseline - run.ascent;
691
+ paintTextGlyphRun(ctx, run, x, baseline, appliedColor, colorRanges);
692
+ if (run.style.underline && ctx.fillRect) ctx.fillRect(x, runY + run.style.size + 1, run.width, Math.max(1, run.style.size / 16));
693
+ if (!run.style.password && run.style.href && run.width > 0) {
694
+ var linkX = Math.max(0, x), linkY = Math.max(0, y);
695
+ var linkRight = width > 0 ? Math.min(width, x + run.width) : x + run.width;
696
+ var linkBottom = height > 0 ? Math.min(height, y + line.height) : y + line.height;
697
+ if (linkRight > linkX && linkBottom > linkY) field._swoofLinkRegions.push({
698
+ x: linkX, y: linkY, width: linkRight - linkX, height: linkBottom - linkY,
699
+ href: run.style.href, target: run.style.target || '',
700
+ });
701
+ }
702
+ x += run.width;
703
+ }
704
+ }
705
+ ctx.restore();
706
+ }
707
+
708
+ export var authoredTextFields = new WeakMap();
709
+ export var authoredCanvasTextViewports = new WeakMap();
710
+ export function authoredTextFormatNumber(value, fallback = 0) {
711
+ var number = +(value ?? fallback);
712
+ return Number.isFinite(number) ? number : fallback;
713
+ }
714
+ export function authoredTextBounds(bounds, clip) {
715
+ if (!bounds || !(clip?._swoofAuthoredText || clip?._swoofAvm1TextField)) return bounds;
716
+ var width = +clip.width, height = +clip.height;
717
+ width = Number.isFinite(width) ? Math.max(0, width) : bounds.w;
718
+ height = Number.isFinite(height) ? Math.max(0, height) : bounds.h;
719
+ var x = bounds.x;
720
+ if (textFieldUsesCenteredAutoSize(clip)) {
721
+ var fixedWidth = +(fixedTextFieldSizes.get(clip)?.width ?? bounds.w);
722
+ if (Number.isFinite(fixedWidth)) x = (x || 0) + (Math.max(0, fixedWidth) - width) / 2;
723
+ }
724
+ return x === bounds.x && width === bounds.w && height === bounds.h ? bounds : { x: x, y: bounds.y, w: width, h: height };
725
+ }
726
+
727
+ export function paintAuthoredText(ctx, info, matrix, clip, content, html, font, fontDefinitions,
728
+ bounds = authoredTextBounds(info.bounds, clip)) {
729
+ if (!bounds) return false;
730
+ var liveTextField = clip?._swoofAuthoredText || clip?._swoofAvm1TextField;
731
+ var wordWrap = liveTextField ? clip.wordWrap : info.wordWrap;
732
+ var fitAuthoredField = (liveTextField && textFieldFitsContent(clip)) ||
733
+ (info.autoSize === true && info.readOnly && !wordWrap && clip?.type !== TextFieldType.INPUT);
734
+ var canPaintWidth = bounds.w > 0 || (fitAuthoredField && !wordWrap);
735
+ var canPaintHeight = bounds.h > 0 || fitAuthoredField;
736
+ if (bounds !== info.bounds && !(canPaintWidth && canPaintHeight)) {
737
+ authoredCanvasTextViewports.delete(clip);
738
+ return true;
739
+ }
740
+ var field = authoredTextFields.get(info);
741
+ if (!field) {
742
+ field = new TextField();
743
+ authoredTextFields.set(info, field);
744
+ }
745
+ field.width = bounds.w;
746
+ field.height = bounds.h;
747
+ field.background = liveTextField ? clip.background : false;
748
+ field.backgroundColor = liveTextField ? clip.backgroundColor : 0xffffff;
749
+ field.border = liveTextField ? clip.border : info.border;
750
+ field.borderColor = liveTextField ? clip.borderColor : 0;
751
+ field.multiline = info.multiline;
752
+ field.wordWrap = wordWrap;
753
+ field.styleSheet = clip?.styleSheet;
754
+ field.displayAsPassword = !!(clip?.password ?? clip?.displayAsPassword ?? info.password);
755
+ field._swoofEmbeddedFont = font;
756
+ field._swoofEmbeddedFontDefinitions = fontDefinitions;
757
+ field.embedFonts = !!font && clip?.embedFonts !== false;
758
+ var format = field.defaultTextFormat;
759
+ var deviceFont = !field.embedFonts && clip?.defaultTextFormat?.font;
760
+ format.font = deviceFont || info.font || 'Arial';
761
+ var liveFontSize = +clip?.defaultTextFormat?.size;
762
+ format.size = Number.isFinite(liveFontSize) && liveFontSize > 0 ? liveFontSize : (info.fontSize || 12);
763
+ format.color = clip?.textColor ?? info.color;
764
+ format.bold = field.embedFonts ? null : (clip?.defaultTextFormat?.bold ?? info.bold);
765
+ format.italic = field.embedFonts ? null : (clip?.defaultTextFormat?.italic ?? info.italic);
766
+ format.align = clip?.defaultTextFormat?.align || info.align;
767
+ format.leftMargin = authoredTextFormatNumber(clip?.defaultTextFormat?.leftMargin, info.leftMargin);
768
+ format.rightMargin = authoredTextFormatNumber(clip?.defaultTextFormat?.rightMargin, info.rightMargin);
769
+ format.indent = authoredTextFormatNumber(clip?.defaultTextFormat?.indent, info.indent);
770
+ var leading = +(clip?.defaultTextFormat?.leading ?? info.leading ?? 0);
771
+ format.leading = Number.isFinite(leading) ? leading : (info.leading || 0);
772
+ format.kerning = clip?.defaultTextFormat?.kerning;
773
+ format.letterSpacing = clip?.defaultTextFormat?.letterSpacing;
774
+ var requestedH = clip?.scrollH, requestedV = clip?.scrollV;
775
+ field.scrollH = requestedH ?? clip?.hscroll ?? 0;
776
+ field.scrollV = requestedV ?? clip?.scroll ?? 1;
777
+ if (html) {
778
+ field.condenseWhite = !!clip?._htmlCondenseWhite;
779
+ if (!field._htmlTextExplicit || field.htmlText !== content || field._htmlCondenseWhite !== field.condenseWhite) {
780
+ field.htmlText = content;
781
+ }
782
+ } else if (field._htmlTextExplicit || field.text !== content) field.text = content;
783
+ ctx.save();
784
+ try {
785
+ ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx / 20, matrix.ty / 20);
786
+ ctx.translate(bounds.x || 0, bounds.y || 0);
787
+ var colorRanges = !html && content === clip?.text ? textFieldColorRanges.get(clip) : undefined;
788
+ paintTextField(ctx, field, fitAuthoredField, clip?._swoofAppliedTextColor, colorRanges);
789
+ if (clip instanceof TextField) authoredCanvasTextViewports.set(clip, {
790
+ requestedV: requestedV, requestedH: requestedH, scrollV: field.scrollV, scrollH: field.scrollH,
791
+ maxScrollV: field._swoofTextLayout.maxScrollV,
792
+ maxScrollH: field._swoofTextLayout.maxScrollH,
793
+ });
794
+ } finally { ctx.restore(); }
795
+ return true;
796
+ }
797
+