-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
StreamFontMetrics.cs
597 lines (517 loc) · 23.2 KB
/
StreamFontMetrics.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Numerics;
using SixLabors.Fonts.Tables;
using SixLabors.Fonts.Tables.AdvancedTypographic;
using SixLabors.Fonts.Tables.Cff;
using SixLabors.Fonts.Tables.General;
using SixLabors.Fonts.Tables.General.Colr;
using SixLabors.Fonts.Tables.General.Kern;
using SixLabors.Fonts.Tables.General.Post;
using SixLabors.Fonts.Tables.TrueType;
using SixLabors.Fonts.Unicode;
namespace SixLabors.Fonts
{
/// <summary>
/// <para>
/// Represents a font face with metrics, which is a set of glyphs with a specific style (regular, italic, bold etc).
/// </para>
/// <para>The font source is a stream.</para>
/// </summary>
internal partial class StreamFontMetrics : FontMetrics
{
private readonly TrueTypeFontTables? trueTypeFontTables;
private readonly CompactFontTables? compactFontTables;
private readonly OutlineType outlineType;
// https://docs.microsoft.com/en-us/typography/opentype/spec/otff#font-tables
private readonly ConcurrentDictionary<(ushort Id, TextAttributes Attributes, bool IsVerticalLayout), GlyphMetrics[]> glyphCache;
private readonly ConcurrentDictionary<(ushort Id, TextAttributes Attributes, bool IsVerticalLayout), GlyphMetrics[]>? colorGlyphCache;
private readonly FontDescription description;
private readonly HorizontalMetrics horizontalMetrics;
private readonly VerticalMetrics verticalMetrics;
private ushort unitsPerEm;
private float scaleFactor;
private short subscriptXSize;
private short subscriptYSize;
private short subscriptXOffset;
private short subscriptYOffset;
private short superscriptXSize;
private short superscriptYSize;
private short superscriptXOffset;
private short superscriptYOffset;
private short strikeoutSize;
private short strikeoutPosition;
private short underlinePosition;
private short underlineThickness;
private float italicAngle;
/// <summary>
/// Initializes a new instance of the <see cref="StreamFontMetrics"/> class.
/// </summary>
/// <param name="tables">The True Type font tables.</param>
internal StreamFontMetrics(TrueTypeFontTables tables)
{
this.trueTypeFontTables = tables;
this.outlineType = OutlineType.TrueType;
this.description = new FontDescription(tables.Name, tables.Os2, tables.Head);
this.glyphCache = new();
if (tables.Colr is not null)
{
this.colorGlyphCache = new();
}
(HorizontalMetrics HorizontalMetrics, VerticalMetrics VerticalMetrics) metrics = this.Initialize(tables);
this.horizontalMetrics = metrics.HorizontalMetrics;
this.verticalMetrics = metrics.VerticalMetrics;
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamFontMetrics"/> class.
/// </summary>
/// <param name="tables">The Compact Font tables.</param>
internal StreamFontMetrics(CompactFontTables tables)
{
this.compactFontTables = tables;
this.outlineType = OutlineType.CFF;
this.description = new FontDescription(tables.Name, tables.Os2, tables.Head);
this.glyphCache = new();
if (tables.Colr is not null)
{
this.colorGlyphCache = new();
}
(HorizontalMetrics HorizontalMetrics, VerticalMetrics VerticalMetrics) metrics = this.Initialize(tables);
this.horizontalMetrics = metrics.HorizontalMetrics;
this.verticalMetrics = metrics.VerticalMetrics;
}
public HeadTable.HeadFlags HeadFlags { get; private set; }
/// <inheritdoc/>
public override FontDescription Description => this.description;
/// <inheritdoc/>
public override ushort UnitsPerEm => this.unitsPerEm;
/// <inheritdoc/>
public override float ScaleFactor => this.scaleFactor;
/// <inheritdoc/>
public override HorizontalMetrics HorizontalMetrics => this.horizontalMetrics;
/// <inheritdoc/>
public override VerticalMetrics VerticalMetrics => this.verticalMetrics;
/// <inheritdoc/>
public override short SubscriptXSize => this.subscriptXSize;
/// <inheritdoc/>
public override short SubscriptYSize => this.subscriptYSize;
/// <inheritdoc/>
public override short SubscriptXOffset => this.subscriptXOffset;
/// <inheritdoc/>
public override short SubscriptYOffset => this.subscriptYOffset;
/// <inheritdoc/>
public override short SuperscriptXSize => this.superscriptXSize;
/// <inheritdoc/>
public override short SuperscriptYSize => this.superscriptYSize;
/// <inheritdoc/>
public override short SuperscriptXOffset => this.superscriptXOffset;
/// <inheritdoc/>
public override short SuperscriptYOffset => this.superscriptYOffset;
/// <inheritdoc/>
public override short StrikeoutSize => this.strikeoutSize;
/// <inheritdoc/>
public override short StrikeoutPosition => this.strikeoutPosition;
/// <inheritdoc/>
public override short UnderlinePosition => this.underlinePosition;
/// <inheritdoc/>
public override short UnderlineThickness => this.underlineThickness;
/// <inheritdoc/>
public override float ItalicAngle => this.italicAngle;
/// <inheritdoc/>
internal override bool TryGetGlyphId(CodePoint codePoint, out ushort glyphId)
=> this.TryGetGlyphId(codePoint, null, out glyphId, out bool _);
/// <inheritdoc/>
internal override bool TryGetGlyphId(CodePoint codePoint, CodePoint? nextCodePoint, out ushort glyphId, out bool skipNextCodePoint)
{
CMapTable cmap = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.Cmap
: this.compactFontTables!.Cmap;
return cmap.TryGetGlyphId(codePoint, nextCodePoint, out glyphId, out skipNextCodePoint);
}
/// <inheritdoc/>
internal override bool TryGetGlyphClass(ushort glyphId, [NotNullWhen(true)] out GlyphClassDef? glyphClass)
{
GlyphDefinitionTable? gdef = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.Gdef
: this.compactFontTables!.Gdef;
glyphClass = null;
return gdef is not null && gdef.TryGetGlyphClass(glyphId, out glyphClass);
}
/// <inheritdoc/>
internal override bool TryGetMarkAttachmentClass(ushort glyphId, [NotNullWhen(true)] out GlyphClassDef? markAttachmentClass)
{
GlyphDefinitionTable? gdef = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.Gdef
: this.compactFontTables!.Gdef;
markAttachmentClass = null;
return gdef is not null && gdef.TryGetMarkAttachmentClass(glyphId, out markAttachmentClass);
}
/// <inheritdoc/>
public override bool TryGetGlyphMetrics(
CodePoint codePoint,
TextAttributes textAttributes,
TextDecorations textDecorations,
LayoutMode layoutMode,
ColorFontSupport support,
[NotNullWhen(true)] out IReadOnlyList<GlyphMetrics>? metrics)
{
// We return metrics for the special glyph representing a missing character, commonly known as .notdef.
this.TryGetGlyphId(codePoint, out ushort glyphId);
metrics = this.GetGlyphMetrics(codePoint, glyphId, textAttributes, textDecorations, layoutMode, support);
return metrics.Any();
}
/// <inheritdoc/>
internal override IReadOnlyList<GlyphMetrics> GetGlyphMetrics(
CodePoint codePoint,
ushort glyphId,
TextAttributes textAttributes,
TextDecorations textDecorations,
LayoutMode layoutMode,
ColorFontSupport support)
{
GlyphType glyphType = GlyphType.Standard;
if (glyphId == 0)
{
// A glyph was not found in this face for the previously matched
// codepoint. Set to fallback.
glyphType = GlyphType.Fallback;
}
if (support == ColorFontSupport.MicrosoftColrFormat
&& this.TryGetColoredMetrics(codePoint, glyphId, textAttributes, textDecorations, layoutMode, out GlyphMetrics[]? metrics))
{
return metrics;
}
// We overwrite the cache entry for this type should the attributes change.
return this.glyphCache.GetOrAdd(
CreateCacheKey(codePoint, glyphId, textAttributes, layoutMode),
key => new[]
{
this.CreateGlyphMetrics(
codePoint,
key.Id,
glyphType,
key.Attributes,
textDecorations,
key.IsVerticalLayout)
});
}
/// <inheritdoc />
internal override IReadOnlyList<CodePoint> GetAvailableCodePoints()
{
CMapTable cmap = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.Cmap
: this.compactFontTables!.Cmap;
return cmap.GetAvailableCodePoints();
}
/// <inheritdoc/>
internal override bool TryGetGSubTable([NotNullWhen(true)] out GSubTable? gSubTable)
{
gSubTable = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.GSub
: this.compactFontTables!.GSub;
return gSubTable is not null;
}
/// <inheritdoc/>
internal override void ApplySubstitution(GlyphSubstitutionCollection collection)
{
if (this.TryGetGSubTable(out GSubTable? gSubTable))
{
gSubTable.ApplySubstitution(this, collection);
}
}
/// <inheritdoc/>
internal override bool TryGetKerningOffset(ushort previousId, ushort currentId, out Vector2 vector)
{
bool isTTF = this.outlineType == OutlineType.TrueType;
KerningTable? kern = isTTF
? this.trueTypeFontTables!.Kern
: this.compactFontTables!.Kern;
if (kern is null)
{
vector = default;
return false;
}
return kern.TryGetKerningOffset(previousId, currentId, out vector);
}
/// <inheritdoc/>
internal override void UpdatePositions(GlyphPositioningCollection collection)
{
bool isTTF = this.outlineType == OutlineType.TrueType;
GPosTable? gpos = isTTF
? this.trueTypeFontTables!.GPos
: this.compactFontTables!.GPos;
bool kerned = false;
KerningMode kerningMode = collection.TextOptions.KerningMode;
gpos?.TryUpdatePositions(this, collection, out kerned);
// TODO: I don't think we should disable kerning here.
if (!kerned && kerningMode != KerningMode.None)
{
KerningTable? kern = isTTF
? this.trueTypeFontTables!.Kern
: this.compactFontTables!.Kern;
if (kern?.Count > 0)
{
// Set max constraints to prevent OutOfMemoryException or infinite loops from attacks.
int maxCount = AdvancedTypographicUtils.GetMaxAllowableShapingCollectionCount(collection.Count);
for (int index = 1; index < collection.Count; index++)
{
if (index >= maxCount)
{
break;
}
kern.UpdatePositions(this, collection, index - 1, index);
}
}
}
}
/// <summary>
/// Reads a <see cref="StreamFontMetrics"/> from the specified stream.
/// </summary>
/// <param name="path">The file path.</param>
/// <returns>a <see cref="StreamFontMetrics"/>.</returns>
public static StreamFontMetrics LoadFont(string path)
{
using FileStream fs = File.OpenRead(path);
var reader = new FontReader(fs);
return LoadFont(reader);
}
/// <summary>
/// Reads a <see cref="StreamFontMetrics"/> from the specified stream.
/// </summary>
/// <param name="path">The file path.</param>
/// <param name="offset">Position in the stream to read the font from.</param>
/// <returns>a <see cref="StreamFontMetrics"/>.</returns>
public static StreamFontMetrics LoadFont(string path, long offset)
{
using FileStream fs = File.OpenRead(path);
fs.Position = offset;
return LoadFont(fs);
}
/// <summary>
/// Reads a <see cref="StreamFontMetrics"/> from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>a <see cref="StreamFontMetrics"/>.</returns>
public static StreamFontMetrics LoadFont(Stream stream)
{
var reader = new FontReader(stream);
return LoadFont(reader);
}
internal static StreamFontMetrics LoadFont(FontReader reader)
{
if (reader.OutlineType == OutlineType.TrueType)
{
return LoadTrueTypeFont(reader);
}
else
{
return LoadCompactFont(reader);
}
}
private (HorizontalMetrics HorizontalMetrics, VerticalMetrics VerticalMetrics) Initialize<T>(T tables)
where T : IFontTables
{
HeadTable head = tables.Head;
HorizontalHeadTable hhea = tables.Hhea;
VerticalHeadTable? vhea = tables.Vhea;
OS2Table os2 = tables.Os2;
PostTable post = tables.Post;
this.HeadFlags = head.Flags;
this.unitsPerEm = head.UnitsPerEm;
this.scaleFactor = this.unitsPerEm * 72F; // 72 * UnitsPerEm means 1pt = 1px
this.subscriptXSize = os2.SubscriptXSize;
this.subscriptYSize = os2.SubscriptYSize;
this.subscriptXOffset = os2.SubscriptXOffset;
this.subscriptYOffset = os2.SubscriptYOffset;
this.superscriptXSize = os2.SuperscriptXSize;
this.superscriptYSize = os2.SuperscriptYSize;
this.superscriptXOffset = os2.SuperscriptXOffset;
this.superscriptYOffset = os2.SuperscriptYOffset;
this.strikeoutSize = os2.StrikeoutSize;
this.strikeoutPosition = os2.StrikeoutPosition;
this.underlinePosition = post.UnderlinePosition;
this.underlineThickness = post.UnderlineThickness;
this.italicAngle = post.ItalicAngle;
HorizontalMetrics horizontalMetrics = InitializeHorizontalMetrics(hhea, vhea, os2);
VerticalMetrics verticalMetrics = InitializeVerticalMetrics(horizontalMetrics, vhea);
return (horizontalMetrics, verticalMetrics);
}
private static HorizontalMetrics InitializeHorizontalMetrics(HorizontalHeadTable hhea, VerticalHeadTable? vhea, OS2Table os2)
{
short ascender;
short descender;
short lineGap;
short lineHeight;
short advanceWidthMax;
short advanceHeightMax;
// https://www.microsoft.com/typography/otspec/recom.htm#tad
// We use the same approach as FreeType for calculating the the global ascender, descender, and
// height of OpenType fonts for consistency.
//
// 1.If the OS/ 2 table exists and the fsSelection bit 7 is set (USE_TYPO_METRICS), trust the font
// and use the Typo* metrics.
// 2.Otherwise, use the HorizontalHeadTable "hhea" table's metrics.
// 3.If they are zero and the OS/ 2 table exists,
// - Use the OS/ 2 table's sTypo* metrics if they are non-zero.
// - Otherwise, use the OS / 2 table's usWin* metrics.
bool useTypoMetrics = os2.FontStyle.HasFlag(OS2Table.FontStyleSelection.USE_TYPO_METRICS);
if (useTypoMetrics)
{
ascender = os2.TypoAscender;
descender = os2.TypoDescender;
lineGap = os2.TypoLineGap;
lineHeight = (short)(ascender - descender + lineGap);
}
else
{
ascender = hhea.Ascender;
descender = hhea.Descender;
lineGap = hhea.LineGap;
lineHeight = (short)(ascender - descender + lineGap);
}
if (ascender == 0 || descender == 0)
{
if (os2.TypoAscender != 0 || os2.TypoDescender != 0)
{
ascender = os2.TypoAscender;
descender = os2.TypoDescender;
lineGap = os2.TypoLineGap;
lineHeight = (short)(ascender - descender + lineGap);
}
else
{
ascender = (short)os2.WinAscent;
descender = (short)-os2.WinDescent;
lineHeight = (short)(ascender - descender);
}
}
advanceWidthMax = (short)hhea.AdvanceWidthMax;
advanceHeightMax = vhea == null ? lineHeight : vhea.AdvanceHeightMax;
return new()
{
Ascender = ascender,
Descender = descender,
LineGap = lineGap,
LineHeight = lineHeight,
AdvanceWidthMax = advanceWidthMax,
AdvanceHeightMax = advanceHeightMax
};
}
private static VerticalMetrics InitializeVerticalMetrics(HorizontalMetrics metrics, VerticalHeadTable? vhea)
{
VerticalMetrics verticalMetrics = new()
{
Ascender = metrics.Ascender,
Descender = metrics.Descender,
LineGap = metrics.LineGap,
LineHeight = metrics.LineHeight,
AdvanceWidthMax = metrics.AdvanceWidthMax,
AdvanceHeightMax = metrics.AdvanceHeightMax,
Synthesized = true
};
if (vhea is null)
{
return verticalMetrics;
}
short ascender = vhea.Ascender;
// Always negative due to the grid orientation.
short descender = (short)(vhea.Descender > 0 ? -vhea.Descender : vhea.Descender);
short lineGap = vhea.LineGap;
short lineHeight = (short)(ascender - descender + lineGap);
verticalMetrics.Ascender = ascender;
verticalMetrics.Descender = descender;
verticalMetrics.LineGap = lineGap;
verticalMetrics.LineHeight = lineHeight;
verticalMetrics.Synthesized = false;
return verticalMetrics;
}
/// <summary>
/// Reads a <see cref="StreamFontMetrics"/> from the specified stream.
/// </summary>
/// <param name="path">The file path.</param>
/// <returns>a <see cref="StreamFontMetrics"/>.</returns>
public static StreamFontMetrics[] LoadFontCollection(string path)
{
using FileStream fs = File.OpenRead(path);
return LoadFontCollection(fs);
}
/// <summary>
/// Reads a <see cref="StreamFontMetrics"/> from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>a <see cref="StreamFontMetrics"/>.</returns>
public static StreamFontMetrics[] LoadFontCollection(Stream stream)
{
long startPos = stream.Position;
var reader = new BigEndianBinaryReader(stream, true);
var ttcHeader = TtcHeader.Read(reader);
var fonts = new StreamFontMetrics[(int)ttcHeader.NumFonts];
for (int i = 0; i < ttcHeader.NumFonts; ++i)
{
stream.Position = startPos + ttcHeader.OffsetTable[i];
fonts[i] = LoadFont(stream);
}
return fonts;
}
private static (ushort Id, TextAttributes Attributes, bool IsVerticalLayout) CreateCacheKey(
CodePoint codePoint,
ushort glyphId,
TextAttributes textAttributes,
LayoutMode layoutMode)
=> (glyphId, textAttributes, AdvancedTypographicUtils.IsVerticalGlyph(codePoint, layoutMode));
private bool TryGetColoredMetrics(
CodePoint codePoint,
ushort glyphId,
TextAttributes textAttributes,
TextDecorations textDecorations,
LayoutMode layoutMode,
[NotNullWhen(true)] out GlyphMetrics[]? metrics)
{
ColrTable? colr = this.outlineType == OutlineType.TrueType
? this.trueTypeFontTables!.Colr
: this.compactFontTables!.Colr;
if (colr == null || this.colorGlyphCache == null)
{
metrics = null;
return false;
}
// We overwrite the cache entry for this type should the attributes change.
metrics = this.colorGlyphCache.GetOrAdd(CreateCacheKey(codePoint, glyphId, textAttributes, layoutMode), key =>
{
GlyphMetrics[] m = Array.Empty<GlyphMetrics>();
Span<LayerRecord> indexes = colr.GetLayers(key.Id);
if (indexes.Length > 0)
{
m = new GlyphMetrics[indexes.Length];
for (int i = 0; i < indexes.Length; i++)
{
LayerRecord layer = indexes[i];
m[i] = this.CreateGlyphMetrics(codePoint, layer.GlyphId, GlyphType.ColrLayer, key.Attributes, textDecorations, key.IsVerticalLayout, layer.PaletteIndex);
}
}
return m;
});
return metrics.Length > 0;
}
private GlyphMetrics CreateGlyphMetrics(
CodePoint codePoint,
ushort glyphId,
GlyphType glyphType,
TextAttributes textAttributes,
TextDecorations textDecorations,
bool isVerticalLayout,
ushort paletteIndex = 0)
=> this.outlineType switch
{
OutlineType.TrueType => this.CreateTrueTypeGlyphMetrics(codePoint, glyphId, glyphType, textAttributes, textDecorations, isVerticalLayout, paletteIndex),
OutlineType.CFF => this.CreateCffGlyphMetrics(codePoint, glyphId, glyphType, textAttributes, textDecorations, isVerticalLayout, paletteIndex),
_ => throw new NotSupportedException(),
};
}
}