Skip to content

Commit ba86a52

Browse files
matmenclaude
andcommitted
text: Unicode data, bidirectional algorithm and line breaking
Groundwork for text in any script, not used by renderText yet: - scripts/unicode.js generates src/render/unicode-data.ts from the Unicode Character Database 18.0 (general category, combining class, bidi class, brackets and mirroring, line break, East Asian width, script, grapheme break, Indic conjunct break, Extended_Pictographic, Indic syllabic/positional categories, joining type): varint encoded ranges in base64, 67 kB (27 kB gzipped), decoded when first used (src/render/unicode.ts) - src/render/bidi.ts: UAX #9, written after the specification (P2-P3, X1-X10, W1-W7, N0 brackets, N1-N2, I1-I2, L1-L2); passes all 770,241 BidiTest.txt and 91,707 BidiCharacterTest.txt cases - src/render/linebreak.ts: UAX #14 revision 57 (LB1-LB31, LB15a-d, LB20a, LB21a-b, LB28a, LB30a-b); passes all 19,346 LineBreakTest.txt cases - tests/unicode.js runs samples of the three conformance files - Unicode License v3 in licenses/ and THIRD_PARTY_NOTICES.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YJgRK5qpwJEbHPuFv6kgAQ
1 parent f40ec28 commit ba86a52

11 files changed

Lines changed: 9221 additions & 0 deletions

File tree

‎THIRD_PARTY_NOTICES.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ following projects, under their own licenses. Each derived file says so in its h
1515
| [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending) | BSD-3-Clause |
1616
| [FreeType](https://freetype.org) | `src/render/hinting.ts` (behavior and parts of the logic of the TrueType interpreter) | FreeType License |
1717
| [Pillow](https://github.com/python-pillow/Pillow) | `src/util/resample.ts` (filter coefficients, box, bilinear and bicubic filters) | MIT-CMU |
18+
| [Unicode Character Database](https://www.unicode.org/ucd/) | `src/render/unicode-data.ts` (character properties, generated by `scripts/unicode.js`) | Unicode License v3 |
1819

1920
## fflate, Fast CRC32 in JavaScript
2021

@@ -195,3 +196,13 @@ The resampling in `src/util/resample.ts` computes its filter coefficients as Pil
195196
filter stretched by the downscaling factor, the source range rounded around each output pixel's center, the weights
196197
normalized) and uses Pillow's box, bilinear and bicubic (a = -0.5) filter functions. The integer passes, the fast
197198
paths and the premultiplied alpha handling are ImageScript's own.
199+
200+
## Unicode Character Database
201+
202+
Copyright © 1991-2026 Unicode, Inc.
203+
204+
`src/render/unicode-data.ts` is generated by `scripts/unicode.js` from data files of the Unicode Character Database
205+
(character properties for the bidirectional algorithm, line breaking, text segmentation and shaping). They are used
206+
under the Unicode License v3, included as [licenses/Unicode-3.0.txt](licenses/Unicode-3.0.txt). The bidirectional
207+
algorithm (`src/render/bidi.ts`) and the line breaking (`src/render/linebreak.ts`) are written after UAX #9 and
208+
UAX #14.

‎licenses/Unicode-3.0.txt‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
UNICODE LICENSE V3
2+
3+
COPYRIGHT AND PERMISSION NOTICE
4+
5+
Copyright © 1991-2026 Unicode, Inc.
6+
7+
NOTICE TO USER: Carefully read the following legal agreement. BY
8+
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9+
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10+
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11+
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12+
13+
Permission is hereby granted, free of charge, to any person obtaining a
14+
copy of data files and any associated documentation (the "Data Files") or
15+
software and any associated documentation (the "Software") to deal in the
16+
Data Files or Software without restriction, including without limitation
17+
the rights to use, copy, modify, merge, publish, distribute, and/or sell
18+
copies of the Data Files or Software, and to permit persons to whom the
19+
Data Files or Software are furnished to do so, provided that either (a)
20+
this copyright and permission notice appear with all copies of the Data
21+
Files or Software, or (b) this copyright and permission notice appear in
22+
associated Documentation.
23+
24+
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25+
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27+
THIRD PARTY RIGHTS.
28+
29+
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30+
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31+
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32+
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33+
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34+
FILES OR SOFTWARE.
35+
36+
Except as contained in this notice, the name of a copyright holder shall
37+
not be used in advertising or otherwise to promote the sale, use or other
38+
dealings in these Data Files or Software without prior written
39+
authorization of the copyright holder.

‎scripts/unicode.js‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
// Generates src/render/unicode-data.ts from the Unicode Character Database: node scripts/unicode.js <ucd directory>
2+
// (the files of https://www.unicode.org/Public/UCD/latest/ucd/, with the auxiliary, extracted and emoji folders)
3+
//
4+
// Every property is a list of ranges of code points with their value (ranges of the default value left out),
5+
// varint encoded (gap to the previous range, length, value) and stored as base64, decoded when first used
6+
const fs = require('fs');
7+
const path = require('path');
8+
9+
const ucd = process.argv[2];
10+
if (!ucd) throw new Error('usage: node scripts/unicode.js <ucd directory>');
11+
const read = file => fs.readFileSync(path.join(ucd, file), 'utf8');
12+
const SIZE = 0x110000;
13+
const version = read('UnicodeData.txt') && (read('DerivedCoreProperties.txt').match(/DerivedCoreProperties-([\d.]+)\.txt/) || [])[1];
14+
15+
const range = text => {
16+
const [start, end] = text.trim().split('..').map(h => parseInt(h, 16));
17+
return [start, end ?? start];
18+
};
19+
20+
// long value names -> short ones per property (the @missing lines use the long ones)
21+
const aliases = new Map();
22+
for (const line of read('PropertyValueAliases.txt').split('\n')) {
23+
const content = line.split('#')[0].trim();
24+
if (!content) continue;
25+
const [property, short, long, ...more] = content.split(';').map(f => f.trim());
26+
for (const name of [long, ...more]) aliases.set(`${property}:${name}`, short);
27+
}
28+
29+
// a property file with "range ; value" lines (field picks the value column), @missing lines set defaults (alias is
30+
// the property's short name, to translate their long value names)
31+
function property(file, { field = 1, filter = null, defaultValue, alias = null } = {}) {
32+
const values = new Array(SIZE).fill(defaultValue);
33+
const text = read(file);
34+
for (const line of text.split('\n')) {
35+
const missing = line.match(/^#\s*@missing:\s*([0-9A-F.]+)\s*;\s*(?:InCB\s*;\s*)?([^;#]+)/);
36+
if (missing) {
37+
const [start, end] = range(missing[1]);
38+
const name = missing[2].trim();
39+
values.fill(alias && aliases.get(`${alias}:${name}`) || name, start, end + 1);
40+
}
41+
}
42+
for (const line of text.split('\n')) {
43+
const content = line.split('#')[0].trim();
44+
if (!content) continue;
45+
const fields = content.split(';').map(f => f.trim());
46+
if (filter && !filter(fields)) continue;
47+
const [start, end] = range(fields[0]);
48+
values.fill(fields[field], start, end + 1);
49+
}
50+
return values;
51+
}
52+
53+
// UnicodeData.txt: a field per code point, "First>"/"Last>" pairs for ranges
54+
function unicodeData(field, defaultValue) {
55+
const values = new Array(SIZE).fill(defaultValue);
56+
let first = -1;
57+
for (const line of read('UnicodeData.txt').split('\n')) {
58+
if (!line) continue;
59+
const fields = line.split(';'), code = parseInt(fields[0], 16);
60+
if (fields[1].endsWith(', First>')) first = code;
61+
else if (fields[1].endsWith(', Last>')) values.fill(fields[field], first, code + 1);
62+
else values[code] = fields[field];
63+
}
64+
return values;
65+
}
66+
67+
// ranges of equal values (the default left out) -> { values, data }
68+
function encode(values, defaultValue) {
69+
const names = [defaultValue, ...[...new Set(values)].filter(v => v !== defaultValue).sort()];
70+
const index = new Map(names.map((name, i) => [name, i]));
71+
const bytes = [];
72+
const varint = n => {
73+
for (; n >= 128; n = Math.floor(n / 128)) bytes.push(n & 127 | 128);
74+
bytes.push(n);
75+
};
76+
let previous = 0, ranges = 0;
77+
for (let start = 0; start < SIZE;) {
78+
let end = start;
79+
while (end + 1 < SIZE && values[end + 1] === values[start]) end++;
80+
if (values[start] !== defaultValue) {
81+
varint(start - previous);
82+
varint(end - start);
83+
varint(index.get(values[start]));
84+
previous = end + 1;
85+
ranges++;
86+
}
87+
start = end + 1;
88+
}
89+
return { names, data: Buffer.from(bytes).toString('base64'), ranges };
90+
}
91+
92+
const tables = {};
93+
const add = (name, description, values, defaultValue) => {
94+
tables[name] = { description, ...encode(values, defaultValue) };
95+
};
96+
97+
const gc = unicodeData(2, 'Cn');
98+
add('generalCategory', 'General_Category', gc, 'Cn');
99+
add('combiningClass', 'Canonical_Combining_Class', unicodeData(3, '0'), '0');
100+
add('bidiClass', 'Bidi_Class', property('extracted/DerivedBidiClass.txt', { defaultValue: 'L', alias: 'bc' }), 'L');
101+
add('lineBreak', 'Line_Break', property('LineBreak.txt', { defaultValue: 'XX', alias: 'lb' }), 'XX');
102+
add('eastAsianWidth', 'East_Asian_Width', property('EastAsianWidth.txt', { defaultValue: 'N', alias: 'ea' }), 'N');
103+
add('script', 'Script', property('Scripts.txt', { defaultValue: 'Unknown' }), 'Unknown');
104+
add('graphemeBreak', 'Grapheme_Cluster_Break', property('auxiliary/GraphemeBreakProperty.txt', { defaultValue: 'XX', alias: 'GCB' }), 'XX');
105+
add('conjunctBreak', 'Indic_Conjunct_Break', property('DerivedCoreProperties.txt', { field: 2, filter: f => f[1] === 'InCB', defaultValue: 'None' }), 'None');
106+
add('extendedPictographic', 'Extended_Pictographic', property('emoji/emoji-data.txt', { filter: f => f[1] === 'Extended_Pictographic', defaultValue: 'No' }), 'No');
107+
add('indicSyllabic', 'Indic_Syllabic_Category', property('IndicSyllabicCategory.txt', { defaultValue: 'Other' }), 'Other');
108+
add('indicPositional', 'Indic_Positional_Category', property('IndicPositionalCategory.txt', { defaultValue: 'NA' }), 'NA');
109+
110+
// joining types: listed ones, else T for marks and format characters, else U (ArabicShaping.txt header)
111+
const joining = gc.map(c => c === 'Mn' || c === 'Me' || c === 'Cf' ? 'T' : 'U');
112+
for (const line of read('ArabicShaping.txt').split('\n')) {
113+
const content = line.split('#')[0].trim();
114+
if (!content) continue;
115+
const fields = content.split(';').map(f => f.trim());
116+
joining[parseInt(fields[0], 16)] = fields[2];
117+
}
118+
add('joiningType', 'Joining_Type', joining, 'U');
119+
120+
// paired brackets and mirrored glyphs as pairs of code points
121+
const brackets = [];
122+
for (const line of read('BidiBrackets.txt').split('\n')) {
123+
const content = line.split('#')[0].trim();
124+
if (!content) continue;
125+
const [code, pair, type] = content.split(';').map(f => f.trim());
126+
brackets.push([parseInt(code, 16), parseInt(pair, 16), type === 'o' ? 1 : 2]);
127+
}
128+
const mirrors = [];
129+
for (const line of read('BidiMirroring.txt').split('\n')) {
130+
const content = line.split('#')[0].trim();
131+
if (!content) continue;
132+
const [code, mirror] = content.split(';').map(f => parseInt(f.trim(), 16));
133+
mirrors.push([code, mirror]);
134+
}
135+
136+
let out = `/*!
137+
* Generated by scripts/unicode.js from the Unicode Character Database ${version}, don't edit. The data is
138+
* Copyright © 1991-${new Date().getUTCFullYear()} Unicode, Inc., Unicode License v3 (see THIRD_PARTY_NOTICES.md and
139+
* licenses/Unicode-3.0.txt)
140+
*/
141+
142+
/** a property: the names of its values (the first is the default) and its ranges (see scripts/unicode.js) */
143+
export interface EncodedProperty {
144+
names: string[];
145+
data: string;
146+
}
147+
148+
export const UNICODE_VERSION = '${version}';
149+
`;
150+
for (const [name, t] of Object.entries(tables))
151+
out += `\n/** ${t.description} (${t.ranges} ranges) */\nexport const ${name}: EncodedProperty = {\n names: ${JSON.stringify(t.names)},\n data: '${t.data}'\n};\n`;
152+
out += `\n/** Bidi_Paired_Bracket: [code point, its pair, 1 opening / 2 closing] */\nexport const brackets: number[] = ${JSON.stringify(brackets.flat())};\n`;
153+
out += `\n/** Bidi_Mirroring_Glyph: [code point, its mirror] */\nexport const mirrors: number[] = ${JSON.stringify(mirrors.flat())};\n`;
154+
155+
fs.writeFileSync(path.join(__dirname, '../src/render/unicode-data.ts'), out);
156+
for (const [name, t] of Object.entries(tables)) console.log(name.padEnd(22), String(t.ranges).padStart(6), 'ranges', String(t.data.length).padStart(7), 'bytes', t.names.length, 'values');
157+
console.log('total', out.length, 'bytes');

0 commit comments

Comments
 (0)