aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
blob: 7bb5a23e1e7cf046ecf8c94e025e8860094e2c8e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.complexscripts.fonts;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.fop.complexscripts.scripts.ScriptProcessor;
import org.apache.fop.complexscripts.util.CharAssociation;
import org.apache.fop.complexscripts.util.GlyphSequence;
import org.apache.fop.complexscripts.util.GlyphTester;

// CSOFF: LineLengthCheck

/**
 * <p>The <code>GlyphSubstitutionTable</code> class is a glyph table that implements
 * <code>GlyphSubstitution</code> functionality.</p>
 *
 * <p>This work was originally authored by Glenn Adams (gadams@apache.org).</p>
 */
public class GlyphSubstitutionTable extends GlyphTable {

    /** logging instance */
    private static final Log log = LogFactory.getLog(GlyphSubstitutionTable.class);

    /** single substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_SINGLE = 1;
    /** multiple substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_MULTIPLE = 2;
    /** alternate substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_ALTERNATE = 3;
    /** ligature substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_LIGATURE = 4;
    /** contextual substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_CONTEXTUAL = 5;
    /** chained contextual substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL = 6;
    /** extension substitution substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION = 7;
    /** reverse chained contextual single substitution subtable type */
    public static final int GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE = 8;

    /**
     * Instantiate a <code>GlyphSubstitutionTable</code> object using the specified lookups
     * and subtables.
     * @param gdef glyph definition table that applies
     * @param lookups a map of lookup specifications to subtable identifier strings
     * @param subtables a list of identified subtables
     */
    public GlyphSubstitutionTable(GlyphDefinitionTable gdef, Map lookups, List subtables) {
        super(gdef, lookups);
        if ((subtables == null) || (subtables.size() == 0)) {
            throw new AdvancedTypographicTableFormatException("subtables must be non-empty");
        } else {
            for (Iterator it = subtables.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o instanceof GlyphSubstitutionSubtable) {
                    addSubtable((GlyphSubtable) o);
                } else {
                    throw new AdvancedTypographicTableFormatException("subtable must be a glyph substitution subtable");
                }
            }
            freezeSubtables();
        }
    }

    /**
     * Perform substitution processing using all matching lookups.
     * @param gs an input glyph sequence
     * @param script a script identifier
     * @param language a language identifier
     * @return the substituted (output) glyph sequence
     */
    public GlyphSequence substitute(GlyphSequence gs, String script, String language) {
        GlyphSequence ogs;
        Map/*<LookupSpec,List<LookupTable>>*/ lookups = matchLookups(script, language, "*");
        if ((lookups != null) && (lookups.size() > 0)) {
            ScriptProcessor sp = ScriptProcessor.getInstance(script);
            ogs = sp.substitute(this, gs, script, language, lookups);
        } else {
            ogs = gs;
        }
        return ogs;
    }

    /**
     * Map a lookup type name to its constant (integer) value.
     * @param name lookup type name
     * @return lookup type
     */
    public static int getLookupTypeFromName(String name) {
        int t;
        String s = name.toLowerCase();
        if ("single".equals(s)) {
            t = GSUB_LOOKUP_TYPE_SINGLE;
        } else if ("multiple".equals(s)) {
            t = GSUB_LOOKUP_TYPE_MULTIPLE;
        } else if ("alternate".equals(s)) {
            t = GSUB_LOOKUP_TYPE_ALTERNATE;
        } else if ("ligature".equals(s)) {
            t = GSUB_LOOKUP_TYPE_LIGATURE;
        } else if ("contextual".equals(s)) {
            t = GSUB_LOOKUP_TYPE_CONTEXTUAL;
        } else if ("chainedcontextual".equals(s)) {
            t = GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL;
        } else if ("extensionsubstitution".equals(s)) {
            t = GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION;
        } else if ("reversechainiingcontextualsingle".equals(s)) {
            t = GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE;
        } else {
            t = -1;
        }
        return t;
    }

    /**
     * Map a lookup type constant (integer) value to its name.
     * @param type lookup type
     * @return lookup type name
     */
    public static String getLookupTypeName(int type) {
        String tn = null;
        switch (type) {
        case GSUB_LOOKUP_TYPE_SINGLE:
            tn = "single";
            break;
        case GSUB_LOOKUP_TYPE_MULTIPLE:
            tn = "multiple";
            break;
        case GSUB_LOOKUP_TYPE_ALTERNATE:
            tn = "alternate";
            break;
        case GSUB_LOOKUP_TYPE_LIGATURE:
            tn = "ligature";
            break;
        case GSUB_LOOKUP_TYPE_CONTEXTUAL:
            tn = "contextual";
            break;
        case GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL:
            tn = "chainedcontextual";
            break;
        case GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION:
            tn = "extensionsubstitution";
            break;
        case GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE:
            tn = "reversechainiingcontextualsingle";
            break;
        default:
            tn = "unknown";
            break;
        }
        return tn;
    }

    /**
     * Create a substitution subtable according to the specified arguments.
     * @param type subtable type
     * @param id subtable identifier
     * @param sequence subtable sequence
     * @param flags subtable flags
     * @param format subtable format
     * @param coverage subtable coverage table
     * @param entries subtable entries
     * @return a glyph subtable instance
     */
    public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
        GlyphSubtable st = null;
        switch (type) {
        case GSUB_LOOKUP_TYPE_SINGLE:
            st = SingleSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_MULTIPLE:
            st = MultipleSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_ALTERNATE:
            st = AlternateSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_LIGATURE:
            st = LigatureSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_CONTEXTUAL:
            st = ContextualSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL:
            st = ChainedContextualSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        case GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE:
            st = ReverseChainedSingleSubtable.create(id, sequence, flags, format, coverage, entries);
            break;
        default:
            break;
        }
        return st;
    }

    /**
     * Create a substitution subtable according to the specified arguments.
     * @param type subtable type
     * @param id subtable identifier
     * @param sequence subtable sequence
     * @param flags subtable flags
     * @param format subtable format
     * @param coverage list of coverage table entries
     * @param entries subtable entries
     * @return a glyph subtable instance
     */
    public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format, List coverage, List entries) {
        return createSubtable(type, id, sequence, flags, format, GlyphCoverageTable.createCoverageTable(coverage), entries);
    }

    private abstract static class SingleSubtable extends GlyphSubstitutionSubtable {
        SingleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_SINGLE;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof SingleSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                int go = getGlyphForCoverageIndex(ci, gi);
                if ((go < 0) || (go > 65535)) {
                    go = 65535;
                }
                ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE);
                ss.consume(1);
                return true;
            }
        }
        /**
         * Obtain glyph for coverage index.
         * @param ci coverage index
         * @param gi original glyph index
         * @return substituted glyph value
         * @throws IllegalArgumentException if coverage index is not valid
         */
        public abstract int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException;
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new SingleSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else if (format == 2) {
                return new SingleSubtableFormat2(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class SingleSubtableFormat1 extends SingleSubtable {
        private int delta;
        private int ciMax;
        SingleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            List entries = new ArrayList(1);
            entries.add(Integer.valueOf(delta));
            return entries;
        }
        /** {@inheritDoc} */
        public int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException {
            if (ci <= ciMax) {
                return gi + delta;
            } else {
                throw new IllegalArgumentException("coverage index " + ci + " out of range, maximum coverage index is " + ciMax);
            }
        }
        private void populate(List entries) {
            if ((entries == null) || (entries.size() != 1)) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null and contain exactly one entry");
            } else {
                Object o = entries.get(0);
                int delta = 0;
                if (o instanceof Integer) {
                    delta = ((Integer) o) .intValue();
                } else {
                    throw new AdvancedTypographicTableFormatException("illegal entries entry, must be Integer, but is: " + o);
                }
                this.delta = delta;
                this.ciMax = getCoverageSize() - 1;
            }
        }
    }

    private static class SingleSubtableFormat2 extends SingleSubtable {
        private int[] glyphs;
        SingleSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            List entries = new ArrayList(glyphs.length);
            for (int i = 0, n = glyphs.length; i < n; i++) {
                entries.add(Integer.valueOf(glyphs[i]));
            }
            return entries;
        }
        /** {@inheritDoc} */
        public int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException {
            if (glyphs == null) {
                return -1;
            } else if (ci >= glyphs.length) {
                throw new IllegalArgumentException("coverage index " + ci + " out of range, maximum coverage index is " + glyphs.length);
            } else {
                return glyphs [ ci ];
            }
        }
        private void populate(List entries) {
            int i = 0;
            int n = entries.size();
            int[] glyphs = new int [ n ];
            for (Iterator it = entries.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o instanceof Integer) {
                    int gid = ((Integer) o) .intValue();
                    if ((gid >= 0) && (gid < 65536)) {
                        glyphs [ i++ ] = gid;
                    } else {
                        throw new AdvancedTypographicTableFormatException("illegal glyph index: " + gid);
                    }
                } else {
                    throw new AdvancedTypographicTableFormatException("illegal entries entry, must be Integer: " + o);
                }
            }
            assert i == n;
            assert this.glyphs == null;
            this.glyphs = glyphs;
        }
    }

    private abstract static class MultipleSubtable extends GlyphSubstitutionSubtable {
        public MultipleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_MULTIPLE;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof MultipleSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                int[] ga = getGlyphsForCoverageIndex(ci, gi);
                if (ga != null) {
                    ss.putGlyphs(ga, CharAssociation.replicate(ss.getAssociation(), ga.length), Boolean.TRUE);
                    ss.consume(1);
                }
                return true;
            }
        }
        /**
         * Obtain glyph sequence for coverage index.
         * @param ci coverage index
         * @param gi original glyph index
         * @return sequence of glyphs to substitute for input glyph
         * @throws IllegalArgumentException if coverage index is not valid
         */
        public abstract int[] getGlyphsForCoverageIndex(int ci, int gi) throws IllegalArgumentException;
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new MultipleSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class MultipleSubtableFormat1 extends MultipleSubtable {
        private int[][] gsa;                            // glyph sequence array, ordered by coverage index
        MultipleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (gsa != null) {
                List entries = new ArrayList(1);
                entries.add(gsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public int[] getGlyphsForCoverageIndex(int ci, int gi) throws IllegalArgumentException {
            if (gsa == null) {
                return null;
            } else if (ci >= gsa.length) {
                throw new IllegalArgumentException("coverage index " + ci + " out of range, maximum coverage index is " + gsa.length);
            } else {
                return gsa [ ci ];
            }
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 1) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof int[][])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an int[][], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    gsa = (int[][]) o;
                }
            }
        }
    }

    private abstract static class AlternateSubtable extends GlyphSubstitutionSubtable {
        public AlternateSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_ALTERNATE;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof AlternateSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                int[] ga = getAlternatesForCoverageIndex(ci, gi);
                int ai = ss.getAlternatesIndex(ci);
                int go;
                if ((ai < 0) || (ai >= ga.length)) {
                    go = gi;
                } else {
                    go = ga [ ai ];
                }
                if ((go < 0) || (go > 65535)) {
                    go = 65535;
                }
                ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE);
                ss.consume(1);
                return true;
            }
        }
        /**
         * Obtain glyph alternates for coverage index.
         * @param ci coverage index
         * @param gi original glyph index
         * @return sequence of glyphs to substitute for input glyph
         * @throws IllegalArgumentException if coverage index is not valid
         */
        public abstract int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException;
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new AlternateSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class AlternateSubtableFormat1 extends AlternateSubtable {
        private int[][] gaa;                            // glyph alternates array, ordered by coverage index
        AlternateSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            List entries = new ArrayList(gaa.length);
            for (int i = 0, n = gaa.length; i < n; i++) {
                entries.add(gaa[i]);
            }
            return entries;
        }
        /** {@inheritDoc} */
        public int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException {
            if (gaa == null) {
                return null;
            } else if (ci >= gaa.length) {
                throw new IllegalArgumentException("coverage index " + ci + " out of range, maximum coverage index is " + gaa.length);
            } else {
                return gaa [ ci ];
            }
        }
        private void populate(List entries) {
            int i = 0;
            int n = entries.size();
            int[][] gaa = new int [ n ][];
            for (Iterator it = entries.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o instanceof int[]) {
                    gaa [ i++ ] = (int[]) o;
                } else {
                    throw new AdvancedTypographicTableFormatException("illegal entries entry, must be int[]: " + o);
                }
            }
            assert i == n;
            assert this.gaa == null;
            this.gaa = gaa;
        }
    }

    private abstract static class LigatureSubtable extends GlyphSubstitutionSubtable {
        public LigatureSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_LIGATURE;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof LigatureSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                LigatureSet ls = getLigatureSetForCoverageIndex(ci, gi);
                if (ls != null) {
                    boolean reverse = false;
                    GlyphTester ignores = ss.getIgnoreDefault();
                    int[] counts = ss.getGlyphsAvailable(0, reverse, ignores);
                    int nga = counts[0];
                    int ngi;
                    if (nga > 1) {
                        int[] iga = ss.getGlyphs(0, nga, reverse, ignores, null, counts);
                        Ligature l = findLigature(ls, iga);
                        if (l != null) {
                            int go = l.getLigature();
                            if ((go < 0) || (go > 65535)) {
                                go = 65535;
                            }
                            int nmg = 1 + l.getNumComponents();
                            // fetch matched number of component glyphs to determine matched and ignored count
                            ss.getGlyphs(0, nmg, reverse, ignores, null, counts);
                            nga = counts[0];
                            ngi = counts[1];
                            // fetch associations of matched component glyphs
                            CharAssociation[] laa = ss.getAssociations(0, nga);
                            // output ligature glyph and its association
                            ss.putGlyph(go, CharAssociation.join(laa), Boolean.TRUE);
                            // fetch and output ignored glyphs (if necessary)
                            if (ngi > 0) {
                                ss.putGlyphs(ss.getIgnoredGlyphs(0, ngi), ss.getIgnoredAssociations(0, ngi), null);
                            }
                            ss.consume(nga + ngi);
                        }
                    }
                }
                return true;
            }
        }
        private Ligature findLigature(LigatureSet ls, int[] glyphs) {
            Ligature[] la = ls.getLigatures();
            int k = -1;
            int maxComponents = -1;
            for (int i = 0, n = la.length; i < n; i++) {
                Ligature l = la [ i ];
                if (l.matchesComponents(glyphs)) {
                    int nc = l.getNumComponents();
                    if (nc > maxComponents) {
                        maxComponents = nc;
                        k = i;
                    }
                }
            }
            if (k >= 0) {
                return la [ k ];
            } else {
                return null;
            }
        }
        /**
         * Obtain ligature set for coverage index.
         * @param ci coverage index
         * @param gi original glyph index
         * @return ligature set (or null if none defined)
         * @throws IllegalArgumentException if coverage index is not valid
         */
        public abstract LigatureSet getLigatureSetForCoverageIndex(int ci, int gi) throws IllegalArgumentException;
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new LigatureSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class LigatureSubtableFormat1 extends LigatureSubtable {
        private LigatureSet[] ligatureSets;
        public LigatureSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            List entries = new ArrayList(ligatureSets.length);
            for (int i = 0, n = ligatureSets.length; i < n; i++) {
                entries.add(ligatureSets[i]);
            }
            return entries;
        }
        /** {@inheritDoc} */
        public LigatureSet getLigatureSetForCoverageIndex(int ci, int gi) throws IllegalArgumentException {
            if (ligatureSets == null) {
                return null;
            } else if (ci >= ligatureSets.length) {
                throw new IllegalArgumentException("coverage index " + ci + " out of range, maximum coverage index is " + ligatureSets.length);
            } else {
                return ligatureSets [ ci ];
            }
        }
        private void populate(List entries) {
            int i = 0;
            int n = entries.size();
            LigatureSet[] ligatureSets = new LigatureSet [ n ];
            for (Iterator it = entries.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o instanceof LigatureSet) {
                    ligatureSets [ i++ ] = (LigatureSet) o;
                } else {
                    throw new AdvancedTypographicTableFormatException("illegal ligatures entry, must be LigatureSet: " + o);
                }
            }
            assert i == n;
            assert this.ligatureSets == null;
            this.ligatureSets = ligatureSets;
        }
    }

    private abstract static class ContextualSubtable extends GlyphSubstitutionSubtable {
        public ContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_CONTEXTUAL;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof ContextualSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                int[] rv = new int[1];
                RuleLookup[] la = getLookups(ci, gi, ss, rv);
                if (la != null) {
                    ss.apply(la, rv[0]);
                }
                return true;
            }
        }
        /**
         * Obtain rule lookups set associated current input glyph context.
         * @param ci coverage index of glyph at current position
         * @param gi glyph index of glyph at current position
         * @param ss glyph substitution state
         * @param rv array of ints used to receive multiple return values, must be of length 1 or greater,
         * where the first entry is used to return the input sequence length of the matched rule
         * @return array of rule lookups or null if none applies
         */
        public abstract RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv);
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new ContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else if (format == 2) {
                return new ContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);
            } else if (format == 3) {
                return new ContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class ContextualSubtableFormat1 extends ContextualSubtable {
        private RuleSet[] rsa;                          // rule set array, ordered by glyph coverage index
        ContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(1);
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {
                            ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;
                            int[] iga = cr.getGlyphs(gi);
                            if (matches(ss, iga, 0, rv)) {
                                return r.getLookups();
                            }
                        }
                    }
                }
            }
            return null;
        }
        static boolean matches(GlyphSubstitutionState ss, int[] glyphs, int offset, int[] rv) {
            if ((glyphs == null) || (glyphs.length == 0)) {
                return true;                            // match null or empty glyph sequence
            } else {
                boolean reverse = offset < 0;
                GlyphTester ignores = ss.getIgnoreDefault();
                int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);
                int nga = counts[0];
                int ngm = glyphs.length;
                if (nga < ngm) {
                    return false;                       // insufficient glyphs available to match
                } else {
                    int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);
                    for (int k = 0; k < ngm; k++) {
                        if (ga [ k ] != glyphs [ k ]) {
                            return false;               // match fails at ga [ k ]
                        }
                    }
                    if (rv != null) {
                        rv[0] = counts[0] + counts[1];
                    }
                    return true;                        // all glyphs match
                }
            }
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 1) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                }
            }
        }
    }

    private static class ContextualSubtableFormat2 extends ContextualSubtable {
        private GlyphClassTable cdt;                    // class def table
        private int ngc;                                // class set count
        private RuleSet[] rsa;                          // rule set array, ordered by class number [0...ngc - 1]
        ContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(3);
                entries.add(cdt);
                entries.add(Integer.valueOf(ngc));
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedClassSequenceRule)) {
                            ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;
                            int[] ca = cr.getClasses(cdt.getClassIndex(gi, ss.getClassMatchSet(gi)));
                            if (matches(ss, cdt, ca, 0, rv)) {
                                return r.getLookups();
                            }
                        }
                    }
                }
            }
            return null;
        }
        static boolean matches(GlyphSubstitutionState ss, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {
            if ((cdt == null) || (classes == null) || (classes.length == 0)) {
                return true;                            // match null class definitions, null or empty class sequence
            } else {
                boolean reverse = offset < 0;
                GlyphTester ignores = ss.getIgnoreDefault();
                int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);
                int nga = counts[0];
                int ngm = classes.length;
                if (nga < ngm) {
                    return false;                       // insufficient glyphs available to match
                } else {
                    int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);
                    for (int k = 0; k < ngm; k++) {
                        int gi = ga [ k ];
                        int ms = ss.getClassMatchSet(gi);
                        int gc = cdt.getClassIndex(gi, ms);
                        if ((gc < 0) || (gc >= cdt.getClassSize(ms))) {
                            return false;               // none or invalid class fails mat ch
                        } else if (gc != classes [ k ]) {
                            return false;               // match fails at ga [ k ]
                        }
                    }
                    if (rv != null) {
                        rv[0] = counts[0] + counts[1];
                    }
                    return true;                        // all glyphs match
                }
            }
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 3) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 3 entries");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    cdt = (GlyphClassTable) o;
                }
                if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    ngc = ((Integer)(o)).intValue();
                }
                if (((o = entries.get(2)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                    if (rsa.length != ngc) {
                        throw new AdvancedTypographicTableFormatException("illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes");
                    }
                }
            }
        }
    }

    private static class ContextualSubtableFormat3 extends ContextualSubtable {
        private RuleSet[] rsa;                          // rule set array, containing a single rule set
        ContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(1);
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {
                            ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;
                            GlyphCoverageTable[] gca = cr.getCoverages();
                            if (matches(ss, gca, 0, rv)) {
                                return r.getLookups();
                            }
                        }
                    }
                }
            }
            return null;
        }
        static boolean matches(GlyphSubstitutionState ss, GlyphCoverageTable[] gca, int offset, int[] rv) {
            if ((gca == null) || (gca.length == 0)) {
                return true;                            // match null or empty coverage array
            } else {
                boolean reverse = offset < 0;
                GlyphTester ignores = ss.getIgnoreDefault();
                int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);
                int nga = counts[0];
                int ngm = gca.length;
                if (nga < ngm) {
                    return false;                       // insufficient glyphs available to match
                } else {
                    int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);
                    for (int k = 0; k < ngm; k++) {
                        GlyphCoverageTable ct = gca [ k ];
                        if (ct != null) {
                            if (ct.getCoverageIndex(ga [ k ]) < 0) {
                                return false;           // match fails at ga [ k ]
                            }
                        }
                    }
                    if (rv != null) {
                        rv[0] = counts[0] + counts[1];
                    }
                    return true;                        // all glyphs match
                }
            }
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 1) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                }
            }
        }
    }

    private abstract static class ChainedContextualSubtable extends GlyphSubstitutionSubtable {
        public ChainedContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof ChainedContextualSubtable;
        }
        /** {@inheritDoc} */
        public boolean substitute(GlyphSubstitutionState ss) {
            int gi = ss.getGlyph();
            int ci;
            if ((ci = getCoverageIndex(gi)) < 0) {
                return false;
            } else {
                int[] rv = new int[1];
                RuleLookup[] la = getLookups(ci, gi, ss, rv);
                if (la != null) {
                    ss.apply(la, rv[0]);
                    return true;
                } else {
                    return false;
                }
            }
        }
        /**
         * Obtain rule lookups set associated current input glyph context.
         * @param ci coverage index of glyph at current position
         * @param gi glyph index of glyph at current position
         * @param ss glyph substitution state
         * @param rv array of ints used to receive multiple return values, must be of length 1 or greater
         * @return array of rule lookups or null if none applies
         */
        public abstract RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv);
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new ChainedContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else if (format == 2) {
                return new ChainedContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);
            } else if (format == 3) {
                return new ChainedContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class ChainedContextualSubtableFormat1 extends ChainedContextualSubtable {
        private RuleSet[] rsa;                          // rule set array, ordered by glyph coverage index
        ChainedContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(1);
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {
                            ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;
                            int[] iga = cr.getGlyphs(gi);
                            if (matches(ss, iga, 0, rv)) {
                                int[] bga = cr.getBacktrackGlyphs();
                                if (matches(ss, bga, -1, null)) {
                                    int[] lga = cr.getLookaheadGlyphs();
                                    if (matches(ss, lga, rv[0], null)) {
                                        return r.getLookups();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
        private boolean matches(GlyphSubstitutionState ss, int[] glyphs, int offset, int[] rv) {
            return ContextualSubtableFormat1.matches(ss, glyphs, offset, rv);
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 1) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                }
            }
        }
    }

    private static class ChainedContextualSubtableFormat2 extends ChainedContextualSubtable {
        private GlyphClassTable icdt;                   // input class def table
        private GlyphClassTable bcdt;                   // backtrack class def table
        private GlyphClassTable lcdt;                   // lookahead class def table
        private int ngc;                                // class set count
        private RuleSet[] rsa;                          // rule set array, ordered by class number [0...ngc - 1]
        ChainedContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(5);
                entries.add(icdt);
                entries.add(bcdt);
                entries.add(lcdt);
                entries.add(Integer.valueOf(ngc));
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedClassSequenceRule)) {
                            ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;
                            int[] ica = cr.getClasses(icdt.getClassIndex(gi, ss.getClassMatchSet(gi)));
                            if (matches(ss, icdt, ica, 0, rv)) {
                                int[] bca = cr.getBacktrackClasses();
                                if (matches(ss, bcdt, bca, -1, null)) {
                                    int[] lca = cr.getLookaheadClasses();
                                    if (matches(ss, lcdt, lca, rv[0], null)) {
                                        return r.getLookups();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
        private boolean matches(GlyphSubstitutionState ss, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {
            return ContextualSubtableFormat2.matches(ss, cdt, classes, offset, rv);
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 5) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 5 entries");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    icdt = (GlyphClassTable) o;
                }
                if (((o = entries.get(1)) != null) && !(o instanceof GlyphClassTable)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass());
                } else {
                    bcdt = (GlyphClassTable) o;
                }
                if (((o = entries.get(2)) != null) && !(o instanceof GlyphClassTable)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass());
                } else {
                    lcdt = (GlyphClassTable) o;
                }
                if (((o = entries.get(3)) == null) || !(o instanceof Integer)) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    ngc = ((Integer)(o)).intValue();
                }
                if (((o = entries.get(4)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, fifth entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                    if (rsa.length != ngc) {
                        throw new AdvancedTypographicTableFormatException("illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes");
                    }
                }
            }
        }
    }

    private static class ChainedContextualSubtableFormat3 extends ChainedContextualSubtable {
        private RuleSet[] rsa;                          // rule set array, containing a single rule set
        ChainedContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            if (rsa != null) {
                List entries = new ArrayList(1);
                entries.add(rsa);
                return entries;
            } else {
                return null;
            }
        }
        /** {@inheritDoc} */
        public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {
            GlyphTable.resolveLookupReferences(rsa, lookupTables);
        }
        /** {@inheritDoc} */
        public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {
            assert ss != null;
            assert (rv != null) && (rv.length > 0);
            assert rsa != null;
            if (rsa.length > 0) {
                RuleSet rs = rsa [ 0 ];
                if (rs != null) {
                    Rule[] ra = rs.getRules();
                    for (int i = 0, n = ra.length; i < n; i++) {
                        Rule r = ra [ i ];
                        if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {
                            ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;
                            GlyphCoverageTable[] igca = cr.getCoverages();
                            if (matches(ss, igca, 0, rv)) {
                                GlyphCoverageTable[] bgca = cr.getBacktrackCoverages();
                                if (matches(ss, bgca, -1, null)) {
                                    GlyphCoverageTable[] lgca = cr.getLookaheadCoverages();
                                    if (matches(ss, lgca, rv[0], null)) {
                                        return r.getLookups();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
        private boolean matches(GlyphSubstitutionState ss, GlyphCoverageTable[] gca, int offset, int[] rv) {
            return ContextualSubtableFormat3.matches(ss, gca, offset, rv);
        }
        private void populate(List entries) {
            if (entries == null) {
                throw new AdvancedTypographicTableFormatException("illegal entries, must be non-null");
            } else if (entries.size() != 1) {
                throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry");
            } else {
                Object o;
                if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {
                    throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null));
                } else {
                    rsa = (RuleSet[]) o;
                }
            }
        }
    }

    private abstract static class ReverseChainedSingleSubtable extends GlyphSubstitutionSubtable {
        public ReverseChainedSingleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage);
        }
        /** {@inheritDoc} */
        public int getType() {
            return GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE;
        }
        /** {@inheritDoc} */
        public boolean isCompatible(GlyphSubtable subtable) {
            return subtable instanceof ReverseChainedSingleSubtable;
        }
        /** {@inheritDoc} */
        public boolean usesReverseScan() {
            return true;
        }
        static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            if (format == 1) {
                return new ReverseChainedSingleSubtableFormat1(id, sequence, flags, format, coverage, entries);
            } else {
                throw new UnsupportedOperationException();
            }
        }
    }

    private static class ReverseChainedSingleSubtableFormat1 extends ReverseChainedSingleSubtable {
        ReverseChainedSingleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {
            super(id, sequence, flags, format, coverage, entries);
            populate(entries);
        }
        /** {@inheritDoc} */
        public List getEntries() {
            return null;
        }
        private void populate(List entries) {
        }
    }

    /**
     * The <code>Ligature</code> class implements a ligature lookup result in terms of
     * a ligature glyph (code) and the <emph>N+1...</emph> components that comprise the ligature,
     * where the <emph>Nth</emph> component was consumed in the coverage table lookup mapping to
     * this ligature instance.
     */
    public static class Ligature {

        private final int ligature;                     // (resulting) ligature glyph
        private final int[] components;                 // component glyph codes (note that first component is implied)

        /**
         * Instantiate a ligature.
         * @param ligature glyph id
         * @param components sequence of <emph>N+1...</emph> component glyph (or character) identifiers
         */
        public Ligature(int ligature, int[] components) {
            if ((ligature < 0) || (ligature > 65535)) {
                throw new AdvancedTypographicTableFormatException("invalid ligature glyph index: " + ligature);
            } else if (components == null) {
                throw new AdvancedTypographicTableFormatException("invalid ligature components, must be non-null array");
            } else {
                for (int i = 0, n = components.length; i < n; i++) {
                    int gc = components [ i ];
                    if ((gc < 0) || (gc > 65535)) {
                        throw new AdvancedTypographicTableFormatException("invalid component glyph index: " + gc);
                    }
                }
                this.ligature = ligature;
                this.components = components;
            }
        }

        /** @return ligature glyph id */
        public int getLigature() {
            return ligature;
        }

        /** @return array of <emph>N+1...</emph> components */
        public int[] getComponents() {
            return components;
        }

        /** @return components count */
        public int getNumComponents() {
            return components.length;
        }

        /**
         * Determine if input sequence at offset matches ligature's components.
         * @param glyphs array of glyph components to match (including first, implied glyph)
         * @return true if matches
         */
        public boolean matchesComponents(int[] glyphs) {
            if (glyphs.length < (components.length + 1)) {
                return false;
            } else {
                for (int i = 0, n = components.length; i < n; i++) {
                    if (glyphs [ i + 1 ] != components [ i ]) {
                        return false;
                    }
                }
                return true;
            }
        }

        /** {@inheritDoc} */
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("{components={");
            for (int i = 0, n = components.length; i < n; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(Integer.toString(components[i]));
            }
            sb.append("},ligature=");
            sb.append(Integer.toString(ligature));
            sb.append("}");
            return sb.toString();
        }

    }

    /**
     * The <code>LigatureSet</code> class implements a set of  ligatures.
     */
    public static class LigatureSet {

        private final Ligature[] ligatures;                     // set of ligatures all of which share the first (implied) component
        private final int maxComponents;                        // maximum number of components (including first)

        /**
         * Instantiate a set of ligatures.
         * @param ligatures collection of ligatures
         */
        public LigatureSet(List ligatures) {
            this ((Ligature[]) ligatures.toArray(new Ligature [ ligatures.size() ]));
        }

        /**
         * Instantiate a set of ligatures.
         * @param ligatures array of ligatures
         */
        public LigatureSet(Ligature[] ligatures) {
            if (ligatures == null) {
                throw new AdvancedTypographicTableFormatException("invalid ligatures, must be non-null array");
            } else {
                this.ligatures = ligatures;
                int ncMax = -1;
                for (int i = 0, n = ligatures.length; i < n; i++) {
                    Ligature l = ligatures [ i ];
                    int nc = l.getNumComponents() + 1;
                    if (nc > ncMax) {
                        ncMax = nc;
                    }
                }
                maxComponents = ncMax;
            }
        }

        /** @return array of ligatures in this ligature set */
        public Ligature[] getLigatures() {
            return ligatures;
        }

        /** @return count of ligatures in this ligature set */
        public int getNumLigatures() {
            return ligatures.length;
        }

        /** @return maximum number of components in one ligature (including first component) */
        public int getMaxComponents() {
            return maxComponents;
        }

        /** {@inheritDoc} */
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("{ligs={");
            for (int i = 0, n = ligatures.length; i < n; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(ligatures[i]);
            }
            sb.append("}}");
            return sb.toString();
        }

    }

}