Debian Codegraph @

components/Image32/source/Img32.Text.pas

raw
1 unit Img32.Text;
2
3 (*******************************************************************************
4 * Author : Angus Johnson *
5 * Version : 4.8 *
6 * Date : 22 January 2025 *
7 * Website : http://www.angusj.com *
8 * Copyright : Angus Johnson 2019-2025 *
9 * Purpose : TrueType fonts for TImage32 (without Windows dependencies) *
10 * License : http://www.boost.org/LICENSE_1_0.txt *
11 *******************************************************************************)
12
13 interface
14
15 {$I Img32.inc}
16
17 uses
18 {$IFDEF MSWINDOWS} Windows, ShlObj, ActiveX, {$ENDIF}
19 Types, SysUtils, Classes, Math,
20 {$IFDEF XPLAT_GENERICS} Generics.Collections, Generics.Defaults,{$ENDIF}
21 Img32, Img32.Draw, Img32.Vector;
22
23 type
24
25 TFixed = type single;
26 Int16 = type SmallInt;
27 TFontFormat = (ffInvalid, ffTrueType, ffCompact);
28 TFontFamily = (tfUnknown, tfSerif, tfSansSerif, tfMonospace);
29
30 TFontReader = class;
31
32 {$IFDEF MSWINDOWS}
33 PArrayOfEnumLogFontEx = ^TArrayOfEnumLogFontEx;
34 TArrayOfEnumLogFontEx = array of TEnumLogFontEx;
35
36 // TFontReaderFamily - a custom (Image32) record
37 TFontReaderFamily = record
38 regularFR : TFontReader;
39 boldFR : TFontReader;
40 italicFR : TFontReader;
41 boldItalicFR : TFontReader;
42 end;
43 {$ENDIF}
44
45 {$IFNDEF Unicode}
46 UnicodeString = WideString;
47 {$ENDIF}
48
49 TMacStyle = (msBold, msItalic, msUnderline, msOutline,
50 msShadow, msCondensed, msExtended);
51 TMacStyles = set of TMacStyle;
52
53 TTextAlign = (taLeft, taRight, taCenter, taJustify);
54 TTextVAlign = (tvaTop, tvaMiddle, tvaBottom);
55
56 // nb: Avoid "packed" records as these cause problems with Android
57
58 TFontHeaderTable = record
59 sfntVersion : Cardinal; // $10000 or 'OTTO'
60 numTables : WORD;
61 searchRange : WORD;
62 entrySelector : WORD;
63 rangeShift : WORD;
64 end;
65
66 TFontTable = record
67 tag : Cardinal;
68 checkSum : Cardinal;
69 offset : Cardinal;
70 length : Cardinal;
71 end;
72
73 TFontTable_Cmap = record
74 version : WORD;
75 numTables : WORD;
76 end;
77
78 TCmapTblRec = record
79 platformID : WORD; // Unicode = 0; Windows = 3 (obsolete);
80 encodingID : WORD;
81 offset : Cardinal;
82 end;
83
84 TCmapFormat0 = record
85 format : WORD; // 0
86 length : WORD;
87 language : WORD;
88 end;
89
90 TCmapFormat4 = record
91 format : WORD; // 4
92 length : WORD;
93 language : WORD;
94 segCountX2 : WORD;
95 searchRange : WORD;
96 entrySelector : WORD;
97 rangeShift : WORD;
98 //endCodes : array of WORD; // last = $FFFF
99 //reserved : WORD; // 0
100 //startCodes : array of WORD;
101 end;
102
103 TFormat4Rec = record
104 startCode : WORD;
105 endCode : WORD;
106 idDelta : WORD;
107 rangeOffset : WORD;
108 end;
109
110 TCmapFormat6 = record
111 format : WORD; // 6
112 length : WORD;
113 language : WORD;
114 firstCode : WORD;
115 entryCount : WORD;
116 end;
117
118 TCmapFormat12 = record
119 format : WORD; // 12
120 reserved : WORD; // 0
121 length : DWORD;
122 language : DWORD;
123 nGroups : DWORD;
124 //array[nGroups] of TFormat12Group;
125 end;
126
127 TFormat12Rec = record
128 startCode : WORD;
129 endCode : WORD;
130 idDelta : WORD;
131 rangeOffset : WORD;
132 end;
133
134 TFormat12Group = record
135 startCharCode : DWORD;
136 endCharCode : DWORD;
137 startGlyphCode: DWORD;
138 end;
139
140 TFontTable_Kern = record
141 version : WORD;
142 numTables : WORD;
143 end;
144
145 TKernSubTbl = record
146 version : WORD;
147 length : WORD;
148 coverage : WORD;
149 end;
150
151 TFormat0KernHdr = record
152 nPairs : WORD;
153 searchRange : WORD;
154 entrySelector : WORD;
155 rangeShift : WORD;
156 end;
157
158 TFormat0KernRec = record
159 left : WORD;
160 right : WORD;
161 value : int16;
162 end;
163 TArrayOfKernRecs = array of TFormat0KernRec;
164
165 TFontTable_Name = record
166 format : WORD;
167 count : WORD;
168 stringOffset : WORD;
169 //nameRecords[]
170 end;
171
172 TNameRec = record
173 platformID : WORD;
174 encodingID : WORD;
175 languageID : WORD;
176 nameID : WORD;
177 length : WORD;
178 offset : WORD;
179 end;
180
181 TFontTable_Head = record
182 majorVersion : WORD;
183 minorVersion : WORD;
184 fontRevision : TFixed;
185 checkSumAdjust : Cardinal;
186 magicNumber : Cardinal; // $5F0F3CF5
187 flags : WORD;
188 unitsPerEm : WORD;
189 dateCreated : UInt64;
190 dateModified : UInt64;
191 xMin : Int16;
192 yMin : Int16;
193 xMax : Int16;
194 yMax : Int16;
195 macStyle : WORD; // see TMacStyles
196 lowestRecPPEM : WORD;
197 fontDirHint : Int16; // left to right, right to left
198 indexToLocFmt : Int16;
199 glyphDataFmt : Int16;
200 end;
201
202 TFontTable_Maxp = record
203 version : TFixed;
204 numGlyphs : WORD;
205 maxPoints : WORD;
206 maxContours : WORD;
207 end;
208
209 TFontTable_Glyf = record
210 numContours : Int16;
211 xMin : Int16;
212 yMin : Int16;
213 xMax : Int16;
214 yMax : Int16;
215 end;
216
217 TFontTable_Hhea = record
218 version : TFixed;
219 ascent : Int16;
220 descent : Int16;
221 lineGap : Int16;
222 advWidthMax : WORD;
223 minLSB : Int16;
224 minRSB : Int16;
225 xMaxExtent : Int16;
226 caretSlopeRise : Int16;
227 caretSlopeRun : Int16;
228 caretOffset : Int16;
229 reserved : UInt64;
230 metricDataFmt : Int16;
231 numLongHorMets : WORD;
232 end;
233
234 TFontTable_Hmtx = record
235 advanceWidth : WORD;
236 leftSideBearing : Int16;
237 end;
238
239 TFontTable_Post = record
240 majorVersion : WORD;
241 minorVersion : WORD;
242 italicAngle : TFixed;
243 underlinePos : Int16;
244 underlineWidth : Int16;
245 isFixedPitch : Cardinal;
246 //minMemType42 : Cardinal;
247 //maxMemType42 : Cardinal;
248 //minMemType1 : Cardinal;
249 //maxMemType1 : Cardinal;
250 end;
251
252 ArrayOfUtf8String = array of Utf8String;
253
254 // TFontInfo: a custom summary record
255 TFontInfo = record
256 fontFormat : TFontFormat;
257 family : TFontFamily;
258 familyNames : ArrayOfUtf8String;
259 faceName : Utf8String;
260 fullFaceName : Utf8String;
261 style : Utf8String;
262 copyright : Utf8String;
263 manufacturer : Utf8String;
264 dateCreated : TDatetime;
265 dateModified : TDatetime;
266 macStyles : TMacStyles;
267 glyphCount : integer;
268 unitsPerEm : integer;
269 xMin : integer;
270 yMin : integer;
271 xMax : integer;
272 yMax : integer;
273 ascent : integer;
274 descent : integer;
275 lineGap : integer;
276 advWidthMax : integer;
277 minLSB : integer;
278 minRSB : integer;
279 xMaxExtent : integer;
280 end;
281
282 TKern = record
283 rightGlyphIdx : integer;
284 kernValue : integer;
285 end;
286 TArrayOfTKern = array of TKern;
287
288 ///////////////////////////////////////////
289 // the following point structures are only
290 // used internally by the TFontReader class
291 TPointEx = record
292 pt: TPointD;
293 flag: byte;
294 end;
295 TPathEx = array of TPointEx;
296 TPathsEx = array of TPathEx;
297 ///////////////////////////////////////////
298
299 PGlyphInfo = ^TGlyphInfo;
300 // TGlyphInfo: another custom record
301 TGlyphInfo = record
302 codepoint : integer;
303 glyphIdx : WORD;
304 unitsPerEm : integer;
305 glyf : TFontTable_Glyf;
306 hmtx : TFontTable_Hmtx;
307 kernList : TArrayOfTKern;
308 paths : TPathsD;
309 end;
310
311 TFontTableArray = array of TFontTable;
312 TArrayOfWord = array of WORD;
313 TArrayOfCardinal = array of Cardinal;
314 TArrayOfCmapTblRec = array of TCmapTblRec;
315
316 TTableName = (tblName, tblHead, tblHhea,
317 tblCmap, tblMaxp, tblLoca, tblGlyf,
318 tblHmtx, tblKern, tblPost);
319
320 {$IFDEF ZEROBASEDSTR}
321 {$ZEROBASEDSTRINGS OFF}
322 {$ENDIF}
323
324 TLoadFontResult = (lfrSuccess, lfrDuplicate, lfrInvalid);
325
326 TFontManager = class
327 private
328 fMaxFonts: integer;
329 {$IFDEF XPLAT_GENERICS}
330 fFontList: TList<TFontReader>;
331 {$ELSE}
332 fFontList: TList;
333 {$ENDIF}
334 procedure SetMaxFonts(value: integer);
335 procedure SortFontListOnLastUse;
336 procedure DeleteOldestFont;
337 function ValidateFontLoad(var fr: TFontReader): TLoadFontResult;
338 function FindDuplicate(fr: TFontReader): integer;
339 public
340 constructor Create;
341 destructor Destroy; override;
342 procedure Clear;
343 {$IFDEF MSWINDOWS}
344 // LoadFontReaderFamily: call will fail if the fonts have already been
345 // loaded, or if the font family hasn't been installed in the PC.
346 function LoadFontReaderFamily(const fontFamily: string): TLoadFontResult; overload;
347 function LoadFontReaderFamily(const fontFamily: string;
348 out fontReaderFamily: TFontReaderFamily): TLoadFontResult; overload;
349 function LoadFontReader(const fontName: string): TFontReader;
350 {$ENDIF}
351 function LoadFromStream(stream: TStream): TFontReader;
352 function LoadFromResource(const resName: string; resType: PChar): TFontReader;
353 function LoadFromFile(const filename: string): TFontReader;
354 function GetBestMatchFont(const fontInfo: TFontInfo): TFontReader; overload;
355 function GetBestMatchFont(const styles: TMacStyles): TFontReader; overload;
356 // FindReaderContainingGlyph: returns a TFontReader object containing the
357 // specified glyph, otherwise nil. If a fontfamily is spedified, then the
358 // search is limited to within that font family. If a TFontReader is found
359 // then the out 'glyphIdx' parameter contains the index to the glyph
360 // matching the supplied codepoint.
361 function FindReaderContainingGlyph(codepoint: Cardinal;
362 fntFamily: TFontFamily; out glyphIdx: WORD): TFontReader;
363 function Delete(fontReader: TFontReader): Boolean;
364 property MaxFonts: integer read fMaxFonts write SetMaxFonts;
365 end;
366
367 TFontReader = class(TInterfacedObj, INotifySender)
368 private
369 fFontManager : TFontManager;
370 fDestroying : Boolean;
371 fUpdateCount : integer;
372 fRecipientList : TRecipients;
373 fLastUsedTime : TDateTime;
374 fStream : TMemoryStream;
375 fFontWeight : integer;
376 fFontInfo : TFontInfo;
377 fTables : TFontTableArray;
378 fTblIdxes : array[TTableName] of integer;
379 fTbl_name : TFontTable_Name;
380 fTbl_head : TFontTable_Head;
381 fTbl_hhea : TFontTable_Hhea;
382 fTbl_cmap : TFontTable_Cmap;
383 fTbl_maxp : TFontTable_Maxp;
384 fTbl_post : TFontTable_Post;
385 fTbl_loca2 : TArrayOfWord;
386 fTbl_loca4 : TArrayOfCardinal;
387 fKernTable : TArrayOfKernRecs;
388
389 fFormat0CodeMap : array of byte;
390 fFormat4CodeMap : array of TFormat4Rec;
391 fFormat12CodeMap : array of TFormat12Group;
392 fFormat4Offset : integer;
393
394 function GetTables: Boolean;
395 function GetTable_name: Boolean;
396 function GetTable_cmap: Boolean;
397 function GetTable_maxp: Boolean;
398 function GetTable_head: Boolean;
399 function GetTable_loca: Boolean;
400 function IsValidFontTable(const tbl : TFontTable): Boolean; {$IFDEF INLINE} inline; {$ENDIF}
401 function GetTable_hhea: Boolean;
402 procedure GetTable_kern;
403 procedure GetTable_post;
404
405 procedure GetFontFamily;
406 function GetGlyphPaths(glyphIdx: WORD;
407 var tbl_hmtx: TFontTable_Hmtx; out tbl_glyf: TFontTable_Glyf): TPathsEx;
408 function GetGlyphIdxUsingCmap(codePoint: Cardinal): WORD;
409 function GetSimpleGlyph(tbl_glyf: TFontTable_Glyf): TPathsEx;
410 function GetCompositeGlyph(var tbl_glyf: TFontTable_Glyf;
411 var tbl_hmtx: TFontTable_Hmtx): TPathsEx;
412 function ConvertSplinesToBeziers(const pathsEx: TPathsEx): TPathsEx;
413 procedure GetPathCoords(var paths: TPathsEx);
414 function GetGlyphHorzMetrics(glyphIdx: WORD): TFontTable_Hmtx;
415 function GetFontInfo: TFontInfo;
416 function GetGlyphKernList(glyphIdx: WORD): TArrayOfTKern;
417 function GetGlyphInfoInternal(glyphIdx: WORD): TGlyphInfo;
418 function GetWeight: integer;
419 procedure BeginUpdate;
420 procedure EndUpdate;
421 procedure NotifyRecipients(notifyFlag: TImg32Notification);
422 protected
423 property LastUsedTime: TDatetime read fLastUsedTime write fLastUsedTime;
424 property PostTable: TFontTable_Post read fTbl_post;
425 public
426 constructor Create; overload;
427 constructor CreateFromResource(const resName: string; resType: PChar);
428 {$IFDEF MSWINDOWS}
429 constructor Create(const fontname: string); overload;
430 {$ENDIF}
431 destructor Destroy; override;
432 procedure Clear;
433 procedure AddRecipient(recipient: INotifyRecipient);
434 procedure DeleteRecipient(recipient: INotifyRecipient);
435 function IsValidFontFormat: Boolean;
436 function HasGlyph(codepoint: Cardinal): Boolean;
437 function LoadFromStream(stream: TStream): Boolean;
438 function LoadFromResource(const resName: string; resType: PChar): Boolean;
439 function LoadFromFile(const filename: string): Boolean;
440 {$IFDEF MSWINDOWS}
441 function Load(const FontName: string): Boolean; overload;
442 function Load(const logFont: TLogFont): Boolean; overload;
443 function LoadUsingFontHdl(hdl: HFont): Boolean;
444 {$ENDIF}
445 function GetGlyphInfo(codepoint: Cardinal;
446 out nextX: integer; out glyphInfo: TGlyphInfo): Boolean;
447 property FontFamily: TFontFamily read fFontInfo.family;
448 property FontInfo: TFontInfo read GetFontInfo;
449 property Weight: integer read GetWeight; // range 100-900
450 end;
451
452 TPageTextMetrics = record
453 bounds : TRect;
454 lineCount : integer;
455 lineHeight : double;
456 topLinePxOffset : integer;
457 nextChuckIdx : integer;
458 startOfLineIdx : TArrayOfInteger;
459 justifyDeltas : TArrayOfDouble;
460 lineWidths : TArrayOfDouble;
461 end;
462
463 TFontCache = class;
464 TChunkedText = class;
465
466 TTextChunk = class
467 public
468 owner : TChunkedText;
469 index : integer;
470 text : UnicodeString;
471 left : double;
472 top : double;
473 width : double;
474 height : double;
475 backColor : TColor32;
476 fontColor : TColor32;
477 ascent : double;
478 userData : Pointer;
479 glyphOffsets : TArrayOfDouble;
480 arrayOfPaths : TArrayOfPathsD;
481 constructor Create(owner: TChunkedText; const chunk: UnicodeString;
482 index: integer; fontCache: TFontCache; fontColor: TColor32;
483 backColor: TColor32 = clNone32);
484 end;
485
486 TDrawChunkEvent = procedure(chunk: TTextChunk; const chunkRec: TRectD) of object;
487
488 // TChunkedText: A font formatted list of text 'chunks' (usually space
489 // seperated words) that will greatly speed up displaying word-wrapped text.
490 TChunkedText = class
491 private
492 fSpaceWidth : double;
493 fLastFont : TFontCache;
494 {$IFDEF XPLAT_GENERICS}
495 fList : TList<TTextChunk>;
496 {$ELSE}
497 fList : TList;
498 {$ENDIF}
499 fDrawChunkEvent: TDrawChunkEvent;
500 function GetChunk(index: integer): TTextChunk;
501 function GetText: UnicodeString;
502 function GetCount: integer;
503 protected
504 function GetGlyphsOrDrawInternal(image: TImage32; const rec: TRect;
505 textAlign: TTextAlign; textAlignV: TTextVAlign; startChunk: integer;
506 lineHeight: double; out paths: TPathsD): TPageTextMetrics;
507 public
508 constructor Create; overload;
509 constructor Create(const text: string; font: TFontCache;
510 fontColor: TColor32 = clBlack32; backColor: TColor32 = clNone32); overload;
511 destructor Destroy; override;
512 procedure Clear;
513 procedure DeleteChunk(Index: Integer);
514 procedure DeleteChunkRange(startIdx, endIdx: Integer);
515 procedure AddNewline(font: TFontCache);
516 procedure AddSpace(font: TFontCache); overload;
517 function GetPageMetrics(const rec: TRect; lineHeight: double;
518 startingChunkIdx: integer): TPageTextMetrics;
519 function GetChunkAndGlyphOffsetAtPt(const ptm: TPageTextMetrics;
520 const pt: TPoint; out glyphIdx, chunkChrOff: integer): Boolean;
521 function InsertTextChunk(font: TFontCache; index: integer;
522 const chunk: UnicodeString; fontColor: TColor32 = clBlack32;
523 backColor: TColor32 = clNone32): TTextChunk;
524 function AddTextChunk(font: TFontCache; const chunk: UnicodeString;
525 fontColor: TColor32 = clBlack32;
526 backColor: TColor32 = clNone32): TTextChunk;
527 procedure SetText(const text: UnicodeString; font: TFontCache;
528 fontColor: TColor32 = clBlack32; backColor: TColor32 = clNone32);
529 // DrawText: see Examples/FMX2, Examples/Text & Examples/Experimental apps.
530 function DrawText(image: TImage32; const rec: TRect;
531 textAlign: TTextAlign; textAlignV: TTextVAlign;
532 startChunk: integer; lineHeight: double = 0.0): TPageTextMetrics;
533 function GetTextGlyphs(const rec: TRect;
534 textAlign: TTextAlign; textAlignV: TTextVAlign; startChunk: integer;
535 lineHeight: double = 0.0): TPathsD;
536 procedure ApplyNewFont(font: TFontCache);
537 property Count: integer read GetCount;
538 property Chunk[index: integer]: TTextChunk read GetChunk; default;
539 property Text: UnicodeString read GetText;
540 property OnDrawChunk: TDrawChunkEvent
541 read fDrawChunkEvent write fDrawChunkEvent;
542 end;
543
544 // TFontCache: speeds up text rendering by parsing font files only once
545 // for each accessed character. It can also scale glyphs to a specified
546 // font height and invert glyphs too (which is necessary on Windows PCs).
547 TFontCache = class(TInterfacedObj, INotifySender, INotifyRecipient)
548 private
549 {$IFDEF XPLAT_GENERICS}
550 fGlyphInfoList : TList<PGlyphInfo>;
551 {$ELSE}
552 fGlyphInfoList : TList;
553 {$ENDIF}
554 fFontReader : TFontReader;
555 fRecipientList : TRecipients;
556 fSorted : Boolean;
557 fScale : double;
558 fUseKerning : Boolean;
559 fFontHeight : double;
560 fFlipVert : Boolean;
561 fUnderlined : Boolean;
562 fStrikeOut : Boolean;
563 procedure NotifyRecipients(notifyFlag: TImg32Notification);
564 function FoundInList(charOrdinal: Cardinal): Boolean;
565 function AddGlyph(codepoint: Cardinal): PGlyphInfo;
566 procedure VerticalFlip(var paths: TPathsD);
567 procedure SetFlipVert(value: Boolean);
568 procedure SetFontHeight(newHeight: double);
569 procedure SetFontReader(newFontReader: TFontReader);
570 procedure UpdateScale;
571 procedure Sort;
572 procedure GetMissingGlyphs(const ordinals: TArrayOfCardinal);
573 function IsValidFont: Boolean;
574 function GetAscent: double;
575 function GetDescent: double;
576 function GetGap: double;
577 function GetLineHeight: double;
578 function GetYyHeight: double;
579 function GetTextOutlineInternal(x, y: double; const text: UnicodeString;
580 underlineIdx: integer; out glyphs: TArrayOfPathsD;
581 out offsets: TArrayOfDouble; out nextX: double): Boolean; overload;
582 procedure UpdateFontReaderLastUsedTime;
583 public
584 constructor Create(fontReader: TFontReader = nil; fontHeight: double = 10); overload;
585 destructor Destroy; override;
586 procedure Clear;
587 // TFontCache is both an INotifySender and an INotifyRecipient.
588 // It receives notifications from a TFontReader object and it sends
589 // notificiations to any number of TFontCache object users
590 procedure ReceiveNotification(Sender: TObject; notify: TImg32Notification);
591 procedure AddRecipient(recipient: INotifyRecipient);
592 procedure DeleteRecipient(recipient: INotifyRecipient);
593 function GetGlyphInfo(codepoint: Cardinal): PGlyphInfo;
594
595 function GetTextOutline(x, y: double; const text: UnicodeString): TPathsD; overload;
596 function GetTextOutline(const rec: TRectD; const text: UnicodeString;
597 ta: TTextAlign; tav: TTextVAlign; underlineIdx: integer = 0): TPathsD; overload;
598 function GetTextOutline(x, y: double; const text: UnicodeString;
599 out nextX: double; underlineIdx: integer = 0): TPathsD; overload;
600
601 // GetUnderlineOutline - another way to underline text. 'y' indicates the
602 // text baseline, and 'dy' is the offset from that baseline.
603 // if dy = InvalidD then the default offset is used (& based on linewidth).
604 function GetUnderlineOutline(leftX, rightX, y: double; dy: double = invalidD;
605 wavy: Boolean = false; strokeWidth: double = 0): TPathD;
606
607 function GetVerticalTextOutline(x, y: double;
608 const text: UnicodeString; lineHeight: double = 0.0): TPathsD;
609
610 function GetAngledTextGlyphs(x, y: double; const text: UnicodeString;
611 angleRadians: double; const rotatePt: TPointD;
612 out nextPt: TPointD): TPathsD;
613 // GetGlyphOffsets - there isn't always a one-to-one relationship between
614 // text characters and glyphs since text can on occasions contain
615 // "surrogate paired" characters (eg emoji characters).
616 function GetGlyphOffsets(const text: UnicodeString;
617 interCharSpace: double = 0): TArrayOfDouble;
618 // As per the comment above, there isn't always a one-to-one relationship
619 // between text characters and their codepoints (2 byte chars vs 4 bytes)
620 function GetTextCodePoints(const text: UnicodeString): TArrayOfCardinal;
621 function GetTextWidth(const text: UnicodeString): double;
622 function CountCharsThatFit(const text: UnicodeString; maxWidth: double): integer;
623 function GetSpaceWidth: double;
624
625 property Ascent : double read GetAscent;
626 property Descent : double read GetDescent;
627 property LineGap : double read GetGap;
628 property FontHeight : double read fFontHeight write SetFontHeight;
629 property FontReader : TFontReader read fFontReader write SetFontReader;
630 property InvertY : boolean read fFlipVert write SetFlipVert;
631 property Kerning : boolean read fUseKerning write fUseKerning;
632 property LineHeight : double read GetLineHeight;
633 property YyHeight : double read GetYyHeight;
634 property Scale : double read fScale;
635 property Underlined : Boolean read fUnderlined write fUnderlined;
636 property StrikeOut : Boolean read fStrikeOut write fStrikeOut;
637 end;
638
639 function DrawText(image: TImage32; x, y: double;
640 const text: UnicodeString; font: TFontCache;
641 textColor: TColor32 = clBlack32): double; overload;
642
643 procedure DrawText(image: TImage32; const rec: TRectD;
644 const text: UnicodeString; font: TFontCache;
645 textColor: TColor32 = clBlack32; align: TTextAlign = taCenter;
646 valign: TTextVAlign = tvaMiddle); overload;
647
648 function DrawText(image: TImage32; x, y: double;
649 const text: UnicodeString; font: TFontCache;
650 renderer: TCustomRenderer): double; overload;
651
652 function DrawAngledText(image: TImage32;
653 x, y: double; angleRadians: double;
654 const text: UnicodeString; font: TFontCache;
655 textColor: TColor32 = clBlack32): TPointD;
656
657 procedure DrawVerticalText(image: TImage32;
658 x, y: double; const text: UnicodeString; font: TFontCache;
659 lineHeight: double = 0.0; textColor: TColor32 = clBlack32);
660
661 function GetTextOutlineOnPath(const text: UnicodeString;
662 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
663 x, y: double; charSpacing: double;
664 out charsThatFit: integer; out outX: double): TPathsD; overload;
665
666 function GetTextOutlineOnPath(const text: UnicodeString;
667 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
668 perpendicOffset: integer = 0; charSpacing: double = 0): TPathsD; overload;
669
670 function GetTextOutlineOnPath(const text: UnicodeString;
671 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
672 perpendicOffset: integer; charSpacing: double;
673 out charsThatFit: integer): TPathsD; overload;
674
675 function GetTextOutlineOnPath(const text: UnicodeString;
676 const path: TPathD; font: TFontCache; x, y: integer;
677 charSpacing: double; out outX: double): TPathsD; overload;
678
679 {$IFDEF MSWINDOWS}
680 procedure FontHeightToFontSize(var logFontHeight: integer);
681 procedure FontSizeToFontHeight(var logFontHeight: integer);
682 function GetFontPixelHeight(logFontHeight: integer): double;
683 function GetFontFolder: string;
684 function GetInstalledTtfFilenames: TArrayOfString;
685
686 // GetLogFonts: using DEFAULT_CHARSET will get logfonts
687 // for ALL charsets that match the specified faceName.
688 function GetLogFonts(const faceName: string;
689 charSet: byte = DEFAULT_CHARSET): TArrayOfEnumLogFontEx;
690 // GetLogFontFromEnumThatMatchesStyles:
691 // will return false when no style match is found
692 function GetLogFontFromEnumThatMatchesStyles(LogFonts: TArrayOfEnumLogFontEx;
693 styles: TMacStyles; out logFont: TLogFont): Boolean;
694 {$ENDIF}
695
696 function FontManager: TFontManager;
697
698 implementation
699
700 uses
701 Img32.Transform;
702
703 resourcestring
704 rsChunkedTextRangeError =
705 'TChunkedText: range error.';
706 rsFontCacheError =
707 'TFontCache error: notification received from the wrong TFontReader';
708 rsChunkedTextFontError =
709 'TChunkedText: invalid font error.';
710
711 var
712 aFontManager: TFontManager;
713
714 const
715 lineFrac = 0.05;
716 SPACE = ' ';
717
718 //------------------------------------------------------------------------------
719 // Miscellaneous functions
720 //------------------------------------------------------------------------------
721
722 // GetMeaningfulDateTime: returns UTC date & time
723 procedure GetMeaningfulDateTime(const secsSince1904: Uint64;
724 out yy,mo,dd, hh,mi,ss: cardinal);
725 const
726 dayInYrAtMthStart: array[boolean, 0..12] of cardinal =
727 ((0,31,59,90,120,151,181,212,243,273,304,334,365), // non-leap year
728 (0,31,60,91,121,152,182,213,244,274,305,335,366)); // leap year
729 var
730 isLeapYr: Boolean;
731 const
732 maxValidYear = 2100;
733 secsPerHour = 3600;
734 secsPerDay = 86400;
735 secsPerNormYr = 31536000;
736 secsPerLeapYr = secsPerNormYr + secsPerDay;
737 secsPer4Years = secsPerNormYr * 3 + secsPerLeapYr; // 126230400;
738 begin
739 // Leap years are divisble by 4, except for centuries which are not
740 // leap years unless they are divisble by 400. (Hence 2000 was a leap year,
741 // but 1900 was not. But 1904 was a leap year because it's divisble by 4.)
742 // Validate at http://www.mathcats.com/explore/elapsedtime.html
743
744 ss := (secsSince1904 div secsPer4Years); // count '4years' since 1904
745
746 // manage invalid dates
747 if (secsSince1904 = 0) or
748 (ss > (maxValidYear-1904) div 4) then
749 begin
750 yy := 1904; mo := 1; dd := 1;
751 hh := 0; mi := 0; ss := 0;
752 Exit;
753 end;
754 yy := 1904 + (ss * 4);
755
756 ss := secsSince1904 mod secsPer4Years; // secs since last leap yr
757 isLeapYr := ss < secsPerLeapYr;
758 if not isLeapYr then
759 begin
760 dec(ss, secsPerLeapYr);
761 yy := yy + (ss div secsPerNormYr) + 1;
762 ss := ss mod secsPerNormYr; // remaining secs in final year
763 end;
764 dd := 1 + ss div secsPerDay; // day number in final year
765 mo := 1; // 1, because mo is base 1
766 while dayInYrAtMthStart[isLeapYr, mo] < dd do inc(mo);
767 // remaining secs in month
768 ss := ss - (dayInYrAtMthStart[isLeapYr, mo -1] * secsPerDay);
769 dd := 1 + (ss div secsPerDay); // because dd is base 1 too
770 ss := ss mod secsPerDay;
771 hh := ss div secsPerHour;
772 ss := ss mod secsPerHour;
773 mi := ss div 60;
774 ss := ss mod 60;
775 end;
776 //------------------------------------------------------------------------------
777
778 function MergeArrayOfPaths(const pa: TArrayOfPathsD): TPathsD;
779 var
780 i, j: integer;
781 resultCount: integer;
782 begin
783 Result := nil;
784
785 // Preallocate the Result-Array
786 resultCount := 0;
787 for i := 0 to High(pa) do
788 inc(resultCount, Length(pa[i]));
789 SetLength(Result, resultCount);
790
791 resultCount := 0;
792 for i := 0 to High(pa) do
793 begin
794 for j := 0 to High(pa[i]) do
795 begin
796 Result[resultCount] := pa[i][j];
797 inc(resultCount);
798 end;
799 end;
800 end;
801 //------------------------------------------------------------------------------
802
803 // MergeArrayOfPathsEx - merges AND translates/offsets paths
804 function MergeArrayOfPathsEx(const pa: TArrayOfPathsD; dx, dy: double): TPathsD;
805 var
806 i, j: integer;
807 resultCount: integer;
808 begin
809 Result := nil;
810
811 // Preallocate the Result-Array
812 resultCount := 0;
813 for i := 0 to High(pa) do
814 inc(resultCount, Length(pa[i]));
815 SetLength(Result, resultCount);
816
817 resultCount := 0;
818 for i := 0 to High(pa) do
819 begin
820 for j := 0 to High(pa[i]) do
821 begin
822 Result[resultCount] := TranslatePath(pa[i][j], dx, dy);
823 inc(resultCount);
824 end;
825 end;
826 end;
827 //------------------------------------------------------------------------------
828
829 function WordSwap(val: WORD): WORD;
830 {$IFDEF ASM_X86}
831 asm
832 rol ax,8;
833 end;
834 {$ELSE}
835 var
836 v: array[0..1] of byte absolute val;
837 r: array[0..1] of byte absolute result;
838 begin
839 r[0] := v[1];
840 r[1] := v[0];
841 end;
842 {$ENDIF}
843 //------------------------------------------------------------------------------
844
845 function Int16Swap(val: Int16): Int16;
846 {$IFDEF ASM_X86}
847 asm
848 rol ax,8;
849 end;
850 {$ELSE}
851 var
852 v: array[0..1] of byte absolute val;
853 r: array[0..1] of byte absolute result;
854 begin
855 r[0] := v[1];
856 r[1] := v[0];
857 end;
858 {$ENDIF}
859 //------------------------------------------------------------------------------
860
861 function Int32Swap(val: integer): integer;
862 {$IFDEF ASM_X86}
863 asm
864 bswap eax
865 end;
866 {$ELSE}
867 var
868 i: integer;
869 v: array[0..3] of byte absolute val;
870 r: array[0..3] of byte absolute Result; // warning: do not inline
871 begin
872 for i := 0 to 3 do r[3-i] := v[i];
873 end;
874 {$ENDIF}
875 //------------------------------------------------------------------------------
876
877 function UInt64Swap(val: UInt64): UInt64;
878 {$IFDEF ASM_X86}
879 asm
880 MOV EDX, val.Int64Rec.Lo
881 BSWAP EDX
882 MOV EAX, val.Int64Rec.Hi
883 BSWAP EAX
884 end;
885 {$ELSE}
886 var
887 i: integer;
888 v: array[0..7] of byte absolute val;
889 r: array[0..7] of byte absolute Result;
890 begin
891 for i := 0 to 7 do r[7-i] := v[i];
892 end;
893 {$ENDIF}
894 //------------------------------------------------------------------------------
895
896 procedure GetByte(stream: TStream; out value: byte);
897 {$IFDEF INLINE} inline; {$ENDIF}
898 begin
899 stream.Read(value, 1);
900 end;
901 //------------------------------------------------------------------------------
902
903 procedure GetShortInt(stream: TStream; out value: ShortInt);
904 {$IFDEF INLINE} inline; {$ENDIF}
905 begin
906 stream.Read(value, 1);
907 end;
908 //------------------------------------------------------------------------------
909
910 function GetWord(stream: TStream; out value: WORD): Boolean;
911 {$IFDEF INLINE} inline; {$ENDIF}
912 begin
913 result := stream.Position + SizeOf(value) < stream.Size;
914 if not Result then Exit;
915 stream.Read(value, SizeOf(value));
916 value := WordSwap(value);
917 end;
918 //------------------------------------------------------------------------------
919
920 function GetInt16(stream: TStream; out value: Int16): Boolean;
921 {$IFDEF INLINE} inline; {$ENDIF}
922 begin
923 result := stream.Position + SizeOf(value) < stream.Size;
924 if not Result then Exit;
925 stream.Read(value, SizeOf(value));
926 value := Int16Swap(value);
927 end;
928 //------------------------------------------------------------------------------
929
930 function GetCardinal(stream: TStream; out value: Cardinal): Boolean;
931 {$IFDEF INLINE} inline; {$ENDIF}
932 begin
933 result := stream.Position + SizeOf(value) < stream.Size;
934 if not Result then Exit;
935 stream.Read(value, SizeOf(value));
936 value := Cardinal(Int32Swap(Integer(value)));
937 end;
938 //------------------------------------------------------------------------------
939
940 function GetInt(stream: TStream; out value: integer): Boolean;
941 {$IFDEF INLINE} inline; {$ENDIF}
942 begin
943 result := stream.Position + SizeOf(value) < stream.Size;
944 if not Result then Exit;
945 stream.Read(value, SizeOf(value));
946 value := Int32Swap(value);
947 end;
948 //------------------------------------------------------------------------------
949
950 function GetUInt64(stream: TStream; out value: UInt64): Boolean;
951 {$IFDEF INLINE} inline; {$ENDIF}
952 begin
953 result := stream.Position + SizeOf(value) < stream.Size;
954 if not Result then Exit;
955 stream.Read(value, SizeOf(value));
956 value := UInt64Swap(value);
957 end;
958 //------------------------------------------------------------------------------
959
960 function Get2Dot14(stream: TStream; out value: single): Boolean;
961 var
962 val: Int16;
963 begin
964 result := GetInt16(stream, val);
965 if result then value := val * 6.103515625e-5; // 16384;
966 end;
967 //------------------------------------------------------------------------------
968
969 function GetFixed(stream: TStream; out value: TFixed): Boolean;
970 var
971 val: integer;
972 begin
973 result := GetInt(stream, val);
974 value := val * 1.52587890625e-5; // 1/35536
975 end;
976 //------------------------------------------------------------------------------
977
978 function GetWideString(stream: TStream; len: integer): Utf8String;
979 var
980 i: integer;
981 w: WORD;
982 s: UnicodeString;
983 begin
984 len := len div 2;
985 setLength(s, len);
986 for i := 1 to len do
987 begin
988 GetWord(stream, w);
989 if w = 0 then
990 begin
991 SetLength(s, i -1);
992 break;
993 end;
994 s[i] := WideChar(w);
995 end;
996 Result := Utf8String(s);
997 end;
998 //------------------------------------------------------------------------------
999
1000 function GetUtf8String(stream: TStream; len: integer): Utf8String;
1001 var
1002 i: integer;
1003 begin
1004 setLength(Result, len+1);
1005 Result[len+1] := #0;
1006 stream.Read(Result[1], len);
1007 for i := 1 to length(Result) do
1008 if Result[i] = #0 then
1009 begin
1010 SetLength(Result, i -1);
1011 break;
1012 end;
1013 end;
1014 //------------------------------------------------------------------------------
1015
1016 function SameText(const text1, text2: Utf8String): Boolean; overload;
1017 var
1018 len: integer;
1019 begin
1020 len := Length(text1);
1021 Result := (Length(text2) = len) and
1022 ((len = 0) or CompareMem(@text1[1], @text2[1], len));
1023 end;
1024
1025 //------------------------------------------------------------------------------
1026 // TTrueTypeReader
1027 //------------------------------------------------------------------------------
1028
1029 constructor TFontReader.Create;
1030 begin
1031 fStream := TMemoryStream.Create;
1032 end;
1033 //------------------------------------------------------------------------------
1034
1035 constructor TFontReader.CreateFromResource(const resName: string; resType: PChar);
1036 begin
1037 Create;
1038 LoadFromResource(resName, resType);
1039 end;
1040 //------------------------------------------------------------------------------
1041
1042 {$IFDEF MSWINDOWS}
1043 constructor TFontReader.Create(const fontname: string);
1044 begin
1045 Create;
1046 Load(fontname);
1047 end;
1048 //------------------------------------------------------------------------------
1049 {$ENDIF}
1050
1051 destructor TFontReader.Destroy;
1052 begin
1053 Clear;
1054 NotifyRecipients(inDestroy);
1055 fStream.Free;
1056 if Assigned(fFontManager) then
1057 begin
1058 fDestroying := true;
1059 fFontManager.Delete(self);
1060 end;
1061 inherited;
1062 end;
1063 //------------------------------------------------------------------------------
1064
1065 procedure TFontReader.Clear;
1066 begin
1067 fTables := nil;
1068 fFormat4CodeMap := nil;
1069 fFormat12CodeMap := nil;
1070 fKernTable := nil;
1071 FillChar(fTbl_post, SizeOf(fTbl_post), 0);
1072 fFontInfo.fontFormat := ffInvalid;
1073 fFontInfo.family := tfUnknown;
1074 fFontWeight := 0;
1075 fStream.Clear;
1076 NotifyRecipients(inStateChange);
1077 end;
1078 //------------------------------------------------------------------------------
1079
1080 procedure TFontReader.BeginUpdate;
1081 begin
1082 inc(fUpdateCount);
1083 end;
1084 //------------------------------------------------------------------------------
1085
1086 procedure TFontReader.EndUpdate;
1087 begin
1088 dec(fUpdateCount);
1089 if fUpdateCount = 0 then NotifyRecipients(inStateChange);
1090 end;
1091 //------------------------------------------------------------------------------
1092
1093 procedure TFontReader.NotifyRecipients(notifyFlag: TImg32Notification);
1094 var
1095 i: integer;
1096 begin
1097 if fUpdateCount > 0 then Exit;
1098 for i := High(fRecipientList) downto 0 do
1099 try
1100 // try .. except block because when TFontReader is destroyed in a
1101 // finalization section, it's possible for recipients to have been
1102 // destroyed without calling their destructors.
1103 fRecipientList[i].ReceiveNotification(self, notifyFlag);
1104 except
1105 end;
1106 end;
1107 //------------------------------------------------------------------------------
1108
1109 procedure TFontReader.AddRecipient(recipient: INotifyRecipient);
1110 var
1111 len: integer;
1112 begin
1113 len := Length(fRecipientList);
1114 SetLength(fRecipientList, len+1);
1115 fRecipientList[len] := Recipient;
1116 end;
1117 //------------------------------------------------------------------------------
1118
1119 procedure TFontReader.DeleteRecipient(recipient: INotifyRecipient);
1120 var
1121 i, highI: integer;
1122 begin
1123 highI := High(fRecipientList);
1124 i := highI;
1125 while (i >= 0) and (fRecipientList[i] <> Recipient) do dec(i);
1126 if i < 0 then Exit;
1127 if i < highI then
1128 Move(fRecipientList[i+1], fRecipientList[i],
1129 (highI - i) * SizeOf(INotifyRecipient));
1130 SetLength(fRecipientList, highI);
1131 end;
1132 //------------------------------------------------------------------------------
1133
1134 function TFontReader.IsValidFontFormat: Boolean;
1135 begin
1136 result := fFontInfo.fontFormat = ffTrueType;
1137 end;
1138 //------------------------------------------------------------------------------
1139
1140 function TFontReader.LoadFromStream(stream: TStream): Boolean;
1141 begin
1142 BeginUpdate;
1143 try
1144 Clear;
1145 fStream.CopyFrom(stream, 0);
1146 fStream.Position := 0;
1147 result := GetTables;
1148 if not result then Clear;
1149 finally
1150 EndUpdate;
1151 end;
1152 end;
1153 //------------------------------------------------------------------------------
1154
1155 function TFontReader.LoadFromResource(const resName: string; resType: PChar): Boolean;
1156 var
1157 rs: TResourceStream;
1158 begin
1159 BeginUpdate;
1160 rs := CreateResourceStream(resName, resType);
1161 try
1162 Result := assigned(rs) and LoadFromStream(rs);
1163 finally
1164 rs.free;
1165 EndUpdate;
1166 end;
1167 end;
1168 //------------------------------------------------------------------------------
1169
1170 function TFontReader.LoadFromFile(const filename: string): Boolean;
1171 var
1172 fs: TFileStream;
1173 begin
1174 try
1175 fs := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
1176 try
1177 Result := LoadFromStream(fs);
1178 finally
1179 fs.free;
1180 end;
1181 except
1182 Result := False;
1183 end;
1184 end;
1185 //------------------------------------------------------------------------------
1186
1187 {$IFDEF MSWINDOWS}
1188 function GetFontMemStreamFromFontHdl(hdl: HFont;
1189 memStream: TMemoryStream): Boolean;
1190 var
1191 memDc: HDC;
1192 cnt: DWORD;
1193 begin
1194 result := false;
1195 if not Assigned(memStream) or (hdl = 0) then Exit;
1196
1197 memDc := CreateCompatibleDC(0);
1198 try
1199 if SelectObject(memDc, hdl) = 0 then Exit;
1200 // get the required size of the font data (file)
1201 cnt := Windows.GetFontData(memDc, 0, 0, nil, 0);
1202 result := cnt <> $FFFFFFFF;
1203 if not Result then Exit;
1204 // copy the font data into the memory stream
1205 memStream.SetSize(cnt);
1206 Windows.GetFontData(memDc, 0, 0, memStream.Memory, cnt);
1207 finally
1208 DeleteDC(memDc);
1209 end;
1210 end;
1211 //------------------------------------------------------------------------------
1212
1213 function TFontReader.LoadUsingFontHdl(hdl: HFont): Boolean;
1214 var
1215 ms: TMemoryStream;
1216 begin
1217 ms := TMemoryStream.Create;
1218 try
1219 Result := GetFontMemStreamFromFontHdl(hdl, ms) and
1220 LoadFromStream(ms);
1221 finally
1222 ms.Free;
1223 end;
1224 end;
1225 //------------------------------------------------------------------------------
1226
1227 function TFontReader.Load(const FontName: string): Boolean;
1228 var
1229 lf: TLogFont;
1230 begin
1231 Result := false;
1232 if fontname = '' then Exit;
1233 FillChar(lf, sizeof(TLogFont), 0);
1234 lf.lfCharSet := DEFAULT_CHARSET;
1235 Move(fontname[1], lf.lfFaceName[0], Length(fontname) * SizeOf(Char));
1236 Result := Load(lf);
1237 end;
1238 //------------------------------------------------------------------------------
1239
1240 function TFontReader.Load(const logFont: TLogFont): Boolean;
1241 var
1242 hdl: HFont;
1243 begin
1244 Result := false;
1245 hdl := CreateFontIndirect({$IFDEF FPC}@{$ENDIF}logfont);
1246 if hdl > 0 then
1247 try
1248 Result := LoadUsingFontHdl(hdl);
1249 finally
1250 DeleteObject(hdl);
1251 end;
1252 end;
1253 //------------------------------------------------------------------------------
1254 {$ENDIF}
1255
1256 function GetHeaderTable(stream: TStream;
1257 out headerTable: TFontHeaderTable): Boolean;
1258 begin
1259 result := stream.Position < stream.Size - SizeOf(TFontHeaderTable);
1260 if not result then Exit;
1261 GetCardinal(stream, headerTable.sfntVersion);
1262 GetWord(stream, headerTable.numTables);
1263 GetWord(stream, headerTable.searchRange);
1264 GetWord(stream, headerTable.entrySelector);
1265 GetWord(stream, headerTable.rangeShift);
1266 end;
1267 //------------------------------------------------------------------------------
1268
1269 function TFontReader.IsValidFontTable(const tbl : TFontTable): Boolean;
1270 begin
1271 Result := (fStream.Size >= tbl.offset + tbl.length);
1272 end;
1273 //------------------------------------------------------------------------------
1274
1275 function TFontReader.GetTables: Boolean;
1276 var
1277 i, tblCount: integer;
1278 tbl: TTableName;
1279 headerTable: TFontHeaderTable;
1280 begin
1281 result := false;
1282 if not GetHeaderTable(fStream, headerTable) then Exit;
1283 tblCount := headerTable.numTables;
1284 result := fStream.Position < fStream.Size - SizeOf(TFontTable) * tblCount;
1285 if not result then Exit;
1286
1287 for tbl := low(TTableName) to High(TTableName) do fTblIdxes[tbl] := -1;
1288 SetLength(fTables, tblCount);
1289
1290 for i := 0 to tblCount -1 do
1291 begin
1292 GetCardinal(fStream, fTables[i].tag);
1293 GetCardinal(fStream, fTables[i].checkSum);
1294 GetCardinal(fStream, fTables[i].offset);
1295 GetCardinal(fStream, fTables[i].length);
1296 case
1297 fTables[i].tag of
1298 $6E616D65: fTblIdxes[tblName] := i;
1299 $68656164: fTblIdxes[tblHead] := i;
1300 $676C7966: fTblIdxes[tblGlyf] := i;
1301 $6C6F6361: fTblIdxes[tblLoca] := i;
1302 $6D617870: fTblIdxes[tblMaxp] := i;
1303 $636D6170: fTblIdxes[tblCmap] := i;
1304 $68686561: fTblIdxes[tblHhea] := i;
1305 $686D7478: fTblIdxes[tblHmtx] := i;
1306 $6B65726E: fTblIdxes[tblKern] := i;
1307 $706F7374: fTblIdxes[tblPost] := i;
1308 end;
1309 end;
1310
1311 if fTblIdxes[tblName] < 0 then fFontInfo.fontFormat := ffInvalid
1312 else if fTblIdxes[tblGlyf] < 0 then fFontInfo.fontFormat := ffCompact
1313 else fFontInfo.fontFormat := ffTrueType;
1314
1315 result := (fFontInfo.fontFormat = ffTrueType) and
1316 (fTblIdxes[tblName] >= 0) and GetTable_name and
1317 (fTblIdxes[tblHead] >= 0) and GetTable_head and
1318 (fTblIdxes[tblHhea] >= 0) and GetTable_hhea and
1319 (fTblIdxes[tblMaxp] >= 0) and GetTable_maxp and
1320 (fTblIdxes[tblLoca] >= 0) and GetTable_loca and // loca must follow maxp
1321 (fTblIdxes[tblCmap] >= 0) and GetTable_cmap and
1322 (fTblIdxes[tblHmtx] >= 0) and IsValidFontTable(fTables[fTblIdxes[tblHmtx]]);
1323
1324 if not Result then Exit;
1325 if (fTblIdxes[tblKern] >= 0) then GetTable_kern;
1326 if (fTblIdxes[tblPost] >= 0) then GetTable_post;
1327
1328 GetFontFamily;
1329 end;
1330 //------------------------------------------------------------------------------
1331
1332 function TFontReader.GetTable_cmap: Boolean;
1333 var
1334 i,j : integer;
1335 segCount : integer;
1336 format : WORD;
1337 reserved : WORD;
1338 format4Rec : TCmapFormat4;
1339 format12Rec : TCmapFormat12;
1340 cmapTbl : TFontTable;
1341 cmapTblRecs : array of TCmapTblRec;
1342 label
1343 format4Error;
1344 begin
1345 Result := false;
1346 cmapTbl := fTables[fTblIdxes[tblCmap]];
1347 if (fStream.Size < cmapTbl.offset + cmapTbl.length) then Exit;
1348
1349 fStream.Position := cmapTbl.offset;
1350 GetWord(fStream, fTbl_cmap.version);
1351 GetWord(fStream, fTbl_cmap.numTables);
1352
1353 // only use the unicode table (0: always first)
1354 SetLength(cmapTblRecs, fTbl_cmap.numTables);
1355 for i := 0 to fTbl_cmap.numTables -1 do
1356 begin
1357 GetWord(fStream, cmapTblRecs[i].platformID);
1358 GetWord(fStream, cmapTblRecs[i].encodingID);
1359 GetCardinal(fStream, cmapTblRecs[i].offset);
1360 end;
1361
1362 for i := 0 to fTbl_cmap.numTables -1 do
1363 begin
1364 with cmapTblRecs[i] do
1365 if (platformID = 0) or (platformID = 3) then
1366 fStream.Position := cmapTbl.offset + offset
1367 else
1368 Continue;
1369 GetWord(fStream, format);
1370
1371 case format of
1372 0:
1373 begin
1374 if Assigned(fFormat0CodeMap) then Continue;
1375 GetWord(fStream, format4Rec.length);
1376 GetWord(fStream, format4Rec.language);
1377 SetLength(fFormat0CodeMap, 256);
1378 for j := 0 to 255 do
1379 GetByte(fStream, fFormat0CodeMap[j]);
1380 fFontInfo.glyphCount := 255;
1381 end;
1382 4: // USC-2
1383 begin
1384 if Assigned(fFormat4CodeMap) then Continue;
1385 GetWord(fStream, format4Rec.length);
1386 GetWord(fStream, format4Rec.language);
1387
1388 fFontInfo.glyphCount := 0;
1389 GetWord(fStream, format4Rec.segCountX2);
1390 segCount := format4Rec.segCountX2 shr 1;
1391 GetWord(fStream, format4Rec.searchRange);
1392 GetWord(fStream, format4Rec.entrySelector);
1393 GetWord(fStream, format4Rec.rangeShift);
1394 SetLength(fFormat4CodeMap, segCount);
1395 for j := 0 to segCount -1 do
1396 GetWord(fStream, fFormat4CodeMap[j].endCode);
1397 if fFormat4CodeMap[segCount-1].endCode <> $FFFF then
1398 GoTo format4Error;
1399 GetWord(fStream, reserved);
1400 if reserved <> 0 then
1401 GoTo format4Error;
1402 for j := 0 to segCount -1 do
1403 GetWord(fStream, fFormat4CodeMap[j].startCode);
1404 if fFormat4CodeMap[segCount-1].startCode <> $FFFF then
1405 GoTo format4Error;
1406 for j := 0 to segCount -1 do
1407 GetWord(fStream, fFormat4CodeMap[j].idDelta);
1408
1409 fFormat4Offset := fStream.Position;
1410 for j := 0 to segCount -1 do
1411 GetWord(fStream, fFormat4CodeMap[j].rangeOffset);
1412 if Assigned(fFormat12CodeMap) then Break
1413 else Continue;
1414
1415 format4Error:
1416 fFormat4CodeMap := nil;
1417 end;
1418 12: // USC-4
1419 begin
1420 if Assigned(fFormat12CodeMap) then Continue;
1421 GetWord(fStream, reserved);
1422 GetCardinal(fStream, format12Rec.length);
1423 GetCardinal(fStream, format12Rec.language);
1424 GetCardinal(fStream, format12Rec.nGroups);
1425 SetLength(fFormat12CodeMap, format12Rec.nGroups);
1426 for j := 0 to format12Rec.nGroups -1 do
1427 with fFormat12CodeMap[j] do
1428 begin
1429 GetCardinal(fStream, startCharCode);
1430 GetCardinal(fStream, endCharCode);
1431 GetCardinal(fStream, startGlyphCode);
1432 end;
1433 if Assigned(fFormat4CodeMap) then Break;
1434 end;
1435 end;
1436 end;
1437 Result := Assigned(fFormat4CodeMap) or Assigned(fFormat12CodeMap);
1438 end;
1439 //------------------------------------------------------------------------------
1440
1441 function TFontReader.GetGlyphIdxUsingCmap(codePoint: Cardinal): WORD;
1442 var
1443 i: integer;
1444 w: WORD;
1445 begin
1446 result := 0; // default to the 'missing' glyph
1447 if (codePoint < 256) and Assigned(fFormat0CodeMap) then
1448 Result := fFormat0CodeMap[codePoint]
1449 else if Assigned(fFormat12CodeMap) then
1450 begin
1451 for i := 0 to High(fFormat12CodeMap) do
1452 with fFormat12CodeMap[i] do
1453 if codePoint <= endCharCode then
1454 begin
1455 if codePoint < startCharCode then Break;
1456 result := (startGlyphCode + WORD(codePoint - startCharCode));
1457 Break;
1458 end;
1459 end
1460 else if (codePoint < $FFFF) and Assigned(fFormat4CodeMap) then
1461 begin
1462 for i := 0 to High(fFormat4CodeMap) do
1463 with fFormat4CodeMap[i] do
1464 if codePoint <= endCode then
1465 begin
1466 if codePoint < startCode then Break;
1467 if rangeOffset > 0 then
1468 begin
1469 fStream.Position := fFormat4Offset +
1470 rangeOffset + 2 * (i + WORD(codePoint - startCode));
1471 GetWord(fStream, w);
1472 if w < fTbl_maxp.numGlyphs then Result := w;
1473 end else
1474 result := (idDelta + codePoint) and $FFFF;
1475 Break;
1476 end;
1477 end;
1478 end;
1479 //------------------------------------------------------------------------------
1480
1481 function TFontReader.GetTable_maxp: Boolean;
1482 var
1483 maxpTbl: TFontTable;
1484 begin
1485 maxpTbl := fTables[fTblIdxes[tblMaxp]];
1486 Result := (fStream.Size >= maxpTbl.offset + maxpTbl.length) and
1487 (maxpTbl.length >= SizeOf(TFixed) + SizeOf(WORD));
1488 if not Result then Exit;
1489 fStream.Position := maxpTbl.offset;
1490 GetFixed(fStream, fTbl_maxp.version);
1491 GetWord(fStream, fTbl_maxp.numGlyphs);
1492 if fTbl_maxp.version >= 1 then
1493 begin
1494 GetWord(fStream, fTbl_maxp.maxPoints);
1495 GetWord(fStream, fTbl_maxp.maxContours);
1496 fFontInfo.glyphCount := fTbl_maxp.numGlyphs;
1497 end else
1498 Result := false;
1499 end;
1500 //------------------------------------------------------------------------------
1501
1502 function TFontReader.GetTable_loca: Boolean;
1503 var
1504 i: integer;
1505 locaTbl: TFontTable;
1506 begin
1507 locaTbl := fTables[fTblIdxes[tblLoca]];
1508 Result := fStream.Size >= locaTbl.offset + locaTbl.length;
1509 if not Result then Exit;
1510 fStream.Position := locaTbl.offset;
1511
1512 if fTbl_head.indexToLocFmt = 0 then
1513 begin
1514 SetLength(fTbl_loca2, fTbl_maxp.numGlyphs +1);
1515 for i := 0 to fTbl_maxp.numGlyphs do
1516 GetWord(fStream, fTbl_loca2[i]);
1517 end else
1518 begin
1519 SetLength(fTbl_loca4, fTbl_maxp.numGlyphs +1);
1520 for i := 0 to fTbl_maxp.numGlyphs do
1521 GetCardinal(fStream, fTbl_loca4[i]);
1522 end;
1523 end;
1524 //------------------------------------------------------------------------------
1525
1526
1527 function IsUnicode(platformID: WORD): Boolean;
1528 begin
1529 Result := (platformID = 0) or (platformID = 3);
1530 end;
1531 //------------------------------------------------------------------------------
1532
1533 function GetNameRecString(stream: TStream;
1534 const nameRec: TNameRec; offset: cardinal): Utf8String;
1535 var
1536 sPos, len: integer;
1537 begin
1538 sPos := stream.Position;
1539 stream.Position := offset + nameRec.offset;
1540 if IsUnicode(nameRec.platformID) then
1541 Result := GetWideString(stream, nameRec.length) else
1542 Result := GetUtf8String(stream, nameRec.length);
1543 len := Length(Result);
1544 if (len > 0) and (Result[len] = #0) then SetLength(Result, len -1);
1545 stream.Position := sPos;
1546 end;
1547 //------------------------------------------------------------------------------
1548
1549 function TFontReader.GetTable_name: Boolean;
1550 var
1551 i: integer;
1552 offset: cardinal;
1553 nameRec: TNameRec;
1554 nameTbl: TFontTable;
1555 begin
1556 fFontInfo.faceName := '';
1557 fFontInfo.fullFaceName := '';
1558 fFontInfo.style := '';
1559 nameTbl := fTables[fTblIdxes[tblName]];
1560 Result := IsValidFontTable(nameTbl) and
1561 (nameTbl.length >= SizeOf(TFontTable_Name));
1562 if not Result then Exit;
1563 fStream.Position := nameTbl.offset;
1564 GetWord(fStream, fTbl_name.format);
1565 GetWord(fStream, fTbl_name.count);
1566 GetWord(fStream, fTbl_name.stringOffset);
1567 offset := nameTbl.offset + fTbl_name.stringOffset;
1568 for i := 1 to fTbl_name.count do
1569 begin
1570 GetWord(fStream, nameRec.platformID);
1571 GetWord(fStream, nameRec.encodingID);
1572 GetWord(fStream, nameRec.languageID);
1573 GetWord(fStream, nameRec.nameID);
1574 GetWord(fStream, nameRec.length);
1575 GetWord(fStream, nameRec.offset);
1576 case nameRec.nameID of
1577 0: fFontInfo.copyright := GetNameRecString(fStream, nameRec, offset);
1578 1: fFontInfo.faceName := GetNameRecString(fStream, nameRec, offset);
1579 2: fFontInfo.style := GetNameRecString(fStream, nameRec, offset);
1580 3: continue;
1581 4: fFontInfo.fullFaceName := GetNameRecString(fStream, nameRec, offset);
1582 5..7: continue;
1583 8: fFontInfo.manufacturer := GetNameRecString(fStream, nameRec, offset);
1584 end;
1585 end;
1586 end;
1587 //------------------------------------------------------------------------------
1588
1589 function TFontReader.GetTable_head: Boolean;
1590 var
1591 headTbl: TFontTable;
1592 yy,mo,dd,hh,mi,ss: cardinal;
1593 begin
1594 headTbl := fTables[fTblIdxes[tblHead]];
1595 Result := IsValidFontTable(headTbl) and (headTbl.length >= 54);
1596 if not Result then Exit;
1597 fStream.Position := headTbl.offset;
1598 GetWord(fStream, fTbl_head.majorVersion);
1599 GetWord(fStream, fTbl_head.minorVersion);
1600 GetFixed(fStream, fTbl_head.fontRevision);
1601
1602 GetCardinal(fStream, fTbl_head.checkSumAdjust);
1603 GetCardinal(fStream, fTbl_head.magicNumber);
1604 GetWord(fStream, fTbl_head.flags);
1605 GetWord(fStream, fTbl_head.unitsPerEm);
1606
1607 GetUInt64(fStream, fTbl_head.dateCreated);
1608 GetMeaningfulDateTime(fTbl_head.dateCreated, yy,mo,dd,hh,mi,ss);
1609 fFontInfo.dateCreated := EncodeDate(yy,mo,dd) + EncodeTime(hh,mi,ss, 0);
1610 GetUInt64(fStream, fTbl_head.dateModified);
1611 GetMeaningfulDateTime(fTbl_head.dateModified, yy,mo,dd,hh,mi,ss);
1612 fFontInfo.dateModified := EncodeDate(yy,mo,dd) + EncodeTime(hh,mi,ss, 0);
1613
1614 GetInt16(fStream, fTbl_head.xMin);
1615 GetInt16(fStream, fTbl_head.yMin);
1616 GetInt16(fStream, fTbl_head.xMax);
1617 GetInt16(fStream, fTbl_head.yMax);
1618 GetWord(fStream, fTbl_head.macStyle);
1619 fFontInfo.macStyles := TMacStyles(Byte(fTbl_head.macStyle));
1620 GetWord(fStream, fTbl_head.lowestRecPPEM);
1621 GetInt16(fStream, fTbl_head.fontDirHint);
1622 GetInt16(fStream, fTbl_head.indexToLocFmt);
1623 GetInt16(fStream, fTbl_head.glyphDataFmt);
1624 result := fTbl_head.magicNumber = $5F0F3CF5
1625 end;
1626 //------------------------------------------------------------------------------
1627
1628 function TFontReader.GetTable_hhea: Boolean;
1629 var
1630 hheaTbl: TFontTable;
1631 begin
1632 hheaTbl := fTables[fTblIdxes[tblHhea]];
1633 Result := IsValidFontTable(hheaTbl) and (hheaTbl.length >= 36);
1634 if not Result then Exit;
1635 fStream.Position := hheaTbl.offset;
1636
1637 GetFixed(fStream, fTbl_hhea.version);
1638 GetInt16(fStream, fTbl_hhea.ascent);
1639 GetInt16(fStream, fTbl_hhea.descent);
1640 GetInt16(fStream, fTbl_hhea.lineGap);
1641 GetWord(fStream, fTbl_hhea.advWidthMax);
1642 GetInt16(fStream, fTbl_hhea.minLSB);
1643 GetInt16(fStream, fTbl_hhea.minRSB);
1644 GetInt16(fStream, fTbl_hhea.xMaxExtent);
1645 GetInt16(fStream, fTbl_hhea.caretSlopeRise);
1646 GetInt16(fStream, fTbl_hhea.caretSlopeRun);
1647 GetInt16(fStream, fTbl_hhea.caretOffset);
1648 GetUInt64(fStream, fTbl_hhea.reserved);
1649 GetInt16(fStream, fTbl_hhea.metricDataFmt);
1650 GetWord(fStream, fTbl_hhea.numLongHorMets);
1651 end;
1652 //------------------------------------------------------------------------------
1653
1654 function TFontReader.GetGlyphHorzMetrics(glyphIdx: WORD): TFontTable_Hmtx;
1655 var
1656 tbl : TFontTable;
1657 begin
1658 tbl := fTables[fTblIdxes[tblHmtx]];
1659 if glyphIdx < fTbl_hhea.numLongHorMets then
1660 begin
1661 fStream.Position := Integer(tbl.offset) + glyphIdx * 4;
1662 GetWord(fStream, Result.advanceWidth);
1663 GetInt16(fStream, Result.leftSideBearing);
1664 end else
1665 begin
1666 fStream.Position := Integer(tbl.offset) +
1667 Integer(fTbl_hhea.numLongHorMets -1) * 4;
1668 GetWord(fStream, Result.advanceWidth);
1669 fStream.Position := Integer(tbl.offset +
1670 fTbl_hhea.numLongHorMets * 4) +
1671 2 * (glyphIdx - Integer(fTbl_hhea.numLongHorMets));
1672 GetInt16(fStream, Result.leftSideBearing);
1673 end;
1674 end;
1675 //------------------------------------------------------------------------------
1676
1677 procedure TFontReader.GetTable_kern;
1678 var
1679 i : integer;
1680 tbl : TFontTable;
1681 tbl_kern : TFontTable_Kern;
1682 kernSub : TKernSubTbl;
1683 format0KernHdr : TFormat0KernHdr;
1684 begin
1685 if fTblIdxes[tblKern] < 0 then Exit;
1686 tbl := fTables[fTblIdxes[tblKern]];
1687 if not IsValidFontTable(tbl) then Exit;
1688 fStream.Position := Integer(tbl.offset);
1689
1690 GetWord(fStream, tbl_kern.version);
1691 GetWord(fStream, tbl_kern.numTables);
1692 if tbl_kern.numTables = 0 then Exit;
1693 // assume there's only one kern table
1694
1695 GetWord(fStream, kernSub.version);
1696 GetWord(fStream, kernSub.length);
1697 GetWord(fStream, kernSub.coverage);
1698 // we're currently only interested in Format0 horizontal kerning
1699 if kernSub.coverage <> 1 then Exit;
1700
1701 GetWord(fStream, format0KernHdr.nPairs);
1702 GetWord(fStream, format0KernHdr.searchRange);
1703 GetWord(fStream, format0KernHdr.entrySelector);
1704 GetWord(fStream, format0KernHdr.rangeShift);
1705
1706 SetLength(fKernTable, format0KernHdr.nPairs);
1707 for i := 0 to format0KernHdr.nPairs -1 do
1708 begin
1709 GetWord(fStream, fKernTable[i].left);
1710 GetWord(fStream, fKernTable[i].right);
1711 GetInt16(fStream, fKernTable[i].value);
1712 end;
1713 end;
1714 //------------------------------------------------------------------------------
1715
1716 procedure TFontReader.GetTable_post;
1717 var
1718 tbl: TFontTable;
1719 begin
1720 if fTblIdxes[tblPost] < 0 then Exit;
1721 tbl := fTables[fTblIdxes[tblPost]];
1722 if not IsValidFontTable(tbl) then Exit;
1723 fStream.Position := Integer(tbl.offset);
1724
1725 GetWord(fStream, fTbl_post.majorVersion);
1726 GetWord(fStream, fTbl_post.minorVersion);
1727 GetFixed(fStream, fTbl_post.italicAngle);
1728 GetInt16(fStream, fTbl_post.underlinePos);
1729 GetInt16(fStream, fTbl_post.underlineWidth);
1730 GetCardinal(fStream, fTbl_post.isFixedPitch);
1731 end;
1732 //------------------------------------------------------------------------------
1733
1734 function FindKernInTable(glyphIdx: WORD; const kernTable: TArrayOfKernRecs): integer;
1735 var
1736 i,l,r: integer;
1737 begin
1738 l := 0;
1739 r := High(kernTable);
1740 while l <= r do
1741 begin
1742 Result := (l + r) shr 1;
1743 i := kernTable[Result].left - glyphIdx;
1744 if i < 0 then
1745 begin
1746 l := Result +1
1747 end else
1748 begin
1749 if i = 0 then
1750 begin
1751 // found a match! Now find the very first one ...
1752 while (Result > 0) and
1753 (kernTable[Result-1].left = glyphIdx) do dec(Result);
1754 Exit;
1755 end;
1756 r := Result -1;
1757 end;
1758 end;
1759 Result := -1;
1760 end;
1761 //------------------------------------------------------------------------------
1762
1763 function TFontReader.GetGlyphKernList(glyphIdx: WORD): TArrayOfTKern;
1764 var
1765 i,j,len: integer;
1766 begin
1767 result := nil;
1768 i := FindKernInTable(glyphIdx, fKernTable);
1769 if i < 0 then Exit;
1770 len := Length(fKernTable);
1771 j := i +1;
1772 while (j < len) and (fKernTable[j].left = glyphIdx) do inc(j);
1773 SetLength(Result, j - i);
1774 for j := 0 to High(Result) do
1775 with fKernTable[i+j] do
1776 begin
1777 Result[j].rightGlyphIdx := right;
1778 Result[j].kernValue := value;
1779 end;
1780 end;
1781 //------------------------------------------------------------------------------
1782
1783 function TFontReader.GetGlyphPaths(glyphIdx: WORD;
1784 var tbl_hmtx: TFontTable_Hmtx; out tbl_glyf: TFontTable_Glyf): TPathsEx;
1785 var
1786 offset: cardinal;
1787 glyfTbl: TFontTable;
1788 begin
1789 result := nil;
1790 if fTbl_head.indexToLocFmt = 0 then
1791 begin
1792 offset := fTbl_loca2[glyphIdx] *2;
1793 if offset = fTbl_loca2[glyphIdx+1] *2 then Exit; // no contours
1794 end else
1795 begin
1796 offset := fTbl_loca4[glyphIdx];
1797 if offset = fTbl_loca4[glyphIdx+1] then Exit; // no contours
1798 end;
1799 glyfTbl := fTables[fTblIdxes[tblGlyf]];
1800 if offset >= glyfTbl.length then Exit;
1801 inc(offset, glyfTbl.offset);
1802
1803 fStream.Position := offset;
1804 GetInt16(fStream, tbl_glyf.numContours);
1805 GetInt16(fStream, tbl_glyf.xMin);
1806 GetInt16(fStream, tbl_glyf.yMin);
1807 GetInt16(fStream, tbl_glyf.xMax);
1808 GetInt16(fStream, tbl_glyf.yMax);
1809
1810 if tbl_glyf.numContours < 0 then
1811 result := GetCompositeGlyph(tbl_glyf, tbl_hmtx) else
1812 result := GetSimpleGlyph(tbl_glyf);
1813 end;
1814 //------------------------------------------------------------------------------
1815
1816 const
1817 // glyf flags - simple
1818 ON_CURVE = $1;
1819 X_SHORT_VECTOR = $2;
1820 Y_SHORT_VECTOR = $4;
1821 REPEAT_FLAG = $8;
1822 X_DELTA = $10;
1823 Y_DELTA = $20;
1824 //------------------------------------------------------------------------------
1825
1826 function TFontReader.GetSimpleGlyph(tbl_glyf: TFontTable_Glyf): TPathsEx;
1827 var
1828 i,j, len: integer;
1829 instructLen: WORD;
1830 flag, repeats: byte;
1831 contourEnds: TArrayOfWord;
1832 begin
1833 SetLength(contourEnds, tbl_glyf.numContours);
1834 for i := 0 to High(contourEnds) do
1835 GetWord(fStream, contourEnds[i]);
1836
1837 // hints are currently ignored
1838 GetWord(fStream, instructLen);
1839 fStream.Position := fStream.Position + instructLen;
1840
1841 setLength(result, tbl_glyf.numContours);
1842 repeats := 0;
1843 flag := 0; // help the compiler with "flag isn't initialized"
1844 for i := 0 to High(result) do
1845 begin
1846 if i = 0 then len := contourEnds[0] +1
1847 else len := contourEnds[i] - contourEnds[i-1];
1848 setLength(result[i], len);
1849
1850 for j := 0 to len -1 do
1851 begin
1852 if repeats = 0 then
1853 begin
1854 GetByte(fStream, flag);
1855 if flag and REPEAT_FLAG = REPEAT_FLAG then
1856 GetByte(fStream, repeats);
1857 end else
1858 dec(repeats);
1859 result[i][j].flag := flag;
1860 end;
1861 end;
1862 if tbl_glyf.numContours > 0 then
1863 GetPathCoords(result);
1864 end;
1865 //------------------------------------------------------------------------------
1866
1867 procedure TFontReader.GetPathCoords(var paths: TPathsEx);
1868 var
1869 i,j: integer;
1870 xi,yi: Int16;
1871 flag, xb,yb: byte;
1872 pt: TPoint;
1873 begin
1874 // get X coords
1875 pt := Point(0,0);
1876 xi := 0;
1877 for i := 0 to high(paths) do
1878 begin
1879 for j := 0 to high(paths[i]) do
1880 begin
1881 flag := paths[i][j].flag;
1882 if flag and X_SHORT_VECTOR = X_SHORT_VECTOR then
1883 begin
1884 GetByte(fStream, xb);
1885 if (flag and X_DELTA) = 0 then
1886 dec(pt.X, xb) else
1887 inc(pt.X, xb);
1888 end else
1889 begin
1890 if flag and X_DELTA = 0 then
1891 begin
1892 if GetInt16(fStream, xi) then
1893 pt.X := pt.X + xi;
1894 end;
1895 end;
1896 paths[i][j].pt.X := pt.X;
1897 end;
1898 end;
1899
1900 // get Y coords
1901 yi := 0;
1902 for i := 0 to high(paths) do
1903 begin
1904 for j := 0 to high(paths[i]) do
1905 begin
1906 flag := paths[i][j].flag;
1907 if flag and Y_SHORT_VECTOR = Y_SHORT_VECTOR then
1908 begin
1909 GetByte(fStream, yb);
1910 if (flag and Y_DELTA) = 0 then
1911 dec(pt.Y, yb) else
1912 inc(pt.Y, yb);
1913 end else
1914 begin
1915 if flag and Y_DELTA = 0 then
1916 begin
1917 if GetInt16(fStream, yi) then
1918 pt.Y := pt.Y + yi;
1919 end;
1920 end;
1921 paths[i][j].pt.Y := pt.Y;
1922 end;
1923 end;
1924 end;
1925 //------------------------------------------------------------------------------
1926
1927 function OnCurve(flag: byte): Boolean;
1928 begin
1929 result := flag and ON_CURVE <> 0;
1930 end;
1931 //------------------------------------------------------------------------------
1932
1933 function MidPoint(const pt1, pt2: TPointEx): TPointEx;
1934 begin
1935 Result.pt.X := (pt1.pt.X + pt2.pt.X) / 2;
1936 Result.pt.Y := (pt1.pt.Y + pt2.pt.Y) / 2;
1937 Result.flag := ON_CURVE;
1938 end;
1939 //------------------------------------------------------------------------------
1940
1941 function TFontReader.ConvertSplinesToBeziers(const pathsEx: TPathsEx): TPathsEx;
1942 var
1943 i,j,k: integer;
1944 pt: TPointEx;
1945 prevOnCurve: Boolean;
1946 begin
1947 SetLength(Result, Length(pathsEx));
1948 for i := 0 to High(pathsEx) do
1949 begin
1950 SetLength(Result[i], Length(pathsEx[i]) *2);
1951 Result[i][0] := pathsEx[i][0]; k := 1;
1952 prevOnCurve := true;
1953 for j := 1 to High(pathsEx[i]) do
1954 begin
1955 if OnCurve(pathsEx[i][j].flag) then
1956 begin
1957 prevOnCurve := true;
1958 end
1959 else if not prevOnCurve then
1960 begin
1961 pt := MidPoint(pathsEx[i][j-1], pathsEx[i][j]);
1962 Result[i][k] := pt; inc(k);
1963 end else
1964 prevOnCurve := false;
1965 Result[i][k] := pathsEx[i][j]; inc(k);
1966 end;
1967 SetLength(Result[i], k);
1968 end;
1969 end;
1970 //------------------------------------------------------------------------------
1971
1972 procedure AppendPathsEx(var paths: TPathsEx; const extra: TPathsEx);
1973 var
1974 i, len1, len2: integer;
1975 begin
1976 len2 := length(extra);
1977 len1 := length(paths);
1978 setLength(paths, len1 + len2);
1979 for i := 0 to len2 -1 do
1980 paths[len1+i] := Copy(extra[i], 0, length(extra[i]));
1981 end;
1982 //------------------------------------------------------------------------------
1983
1984 procedure AffineTransform(const a,b,c,d,e,f: double; var pathsEx: TPathsEx);
1985 var
1986 i,j: integer;
1987 mat: TMatrixD;
1988 begin
1989 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
1990 if ((a = 0) and (b = 0)) or ((c = 0) and (d = 0)) then
1991 begin
1992 if (e = 0) and (f = 0) then Exit;
1993 for i := 0 to High(pathsEx) do
1994 for j := 0 to High(pathsEx[i]) do
1995 with pathsEx[i][j].pt do
1996 begin
1997 X := X + e;
1998 y := Y + f;
1999 end;
2000 end else
2001 begin
2002 mat[0,0] := a;
2003 mat[0,1] := b;
2004 mat[1,0] := c;
2005 mat[1,1] := d;
2006 mat[2][0] := e;
2007 mat[2][1] := f;
2008
2009 for i := 0 to High(pathsEx) do
2010 for j := 0 to High(pathsEx[i]) do
2011 MatrixApply(mat, pathsEx[i][j].pt);
2012 end;
2013 end;
2014 //------------------------------------------------------------------------------
2015
2016 function TFontReader.GetCompositeGlyph(var tbl_glyf: TFontTable_Glyf;
2017 var tbl_hmtx: TFontTable_Hmtx): TPathsEx;
2018 var
2019 streamPos: integer;
2020 flag, glyphIndex: WORD;
2021 arg1_i8, arg2_i8: ShortInt;
2022 arg1_i16, arg2_i16: Int16;
2023 tmp_single: single;
2024 a,b,c,d,e,f: double;
2025 componentPaths: TPathsEx;
2026 component_tbl_glyf: TFontTable_Glyf;
2027 component_tbl_hmtx: TFontTable_Hmtx;
2028 const
2029 ARG_1_AND_2_ARE_WORDS = $1;
2030 ARGS_ARE_XY_VALUES = $2;
2031 ROUND_XY_TO_GRID = $4;
2032 WE_HAVE_A_SCALE = $8;
2033 MORE_COMPONENTS = $20;
2034 WE_HAVE_AN_X_AND_Y_SCALE = $40;
2035 WE_HAVE_A_TWO_BY_TWO = $80;
2036 WE_HAVE_INSTRUCTIONS = $100;
2037 USE_MY_METRICS = $200;
2038 begin
2039 result := nil;
2040 flag := MORE_COMPONENTS;
2041 while (flag and MORE_COMPONENTS <> 0) do
2042 begin
2043 glyphIndex := 0;
2044 a := 0; b := 0; c := 0; d := 0; e := 0; f := 0;
2045
2046 GetWord(fStream, flag);
2047 GetWord(fStream, glyphIndex);
2048
2049 if (flag and ARG_1_AND_2_ARE_WORDS <> 0) then
2050 begin
2051 GetInt16(fStream, arg1_i16);
2052 GetInt16(fStream, arg2_i16);
2053 if (flag and ARGS_ARE_XY_VALUES <> 0) then
2054 begin
2055 e := arg1_i16;
2056 f := arg2_i16;
2057 end;
2058 end else
2059 begin
2060 GetShortInt(fStream, arg1_i8);
2061 GetShortInt(fStream, arg2_i8);
2062 if (flag and ARGS_ARE_XY_VALUES <> 0) then
2063 begin
2064 e := arg1_i8;
2065 f := arg2_i8;
2066 end;
2067 end;
2068
2069 if (flag and WE_HAVE_A_SCALE <> 0) then
2070 begin
2071 Get2Dot14(fStream, tmp_single);
2072 a := tmp_single; d := tmp_single;
2073 end
2074 else if (flag and WE_HAVE_AN_X_AND_Y_SCALE <> 0) then
2075 begin
2076 Get2Dot14(fStream, tmp_single); a := tmp_single;
2077 Get2Dot14(fStream, tmp_single); d := tmp_single;
2078 end
2079 else if (flag and WE_HAVE_A_TWO_BY_TWO <> 0) then
2080 begin
2081 Get2Dot14(fStream, tmp_single); a := tmp_single;
2082 Get2Dot14(fStream, tmp_single); b := tmp_single;
2083 Get2Dot14(fStream, tmp_single); c := tmp_single;
2084 Get2Dot14(fStream, tmp_single); d := tmp_single;
2085 end;
2086
2087 component_tbl_hmtx := tbl_hmtx;
2088
2089 // GetGlyphPaths() will change the stream position, so save it.
2090 streamPos := fStream.Position;
2091 componentPaths := GetGlyphPaths(glyphIndex, component_tbl_hmtx, component_tbl_glyf);
2092 // return to saved stream position
2093 fStream.Position := streamPos;
2094
2095 if (flag and ARGS_ARE_XY_VALUES <> 0) then
2096 AffineTransform(a,b,c,d,e,f, componentPaths); // (#131)
2097
2098 if (flag and USE_MY_METRICS <> 0) then
2099 tbl_hmtx := component_tbl_hmtx; // (#24)
2100
2101 if component_tbl_glyf.numContours > 0 then
2102 begin
2103 if tbl_glyf.numContours < 0 then tbl_glyf.numContours := 0;
2104 inc(tbl_glyf.numContours, component_tbl_glyf.numContours);
2105 tbl_glyf.xMin := Min(tbl_glyf.xMin, component_tbl_glyf.xMin);
2106 tbl_glyf.xMax := Max(tbl_glyf.xMax, component_tbl_glyf.xMax);
2107 tbl_glyf.yMin := Min(tbl_glyf.yMin, component_tbl_glyf.yMin);
2108 tbl_glyf.yMax := Max(tbl_glyf.yMax, component_tbl_glyf.yMax);
2109 end;
2110 AppendPathsEx(result, componentPaths);
2111 end;
2112 end;
2113 //------------------------------------------------------------------------------
2114
2115 function TFontReader.HasGlyph(codepoint: Cardinal): Boolean;
2116 begin
2117 Result := GetGlyphIdxUsingCmap(codepoint) > 0;
2118 end;
2119 //------------------------------------------------------------------------------
2120
2121 function FlattenPathExBeziers(pathsEx: TPathsEx): TPathsD;
2122 var
2123 i,j : integer;
2124 pt2: TPointEx;
2125 bez: TPathD;
2126 begin
2127 setLength(Result, length(pathsEx));
2128 for i := 0 to High(pathsEx) do
2129 begin
2130 SetLength(Result[i],1);
2131 Result[i][0] := pathsEx[i][0].pt;
2132 for j := 1 to High(pathsEx[i]) do
2133 begin
2134 if OnCurve(pathsEx[i][j].flag) then
2135 begin
2136 AppendPoint(Result[i], pathsEx[i][j].pt);
2137 end else
2138 begin
2139 if j = High(pathsEx[i]) then
2140 pt2 := pathsEx[i][0] else
2141 pt2 := pathsEx[i][j+1];
2142 bez := FlattenQBezier(pathsEx[i][j-1].pt, pathsEx[i][j].pt, pt2.pt);
2143 ConcatPaths(Result[i], bez);
2144 end;
2145 end;
2146 end;
2147 end;
2148 //------------------------------------------------------------------------------
2149
2150 function TFontReader.GetGlyphInfo(codepoint: Cardinal;
2151 out nextX: integer; out glyphInfo: TGlyphInfo): Boolean;
2152 var
2153 glyphIdx: WORD;
2154 begin
2155 Result := IsValidFontFormat;
2156 if not Result then Exit;
2157 glyphIdx := GetGlyphIdxUsingCmap(codepoint);
2158 glyphInfo := GetGlyphInfoInternal(glyphIdx);
2159 glyphInfo.hmtx := GetGlyphHorzMetrics(glyphIdx);
2160 nextX := glyphInfo.hmtx.advanceWidth;
2161 glyphInfo.codepoint := codepoint;
2162 end;
2163 //------------------------------------------------------------------------------
2164
2165 function TFontReader.GetFontInfo: TFontInfo;
2166 begin
2167 if not IsValidFontFormat then
2168 begin
2169 FillChar(Result, SizeOf(Result), 0);
2170 Exit;
2171 end;
2172
2173 result := fFontInfo;
2174 if result.unitsPerEm > 0 then Exit;
2175
2176 // and updated the record with everything except the strings
2177 result.unitsPerEm := fTbl_head.unitsPerEm;
2178 result.xMin := fTbl_head.xMin;
2179 result.xMax := fTbl_head.xMax;
2180 result.yMin := fTbl_head.yMin;
2181 result.yMax := fTbl_head.yMax;
2182
2183 // note: the following three fields "represent the design
2184 // intentions of the font's creator rather than any computed value"
2185 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6hhea.html
2186
2187 result.ascent := fTbl_hhea.ascent;
2188 result.descent := abs(fTbl_hhea.descent);
2189 result.lineGap := fTbl_hhea.lineGap;
2190 result.advWidthMax := fTbl_hhea.advWidthMax;
2191 result.minLSB := fTbl_hhea.minLSB;
2192 result.minRSB := fTbl_hhea.minRSB;
2193 result.xMaxExtent := fTbl_hhea.xMaxExtent;
2194 end;
2195 //------------------------------------------------------------------------------
2196
2197 function TFontReader.GetGlyphInfoInternal(glyphIdx: WORD): TGlyphInfo;
2198 var
2199 pathsEx: TPathsEx;
2200 begin
2201 FillChar(result, sizeOf(Result), 0);
2202 if not IsValidFontFormat then Exit;
2203 result.glyphIdx := glyphIdx;
2204 result.unitsPerEm := fTbl_head.unitsPerEm;
2205 // get raw splines
2206 pathsEx := GetGlyphPaths(glyphIdx, result.hmtx, result.glyf);
2207 if Assigned(pathsEx) then
2208 begin
2209 pathsEx := ConvertSplinesToBeziers(pathsEx);
2210 result.paths := FlattenPathExBeziers(PathsEx);
2211 end;
2212 Result.kernList := GetGlyphKernList(glyphIdx);
2213 end;
2214 //------------------------------------------------------------------------------
2215
2216 function TFontReader.GetWeight: integer;
2217 var
2218 i, dummy: integer;
2219 accum: Cardinal;
2220 gm: TGlyphInfo;
2221 rec: TRectD;
2222 img: TImage32;
2223 p: PARGB;
2224 const
2225 imgSize = 16;
2226 k = 5; // an empirical constant
2227 begin
2228 // get an empirical weight based on the character 'G'
2229 result := 0;
2230 if not IsValidFontFormat then Exit;
2231 if fFontWeight > 0 then
2232 begin
2233 Result := fFontWeight;
2234 Exit;
2235 end;
2236 GetGlyphInfo(Ord('G'),dummy, gm);
2237 rec := GetBoundsD(gm.paths);
2238 gm.paths := Img32.Vector.TranslatePath(gm.paths, -rec.Left, -rec.Top);
2239 gm.paths := Img32.Vector.ScalePath(gm.paths, imgSize/rec.Width, imgSize/rec.Height);
2240 img := TImage32.Create(imgSize,imgSize);
2241 try
2242 DrawPolygon(img, gm.paths, frEvenOdd, clBlack32);
2243 accum := 0;
2244 p := PARGB(img.PixelBase);
2245 for i := 0 to imgSize * imgSize do
2246 begin
2247 inc(accum, p.A);
2248 inc(p);
2249 end;
2250 finally
2251 img.Free;
2252 end;
2253 fFontWeight := Max(100, Min(900,
2254 Round(k * accum / (imgSize * imgSize * 100)) * 100));
2255 Result := fFontWeight;
2256 end;
2257 //------------------------------------------------------------------------------
2258
2259 procedure TFontReader.GetFontFamily;
2260 var
2261 giT, giI, giM: integer;
2262 gmT: TGlyphInfo;
2263 hmtxI, hmtxM: TFontTable_Hmtx;
2264 begin
2265 fFontInfo.family := tfUnknown;
2266
2267 if (fTbl_post.majorVersion > 0) and
2268 (fTbl_post.isFixedPitch <> 0) then
2269 begin
2270 fFontInfo.family := tfMonospace;
2271 Exit;
2272 end;
2273
2274 // use glyph metrics for 'T', 'i' & 'm' to determine the font family
2275 // if the widths of 'i' & 'm' are equal, then assume a monospace font
2276 // else if the number of vertices used to draw 'T' is greater than 10
2277 // then assume a serif font otherwise assume a sans serif font.
2278
2279 giT := GetGlyphIdxUsingCmap(Ord('T'));
2280 giI := GetGlyphIdxUsingCmap(Ord('i'));
2281 giM := GetGlyphIdxUsingCmap(Ord('m'));
2282 if (giT = 0) or (giI = 0) or (giM = 0) then Exit;
2283
2284 hmtxI := GetGlyphHorzMetrics(giI);
2285 hmtxM := GetGlyphHorzMetrics(giM);
2286 if hmtxI.advanceWidth = hmtxM.advanceWidth then
2287 begin
2288 fFontInfo.family := tfMonospace;
2289 Exit;
2290 end;
2291
2292 gmT := GetGlyphInfoInternal(giT);
2293 if Assigned(gmT.paths) and (Length(gmT.paths[0]) > 10) then
2294 fFontInfo.family := tfSerif else
2295 fFontInfo.family := tfSansSerif;
2296 end;
2297
2298 //------------------------------------------------------------------------------
2299 // TFontCache
2300 //------------------------------------------------------------------------------
2301
2302 constructor TFontCache.Create(fontReader: TFontReader; fontHeight: double);
2303 begin
2304 {$IFDEF XPLAT_GENERICS}
2305 fGlyphInfoList := TList<PGlyphInfo>.Create;
2306 {$ELSE}
2307 fGlyphInfoList := TList.Create;
2308 {$ENDIF}
2309 fSorted := false;
2310 fUseKerning := true;
2311 fFlipVert := true;
2312
2313 fFontHeight := fontHeight;
2314 SetFontReader(fontReader);
2315 end;
2316 //------------------------------------------------------------------------------
2317
2318 destructor TFontCache.Destroy;
2319 begin
2320 SetFontReader(nil);
2321 Clear;
2322 NotifyRecipients(inDestroy);
2323 fGlyphInfoList.Free;
2324 inherited;
2325 end;
2326 //------------------------------------------------------------------------------
2327
2328 procedure TFontCache.ReceiveNotification(Sender: TObject; notify: TImg32Notification);
2329 begin
2330 if Sender <> fFontReader then
2331 raise Exception.Create(rsFontCacheError);
2332 if notify = inStateChange then
2333 begin
2334 Clear;
2335 UpdateScale;
2336 end else
2337 SetFontReader(nil);
2338 end;
2339 //------------------------------------------------------------------------------
2340
2341 procedure TFontCache.NotifyRecipients(notifyFlag: TImg32Notification);
2342 var
2343 i: integer;
2344 begin
2345 for i := High(fRecipientList) downto 0 do
2346 try
2347 // try .. except block because when TFontCache is destroyed in a
2348 // finalization section, it's possible for recipients to have been
2349 // destroyed without calling their destructors.
2350 fRecipientList[i].ReceiveNotification(self, notifyFlag);
2351 except
2352 end;
2353 end;
2354 //------------------------------------------------------------------------------
2355
2356 procedure TFontCache.AddRecipient(recipient: INotifyRecipient);
2357 var
2358 len: integer;
2359 begin
2360 len := Length(fRecipientList);
2361 SetLength(fRecipientList, len+1);
2362 fRecipientList[len] := Recipient;
2363 end;
2364 //------------------------------------------------------------------------------
2365
2366 procedure TFontCache.DeleteRecipient(recipient: INotifyRecipient);
2367 var
2368 i, highI: integer;
2369 begin
2370 highI := High(fRecipientList);
2371 i := highI;
2372 while (i >= 0) and (fRecipientList[i] <> Recipient) do dec(i);
2373 if i < 0 then Exit;
2374 if i < highI then
2375 Move(fRecipientList[i+i], fRecipientList[i],
2376 (highI - i) * SizeOf(INotifyRecipient));
2377 SetLength(fRecipientList, highI);
2378 end;
2379 //------------------------------------------------------------------------------
2380
2381 procedure TFontCache.Clear;
2382 var
2383 i: integer;
2384 begin
2385 for i := 0 to fGlyphInfoList.Count -1 do
2386 Dispose(PGlyphInfo(fGlyphInfoList[i]));
2387 fGlyphInfoList.Clear;
2388 fSorted := false;
2389 end;
2390 //------------------------------------------------------------------------------
2391
2392 {$IFDEF XPLAT_GENERICS}
2393 function FindInSortedList(charOrdinal: Cardinal; glyphList: TList<PGlyphInfo>): integer;
2394 {$ELSE}
2395 function FindInSortedList(charOrdinal: Cardinal; glyphList: TList): integer;
2396 {$ENDIF}
2397 var
2398 i,l,r: integer;
2399 begin
2400 // binary search the sorted list ...
2401 l := 0;
2402 r := glyphList.Count -1;
2403 while l <= r do
2404 begin
2405 Result := (l + r) shr 1;
2406 i := integer(PGlyphInfo(glyphList[Result]).codepoint) - integer(charOrdinal);
2407 if i < 0 then
2408 begin
2409 l := Result +1
2410 end else
2411 begin
2412 if i = 0 then Exit;
2413 r := Result -1;
2414 end;
2415 end;
2416 Result := -1;
2417 end;
2418 //------------------------------------------------------------------------------
2419
2420 function TFontCache.FoundInList(charOrdinal: Cardinal): Boolean;
2421 begin
2422 if not fSorted then Sort;
2423 result := FindInSortedList(charOrdinal, fGlyphInfoList) >= 0;
2424 end;
2425 //------------------------------------------------------------------------------
2426
2427 procedure TFontCache.GetMissingGlyphs(const ordinals: TArrayOfCardinal);
2428 var
2429 i, len: integer;
2430 begin
2431 if not IsValidFont then Exit;
2432 len := Length(ordinals);
2433 for i := 0 to len -1 do
2434 begin
2435 if ordinals[i] < 32 then continue
2436 else if not FoundInList(ordinals[i]) then AddGlyph(ordinals[i]);
2437 end;
2438 end;
2439 //------------------------------------------------------------------------------
2440
2441 function TFontCache.IsValidFont: Boolean;
2442 begin
2443 Result := assigned(fFontReader) and fFontReader.IsValidFontFormat;
2444 end;
2445 //------------------------------------------------------------------------------
2446
2447 function TFontCache.GetAscent: double;
2448 begin
2449 if not IsValidFont then Result := 0
2450 else with fFontReader.FontInfo do
2451 Result := Max(ascent, yMax) * fScale;
2452 end;
2453 //------------------------------------------------------------------------------
2454
2455 function TFontCache.GetDescent: double;
2456 begin
2457 if not IsValidFont then Result := 0
2458 else with fFontReader.FontInfo do
2459 Result := Max(descent, -yMin) * fScale;
2460 end;
2461 //------------------------------------------------------------------------------
2462
2463 function TFontCache.GetGap: double;
2464 begin
2465 if not IsValidFont then Result := 0
2466 else Result := fFontReader.FontInfo.lineGap * fScale;
2467 end;
2468 //------------------------------------------------------------------------------
2469
2470 function TFontCache.GetLineHeight: double;
2471 begin
2472 if not IsValidFont then Result := 0
2473 else Result := Ascent + Descent + LineGap;
2474 end;
2475 //------------------------------------------------------------------------------
2476
2477 function TFontCache.GetYyHeight: double;
2478 var
2479 minY, maxY: double;
2480 begin
2481 // nb: non-inverted Y coordinates.
2482 maxY := GetGlyphInfo(ord('Y')).glyf.yMax;
2483 minY := GetGlyphInfo(ord('y')).glyf.yMin;
2484 Result := (maxY - minY) * fScale;
2485 end;
2486 //------------------------------------------------------------------------------
2487
2488 procedure TFontCache.VerticalFlip(var paths: TPathsD);
2489 var
2490 i,j: integer;
2491 begin
2492 for i := 0 to High(paths) do
2493 for j := 0 to High(paths[i]) do
2494 with paths[i][j] do Y := -Y;
2495 end;
2496 //------------------------------------------------------------------------------
2497
2498 function FindInKernList(glyphIdx: WORD; const kernList: TArrayOfTKern): integer;
2499 var
2500 i,l,r: integer;
2501 begin
2502 l := 0;
2503 r := High(kernList);
2504 while l <= r do
2505 begin
2506 Result := (l + r) shr 1;
2507 i := kernList[Result].rightGlyphIdx - glyphIdx;
2508 if i < 0 then
2509 begin
2510 l := Result +1
2511 end else
2512 begin
2513 if i = 0 then Exit; // found!
2514 r := Result -1;
2515 end;
2516 end;
2517 Result := -1;
2518 end;
2519 //------------------------------------------------------------------------------
2520
2521 function TFontCache.GetGlyphInfo(codepoint: Cardinal): PGlyphInfo;
2522 var
2523 listIdx: integer;
2524 begin
2525 Result := nil;
2526 if not IsValidFont then Exit;
2527 if not fSorted then Sort;
2528 listIdx := FindInSortedList(codepoint, fGlyphInfoList);
2529 if listIdx < 0 then
2530 Result := AddGlyph(codepoint) else
2531 Result := PGlyphInfo(fGlyphInfoList[listIdx]);
2532 end;
2533 //------------------------------------------------------------------------------
2534
2535 function IsSurrogate(c: WideChar): Boolean;
2536 {$IFDEF INLINE} inline; {$ENDIF}
2537 begin
2538 Result := (c >= #$D800) and (c <= #$DFFF);
2539 end;
2540 //------------------------------------------------------------------------------
2541
2542 function ConvertSurrogatePair(hiSurrogate, loSurrogate: Cardinal): Cardinal;
2543 {$IFDEF INLINE} inline; {$ENDIF}
2544 begin
2545 Result := ((hiSurrogate - $D800) shl 10) + (loSurrogate - $DC00) + $10000;
2546 end;
2547 //------------------------------------------------------------------------------
2548
2549 function TFontCache.GetTextCodePoints(const text: UnicodeString): TArrayOfCardinal;
2550 var
2551 i,j, len: integer;
2552 inSurrogate: Boolean;
2553 begin
2554 len := Length(text);
2555 setLength(Result, len);
2556 inSurrogate := false;
2557 j := 0;
2558 for i := 1 to len do
2559 begin
2560 if inSurrogate then
2561 begin
2562 Result[j] := ConvertSurrogatePair(Ord(text[i -1]), Ord(text[i]));
2563 inSurrogate := false;
2564 end
2565 else if IsSurrogate(text[i]) then
2566 begin
2567 inSurrogate := true;
2568 Continue;
2569 end
2570 else
2571 Result[j] := Ord(WideChar(text[i]));
2572 inc(j);
2573 end;
2574 setLength(Result, j);
2575 end;
2576 //------------------------------------------------------------------------------
2577
2578 function TFontCache.GetGlyphOffsets(const text: UnicodeString;
2579 interCharSpace: double): TArrayOfDouble;
2580 var
2581 i,j, len: integer;
2582 codePoints: TArrayOfCardinal;
2583 glyphInfo: PGlyphInfo;
2584 thisX: double;
2585 prevGlyphKernList: TArrayOfTKern;
2586 begin
2587 codePoints := GetTextCodePoints(text);
2588 len := Length(codePoints);
2589 SetLength(Result, len +1);
2590 Result[0] := 0;
2591 if len = 0 then Exit;
2592 GetMissingGlyphs(codePoints);
2593
2594 thisX := 0;
2595 prevGlyphKernList := nil;
2596 for i := 0 to High(codePoints) do
2597 begin
2598 glyphInfo := GetGlyphInfo(codePoints[i]);
2599 if not assigned(glyphInfo) then Break;
2600 if fUseKerning and assigned(prevGlyphKernList) then
2601 begin
2602 j := FindInKernList(glyphInfo.glyphIdx, prevGlyphKernList);
2603 if (j >= 0) then
2604 thisX := thisX + prevGlyphKernList[j].kernValue*fScale;
2605 end;
2606 Result[i] := thisX;
2607 thisX := thisX + glyphInfo.hmtx.advanceWidth*fScale +interCharSpace;
2608 prevGlyphKernList := glyphInfo.kernList;
2609 end;
2610 Result[len] := thisX - interCharSpace;
2611 end;
2612 //------------------------------------------------------------------------------
2613
2614 function TFontCache.GetTextWidth(const text: UnicodeString): double;
2615 var
2616 offsets: TArrayOfDouble;
2617 begin
2618 Result := 0;
2619 if not IsValidFont then Exit;
2620 offsets := GetGlyphOffsets(text);
2621 Result := offsets[high(offsets)];
2622 end;
2623 //------------------------------------------------------------------------------
2624
2625 function TFontCache.CountCharsThatFit(const text: UnicodeString;
2626 maxWidth: double): integer;
2627 var
2628 offsets: TArrayOfDouble;
2629 begin
2630 Result := 0;
2631 if not IsValidFont then Exit;
2632 offsets := GetGlyphOffsets(text);
2633 Result := Length(offsets);
2634 while offsets[Result -1] > maxWidth do
2635 Dec(Result);
2636 end;
2637 //------------------------------------------------------------------------------
2638
2639 function TFontCache.GetSpaceWidth: double;
2640 begin
2641 Result := GetGlyphInfo(32).hmtx.advanceWidth * fScale;
2642 end;
2643 //------------------------------------------------------------------------------
2644
2645 function TFontCache.GetTextOutline(x, y: double; const text: UnicodeString): TPathsD;
2646 var
2647 dummy: double;
2648 begin
2649 Result := GetTextOutline(x, y, text, dummy);
2650 end;
2651 //------------------------------------------------------------------------------
2652
2653 function TFontCache.GetTextOutline(x, y: double; const text: UnicodeString;
2654 out nextX: double; underlineIdx: integer): TPathsD;
2655 var
2656 arrayOfGlyphs: TArrayOfPathsD;
2657 dummy: TArrayOfDouble;
2658 begin
2659 Result := nil;
2660 if not GetTextOutlineInternal(x, y,
2661 text, underlineIdx, arrayOfGlyphs, dummy, nextX) then Exit;
2662 Result := MergeArrayOfPaths(arrayOfGlyphs);
2663 end;
2664 //------------------------------------------------------------------------------
2665
2666 function TFontCache.GetTextOutline(const rec: TRectD; const text: UnicodeString;
2667 ta: TTextAlign; tav: TTextVAlign; underlineIdx: integer): TPathsD;
2668 var
2669 dummy2, dx, dy: double;
2670 arrayOfGlyphs: TArrayOfPathsD;
2671 dummy1: TArrayOfDouble;
2672 rec2: TRectD;
2673 begin
2674 Result := nil;
2675 if not GetTextOutlineInternal(0, 0, text, underlineIdx,
2676 arrayOfGlyphs, dummy1, dummy2) or (arrayOfGlyphs = nil) then Exit;
2677
2678 rec2 := GetBoundsD(arrayOfGlyphs);
2679 case ta of
2680 taRight: dx := rec.Right - rec2.Width;
2681 taCenter: dx := rec.Left + (rec.Width - rec2.Width)/ 2;
2682 else dx := rec.Left;
2683 end;
2684
2685 case tav of
2686 tvaMiddle: dy := rec.Top - rec2.Top + (rec.Height - rec2.Height)/ 2;
2687 tvaBottom: dy := rec.Bottom - Descent;
2688 else dy := rec.Top + Ascent;
2689 end;
2690
2691 Result := MergeArrayOfPathsEx(arrayOfGlyphs, dx, dy);
2692 end;
2693 //------------------------------------------------------------------------------
2694
2695 function TFontCache.GetUnderlineOutline(leftX, rightX, y: double;
2696 dy: double; wavy: Boolean; strokeWidth: double): TPathD;
2697 var
2698 i, cnt: integer;
2699 dx: double;
2700 wavyPath: TPathD;
2701 begin
2702
2703 if strokeWidth <= 0 then
2704 strokeWidth := LineHeight * lineFrac;
2705 if dy = InvalidD then
2706 y := y + 1.5 * (1 + strokeWidth) else
2707 y := y + dy;
2708
2709 if wavy then
2710 begin
2711 Result := nil;
2712 cnt := Ceil((rightX - leftX) / (strokeWidth *4));
2713 if cnt < 2 then Exit;
2714 dx := (rightX - leftX)/ cnt;
2715 SetLength(wavyPath, cnt +2);
2716 wavyPath[0] := PointD(leftX, y + strokeWidth/2);
2717 wavyPath[1] := PointD(leftX + dx/2, y-(strokeWidth *2));
2718
2719 for i := 1 to cnt do
2720 wavyPath[i+1] := PointD(leftX + dx * i, y + strokeWidth/2);
2721 Result := FlattenQSpline(wavyPath);
2722 wavyPath := ReversePath(Result);
2723 wavyPath := TranslatePath(wavyPath, 0, strokeWidth *1.5);
2724 ConcatPaths(Result, wavyPath);
2725 end else
2726 Result := Rectangle(leftX, y, rightX, y + strokeWidth);
2727 end;
2728 //------------------------------------------------------------------------------
2729
2730 function TFontCache.GetVerticalTextOutline(x, y: double;
2731 const text: UnicodeString; lineHeight: double): TPathsD;
2732 var
2733 i, cnt, xxMax: integer;
2734 glyphInfo: PGlyphInfo;
2735 dx: double;
2736 codePoints: TArrayOfCardinal;
2737 glyphInfos: array of PGlyphInfo;
2738 begin
2739 Result := nil;
2740 if not IsValidFont then Exit;
2741
2742 codePoints := GetTextCodePoints(text);
2743 xxMax := 0;
2744 cnt := Length(codePoints);
2745 SetLength(glyphInfos, cnt);
2746 for i := 0 to cnt -1 do
2747 begin
2748 glyphInfos[i] := GetGlyphInfo(codePoints[i]);
2749 if not assigned(glyphInfos[i]) then Exit;
2750 with glyphInfos[i].glyf do
2751 if xMax > xxMax then
2752 xxMax := xMax;
2753 end;
2754
2755 if lineHeight = 0.0 then
2756 lineHeight := self.LineHeight;
2757
2758 for i := 0 to cnt -1 do
2759 begin
2760 glyphInfo := glyphInfos[i];
2761 with glyphInfo.glyf do
2762 dx := (xxMax - xMax) * 0.5 * scale;
2763 AppendPath(Result, TranslatePath(glyphInfo.paths, x + dx, y));
2764 y := y + lineHeight;
2765 end;
2766 UpdateFontReaderLastUsedTime;
2767 end;
2768 //------------------------------------------------------------------------------
2769
2770 function TFontCache.GetTextOutlineInternal(x, y: double;
2771 const text: UnicodeString; underlineIdx: integer; out glyphs: TArrayOfPathsD;
2772 out offsets: TArrayOfDouble; out nextX: double): Boolean;
2773 var
2774 i,j, len : integer;
2775 dx,y2,w : double;
2776 codepoints : TArrayOfCardinal;
2777 glyphInfo : PGlyphInfo;
2778 currGlyph : TPathsD;
2779 prevGlyphKernList: TArrayOfTKern;
2780 begin
2781 Result := true;
2782 codePoints := GetTextCodePoints(text);
2783 len := Length(codepoints);
2784 GetMissingGlyphs(codepoints);
2785
2786 SetLength(offsets, len);
2787 nextX := x;
2788 prevGlyphKernList := nil;
2789 for i := 0 to len -1 do
2790 begin
2791 offsets[i] := nextX;
2792 glyphInfo := GetGlyphInfo(codepoints[i]);
2793 if not assigned(glyphInfo) then Break;
2794 if fUseKerning and assigned(prevGlyphKernList) then
2795 begin
2796 j := FindInKernList(glyphInfo.glyphIdx, prevGlyphKernList);
2797 if (j >= 0) then
2798 nextX := nextX + prevGlyphKernList[j].kernValue * fScale;
2799 end;
2800
2801 currGlyph := TranslatePath(glyphInfo.paths, nextX, y);
2802 dx := glyphInfo.hmtx.advanceWidth * fScale;
2803 AppendPath(glyphs, currGlyph);
2804
2805 if not fUnderlined and (underlineIdx -1 = i) then
2806 begin
2807 w := LineHeight * lineFrac;
2808 y2 := y + 1.5 * (1 + w);
2809 SetLength(currGlyph, 1);
2810 currGlyph[0] := Rectangle(nextX, y2, nextX +dx, y2 + w);
2811 AppendPath(glyphs, currGlyph);
2812 end;
2813
2814 nextX := nextX + dx;
2815 prevGlyphKernList := glyphInfo.kernList;
2816 end;
2817
2818 if fUnderlined then
2819 begin
2820 w := LineHeight * lineFrac;
2821 y2 := y + 1.5 * (1 + w);
2822 SetLength(currGlyph, 1);
2823 currGlyph[0] := Rectangle(x, y2, nextX, y2 + w);
2824 AppendPath(glyphs, currGlyph);
2825 end;
2826
2827 if fStrikeOut then
2828 begin
2829 w := LineHeight * lineFrac;
2830 y2 := y - LineHeight * 0.22;
2831 SetLength(currGlyph, 1);
2832 currGlyph[0] := Rectangle(x, y2, nextX, y2 + w);
2833 AppendPath(glyphs, currGlyph);
2834 end;
2835
2836 UpdateFontReaderLastUsedTime;
2837 end;
2838 //------------------------------------------------------------------------------
2839
2840 function TFontCache.GetAngledTextGlyphs(x, y: double;
2841 const text: UnicodeString; angleRadians: double;
2842 const rotatePt: TPointD; out nextPt: TPointD): TPathsD;
2843 begin
2844 nextPt.Y := y;
2845 Result := GetTextOutline(x,y, text, nextPt.X);
2846 if not Assigned(Result) then Exit;
2847 Result := RotatePath(Result, rotatePt, angleRadians);
2848 RotatePoint(nextPt, PointD(x,y), angleRadians);
2849 UpdateFontReaderLastUsedTime;
2850 end;
2851 //------------------------------------------------------------------------------
2852
2853 procedure TFontCache.UpdateFontReaderLastUsedTime;
2854 begin
2855 if Assigned(fFontReader) then
2856 fFontReader.LastUsedTime := now;
2857 end;
2858 //------------------------------------------------------------------------------
2859
2860 procedure TFontCache.SetFontReader(newFontReader: TFontReader);
2861 begin
2862 if newFontReader = fFontReader then Exit;
2863 if Assigned(fFontReader) then
2864 begin
2865 fFontReader.DeleteRecipient(self as INotifyRecipient);
2866 Clear;
2867 end;
2868 fFontReader := newFontReader;
2869 if Assigned(fFontReader) then
2870 fFontReader.AddRecipient(self as INotifyRecipient);
2871 UpdateScale;
2872 end;
2873 //------------------------------------------------------------------------------
2874
2875 procedure TFontCache.UpdateScale;
2876 begin
2877 if IsValidFont and (fFontHeight > 0) then
2878 fScale := fFontHeight / fFontReader.FontInfo.unitsPerEm else
2879 fScale := 1;
2880 NotifyRecipients(inStateChange);
2881 end;
2882 //------------------------------------------------------------------------------
2883
2884 procedure TFontCache.SetFontHeight(newHeight: double);
2885 begin
2886 newHeight := abs(newHeight); // manage point - pixel conversions externally
2887 if fFontHeight = newHeight then Exit;
2888 fFontHeight := newHeight;
2889 Clear;
2890 UpdateScale;
2891 end;
2892 //------------------------------------------------------------------------------
2893
2894 procedure FlipVert(var paths: TPathsD);
2895 var
2896 i,j: integer;
2897 begin
2898 for i := 0 to High(paths) do
2899 for j := 0 to High(paths[i]) do
2900 paths[i][j].Y := -paths[i][j].Y;
2901 end;
2902 //------------------------------------------------------------------------------
2903
2904 procedure TFontCache.SetFlipVert(value: Boolean);
2905 var
2906 i: integer;
2907 glyphInfo: PGlyphInfo;
2908 begin
2909 if fFlipVert = value then Exit;
2910 for i := 0 to fGlyphInfoList.Count -1 do
2911 begin
2912 glyphInfo := PGlyphInfo(fGlyphInfoList[i]);
2913 FlipVert(glyphInfo.paths);
2914 end;
2915 fFlipVert := value;
2916 end;
2917 //------------------------------------------------------------------------------
2918
2919 function GlyphSorter(glyph1, glyph2: pointer): integer;
2920 begin
2921 Result := PGlyphInfo(glyph1).codepoint - PGlyphInfo(glyph2).codepoint;
2922 end;
2923 //------------------------------------------------------------------------------
2924
2925 procedure TFontCache.Sort;
2926 begin
2927 {$IFDEF XPLAT_GENERICS}
2928 fGlyphInfoList.Sort(TComparer<PGlyphInfo>.Construct(
2929 function (const glyph1, glyph2: PGlyphInfo): integer
2930 begin
2931 Result := glyph1.codepoint - glyph2.codepoint;
2932 end));
2933 {$ELSE}
2934 fGlyphInfoList.Sort(GlyphSorter);
2935 {$ENDIF}
2936 fSorted := true;
2937 end;
2938 //------------------------------------------------------------------------------
2939
2940 function TFontCache.AddGlyph(codepoint: Cardinal): PGlyphInfo;
2941 var
2942 dummy: integer;
2943 altFontReader: TFontReader;
2944 glyphIdx: WORD;
2945 scale: double;
2946 const
2947 minLength = 0.1;
2948 begin
2949
2950 New(Result);
2951 Result.codepoint := codepoint;
2952 if not fFontReader.GetGlyphInfo(codepoint, dummy, Result^) or
2953 (Result.glyphIdx = 0) then
2954 begin
2955 // to get here the unicode char is not supported by fFontReader
2956 altFontReader :=
2957 aFontManager.FindReaderContainingGlyph(codepoint, tfUnknown, glyphIdx);
2958 if Assigned(altFontReader) then
2959 begin
2960 altFontReader.GetGlyphInfo(codepoint, dummy, Result^);
2961 altFontReader.LastUsedTime := now;
2962 scale := fFontReader.FontInfo.unitsPerEm / altFontReader.FontInfo.unitsPerEm;
2963 if scale <> 1.0 then
2964 Result.paths := ScalePath(Result.paths, scale);
2965 end;
2966 end;
2967
2968 fGlyphInfoList.Add(Result);
2969 if fFontHeight > 0 then
2970 begin
2971 Result.paths := ScalePath(Result.paths, fScale);
2972 // text rendering is about twice as fast when excess detail is removed
2973 Result.paths := StripNearDuplicates(Result.paths, minLength, true);
2974 end;
2975
2976 if fFlipVert then VerticalFlip(Result.paths);
2977 fSorted := false;
2978 end;
2979
2980 //------------------------------------------------------------------------------
2981 //------------------------------------------------------------------------------
2982
2983 function AppendSlash(const foldername: string): string;
2984 begin
2985 Result := foldername;
2986 if (Result = '') or (Result[Length(Result)] = '\') then Exit;
2987 Result := Result + '\';
2988 end;
2989 //------------------------------------------------------------------------------
2990
2991 {$IFDEF MSWINDOWS}
2992
2993 procedure FontHeightToFontSize(var logFontHeight: integer);
2994 const
2995 _72Div96 = 72/96;
2996 begin
2997 if logFontHeight < 0 then
2998 logFontHeight := -Round(logFontHeight * _72Div96 / dpiAware1);
2999 end;
3000 //------------------------------------------------------------------------------
3001
3002 procedure FontSizeToFontHeight(var logFontHeight: integer);
3003 const
3004 _96Div72 = 96/72;
3005 begin
3006 if logFontHeight > 0 then
3007 logFontHeight := -Round(DpiAware(logFontHeight * _96Div72));
3008 end;
3009 //------------------------------------------------------------------------------
3010
3011 function GetFontPixelHeight(logFontHeight: integer): double;
3012 const
3013 _96Div72 = 96/72;
3014 begin
3015 if logFontHeight > 0 then
3016 Result := DPIAware(logFontHeight * _96Div72) else
3017 Result := DPIAware(-logFontHeight);
3018 end;
3019 //------------------------------------------------------------------------------
3020
3021 function GetFontFolder: string;
3022 var
3023 pidl: PItemIDList;
3024 path: array[0..MAX_PATH] of char;
3025 begin
3026 SHGetSpecialFolderLocation(0, CSIDL_FONTS, pidl);
3027 SHGetPathFromIDList(pidl, path);
3028 CoTaskMemFree(pidl);
3029 result := path;
3030 end;
3031 //------------------------------------------------------------------------------
3032
3033 function GetInstalledTtfFilenames: TArrayOfString;
3034 var
3035 cnt, buffLen: integer;
3036 fontFolder: string;
3037 sr: TSearchRec;
3038 res: integer;
3039 begin
3040 cnt := 0; buffLen := 1024;
3041 SetLength(Result, buffLen);
3042 fontFolder := AppendSlash(GetFontFolder);
3043 res := FindFirst(fontFolder + '*.ttf', faAnyFile, sr);
3044 while res = 0 do
3045 begin
3046 if cnt = buffLen then
3047 begin
3048 inc(buffLen, 128);
3049 SetLength(Result, buffLen);
3050 end;
3051 Result[cnt] := fontFolder + sr.Name;
3052 inc(cnt);
3053 res := FindNext(sr);
3054 end;
3055 FindClose(sr);
3056 SetLength(Result, cnt);
3057 end;
3058 //------------------------------------------------------------------------------
3059
3060 function EnumFontProc(LogFont: PEnumLogFontEx; TextMetric: PNewTextMetric;
3061 FontType: DWORD; userDefined: LPARAM): Integer; stdcall;
3062 var
3063 len: integer;
3064 alf: PArrayOfEnumLogFontEx absolute userDefined;
3065 begin
3066 if (FontType = TRUETYPE_FONTTYPE) then
3067 begin
3068 len := Length(alf^);
3069 SetLength(alf^, len +1);
3070 Move(LogFont^, alf^[len], SizeOf(TEnumLogFontEx));
3071 end;
3072 Result := 1;
3073 end;
3074 //------------------------------------------------------------------------------
3075
3076 function GetLogFonts(const faceName: string; charSet: byte): TArrayOfEnumLogFontEx;
3077 var
3078 lf: TLogFont;
3079 dc: HDC;
3080 begin
3081 Result := nil;
3082 if faceName = '' then Exit;
3083 FillChar(lf, sizeof(lf), 0);
3084 lf.lfCharSet := charSet;
3085 Move(faceName[1], lf.lfFaceName[0], Length(faceName) * SizeOf(Char));
3086 dc := CreateCompatibleDC(0);
3087 try
3088 EnumFontFamiliesEx(dc, lf, @EnumFontProc, LParam(@Result), 0);
3089 finally
3090 DeleteDC(dc);
3091 end;
3092 end;
3093 //------------------------------------------------------------------------------
3094
3095 function GetLogFontFromEnumThatMatchesStyles(LogFonts: TArrayOfEnumLogFontEx;
3096 styles: TMacStyles; out logFont: TLogFont): Boolean;
3097 var
3098 i: integer;
3099 styles2: TMacStyles;
3100 begin
3101 Result := False;
3102 if not Assigned(LogFonts) then Exit;
3103 for i := 0 to High(LogFonts) do
3104 begin
3105 styles2 := [];
3106 if LogFonts[i].elfLogFont.lfWeight > 500 then Include(styles2, msBold);
3107 if LogFonts[i].elfLogFont.lfItalic <> 0 then Include(styles2, msItalic);
3108 if styles <> styles2 then Continue;
3109 logFont := LogFonts[i].elfLogFont;
3110 Result := true;
3111 Exit;
3112 end;
3113 end;
3114 //------------------------------------------------------------------------------
3115 {$ENDIF}
3116
3117 //------------------------------------------------------------------------------
3118 //------------------------------------------------------------------------------
3119
3120 function DrawText(image: TImage32; x, y: double; const text: UnicodeString;
3121 font: TFontCache; textColor: TColor32 = clBlack32): double;
3122 var
3123 glyphs: TPathsD;
3124 begin
3125 Result := 0;
3126 if (text = '') or not assigned(font) or not font.IsValidFont then Exit;
3127 glyphs := font.GetTextOutline(x,y, text, Result);
3128 DrawPolygon(image, glyphs, frNonZero, textColor);
3129 end;
3130 //------------------------------------------------------------------------------
3131
3132 function DrawText(image: TImage32; x, y: double; const text: UnicodeString;
3133 font: TFontCache; renderer: TCustomRenderer): double;
3134 var
3135 glyphs: TPathsD;
3136 begin
3137 Result := 0;
3138 if (text = '') or not assigned(font) or
3139 not font.IsValidFont then Exit;
3140 glyphs := font.GetTextOutline(x,y, text, Result);
3141 DrawPolygon(image, glyphs, frNonZero, renderer);
3142 end;
3143 //------------------------------------------------------------------------------
3144
3145 procedure DrawText(image: TImage32; const rec: TRectD;
3146 const text: UnicodeString; font: TFontCache;
3147 textColor: TColor32 = clBlack32; align: TTextAlign = taCenter;
3148 valign: TTextVAlign = tvaMiddle);
3149 var
3150 glyphs: TPathsD;
3151 dx,dy: double;
3152 rec2: TRectD;
3153 chunkedText: TChunkedText;
3154 begin
3155 if (text = '') or not assigned(font) or not font.IsValidFont then Exit;
3156 if align = taJustify then
3157 begin
3158 chunkedText := TChunkedText.Create(text, font, textColor);
3159 try
3160 chunkedText.DrawText( image, Rect(rec), taJustify, valign, 0);
3161 finally
3162 chunkedText.Free;
3163 end;
3164 Exit;
3165 end;
3166
3167 glyphs := font.GetTextOutline(0,0, text);
3168 rec2 := GetBoundsD(glyphs);
3169 case align of
3170 taRight: dx := rec.Right - rec2.Right;
3171 taCenter: dx := (rec.Left + rec.Right - rec2.Right) * 0.5;
3172 else dx := rec.Left;
3173 end;
3174 case valign of
3175 tvaMiddle: dy := (rec.Top + rec.Bottom - rec2.Top) * 0.5;
3176 tvaBottom: dy := rec.Bottom - rec2.Bottom;
3177 else dy := rec.Top + font.Ascent;
3178 end;
3179 glyphs := TranslatePath(glyphs, dx, dy);
3180 DrawPolygon(image, glyphs, frNonZero, textColor);
3181 end;
3182 //------------------------------------------------------------------------------
3183
3184 function DrawAngledText(image: TImage32;
3185 x, y: double; angleRadians: double;
3186 const text: UnicodeString; font: TFontCache;
3187 textColor: TColor32 = clBlack32): TPointD;
3188 var
3189 glyphs: TPathsD;
3190 rotatePt: TPointD;
3191 begin
3192 rotatePt := PointD(x,y);
3193 if not assigned(font) or not font.IsValidFont then
3194 begin
3195 Result := NullPointD;
3196 Exit;
3197 end;
3198 glyphs := font.GetAngledTextGlyphs(x, y,
3199 text, angleRadians, rotatePt, Result);
3200 DrawPolygon(image, glyphs, frNonZero, textColor);
3201 end;
3202 //------------------------------------------------------------------------------
3203
3204 procedure DrawVerticalText(image: TImage32; x, y: double;
3205 const text: UnicodeString; font: TFontCache;
3206 lineHeight: double; textColor: TColor32);
3207 var
3208 glyphs: TPathsD;
3209 cr: TCustomRenderer;
3210 begin
3211 if not assigned(font) or not font.IsValidFont or (text = '') then Exit;
3212 glyphs := font.GetVerticalTextOutline(x,y, text, lineHeight);
3213 if image.AntiAliased then
3214 cr := TColorRenderer.Create(textColor) else
3215 cr := TAliasedColorRenderer.Create(textColor);
3216 try
3217 DrawPolygon(image, glyphs, frNonZero, cr);
3218 finally
3219 cr.Free;
3220 end;
3221 end;
3222 //------------------------------------------------------------------------------
3223
3224 function FindLastSpace(const text: string; StartAt: integer): integer;
3225 begin
3226 Result := StartAt;
3227 while (Result > 0) and (text[Result] <> SPACE) do Dec(Result);
3228 end;
3229 //------------------------------------------------------------------------------
3230
3231 function GetTextOutlineOnPath(const text: UnicodeString;
3232 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
3233 x, y: double; charSpacing: double;
3234 out charsThatFit: integer; out outX: double): TPathsD;
3235 var
3236 pathLen, pathLenMin1: integer;
3237 cummDists: TArrayOfDouble; // cummulative distances
3238 i, currentPathIdx: integer;
3239 textWidth, glyphCenterX, glyphCenterOnPath, dist, dx: double;
3240 glyph: PGlyphInfo;
3241 CharOffsets: TArrayOfDouble;
3242 unitVector: TPointD;
3243 tmpPaths: TPathsD;
3244 begin
3245 Result := nil;
3246 pathLen := Length(path);
3247 pathLenMin1 := pathLen -1;
3248 charsThatFit := Length(text);
3249 if (pathLen < 2) or (charsThatFit = 0) then Exit;
3250
3251 CharOffsets := font.GetGlyphOffsets(text, charSpacing);
3252 textWidth := CharOffsets[charsThatFit];
3253 setLength(cummDists, pathLen +1);
3254 cummDists[0] := 0;
3255 dist := 0;
3256 for i:= 1 to pathLen -1 do
3257 begin
3258 dist := dist + Distance(path[i-1], path[i]);
3259 cummDists[i] := dist;
3260 end;
3261
3262 // truncate text that doesn't fit ...
3263 if textWidth > dist then
3264 begin
3265 Dec(charsThatFit);
3266 while CharOffsets[charsThatFit] > dist do Dec(charsThatFit);
3267 // if possible, break text at a SPACE char
3268 i := FindLastSpace(text, charsThatFit);
3269 if i > 0 then charsThatFit := i;
3270 end;
3271
3272 case textAlign of
3273 taCenter: x := (dist - textWidth) * 0.5;
3274 taRight : x := dist - textWidth;
3275 // else use user defined starting x
3276 end;
3277
3278 Result := nil;
3279 currentPathIdx := 0;
3280 for i := 1 to charsThatFit do
3281 begin
3282 glyph := font.GetGlyphInfo(Ord(text[i]));
3283 with glyph^ do
3284 glyphCenterX := (glyf.xMax - glyf.xMin) * font.Scale * 0.5;
3285 glyphCenterOnPath := x + glyphCenterX;
3286 while (currentPathIdx < pathLenMin1) and
3287 (cummDists[currentPathIdx +1] < glyphCenterOnPath) do
3288 inc(currentPathIdx);
3289 if currentPathIdx = pathLenMin1 then
3290 begin
3291 charsThatFit := i; // nb 1 base vs 0 base :)
3292 Break;
3293 end;
3294 x := x + glyph.hmtx.advanceWidth * font.Scale + charSpacing;
3295 unitVector := GetUnitVector(path[currentPathIdx], path[currentPathIdx +1]);
3296 tmpPaths := RotatePath(glyph.paths,
3297 PointD(glyphCenterX, -y), GetAngle(NullPointD, unitVector));
3298 dx := glyphCenterOnPath - cummDists[currentPathIdx];
3299 tmpPaths := TranslatePath(tmpPaths,
3300 path[currentPathIdx].X + unitVector.X * dx - glyphCenterX,
3301 path[currentPathIdx].Y + unitVector.Y * dx + y);
3302 AppendPath(Result, tmpPaths);
3303 end;
3304 outX := x;
3305 end;
3306 //------------------------------------------------------------------------------
3307
3308 function GetTextOutlineOnPath(const text: UnicodeString;
3309 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
3310 perpendicOffset: integer; charSpacing: double;
3311 out charsThatFit: integer): TPathsD;
3312 var
3313 dummy: double;
3314 begin
3315 Result := GetTextOutlineOnPath(text, path, font, textAlign,
3316 0, perpendicOffset, charSpacing, charsThatFit, dummy);
3317 end;
3318 //------------------------------------------------------------------------------
3319
3320 function GetTextOutlineOnPath(const text: UnicodeString;
3321 const path: TPathD; font: TFontCache; textAlign: TTextAlign;
3322 perpendicOffset: integer = 0; charSpacing: double = 0): TPathsD;
3323 var
3324 dummy: integer;
3325 begin
3326 Result := GetTextOutlineOnPath(text, path, font, textAlign,
3327 perpendicOffset, charSpacing, dummy);
3328 end;
3329 //------------------------------------------------------------------------------
3330
3331 function GetTextOutlineOnPath(const text: UnicodeString;
3332 const path: TPathD; font: TFontCache; x, y: integer;
3333 charSpacing: double; out outX: double): TPathsD;
3334 var
3335 dummy: integer;
3336 begin
3337 Result := GetTextOutlineOnPath(text, path, font, taLeft,
3338 x, y, charSpacing, dummy, outX);
3339 end;
3340
3341 //------------------------------------------------------------------------------
3342 // TTextChunk class
3343 //------------------------------------------------------------------------------
3344
3345 constructor TTextChunk.Create(owner: TChunkedText; const chunk: UnicodeString;
3346 index: integer; fontCache: TFontCache; fontColor, backColor: TColor32);
3347 var
3348 i, listCnt: integer;
3349 begin
3350 Self.owner := owner;
3351 listCnt := owner.fList.Count;
3352 if index < 0 then index := 0
3353 else if index > listCnt then index := listCnt;
3354
3355 self.index := index;
3356 self.text := chunk;
3357 self.fontColor := fontColor;
3358 self.backColor := backColor;
3359
3360 if Assigned(fontCache) then
3361 begin
3362 fontCache.GetTextOutlineInternal(0,0,
3363 chunk, 0, self.arrayOfPaths, self.glyphOffsets, self.width);
3364 self.height := fontCache.LineHeight;
3365 self.ascent := fontCache.Ascent;
3366 end else
3367 begin
3368 self.arrayOfPaths := nil;
3369 SetLength(self.glyphOffsets, 1);
3370 self.glyphOffsets[0] := 0;
3371 self.width := 0;
3372 self.height := 0;
3373 self.ascent := 0;
3374 end;
3375
3376 owner.fList.Insert(index, self);
3377 // reindex any trailing chunks
3378 if index < listCnt then
3379 for i := index +1 to listCnt do
3380 TTextChunk(owner.fList[i]).index := i;
3381 end;
3382
3383 //------------------------------------------------------------------------------
3384 // TChunkedText
3385 //------------------------------------------------------------------------------
3386
3387 constructor TChunkedText.Create;
3388 begin
3389 inherited;
3390 {$IFDEF XPLAT_GENERICS}
3391 fList := TList<TTextChunk>.Create;
3392 {$ELSE}
3393 fList := TList.Create;
3394 {$ENDIF}
3395 end;
3396 //------------------------------------------------------------------------------
3397
3398 constructor TChunkedText.Create(const text: string; font: TFontCache;
3399 fontColor: TColor32; backColor: TColor32);
3400 begin
3401 Create;
3402 SetText(text, font, fontColor, backColor);
3403 end;
3404 //------------------------------------------------------------------------------
3405
3406 destructor TChunkedText.Destroy;
3407 begin
3408 Clear;
3409 fList.Free;
3410 inherited;
3411 end;
3412 //------------------------------------------------------------------------------
3413
3414 function TChunkedText.GetChunk(index: integer): TTextChunk;
3415 begin
3416 if (index < 0) or (index >= fList.Count) then
3417 raise Exception.Create(rsChunkedTextRangeError);
3418 Result := TTextChunk(fList.Items[index]);
3419 end;
3420 //------------------------------------------------------------------------------
3421
3422 function TChunkedText.GetText: UnicodeString;
3423 var
3424 i: integer;
3425 begin
3426 Result := '';
3427 for i := 0 to Count -1 do
3428 Result := Result + TTextChunk(fList.Items[i]).text;
3429 end;
3430 //------------------------------------------------------------------------------
3431
3432 procedure TChunkedText.AddNewline(font: TFontCache);
3433 var
3434 nlChunk: TTextChunk;
3435 begin
3436 if not Assigned(font) or not font.IsValidFont then
3437 raise Exception.Create(rsChunkedTextFontError);
3438 if (fLastFont = font) then
3439 begin
3440 // this is much faster as it bypasses font.GetTextOutlineInternal
3441 nlChunk := InsertTextChunk(nil, MaxInt, #10, clNone32);
3442 nlChunk.height := fLastFont.LineHeight;
3443 nlChunk.ascent := fLastFont.Ascent;
3444 end else
3445 begin
3446 nlChunk := InsertTextChunk(font, MaxInt, SPACE, clNone32);
3447 nlChunk.text := #10;
3448 fSpaceWidth := nlChunk.width;
3449 fLastFont := font;
3450 end;
3451 end;
3452 //------------------------------------------------------------------------------
3453
3454 procedure TChunkedText.AddSpace(font: TFontCache);
3455 var
3456 spaceChunk: TTextChunk;
3457 begin
3458 if not Assigned(font) or not font.IsValidFont then
3459 raise Exception.Create(rsChunkedTextFontError);
3460 if (fLastFont = font) then
3461 begin
3462 // this is much faster as it bypasses font.GetTextOutlineInternal
3463 spaceChunk := InsertTextChunk(nil, MaxInt, SPACE, clNone32);
3464 spaceChunk.width := fSpaceWidth;
3465 spaceChunk.height := fLastFont.LineHeight;
3466 spaceChunk.ascent := fLastFont.Ascent;
3467 end else
3468 begin
3469 spaceChunk := InsertTextChunk(font, MaxInt, SPACE, clNone32);
3470 fLastFont := font;
3471 fSpaceWidth := spaceChunk.width;
3472 end;
3473 end;
3474 //------------------------------------------------------------------------------
3475
3476 function TChunkedText.AddTextChunk(font: TFontCache; const chunk: UnicodeString;
3477 fontColor: TColor32; backColor: TColor32): TTextChunk;
3478 begin
3479 Result := InsertTextChunk(font, MaxInt, chunk, fontColor, backColor);
3480 end;
3481 //------------------------------------------------------------------------------
3482
3483 function TChunkedText.InsertTextChunk(font: TFontCache; index: integer;
3484 const chunk: UnicodeString; fontColor: TColor32;
3485 backColor: TColor32): TTextChunk;
3486 begin
3487 Result := TTextChunk.Create(self, chunk, index, font, fontColor, backColor);
3488 end;
3489 //------------------------------------------------------------------------------
3490
3491 function TChunkedText.GetCount: integer;
3492 begin
3493 Result := fList.Count;
3494 end;
3495 //------------------------------------------------------------------------------
3496
3497 procedure TChunkedText.Clear;
3498 var
3499 i: integer;
3500 begin
3501 for i := 0 to fList.Count -1 do
3502 TTextChunk(fList.Items[i]).Free;
3503 fList.Clear;
3504 end;
3505 //------------------------------------------------------------------------------
3506
3507 procedure TChunkedText.DeleteChunk(Index: Integer);
3508 var
3509 i: integer;
3510 begin
3511 if (index < 0) or (index >= fList.Count) then
3512 raise Exception.Create(rsChunkedTextRangeError);
3513 TTextChunk(fList.Items[index]).Free;
3514 fList.Delete(index);
3515 // reindex
3516 for i := Index to fList.Count -1 do
3517 dec(TTextChunk(fList.Items[i]).index);
3518 end;
3519 //------------------------------------------------------------------------------
3520
3521 procedure TChunkedText.DeleteChunkRange(startIdx, endIdx: Integer);
3522 var
3523 i, cnt: Integer;
3524 begin
3525 cnt := endIdx - startIdx +1;
3526 if (startIdx < 0) or (endIdx >= fList.Count) or (cnt <= 0) then
3527 raise Exception.Create(rsChunkedTextRangeError);
3528
3529 for i := startIdx to endIdx do
3530 TTextChunk(fList.Items[i]).Free;
3531 // reindex
3532 for i := startIdx to fList.Count -1 do
3533 dec(TTextChunk(fList.Items[i]).index, cnt);
3534 end;
3535 //------------------------------------------------------------------------------
3536
3537 procedure TChunkedText.SetText(const text: UnicodeString;
3538 font: TFontCache; fontColor: TColor32; backColor: TColor32);
3539 var
3540 len: integer;
3541 p, p2, pEnd: PWideChar;
3542 s: UnicodeString;
3543 begin
3544 if not Assigned(font) then Exit;
3545
3546 Clear;
3547 p := PWideChar(text);
3548 pEnd := p;
3549 Inc(pEnd, Length(text));
3550 while p < pEnd do
3551 begin
3552 if (p^ <= SPACE) then
3553 begin
3554 if (p^ = SPACE) then AddSpace(font)
3555 else if (p^ = #10) then AddNewline(font);
3556 inc(p);
3557 end else
3558 begin
3559 p2 := p;
3560 inc(p);
3561 while (p < pEnd) and (p^ > SPACE) do inc(p);
3562 len := p - p2;
3563 SetLength(s, len);
3564 Move(p2^, s[1], len * SizeOf(Char));
3565 AddTextChunk(font, s, fontColor, backColor);
3566 end;
3567 end;
3568 end;
3569 //------------------------------------------------------------------------------
3570
3571 function TChunkedText.GetPageMetrics(const rec: TRect; lineHeight: double;
3572 startingChunkIdx: integer): TPageTextMetrics;
3573 var
3574 pageWidth, pageHeight : integer;
3575 lh, priorSplitWidth : double;
3576 currentX : double;
3577 arrayCnt, arrayCap : integer;
3578 chunkIdxAtStartOfLine : integer;
3579 currentChunkIdx : integer;
3580 linesFinished : Boolean;
3581
3582 procedure SetResultLength(len: integer);
3583 begin
3584 SetLength(Result.startOfLineIdx, len);
3585 SetLength(Result.justifyDeltas, len);
3586 SetLength(Result.lineWidths, len);
3587 end;
3588
3589 procedure CheckArrayCap;
3590 begin
3591 if arrayCnt < arrayCap then Exit;
3592 inc(arrayCap, 16);
3593 SetResultLength(arrayCap);
3594 end;
3595
3596 function IsRoomForCurrentLine: Boolean;
3597 begin
3598 Result := (arrayCnt + 1) * lh <= pageHeight;
3599 end;
3600
3601 function CheckLineHeight(currentChunk: TTextChunk): Boolean;
3602 begin
3603 // unless a user-defined lineHeight has been assigned (lineHeight > 0),
3604 // get the largest lineHeight of all displayed chunks and use that
3605 // lineHeight for *every* line that's being displayed ...
3606 if (lineHeight = 0) and (currentChunk.height > lh) then
3607 begin
3608 // first make sure that this chunk will fit
3609 Result := (arrayCnt + 1) * currentChunk.height <= pageHeight;
3610 if Result then lh := currentChunk.height;
3611 end else
3612 Result := IsRoomForCurrentLine;
3613 end;
3614
3615 procedure AddLine;
3616 var
3617 i, spcCnt, ChunkIdxAtEndOfLine: integer;
3618 x: double;
3619 chnk: TTextChunk;
3620 begin
3621 CheckArrayCap;
3622 ChunkIdxAtEndOfLine := currentChunkIdx -1;
3623 // ignore spaces at the end of lines
3624 while (ChunkIdxAtEndOfLine > chunkIdxAtStartOfLine) and
3625 (Chunk[ChunkIdxAtEndOfLine].text = SPACE) do
3626 Dec(ChunkIdxAtEndOfLine);
3627
3628 x := -priorSplitWidth; spcCnt := 0;
3629 for i := chunkIdxAtStartOfLine to ChunkIdxAtEndOfLine do
3630 begin
3631 chnk := Chunk[i];
3632 if chnk.text = SPACE then inc(spcCnt);
3633 x := x + chnk.width;
3634 end;
3635 Result.lineWidths[arrayCnt] := x;
3636 Result.lineHeight := lh;
3637 Result.startOfLineIdx[arrayCnt] := chunkIdxAtStartOfLine;
3638 if spcCnt = 0 then
3639 Result.justifyDeltas[arrayCnt] := 0 else
3640 Result.justifyDeltas[arrayCnt] := (pageWidth - x)/spcCnt;
3641 inc(arrayCnt);
3642 chunkIdxAtStartOfLine := currentChunkIdx;
3643 currentX := 0;
3644 priorSplitWidth := 0;
3645 end;
3646
3647 procedure AddSplitChunkLines(glyphOffset: integer);
3648 var
3649 highI: integer;
3650 residualWidth: double;
3651 chnk: TTextChunk;
3652 begin
3653 chnk := Chunk[chunkIdxAtStartOfLine];
3654 priorSplitWidth := chnk.glyphOffsets[glyphOffset];
3655 highI := High(chnk.glyphOffsets);
3656 residualWidth := chnk.width - priorSplitWidth;
3657 while (highI >= glyphOffset) and (residualWidth > pageWidth) do
3658 begin
3659 residualWidth := chnk.glyphOffsets[highI] - priorSplitWidth;
3660 Dec(highI);
3661 end;
3662
3663 if highI < glyphOffset then
3664 begin
3665 // oops, even a single character won't fit !!
3666 linesFinished := true;
3667 currentChunkIdx := chunkIdxAtStartOfLine;
3668 end
3669 else if not IsRoomForCurrentLine then
3670 begin
3671 linesFinished := true;
3672 currentChunkIdx := chunkIdxAtStartOfLine;
3673 end
3674 else
3675 begin
3676 CheckArrayCap;
3677 Result.lineWidths[arrayCnt] := residualWidth;
3678 Result.lineHeight := lh;
3679 Result.startOfLineIdx[arrayCnt] := chunkIdxAtStartOfLine;
3680 Result.justifyDeltas[arrayCnt] := 0;
3681 if (highI = High(chnk.glyphOffsets)) then
3682 begin
3683 currentX := residualWidth;
3684 inc(currentChunkIdx);
3685 end else
3686 begin
3687 inc(arrayCnt);
3688 AddSplitChunkLines(highI +1); // note recursion
3689 end;
3690 end;
3691 end;
3692
3693 var
3694 chnk: TTextChunk;
3695 begin
3696 FillChar(Result, SizeOf(Result), 0);
3697 arrayCnt := 0; arrayCap := 0;
3698 if (startingChunkIdx < 0) then startingChunkIdx := 0;
3699 if (Count = 0) or (startingChunkIdx >= Count) then Exit;
3700
3701 lh := lineHeight;
3702 RectWidthHeight(rec, pageWidth, pageHeight);
3703 currentChunkIdx := startingChunkIdx;
3704 chunkIdxAtStartOfLine := startingChunkIdx;
3705 currentX := 0;
3706 priorSplitWidth := 0;
3707 linesFinished := false;
3708 while (currentChunkIdx < Count) do
3709 begin
3710 chnk := Chunk[currentChunkIdx];
3711 if not CheckLineHeight(chnk) then break;
3712
3713 if (chnk.text = #10) then
3714 begin
3715 AddLine;
3716 if arrayCnt > 0 then
3717 Result.justifyDeltas[arrayCnt-1] := 0;
3718 inc(currentChunkIdx);
3719 chunkIdxAtStartOfLine := currentChunkIdx;
3720 end
3721 else if (currentX + chnk.width > pageWidth) then
3722 begin
3723 if (currentChunkIdx = chunkIdxAtStartOfLine) then
3724 begin
3725 // a single chunk is too wide for 'pageWidth'
3726 AddSplitChunkLines(0);
3727 if linesFinished or (currentChunkIdx = Count) then Break;
3728 end else
3729 begin
3730 AddLine;
3731 // don't allow spaces to wrap to the front of the following line
3732 while (currentChunkIdx < Count) and
3733 (self.chunk[currentChunkIdx].text = SPACE) do
3734 inc(currentChunkIdx);
3735 chunkIdxAtStartOfLine := currentChunkIdx;
3736 end;
3737 end else
3738 begin
3739 currentX := currentX + chnk.width;
3740 inc(currentChunkIdx);
3741 end;
3742 end;
3743
3744 if not linesFinished and
3745 (currentChunkIdx > chunkIdxAtStartOfLine) then AddLine;
3746 Result.lineCount := arrayCnt;
3747 SetResultLength(arrayCnt);
3748 Result.nextChuckIdx := currentChunkIdx;
3749 if (arrayCnt > 0) and (Result.nextChuckIdx = Count) then
3750 Result.justifyDeltas[arrayCnt-1] := 0;
3751 end;
3752 //------------------------------------------------------------------------------
3753
3754 function TChunkedText.GetChunkAndGlyphOffsetAtPt(const ptm: TPageTextMetrics;
3755 const pt: TPoint; out glyphIdx, chunkChrOff: integer): Boolean;
3756 var
3757 x,y, maxY, maxIdx: integer;
3758 x2 : Double;
3759 chnk: TTextChunk;
3760 begin
3761 Result := false;
3762 x := pt.X - ptm.bounds.Left;
3763 y := Trunc((pt.Y - ptm.bounds.Top - ptm.topLinePxOffset) / ptm.lineHeight);
3764 maxY := ptm.lineCount -1;
3765
3766 if (x < 0) or (x > ptm.bounds.right - ptm.bounds.Left) or
3767 (y < 0) or (y > maxY) then Exit;
3768
3769 if y = maxY then
3770 maxIdx := ptm.nextChuckIdx -1 else
3771 maxIdx := ptm.startOfLineIdx[y +1] -1;
3772
3773 glyphIdx := ptm.startOfLineIdx[y];
3774 chunkChrOff := 0;
3775 x2 := x;
3776
3777 // get chunkIdx within line 'y' ...
3778 while (glyphIdx < maxIdx) do
3779 begin
3780 if Chunk[glyphIdx].text = space then
3781 begin
3782 if x2 < Chunk[glyphIdx].width + ptm.justifyDeltas[y] then Break;
3783 x2 := x2 - Chunk[glyphIdx].width - ptm.justifyDeltas[y];
3784 end else
3785 begin
3786 if x2 < Chunk[glyphIdx].width then Break;
3787 x2 := x2 - Chunk[glyphIdx].width;
3788 end;
3789 inc(glyphIdx);
3790 end;
3791
3792 // get chunkChrOffset within Chunk[chunkIdx] ...
3793 chnk := Chunk[glyphIdx];
3794 while x2 >= chnk.glyphOffsets[chunkChrOff +1] do Inc(chunkChrOff);
3795 Result := true;
3796 end;
3797 //------------------------------------------------------------------------------
3798
3799 function TChunkedText.GetGlyphsOrDrawInternal(image: TImage32; const rec: TRect;
3800 textAlign: TTextAlign; textAlignV: TTextVAlign; startChunk: integer;
3801 lineHeight: double; out paths: TPathsD): TPageTextMetrics;
3802 var
3803 i,j, highJ,k, recWidth, recHeight: integer;
3804 a,b, chrIdx, lastLine: integer;
3805 x,y, totalHeight, lineWidth, spcDx: double;
3806 consumedWidth: double;
3807 pp: TPathsD;
3808 top: double;
3809 chnk: TTextChunk;
3810 begin
3811 paths := nil;
3812 FillChar(Result, SizeOf(Result), 0);
3813 Result.nextChuckIdx := startChunk;
3814 if Count = 0 then Exit;
3815
3816 RectWidthHeight(rec, recWidth, recHeight);
3817
3818 // LINE HEIGHTS ...............
3819 // Getting lineheights based on a given font's ascent and descent values
3820 // works well only when a single font is used. Unfortunately, when using
3821 // multiple fonts, line spacing becomes uneven and looks ugly.
3822 // An alternative approach is to measure the highest and lowest bounds of all
3823 // the glyphs in a line, and use these and a fixed inter line space
3824 // to derive variable line heights. But this approach also has problems,
3825 // especially when lines contain no glyphs, or when they only contain glyphs
3826 // with minimal heights (----------). So this too can look ugly.
3827 // A third approach, is to get the maximum of every lines' height and use
3828 // that value for every line. But this approach tends to produce undesirably
3829 // large line heights.
3830 // A fourth approach is to use the height of the very first text chunk.
3831 // And a final approach ia simply to use a user defined line height
3832
3833 if lineHeight = 0 then
3834 lineHeight := Chunk[0].height;
3835 Result := GetPageMetrics(rec, lineHeight, startChunk);
3836 if (Result.lineCount = 0) or (lineHeight > recHeight) then Exit;
3837
3838 // only return glyphs for visible lines
3839 totalHeight := lineHeight * Result.lineCount;
3840
3841 i := Result.startOfLineIdx[0];
3842 top := rec.Top + Chunk[i].ascent;
3843
3844 case textAlignV of
3845 tvaMiddle: y := top + (RecHeight - totalHeight) /2 -1;
3846 tvaBottom: y := rec.bottom - totalHeight + Chunk[i].ascent;
3847 else y := top;
3848 end;
3849
3850 Result.bounds := rec;
3851 Result.topLinePxOffset := Round(y - top);
3852 chrIdx := 0;
3853 lastLine := Result.lineCount -1;
3854 for i := 0 to lastLine do
3855 begin
3856 a := Result.startOfLineIdx[i];
3857 if i = lastLine then
3858 begin
3859 if (chunk[a].width - chunk[a].glyphOffsets[chrIdx] > recWidth) then
3860 b := a -1 // flag getting glyphs for a partial chunk
3861 else if Result.nextChuckIdx = 0 then
3862 b := Count -1
3863 else
3864 b := Result.nextChuckIdx -1;
3865 end else
3866 b := Result.startOfLineIdx[i+1] -1;
3867
3868 if textAlign = taJustify then
3869 spcDx := Result.justifyDeltas[i] else
3870 spcDx := 0;
3871 lineWidth := Result.lineWidths[i];
3872
3873 if (b < a) then
3874 begin
3875 // chunk[a] width exceeds recWidth
3876 chnk := chunk[a];
3877 consumedWidth := chnk.glyphOffsets[chrIdx];
3878 highJ := High(chnk.glyphOffsets);
3879 j := chrIdx;
3880 while (j < highJ) and
3881 (chnk.glyphOffsets[j+1] -consumedWidth < lineWidth) do inc(j);
3882 pp := nil;
3883 for k := chrIdx to j do
3884 AppendPath(pp, chnk.arrayOfPaths[k]);
3885 pp := TranslatePath(pp, rec.Left - consumedWidth, y);
3886 chnk.left := rec.Left;
3887 chnk.top := y - chnk.ascent;
3888
3889 if Assigned(image) then
3890 begin
3891 if Assigned(fDrawChunkEvent) then
3892 fDrawChunkEvent(chnk, RectD(rec.Left, chnk.top,
3893 rec.Left + consumedWidth, chnk.top + chnk.height));
3894
3895 DrawPolygon(image, pp, frNonZero, chnk.fontColor);
3896 end else
3897 AppendPath(paths, pp);
3898
3899 y := y + lineHeight;
3900 chrIdx := j +1;
3901 Continue;
3902 end
3903 else if chrIdx > 0 then
3904 begin
3905 // finish the partially processed chunk before continuing to next one
3906 chnk := chunk[a];
3907 highJ := High(chnk.glyphOffsets);
3908 consumedWidth := chnk.glyphOffsets[chrIdx];
3909 j := chrIdx;
3910 while (j < highJ) and
3911 (chnk.glyphOffsets[j+1] -consumedWidth < lineWidth) do inc(j);
3912 pp := nil;
3913 for k := chrIdx to j do
3914 AppendPath(pp, chnk.arrayOfPaths[k]);
3915 pp := TranslatePath(pp, rec.Left - consumedWidth, y);
3916
3917 if Assigned(image) then
3918 DrawPolygon(image, pp, frNonZero, chnk.fontColor) else
3919 AppendPath(paths, pp);
3920
3921 if (j = chrIdx) and (j < highJ) then
3922 break // oops, even a character is too wide for 'rec' !
3923 else if j < HighJ then
3924 begin
3925 chrIdx := j;
3926 Continue;
3927 end else
3928 begin
3929 chrIdx := 0;
3930 x := rec.Left + chnk.width - consumedWidth;
3931 inc(a);
3932 end;
3933 end else
3934 begin
3935 case textAlign of
3936 taRight : x := rec.Left + (recWidth - lineWidth);
3937 taCenter : x := rec.Left + (recWidth - lineWidth) / 2;
3938 else x := rec.Left;
3939 end;
3940 end;
3941
3942 // ignore trailing spaces
3943 while (b >= a) do
3944 if Chunk[b].text <= SPACE then
3945 dec(b) else
3946 break;
3947
3948 for j := a to b do
3949 begin
3950 chnk := GetChunk(j);
3951 chnk.left := x;
3952 chnk.top := y - chnk.ascent;
3953
3954 if chnk.text > SPACE then
3955 begin
3956 pp := MergeArrayOfPathsEx(chnk.arrayOfPaths, x, y);
3957
3958 if Assigned(image) then
3959 begin
3960 if (GetAlpha(chnk.backColor) > 0) then
3961 image.FillRect(Img32.Vector.Rect(RectD(x, chnk.top,
3962 x + chnk.width, chnk.top + chnk.height)), chnk.backColor);
3963
3964 if Assigned(fDrawChunkEvent) then
3965 fDrawChunkEvent(chnk, RectD(x, chnk.top,
3966 x + chnk.width, chnk.top + chnk.height));
3967
3968 DrawPolygon(image, pp, frNonZero, chnk.fontColor);
3969 end else
3970 AppendPath(paths, pp);
3971
3972 x := x + chnk.width;
3973 end else
3974 begin
3975 if (GetAlpha(chnk.backColor) > 0) then
3976 image.FillRect(Img32.Vector.Rect(RectD(x, chnk.top,
3977 x + chnk.width + spcDx, chnk.top + chnk.height)),
3978 chnk.backColor);
3979
3980 if Assigned(image) and Assigned(fDrawChunkEvent) then
3981 fDrawChunkEvent(chnk, RectD(x, chnk.top,
3982 x + chnk.width + spcDx, chnk.top + chnk.height));
3983
3984 x := x + chnk.width + spcDx;
3985 end;
3986 end;
3987 y := y + lineHeight;
3988 end;
3989 end;
3990 //------------------------------------------------------------------------------
3991
3992 function TChunkedText.DrawText(image: TImage32; const rec: TRect;
3993 textAlign: TTextAlign; textAlignV: TTextVAlign;
3994 startChunk: integer; lineHeight: double): TPageTextMetrics;
3995 var
3996 dummy: TPathsD;
3997 begin
3998 Result := GetGlyphsOrDrawInternal(image,
3999 rec, textAlign, textAlignV, startChunk, lineHeight, dummy);
4000 end;
4001 //------------------------------------------------------------------------------
4002
4003 function TChunkedText.GetTextGlyphs(const rec: TRect;
4004 textAlign: TTextAlign; textAlignV: TTextVAlign; startChunk: integer;
4005 lineHeight: double = 0.0): TPathsD;
4006 begin
4007 GetGlyphsOrDrawInternal(nil, rec, textAlign, textAlignV,
4008 startChunk, lineHeight, Result);
4009 end;
4010 //------------------------------------------------------------------------------
4011
4012 procedure TChunkedText.ApplyNewFont(font: TFontCache);
4013 var
4014 i: integer;
4015 begin
4016 if not Assigned(font) then Exit;
4017 for i := 0 to Count -1 do
4018 with Chunk[i] do
4019 begin
4020 font.GetTextOutlineInternal(0,0,
4021 text, 0, arrayOfPaths, glyphOffsets, width);
4022 height := font.LineHeight;
4023 ascent := font.Ascent;
4024 end;
4025 end;
4026
4027 //------------------------------------------------------------------------------
4028 // TFontManager
4029 //------------------------------------------------------------------------------
4030
4031 constructor TFontManager.Create;
4032 begin
4033 fMaxFonts := 32;
4034 {$IFDEF XPLAT_GENERICS}
4035 fFontList := TList<TFontReader>.Create;
4036 {$ELSE}
4037 fFontList:= TList.Create;
4038 {$ENDIF}
4039 end;
4040 //------------------------------------------------------------------------------
4041
4042 destructor TFontManager.Destroy;
4043 begin
4044 Clear;
4045 fFontList.Free;
4046 inherited;
4047 end;
4048 //------------------------------------------------------------------------------
4049
4050 procedure TFontManager.Clear;
4051 var
4052 i: integer;
4053 begin
4054 for i := 0 to fFontList.Count -1 do
4055 with TFontReader(fFontList[i]) do
4056 begin
4057 fFontManager := nil;
4058 Free;
4059 end;
4060 fFontList.Clear;
4061 end;
4062 //------------------------------------------------------------------------------
4063
4064 function TFontManager.FindDuplicate(fr: TFontReader): integer;
4065 var
4066 fi, fi2: TFontInfo;
4067 begin
4068 fi := fr.FontInfo;
4069 for Result := 0 to fFontList.Count -1 do
4070 begin
4071 fi2 := TFontReader(fFontList[Result]).FontInfo;
4072 if SameText(fi.fullFaceName, fi2.fullFaceName) and
4073 (fi.macStyles = fi2.macStyles) then Exit;
4074 end;
4075 Result := -1;
4076 end;
4077 //------------------------------------------------------------------------------
4078
4079 {$IFDEF MSWINDOWS}
4080 function TFontManager.LoadFontReaderFamily(const fontFamily: string): TLoadFontResult;
4081 var
4082 frf: TFontReaderFamily;
4083 begin
4084 Result := LoadFontReaderFamily(fontFamily, frf);
4085 end;
4086 //------------------------------------------------------------------------------
4087
4088 function TFontManager.LoadFontReaderFamily(const fontFamily: string;
4089 out fontReaderFamily: TFontReaderFamily): TLoadFontResult;
4090 var
4091 arrayEnumLogFont: TArrayOfEnumLogFontEx;
4092 lf: TLogFont;
4093 fontInfo: TFontInfo;
4094
4095 function FontInfoNamesAndSytlesMatch(const fontInfo1, fontInfo2: TFontInfo): Boolean;
4096 begin
4097 Result := (fontInfo1.faceName = fontInfo2.faceName) and
4098 (fontInfo1.macStyles = fontInfo2.macStyles);
4099 end;
4100
4101 begin
4102 Result := lfrInvalid;
4103 fontReaderFamily.regularFR := nil;
4104 fontReaderFamily.boldFR := nil;
4105 fontReaderFamily.italicFR := nil;
4106 fontReaderFamily.boldItalicFR := nil;
4107
4108 if (fontFamily = '') or (Length(fontFamily) > LF_FACESIZE) then Exit;
4109 arrayEnumLogFont := GetLogFonts(fontFamily, DEFAULT_CHARSET); //ANSI_CHARSET);
4110
4111 FillChar(lf, SizeOf(TLogFont), 0);
4112 Move(fontFamily[1], lf.lfFaceName[0], Length(fontFamily) * SizeOf(Char));
4113 if not GetLogFontFromEnumThatMatchesStyles(arrayEnumLogFont, [], lf) then Exit;
4114
4115 // make room for 4 new fontreaders
4116 while fFontList.Count > fMaxFonts - 4 do DeleteOldestFont;
4117
4118 fontReaderFamily.regularFR := TFontReader.Create;
4119 fontReaderFamily.regularFR.Load(lf);
4120
4121 Result := ValidateFontLoad(fontReaderFamily.regularFR);
4122 case Result of
4123 lfrInvalid: Exit;
4124 lfrDuplicate:
4125 begin
4126 fontInfo := fontReaderFamily.regularFR.FontInfo;
4127
4128 fontInfo.macStyles := [msBold];
4129 fontReaderFamily.boldFR := GetBestMatchFont(fontInfo);
4130 if not FontInfoNamesAndSytlesMatch(FontInfo,
4131 fontReaderFamily.boldFR.FontInfo) then
4132 fontReaderFamily.boldFR := nil;
4133
4134 fontInfo.macStyles := [msItalic];
4135 fontReaderFamily.italicFR := GetBestMatchFont(fontInfo);
4136 if not FontInfoNamesAndSytlesMatch(FontInfo,
4137 fontReaderFamily.italicFR.FontInfo) then
4138 fontReaderFamily.italicFR := nil;
4139
4140 fontInfo.macStyles := [msBold, msItalic];
4141 fontReaderFamily.boldItalicFR := GetBestMatchFont(fontInfo);
4142 if not FontInfoNamesAndSytlesMatch(FontInfo,
4143 fontReaderFamily.boldItalicFR.FontInfo) then
4144 fontReaderFamily.boldItalicFR := nil;
4145 end;
4146 else
4147 begin
4148 if GetLogFontFromEnumThatMatchesStyles(arrayEnumLogFont, [msBold], lf) then
4149 begin
4150 fontReaderFamily.boldFR := TFontReader.Create;
4151 fontReaderFamily.boldFR.Load(lf);
4152 ValidateFontLoad(fontReaderFamily.boldFR);
4153 end;
4154 if GetLogFontFromEnumThatMatchesStyles(arrayEnumLogFont, [msItalic], lf) then
4155 begin
4156 fontReaderFamily.italicFR := TFontReader.Create;
4157 fontReaderFamily.italicFR.Load(lf);
4158 ValidateFontLoad(fontReaderFamily.italicFR);
4159 end;
4160
4161 if GetLogFontFromEnumThatMatchesStyles(arrayEnumLogFont, [msBold, msItalic], lf) then
4162 begin
4163 fontReaderFamily.boldItalicFR := TFontReader.Create;
4164 fontReaderFamily.boldItalicFR.Load(lf);
4165 ValidateFontLoad(fontReaderFamily.boldItalicFR);
4166 end;
4167 end;
4168 end;
4169 end;
4170 //------------------------------------------------------------------------------
4171
4172 function TFontManager.LoadFontReader(const fontName: string): TFontReader;
4173 begin
4174 Result := nil;
4175 if (fontName = '') or (Length(fontName) > LF_FACESIZE) then Exit;
4176 if fFontList.Count >= fMaxFonts then DeleteOldestFont;
4177 Result := TFontReader.Create(fontName);
4178 ValidateFontLoad(Result);
4179 end;
4180 //------------------------------------------------------------------------------
4181 {$ENDIF}
4182
4183 function TFontManager.LoadFromStream(stream: TStream): TFontReader;
4184 begin
4185 if fFontList.Count >= fMaxFonts then DeleteOldestFont;
4186
4187 Result := TFontReader.Create;
4188 try
4189 if not Result.LoadFromStream(stream) then FreeAndNil(Result)
4190 else ValidateFontLoad(Result);
4191 except
4192 FreeAndNil(Result);
4193 end;
4194 end;
4195 //------------------------------------------------------------------------------
4196
4197 function TFontManager.LoadFromResource(const resName: string; resType: PChar): TFontReader;
4198 begin
4199 if fFontList.Count >= fMaxFonts then DeleteOldestFont;
4200
4201 Result := TFontReader.Create;
4202 try
4203 if not Result.LoadFromResource(resName, resType) then FreeAndNil(Result)
4204 else ValidateFontLoad(Result);
4205 except
4206 FreeAndNil(Result);
4207 end;
4208 end;
4209 //------------------------------------------------------------------------------
4210
4211 function TFontManager.LoadFromFile(const filename: string): TFontReader;
4212 begin
4213 if fFontList.Count >= fMaxFonts then DeleteOldestFont;
4214
4215 Result := TFontReader.Create;
4216 try
4217 if not Result.LoadFromFile(filename) then FreeAndNil(Result)
4218 else ValidateFontLoad(Result);
4219 except
4220 FreeAndNil(Result);
4221 end;
4222 end;
4223 //------------------------------------------------------------------------------
4224
4225 function TFontManager.ValidateFontLoad(var fr: TFontReader): TLoadFontResult;
4226 var
4227 dupIdx: integer;
4228 begin
4229 if not fr.IsValidFontFormat then
4230 begin
4231 FreeAndNil(fr);
4232 result := lfrInvalid;
4233 Exit;
4234 end;
4235 dupIdx := FindDuplicate(fr);
4236 if dupIdx >= 0 then
4237 begin
4238 FreeAndNil(fr);
4239 result := lfrDuplicate;
4240 fr := fFontList[dupIdx];
4241 end else
4242 begin
4243 Result := lfrSuccess;
4244 fFontList.Add(fr);
4245 fr.fFontManager := self;
4246 end;
4247 end;
4248 //------------------------------------------------------------------------------
4249
4250 function TFontManager.Delete(fontReader: TFontReader): Boolean;
4251 var
4252 i: integer;
4253 begin
4254 for i := 0 to fFontList.Count -1 do
4255 if TFontReader(fFontList[i]) = fontReader then
4256 begin
4257 // make sure the FontReader object isn't destroying itself externally
4258 if not fontReader.fDestroying then fontReader.Free;
4259 fFontList.Delete(i);
4260 Result := true;
4261 Exit;
4262 end;
4263 Result := false;
4264 end;
4265 //------------------------------------------------------------------------------
4266
4267 function StylesToInt(macstyles: TMacStyles): integer;
4268 {$IFDEF INLINE} inline; {$ENDIF}
4269 begin
4270 if msBold in macStyles then
4271 Result := 1 else Result := 0;
4272 if msItalic in macStyles then inc(Result, 2);
4273 end;
4274 //------------------------------------------------------------------------------
4275
4276 function FontFamilyToInt(family: TFontFamily): integer;
4277 {$IFDEF INLINE} inline; {$ENDIF}
4278 begin
4279 Result := Ord(family) +1;
4280 end;
4281 //------------------------------------------------------------------------------
4282
4283 function TFontManager.GetBestMatchFont(const fontInfo: TFontInfo): TFontReader;
4284
4285 function GetStyleDiff(const macstyles1, macstyles2: TMacStyles): integer;
4286 {$IFDEF INLINE} inline; {$ENDIF}
4287 begin
4288 // top priority
4289 Result := (((Byte(macstyles1) xor $FF) or
4290 (Byte(macstyles2) xor $FF)) and $3) * 256;
4291 end;
4292
4293 function GetFontFamilyDiff(const family1, family2: TFontFamily): integer;
4294 {$IFDEF INLINE} inline; {$ENDIF}
4295 begin
4296 // second priority
4297 if family1 = tfUnknown then
4298 Result := 0 else
4299 Result := Abs(FontFamilyToInt(family1) - FontFamilyToInt(family2)) * 8;
4300 end;
4301
4302 function GetShortNameDiff(const name1, name2: Utf8String): integer;
4303 {$IFDEF INLINE} inline; {$ENDIF}
4304 begin
4305 // third priority (shl 3)
4306 if name1 = '' then
4307 Result := 0 else
4308 if SameText(name1, name2) then Result := 0 else Result := 4;
4309 end;
4310
4311 function GetFullNameDiff(const fiToMatch: TFontInfo;
4312 const candidateName: Utf8String): integer;
4313 var
4314 i: integer;
4315 begin
4316 // lowest priority
4317 Result := 0;
4318 if Assigned(fiToMatch.familyNames) then
4319 begin
4320 for i := 0 to High(fiToMatch.familyNames) do
4321 if SameText(fiToMatch.familyNames[i], candidateName) then Exit;
4322 end
4323 else if SameText(fiToMatch.faceName, candidateName) then Exit;
4324 Result := 2;
4325 end;
4326
4327 function CompareFontInfos(const fiToMatch, fiCandidate: TFontInfo): integer;
4328 begin
4329 Result :=
4330 GetStyleDiff(fiToMatch.macStyles, fiCandidate.macStyles) +
4331 GetFontFamilyDiff(fiToMatch.family, fiCandidate.family) +
4332 GetShortNameDiff(fiToMatch.faceName, fiCandidate.faceName) +
4333 GetFullNameDiff(fiToMatch, fiCandidate.fullFaceName);
4334 end;
4335
4336 var
4337 i, bestDiff, currDiff: integer;
4338 fr: TFontReader;
4339 begin
4340 Result := nil;
4341 bestDiff := MaxInt;
4342 for i := 0 to fFontList.Count -1 do
4343 begin
4344 fr := TFontReader(fFontList[i]);
4345 currDiff := CompareFontInfos(fontInfo, fr.fFontInfo);
4346 if (currDiff < bestDiff) then
4347 begin
4348 Result := fr;
4349 if currDiff = 0 then Break; // can't do better :)
4350 bestDiff := currDiff;
4351 end;
4352 end;
4353 end;
4354 //------------------------------------------------------------------------------
4355
4356 function TFontManager.GetBestMatchFont(const styles: TMacStyles): TFontReader;
4357 var
4358 i, bestDiff, currDiff: integer;
4359 fr: TFontReader;
4360 begin
4361 Result := nil;
4362 bestDiff := MaxInt;
4363 for i := 0 to fFontList.Count -1 do
4364 begin
4365 fr := TFontReader(fFontList[i]);
4366 currDiff := (((Byte(styles) xor $FF) or (Byte(fr.fFontInfo.macStyles) xor $FF)) and $3);
4367 if (currDiff < bestDiff) then
4368 begin
4369 Result := fr;
4370 if currDiff = 0 then Break; // can't do any better :)
4371 bestDiff := currDiff;
4372 end;
4373 end;
4374 end;
4375 //------------------------------------------------------------------------------
4376
4377 function TFontManager.FindReaderContainingGlyph(codepoint: Cardinal;
4378 fntFamily: TFontFamily; out glyphIdx: WORD): TFontReader;
4379 var
4380 i: integer;
4381 reader: TFontReader;
4382 begin
4383 result := nil;
4384 for i := 0 to fFontList.Count -1 do
4385 begin
4386 reader := TFontReader(fFontList[i]);
4387 glyphIdx := reader.GetGlyphIdxUsingCmap(codepoint);
4388 // if a font family is specified, then only return true
4389 // when finding the glyph within that font family
4390 if (glyphIdx > 0) and ((fntFamily = tfUnknown) or
4391 (reader.FontFamily = tfUnknown) or (fntFamily = reader.FontFamily)) then
4392 begin
4393 Result := reader;
4394 Exit;
4395 end;
4396 end;
4397 glyphIdx := 0;
4398 end;
4399 //------------------------------------------------------------------------------
4400
4401 procedure TFontManager.SetMaxFonts(value: integer);
4402 begin
4403 if value < 0 then value := 0;
4404 if value <= 0 then Clear
4405 else while value > fFontList.Count do
4406 Delete(TFontReader(fFontList[0]));
4407 fMaxFonts := value;
4408 end;
4409 //------------------------------------------------------------------------------
4410
4411 function FontSorterProc(fontreader1, fontreader2: Pointer): integer;
4412 var
4413 fr1: TFontReader absolute fontreader1;
4414 fr2: TFontReader absolute fontreader2;
4415 begin
4416 if fr1.fLastUsedTime > fr2.fLastUsedTime then Result := -1
4417 else if fr1.fLastUsedTime < fr2.fLastUsedTime then Result := 1
4418 else Result := 0;
4419 end;
4420 //------------------------------------------------------------------------------
4421
4422 procedure TFontManager.SortFontListOnLastUse;
4423 begin
4424 {$IFDEF XPLAT_GENERICS}
4425 fFontList.Sort(TComparer<TFontReader>.Construct(
4426 function (const fr1, fr2: TFontReader): integer
4427 begin
4428 if fr1.fLastUsedTime > fr2.fLastUsedTime then Result := -1
4429 else if fr1.fLastUsedTime < fr2.fLastUsedTime then Result := 1
4430 else Result := 0;
4431 end));
4432 {$ELSE}
4433 fFontList.Sort(FontSorterProc);
4434 {$ENDIF}
4435 end;
4436 //------------------------------------------------------------------------------
4437
4438 procedure TFontManager.DeleteOldestFont;
4439 var
4440 cnt: integer;
4441 begin
4442 cnt := fFontList.Count;
4443 if cnt = 0 then Exit;
4444 SortFontListOnLastUse;
4445 TFontReader(fFontList[cnt -1]).Free;
4446 end;
4447 //------------------------------------------------------------------------------
4448
4449 //------------------------------------------------------------------------------
4450 //------------------------------------------------------------------------------
4451
4452 function FontManager: TFontManager;
4453 begin
4454 result := aFontManager;
4455 end;
4456 //------------------------------------------------------------------------------
4457
4458 initialization
4459 aFontManager := TFontManager.Create;
4460
4461 finalization
4462 aFontManager.Free;
4463
4464 end.