-
Notifications
You must be signed in to change notification settings - Fork 27
/
Img32.Text.pas
3730 lines (3372 loc) · 107 KB
/
Img32.Text.pas
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
unit Img32.Text;
(*******************************************************************************
* Author : Angus Johnson *
* Version : 4.4 *
* Date : 1 May 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2019-2023 *
* Purpose : TrueType fonts for TImage32 (without Windows dependencies) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************)
interface
{$I Img32.inc}
uses
{$IFDEF MSWINDOWS} Windows, ShlObj, ActiveX, {$ENDIF}
Types, SysUtils, Classes, Math,
{$IFDEF XPLAT_GENERICS} Generics.Collections, Generics.Defaults,{$ENDIF}
Img32, Img32.Draw;
type
TFixed = type single;
Int16 = type SmallInt;
TFontFormat = (ffInvalid, ffTrueType, ffCompact);
TTtfFontFamily = (ttfUnknown, ttfSerif, ttfSansSerif, ttfMonospace);
{$IFNDEF Unicode}
UnicodeString = WideString;
{$ENDIF}
TMacStyle = (msBold, msItalic, msUnderline, msOutline,
msShadow, msCondensed, msExtended);
TMacStyles = set of TMacStyle;
TTextAlign = (taLeft, taRight, taCenter, taJustify);
TTextVAlign = (tvaTop, tvaMiddle, tvaBottom);
//nb: Avoid "packed" records as these cause problems with Android
TFontHeaderTable = record
sfntVersion : Cardinal; // $10000 or 'OTTO'
numTables : WORD;
searchRange : WORD;
entrySelector : WORD;
rangeShift : WORD;
end;
TFontTable = record
tag : Cardinal;
checkSum : Cardinal;
offset : Cardinal;
length : Cardinal;
end;
TFontTable_Cmap = record
version : WORD;
numTables : WORD;
end;
TCmapTblRec = record
platformID : WORD; //Unicode = 0; Windows = 3 (obsolete);
encodingID : WORD;
offset : Cardinal;
end;
TCmapFormat0 = record
format : WORD; //0
length : WORD;
language : WORD;
end;
TCmapFormat4 = record
format : WORD; //4
length : WORD;
language : WORD;
segCountX2 : WORD;
searchRange : WORD;
entrySelector : WORD;
rangeShift : WORD;
//endCodes : array of WORD; //last = $FFFF
//reserved : WORD; //0
//startCodes : array of WORD;
end;
TCmapFormat6 = record
format : WORD; //6
length : WORD;
language : WORD;
firstCode : WORD;
entryCount : WORD;
end;
TFontTable_Kern = record
version : WORD;
numTables : WORD;
end;
TKernSubTbl = record
version : WORD;
length : WORD;
coverage : WORD;
end;
TFormat0KernHdr = record
nPairs : WORD;
searchRange : WORD;
entrySelector : WORD;
rangeShift : WORD;
end;
TFormat0KernRec = record
left : WORD;
right : WORD;
value : int16;
end;
TArrayOfKernRecs = array of TFormat0KernRec;
TFontTable_Name = record
format : WORD;
count : WORD;
stringOffset : WORD;
//nameRecords[]
end;
TNameRec = record
platformID : WORD;
encodingID : WORD;
languageID : WORD;
nameID : WORD;
length : WORD;
offset : WORD;
end;
TFontTable_Head = record
majorVersion : Word;
minorVersion : Word;
fontRevision : TFixed;
checkSumAdjust : Cardinal;
magicNumber : Cardinal; // $5F0F3CF5
flags : Word;
unitsPerEm : Word;
dateCreated : UInt64;
dateModified : UInt64;
xMin : Int16;
yMin : Int16;
xMax : Int16;
yMax : Int16;
macStyle : Word; //see TMacStyles
lowestRecPPEM : Word;
fontDirHint : Int16; //ltr, rtl
indexToLocFmt : Int16;
glyphDataFmt : Int16;
end;
TFontTable_Maxp = record
version : TFixed;
numGlyphs : WORD;
maxPoints : WORD;
maxContours : WORD;
end;
TFontTable_Glyf = record
numContours : Int16;
xMin : Int16;
yMin : Int16;
xMax : Int16;
yMax : Int16;
end;
TFontTable_Hhea = record
version : TFixed;
ascent : Int16;
descent : Int16;
lineGap : Int16;
advWidthMax : WORD;
minLSB : Int16;
minRSB : Int16;
xMaxExtent : Int16;
caretSlopeRise : Int16;
caretSlopeRun : Int16;
caretOffset : Int16;
reserved : UInt64;
metricDataFmt : Int16;
numLongHorMets : WORD;
end;
TFontTable_Hmtx = record
advanceWidth : WORD;
leftSideBearing : Int16;
end;
TFontTable_Post = record
majorVersion : Word;
minorVersion : Word;
italicAngle : TFixed;
underlinePos : Int16;
underlineWidth : Int16;
isFixedPitch : Cardinal;
//minMemType42 : Cardinal;
//maxMemType42 : Cardinal;
//minMemType1 : Cardinal;
//maxMemType1 : Cardinal;
end;
TFontInfo = record //a custom summary record
fontFormat : TFontFormat;
fontFamily : TTtfFontFamily;
faceName : UnicodeString;
style : UnicodeString;
copyright : UnicodeString;
manufacturer : UnicodeString;
dateCreated : TDatetime;
dateModified : TDatetime;
macStyles : TMacStyles;
glyphCount : integer;
unitsPerEm : integer;
xMin : integer;
yMin : integer;
xMax : integer;
yMax : integer;
ascent : integer;
descent : integer;
lineGap : integer;
advWidthMax : integer;
minLSB : integer;
minRSB : integer;
xMaxExtent : integer;
end;
TKern = record
rightGlyphIdx : integer;
kernValue : integer;
end;
TArrayOfTKern = array of TKern;
TGlyphMetrics = record //a custom metrics record
glyphIdx : integer;
unitsPerEm : integer;
glyf : TFontTable_Glyf;
hmtx : TFontTable_Hmtx;
kernList : TArrayOfTKern;
end;
TFontTableArray = array of TFontTable;
TArrayOfWord = array of WORD;
TArrayOfCardinal = array of Cardinal;
TArrayOfCmapTblRec = array of TCmapTblRec;
TPointEx = record
pt: TPointD;
flag: byte;
end;
TPathEx = array of TPointEx;
TPathsEx = array of TPathEx;
TTableName = (tblName, tblHead, tblHhea,
tblCmap, tblMaxp, tblLoca, tblGlyf, tblHmtx, tblKern, tblPost);
{$IFDEF ZEROBASEDSTR}
{$ZEROBASEDSTRINGS OFF}
{$ENDIF}
TFontReader = class;
TFontManager = class
private
fMaxFonts: integer;
{$IFDEF XPLAT_GENERICS}
fFontList: TList<TFontReader>;
{$ELSE}
fFontList: TList;
{$ENDIF}
procedure SetMaxFonts(value: integer);
function ValidateAdd(fr: TFontReader): Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function GetFont(const fontName: string): TFontReader;
{$IFDEF MSWINDOWS}
function Load(const fontName: string; Weight: Integer = FW_NORMAL; Italic: Boolean = False): TFontReader;
{$ENDIF}
function LoadFromStream(stream: TStream): TFontReader;
function LoadFromResource(const resName: string; resType: PChar): TFontReader;
function LoadFromFile(const filename: string): TFontReader;
function GetBestMatchFont(const fontInfo: TFontInfo): TFontReader;
// FindReaderContainingGlyph: will return false either when no TFontReader
// is found, or a TFontReader is found but not in the specified family.
// When the latter occurs, fntReader will be assigned and index will be > 0.
function FindReaderContainingGlyph(missingUnicode: Word;
fntFamily: TTtfFontFamily; out fntReader: TFontReader; out index: integer): Boolean;
function Delete(fontReader: TFontReader): Boolean;
property MaxFonts: integer read fMaxFonts write SetMaxFonts;
end;
TFontReader = class(TInterfacedObj, INotifySender)
private
fFontManager : TFontManager;
fDestroying : Boolean;
fUpdateCount : integer;
fRecipientList : TRecipients;
fStream : TMemoryStream;
fFontWeight : integer;
fFontInfo : TFontInfo;
fTables : TFontTableArray;
fTblIdxes : array[TTableName] of integer;
fTbl_name : TFontTable_Name;
fTbl_head : TFontTable_Head;
fTbl_hhea : TFontTable_Hhea;
fTbl_cmap : TFontTable_Cmap;
fTbl_maxp : TFontTable_Maxp;
fTbl_glyf : TFontTable_Glyf;
fTbl_post : TFontTable_Post;
fTbl_loca2 : TArrayOfWord;
fTbl_loca4 : TArrayOfCardinal;
fCmapTblRecs : TArrayOfCmapTblRec;
fFormat0CodeMap : array[0..255] of byte;
fFormat4EndCodes : TArrayOfWord;
fFormat4StartCodes : TArrayOfWord;
fFormat4IdDelta : TArrayOfWord;
fFormat4RangeOff : TArrayOfWord;
fFormat4Offset : integer;
fKernTable : TArrayOfKernRecs;
function GetTables: Boolean;
function GetTable_name: Boolean;
function GetTable_cmap: Boolean;
function GetTable_maxp: Boolean;
function GetTable_head: Boolean;
function GetTable_loca: Boolean;
function GetTable_hhea: Boolean;
procedure GetTable_kern;
procedure GetTable_post;
procedure GetFontFamily;
function GetGlyphPaths(glyphIdx: integer): TPathsEx;
function GetGlyphIdxFromCmapIdx(idx: Word): integer;
function GetSimpleGlyph: TPathsEx;
function GetCompositeGlyph: TPathsEx;
function ConvertSplinesToBeziers(const pathsEx: TPathsEx): TPathsEx;
procedure GetPathCoords(var paths: TPathsEx);
function GetGlyphHorzMetrics(glyphIdx: integer;
out tbl_hmtx: TFontTable_Hmtx): Boolean;
function GetFontInfo: TFontInfo;
function GetGlyphKernList(glyphIdx: integer): TArrayOfTKern;
function GetGlyphMetricsInternal(glyphIdx: integer;
tbl_hmtx: TFontTable_Hmtx): TGlyphMetrics;
function GetWeight: integer;
procedure BeginUpdate;
procedure EndUpdate;
procedure NotifyRecipients(notifyFlag: TImg32Notification);
protected
property PostTable: TFontTable_Post read fTbl_post;
public
constructor Create; overload;
constructor CreateFromResource(const resName: string; resType: PChar);
{$IFDEF MSWINDOWS}
constructor Create(const fontname: string; Weight: Integer = FW_NORMAL; Italic: Boolean = False); overload;
{$ENDIF}
destructor Destroy; override;
procedure Clear;
procedure AddRecipient(recipient: INotifyRecipient);
procedure DeleteRecipient(recipient: INotifyRecipient);
function IsValidFontFormat: Boolean;
function HasGlyph(unicode: Word): Boolean;
function LoadFromStream(stream: TStream): Boolean;
function LoadFromResource(const resName: string; resType: PChar): Boolean;
function LoadFromFile(const filename: string): Boolean;
{$IFDEF MSWINDOWS}
function Load(const fontname: string; Weight: Integer = FW_NORMAL; Italic: Boolean = False): Boolean;
function LoadUsingFontHdl(hdl: HFont): Boolean;
{$ENDIF}
function GetGlyphInfo(unicode: Word; out paths: TPathsD;
out nextX: integer; out glyphMetrics: TGlyphMetrics): Boolean;
property FontFamily: TTtfFontFamily read fFontInfo.FontFamily;
property FontInfo: TFontInfo read GetFontInfo;
property Weight: integer read GetWeight; //range 100-900
end;
PGlyphInfo = ^TGlyphInfo;
TGlyphInfo = record
unicode : Word;
contours : TPathsD;
metrics : TGlyphMetrics;
end;
TTextPageMetrics = record
lineCount : integer;
maxLineWidth : double;
wordListOffsets : TArrayOfInteger;
justifyDeltas : TArrayOfDouble;
lineWidths : TArrayOfDouble;
end;
TWordInfoList = class;
TWordInfo = class
index : integer;
aWord : UnicodeString;
width : double;
length : integer;
paths : TArrayOfPathsD;
constructor Create(owner: TWordInfoList; idx: integer);
end;
TFontCache = class;
//TWordInfoList: A font formatted word list where text is broken into
//individual words and stored with their glyph info. This class is very
//useful with custom text editors.
TWordInfoList = class
private
{$IFDEF XPLAT_GENERICS}
fList : TList<TWordInfo>;
{$ELSE}
fList : TList;
{$ENDIF}
fSingleLine : Boolean;
//fListUpdates: accommodates many calls to UpdateWordList
//by occasionally refreshing glyph outlines.
//fListUpdates: integer;
fUpdateCount: integer;
fOnChanged : TNotifyEvent;
function GetWord(index: integer): TWordInfo;
function GetText: UnicodeString;
protected
procedure Changed; Virtual;
public
constructor Create;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
procedure ApplyNewFont(font: TFontCache);
procedure Clear;
function Count: integer;
procedure Edit(font: TFontCache; index: Integer; const newWord: string);
procedure Delete(Index: Integer);
procedure DeleteRange(startIdx, endIdx: Integer);
procedure AddNewline;
procedure AddSpace(font: TFontCache); overload;
procedure AddSpace(spaceWidth: double); overload;
procedure AddWord(font: TFontCache;
const word: UnicodeString; underlineIdx: integer = 0);
procedure InsertNewline(index: integer);
procedure InsertSpace(font: TFontCache; index: integer); overload;
procedure InsertSpace(spaceWidth: double; index: integer); overload;
procedure InsertWord(font: TFontCache; index: integer;
const word: UnicodeString; underlineIdx: integer = 0);
procedure SetText(const text: UnicodeString;
font: TFontCache; underlineIdx: integer = 0);
property ForceSingleLine: Boolean read fSingleLine write fSingleLine;
property WordInfo[index: integer]: TWordInfo read GetWord; default;
property Text: UnicodeString read GetText;
property OnChanged: TNotifyEvent read fOnChanged write fOnChanged;
end;
//TFontCache: speeds up text rendering by parsing font files only once
//for each accessed character. It can also scale glyphs to a specified
//font height and invert them too (which is necessary on Windows PCs).
TFontCache = class(TInterfacedObj, INotifySender, INotifyRecipient)
private
{$IFDEF XPLAT_GENERICS}
fGlyphInfoList : TList<PGlyphInfo>;
{$ELSE}
fGlyphInfoList : TList;
{$ENDIF}
fFontReader : TFontReader;
fRecipientList : TRecipients;
fSorted : Boolean;
fScale : double;
fUseKerning : Boolean;
fFontHeight : double;
fFlipVert : Boolean;
fUnderlined : Boolean;
fStrikeOut : Boolean;
procedure NotifyRecipients(notifyFlag: TImg32Notification);
function FoundInList(charOrdinal: WORD): Boolean;
function AddGlyph(unicode: Word): PGlyphInfo;
procedure VerticalFlip(var paths: TPathsD);
procedure SetFlipVert(value: Boolean);
procedure SetFontHeight(newHeight: double);
procedure SetFontReader(newFontReader: TFontReader);
procedure UpdateScale;
procedure Sort;
procedure GetMissingGlyphs(const ordinals: TArrayOfWord);
function IsValidFont: Boolean;
function GetAscent: double;
function GetDescent: double;
function GetLineHeight: double;
function GetYyHeight: double;
function GetTextOutlineInternal(x, y: double;
const text: UnicodeString; out glyphs: TArrayOfPathsD;
out nextX: double; underlineIdx: integer = 0): Boolean;
public
constructor Create(fontReader: TFontReader = nil; fontHeight: double = 10); overload;
destructor Destroy; override;
procedure Clear;
//TFontCache is both an INotifySender and an INotifyRecipient.
//It receives notifications from a TFontReader object and it sends
//notificiations to any number of TFontCache object users
procedure ReceiveNotification(Sender: TObject; notify: TImg32Notification);
procedure AddRecipient(recipient: INotifyRecipient);
procedure DeleteRecipient(recipient: INotifyRecipient);
function GetCharInfo(charOrdinal: WORD): PGlyphInfo;
function GetTextOutline(x, y: double;
const text: UnicodeString): TPathsD; overload;
function GetTextOutline(const rec: TRect; const text: UnicodeString;
textAlign: TTextAlign; textAlignV: TTextVAlign;
underlineIdx: integer = 0): TPathsD; overload;
function GetTextOutline(const rec: TRect; wordList: TWordInfoList;
tpm: TTextPageMetrics; textAlign: TTextAlign;
startLine, endLine: integer): TPathsD; overload;
function GetTextOutline(x, y: double; const text: UnicodeString;
out nextX: double; underlineIdx: integer = 0): TPathsD; overload;
function GetVerticalTextOutline(x, y: double;
const text: UnicodeString; interCharSpace: double =0): TPathsD;
function GetAngledTextGlyphs(x, y: double; const text: UnicodeString;
angleRadians: double; const rotatePt: TPointD;
out nextPt: TPointD): TPathsD;
function GetCharOffsets(const text: UnicodeString;
interCharSpace: double = 0): TArrayOfDouble;
function GetTextWidth(const text: UnicodeString): double;
function GetSpaceWidth: double;
property Ascent: double read GetAscent;
property Descent: double read GetDescent;
property FontHeight: double read fFontHeight write SetFontHeight;
property FontReader: TFontReader read
fFontReader write SetFontReader;
property InvertY: boolean read fFlipVert write SetFlipVert;
property Kerning: boolean read fUseKerning write fUseKerning;
property LineHeight: double read GetLineHeight;
property YyHeight: double read GetYyHeight;
property Scale : double read fScale;
property Underlined: Boolean read fUnderlined write fUnderlined;
property StrikeOut: Boolean read fStrikeOut write fStrikeOut;
end;
//Given a wordList and a specified maximum line width (in pixels),
//get both the line count and the offsets to the words in wordlist
//that will start each line.
function GetPageMetrics(lineWidth: double;
wordList: TWordInfoList): TTextPageMetrics;
function DrawText(image: TImage32; x, y: double;
const text: UnicodeString; font: TFontCache;
textColor: TColor32 = clBlack32;
useClearType: Boolean = false;
clearTypeBgColor: TColor32 = clWhite32): double; overload;
function DrawText(image: TImage32; x, y: double;
const text: UnicodeString; font: TFontCache;
renderer: TCustomRenderer): double; overload;
procedure DrawText(image: TImage32; const rec: TRect;
const text: UnicodeString;
textAlign: TTextAlign; textAlignV: TTextVAlign;
font: TFontCache; textColor: TColor32 = clBlack32;
useClearType: Boolean = false;
clearTypeBgColor: TColor32 = clWhite32); overload;
function DrawAngledText(image: TImage32;
x, y: double; angleRadians: double;
const text: UnicodeString; font: TFontCache;
textColor: TColor32 = clBlack32): TPointD;
function DrawVerticalText(image: TImage32;
x, y, interCharSpace: double;
const text: UnicodeString; font: TFontCache;
textColor: TColor32 = clBlack32): double;
function GetTextOutlineOnPath(const text: UnicodeString;
const path: TPathD; font: TFontCache; textAlign: TTextAlign;
perpendicOffset: integer = 0; charSpacing: double = 0): TPathsD; overload;
function GetTextOutlineOnPath(const text: UnicodeString;
const path: TPathD; font: TFontCache; textAlign: TTextAlign;
perpendicOffset: integer; charSpacing: double;
out charsThatFit: integer): TPathsD; overload;
{$IFDEF MSWINDOWS}
procedure CheckFontHeight(var logFont: TLogFont);
function PointHeightToPixelHeight(pt: double): double;
function GetFontFolder: string;
function GetInstalledTtfFilenames: TArrayOfString;
{$ENDIF}
function FontManager: TFontManager;
implementation
uses
Img32.Vector;
resourcestring
rsTooManyFonts = 'TFontManager error: Too many fonts are open.';
rsWordListRangeError = 'TFFWordList: range error.';
rsFontCacheError = 'TFontCache error: message from incorrect TFontReader';
rsWordListFontError = 'TFFWordList: invalid font error.';
var
aFontManager: TFontManager;
const
lineFrac = 0.05;
//------------------------------------------------------------------------------
// Miscellaneous functions
//------------------------------------------------------------------------------
//GetMeaningfulDateTime: returns UTC date & time
procedure GetMeaningfulDateTime(const secsSince1904: Uint64;
out yy,mo,dd, hh,mi,ss: cardinal);
const
dim: array[boolean, 0..12] of cardinal =
((0,31,59,90,120,151,181,212,243,273,304,334,365), //non-leap year
(0,31,60,91,121,152,182,213,244,274,305,335,366)); //leap year
var
isLeapYr: Boolean;
const
maxValidYear = 2100;
secsPerHour = 3600;
secsPerDay = 86400;
secsPerNormYr = 31536000;
secsPerLeapYr = secsPerNormYr + secsPerDay;
secsPer4Years = secsPerNormYr * 3 + secsPerLeapYr; //126230400;
begin
//nb: Centuries are not leap years unless they are multiples of 400.
// 2000 WAS a leap year, but 2100 won't be.
// Validate function at http://www.mathcats.com/explore/elapsedtime.html
ss := (secsSince1904 div secsPer4Years); //count '4years' since 1904
//manage invalid dates
if (secsSince1904 = 0) or
(ss > (maxValidYear-1904) div 4) then
begin
yy := 1904; mo := 1; dd := 1;
hh := 0; mi := 0; ss := 0;
Exit;
end;
yy := 1904 + (ss * 4);
ss := secsSince1904 mod secsPer4Years; //secs since START last leap yr
isLeapYr := ss < secsPerLeapYr;
if not isLeapYr then
begin
dec(ss, secsPerLeapYr);
yy := yy + (ss div secsPerNormYr) + 1;
ss := ss mod secsPerNormYr; //remaining secs in final year
end;
dd := 1 + ss div secsPerDay; //day number in final year
mo := 1;
while dim[isLeapYr, mo] < dd do inc(mo);
ss := ss - (dim[isLeapYr, mo-1] * secsPerDay); //remaining secs in month
dd := 1 + (ss div secsPerDay);
ss := ss mod secsPerDay;
hh := ss div secsPerHour;
ss := ss mod secsPerHour;
mi := ss div 60;
ss := ss mod 60;
end;
//------------------------------------------------------------------------------
function MergePathsArray(const pa: TArrayOfPathsD): TPathsD;
var
i: integer;
begin
Result := nil;
for i := 0 to High(pa) do
AppendPath(Result, pa[i]);
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function WordSwap(val: WORD): WORD;
{$IFDEF ASM_X86}
asm
rol ax,8;
end;
{$ELSE}
var
v: array[0..1] of byte absolute val;
r: array[0..1] of byte absolute result;
begin
r[0] := v[1];
r[1] := v[0];
end;
{$ENDIF}
//------------------------------------------------------------------------------
function Int16Swap(val: Int16): Int16;
{$IFDEF ASM_X86}
asm
rol ax,8;
end;
{$ELSE}
var
v: array[0..1] of byte absolute val;
r: array[0..1] of byte absolute result;
begin
r[0] := v[1];
r[1] := v[0];
end;
{$ENDIF}
//------------------------------------------------------------------------------
function Int32Swap(val: integer): integer;
{$IFDEF ASM_X86}
asm
bswap eax
end;
{$ELSE}
var
i: integer;
v: array[0..3] of byte absolute val;
r: array[0..3] of byte absolute Result; //warning: do not inline
begin
for i := 0 to 3 do r[3-i] := v[i];
end;
{$ENDIF}
//------------------------------------------------------------------------------
function UInt64Swap(val: UInt64): UInt64;
{$IFDEF ASM_X86}
asm
MOV EDX, val.Int64Rec.Lo
BSWAP EDX
MOV EAX, val.Int64Rec.Hi
BSWAP EAX
end;
{$ELSE}
var
i: integer;
v: array[0..7] of byte absolute val;
r: array[0..7] of byte absolute Result;
begin
for i := 0 to 7 do r[7-i] := v[i];
end;
{$ENDIF}
//------------------------------------------------------------------------------
procedure GetByte(stream: TStream; out value: byte);
begin
stream.Read(value, 1);
end;
//------------------------------------------------------------------------------
procedure GetShortInt(stream: TStream; out value: ShortInt);
begin
stream.Read(value, 1);
end;
//------------------------------------------------------------------------------
function GetWord(stream: TStream; out value: WORD): Boolean;
begin
result := stream.Position + SizeOf(value) < stream.Size;
stream.Read(value, SizeOf(value));
value := WordSwap(value);
end;
//------------------------------------------------------------------------------
function GetInt16(stream: TStream; out value: Int16): Boolean;
begin
result := stream.Position + SizeOf(value) < stream.Size;
stream.Read(value, SizeOf(value));
value := Int16Swap(value);
end;
//------------------------------------------------------------------------------
function GetCardinal(stream: TStream; out value: Cardinal): Boolean;
begin
result := stream.Position + SizeOf(value) < stream.Size;
stream.Read(value, SizeOf(value));
value := Cardinal(Int32Swap(Integer(value)));
end;
//------------------------------------------------------------------------------
function GetInt(stream: TStream; out value: integer): Boolean;
begin
result := stream.Position + SizeOf(value) < stream.Size;
stream.Read(value, SizeOf(value));
value := Int32Swap(value);
end;
//------------------------------------------------------------------------------
function GetUInt64(stream: TStream; out value: UInt64): Boolean;
begin
result := stream.Position + SizeOf(value) < stream.Size;
stream.Read(value, SizeOf(value));
value := UInt64Swap(value);
end;
//------------------------------------------------------------------------------
function Get2Dot14(stream: TStream; out value: single): Boolean;
var
val: Int16;
begin
result := GetInt16(stream, val);
if result then value := val * 6.103515625e-5; // 16384;
end;
//------------------------------------------------------------------------------
function GetFixed(stream: TStream; out value: TFixed): Boolean;
var
val: integer;
begin
result := GetInt(stream, val);
value := val * 1.52587890625e-5; // 1/35536
end;
//------------------------------------------------------------------------------
function GetWideString(stream: TStream; length: integer): UnicodeString;
var
i: integer;
w: Word;
begin
length := length div 2;
setLength(Result, length);
for i := 1 to length do
begin
GetWord(stream, w); //nb: reverses byte order
if w = 0 then
begin
SetLength(Result, i -1);
break;
end;
result[i] := WideChar(w);
end;
end;
//------------------------------------------------------------------------------
function GetAnsiString(stream: TStream; len: integer): string;
var
i: integer;
ansi: UTF8String;
begin
setLength(ansi, len+1);
ansi[len+1] := #0;
stream.Read(ansi[1], len);
result := string(ansi);
for i := 1 to length(Result) do
if Result[i] = #0 then
begin
SetLength(Result, i -1);
break;
end;
end;
//------------------------------------------------------------------------------
// TTrueTypeReader
//------------------------------------------------------------------------------
constructor TFontReader.Create;
begin
fStream := TMemoryStream.Create;
end;
//------------------------------------------------------------------------------
constructor TFontReader.CreateFromResource(const resName: string; resType: PChar);
begin
Create;
LoadFromResource(resName, resType);
end;
//------------------------------------------------------------------------------
{$IFDEF MSWINDOWS}
constructor TFontReader.Create(const fontname: string; Weight: Integer; Italic: Boolean);
begin
Create;
Load(fontname, Weight, Italic);
end;
//------------------------------------------------------------------------------
{$ENDIF}
destructor TFontReader.Destroy;
begin
Clear;
NotifyRecipients(inDestroy);
fStream.Free;
if Assigned(fFontManager) then
begin
fDestroying := true;
fFontManager.Delete(self);
end;
inherited;
end;
//------------------------------------------------------------------------------
procedure TFontReader.Clear;
begin
fTables := nil;
fCmapTblRecs := nil;
fFormat4Offset := 0;
fFormat4EndCodes := nil;
fKernTable := nil;
FillChar(fTbl_post, SizeOf(fTbl_post), 0);
fTbl_glyf.numContours := 0;
fFontInfo.fontFormat := ffInvalid;
fFontInfo.fontFamily := ttfUnknown;
fFontWeight := 0;
fStream.Clear;
NotifyRecipients(inStateChange);
end;
//------------------------------------------------------------------------------
procedure TFontReader.BeginUpdate;
begin
inc(fUpdateCount);
end;
//------------------------------------------------------------------------------
procedure TFontReader.EndUpdate;
begin
dec(fUpdateCount);
if fUpdateCount = 0 then NotifyRecipients(inStateChange);
end;
//------------------------------------------------------------------------------
procedure TFontReader.NotifyRecipients(notifyFlag: TImg32Notification);
var
i: integer;
begin
if fUpdateCount > 0 then Exit;
for i := High(fRecipientList) downto 0 do
try
//when destroying in a finalization section
//it's possible for recipients to have been destroyed
//without their destructors being called.
fRecipientList[i].ReceiveNotification(self, notifyFlag);
except
end;
end;
//------------------------------------------------------------------------------
procedure TFontReader.AddRecipient(recipient: INotifyRecipient);
var
len: integer;
begin
len := Length(fRecipientList);
SetLength(fRecipientList, len+1);
fRecipientList[len] := Recipient;
end;
//------------------------------------------------------------------------------
procedure TFontReader.DeleteRecipient(recipient: INotifyRecipient);
var
i, highI: integer;
begin
highI := High(fRecipientList);
i := highI;
while (i >= 0) and (fRecipientList[i] <> Recipient) do dec(i);
if i < 0 then Exit;
if i < highI then
Move(fRecipientList[i+1], fRecipientList[i],
(highI - i) * SizeOf(INotifyRecipient));
SetLength(fRecipientList, highI);
end;
//------------------------------------------------------------------------------
function TFontReader.IsValidFontFormat: Boolean;
begin
result := fFontInfo.fontFormat = ffTrueType;
end;
//------------------------------------------------------------------------------
function TFontReader.LoadFromStream(stream: TStream): Boolean;
begin
BeginUpdate;
try
Clear;
fStream.CopyFrom(stream, 0);
fStream.Position := 0;
result := GetTables;
if not result then Clear;
finally
EndUpdate;
end;
end;
//------------------------------------------------------------------------------
function TFontReader.LoadFromResource(const resName: string; resType: PChar): Boolean;
var
rs: TResourceStream;
begin
BeginUpdate;
rs := CreateResourceStream(resName, resType);
try
Result := assigned(rs) and LoadFromStream(rs);
finally
rs.free;
EndUpdate;
end;