-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPascalType.Tables.OpenType.Lookup.pas
More file actions
1361 lines (1079 loc) · 49.7 KB
/
PascalType.Tables.OpenType.Lookup.pas
File metadata and controls
1361 lines (1079 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit PascalType.Tables.OpenType.Lookup;
////////////////////////////////////////////////////////////////////////////////
// //
// Version: MPL 1.1 or LGPL 2.1 with linking exception //
// //
// The contents of this file are subject to the Mozilla Public License //
// Version 1.1 (the "License"); you may not use this file except in //
// compliance with the License. You may obtain a copy of the License at //
// http://www.mozilla.org/MPL/ //
// //
// Software distributed under the License is distributed on an "AS IS" //
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the //
// License for the specific language governing rights and limitations under //
// the License. //
// //
// Alternatively, the contents of this file may be used under the terms of //
// the Free Pascal modified version of the GNU Lesser General Public //
// License Version 2.1 (the "FPC modified LGPL License"), in which case the //
// provisions of this license are applicable instead of those above. //
// Please see the file LICENSE.txt for additional information concerning //
// this license. //
// //
// The code is part of the PascalType Project //
// //
// The initial developer of this code is Christian-W. Budde //
// //
// Portions created by Christian-W. Budde are Copyright (C) 2010-2017 //
// by Christian-W. Budde. All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////////////
interface
{$I PT_Compiler.inc}
{-$define VerboseDebug}
uses
Generics.Collections,
Generics.Defaults,
System.Classes,
PascalType.Types,
PascalType.Classes,
PascalType.Tables,
PascalType.GlyphString,
PascalType.Tables.OpenType.Coverage,
PascalType.Tables.OpenType.ClassDefinition;
type
TContextPart = (cpBacktrack, cpInput, cpLookahead);
type
TCustomOpenTypeLookupTable = class;
TOpenTypeLookupListTable = class;
//------------------------------------------------------------------------------
//
// TCustomOpenTypeLookupSubTable
//
//------------------------------------------------------------------------------
// Base class for lookup table sub-formats
//------------------------------------------------------------------------------
TCustomOpenTypeLookupSubTable = class abstract(TCustomPascalTypeTable)
private type
TMatchOptions = TPascalTypeGlyphString.TMatchOptions;
protected type
TSequenceLookupRecord = record
SequenceIndex: Word;
LookupListIndex: Word;
end;
TSequenceLookupRecords = TArray<TSequenceLookupRecord>;
protected type
TCoverageTables = TList<TCustomOpenTypeCoverageTable>;
TContextCoverageTables = array[TContextPart] of TCoverageTables;
private
FSubFormat: Word;
function GetLookupTable: TCustomOpenTypeLookupTable;
protected
function ApplyLookupRecords(var AGlyphIterator: TPascalTypeGlyphIterator; ANextIndex: integer; const LookupRecords: TSequenceLookupRecords): boolean;
protected
function MatchCoverage(var AGlyphIterator: TPascalTypeGlyphIterator; ACoverageTables: TCoverageTables; out ALastMatchedIndex: integer; AOptions: TMatchOptions = []): boolean; overload;
function MatchCoverage(var AGlyphIterator: TPascalTypeGlyphIterator; ACoverageTables: TCoverageTables; AOptions: TMatchOptions = []): boolean; overload;
// Common handler for:
// - TOpenTypePositioningSubTableChainedContextCoverage.Apply
// - TOpenTypeSubstitutionSubTableChainedContextCoverage.Apply
function ApplyChainedContextCoverage(const ACoverageTables: TContextCoverageTables; const ASequenceRules: TSequenceLookupRecords; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
// Common handler for:
// - TOpenTypePositioningSubTableContextCoverage.Apply
// - TOpenTypeSubstitutionSubTableContextCoverage.Apply
function ApplyContextCoverage(const ACoverageTables: TCoverageTables; const ASequenceRules: TSequenceLookupRecords; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
public
constructor Create(AParent: TCustomPascalTypeTable); override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream; Size: Cardinal = 0); override;
procedure SaveToStream(Stream: TStream); override;
function Apply(var AGlyphIterator: TPascalTypeGlyphIterator): boolean; virtual; abstract;
property SubFormat: Word read FSubFormat;
property LookupTable: TCustomOpenTypeLookupTable read GetLookupTable;
end;
TOpenTypeLookupSubTableClass = class of TCustomOpenTypeLookupSubTable;
//------------------------------------------------------------------------------
//
// TCustomOpenTypeLookupTable
//
//------------------------------------------------------------------------------
// Common base class for GSUB/GPOS lookup tables
//------------------------------------------------------------------------------
// https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2#lookup-table
//------------------------------------------------------------------------------
TCustomOpenTypeLookupTable = class abstract(TCustomPascalTypeTable)
public const
RIGHT_TO_LEFT = $0001;
IGNORE_BASE_GLYPHS = $0002;
IGNORE_LIGATURES = $0004;
IGNORE_MARKS = $0008;
USE_MARK_FILTERING_SET = $0010;
MASK_RESERVED = $00E0;
MARK_ATTACHMENT_TYPE_MASK = $FF00;
MARK_ATTACHMENT_CLASS_FILTER = MARK_ATTACHMENT_TYPE_MASK; // The official name
private
FLookupType : Word; // Different enumerations for GSUB and GPOS
FLookupFlags : Word; // Lookup qualifiers
FMarkFilteringSet : Word; // Index (base 0) into GDEF mark glyph sets structure. This field is only present if bit UseMarkFilteringSet of lookup flags is set.
FSubTableList: TPascalTypeTableInterfaceList<TCustomOpenTypeLookupSubTable>;
protected
procedure SetLookupFlags(const Value: Word);
procedure SetMarkFilteringSet(const Value: Word);
function GetSubTable(Index: Integer): TCustomOpenTypeLookupSubTable;
function GetSubTableCount: Integer;
function GetLookupList: TOpenTypeLookupListTable;
procedure LookupFlagsChanged; virtual;
procedure MarkFilteringSetChanged; virtual;
function GetSubTableClass(ASubFormat: Word): TOpenTypeLookupSubTableClass; virtual; abstract;
function GetUseReverseDirection: boolean; virtual;
public
constructor Create(AParent: TCustomPascalTypeTable); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream; Size: Cardinal = 0); override;
procedure SaveToStream(Stream: TStream); override;
function GetEnumerator: TEnumerator<TCustomOpenTypeLookupSubTable>;
function Apply(var AGlyphIterator: TPascalTypeGlyphIterator): boolean; virtual;
// The meaning of LookupType depends on the parent type (GSUB/GPOS)
property LookupType: Word read FLookupType;
property LookupFlags: Word read FLookupFlags write SetLookupFlags;
property MarkFilteringSet: Word read FMarkFilteringSet write SetMarkFilteringSet;
// See: TCustomPascalTypeOpenTypeProcessor.ApplyLookups
property UseReverseDirection: boolean read GetUseReverseDirection;
property SubTableCount: Integer read GetSubTableCount;
property SubTables[Index: Integer]: TCustomOpenTypeLookupSubTable read GetSubTable; default;
property LookupList: TOpenTypeLookupListTable read GetLookupList;
end;
TOpenTypeLookupTableClass = class of TCustomOpenTypeLookupTable;
//------------------------------------------------------------------------------
//
// TCustomOpenTypeLookupSubTableWithCoverage
//
//------------------------------------------------------------------------------
// Base class for lookup table sub-formats with a coverage table (all except the
// Extension lookup type sub-table)
//------------------------------------------------------------------------------
TCustomOpenTypeLookupSubTableWithCoverage = class abstract(TCustomOpenTypeLookupSubTable)
protected type
TChainedSequenceRule = record
BacktrackSequence: TGlyphString;
InputSequence: TGlyphString;
LookaheadSequence: TGlyphString;
SequenceLookupRecords: TSequenceLookupRecords;
end;
TChainedSequenceRuleSet = TArray<TChainedSequenceRule>;
TChainedSequenceRuleSets = TArray<TChainedSequenceRuleSet>;
protected type
TSequenceRule = record
InputSequence: TGlyphString;
SequenceLookupRecords: TSequenceLookupRecords;
end;
TSequenceRuleSet = TArray<TSequenceRule>;
TSequenceRuleSets = TArray<TSequenceRuleSet>;
protected type
TClassDefinitions = array[TContextPart] of TCustomOpenTypeClassDefinitionTable;
private type
TGlyphMapperDelegate = TPascalTypeGlyphString.TGlyphMapperDelegate;
TMatchOptions = TPascalTypeGlyphString.TMatchOptions;
private
FCoverageTable: TCustomOpenTypeCoverageTable;
protected
procedure DoSaveToStream(Stream: TStream); virtual; abstract;
protected
// Common handler for:
// - TOpenTypePositioningSubTableChainedContextSimple.Apply
// - TOpenTypeSubstitutionSubTableChainedContextSimple.Apply
function ApplyChainedContextSimple(const ASequenceRules: TChainedSequenceRuleSets; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
// Common handler for:
// - TOpenTypePositioningSubTableChainedContextClass.Apply
// - TOpenTypeSubstitutionSubTableChainedContextClass.Apply
function ApplyChainedContextClass(const ASequenceRules: TChainedSequenceRuleSets; const AClassDefinitions: TClassDefinitions; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
// Common handler for:
// - TOpenTypePositioningSubTableContextSimple.Apply
// - TOpenTypeSubstitutionSubTableContextSimple.Apply
function ApplyContextSimple(const ASequenceRules: TSequenceRuleSets; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
// Common handler for:
// - TOpenTypePositioningSubTableContextClass.Apply
// - TOpenTypeSubstitutionSubTableContextClass.Apply
function ApplyContextClass(const ASequenceRules: TSequenceRuleSets; AClassDefinitions: TCustomOpenTypeClassDefinitionTable; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream; Size: Cardinal = 0); override;
procedure SaveToStream(Stream: TStream); reintroduce; override; // Prevent derived from overriding; They must go through DoSaveToStream
property CoverageTable: TCustomOpenTypeCoverageTable read FCoverageTable;
end;
//------------------------------------------------------------------------------
//
// TOpenTypeLookupListTable
//
//------------------------------------------------------------------------------
// Lookup list table
//------------------------------------------------------------------------------
// https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2#lookup-list-table
//------------------------------------------------------------------------------
TOpenTypeLookupListTable = class(TCustomPascalTypeTable)
private
FLookupList: TPascalTypeTableInterfaceList<TCustomOpenTypeLookupTable>;
function GetLookupTableCount: Integer;
function GetLookupTable(Index: Integer): TCustomOpenTypeLookupTable;
public
constructor Create(AParent: TCustomPascalTypeTable); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream; Size: Cardinal = 0); override;
procedure SaveToStream(Stream: TStream); override;
property LookupTableCount: Integer read GetLookupTableCount;
property LookupTables[Index: Integer]: TCustomOpenTypeLookupTable read GetLookupTable; default;
end;
//------------------------------------------------------------------------------
//
// TOpenTypeLookupTableGeneric
//
//------------------------------------------------------------------------------
// Generic placeholder for those lookup types that have no concrete implementation.
//------------------------------------------------------------------------------
type
TOpenTypeLookupTableGeneric = class(TCustomOpenTypeLookupTable)
private type
TOpenTypeLookupSubTableGeneric = class(TCustomOpenTypeLookupSubTable)
public
function Apply(var AGlyphIterator: TPascalTypeGlyphIterator): boolean; override;
end;
protected
function GetSubTableClass(ASubFormat: Word): TOpenTypeLookupSubTableClass; override;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
uses
System.SysUtils,
System.Math,
{$ifdef DEBUG}
WinApi.Windows,
{$endif DEBUG}
PascalType.ResourceStrings,
PascalType.Tables.OpenType.Common;
//------------------------------------------------------------------------------
//
// TCustomOpenTypeLookupTable
//
//------------------------------------------------------------------------------
constructor TCustomOpenTypeLookupTable.Create(AParent: TCustomPascalTypeTable);
begin
inherited Create(AParent); // Type check the parent
FSubTableList := TPascalTypeTableInterfaceList<TCustomOpenTypeLookupSubTable>.Create(Self);
end;
destructor TCustomOpenTypeLookupTable.Destroy;
begin
FreeAndNil(FSubTableList);
inherited;
end;
procedure TCustomOpenTypeLookupTable.Assign(Source: TPersistent);
begin
inherited;
if Source is TCustomOpenTypeLookupTable then
begin
Assert(FLookupType = TCustomOpenTypeLookupTable(Source).FLookupType);
FLookupFlags := TCustomOpenTypeLookupTable(Source).FLookupFlags;
FMarkFilteringSet := TCustomOpenTypeLookupTable(Source).FMarkFilteringSet;
FSubTableList.Assign(TCustomOpenTypeLookupTable(Source).FSubTableList);
end;
end;
procedure TCustomOpenTypeLookupTable.LoadFromStream(Stream: TStream; Size: Cardinal);
var
StartPos: Int64;
LookupPos: Int64;
IsExtension: boolean;
PosFormat: Word;
Offset: Cardinal;
i: integer;
SubTableType: Word;
SubTableOffsets: array of Word;
SubTable: TCustomOpenTypeLookupSubTable;
SubTableClass: TOpenTypeLookupSubTableClass;
begin
// +----------+-----------------------+--------------------------------------------+
// | Type | Name | Description |
// +==========+=======================+============================================+
// | uint16 | lookupType | Different enumerations for GSUB and GPOS. |
// +----------+-----------------------+--------------------------------------------+
// | uint16 | lookupFlag | Lookup qualifiers. |
// +----------+-----------------------+--------------------------------------------+
// | uint16 | subTableCount | Number of SubTable offsets. |
// +----------+-----------------------+--------------------------------------------+
// | Offset16 | subTableOffsets[count]| Array of offsets to SubTables. |
// +----------+-----------------------+--------------------------------------------+
// | uint16 | markFilteringSet | Index (for GDEF mark filtering sets). |
// +----------+-----------------------+--------------------------------------------+
StartPos := Stream.Position;
FLookupType := BigEndianValue.ReadWord(Stream);
IsExtension := TCustomOpenTypeCommonTable(Parent.Parent).IsExtensionLookupType(FLookupType);
FLookupFlags := BigEndianValue.ReadWord(Stream);
// Read subtable count
SetLength(SubTableOffsets, BigEndianValue.ReadWord(Stream));
// Read lookup list index offsets
for i := 0 to High(SubTableOffsets) do
SubTableOffsets[i] := BigEndianValue.ReadWord(Stream);
if (FLookupFlags and USE_MARK_FILTERING_SET <> 0) then
FMarkFilteringSet := BigEndianValue.ReadWord(Stream);
for i := 0 to High(SubTableOffsets) do
begin
LookupPos := StartPos + SubTableOffsets[i];
Stream.Position := LookupPos;
// Lookup is a an extension.
// Get the actual lookuptype from the sub-table and the offset to the sub-table.
if (IsExtension) then
begin
PosFormat := BigEndianValue.ReadWord(Stream);
if (PosFormat <> 1) then
raise EPascalTypeError.CreateFmt(RCStrUnknownVersion, [PosFormat]);
FLookupType := BigEndianValue.ReadWord(Stream);
if (TCustomOpenTypeCommonTable(Parent.Parent).IsExtensionLookupType(FLookupType)) then
raise EPascalTypeError.CreateFmt(RCStrInvalidLookupType, [FLookupType]);
Offset := BigEndianValue.ReadCardinal(Stream);
Stream.Position := LookupPos + Offset;
end;
// Read lookup type
SubTableType := BigEndianValue.ReadWord(Stream);
SubTableClass := GetSubTableClass(SubTableType);
if (SubTableClass = nil) then
continue;
// Add to subtable list
SubTable := FSubTableList.Add(SubTableClass);
// Load subtable
Stream.Seek(-SizeOf(Word), soFromCurrent);
SubTable.LoadFromStream(Stream);
end;
end;
procedure TCustomOpenTypeLookupTable.SaveToStream(Stream: TStream);
var
StartPos: Int64;
SubTableOffsets: array of Word;
i: integer;
OffsetTablePos: Int64;
begin
StartPos := Stream.Position;
inherited;
BigEndianValue.WriteWord(Stream, FLookupType);
BigEndianValue.WriteWord(Stream, FLookupFlags);
BigEndianValue.WriteWord(Stream, FSubTableList.Count);
OffsetTablePos := Stream.Position;
// Reserve space for offset list
Stream.Seek(FSubTableList.Count * SizeOf(Word), soCurrent);
SetLength(SubTableOffsets, FSubTableList.Count);
for i := 0 to FSubTableList.Count-1 do
begin
SubTableOffsets[i] := Stream.Position - StartPos;
FSubTableList[i].SaveToStream(Stream);
end;
StartPos := Stream.Position;
Stream.Position := OffsetTablePos;
for i := 0 to FSubTableList.Count-1 do
BigEndianValue.WriteWord(Stream, SubTableOffsets[i]);
Stream.Position := StartPos;
end;
function TCustomOpenTypeLookupTable.GetEnumerator: TEnumerator<TCustomOpenTypeLookupSubTable>;
begin
Result := FSubTableList.GetEnumerator;
end;
function TCustomOpenTypeLookupTable.GetLookupList: TOpenTypeLookupListTable;
begin
// Not so nice, but I'd rather not go through the FontFace to get at the list :-(
Result := Parent as TOpenTypeLookupListTable;
end;
function TCustomOpenTypeLookupTable.Apply(var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
var
SubTable: TCustomOpenTypeLookupSubTable;
begin
for SubTable in FSubTableList do
if (SubTable.Apply(AGlyphIterator)) then
{$if (not Defined(DEBUG)) or (not Defined(VerboseDebug))}
Exit(True);
{$else}
begin
OutputDebugString(PChar(Format('Applied lookup %s: %s', [ClassName, SubTable.ClassName])));
Exit(True);
end else
;//OutputDebugString(PChar(Format('Did not match lookup %s: %s', [ClassName, SubTable.ClassName])));
{$ifend}
Result := False;
end;
function TCustomOpenTypeLookupTable.GetSubTable(Index: Integer): TCustomOpenTypeLookupSubTable;
begin
if (Index < 0) or (Index >= FSubTableList.Count) then
raise EPascalTypeError.CreateFmt(RCStrIndexOutOfBounds, [Index]);
Result := TCustomOpenTypeLookupSubTable(FSubTableList[Index]);
end;
function TCustomOpenTypeLookupTable.GetSubTableCount: Integer;
begin
Result := FSubTableList.Count;
end;
function TCustomOpenTypeLookupTable.GetUseReverseDirection: boolean;
begin
Result := False;
end;
procedure TCustomOpenTypeLookupTable.SetLookupFlags(const Value: Word);
begin
if FLookupFlags <> Value then
begin
FLookupFlags := Value;
LookupFlagsChanged;
end;
end;
procedure TCustomOpenTypeLookupTable.SetMarkFilteringSet(const Value: Word);
begin
if FMarkFilteringSet <> Value then
begin
FMarkFilteringSet := Value;
MarkFilteringSetChanged;
end;
end;
procedure TCustomOpenTypeLookupTable.LookupFlagsChanged;
begin
Changed;
end;
procedure TCustomOpenTypeLookupTable.MarkFilteringSetChanged;
begin
Changed;
end;
//------------------------------------------------------------------------------
//
// TOpenTypeLookupTableGeneric
//
//------------------------------------------------------------------------------
function TOpenTypeLookupTableGeneric.GetSubTableClass(ASubFormat: Word): TOpenTypeLookupSubTableClass;
begin
Result := TOpenTypeLookupSubTableGeneric;
end;
function TOpenTypeLookupTableGeneric.TOpenTypeLookupSubTableGeneric.Apply(var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
begin
{$ifdef DEBUG}
OutputDebugString(PChar(Format('%s lookup not implemented. Lookup type: %d, sub-format: %d', [string(TCustomPascalTypeNamedTable(TOpenTypeLookupTableGeneric(Parent).LookupList.Parent).TableType.AsAnsiChar), TOpenTypeLookupTableGeneric(Parent).LookupType, SubFormat])));
{$endif DEBUG}
Result := False;
end;
//------------------------------------------------------------------------------
//
// TOpenTypeLookupListTable
//
//------------------------------------------------------------------------------
constructor TOpenTypeLookupListTable.Create(AParent: TCustomPascalTypeTable);
begin
inherited Create(AParent as TCustomOpenTypeCommonTable); // Type check the parent
FLookupList := TPascalTypeTableInterfaceList<TCustomOpenTypeLookupTable>.Create(Self);
end;
destructor TOpenTypeLookupListTable.Destroy;
begin
FreeAndNil(FLookupList);
inherited;
end;
procedure TOpenTypeLookupListTable.Assign(Source: TPersistent);
begin
inherited;
if Source is TOpenTypeLookupListTable then
FLookupList.Assign(TOpenTypeLookupListTable(Source).FLookupList);
end;
function TOpenTypeLookupListTable.GetLookupTable(Index: Integer): TCustomOpenTypeLookupTable;
begin
if (Index < 0) or (Index >= FLookupList.Count) then
raise EPascalTypeError.CreateFmt(RCStrIndexOutOfBounds, [Index]);
Result := FLookupList[Index];
end;
function TOpenTypeLookupListTable.GetLookupTableCount: Integer;
begin
Result := FLookupList.Count;
end;
procedure TOpenTypeLookupListTable.LoadFromStream(Stream: TStream; Size: Cardinal);
function GetLookupTypeFromExtension: Word;
var
StartPos: Int64;
LookupFlags: Word;
Count: Word;
SubOffset: Word;
PosFormat: Word;
begin
StartPos := Stream.Position;
Result := 0;
// Skip LookupType and LookupFlags
Stream.Position := Stream.Position + SizeOf(Word);
// Read LookupFlags
LookupFlags := BigEndianValue.ReadWord(Stream);
// Read subtable count
Count := BigEndianValue.ReadWord(Stream);
// Read first lookup list index offset
if (Count = 0) then
Exit; // Invalid
SubOffset := BigEndianValue.ReadWord(Stream);
Stream.Position := Stream.Position + (Count-1)*SizeOf(Word);
// Skip MarkFilteringSet
if (LookupFlags and TCustomOpenTypeLookupTable.USE_MARK_FILTERING_SET <> 0) then
Stream.Position := Stream.Position + SizeOf(Word);
// Seek to sub-table
Stream.Position := StartPos + SubOffset;
// Read Extension Positioning Subtable Format 1
// - posFormat (we just verify that it has the correct value)
PosFormat := BigEndianValue.ReadWord(Stream);
if (PosFormat <> 1) then
Exit;
// - extensionLookupType
Result := BigEndianValue.ReadWord(Stream);
// Skip extensionOffset. We don't need it here.
end;
var
StartPos: Int64;
SavePos: Int64;
i: Integer;
LookupTableOffsets: array of Word;
LookupTable: TCustomOpenTypeLookupTable;
LookupType: Word;
LookupTableClass: TOpenTypeLookupTableClass;
begin
StartPos := Stream.Position;
inherited;
// check (minimum) table size
if Stream.Position + 2 > Stream.Size then
raise EPascalTypeError.Create(RCStrTableIncomplete);
// read lookup list count
SetLength(LookupTableOffsets, BigEndianValue.ReadWord(Stream));
// read offsets
for i := 0 to High(LookupTableOffsets) do
LookupTableOffsets[i] := BigEndianValue.ReadWord(Stream);
FLookupList.Clear;
for i := 0 to High(LookupTableOffsets) do
begin
// set position to start of lookup table
Stream.Position := StartPos + LookupTableOffsets[i];
// We peek ahead into the stream to determine the lookup table class in order to
// support extension lookups. For extension lookup types the actual lookup type
// is stored in the lookup sub-tables.
LookupType := BigEndianValue.ReadWord(Stream);
Stream.Seek(-SizeOf(Word), soFromCurrent);
if (TCustomOpenTypeCommonTable(Parent).IsExtensionLookupType(LookupType)) then
begin
SavePos := Stream.Position;
// Peek ahead into lookup table to get actual lookup type
LookupType := GetLookupTypeFromExtension;
// Make sure that the extension lookup didn't specify the lookup type as an extension lookup
if (TCustomOpenTypeCommonTable(Parent).IsExtensionLookupType(LookupType)) then
raise EPascalTypeError.CreateFmt(RCStrInvalidLookupType, [LookupType]);
Stream.Position := SavePos;
end;
// Get the lookup table class from the parent.
// The mapping from LookupType to lookup table class differs between GSUB and GPOS.
LookupTableClass := TCustomOpenTypeCommonTable(Parent).GetLookupTableClass(LookupType);
if (LookupTableClass = nil) then
// We *must* load the table even if we have no implementation for it.
// Otherwise the index numbers in the feature lookup list (see
// TCustomOpenTypeFeatureTable) will not match.
LookupTableClass := TOpenTypeLookupTableGeneric;
LookupTable := FLookupList.Add(LookupTableClass);
// Load lookup table
LookupTable.LoadFromStream(Stream);
end;
end;
procedure TOpenTypeLookupListTable.SaveToStream(Stream: TStream);
begin
inherited;
raise EPascalTypeNotImplemented.Create(RCStrNotImplemented);
end;
//------------------------------------------------------------------------------
//
// TCustomOpenTypeLookupSubTable
//
//------------------------------------------------------------------------------
constructor TCustomOpenTypeLookupSubTable.Create(AParent: TCustomPascalTypeTable);
begin
inherited Create(AParent as TCustomOpenTypeLookupTable);
FSubFormat := $FFFF;
end;
//------------------------------------------------------------------------------
function TCustomOpenTypeLookupSubTable.GetLookupTable: TCustomOpenTypeLookupTable;
begin
Result := TCustomOpenTypeLookupTable(Parent);
end;
//------------------------------------------------------------------------------
procedure TCustomOpenTypeLookupSubTable.LoadFromStream(Stream: TStream; Size: Cardinal);
begin
inherited;
FSubFormat := BigEndianValue.ReadWord(Stream);
end;
procedure TCustomOpenTypeLookupSubTable.SaveToStream(Stream: TStream);
begin
inherited;
BigEndianValue.WriteWord(Stream, FSubFormat);
end;
//------------------------------------------------------------------------------
function TCustomOpenTypeLookupSubTable.MatchCoverage(var AGlyphIterator: TPascalTypeGlyphIterator; ACoverageTables: TCoverageTables; out ALastMatchedIndex: integer; AOptions: TMatchOptions): boolean;
begin
ALastMatchedIndex := -1;
if (ACoverageTables.Count = 0) then
Exit(True);
var Iterator := AGlyphIterator.Clone;
for var i := 0 to ACoverageTables.Count-1 do
begin
if (Iterator.EOF) then
Exit(False);
var CoverageIndex := ACoverageTables[i].IndexOfGlyph(Iterator.Glyph.GlyphID);
if (CoverageIndex = -1) then
Exit(False);
ALastMatchedIndex := Iterator.Index;
if (moBacktrack in AOptions) then
Iterator.Previous
else
Iterator.Next;
end;
if (moMoveOnMatch in AOptions) then
AGlyphIterator.Index := Iterator.Index;
Result := True;
end;
function TCustomOpenTypeLookupSubTable.MatchCoverage(var AGlyphIterator: TPascalTypeGlyphIterator; ACoverageTables: TCoverageTables; AOptions: TMatchOptions): boolean;
var
LastMatchedIndex: integer;
begin
Result := MatchCoverage(AGlyphIterator, ACoverageTables, LastMatchedIndex, AOptions);
end;
//------------------------------------------------------------------------------
function TCustomOpenTypeLookupSubTable.ApplyChainedContextCoverage(const ACoverageTables: TContextCoverageTables;
const ASequenceRules: TSequenceLookupRecords;
var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
begin
Result := False;
if (AGlyphIterator.EOF) then
exit;
// Quick short-circuit exit.
// We can get away with not taking the iterator filters into account here
// because the filters would only ever reduce the effective length of the
// glyph string, so if the sequences are larger than the raw glyph string,
// then they will also be larger than the filtered glyph string.
//
// 1) There needs to be enough glyphs to matching input+lookahead, starting
// at the current glyph.
if (AGlyphIterator.Index + ACoverageTables[cpInput].Count + ACoverageTables[cpLookahead].Count > AGlyphIterator.GlyphString.Count) then
exit;
// 2) There needs to be enough glyphs to match backtrack, before the
// current glyph.
if (AGlyphIterator.Index < ACoverageTables[cpBacktrack].Count) then
exit;
var Iterator := AGlyphIterator.Clone;
// The strings are matched, character by character, against the coverage tables.
// The coverage index itself isn't used. We just need to determine if we should proceed.
// Input
var LastMatchedIndex: integer := -1;
if (ACoverageTables[cpInput].Count > 0) then
begin
if (not MatchCoverage(Iterator, ACoverageTables[cpInput], LastMatchedIndex, [moMoveOnMatch])) then
exit;
end;
// Save position, just after Input sequence, so we can resume the match for Lookahead there
var LookaheadIndex := Iterator.Index;
// Backtrack
if (ACoverageTables[cpBacktrack].Count > 0) then
begin
// Backtrack starts just before the initial start position
Iterator.Index := AGlyphIterator.Peek(-1);
// Note: We match backwards in the glyph string
if (not MatchCoverage(Iterator, ACoverageTables[cpBacktrack], [moBackTrack])) then
exit;
end;
// Lookahead
if (ACoverageTables[cpLookahead].Count > 0) then
begin
// Lookahead starts just after the Input sequence
Iterator.Index := LookaheadIndex;
if (not MatchCoverage(Iterator, ACoverageTables[cpLookahead])) then
exit;
end;
// We have a match. Apply the rules.
Result := ApplyLookupRecords(AGlyphIterator, LookaheadIndex, ASequenceRules);
end;
function TCustomOpenTypeLookupSubTable.ApplyContextCoverage(const ACoverageTables: TCoverageTables;
const ASequenceRules: TSequenceLookupRecords; var AGlyphIterator: TPascalTypeGlyphIterator): boolean;
begin
Result := False;
if (AGlyphIterator.Index + ACoverageTables.Count > AGlyphIterator.GlyphString.Count) then
exit;
var Iterator := AGlyphIterator.Clone;
// The string is matched, character by character, against the coverage table.
// The coverage index itself isn't used. We just need to determine if we should proceed.
var LastMatchedIndex: integer;
if (not MatchCoverage(Iterator, ACoverageTables, LastMatchedIndex, [moMoveOnMatch])) then
exit;
// We have a match. Apply the rules.
Result := ApplyLookupRecords(AGlyphIterator, Iterator.Index, ASequenceRules);
end;
function TCustomOpenTypeLookupSubTable.ApplyLookupRecords(var AGlyphIterator: TPascalTypeGlyphIterator; ANextIndex: integer;
const LookupRecords: TSequenceLookupRecords): boolean;
begin
// Lookup can be empty in which case we consider it a match. See issue #49
if (Length(LookupRecords) = 0) then
begin
AGlyphIterator.Index := ANextIndex;
Exit(True);
end;
// Note:
// ANextIndex contains the position the iterator must have after skipping the input
// sequence, in the current state of the glyph string - before any substitutions has
// been made. We adjust for glyphs added/deleted at the end when we reposition to
// ANextIndex.
Result := False;
var LookupList := LookupTable.LookupList;
(*
Sequence context format 1: simple glyph contexts
https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2#sequence-context-format-1-simple-glyph-contexts
The seqLookupRecords array lists the sequence lookup records that specify actions
to be taken on glyphs at various positions within the input sequence. These do not
have to be ordered in sequence position order; they are ordered according to the
desired result. All of the sequence lookup records are processed in order, and
each applies to the results of the actions indicated by the preceding record.
Note: The above text is present in the description of all the sequence context
formats. Not just format 1.
*)
var StartCount := AGlyphIterator.GlyphString.Count;
for var i := 0 to High(LookupRecords) do
begin
var Iterator := AGlyphIterator.Clone;
// Adjust delta for glyphs added or deleted (in prior loop iterations);
// If a preceding lookup record changed the length of the glyph string (e.g. inserted
// or deleted glyphs), then the SequenceIndex of subsequent records (which is relative
// to the original sequence) will point to a different physical glyph in the modified
// buffer if we just apply the same offset to the base index.
// The spec requires that each record applies to the results of the preceding one,
// which implies the engine must track these buffer modifications within the sequence.
(* It turnes out that this isn't necessary at all; The lookups (or rather the value of
** SequenceIndex already takes deletions and insertions into account.
var Delta := Iterator.GlyphString.Count - StartCount;
*)
var Delta := 0;
// Adjust the glyph index
if (Iterator.Next(LookupRecords[i].SequenceIndex + Delta) = -1) then
// Sequence starts past end of string so we cannot apply the lookup.
// This is likely a bug in the font. The more correct thing to do if
// this occurs would probably be to exit.
continue;
// Get the referenced lookup
var Lookup := LookupList[LookupRecords[i].LookupListIndex];
if (Lookup.LookupFlags and TCustomOpenTypeLookupTable.USE_MARK_FILTERING_SET <> 0) then
Iterator.ResetFlags(Lookup.LookupFlags, Lookup.MarkFilteringSet)
else
Iterator.ResetFlags(Lookup.LookupFlags);
// *Recursively* apply
if (Lookup.Apply(Iterator)) then
Result := True;
end;
(*
** OpenType Layout Common Table Formats, Lookup table
**
** https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2
**
** "To move to the 'next' glyph, the client skips all the glyphs that participated in
** the lookup operation: glyphs that were substituted as well as any other glyphs
** that formed a context for the operation."
**
** While "context" could be interpreted to include lookahead, standard practice (e.g.
** HarfBuzz) is to advance past the entire *input sequence* but NOT the lookahead
** sequence, as lookahead glyphs may need to be the start of a subsequent match.
**
** For example, let's say we have a sequence of glyphs [A, B, C, D] and a contextual
** rule matches the 3-glyph sequence [A, B, C] but `ApplyLookupRecords` only applies
** a lookup to the 1st glyph (A), the shaper must advance past the whole input
** sequence and continue at D; Not just advance past A to continue at B.
**
** Note that there is an exception to the above rule:
**
** "However, an exception to this rule is made in the case of pair positioning
** operations (for example, kerning): the "next" glyph in a sequence may be the
** second glyph of the input sequence pair, rather than skipping over the entire
** input sequence."
**
** Another place the specs qualify the above rule:
**
** "There is just one exception: the "next" glyph in a sequence may be one of those
** that formed a context for the operation just performed. Specifically, in the
** case of pair positioning operations (i.e., kerning), if the ValueRecord for the
** second glyph is null, that glyph is treated as the "next" glyph in the sequence."
**
** The above is implemented in TOpenTypePositioningSubTablePairSingle.Apply and
** TOpenTypePositioningSubTablePairClass.Apply.
*)
// Reposition past the input sequence, adjusted for deletions/insertions performed
// by ApplyLookupRecords.
// TODO : Do we skip the input sequence if no lookups were applied (i.e. Result=False)?
AGlyphIterator.Index := ANextIndex + (AGlyphIterator.GlyphString.Count - StartCount);
end;
procedure TCustomOpenTypeLookupSubTable.Assign(Source: TPersistent);