-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOpenType.cs
1407 lines (1241 loc) · 56.2 KB
/
OpenType.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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Text;
namespace TriDelta.OpenType {
//Note: This parser only supports Microsoft "TTF" fonts with Windows encodings.
// OpenType fonts are NOT supported.
// Collections are NOT supported.
// Composite glyphs are NOT supported.
public class OpenFont {
// Private storage
private float m_sfnt_version;
private int m_search_range;
private int m_entry_selector;
private int m_range_shift;
private int m_curve_quality = 2;
private float m_optimize_tolerance = 0.500f;
private int m_device_dpi;
private float m_point_size;
private float m_glyph_scale;
private string m_name;
private string m_filePath;
private bool m_font_valid = false;
private bool m_font_cached = false;
SectionHead head;
SectionMaxp maxp;
SectionHhea hhea;
Dictionary<string, Section> records;
Dictionary<int, string> names;
Dictionary<int, Glyph> glyphs;
List<HorizontalMetrics> glyphmetrics;
Dictionary<char, Glyph> glyphmap;
List<PointF> m_last_controllist;
//winapi for grabbing screen dpi
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
//-------------------------------------------------------------------------------------
// Static properties and methods
//-------------------------------------------------------------------------------------
private static List<OpenFont> m_fontcache;
/// <summary>Gets a list of supported fonts installed on the system</summary>
public static List<OpenFont> Fonts {
get {
if (m_fontcache == null) {
m_fontcache = new List<OpenFont>();
string pathFonts = GetPath(20); //Windows font folder
DirectoryInfo folder = new DirectoryInfo(pathFonts);
FileInfo[] files = folder.GetFiles();
OpenFont font;
foreach (FileInfo file in files) {
try {
if (file.Extension.ToLower() == ".ttf") {
font = new OpenFont(file.FullName, 12);
//Load times increase dramatically at glyph high counts.
//For example, the font "Arial Unicode MS" contains 50377 glyphs.
//Some performance has been gained by caching point data for glyphs and only on demand.
//The remaining issue is the byte-by-byte reading in the .ReadStream function which incurs
// a serious performance hit. A future enhancement would be reading the entire glyph data
// into a byte array and operating off of that instead of reading from the stream one
// byte at a time.
if (font.GlyphCount < 10000)
m_fontcache.Add(new OpenFont(file.FullName, 12));
}
} catch { } //Dont care about what fonts were skipped
}
}
return m_fontcache;
}
}
/// <summary>Gets a font based on its font name</summary>
public static OpenFont GetFont(string name) {
foreach (OpenFont font in Fonts) {
if (font.Name == name)
return font;
}
return null;
}
//Retrieves a special window folder based on its index
private static string GetPath(int folder) {
StringBuilder lpszPath = new StringBuilder(260);
SHGetFolderPath(IntPtr.Zero, folder, IntPtr.Zero, 0, lpszPath);
return lpszPath.ToString();
}
//-------------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------------
public OpenFont(string FontFile, float pointSize) {
m_filePath = FontFile;
m_name = FontFile;
m_device_dpi = GetDpi();
m_point_size = pointSize;
records = new Dictionary<string, Section>();
names = new Dictionary<int, string>();
glyphs = new Dictionary<int, Glyph>();
glyphmetrics = new List<HorizontalMetrics>();
glyphmap = new Dictionary<char, Glyph>();
LoadFont(FontFile);
}
//determine the system wide dpi setting
private int GetDpi() {
IntPtr hdc = GetDC(IntPtr.Zero);
int dpi;
if (hdc != IntPtr.Zero) {
dpi = GetDeviceCaps(hdc, 88); //LOGPIXELSX
ReleaseDC(IntPtr.Zero, hdc);
return dpi;
}
return 0;
}
//-------------------------------------------------------------------------------------
// Properties
//-------------------------------------------------------------------------------------
public Dictionary<int, Glyph> Glyphs {
get { return glyphs; }
}
public int GlyphCount {
get { return maxp.numGlyphs; }
}
public int Quality {
get { return m_curve_quality; }
set {
m_curve_quality = value;
foreach (KeyValuePair<int, Glyph> pair in glyphs)
pair.Value.Update();
}
}
public float Tolerance {
get { return m_optimize_tolerance; }
set {
m_optimize_tolerance = value;
foreach (KeyValuePair<int, Glyph> pair in glyphs)
pair.Value.Update();
}
}
public int UnitsPerEM {
get { return head.unitsPerEM; }
}
public float GlyphScale {
get { return m_glyph_scale; }
}
public float PointSize {
get { return m_point_size; }
set {
m_point_size = value;
CalculateGlyphScale();
}
}
public string Name {
get { return m_name; }
}
public string FontFamily {
get {
if (names.ContainsKey(1))
return names[1];
return "";
}
}
public List<PointF> LastControlList {
get {
return m_last_controllist;
}
}
//-------------------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------------------
/// <summary>Retrieve the glyph data associated with a unicode character.</summary>
public Glyph GetGlyph(Char c) {
if (!m_font_cached)
CacheData();
if (glyphmap.ContainsKey(c))
return glyphmap[c];
return glyphs[0];
}
/// <summary>Renders the outline of a string to graphic buffer</summary>
/// <param name="g">A graphic buffer to draw the outline on</param>
/// <param name="p">The pen to draw the outline with</param>
/// <param name="text">Text to render</param>
/// <param name="origin">The leftmost location for text</param>
/// <param name="vector">The rightmost location for text</param>
/// <param name="mode">Determines how the text should be drawn</param>
/// <param name="alignment">Determines where the text should be drawn</param>
/// <param name="padding">Extra space to add between characters</param>
public void RenderString(Graphics g, Pen p, string text, PointF origin, PointF vector, PlotMode mode, TextAlignment alignment, int padding) {
if (!m_font_cached)
CacheData();
if (origin.Equals(vector))
return;
List<PointF[]> lines = PlotString(text, origin, vector, mode, alignment, padding);
if (lines != null) {
foreach (PointF[] points in lines) {
g.DrawLines(p, points);
}
}
}
/// <summary>Creates a list of points that represent a string</summary>
/// <param name="text">Text to render</param>
/// <param name="origin">The leftmost location for text</param>
/// <param name="vector">The rightmost location for text</param>
/// <param name="mode">Determines how the text should be drawn</param>
/// <param name="alignment">Determines where the text should be drawn</param>
/// <param name="padding">Extra space to add between characters</param>
public List<PointF[]> PlotString(string text, PointF origin, PointF vector, PlotMode mode, TextAlignment alignment, float padding) {
if (!m_font_cached)
CacheData();
List<PointF[]> lines = new List<PointF[]>();
List<PointF> controls = new List<PointF>();
Glyph glyph;
PointF pos = origin;
float angle, offset, width;
double sin, cos;
float radius = (float)Math.Sqrt((vector.X - origin.X) * (vector.X - origin.X) + (vector.Y - origin.Y) * (vector.Y - origin.Y));
float rotation = 0;
float lsb;
switch (mode) {
case PlotMode.Normal:
if (text.Length > 0) {
angle = (float)Math.Atan2(vector.Y - origin.Y, vector.X - origin.X);
sin = Math.Sin(angle);
cos = Math.Cos(angle);
//measure the string width
float totalwidth = 0;
foreach (char c in text) {
glyph = GetGlyph(c);
totalwidth += glyph.Width;
if (alignment != TextAlignment.Justified)
totalwidth += padding;
}
totalwidth *= m_glyph_scale;
if (totalwidth > radius)
alignment = TextAlignment.Left;
switch (alignment) {
case TextAlignment.Center:
lsb = ((radius / 2) - (totalwidth / 2));
pos.X += (float)(cos * lsb);
pos.Y += (float)(sin * lsb);
break;
case TextAlignment.Justified:
if (text.Length > 1)
padding += ((radius - totalwidth) / (text.Length - 1)) / m_glyph_scale;
break;
case TextAlignment.Right:
lsb = radius - totalwidth;
pos.X += (float)(cos * lsb);
pos.Y += (float)(sin * lsb);
break;
}
foreach (char c in text) {
glyph = GetGlyph(c);
lines.AddRange(glyph.TranslateOutline(pos, angle + rotation, RotationAnchor.Origin));
controls.AddRange(glyph.TranslateOutlineControls(pos, angle + rotation, RotationAnchor.Origin));
width = (glyph.Width + padding) * m_glyph_scale;
pos.X += (float)(cos * width);
pos.Y += (float)(sin * width);
}
}
break;
case PlotMode.Circle:
float justifiedrads, offset2;
//precache
angle = (float)Math.Atan2(vector.Y - origin.Y, vector.X - origin.X);
offset = angle;
rotation = -1.57079637f; //(float)((double)-90 * (Math.PI / 180));
offset2 = justifiedrads = 0f;
if (alignment == TextAlignment.Justified)
justifiedrads = (float)((Math.PI / (double)text.Length) * 2);
foreach (char c in text) {
glyph = GetGlyph(c);
if (alignment != TextAlignment.Justified)
offset2 = (((glyph.Width + padding) * m_glyph_scale) / radius) / 2;
pos.X = origin.X + (float)(Math.Cos(offset - offset2) * radius);
pos.Y = origin.Y + (float)(Math.Sin(offset - offset2) * radius);
lines.AddRange(glyph.TranslateOutline(pos, offset - offset2 + rotation, RotationAnchor.CenterBaseline));
controls.AddRange(glyph.TranslateOutlineControls(pos, offset - offset2 + rotation, RotationAnchor.CenterBaseline));
if (alignment == TextAlignment.Justified) {
offset -= justifiedrads;
} else {
offset -= ((glyph.Width + padding) * m_glyph_scale) / radius;
}
}
break;
default:
throw new OpenFontException(this, "Unsupported plotting mode");
}
m_last_controllist = controls;
return lines;
}
/// <summary>Returns the font name</summary>
public override string ToString() {
return Name;
}
//-------------------------------------------------------------------------------------
// Internal Functions
//-------------------------------------------------------------------------------------
private void LoadFont(string FilePath) {
Stream s = File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
try {
m_sfnt_version = Tools.ReadFixed(s);
if (m_sfnt_version != 1)
throw new OpenFontException(this, "Unsupported font version");
//read the font header
int sectioncnt = Tools.ReadUShort(s);
m_search_range = Tools.ReadUShort(s);
m_entry_selector = Tools.ReadUShort(s);
m_range_shift = Tools.ReadUShort(s);
//cache the font table data
for (int i = 0; i < sectioncnt; i++) {
Section newsection = new Section(
Tools.ReadString(s, 4), //tag
Tools.ReadInt(s), //checksum
Tools.ReadInt(s), //offset
Tools.ReadInt(s) //length
);
records.Add(newsection.Tag, newsection);
}
//only accept the font if certain tables exist
if (!records.ContainsKey("glyf"))
throw new OpenFontException(this, "Only vector based fonts is supported.");
if (!records.ContainsKey("head"))
throw new OpenFontException(this, "missing required table: head");
if (!records.ContainsKey("hhea"))
throw new OpenFontException(this, "missing required table: hhea");
if (!records.ContainsKey("maxp"))
throw new OpenFontException(this, "missing required table: maxp");
if (!records.ContainsKey("hmtx"))
throw new OpenFontException(this, "missing required table: hmtx");
if (!records.ContainsKey("loca"))
throw new OpenFontException(this, "missing required table: loca");
if (!records.ContainsKey("cmap"))
throw new OpenFontException(this, "missing required table: cmap");
if (!records.ContainsKey("name"))
throw new OpenFontException(this, "missing required table: name");
//only read the header information for the first pass. glyph data is lazy loaded upon demand.
ReadNAME(s, records["name"].Offset);
ReadHEAD(s, records["head"].Offset);
ReadHHEA(s, records["hhea"].Offset);
ReadMAXP(s, records["maxp"].Offset);
ReadHMTX(s, records["hmtx"].Offset);
m_font_valid = true;
} catch (OpenFontException ex) {
Debug.WriteLine("OFE ERROR: " + ex.Message);
throw ex;
} catch (Exception ex) {
Debug.WriteLine("ERROR: " + ex.Message);
} finally {
s.Close();
}
}
/// <summary>Builds and caches the glyph data</summary>
public void CacheData() {
if (m_font_cached)
return;
if (!m_font_valid)
throw new OpenFontException(this, "Unable to cache becuase the font is unsupported");
Stream s = File.Open(m_filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
try {
ReadGLYF(s, records["loca"], records["glyf"]);
ReadCMAP(s, records["cmap"].Offset);
} catch (OpenFontException ex) {
m_font_valid = false;
throw ex;
} catch (Exception ex) {
m_font_valid = false;
throw ex;
} finally {
s.Close();
}
m_font_cached = true;
}
private void CalculateGlyphScale() {
m_glyph_scale = (m_point_size * m_device_dpi / 72) / head.unitsPerEM;
}
private void ReadHEAD(Stream s, int offset) {
s.Position = offset;
float version = Tools.ReadFixed(s);
if (version != 1.0f)
throw new OpenFontException(this, "HEAD table declares an unsupported version");
head.revision = Tools.ReadFixed(s);
head.checksumAdjustment = Tools.ReadInt(s);
head.magicNumber = Tools.ReadInt(s);
head.flags = Tools.ReadUShort(s);
head.unitsPerEM = Tools.ReadUShort(s);
for (int i = 0; i < 8; i++) //consume created & modified dates (64bit each)
Tools.ReadUShort(s);
head.xMin = Tools.ReadShort(s);
head.yMin = Tools.ReadShort(s);
head.xMax = Tools.ReadShort(s);
head.yMax = Tools.ReadShort(s);
head.macStyle = Tools.ReadUShort(s);
head.lowestRecPPEM = Tools.ReadUShort(s);
head.fontDirectionHint = Tools.ReadShort(s);
head.indexToLocFormat = Tools.ReadShort(s);
head.glyphDataFormat = Tools.ReadShort(s);
if (head.magicNumber != 0x5F0F3CF5)
throw new OpenFontException(this, "Invalid Font");
CalculateGlyphScale();
}
private void ReadMAXP(Stream s, int offset) {
s.Position = offset;
float version = Tools.ReadFixed(s);
if (!(version == 1.0f || version == 0.5f))
throw new OpenFontException(this, "MAXP table declares an unsupported version");
maxp.numGlyphs = Tools.ReadUShort(s);
if (version == 1.0f) {
maxp.maxPoints = Tools.ReadUShort(s);
maxp.maxContours = Tools.ReadUShort(s);
maxp.maxCompositePoints = Tools.ReadUShort(s);
maxp.maxCompositeContours = Tools.ReadUShort(s);
maxp.maxZones = Tools.ReadUShort(s);
maxp.maxTwilightPoints = Tools.ReadUShort(s);
maxp.maxStorage = Tools.ReadUShort(s);
maxp.maxFunctionDefs = Tools.ReadUShort(s);
maxp.maxInstructionDefs = Tools.ReadUShort(s);
maxp.maxStackElements = Tools.ReadUShort(s);
maxp.maxSizeOfInstructions = Tools.ReadUShort(s);
maxp.maxComponentElements = Tools.ReadUShort(s);
maxp.maxComponentDepth = Tools.ReadUShort(s);
}
}
private void ReadHHEA(Stream s, int offset) {
s.Position = offset;
float version = Tools.ReadFixed(s);
if (version != 1.0f)
throw new OpenFontException(this, "HHEA table declares an unsupported version");
hhea.Ascender = Tools.ReadShort(s);
hhea.Descender = Tools.ReadShort(s);
hhea.LineGap = Tools.ReadShort(s);
hhea.advanceWidthMax = Tools.ReadUShort(s);
hhea.minLeftSideBearing = Tools.ReadShort(s);
hhea.minRightSideBearing = Tools.ReadShort(s);
hhea.xMaxExtent = Tools.ReadShort(s);
hhea.caretSlopeRise = Tools.ReadShort(s);
hhea.caretSlopeRun = Tools.ReadShort(s);
hhea.caretOffset = Tools.ReadShort(s);
Tools.ReadShort(s); //reserved
Tools.ReadShort(s); //reserved
Tools.ReadShort(s); //reserved
Tools.ReadShort(s); //reserved
hhea.metricDataFormat = Tools.ReadShort(s);
hhea.numberOfHMetrics = Tools.ReadUShort(s);
}
private void ReadHMTX(Stream s, int offset) {
int i;
s.Position = offset;
HorizontalMetrics metrics;
metrics.advanceWidth = 0; //squelch compiler error
//read the base metric info
for (i = 0; i < hhea.numberOfHMetrics; i++) {
metrics.advanceWidth = Tools.ReadUShort(s);
metrics.lsb = Tools.ReadShort(s);
glyphmetrics.Add(metrics);
}
//add additional lsb data for monospaced fonts, if applicable
for (i = 0; i < (maxp.numGlyphs - hhea.numberOfHMetrics); i++) {
metrics.lsb = Tools.ReadShort(s);
glyphmetrics.Add(metrics);
}
}
private void ReadNAME(Stream s, int offset) {
s.Position = offset;
NameRecord record;
Dictionary<int, SortedList<int, NameRecord>> records = new Dictionary<int, SortedList<int, NameRecord>>();
//read name table header
int format = Tools.ReadUShort(s);
int count = Tools.ReadUShort(s);
int stringOffset = Tools.ReadUShort(s);
//read and cache the tables
for (int i = 0; i < count; i++) {
record.platformID = Tools.ReadUShort(s);
record.encodingID = Tools.ReadUShort(s);
record.languageID = Tools.ReadUShort(s);
record.nameID = Tools.ReadUShort(s);
record.length = Tools.ReadUShort(s);
record.offset = Tools.ReadUShort(s);
if (record.platformID == 3) {
if (!records.ContainsKey(record.nameID))
records[record.nameID] = new SortedList<int, NameRecord>();
records[record.nameID].Add(record.languageID, record);
}
}
//for each string ID, pull out string for the current language or the first in the sorted pile if not found
int currentLangId = CultureInfo.CurrentCulture.LCID;
foreach (KeyValuePair<int, SortedList<int, NameRecord>> outer in records) {
SortedList<int, NameRecord> inner = outer.Value;
if (inner.ContainsKey(currentLangId))
record = inner[currentLangId];
else
record = inner[inner.Keys[0]];
s.Position = offset + stringOffset + record.offset;
string text = Tools.ReadUnicodeString(s, record.length);
names[outer.Key] = text;
}
if (names.ContainsKey(4))
m_name = names[4];
else if (names.ContainsKey(1))
m_name = names[1];
}
private void ReadCMAP(Stream s, int offset) {
s.Position = offset;
int i;
int version = Tools.ReadUShort(s);
if (version != 0f)
throw new OpenFontException(this, "CMAP table declares an unsupported version");
//read in the encoding list for the microsoft platform and sort it
SortedList<int, MappingTable> encodings = new SortedList<int, MappingTable>();
int numTables = Tools.ReadUShort(s);
for (i = 0; i < numTables; i++) {
MappingTable table;
table.platformID = Tools.ReadUShort(s);
table.encodingID = Tools.ReadUShort(s);
table.offset = Tools.ReadInt(s);
//only interested in the microsoft platform
if (table.platformID == 3)
encodings.Add(table.encodingID, table);
}
if (encodings.Count == 0)
throw new OpenFontException(this, "No suitable font encoding is available.");
//take the lowest encoding the in the platform and process it
MappingTable chartable = encodings[encodings.Keys[0]];
s.Position = offset + chartable.offset;
int format = Tools.ReadUShort(s);
switch (format) {
case 4: //dumb m$ format
//read format info
int length = Tools.ReadUShort(s);
int endoffset = offset + chartable.offset + length;
int lang = Tools.ReadUShort(s);
int segCountX2 = Tools.ReadUShort(s);
int segCount = segCountX2 >> 1; //cause I can!
int searchRange = Tools.ReadUShort(s);
int entrySelector = Tools.ReadUShort(s);
int rangeShift = Tools.ReadUShort(s);
bool isSymbol = chartable.encodingID == 0;
//read segment data
int[] endCount = new int[segCount];
int[] startCount = new int[segCount];
int[] idDelta = new int[segCount];
int[] idRangeOffset = new int[segCount];
for (i = 0; i < segCount; i++)
endCount[i] = Tools.ReadUShort(s);
Tools.ReadUShort(s); //reservedPad
for (i = 0; i < segCount; i++)
startCount[i] = Tools.ReadUShort(s);
for (i = 0; i < segCount; i++)
idDelta[i] = Tools.ReadUShort(s);
for (i = 0; i < segCount; i++)
idRangeOffset[i] = Tools.ReadUShort(s);
int bytesLeft = endoffset - (int)s.Position;
int[] glyphIdArray = new int[bytesLeft / 2];
for (i = 0; i < (bytesLeft / 2); i++)
glyphIdArray[i] = Tools.ReadUShort(s);
//process the segment data
int unicode, gid, delta, shift, shift2;
char keycode;
shift2 = 0;
for (i = 0; i < segCount; i++) {
//Do not capture the table terminator character
if (startCount[i] == 0xFFFF)
break;
delta = idDelta[i];
shift = idRangeOffset[i];
if (shift > 0)
shift2 = (shift / 2) - (segCount - i);
//process each unicode character in the range
for (unicode = startCount[i]; unicode <= endCount[i]; unicode++) {
//look up the glyph id for the unicode character
if (shift > 0)
gid = glyphIdArray[(unicode - startCount[i]) + shift2];
else
gid = (unicode + delta) % 65536;
//convert the unicode if this is a symbol font
if (isSymbol)
keycode = (char)(unicode & 0x00ff);
else
keycode = (char)unicode;
//bind the glyph to the character code if not already taken
if (!glyphmap.ContainsKey(keycode)) {
if (glyphs.ContainsKey(gid))
glyphmap.Add(keycode, glyphs[gid]);
else
glyphmap.Add(keycode, glyphs[0]);
}
}
}
break;
default:
throw new OpenFontException(this, "Unsupported character binding format.");
}
}
private void ReadGLYF(Stream s, Section loca, Section glyf) {
//read offset data. this also declares the glyph id (index)
s.Position = loca.Offset;
int[] offsets = new int[maxp.numGlyphs + 1];
if (head.indexToLocFormat == 0) {
for (int i = 0; i <= maxp.numGlyphs; ++i)
offsets[i] = Tools.ReadUShort(s) * 2;
} else {
for (int i = 0; i <= maxp.numGlyphs; ++i)
offsets[i] = Tools.ReadInt(s);
}
//read glyph data
for (int i = 0; i < maxp.numGlyphs; ++i) {
//Add the glyph shell to the pile. If the glyph data is bad (but not missing) then it will render blank
Glyph g = new Glyph(this, i, glyphmetrics[i]);
glyphs.Add(i, g);
if (offsets[i + 1] > glyf.Length) //skip glyphs whos end exceeds the glyph data
continue;
if (offsets[i + 1] < offsets[i]) //skip glyphs whos end offset is set before its start
continue;
if (offsets[i + 1] == offsets[i]) //skip empty declarations
continue;
s.Position = glyf.Offset + offsets[i];
g.ReadStream(s);
}
}
}
/// <summary>A set of stream reading utilities for BigEndian binary data</summary>
public static class Tools {
//The binary data for the open type file format is stored in big-endian machine order.
// These functions extract and reverse the binary data.
public static int ReadUShort(Stream s) {
return (s.ReadByte() << 8) | s.ReadByte();
}
public static int ReadShort(Stream s) {
return (int)((Int16)ReadUShort(s));
}
public static int ReadInt(Stream s) {
return (s.ReadByte() << 24) | (s.ReadByte() << 16) | (s.ReadByte() << 8) | s.ReadByte();
}
public static float ReadFixed(Stream s) {
int val = ReadInt(s);
int mant = val & 0xffff;
return (float)(val >> 16) + (float)(mant / 65536.0);
}
public static float Read2Dot14(Stream s) {
int val = ReadUShort(s);
int mant = val & 0x3fff;
return ((float)((val << 16) >> (16 + 14)) + (float)(mant / 16384.0));
}
public static string ReadString(Stream s, int length) {
byte[] buffer = new byte[length];
s.Read(buffer, 0, length);
return System.Text.Encoding.ASCII.GetString(buffer);
}
public static string ReadUnicodeString(Stream s, int length) {
byte[] buffer = new byte[length];
s.Read(buffer, 0, length);
return System.Text.Encoding.BigEndianUnicode.GetString(buffer);
}
}
public class Section {
private string m_tag;
private int m_checksum;
private int m_offset;
private int m_length;
public Section(string tag, int checksum, int offset, int length) {
m_tag = tag;
m_checksum = checksum;
m_offset = offset;
m_length = length;
}
public string Tag {
get { return m_tag; }
}
public int Offset {
get { return m_offset; }
}
public int Length {
get { return m_length; }
}
public int Checksum {
get { return m_checksum; }
}
}
public struct SectionHead {
public float revision;
public int checksumAdjustment;
public int magicNumber;
public int flags;
public int unitsPerEM;
public int xMin;
public int yMin;
public int xMax;
public int yMax;
public int macStyle;
public int lowestRecPPEM;
public int fontDirectionHint;
public int indexToLocFormat;
public int glyphDataFormat;
}
public struct SectionMaxp {
public int numGlyphs;
public int maxPoints;
public int maxContours;
public int maxCompositePoints;
public int maxCompositeContours;
public int maxZones;
public int maxTwilightPoints;
public int maxStorage;
public int maxFunctionDefs;
public int maxInstructionDefs;
public int maxStackElements;
public int maxSizeOfInstructions;
public int maxComponentElements;
public int maxComponentDepth;
}
public struct SectionHhea {
public int Ascender;
public int Descender;
public int LineGap;
public int advanceWidthMax;
public int minLeftSideBearing;
public int minRightSideBearing;
public int xMaxExtent;
public int caretSlopeRise;
public int caretSlopeRun;
public int caretOffset;
public int metricDataFormat;
public int numberOfHMetrics;
}
public struct HorizontalMetrics {
public int advanceWidth;
public int lsb;
}
public struct MappingTable {
public int platformID;
public int encodingID;
public int offset;
}
public struct NameRecord {
public int platformID;
public int encodingID;
public int languageID;
public int nameID;
public int length;
public int offset;
}
[Flags]
public enum GlyphFlags : int {
OnCurve = 1,
xShort = 2,
yShort = 4,
Repeat = 8,
xSame = 16,
ySame = 32,
}
public enum PlotMode : int {
Normal = 1,
Circle = 2,
}
public enum TextAlignment : int {
Left = 1,
Right = 2,
Center = 3,
Justified = 4
}
public enum RotationAnchor : int {
Origin = 1,
CenterBaseline = 2
}
/// <summary>Defines the outline of a glyph character within the font.</summary>
public class Glyph {
OpenFont m_font;
int gid;
int minX;
int minY;
int maxX;
int maxY;
int width;
int lsb;
int[] instructions;
List<Shape> shapes;
public Glyph(OpenFont font, int id, HorizontalMetrics metrics) {
shapes = new List<Shape>();
m_font = font;
gid = id;
width = metrics.advanceWidth;
lsb = metrics.lsb;
}
/// <summary>Gets the parent font.</summary>
public OpenFont Font {
get { return m_font; }
}
/// <summary>Gets the bezier quality level.</summary>
public int Quality {
get { return Font.Quality; }
}
/// <summary>Gets the optimization tolerance.</summary>
public float Tolerance {
get { return Font.Tolerance; }
}
/// <summary>Gets the global id associated with this glyph.</summary>
public int ID {
get { return gid; }
}
/// <summary>Gets the minimum X boundary for the entire glyph across all shapes.</summary>
public int MinX {
get { return minX; }
}
/// <summary>Gets the minimum Y boundary for the entire glyph across all shapes.</summary>
public int MinY {
get { return minY; }
}
/// <summary>Gets the maximum X boundary for the entire glyph across all shapes.</summary>
public int MaxX {
get { return maxX; }
}
/// <summary>Gets the maximum Y boundary for the entire glyph across all shapes.</summary>
public int MaxY {
get { return maxY; }
}
/// <summary>Gets the width of the glyph</summary>
public int Width {
get { return width; }
}
/// <summary>Gets the left side bearing of the glyph</summary>
public int LSB {
get { return lsb; }
}
/// <summary>Returns an enumerator that iterates through the glyph shape collection.</summary>
public List<Shape>.Enumerator GetEnumerator() {
return shapes.GetEnumerator();
}
/// <summary>Gets the shape at the specified index.</summary>
public Shape this[int index] {
get { return shapes[index]; }
}
/// <summary>Gets the hint instructions defined for this glyph.</summary>
public int[] InstructionList {
get { return instructions; }
}
/// <summary>Updates cached shape data when the bezier quality changes.</summary>
public void Update() {
foreach (Shape shape in shapes) {
if (shape != null)
shape.ClearShape();
}
}
/// <summary>Reads the binary glyph data from the stream.</summary>
public void ReadStream(Stream s) {
try {
int contours = Tools.ReadShort(s);
minX = Tools.ReadShort(s);
minY = Tools.ReadShort(s);
maxX = Tools.ReadShort(s);
maxY = Tools.ReadShort(s);
if (contours >= 0)
ReadSimpleGlyph(s, contours);
//else //composite glyphs are negative
// Debug.WriteLine("-- SKIPPING COMPOSITE GLYPH " + gid);
} catch (Exception ex) {
Debug.WriteLine("error reading glyph " + gid + ": " + ex.Message);
}
}
// Processes contour data for simple glyphs
private void ReadSimpleGlyph(Stream s, int contours) {
int i, j, totalPoints, last_pos, len;
PointF[] points, shapepoints;
GlyphFlags[] flags, shapeflags;
Shape shape;
int[] endPoints;
//For each contour, read the end point.
//shapes = new Shape[contours];
endPoints = new int[contours];
for (i = 0; i < contours; ++i) {
endPoints[i] = Tools.ReadUShort(s);
if (i != 0 && endPoints[i] < endPoints[i - 1]) {
Debug.WriteLine("WARNING: bad contour detected for glyph " + gid);
return;
}
}
//determine how many coordinate points are defined by this glyph
if (contours == 0) {