(OTF_check_features): Even if failed in getting features, if all
[m17n/libotf.git] / src / otfopen.c
1 /* otfopen.c -- OpenType font reader.
2
3 Copyright (C) 2003, 2004, 2005
4   National Institute of Advanced Industrial Science and Technology (AIST)
5   Registration Number H15PRO167
6
7 This file is part of libotf.
8
9 Libotf is free software; you can redistribute it and/or modify it
10 under the terms of the GNU Lesser General Public License as published
11 by the Free Software Foundation; either version 2.1 of the License, or
12 (at your option) any later version.
13
14 Libotf is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library, in a file named COPYING; if not,
21 write to the Free Software Foundation, Inc., 59 Temple Place, Suite
22 330, Boston, MA 02111-1307, USA.  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <config.h>
28
29 #include "otf.h"
30 #include "otferror.h"
31
32 /***
33     Table of contents (almost parallel to otf.h):
34
35     (0) Stream handler
36
37     (1) Readers for OTF Layout tables and OTF itself
38     (1-1) Basic types and functions
39     (1-2) "head" table
40     (1-3) "name" table
41     (1-4) "cmap" table
42     (1-5) Structures common to GDEF, GSUB, and GPOS
43     (1-6) "GDEF" table
44     (1-7) Structures for ScriptList, FeatureList, and LookupList
45     (1-8) Structures common to GSUB and GPOS
46     (1-9) "GSUB" table
47     (1-10) "GPOS" table
48     (1-11) Structure for OTF
49
50     (2) API for reading OTF
51     (2-1) OTF_open()
52     (2-2) OTF_close()
53     (2-3) OTF_get_table()
54     (2-4) OTF_check_table()
55
56     (5) API miscellaneous
57 */
58 \f
59 /* (0) Stream handler
60
61    Example of typical usage of OTF_Stream.
62
63     {
64       OTF_Stream *stream;
65       OTF_StreamState state;
66       int offset, nbytes;
67
68       OPEN_STREAM (_FILE_NAME_, stream);
69       if (! stream)
70         _ERROR_;
71       SETUP_STREAM (stream, fp, 0, 256, _NAME_);
72       offset = READ_OFFSET (stream);
73       nbytes = READ_ULONG (stream);
74       SETUP_STREAM (stream, fp, offset, nbytes, _NAME2_);
75       ...;
76       CLOSE_STREAM (stream);
77     }
78
79 */
80
81 typedef struct
82 {
83   FILE *fp;
84   char *name;
85   long pos;
86   long bufsize;
87   long allocated;
88   unsigned char *buf;
89 } OTF_Stream;
90
91 typedef long OTF_StreamState;
92
93 OTF_Stream *
94 make_stream ()
95 {
96   OTF_Stream *stream;
97   char *errfmt = "stream creation%s";
98   void *errret = NULL;
99
100   stream = calloc (1, sizeof (OTF_Stream));
101   if (! stream)
102     OTF_ERROR (OTF_ERROR_MEMORY, "");
103   return stream;
104 }
105
106 int
107 setup_stream (OTF_Stream *stream, FILE *fp, long offset, int nbytes,
108               char *name)
109 {
110   char *errfmt = "stream setup for %s";
111   int errret = -1;
112
113   stream->name = name;
114   stream->pos = 0;
115   if (stream->allocated < nbytes)
116     {
117       unsigned char *buf = malloc (nbytes);
118
119       if (! buf)
120         OTF_ERROR (OTF_ERROR_MEMORY, stream->name);
121       if (stream->buf)
122         free (stream->buf);
123       stream->buf = buf;
124       stream->allocated = nbytes;
125     }
126   stream->bufsize = nbytes;
127   if (fseek (fp, offset, SEEK_SET) < 0)
128     OTF_ERROR (OTF_ERROR_FILE, stream->name);
129   if (fread (stream->buf, 1, nbytes, fp) != nbytes)
130     OTF_ERROR (OTF_ERROR_FILE, stream->name);
131   return 0;
132 }
133
134
135 void
136 free_stream (OTF_Stream *stream)
137 {
138   free (stream->buf);
139   free (stream);
140 }
141
142 #define SAVE_STREAM(stream, state) ((state) = (stream)->pos)
143 #define RESTORE_STREAM(stream, state) ((stream)->pos = (state))
144 #define SEEK_STREAM(stream, offset) ((stream)->pos = (offset))
145
146 #define STREAM_CHECK_SIZE(stream, size)                 \
147   if ((stream)->pos + (size) > (stream)->bufsize)       \
148     {                                                   \
149       char *errfmt = "buffer overrun in %s";            \
150                                                         \
151       OTF_ERROR (OTF_ERROR_TABLE, (stream)->name);      \
152       return errret;                                    \
153     }                                                   \
154   else
155
156
157 #define READ_USHORT(stream, var)                        \
158   do {                                                  \
159     STREAM_CHECK_SIZE ((stream), 2);                    \
160     (var) = (((stream)->buf[(stream)->pos] << 8)        \
161              | (stream)->buf[(stream)->pos + 1]);       \
162     (stream)->pos += 2;                                 \
163   } while (0)
164
165 #define READ_SHORT(stream, var)                                 \
166   do {                                                          \
167     STREAM_CHECK_SIZE ((stream), 2);                            \
168     (var) = (short) (((stream)->buf[(stream)->pos] << 8)        \
169                      | (stream)->buf[(stream)->pos + 1]);       \
170     (stream)->pos += 2;                                         \
171   } while (0)
172
173 #define READ_ULONG(stream, var)                         \
174   do {                                                  \
175     STREAM_CHECK_SIZE ((stream), 4);                    \
176     (var) = (((stream)->buf[(stream)->pos] << 24)       \
177              | ((stream)->buf[(stream)->pos + 1] << 16) \
178              | ((stream)->buf[(stream)->pos + 2] << 8)  \
179              | (stream)->buf[(stream)->pos + 3]);       \
180     (stream)->pos += 4;                                 \
181   } while (0)
182
183 #define READ_LONG(stream, var)                                  \
184   do {                                                          \
185     STREAM_CHECK_SIZE ((stream), 4);                            \
186     (var) = (int) (((stream)->buf[(stream)->pos] << 24)         \
187                    | ((stream)->buf[(stream)->pos + 1] << 16)   \
188                    | ((stream)->buf[(stream)->pos + 2] << 8)    \
189                    | (stream)->buf[(stream)->pos + 3]);         \
190     (stream)->pos += 4;                                         \
191   } while (0)
192
193
194 #define READ_FIXED(stream, fixed)               \
195   do {                                          \
196     READ_USHORT ((stream), (fixed).high);       \
197     READ_USHORT ((stream), (fixed).low);        \
198   } while (0)
199
200
201 #define READ_BYTES(stream, p, nbytes)                           \
202   do {                                                          \
203     STREAM_CHECK_SIZE ((stream), (nbytes));                     \
204     memcpy ((p), (stream)->buf + (stream)->pos, (nbytes));      \
205     (stream)->pos += (nbytes);                                  \
206   } while (0)
207
208
209 #define READ_TAG READ_ULONG
210 #define READ_OFFSET READ_USHORT
211 #define READ_UINT16 READ_USHORT
212 #define READ_INT16 READ_SHORT
213 #define READ_GLYPHID READ_USHORT
214
215 \f
216 /*** (1) Structures for OTF Layout tables and OTF itself */
217
218 /*** (1-1) Basic types and functions */
219
220 enum OTF_TableType
221   {
222     OTF_TABLE_TYPE_HEAD,
223     OTF_TABLE_TYPE_NAME,
224     OTF_TABLE_TYPE_CMAP,
225     OTF_TABLE_TYPE_GDEF,
226     OTF_TABLE_TYPE_GSUB,
227     OTF_TABLE_TYPE_GPOS,
228     OTF_TABLE_TYPE_MAX
229   };
230
231 #define OTF_MEMORY_RECORD_SIZE 1024
232
233 struct OTF_MemoryRecord
234 {
235   int used;
236   void *memory[OTF_MEMORY_RECORD_SIZE];
237   struct OTF_MemoryRecord *next;
238 };
239
240 typedef struct OTF_MemoryRecord OTF_MemoryRecord;
241
242 enum OTF_ReaderFlag
243   {
244     OTF_READ_FULL,
245     OTF_READ_SCRIPTS,
246     OTF_READ_FEATURES,
247     OTF_READ_MAX
248   };
249
250 struct _OTF_TableInfo;
251 typedef struct _OTF_TableInfo OTF_TableInfo;
252
253 struct _OTF_TableInfo
254 {
255   /* Points to one of OTF->head, OTF->name, etc.  */
256   void **address;
257   /* Function to read one of OTF tables.  */
258   void *(*reader) (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag);
259   /* Stream given to <reader>.  */
260   OTF_Stream *stream;
261 };
262
263 struct OTF_InternalData
264 {
265   /* Information about each OTF table.  */
266   OTF_TableInfo table_info[OTF_TABLE_TYPE_MAX];
267
268   /* Stream used to read the header part of OTF.  */
269   OTF_Stream *header_stream;
270
271   /* Records of allocated memories.  */
272   OTF_MemoryRecord *memory_record;
273 };
274
275
276 static OTF_MemoryRecord *
277 allocate_memory_record (OTF *otf)
278 {
279   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
280   OTF_MemoryRecord *memrec = malloc (sizeof (OTF_MemoryRecord));
281
282   if (! memrec)
283     return NULL;
284   memrec->used = 0;
285   memrec->next = internal_data->memory_record;
286   internal_data->memory_record = memrec;
287   return memrec;
288 }
289
290 /* Memory allocation macros.  */
291
292 #define OTF_MALLOC(p, size, arg)                                        \
293   do {                                                                  \
294     if (size == 0)                                                      \
295       (p) = NULL;                                                       \
296     else                                                                \
297       {                                                                 \
298         OTF_MemoryRecord *memrec                                        \
299           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
300         (p) = malloc (sizeof (*(p)) * (size));                          \
301         if (! (p)                                                       \
302             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
303                 && ! (memrec = allocate_memory_record (otf))))          \
304           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
305         memrec->memory[memrec->used++] = (p);                           \
306       }                                                                 \
307   } while (0)
308
309
310 #define OTF_CALLOC(p, size, arg)                                        \
311   do {                                                                  \
312     if (size == 0)                                                      \
313       (p) = NULL;                                                       \
314     else                                                                \
315       {                                                                 \
316         OTF_MemoryRecord *memrec                                        \
317           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
318         (p) = calloc ((size), sizeof (*(p)));                           \
319         if (! (p)                                                       \
320             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
321                 && ! (memrec = allocate_memory_record (otf))))          \
322           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
323         memrec->memory[memrec->used++] = (p);                           \
324       }                                                                 \
325   } while (0)
326
327 \f
328 /*** (1-2) "head" table */
329
330 static void *
331 read_head_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
332 {
333   OTF_Stream *stream = table->stream;
334   char *errfmt = "head%s";
335   void *errret = NULL;
336   OTF_head *head;
337
338   OTF_CALLOC (head, 1, "");
339   READ_FIXED (stream, head->TableVersionNumber);
340   READ_FIXED (stream, head->fontRevision);
341   READ_ULONG (stream, head->checkSumAdjustment);
342   READ_ULONG (stream, head->magicNumber);
343   READ_USHORT (stream, head->flags);
344   READ_USHORT (stream, head->unitsPerEm);
345
346   *table->address = head;
347   return head;
348 }
349
350 \f
351 /*** (1-3) "name" table */
352
353 static int
354 read_name (OTF *otf, OTF_Stream *stream, OTF_NameRecord *rec)
355 {
356   char *errfmt = "nameID (%d)";
357   int errret = -1;
358   OTF_StreamState state;
359   int ucs = 0;
360   int ascii = 0;
361   int i;
362
363   if (rec->platformID == 0)
364     ucs = (rec->encodingID <= 3) ? 2 : 4;
365   else if (rec->platformID == 1 && rec->encodingID == 0)
366     ascii = 1;
367   else if (rec->platformID == 3)
368     ucs = (rec->encodingID == 1  ? 2
369            : rec->encodingID == 10 ? 4
370            : 0);
371
372   OTF_MALLOC (rec->name, rec->length + 1, (void *) rec->nameID);
373   SAVE_STREAM (stream, state);
374   SEEK_STREAM (stream, stream->pos + rec->offset);
375   READ_BYTES (stream, rec->name, rec->length);
376   RESTORE_STREAM (stream, state);
377   rec->name[rec->length] = 0;
378
379   if (ascii)
380     {
381       rec->ascii = 1;
382     }
383   else if (ucs == 2)
384     {
385       rec->ascii = 1;
386       for (i = 0; i < rec->length / 2; i++)
387         {
388           if (rec->name[i * 2] > 0
389               || rec->name[i * 2 + 1] >= 128)
390             {
391               rec->ascii = 0;
392               break;
393             }
394         }
395       if (rec->ascii)
396         for (i = 0; i < rec->length / 2; i++)
397           rec->name[i] = rec->name[i * 2 + 1];
398       rec->name[i] = 0;
399     }
400   else if (ucs == 4)
401     {
402       rec->ascii = 1;
403       for (i = 0; i < rec->length / 4; i++)
404         {
405           if (rec->name[i * 4] > 0
406               || rec->name[i * 4 + 1] > 0
407               || rec->name[i * 4 + 2] > 0
408               || rec->name[i * 2 + 3] >= 128)
409             {
410               rec->ascii = 0;
411               break;
412             }
413         }
414       if (rec->ascii)
415         for (i = 0; i < rec->length / 4; i++)
416           rec->name[i] = rec->name[i * 4 + 3];
417       rec->name[i] = 0;
418     }
419
420   return 0;
421 }
422
423 static void *
424 read_name_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
425 {
426   OTF_Stream *stream = table->stream;
427   char *errfmt = "name%s";
428   void *errret = NULL;
429   OTF_name *name;
430   int i;
431
432   OTF_CALLOC (name, 1, "");
433   READ_USHORT (stream, name->format);
434   READ_USHORT (stream, name->count);
435   READ_USHORT (stream, name->stringOffset);
436   OTF_MALLOC (name->nameRecord, name->count, "");
437   for (i = 0; i < name->count; i++)
438     {
439       OTF_NameRecord *rec = name->nameRecord + i;
440
441       READ_USHORT (stream, rec->platformID);
442       READ_USHORT (stream, rec->encodingID);
443       READ_USHORT (stream, rec->languageID);
444       READ_USHORT (stream, rec->nameID);
445       READ_USHORT (stream, rec->length);
446       READ_USHORT (stream, rec->offset);
447     }
448   for (i = 0; i < name->count; i++)
449     {
450       OTF_NameRecord *rec = name->nameRecord + i;
451       int nameID = rec->nameID;
452
453       read_name (otf, stream, rec);
454
455       if (nameID >= OTF_max_nameID)
456         continue;
457       if (! name->name[nameID]
458           && rec->ascii)
459         name->name[nameID] = (char *) rec->name;
460     }
461
462   *table->address = name;
463   return name;
464 }
465
466 \f
467 /*** (1-4) "cmap" table */
468
469 static void *
470 read_cmap_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
471 {
472   OTF_Stream *stream = table->stream;
473   char *errfmt = "cmap%s";
474   void *errret = NULL;
475   OTF_cmap *cmap;
476   int unicode_bmp_index = -1, unicode_full_index = -1;
477   int i;
478
479   OTF_CALLOC (cmap, 1, "");
480   READ_USHORT (stream, cmap->version);
481   READ_USHORT (stream, cmap->numTables);
482   OTF_MALLOC (cmap->EncodingRecord, cmap->numTables, "");
483   for (i = 0; i < cmap->numTables; i++)
484     {
485       unsigned platformID, encodingID;
486
487       READ_USHORT (stream, platformID);
488       cmap->EncodingRecord[i].platformID = platformID;
489       READ_USHORT (stream, encodingID);
490       cmap->EncodingRecord[i].encodingID = encodingID;
491       READ_ULONG (stream, cmap->EncodingRecord[i].offset);
492       if (platformID == 0)
493         {
494           if (encodingID <= 3)
495             unicode_bmp_index = i;
496           else
497             unicode_full_index = i;
498         }
499       else if (platformID == 3)
500         {
501           if (encodingID == 1)
502             unicode_bmp_index = i;
503           else if (encodingID == 10)
504             unicode_full_index = i;
505         }
506     }
507   for (i = 0; i < cmap->numTables; i++)
508     {
509       unsigned format;
510
511       SEEK_STREAM (stream, cmap->EncodingRecord[i].offset);
512       READ_USHORT (stream, format);
513       cmap->EncodingRecord[i].subtable.format = format;
514       READ_USHORT (stream, cmap->EncodingRecord[i].subtable.length);
515       if (format == 8 || format == 10 || format == 12)
516         {
517           READ_ULONG (stream, cmap->EncodingRecord[i].subtable.length);
518           READ_ULONG (stream, cmap->EncodingRecord[i].subtable.language);
519         }
520       else
521         {
522           READ_USHORT (stream, cmap->EncodingRecord[i].subtable.language);
523         }
524       switch (format)
525         {
526         case 0:
527           {
528             OTF_MALLOC (cmap->EncodingRecord[i].subtable.f.f0, 1,
529                         " (EncodingRecord)");
530             READ_BYTES (stream,
531                         cmap->EncodingRecord[i].subtable.f.f0->glyphIdArray,
532                         256);
533           }
534           break;
535
536         case 2:
537           {
538             OTF_EncodingSubtable2 *sub2;
539             int j, max_key;
540
541             OTF_MALLOC (sub2, 1, " (EncodingSubtable2)");
542             cmap->EncodingRecord[i].subtable.f.f2 = sub2;
543             for (j = 0, max_key = 0; j < 256; j++)
544               {
545                 READ_USHORT (stream, sub2->subHeaderKeys[j]);
546                 if (max_key < sub2->subHeaderKeys[j])
547                   max_key = sub2->subHeaderKeys[j];
548               }
549             max_key += 8;
550             sub2->subHeaderCount = max_key / 8;
551             OTF_MALLOC (sub2->subHeaders, max_key / 8, " (subHeaders)");
552             for (j = 0; j < sub2->subHeaderCount; j++)
553               {
554                 READ_USHORT (stream, sub2->subHeaders[j].firstCode);
555                 READ_USHORT (stream, sub2->subHeaders[j].entryCount);
556                 READ_SHORT (stream, sub2->subHeaders[j].idDelta);
557                 READ_USHORT (stream, sub2->subHeaders[j].idRangeOffset);
558                 /* Make it offset from sub2->glyphIndexArray.  */
559                 sub2->subHeaders[j].idRangeOffset -= max_key - (j * 8 + 6);
560               }
561             sub2->glyphIndexCount = (cmap->EncodingRecord[i].subtable.length
562                                      - 262 - max_key);
563             OTF_MALLOC (sub2->glyphIndexArray, sub2->glyphIndexCount,
564                         " (glyphIndexArray)");
565             READ_BYTES (stream, sub2->glyphIndexArray, sub2->glyphIndexCount);
566           }
567           break;
568
569         case 4:
570           {
571             OTF_EncodingSubtable4 *sub4;
572             int segCount;
573             int j;
574             unsigned dummy;
575
576             OTF_MALLOC (sub4, 1, " (EncodingSubtable4)");
577             cmap->EncodingRecord[i].subtable.f.f4 = sub4;
578             READ_USHORT (stream, sub4->segCountX2);
579             segCount = sub4->segCountX2 / 2;
580             READ_USHORT (stream, sub4->searchRange);
581             READ_USHORT (stream, sub4->entrySelector);
582             READ_USHORT (stream, sub4->rangeShift);
583             OTF_MALLOC (sub4->segments, segCount, " (segCount)");
584             for (j = 0; j < segCount; j++)
585               READ_USHORT (stream, sub4->segments[j].endCount);
586             READ_USHORT (stream, dummy);
587             for (j = 0; j < segCount; j++)
588               READ_USHORT (stream, sub4->segments[j].startCount);
589             for (j = 0; j < segCount; j++)
590               READ_SHORT (stream, sub4->segments[j].idDelta);
591             for (j = 0; j < segCount; j++)
592               {
593                 unsigned off;
594                 unsigned rest = 2 * (segCount - j);
595                 
596                 READ_USHORT (stream, off);
597                 if (off == 0)
598                   sub4->segments[j].idRangeOffset = 0xFFFF;
599                 else
600                   sub4->segments[j].idRangeOffset = (off - rest) / 2;
601               }
602             j = (cmap->EncodingRecord[i].subtable.length
603                  - (14 + 2 * (segCount * 4 + 1)));
604             sub4->GlyphCount = j / 2;
605             OTF_MALLOC (sub4->glyphIdArray, sub4->GlyphCount, " (GlyphCount)");
606             for (j = 0; j < sub4->GlyphCount; j++)
607               READ_USHORT (stream, sub4->glyphIdArray[j]);
608           }
609           break;
610
611         case 6:
612           {
613             OTF_EncodingSubtable6 *sub6;
614             int j;
615
616             OTF_MALLOC (sub6, 1, " (EncodingSubtable6)");
617             cmap->EncodingRecord[i].subtable.f.f6 = sub6;
618             READ_USHORT (stream, sub6->firstCode);
619             READ_USHORT (stream, sub6->entryCount);
620             OTF_MALLOC (sub6->glyphIdArray, sub6->entryCount, " (GlyphCount)");
621             for (j = 0; j < sub6->entryCount; j++)
622               READ_USHORT (stream, sub6->glyphIdArray[j]);
623           }
624           break;
625
626         case 8:
627           {
628             OTF_EncodingSubtable8 *sub8;
629             int j;
630
631             OTF_MALLOC (sub8, 1, " (EncodingSubtable8)");
632             cmap->EncodingRecord[i].subtable.f.f8 = sub8;
633             for (j = 0; j < 8192; j++)
634               READ_BYTES (stream, sub8->is32, 8192);
635             READ_ULONG (stream, sub8->nGroups);
636             OTF_MALLOC (sub8->Groups, sub8->nGroups, " (Groups)");
637             for (j = 0; j < sub8->nGroups; j++)
638               {
639                 READ_ULONG (stream, sub8->Groups[i].startCharCode);
640                 READ_ULONG (stream, sub8->Groups[i].endCharCode);
641                 READ_ULONG (stream, sub8->Groups[i].startGlyphID);
642               }
643           }
644           break;
645
646         case 10:
647           {
648             OTF_EncodingSubtable10 *sub10;
649             int j;
650
651             OTF_MALLOC (sub10, 1, " (EncodingSubtable10)");
652             cmap->EncodingRecord[i].subtable.f.f10 = sub10;
653             READ_ULONG (stream, sub10->startCharCode);
654             READ_ULONG (stream, sub10->numChars);
655             OTF_MALLOC (sub10->glyphs, sub10->numChars, " (GlyphCount)");
656             for (j = 0; j < sub10->numChars; j++)
657               READ_USHORT (stream, sub10->glyphs[j]);
658           }
659           break;
660
661         case 12:
662           {
663             OTF_EncodingSubtable12 *sub12;
664             int j;
665
666             OTF_MALLOC (sub12, 1, " (EncodingSubtable12)");
667             cmap->EncodingRecord[i].subtable.f.f12 = sub12;
668             READ_ULONG (stream, sub12->nGroups);
669             OTF_MALLOC (sub12->Groups, sub12->nGroups, " (Groups)");
670             for (j = 0; j < sub12->nGroups; j++)
671               {
672                 READ_ULONG (stream, sub12->Groups[i].startCharCode);
673                 READ_ULONG (stream, sub12->Groups[i].endCharCode);
674                 READ_ULONG (stream, sub12->Groups[i].startGlyphID);
675               }
676           }
677           break;
678
679         default:
680           OTF_ERROR (OTF_ERROR_TABLE, " (invalid Subtable format)");
681         }
682     }
683
684   if (unicode_bmp_index >= 0)
685     {
686       OTF_EncodingRecord *rec = cmap->EncodingRecord + unicode_bmp_index;
687       OTF_GlyphID glyph_id, max_glyph_id = 0;
688
689       OTF_CALLOC (cmap->unicode_table, 0x10000, "");
690       switch (rec->subtable.format)
691         {
692         case 4:
693           {
694             OTF_EncodingSubtable4 *sub4 = rec->subtable.f.f4;
695             int segCount = sub4->segCountX2 / 2;
696
697             for (i = 0; i < segCount; i++)
698               {
699                 OTF_cmapSegument *seg = sub4->segments + i;
700                 int c;
701
702                 if (seg->idRangeOffset == 0xFFFF)
703                   for (c = seg->startCount; c <= seg->endCount; c++)
704                     {
705                       glyph_id = c + seg->idDelta;
706                       cmap->unicode_table[c] = glyph_id;
707                       if (glyph_id > max_glyph_id)
708                         max_glyph_id = glyph_id;
709                     }
710                 else
711                   for (c = seg->startCount; c <= seg->endCount && c != 0xFFFF;
712                        c++)
713                     {
714                       glyph_id = sub4->glyphIdArray[seg->idRangeOffset
715                                                     + (c - seg->startCount)];
716                       cmap->unicode_table[c] = glyph_id;
717                       if (glyph_id > max_glyph_id)
718                         max_glyph_id = glyph_id;
719                     }
720               }
721           }
722         }
723
724       OTF_CALLOC (cmap->decode_table, max_glyph_id + 1, "");
725       for (i = 0; i < 0x10000; i++)
726         if (cmap->unicode_table[i])
727           cmap->decode_table[cmap->unicode_table[i]] = i;
728       cmap->max_glyph_id = max_glyph_id;
729     }
730
731   *table->address = cmap;
732   return cmap;
733 }
734
735 \f
736 /*** (1-5) Structures common to GDEF, GSUB, and GPOS */
737
738 /* Read Glyph-IDs from STREAM.  Allocate memory for IDS, and store the
739    Glyph-IDs there.  If COUNT is negative, read the number of
740    Glyphs-IDs at first.  MINUS if nozero is how few the actual
741    Glyph-IDs are in STREAM than COUNT.  */
742
743 static int
744 read_glyph_ids (OTF *otf, OTF_Stream *stream, OTF_GlyphID **ids,
745                 int minus, int count)
746 {
747   char *errfmt = "GlyphID List%s";
748   int errret = -1;
749   int i;
750
751   if (count < 0)
752     READ_UINT16 (stream, count);
753   if (! count)
754     return 0;
755   OTF_MALLOC (*ids, count, "");
756   for (i = 0; i < count + minus; i++)
757     READ_GLYPHID (stream, (*ids)[i]);
758   return count;
759 }
760
761 static unsigned
762 read_range_records (OTF *otf, OTF_Stream *stream, OTF_RangeRecord **record)
763 {
764   char *errfmt = "RangeRecord%s";
765   unsigned errret = 0;
766   unsigned count;
767   int i;
768
769   READ_UINT16 (stream, count);
770   if (! count)
771     return 0;
772   OTF_MALLOC (*record, count, "");
773   for (i = 0; i < count; i++)
774     {
775       READ_GLYPHID (stream, (*record)[i].Start);
776       READ_GLYPHID (stream, (*record)[i].End);
777       READ_UINT16 (stream, (*record)[i].StartCoverageIndex);
778     }
779   return count;
780 }
781
782
783 static int
784 read_coverage (OTF *otf, OTF_Stream *stream, long offset,
785                OTF_Coverage *coverage)
786 {
787   char *errfmt = "Coverage%s";
788   int errret = -1;
789   OTF_StreamState state;
790   int count;
791
792   READ_OFFSET (stream, coverage->offset);
793   SAVE_STREAM (stream, state);
794   SEEK_STREAM (stream, offset + coverage->offset);
795   READ_UINT16 (stream, coverage->CoverageFormat);
796   if (coverage->CoverageFormat == 1)
797     count = read_glyph_ids (otf, stream, &coverage->table.GlyphArray, 0, -1);
798   else if (coverage->CoverageFormat == 2)
799     count = read_range_records (otf, stream, &coverage->table.RangeRecord);
800   else
801     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid Format)");
802   if (count < 0)
803     return -1;
804   coverage->Count = (unsigned) count;
805   RESTORE_STREAM (stream, state);
806   return 0;
807 }
808
809 /* Read list of Coverages from STREAM.  Allocate memory for COVERAGE,
810    and store the Coverages there.  If COUNT is negative, read the
811    number of Coverages at first.  */
812
813 static int
814 read_coverage_list (OTF *otf, OTF_Stream *stream, long offset,
815                     OTF_Coverage **coverage, int count)
816 {
817   char *errfmt = "Coverage List%s";
818   int errret = -1;
819   int i;
820
821   if (count < 0)
822     READ_UINT16 (stream, count);
823   if (! count)
824     return 0;
825   OTF_MALLOC (*coverage, count, "");
826   for (i = 0; i < count; i++)
827     if (read_coverage (otf, stream, offset, (*coverage) + i) < 0)
828       return -1;
829   return count;
830 }
831
832
833 static int
834 read_class_def_without_offset (OTF *otf, OTF_Stream *stream,
835                                OTF_ClassDef *class)
836 {
837   char *errfmt = "ClassDef%s";
838   int errret = -1;
839
840   SEEK_STREAM (stream, class->offset);
841   READ_UINT16 (stream, class->ClassFormat);
842   if (class->ClassFormat == 1)
843     {
844       READ_GLYPHID (stream, class->f.f1.StartGlyph);
845       class->f.f1.GlyphCount
846         = (read_glyph_ids
847            (otf, stream, (OTF_GlyphID **) &class->f.f1.ClassValueArray, 0, -1));
848       if (! class->f.f1.GlyphCount)
849         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
850     }
851   else if (class->ClassFormat == 2)
852     {
853       class->f.f2.ClassRangeCount
854         = (read_range_records
855            (otf, stream, (OTF_RangeRecord **) &class->f.f2.ClassRangeRecord));
856       if (! class->f.f2.ClassRangeCount)
857         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
858     }
859   else
860     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
861   return 0;
862 }
863
864
865 static int
866 read_class_def (OTF *otf, OTF_Stream *stream, long offset, OTF_ClassDef *class)
867 {
868   char *errfmt = "ClassDef%s";
869   int errret = -1;
870   OTF_StreamState state;
871
872   READ_OFFSET (stream, class->offset);
873   if (! class->offset)
874     return 0;
875   SAVE_STREAM (stream, state);
876   SEEK_STREAM (stream, offset + class->offset);
877   READ_UINT16 (stream, class->ClassFormat);
878   if (class->ClassFormat == 1)
879     {
880       READ_GLYPHID (stream, class->f.f1.StartGlyph);
881       class->f.f1.GlyphCount
882         = read_glyph_ids (otf, stream,
883                           (OTF_GlyphID **) &class->f.f1.ClassValueArray,
884                           0, -1);
885       if (! class->f.f1.GlyphCount)
886         return -1;
887     }
888   else if (class->ClassFormat == 2)
889     {
890       class->f.f2.ClassRangeCount
891         = read_range_records (otf, stream,
892                               (OTF_RangeRecord **)
893                               &class->f.f2.ClassRangeRecord);
894       if (! class->f.f2.ClassRangeCount)
895         return -1;
896     }
897   else
898     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
899
900   RESTORE_STREAM (stream, state);
901   return 0;
902 }
903
904
905 static int
906 read_device_table (OTF *otf, OTF_Stream *stream, long offset,
907                    OTF_DeviceTable *table)
908 {
909   char *errfmt = "Device Table%s";
910   int errret = -1;
911
912   int num, i;
913   unsigned val;
914   struct {
915     int int2 : 2;
916     int int4 : 4;
917     int int8 : 8;
918   } intval;
919
920   SEEK_STREAM (stream, offset + table->offset);
921   READ_UINT16 (stream, table->StartSize);
922   READ_UINT16 (stream, table->EndSize);
923   READ_UINT16 (stream, table->DeltaFormat);
924   num = table->EndSize - table->StartSize + 1;
925   OTF_MALLOC (table->DeltaValue, num, "");
926
927   if (table->DeltaFormat == 1)
928     for (i = 0; i < num; i++)
929       {
930         if ((i % 8) == 0)
931           READ_UINT16 (stream, val);
932         intval.int2 = (val >> (14 - (i % 8) * 2)) & 0x03;
933         table->DeltaValue[i] = intval.int2;
934       }
935   else if (table->DeltaFormat == 2)
936     for (i = 0; i < num; i++)
937       {
938         if ((i % 4) == 0)
939           READ_UINT16 (stream, val);
940         intval.int4 = (val >> (12 - (i % 4) * 4)) & 0x0F;
941         table->DeltaValue[i] = intval.int4;
942       }
943   else if (table->DeltaFormat == 3)
944     for (i = 0; i < num; i++)
945       {
946         if ((i % 2) == 0)
947           {
948             READ_UINT16 (stream, val);
949             intval.int8 = val >> 8;
950             table->DeltaValue[i] = intval.int8;
951           }
952         else
953           {
954             intval.int8 = val >> 8;
955             table->DeltaValue[i] = intval.int8;
956           }
957       }
958   else
959     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
960   return 0;
961 }
962
963 \f
964 /*** (1-6) "GDEF" table */
965
966 static int
967 read_attach_list (OTF *otf, OTF_Stream *stream, long offset,
968                   OTF_AttachList *list)
969 {
970   char *errfmt = "AttachList%s";
971   int errret = -1;
972   int i, j;
973
974   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
975     return -1;
976   READ_UINT16 (stream, list->GlyphCount);
977   OTF_MALLOC (list->AttachPoint, list->GlyphCount, "");
978   for (i = 0; i < list->GlyphCount; i++)
979     READ_OFFSET (stream, list->AttachPoint[i].offset);
980   for (i = 0; i < list->GlyphCount; i++)
981     {
982       int count;
983
984       SEEK_STREAM (stream, offset + list->AttachPoint[i].offset);
985       READ_UINT16 (stream, count);
986       list->AttachPoint[i].PointCount = count;
987       OTF_MALLOC (list->AttachPoint[i].PointIndex, count, " (PointIndex)");
988       for (j = 0; j < count; j++)
989         READ_UINT16 (stream, list->AttachPoint[i].PointIndex[j]);
990     }
991   return 0;
992 }
993
994 static int
995 read_caret_value (OTF *otf, OTF_Stream *stream, long offset,
996                   OTF_CaretValue *caret)
997 {
998   char *errfmt = "CaretValue%s";
999   int errret = -1;
1000
1001   SEEK_STREAM (stream, offset + caret->offset);
1002   READ_UINT16 (stream, caret->CaretValueFormat);
1003   if (caret->CaretValueFormat == 1)
1004     READ_INT16 (stream, caret->f.f1.Coordinate);
1005   else if (caret->CaretValueFormat == 2)
1006     READ_UINT16 (stream, caret->f.f2.CaretValuePoint);
1007   else if (caret->CaretValueFormat == 3)
1008     {
1009       READ_INT16 (stream, caret->f.f3.Coordinate);
1010       if (read_device_table (otf, stream, offset + caret->offset,
1011                              &caret->f.f3.DeviceTable) < 0)
1012         return -1;
1013     }
1014   else
1015     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
1016   return 0;
1017 }
1018
1019 static int
1020 read_lig_caret_list (OTF *otf, OTF_Stream *stream, long offset,
1021                      OTF_LigCaretList *list)
1022 {
1023   char *errfmt = "LigCaretList%s";
1024   int errret = -1;
1025   int i, j;
1026
1027   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
1028     return -1;
1029   READ_UINT16 (stream, list->LigGlyphCount);
1030   OTF_MALLOC (list->LigGlyph, list->LigGlyphCount, "");
1031   for (i = 0; i < list->LigGlyphCount; i++)
1032     READ_OFFSET (stream, list->LigGlyph[i].offset);
1033   for (i = 0; i < list->LigGlyphCount; i++)
1034     {
1035       int count;
1036
1037       SEEK_STREAM (stream, offset + list->LigGlyph[i].offset);
1038       READ_UINT16 (stream, count);
1039       list->LigGlyph[i].CaretCount = count;
1040       OTF_MALLOC (list->LigGlyph[i].CaretValue, count, " (CaretValue)");
1041       for (j = 0; j < count; j++)
1042         READ_OFFSET (stream, list->LigGlyph[i].CaretValue[j].offset);
1043       for (j = 0; j < count; j++)
1044         if (read_caret_value (otf, stream, offset + list->LigGlyph[i].offset,
1045                               &list->LigGlyph[i].CaretValue[j]) < 0)
1046           return -1;
1047     }
1048   return 0;
1049 }
1050
1051 static int
1052 read_gdef_header (OTF_Stream *stream, OTF_GDEFHeader *header)
1053 {
1054   int errret = -1;
1055
1056   READ_FIXED (stream, header->Version);
1057   READ_OFFSET (stream, header->GlyphClassDef);
1058   READ_OFFSET (stream, header->AttachList);
1059   READ_OFFSET (stream, header->LigCaretList);
1060   READ_OFFSET (stream, header->MarkAttachClassDef);
1061   return 0;
1062 }
1063
1064 static void *
1065 read_gdef_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
1066 {
1067   OTF_Stream *stream = table->stream;
1068   char *errfmt = "GDEF%s";
1069   void *errret = NULL;
1070   OTF_GDEF *gdef;
1071
1072   OTF_CALLOC (gdef, 1, "");
1073   read_gdef_header (stream, (OTF_GDEFHeader *) &gdef->header);
1074   if (gdef->header.GlyphClassDef)
1075     {
1076       gdef->glyph_class_def.offset = gdef->header.GlyphClassDef;
1077       read_class_def_without_offset (otf, stream, &gdef->glyph_class_def);
1078     }
1079   if (gdef->header.AttachList)
1080     read_attach_list (otf, stream, gdef->header.AttachList,
1081                       &gdef->attach_list);
1082   if (gdef->header.LigCaretList)
1083     read_lig_caret_list (otf, stream, gdef->header.LigCaretList,
1084                          &gdef->lig_caret_list);
1085   if (gdef->header.MarkAttachClassDef)
1086     {
1087       gdef->mark_attach_class_def.offset = gdef->header.MarkAttachClassDef;
1088       read_class_def_without_offset (otf, stream, &gdef->mark_attach_class_def);
1089     }
1090
1091   *table->address = gdef;
1092   return gdef;
1093 }
1094
1095 \f
1096 /*** (1-7) Structures for ScriptList, FeatureList, and LookupList */
1097
1098 static int
1099 read_script_list (OTF *otf, OTF_Stream *stream, long offset,
1100                   OTF_ScriptList *list)
1101 {
1102   char *errfmt = "Script List%s";
1103   int errret = -1;
1104   int i, j, k;
1105
1106   SEEK_STREAM (stream, offset);
1107   READ_USHORT (stream, list->ScriptCount);
1108   OTF_CALLOC (list->Script, list->ScriptCount, "");
1109
1110   for (i = 0; i < list->ScriptCount; i++)
1111     {
1112       READ_TAG (stream, list->Script[i].ScriptTag);
1113       READ_OFFSET (stream, list->Script[i].offset);
1114     }
1115   for (i = 0;  i < list->ScriptCount; i++)
1116     {
1117       OTF_Script *script = list->Script + i;
1118       long script_offset = offset + script->offset;
1119
1120       SEEK_STREAM (stream, script_offset);
1121       READ_OFFSET (stream, script->DefaultLangSysOffset);
1122       READ_USHORT (stream, script->LangSysCount);
1123       OTF_MALLOC (script->LangSysRecord, script->LangSysCount, " (LangSys)");
1124       OTF_CALLOC (script->LangSys, script->LangSysCount, " (LangSys)");
1125       for (j = 0; j < script->LangSysCount; j++)
1126         {
1127           READ_TAG (stream, script->LangSysRecord[j].LangSysTag);
1128           READ_OFFSET (stream, script->LangSysRecord[j].LangSys);
1129         }
1130
1131       if (script->DefaultLangSysOffset)
1132         {
1133           OTF_LangSys *langsys = &script->DefaultLangSys;
1134
1135           SEEK_STREAM (stream, script_offset + script->DefaultLangSysOffset);
1136           READ_OFFSET (stream, langsys->LookupOrder);
1137           READ_USHORT (stream, langsys->ReqFeatureIndex);
1138           READ_USHORT (stream, langsys->FeatureCount);
1139           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1140                       " (FeatureIndex)");
1141           for (k = 0; k < langsys->FeatureCount; k++)
1142             READ_USHORT (stream, langsys->FeatureIndex[k]);
1143         }
1144
1145       for (j = 0; j < script->LangSysCount; j++)
1146         {
1147           OTF_LangSys *langsys = script->LangSys + j;
1148
1149           SEEK_STREAM (stream,
1150                        script_offset + script->LangSysRecord[j].LangSys);
1151           READ_OFFSET (stream, langsys->LookupOrder);
1152           READ_USHORT (stream, langsys->ReqFeatureIndex);
1153           READ_USHORT (stream, langsys->FeatureCount);
1154           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1155                       " (FeatureIndex)");
1156           for (k = 0; k < langsys->FeatureCount; k++)
1157             READ_USHORT (stream, langsys->FeatureIndex[k]);
1158         }
1159     }
1160
1161   return 0;
1162 }
1163
1164 static int
1165 read_feature_list (OTF *otf, OTF_Stream *stream, long offset,
1166                    OTF_FeatureList *list)
1167 {
1168   char *errfmt = "Feature List%s";
1169   int errret = -1;
1170   int i, j;
1171
1172   SEEK_STREAM (stream, offset);
1173   READ_UINT16 (stream, list->FeatureCount);
1174   OTF_CALLOC (list->Feature, list->FeatureCount, "");
1175   for (i = 0; i < list->FeatureCount; i++)
1176     {
1177       READ_TAG (stream, list->Feature[i].FeatureTag);
1178       READ_OFFSET (stream, list->Feature[i].offset);
1179     }
1180   for (i = 0; i < list->FeatureCount; i++)
1181     {
1182       OTF_Feature *feature = list->Feature + i;
1183
1184       SEEK_STREAM (stream, offset + feature->offset);
1185       READ_OFFSET (stream, feature->FeatureParams);
1186       READ_UINT16 (stream, feature->LookupCount);
1187       OTF_MALLOC (feature->LookupListIndex, feature->LookupCount,
1188                   " (LookupListIndex)");
1189       for (j = 0; j < feature->LookupCount; j++)
1190         READ_UINT16 (stream, feature->LookupListIndex[j]);
1191     }
1192
1193   return 0;
1194 }
1195
1196 static int read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream,
1197                                       long offset, unsigned type,
1198                                       OTF_LookupSubTableGSUB *subtable);
1199 static int read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
1200                                       long offset, unsigned type,
1201                                       OTF_LookupSubTableGPOS *subtable);
1202
1203 static int
1204 read_lookup_list (OTF *otf, OTF_Stream *stream, long offset,
1205                   OTF_LookupList *list, int gsubp)
1206 {
1207   char *errfmt = "Lookup List%s";
1208   int errret = -1;
1209   int i, j;
1210
1211   SEEK_STREAM (stream, offset);
1212   READ_UINT16 (stream, list->LookupCount);
1213   OTF_CALLOC (list->Lookup, list->LookupCount, "");
1214
1215   for (i = 0; i < list->LookupCount; i++)
1216     READ_OFFSET (stream, list->Lookup[i].offset);
1217   for (i = 0; i < list->LookupCount; i++)
1218     {
1219       OTF_Lookup *lookup = list->Lookup + i;
1220
1221       SEEK_STREAM (stream, offset + lookup->offset);
1222       READ_UINT16 (stream, lookup->LookupType);
1223       READ_UINT16 (stream, lookup->LookupFlag);
1224       READ_UINT16 (stream, lookup->SubTableCount);
1225       OTF_MALLOC (lookup->SubTableOffset, lookup->SubTableCount,
1226                   " (SubTableOffset)");
1227       if (gsubp)
1228         OTF_CALLOC (lookup->SubTable.gsub, lookup->SubTableCount,
1229                     " (SubTable)");
1230       else
1231         OTF_CALLOC (lookup->SubTable.gpos, lookup->SubTableCount,
1232                     " (SubTable)");
1233       for (j = 0; j < lookup->SubTableCount; j++)
1234         READ_OFFSET (stream, lookup->SubTableOffset[j]);
1235       for (j = 0; j < lookup->SubTableCount; j++)
1236         {
1237           long this_offset
1238             = offset + lookup->offset + lookup->SubTableOffset[j];
1239
1240           if (gsubp
1241               ? read_lookup_subtable_gsub (otf, stream, this_offset,
1242                                            lookup->LookupType,
1243                                            lookup->SubTable.gsub + j) < 0
1244               : read_lookup_subtable_gpos (otf, stream, this_offset,
1245                                            lookup->LookupType,
1246                                            lookup->SubTable.gpos + j) < 0)
1247             return errret;
1248         }
1249     }
1250
1251   return 0;
1252 }
1253
1254 \f
1255 /*** (1-8) Structures common to GSUB and GPOS */
1256
1257 static unsigned
1258 read_lookup_record_list (OTF *otf, OTF_Stream *stream,
1259                          OTF_LookupRecord **record, int count)
1260 {
1261   char *errfmt = "LookupRecord%s";
1262   unsigned errret = 0;
1263   int i;
1264
1265   if (count < 0)
1266     READ_UINT16 (stream, count);
1267   if (! count)
1268     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1269   OTF_MALLOC (*record, count, "");
1270   for (i = 0; i < count; i++)
1271     {
1272       READ_UINT16 (stream, (*record)[i].SequenceIndex);
1273       READ_UINT16 (stream, (*record)[i].LookupListIndex);
1274     }
1275   return count;
1276 }
1277
1278 static unsigned
1279 read_rule_list (OTF *otf, OTF_Stream *stream, long offset, OTF_Rule **rule)
1280 {
1281   char *errfmt = "List of Rule%s";
1282   unsigned errret = 0;
1283   OTF_StreamState state;
1284   unsigned count;
1285   int i;
1286
1287   READ_UINT16 (stream, count);
1288   if (! count)
1289     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1290   OTF_MALLOC (*rule, count, "");
1291   for (i = 0; i < count; i++)
1292     {
1293       READ_OFFSET (stream, (*rule)[i].offset);
1294       if (! (*rule)[i].offset)
1295         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1296     }
1297   SAVE_STREAM (stream, state);
1298   for (i = 0; i < count; i++)
1299     {
1300       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1301       READ_UINT16 (stream, (*rule)[i].GlyphCount);
1302       if ((*rule)[i].GlyphCount == 0)
1303         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1304       READ_UINT16 (stream, (*rule)[i].LookupCount);
1305       if (read_glyph_ids (otf, stream, &(*rule)[i].Input, 0,
1306                           (*rule)[i].GlyphCount) < 0)
1307         return errret;
1308       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1309                                    (*rule)[i].LookupCount) == 0)
1310         return errret;
1311     }
1312   RESTORE_STREAM (stream, state);
1313   return count;
1314 }
1315
1316
1317 static unsigned
1318 read_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1319                     OTF_RuleSet **set)
1320 {
1321   char *errfmt = "List of RuleSet%s";
1322   unsigned errret = 0;
1323   OTF_StreamState state;
1324   unsigned count;
1325   int i;
1326
1327   READ_UINT16 (stream, count);
1328   if (! count)
1329     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1330   OTF_MALLOC (*set, count, "");
1331   for (i = 0; i < count; i++)
1332     {
1333       READ_OFFSET (stream, (*set)[i].offset);
1334       if (! (*set)[i].offset)
1335         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1336     }
1337   SAVE_STREAM (stream, state);
1338   for (i = 0; i < count; i++)
1339     {
1340       SEEK_STREAM (stream, offset + (*set)[i].offset);
1341       (*set)[i].RuleCount
1342         = read_rule_list (otf, stream, offset + (*set)[i].offset,
1343                           &(*set)[i].Rule);
1344       if (! (*set)[i].RuleCount)
1345         return errret;
1346     }
1347   RESTORE_STREAM (stream, state);
1348   return count;
1349 }
1350
1351 static unsigned
1352 read_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1353                       OTF_ClassRule **rule)
1354 {
1355   char *errfmt = "ClassRule%s";
1356   unsigned errret = 0;
1357   OTF_StreamState state;
1358   unsigned count;
1359   int i;
1360
1361   READ_UINT16 (stream, count);
1362   if (! count)
1363     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1364   OTF_MALLOC (*rule, count, "");
1365   for (i = 0; i < count; i++)
1366     {
1367       READ_OFFSET (stream, (*rule)[i].offset);
1368       if (! (*rule)[i].offset)
1369         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1370     }
1371   SAVE_STREAM (stream, state);
1372   for (i = 0; i < count; i++)
1373     {
1374       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1375       READ_USHORT (stream, (*rule)[i].GlyphCount);
1376       if (! (*rule)[i].GlyphCount)
1377         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1378       READ_USHORT (stream, (*rule)[i].LookupCount);
1379       if (read_glyph_ids (otf, stream, (OTF_GlyphID **) &(*rule)[i].Class,
1380                           0, (*rule)[i].GlyphCount - 1) < 0)
1381         return errret;
1382       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1383                                    (*rule)[i].LookupCount) == 0)
1384         return errret;
1385     }
1386   RESTORE_STREAM (stream, state);
1387   return count;
1388 }
1389
1390 static unsigned
1391 read_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1392                      OTF_ClassSet **set)
1393 {
1394   char *errfmt = "ClassSet%s";
1395   unsigned errret = 0;
1396   OTF_StreamState state;
1397   unsigned count;
1398   int i;
1399
1400   READ_UINT16 (stream, count);
1401   if (! count)
1402     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1403   OTF_CALLOC (*set, count, "");
1404   for (i = 0; i < count; i++)
1405     /* Offset can be zero.  */
1406     READ_OFFSET (stream, (*set)[i].offset);
1407   SAVE_STREAM (stream, state);
1408   for (i = 0; i < count; i++)
1409     if ((*set)[i].offset)
1410       {
1411         SEEK_STREAM (stream, offset + (*set)[i].offset);
1412         (*set)[i].ClassRuleCnt
1413           = read_class_rule_list (otf, stream, offset + (*set)[i].offset,
1414                                   &(*set)[i].ClassRule);
1415         if (! (*set)[i].ClassRuleCnt)
1416           return errret;
1417       }
1418   RESTORE_STREAM (stream, state);
1419   return count;
1420 }
1421
1422 static unsigned
1423 read_chain_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1424                       OTF_ChainRule **rule)
1425 {
1426   char *errfmt = "ChainRule%s";
1427   unsigned errret = 0;
1428   unsigned count;
1429   int i;
1430
1431   READ_UINT16 (stream, count);
1432   if (! count)
1433     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1434   OTF_MALLOC (*rule, count, "");
1435   for (i = 0; i < count; i++)
1436     READ_OFFSET (stream, (*rule)[i].offset);
1437   for (i = 0; i < count; i++)
1438     {
1439       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1440       (*rule)[i].BacktrackGlyphCount
1441         = read_glyph_ids (otf, stream, &(*rule)[i].Backtrack, 0, -1);
1442       (*rule)[i].InputGlyphCount
1443         = read_glyph_ids (otf, stream, &(*rule)[i].Input, -1, -1);
1444       if (! (*rule)[i].InputGlyphCount)
1445         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1446       (*rule)[i].LookaheadGlyphCount
1447         = read_glyph_ids (otf, stream, &(*rule)[i].LookAhead, 0, -1);
1448       (*rule)[i].LookupCount
1449         = read_lookup_record_list (otf, stream,
1450                                    &(*rule)[i].LookupRecord, -1);
1451       if (! (*rule)[i].LookupCount)
1452         return errret;
1453     }
1454   return count;
1455 }
1456
1457
1458 static unsigned
1459 read_chain_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1460                      OTF_ChainRuleSet **set)
1461 {
1462   char *errfmt = "ChainRuleSet%s";
1463   unsigned errret = 0;
1464   OTF_StreamState state;
1465   unsigned count;
1466   int i;
1467
1468   READ_UINT16 (stream, count);
1469   if (! count)
1470     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1471   OTF_MALLOC (*set, count, "");
1472   for (i = 0; i < count; i++)
1473     {
1474       READ_OFFSET (stream, (*set)[i].offset);
1475       if (! (*set)[i].offset)
1476         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1477     }
1478   SAVE_STREAM (stream, state);
1479   for (i = 0; i < count; i++)
1480     {
1481       SEEK_STREAM (stream, offset + (*set)[i].offset);
1482       (*set)[i].ChainRuleCount
1483         = read_chain_rule_list (otf, stream, offset + (*set)[i].offset,
1484                                 &(*set)[i].ChainRule);
1485       if (! (*set)[i].ChainRuleCount)
1486         return errret;
1487     }
1488   RESTORE_STREAM (stream, state);
1489   return count;
1490 }
1491
1492 static unsigned
1493 read_chain_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1494                             OTF_ChainClassRule **rule)
1495 {
1496   char *errfmt = "ChainClassRule%s";
1497   unsigned errret = 0;
1498   unsigned count;
1499   int i;
1500
1501   READ_UINT16 (stream, count);
1502   if (! count)
1503     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1504   OTF_MALLOC (*rule, count, "");
1505   for (i = 0; i < count; i++)
1506     {
1507       READ_OFFSET (stream, (*rule)[i].offset);
1508       if (! (*rule)[i].offset)
1509         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1510     }
1511   for (i = 0; i < count; i++)
1512     {
1513       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1514       (*rule)[i].BacktrackGlyphCount
1515         = read_glyph_ids (otf, stream,
1516                           (OTF_GlyphID **) &(*rule)[i].Backtrack, 0, -1);
1517       (*rule)[i].InputGlyphCount
1518         = read_glyph_ids (otf, stream,
1519                           (OTF_GlyphID **) &(*rule)[i].Input, -1, -1);
1520       if (! (*rule)[i].InputGlyphCount)
1521         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1522       (*rule)[i].LookaheadGlyphCount
1523         = read_glyph_ids (otf, stream,
1524                           (OTF_GlyphID **) &(*rule)[i].LookAhead, 0, -1);
1525       (*rule)[i].LookupCount
1526         = read_lookup_record_list (otf, stream,
1527                                    &(*rule)[i].LookupRecord, -1);
1528       if (! (*rule)[i].LookupCount)
1529         return errret;
1530     }
1531   return count;
1532 }
1533
1534 static unsigned
1535 read_chain_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1536                            OTF_ChainClassSet **set)
1537 {
1538   char *errfmt = "ChainClassSet%s";
1539   unsigned errret = 0;
1540   OTF_StreamState state;
1541   unsigned count;
1542   int i;
1543
1544   READ_UINT16 (stream, count);
1545   if (! count)
1546     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1547   OTF_MALLOC (*set, count, "");
1548   for (i = 0; i < count; i++)
1549     /* Offset may be zero.  */
1550     READ_OFFSET (stream, (*set)[i].offset);
1551   SAVE_STREAM (stream, state);
1552   for (i = 0; i < count; i++)
1553     if ((*set)[i].offset)
1554       {
1555         SEEK_STREAM (stream, offset + (*set)[i].offset);
1556         (*set)[i].ChainClassRuleCnt
1557           = read_chain_class_rule_list (otf, stream, offset + (*set)[i].offset,
1558                                         &(*set)[i].ChainClassRule);
1559         if (! (*set)[i].ChainClassRuleCnt)
1560           return errret;
1561       }
1562   RESTORE_STREAM (stream, state);
1563   return count;
1564 }
1565
1566 static int
1567 read_context1 (OTF *otf, OTF_Stream *stream, long offset,
1568                OTF_Coverage *coverage,OTF_Context1 *context1)
1569 {
1570   if (read_coverage (otf, stream, offset, coverage) < 0)
1571     return -1;
1572   context1->RuleSetCount
1573     = read_rule_set_list (otf, stream, offset, &context1->RuleSet);
1574   if (! context1->RuleSetCount)
1575     return -1;
1576   return 0;
1577 }
1578
1579 static int
1580 read_context2 (OTF *otf, OTF_Stream *stream, long offset,
1581                OTF_Coverage *coverage,OTF_Context2 *context2)
1582 {
1583   if (read_coverage (otf, stream, offset, coverage) < 0
1584       || read_class_def (otf, stream, offset, &context2->ClassDef) < 0)
1585     return -1;
1586   context2->ClassSetCnt
1587     = read_class_set_list (otf, stream, offset, &context2->ClassSet);
1588   if (! context2->ClassSetCnt)
1589     return -1;
1590   return 0;
1591 }
1592
1593 static int
1594 read_context3 (OTF *otf, OTF_Stream *stream, long offset,
1595                OTF_Coverage *coverage,OTF_Context3 *context3)
1596 {
1597   char *errfmt = "Context1%s";
1598   int errret = -1;
1599
1600   READ_USHORT (stream, context3->GlyphCount);
1601   if (context3->GlyphCount < 0)
1602     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1603   READ_USHORT (stream, context3->LookupCount);
1604   if (read_coverage_list (otf, stream, offset, &context3->Coverage,
1605                           context3->GlyphCount) < 0)
1606     return errret;
1607   if (read_lookup_record_list (otf, stream, &context3->LookupRecord,
1608                                context3->LookupCount) < 0)
1609     return errret;
1610   return 0;
1611 }
1612
1613 static int
1614 read_chain_context1 (OTF *otf, OTF_Stream *stream, long offset,
1615                      OTF_Coverage *coverage, OTF_ChainContext1 *chain_context1)
1616 {
1617   if (read_coverage (otf, stream, offset, coverage) < 0)
1618     return -1;
1619   chain_context1->ChainRuleSetCount
1620     = read_chain_rule_set_list (otf, stream, offset,
1621                                 &chain_context1->ChainRuleSet);
1622   if (! chain_context1->ChainRuleSetCount)
1623     return -1;
1624   return 0;
1625 }
1626
1627 static int
1628 read_chain_context2 (OTF *otf, OTF_Stream *stream, long offset,
1629                      OTF_Coverage *coverage, OTF_ChainContext2 *chain_context2)
1630 {
1631   if (read_coverage (otf, stream, offset, coverage) < 0
1632       || read_class_def (otf, stream, offset,
1633                          &chain_context2->BacktrackClassDef) < 0
1634       || read_class_def (otf, stream, offset,
1635                          &chain_context2->InputClassDef) < 0
1636       || read_class_def (otf, stream, offset,
1637                          &chain_context2->LookaheadClassDef) < 0)
1638     return -1;
1639   chain_context2->ChainClassSetCnt
1640     = read_chain_class_set_list (otf, stream, offset,
1641                                  &chain_context2->ChainClassSet);
1642   if (! chain_context2->ChainClassSetCnt)
1643     return -1;
1644   return 0;
1645 }
1646
1647 static int
1648 read_chain_context3 (OTF *otf, OTF_Stream *stream, long offset,
1649                      OTF_Coverage *coverage, OTF_ChainContext3 *chain_context3)
1650 {
1651   int count;
1652
1653   count = read_coverage_list (otf, stream, offset,
1654                               &chain_context3->Backtrack, -1);
1655   if (count < 0)
1656     return -1;
1657   chain_context3->BacktrackGlyphCount = (unsigned) count;
1658   count = read_coverage_list (otf, stream, offset,
1659                               &chain_context3->Input, -1);
1660   if (count <= 0)
1661     return -1;
1662   chain_context3->InputGlyphCount = (unsigned) count;
1663   *coverage = chain_context3->Input[0];
1664   count = read_coverage_list (otf, stream, offset,
1665                               &chain_context3->LookAhead, -1);
1666   chain_context3->LookaheadGlyphCount = (unsigned) count;
1667   chain_context3->LookupCount
1668     = read_lookup_record_list (otf, stream,
1669                                &chain_context3->LookupRecord, -1);
1670   return 0;
1671 }
1672
1673 static void *
1674 read_gsub_gpos_table (OTF *otf, OTF_TableInfo *table, int gsubp,
1675                       enum OTF_ReaderFlag flag)
1676 {
1677   OTF_Stream *stream = table->stream;
1678   char *errfmt = gsubp ? "GSUB%s" : "GPOS%s";
1679   void *errret = NULL;
1680   OTF_GSUB_GPOS *gsub_gpos = *table->address;
1681
1682   if (gsub_gpos)
1683     SEEK_STREAM (stream, 10);
1684   else
1685     {
1686       SEEK_STREAM (stream, 0);
1687       OTF_CALLOC (gsub_gpos, 1, "");
1688       READ_FIXED (stream, gsub_gpos->Version);
1689       READ_OFFSET (stream, gsub_gpos->ScriptList.offset);
1690       READ_OFFSET (stream, gsub_gpos->FeatureList.offset);
1691       READ_OFFSET (stream, gsub_gpos->LookupList.offset);
1692       *table->address = gsub_gpos;
1693     }
1694
1695   if (! gsub_gpos->ScriptList.Script
1696       && read_script_list (otf, stream, gsub_gpos->ScriptList.offset,
1697                            &gsub_gpos->ScriptList) < 0)
1698     return NULL;
1699   if (flag != OTF_READ_SCRIPTS)
1700     {
1701       if (! gsub_gpos->FeatureList.Feature
1702           && read_feature_list (otf, stream, gsub_gpos->FeatureList.offset,
1703                                 &gsub_gpos->FeatureList) < 0)
1704         return NULL;
1705       if (flag != OTF_READ_FEATURES)
1706         {
1707           if (! gsub_gpos->LookupList.Lookup
1708               && read_lookup_list (otf, stream, gsub_gpos->LookupList.offset,
1709                                    &gsub_gpos->LookupList, gsubp) < 0)
1710             return NULL;
1711         }
1712     }
1713
1714   return gsub_gpos;
1715 }
1716
1717 \f
1718 /* (1-9) "GSUB" table */
1719
1720 static unsigned
1721 read_sequence (OTF *otf, OTF_Stream *stream, long offset, OTF_Sequence **seq)
1722 {
1723   char *errfmt = "Sequence%s";
1724   unsigned errret = 0;
1725   unsigned count;
1726   int i;
1727
1728   READ_UINT16 (stream, count);
1729   if (! count)
1730     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1731   OTF_MALLOC (*seq, count, "");
1732   for (i = 0; i < count; i++)
1733     READ_OFFSET (stream, (*seq)[i].offset);
1734   for (i = 0; i < count; i++)
1735     {
1736       SEEK_STREAM (stream, offset + (*seq)[i].offset);
1737       (*seq)[i].GlyphCount = read_glyph_ids (otf, stream,
1738                                              &(*seq)[i].Substitute, 0, -1);
1739       if (! (*seq)[i].GlyphCount)
1740         return 0;
1741     }
1742   return count;
1743 }
1744
1745 static int
1746 read_ligature (OTF *otf, OTF_Stream *stream, long offset,
1747                OTF_Ligature **ligature)
1748 {
1749   char *errfmt = "Ligature%s";
1750   int errret = -1;
1751   int count;
1752   int i;
1753
1754   READ_UINT16 (stream, count);
1755   if (! count)
1756     return 0;
1757   OTF_MALLOC (*ligature, count, "");
1758   for (i = 0; i < count; i++)
1759     READ_OFFSET (stream, (*ligature)[i].offset);
1760   for (i = 0; i < count; i++)
1761     {
1762       SEEK_STREAM (stream, offset + (*ligature)[i].offset);
1763       READ_GLYPHID (stream, (*ligature)[i].LigGlyph);
1764       (*ligature)[i].CompCount
1765         = read_glyph_ids (otf, stream, &(*ligature)[i].Component, -1, -1);
1766       if (! (*ligature)[i].CompCount)
1767         return -1;
1768     }
1769   return count;
1770 }
1771
1772 static unsigned
1773 read_ligature_set_list (OTF *otf, OTF_Stream *stream, long offset,
1774                         OTF_LigatureSet **ligset)
1775 {
1776   char *errfmt = "LigatureSet%s";
1777   int errret = 0;
1778   int count;
1779   int i;
1780
1781   READ_UINT16 (stream, count);
1782   if (! count)
1783     return errret;
1784   OTF_MALLOC (*ligset, count, "");
1785   for (i = 0; i < count; i++)
1786     READ_OFFSET (stream, (*ligset)[i].offset);
1787   for (i = 0; i < count; i++)
1788     {
1789       int lig_count;
1790
1791       SEEK_STREAM (stream, offset + (*ligset)[i].offset);
1792       lig_count = read_ligature (otf, stream, offset + (*ligset)[i].offset,
1793                                  &(*ligset)[i].Ligature);
1794       if (lig_count < 0)
1795         return errret;
1796       (*ligset)[i].LigatureCount = (unsigned) lig_count;
1797     }
1798   return count;
1799 }
1800
1801 static unsigned
1802 read_alternate_set_list (OTF *otf, OTF_Stream *stream, long offset,
1803                          OTF_AlternateSet **altset)
1804 {
1805   char *errfmt = "AlternateSet%s";
1806   int errret = 0;
1807   unsigned count;
1808   int i;
1809
1810   READ_UINT16 (stream, count);
1811   if (! count)
1812     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1813   OTF_MALLOC (*altset, count, "");
1814   for (i = 0; i < count; i++)
1815     READ_OFFSET (stream, (*altset)[i].offset);
1816   for (i = 0; i < count; i++)
1817     {
1818       int alt_count;
1819
1820       SEEK_STREAM (stream, offset + (*altset)[i].offset);
1821       alt_count = read_glyph_ids (otf, stream, &(*altset)[i].Alternate, 0, -1);
1822       if (alt_count < 0)
1823         return errret;
1824       (*altset)[i].GlyphCount = (unsigned) alt_count;
1825     }
1826   return count;
1827 }
1828
1829 static int
1830 read_reverse_chain1 (OTF *otf, OTF_Stream *stream, long offset,
1831                      OTF_Coverage *coverage,
1832                      OTF_GSUB_ReverseChain1 *reverse_chain)
1833 {
1834   int count;
1835
1836   if (read_coverage (otf, stream, offset, coverage) < 0)
1837     return -1;
1838   count = read_coverage_list (otf, stream, offset,
1839                               &reverse_chain->Backtrack, -1);
1840   if (count < 0)
1841     return -1;
1842   reverse_chain->BacktrackGlyphCount = (unsigned) count;
1843   count = read_coverage_list (otf, stream, offset,
1844                               &reverse_chain->LookAhead, -1);
1845   if (count <= 0)
1846     return -1;
1847   reverse_chain->LookaheadGlyphCount = (unsigned) count;
1848   count = read_glyph_ids (otf, stream, &reverse_chain->Substitute, 0, -1);
1849   if (count <= 0)
1850     return -1;
1851   reverse_chain->GlyphCount = count;  
1852   return 0;
1853 }
1854
1855 static int
1856 read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream, long offset,
1857                            unsigned type, OTF_LookupSubTableGSUB *subtable)
1858 {
1859   char errfmt[256];
1860   int errret = -1;
1861
1862   SEEK_STREAM (stream, offset);
1863   READ_USHORT (stream, subtable->Format);
1864   sprintf (errfmt, "GSUB Lookup %d-%d%%s", type, subtable->Format);
1865   switch (type)
1866     {
1867     case 1:
1868       if (subtable->Format == 1)
1869         {
1870           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1871             return -1;
1872           READ_INT16 (stream, subtable->u.single1.DeltaGlyphID);
1873         }
1874       else if (subtable->Format == 2)
1875         {
1876           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1877             return -1;
1878           subtable->u.single2.GlyphCount
1879             = read_glyph_ids (otf, stream, &subtable->u.single2.Substitute,
1880                               0, -1);
1881           if (! subtable->u.single2.GlyphCount)
1882             return -1;
1883         }
1884       else
1885         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1886       break;
1887
1888     case 2:
1889       if (subtable->Format == 1)
1890         {
1891           read_coverage (otf, stream, offset, &subtable->Coverage);
1892           subtable->u.multiple1.SequenceCount
1893             = read_sequence (otf, stream, offset,
1894                              &subtable->u.multiple1.Sequence);
1895         }
1896       else
1897         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1898       break;
1899
1900     case 3:
1901       if (subtable->Format == 1)
1902         {
1903           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1904             return -1;
1905           subtable->u.alternate1.AlternateSetCount
1906             = read_alternate_set_list (otf, stream, offset,
1907                                        &subtable->u.alternate1.AlternateSet);
1908           if (! subtable->u.alternate1.AlternateSetCount)
1909             return -1;
1910         }
1911       else
1912         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1913       break;
1914
1915     case 4:
1916       if (subtable->Format == 1)
1917         {
1918           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
1919             return -1;
1920           subtable->u.ligature1.LigSetCount
1921             = read_ligature_set_list (otf, stream, offset,
1922                                       &subtable->u.ligature1.LigatureSet);
1923           if (! subtable->u.ligature1.LigSetCount)
1924             return -1;
1925         }
1926       else
1927         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1928       break;
1929
1930     case 5:
1931       if (subtable->Format == 1)
1932         {
1933           if (read_context1 (otf, stream, offset, &subtable->Coverage,
1934                              &subtable->u.context1) < 0)
1935             return errret;
1936         }
1937       else if (subtable->Format == 2)
1938         {
1939           if (read_context2 (otf, stream, offset, &subtable->Coverage,
1940                              &subtable->u.context2) < 0)
1941             return errret;
1942         }
1943       else if (subtable->Format == 3)
1944         {
1945           if (read_context3 (otf, stream, offset, &subtable->Coverage,
1946                              &subtable->u.context3) < 0)
1947             return errret;
1948         }
1949       else
1950         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1951       break;
1952
1953     case 6:
1954       if (subtable->Format == 1)
1955         {
1956           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
1957                                    &subtable->u.chain_context1) < 0)
1958             return errret;
1959         }
1960       else if (subtable->Format == 2)
1961         {
1962           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
1963                                    &subtable->u.chain_context2) < 0)
1964             return errret;
1965         }
1966       else if (subtable->Format == 3)
1967         {
1968           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
1969                                    &subtable->u.chain_context3) < 0)
1970             return errret;
1971         }
1972       else
1973         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1974       break;
1975
1976     case 7:
1977       if (subtable->Format == 1)
1978         {
1979           unsigned ex_type;
1980           long ex_offset;
1981           OTF_LookupSubTableGSUB *ex_subtable;
1982
1983           READ_USHORT (stream, ex_type);
1984           READ_ULONG (stream, ex_offset);
1985           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
1986           if (read_lookup_subtable_gsub (otf, stream, offset + ex_offset,
1987                                          ex_type, ex_subtable) < 0)
1988             return errret;
1989           subtable->u.extension1.ExtensionLookupType = ex_type;
1990           subtable->u.extension1.ExtensionOffset = ex_offset;
1991           subtable->u.extension1.ExtensionSubtable = ex_subtable;
1992         }
1993       else
1994         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
1995       break;
1996
1997     case 8:
1998       if (subtable->Format == 1)
1999         {
2000           if (read_reverse_chain1 (otf, stream, offset, &subtable->Coverage,
2001                                    &subtable->u.reverse_chain1) < 0)
2002             return errret;
2003         }
2004       else
2005         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2006       break;
2007
2008     default:
2009       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2010     }
2011   return 0;
2012 }
2013
2014 static void *
2015 read_gsub_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2016 {
2017   return read_gsub_gpos_table (otf, table, 1, flag);
2018 }
2019
2020 \f
2021 /* (1-10) "GPOS" table */
2022
2023 static int
2024 read_value_record (OTF *otf, OTF_Stream *stream, long offset,
2025                    enum OTF_ValueFormat bit, OTF_ValueRecord *value_record)
2026 {
2027   int errret = -1;
2028   OTF_StreamState state;
2029   int size, i;
2030
2031   memset (value_record, 0, sizeof (OTF_ValueRecord));
2032   if (! bit)
2033     return 0;
2034   for (i = 0, size = 0; i < 8; i++)
2035     if (bit & (1 << i))
2036       size += 2;
2037
2038   if (bit & OTF_XPlacement)
2039     READ_INT16 (stream, value_record->XPlacement);
2040   if (bit & OTF_YPlacement)
2041     READ_INT16 (stream, value_record->YPlacement);
2042   if (bit & OTF_XAdvance)
2043     READ_INT16 (stream, value_record->XAdvance);
2044   if (bit & OTF_YAdvance)
2045     READ_INT16 (stream, value_record->YAdvance);
2046   if (bit & OTF_XPlaDevice)
2047     READ_OFFSET (stream, value_record->XPlaDevice.offset);
2048   if (bit & OTF_YPlaDevice)
2049     READ_OFFSET (stream, value_record->YPlaDevice.offset);
2050   if (bit & OTF_XAdvDevice)
2051     READ_OFFSET (stream, value_record->XAdvDevice.offset);
2052   if (bit & OTF_YAdvDevice)
2053     READ_OFFSET (stream, value_record->YAdvDevice.offset);
2054   SAVE_STREAM (stream, state);
2055   if (value_record->XPlaDevice.offset)
2056     {
2057       if (read_device_table (otf, stream, offset, &value_record->XPlaDevice) < 0)
2058         return -1;
2059     }
2060   if (value_record->YPlaDevice.offset)
2061     {
2062       if (read_device_table (otf, stream, offset, &value_record->YPlaDevice) < 0)
2063         return -1;
2064     }
2065   if (value_record->XAdvDevice.offset)
2066     {
2067       if (read_device_table (otf, stream, offset, &value_record->XAdvDevice) < 0)
2068         return -1;
2069     }
2070   if (value_record->YAdvDevice.offset)
2071     {
2072       if (read_device_table (otf, stream, offset, &value_record->YAdvDevice) < 0)
2073         return -1;
2074     }
2075   RESTORE_STREAM (stream, state);
2076   return 0;
2077 }
2078
2079
2080 static int
2081 read_anchor (OTF *otf, OTF_Stream *stream, long offset, OTF_Anchor *anchor)
2082 {
2083   char *errfmt = "Anchor%s";
2084   int errret = -1;
2085
2086   SEEK_STREAM (stream, offset + anchor->offset);
2087   READ_UINT16 (stream, anchor->AnchorFormat);
2088   READ_INT16 (stream, anchor->XCoordinate);
2089   READ_INT16 (stream, anchor->YCoordinate);
2090   if (anchor->AnchorFormat == 1)
2091     ;
2092   else if (anchor->AnchorFormat == 2)
2093     {
2094       READ_UINT16 (stream, anchor->f.f1.AnchorPoint);
2095     }
2096   else if (anchor->AnchorFormat == 3)
2097     {
2098       READ_OFFSET (stream, anchor->f.f2.XDeviceTable.offset);
2099       READ_OFFSET (stream, anchor->f.f2.YDeviceTable.offset);
2100       if (anchor->f.f2.XDeviceTable.offset)
2101         {
2102           if (read_device_table (otf, stream, offset + anchor->offset,
2103                                  &anchor->f.f2.XDeviceTable) < 0)
2104             return -1;
2105         }
2106       if (anchor->f.f2.YDeviceTable.offset)
2107         {
2108           if (read_device_table (otf, stream, offset + anchor->offset,
2109                                  &anchor->f.f2.YDeviceTable) < 0)
2110             return -1;
2111         }
2112     }
2113   else
2114     OTF_ERROR (OTF_ERROR_TABLE, " (invalid format)");
2115
2116   return 0;
2117 }
2118
2119 static int
2120 read_mark_array (OTF *otf, OTF_Stream *stream, long offset,
2121                  OTF_MarkArray *array)
2122 {
2123   char *errfmt = "MarkArray%s";
2124   int errret = -1;
2125   OTF_StreamState state;
2126   int i;
2127
2128   READ_OFFSET (stream, array->offset);
2129   SAVE_STREAM (stream, state);
2130   SEEK_STREAM (stream, offset + array->offset);
2131   READ_UINT16 (stream, array->MarkCount);
2132   OTF_MALLOC (array->MarkRecord, array->MarkCount, "");
2133   for (i = 0; i < array->MarkCount; i++)
2134     {
2135       READ_UINT16 (stream, array->MarkRecord[i].Class);
2136       READ_OFFSET (stream, array->MarkRecord[i].MarkAnchor.offset);
2137     }
2138   for (i = 0; i < array->MarkCount; i++)
2139     if (read_anchor (otf, stream, offset + array->offset,
2140                      &array->MarkRecord[i].MarkAnchor) < 0)
2141       return -1;;
2142   RESTORE_STREAM (stream, state);
2143   return 0;
2144 }
2145
2146 static int
2147 read_anchor_array (OTF *otf, OTF_Stream *stream, long offset,
2148                    unsigned ClassCount, OTF_AnchorArray *array)
2149 {
2150   char *errfmt = "AnchorArray%s";
2151   int errret = -1;
2152   OTF_StreamState state;
2153   int i, j;
2154
2155   READ_OFFSET (stream, array->offset);
2156   SAVE_STREAM (stream, state);
2157   SEEK_STREAM (stream, offset + array->offset);
2158   READ_UINT16 (stream, array->Count);
2159   OTF_MALLOC (array->AnchorRecord, array->Count, "");
2160   for (i = 0; i < array->Count; i++)
2161     {
2162       OTF_MALLOC (array->AnchorRecord[i].Anchor, ClassCount,
2163                   " (AnchorRecord)");
2164       for (j = 0; j < ClassCount; j++)
2165         READ_OFFSET (stream, array->AnchorRecord[i].Anchor[j].offset);
2166     }
2167   for (i = 0; i < array->Count; i++)
2168     for (j = 0; j < ClassCount; j++)
2169       if (read_anchor (otf, stream, offset + array->offset,
2170                        &array->AnchorRecord[i].Anchor[j]) < 0)
2171         return -1;
2172   RESTORE_STREAM (stream, state);
2173   return 0;
2174 }
2175
2176 static OTF_PairSet *
2177 read_pair_set_list (OTF *otf, OTF_Stream *stream, long offset, unsigned num,
2178                     enum OTF_ValueFormat bit1, enum OTF_ValueFormat bit2)
2179 {
2180   char *errfmt = "PairSet%s";
2181   void *errret = NULL;
2182   OTF_StreamState state;
2183   OTF_PairSet *set;
2184   int i, j;
2185
2186   OTF_MALLOC (set, num, "");
2187   for (i = 0; i < num; i++)
2188     READ_OFFSET (stream, set[i].offset);
2189   SAVE_STREAM (stream, state);
2190   for (i = 0; i < num; i++)
2191     {
2192       SEEK_STREAM (stream, offset + set[i].offset);
2193       READ_UINT16 (stream, set[i].PairValueCount);
2194       OTF_MALLOC (set[i].PairValueRecord, set[i].PairValueCount, "");
2195       for (j = 0; j < set[i].PairValueCount; j++)
2196         {
2197           OTF_PairValueRecord *rec = set[i].PairValueRecord + j;
2198
2199           READ_UINT16 (stream, rec->SecondGlyph);
2200           read_value_record (otf, stream, offset, bit1, &rec->Value1);
2201           read_value_record (otf, stream, offset, bit2, &rec->Value2);
2202         }
2203     }
2204   RESTORE_STREAM (stream, state);
2205   return set;
2206 }
2207
2208 static OTF_Class1Record *
2209 read_class1_record_list (OTF *otf, OTF_Stream *stream, long offset,
2210                          unsigned num1, enum OTF_ValueFormat bit1,
2211                          unsigned num2, enum OTF_ValueFormat bit2)
2212 {
2213   char *errfmt = "Class1Record%s";
2214   void *errret = NULL;
2215   OTF_Class1Record *rec;
2216   int i, j;
2217
2218   OTF_MALLOC (rec, num1, "");
2219   for (i = 0; i < num1; i++)
2220     {
2221       OTF_CALLOC (rec[i].Class2Record, num2, " (Class2Record)");
2222       for (j = 0; j < num2; j++)
2223         {
2224           if (read_value_record (otf, stream, offset,
2225                                  bit1, &rec[i].Class2Record[j].Value1) < 0
2226               || read_value_record (otf, stream, offset,
2227                                     bit2, &rec[i].Class2Record[j].Value2) < 0)
2228             return NULL;
2229         }
2230     }
2231   return rec;
2232 }
2233
2234 static unsigned
2235 read_entry_exit_list (OTF *otf, OTF_Stream *stream, long offset,
2236                       OTF_EntryExitRecord **rec)
2237 {
2238   char *errfmt = "EntryExitSet%s";
2239   int errret = 0;
2240   unsigned count;
2241   int i;
2242   OTF_StreamState state;
2243
2244   READ_UINT16 (stream, count);
2245   if (! count)
2246     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
2247   OTF_MALLOC (*rec, count, "");
2248   for (i = 0; i < count; i++)
2249     {
2250       READ_OFFSET (stream, (*rec)[i].EntryAnchor.offset);
2251       READ_OFFSET (stream, (*rec)[i].ExitAnchor.offset);
2252     }
2253   SAVE_STREAM (stream, state);
2254   for (i = 0; i < count; i++)
2255     {
2256       if (read_anchor (otf, stream, offset, &(*rec)[i].EntryAnchor) < 0)
2257         return -1;
2258       if (read_anchor (otf, stream, offset, &(*rec)[i].ExitAnchor) < 0)
2259         return -1;
2260     }
2261   RESTORE_STREAM (stream, state);
2262   return count;
2263 }
2264
2265 static int
2266 read_ligature_attach (OTF *otf, OTF_Stream *stream, long offset,
2267                       unsigned ClassCount, OTF_LigatureAttach *attach)
2268 {
2269   char *errfmt = "LigatureAttach%s";
2270   int errret = 1;
2271   int i, j;
2272
2273   SEEK_STREAM (stream, offset + attach->offset);
2274   READ_UINT16 (stream, attach->ComponentCount);
2275   OTF_MALLOC (attach->ComponentRecord, attach->ComponentCount, "");
2276   for (i = 0; i < attach->ComponentCount; i++)
2277     {
2278       OTF_MALLOC (attach->ComponentRecord[i].LigatureAnchor, ClassCount,
2279                   " (ComponentRecord)");
2280       for (j = 0; j < ClassCount; j++)
2281         READ_OFFSET (stream,
2282                      attach->ComponentRecord[i].LigatureAnchor[j].offset);
2283     }
2284   for (i = 0; i < attach->ComponentCount; i++)
2285     for (j = 0; j < ClassCount; j++)
2286       {
2287         if (attach->ComponentRecord[i].LigatureAnchor[j].offset)
2288           {
2289             if (read_anchor (otf, stream, offset + attach->offset,
2290                              &attach->ComponentRecord[i].LigatureAnchor[j]) < 0)
2291               return -1;
2292           }
2293         else
2294           attach->ComponentRecord[i].LigatureAnchor[j].AnchorFormat = 0;
2295       }
2296   return 0;
2297 }
2298
2299 static int
2300 read_ligature_array (OTF *otf, OTF_Stream *stream, long offset,
2301                      unsigned class_count, OTF_LigatureArray *array)
2302 {
2303   char *errfmt = "LigatureArray%s";
2304   int errret = -1;
2305   OTF_StreamState state;
2306   int i;
2307
2308   READ_OFFSET (stream, array->offset);
2309   SAVE_STREAM (stream, state);
2310   SEEK_STREAM (stream, offset + array->offset);
2311   READ_UINT16 (stream, array->LigatureCount);
2312   OTF_MALLOC (array->LigatureAttach, array->LigatureCount, "");
2313   for (i = 0; i < array->LigatureCount; i++)
2314     READ_OFFSET (stream, array->LigatureAttach[i].offset);
2315   for (i = 0; i < array->LigatureCount; i++)
2316     read_ligature_attach (otf, stream, offset + array->offset,
2317                           class_count, array->LigatureAttach + i);
2318   RESTORE_STREAM (stream, state);
2319   return 0;
2320 }
2321
2322 static int
2323 read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
2324                            long offset, unsigned type,
2325                            OTF_LookupSubTableGPOS *subtable)
2326 {
2327   char errfmt[256];
2328   int errret = -1;
2329
2330   SEEK_STREAM (stream, offset);
2331   READ_UINT16 (stream, subtable->Format);
2332   sprintf (errfmt, "GPOS Lookup %d-%d%%s", type, subtable->Format);
2333   switch (type)
2334     {
2335     case 1:
2336       if (subtable->Format == 1)
2337         {
2338           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2339             return -1;
2340           READ_UINT16 (stream, subtable->u.single1.ValueFormat);
2341           read_value_record (otf, stream, offset,
2342                              subtable->u.single1.ValueFormat,
2343                              &subtable->u.single1.Value);
2344         }
2345       else if (subtable->Format == 2)
2346         {
2347           OTF_GPOS_Single2 *single2 = &subtable->u.single2;
2348           int i;
2349
2350           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2351             return -1;
2352           READ_UINT16 (stream, single2->ValueFormat);
2353           READ_UINT16 (stream, single2->ValueCount);
2354           OTF_CALLOC (single2->Value, single2->ValueCount," (ValueRecord)");
2355           for (i = 0; i < single2->ValueCount; i++)
2356             read_value_record (otf, stream, offset, single2->ValueFormat,
2357                                single2->Value + i);
2358         }
2359       else
2360         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2361       break;
2362
2363     case 2:
2364       if (subtable->Format == 1)
2365         {
2366           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2367             return -1;
2368           READ_UINT16 (stream, subtable->u.pair1.ValueFormat1);
2369           READ_UINT16 (stream, subtable->u.pair1.ValueFormat2);
2370           READ_UINT16 (stream, subtable->u.pair1.PairSetCount);
2371           subtable->u.pair1.PairSet
2372             = read_pair_set_list (otf, stream, offset,
2373                                   subtable->u.pair1.PairSetCount,
2374                                   subtable->u.pair1.ValueFormat1,
2375                                   subtable->u.pair1.ValueFormat2);
2376           if (! subtable->u.pair1.PairSet)
2377             return -1;
2378         }
2379       else if (subtable->Format == 2)
2380         {
2381           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2382             return -1;
2383           READ_UINT16 (stream, subtable->u.pair2.ValueFormat1);
2384           READ_UINT16 (stream, subtable->u.pair2.ValueFormat2);
2385           if (read_class_def (otf, stream, offset,
2386                               &subtable->u.pair2.ClassDef1) < 0
2387               || read_class_def (otf, stream, offset,
2388                                  &subtable->u.pair2.ClassDef2) < 0)
2389             return -1;
2390           READ_UINT16 (stream, subtable->u.pair2.Class1Count);
2391           READ_UINT16 (stream, subtable->u.pair2.Class2Count);
2392           subtable->u.pair2.Class1Record
2393             = read_class1_record_list (otf, stream, offset,
2394                                        subtable->u.pair2.Class1Count,
2395                                        subtable->u.pair2.ValueFormat1,
2396                                        subtable->u.pair2.Class2Count,
2397                                        subtable->u.pair2.ValueFormat2);
2398           if (! subtable->u.pair2.Class1Record)
2399             return -1;
2400         }
2401       else
2402         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2403       break;
2404
2405     case 3:
2406       if (subtable->Format == 1)
2407         {
2408           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2409             return -1;
2410           subtable->u.cursive1.EntryExitCount
2411             = read_entry_exit_list (otf, stream, offset,
2412                                     &subtable->u.cursive1.EntryExitRecord);
2413           if (! subtable->u.cursive1.EntryExitCount)
2414             return -1;
2415         }
2416       else
2417         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2418       break;
2419
2420     case 4:
2421       if (subtable->Format == 1)
2422         {
2423           read_coverage (otf, stream, offset, &subtable->Coverage);
2424           read_coverage (otf, stream, offset,
2425                          &subtable->u.mark_base1.BaseCoverage);
2426           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2427           read_mark_array (otf, stream, offset,
2428                            &subtable->u.mark_base1.MarkArray);
2429           read_anchor_array (otf, stream, offset,
2430                              subtable->u.mark_base1.ClassCount,
2431                              &subtable->u.mark_base1.BaseArray);
2432         }
2433       else
2434         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2435       break;
2436
2437     case 5:
2438       if (subtable->Format == 1)
2439         {
2440           read_coverage (otf, stream, offset, &subtable->Coverage);
2441           read_coverage (otf, stream, offset,
2442                          &subtable->u.mark_lig1.LigatureCoverage);
2443           READ_UINT16 (stream, subtable->u.mark_lig1.ClassCount);
2444           read_mark_array (otf, stream, offset,
2445                            &subtable->u.mark_lig1.MarkArray);
2446           read_ligature_array (otf, stream, offset,
2447                                subtable->u.mark_lig1.ClassCount,
2448                                &subtable->u.mark_lig1.LigatureArray);
2449         }
2450       break;
2451
2452     case 6:
2453       if (subtable->Format == 1)
2454         {
2455           read_coverage (otf, stream, offset, &subtable->Coverage);
2456           read_coverage (otf, stream, offset,
2457                          &subtable->u.mark_mark1.Mark2Coverage);
2458           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2459           read_mark_array (otf, stream, offset,
2460                            &subtable->u.mark_mark1.Mark1Array);
2461           read_anchor_array (otf, stream, offset,
2462                              subtable->u.mark_mark1.ClassCount,
2463                              &subtable->u.mark_mark1.Mark2Array);
2464         }
2465       else
2466         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2467       break;
2468
2469     case 7:
2470       if (subtable->Format == 1)
2471         {
2472           if (read_context1 (otf, stream, offset, &subtable->Coverage,
2473                              &subtable->u.context1) < 0)
2474             return errret;
2475         }
2476       else if (subtable->Format == 2)
2477         {
2478           if (read_context2 (otf, stream, offset, &subtable->Coverage,
2479                              &subtable->u.context2) < 0)
2480             return errret;
2481         }
2482       else if (subtable->Format == 3)
2483         {
2484           if (read_context3 (otf, stream, offset, &subtable->Coverage,
2485                              &subtable->u.context3) < 0)
2486             return errret;
2487         }
2488       else
2489         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2490       break;
2491
2492     case 8:
2493       if (subtable->Format == 1)
2494         {
2495           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
2496                                    &subtable->u.chain_context1) < 0)
2497             return errret;
2498         }
2499       else if (subtable->Format == 2)
2500         {
2501           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
2502                                    &subtable->u.chain_context2) < 0)
2503             return errret;
2504         }
2505       else if (subtable->Format == 3)
2506         {
2507           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
2508                                    &subtable->u.chain_context3) < 0)
2509             return errret;
2510         }
2511       else
2512         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2513       break;
2514
2515     case 9:
2516       if (subtable->Format == 1)
2517         {
2518           unsigned ex_type;
2519           long ex_offset;
2520           OTF_LookupSubTableGPOS *ex_subtable;
2521
2522           READ_USHORT (stream, ex_type);
2523           READ_ULONG (stream, ex_offset);
2524           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
2525           if (read_lookup_subtable_gpos (otf, stream, offset + ex_offset,
2526                                          ex_type, ex_subtable) < 0)
2527             return errret;
2528           subtable->u.extension1.ExtensionLookupType = ex_type;
2529           subtable->u.extension1.ExtensionOffset = ex_offset;
2530           subtable->u.extension1.ExtensionSubtable = ex_subtable;
2531         }
2532       else
2533         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2534       break;
2535
2536     default:
2537       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2538     }
2539   return 0;
2540 }
2541
2542 static void *
2543 read_gpos_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2544 {
2545   return read_gsub_gpos_table (otf, table, 0, flag);
2546 }
2547
2548 \f
2549 #if 0
2550 /* BASE */
2551
2552 static OTF_BASE *
2553 read_base_table (OTF_Stream *stream, long offset)
2554 {
2555   OTF_BASE *base;
2556
2557   OTF_MALLOC (base, 1);
2558
2559   return base;
2560 }
2561
2562 \f
2563 /* JSTF */
2564
2565 static OTF_JSTF *
2566 read_jstf_table (OTF_Stream *stream, long offset)
2567 {
2568   OTF_JSTF *jstf;
2569
2570   OTF_MALLOC (jstf, 1);
2571
2572   return jstf;
2573 }
2574 #endif /* 0 */
2575 \f
2576 /*** (1-11) Structure for OTF */
2577
2578 int
2579 read_offset_table (OTF *otf, OTF_Stream *stream, OTF_OffsetTable *table)
2580 {
2581   int errret = -1;
2582
2583   READ_FIXED (stream, table->sfnt_version);
2584   READ_USHORT (stream, table->numTables);
2585   READ_USHORT (stream, table->searchRange);
2586   READ_USHORT (stream, table->enterSelector);
2587   READ_USHORT (stream, table->rangeShift);
2588   return 0;
2589 }
2590
2591 static OTF_Tag
2592 read_table_directory (OTF_Stream *stream, OTF_TableDirectory *table)
2593 {
2594   int errret = 0;
2595   OTF_Tag tag;
2596
2597   READ_TAG (stream, tag);
2598   table->tag = tag;
2599   table->name[0] = tag >> 24;
2600   table->name[1] = (tag >> 16) & 0xFF;
2601   table->name[0] = (tag >> 8) & 0xFF;
2602   table->name[0] = tag >> 8;
2603   table->name[0] = '\0';
2604   READ_ULONG (stream, table->checkSum);
2605   READ_ULONG (stream, table->offset);
2606   READ_ULONG (stream, table->length);
2607   return tag;
2608 }
2609
2610 static int
2611 read_header_part (OTF *otf, FILE *fp)
2612 {
2613   char *errfmt = "otf header%s";
2614   int errret = -1;
2615   OTF_Tag head_tag, name_tag, cmap_tag, gdef_tag, gsub_tag, gpos_tag;
2616   OTF_Stream *stream;
2617   int i;
2618   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
2619
2620   internal_data->table_info[OTF_TABLE_TYPE_HEAD].address = (void *) &otf->head;
2621   internal_data->table_info[OTF_TABLE_TYPE_HEAD].reader = read_head_table;
2622   internal_data->table_info[OTF_TABLE_TYPE_NAME].address = (void *) &otf->name;
2623   internal_data->table_info[OTF_TABLE_TYPE_NAME].reader = read_name_table;
2624   internal_data->table_info[OTF_TABLE_TYPE_CMAP].address = (void *) &otf->cmap;
2625   internal_data->table_info[OTF_TABLE_TYPE_CMAP].reader = read_cmap_table;
2626   internal_data->table_info[OTF_TABLE_TYPE_GDEF].address = (void *) &otf->gdef;
2627   internal_data->table_info[OTF_TABLE_TYPE_GDEF].reader = read_gdef_table;
2628   internal_data->table_info[OTF_TABLE_TYPE_GSUB].address = (void *) &otf->gsub;
2629   internal_data->table_info[OTF_TABLE_TYPE_GSUB].reader = read_gsub_table;
2630   internal_data->table_info[OTF_TABLE_TYPE_GPOS].address = (void *) &otf->gpos;
2631   internal_data->table_info[OTF_TABLE_TYPE_GPOS].reader = read_gpos_table;
2632
2633   head_tag = OTF_tag ("head");
2634   name_tag = OTF_tag ("name");
2635   cmap_tag = OTF_tag ("cmap");
2636   gdef_tag = OTF_tag ("GDEF");
2637   gsub_tag = OTF_tag ("GSUB");
2638   gpos_tag = OTF_tag ("GPOS");
2639
2640   stream = make_stream ();
2641   if (! stream)
2642     return -1;
2643
2644   internal_data->header_stream = stream;
2645
2646   /* Size of Offset Table is 12 bytes.  */
2647   if (setup_stream (stream, fp, 0, 12, "Offset Table") < 0)
2648     return -1;
2649   if (read_offset_table (otf, stream, &otf->offset_table) < 0)
2650     return -1;
2651
2652   /* Size of each Table Directory is 16 bytes.  */
2653   if (setup_stream (stream, fp, 12, 16 * otf->offset_table.numTables,
2654                     "Table Directory") < 0)
2655     return -1;
2656
2657   OTF_CALLOC (otf->table_dirs, otf->offset_table.numTables, " (OffsetTable)");
2658   for (i = 0; i < otf->offset_table.numTables; i++)
2659     {
2660       OTF_Tag tag = read_table_directory (stream, otf->table_dirs + i);
2661       OTF_TableInfo *table_info = NULL;
2662
2663       if (! tag)
2664         return -1;
2665       if (tag == head_tag)
2666         table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2667       else if (tag == name_tag)
2668         table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2669       else if (tag == cmap_tag)
2670         table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2671       else if (tag == gdef_tag)
2672         table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2673       else if (tag == gsub_tag)
2674         table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2675       else if (tag == gpos_tag)
2676         table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2677
2678       if (table_info)
2679         {
2680           table_info->stream = make_stream ();
2681           if (setup_stream (table_info->stream, fp,
2682                             otf->table_dirs[i].offset,
2683                             otf->table_dirs[i].length,
2684                             otf->table_dirs[i].name) < 0)
2685             return -1;
2686         }
2687     }
2688
2689   internal_data->header_stream = NULL;
2690   free_stream (stream);
2691   return 0;
2692 }
2693
2694 static OTF_TableInfo *
2695 get_table_info (OTF *otf, char *name)
2696 {
2697   char *errfmt = "OTF Table Read%s";
2698   OTF_TableInfo *errret = NULL;
2699   OTF_InternalData *internal_data = otf->internal_data;
2700   OTF_TableInfo *table_info;
2701   OTF_Tag tag = OTF_tag (name);
2702
2703   if (! tag)
2704     OTF_ERROR (OTF_ERROR_TABLE, " (invalid table name)");
2705
2706   if (tag == OTF_tag ("head"))
2707     table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2708   else if (tag == OTF_tag ("name"))
2709     table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2710   else if (tag == OTF_tag ("cmap"))
2711     table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2712   else if (tag == OTF_tag ("GDEF"))
2713     table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2714   else if (tag == OTF_tag ("GSUB"))
2715     table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2716   else if (tag == OTF_tag ("GPOS"))
2717     table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2718   else
2719     OTF_ERROR (OTF_ERROR_TABLE, " (unsupported table name)");
2720
2721   if (*table_info->address)
2722     /* Already read.  */
2723     return table_info;
2724   if (! table_info->stream)
2725     OTF_ERROR (OTF_ERROR_TABLE, " (table not found)");
2726   if (! table_info->reader)
2727     OTF_ERROR (OTF_ERROR_TABLE, " (invalid contents)");
2728   return table_info;
2729 }
2730
2731
2732 \f
2733 /*** (2) API for reading OTF */
2734
2735 /*** (2-1) OTF_open() */
2736
2737 /* Note: We can't use memory allocation macros in the following
2738    functions because those macros return from the functions before
2739    freeing memory previously allocated.  */
2740
2741 OTF *
2742 OTF_open (char *otf_name)
2743 {
2744   FILE *fp;
2745   char *errfmt = "opening otf (%s)";
2746   void *errret = NULL;
2747   OTF *otf;
2748   OTF_InternalData *internal_data;
2749   int len = strlen (otf_name);
2750   const char *ext = otf_name + (len - 4);
2751
2752   if (len < 4
2753       || ext[0] != '.'
2754       || (ext[1] != 'O' && ext[1] != 'T' && ext[1] != 'o' && ext[1] != 't')
2755       || (ext[2] != 'T' && ext[2] != 't')
2756       || (ext[3] != 'F' && ext[3] != 'f'))
2757     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2758   fp = fopen (otf_name, "r");
2759   if (! fp)
2760     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2761   otf = calloc (1, sizeof (OTF));
2762   if (! otf)
2763     OTF_ERROR (OTF_ERROR_MEMORY, "body allocation");
2764   otf->filename = strdup (otf_name);
2765   if (! otf->filename)
2766     {
2767       OTF_close (otf);
2768       fclose (fp);
2769       OTF_ERROR (OTF_ERROR_MEMORY, "filename allocation");
2770     }
2771
2772   internal_data = calloc (1, sizeof (OTF_InternalData));
2773   if (! internal_data)
2774     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData");
2775   otf->internal_data = internal_data;
2776   if (! allocate_memory_record (otf))
2777     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData)");
2778
2779   /* Here after, all pointers to allocated memory are recorded in
2780      otf->internal_data->memory_record except for what allocated by
2781      the functions allocate_memory_record and make_stream.  */
2782
2783   if (read_header_part (otf, fp) < 0)
2784     {
2785       OTF_close (otf);
2786       fclose (fp);
2787       return NULL;
2788     }
2789
2790   fclose (fp);
2791   return otf;
2792 }
2793
2794 /*** (2-2) OTF_close() */
2795
2796 void
2797 OTF_close (OTF *otf)
2798 {
2799   OTF_InternalData *internal_data = otf->internal_data;
2800   int i;
2801
2802   if (internal_data)
2803     {
2804       OTF_MemoryRecord *memrec = internal_data->memory_record;
2805
2806       if (internal_data->header_stream)
2807         free_stream (internal_data->header_stream);
2808
2809       for (i = 0; i < OTF_TABLE_TYPE_MAX; i++)
2810         if (internal_data->table_info[i].stream)
2811           free_stream (internal_data->table_info[i].stream);
2812
2813       while (memrec)
2814         {
2815           OTF_MemoryRecord *next = memrec->next;
2816
2817           for (i = memrec->used - 1; i >= 0; i--)
2818             free (memrec->memory[i]);
2819           free (memrec);
2820           memrec = next;
2821         }
2822       free (internal_data);
2823     }
2824   if (otf->filename)
2825     free (otf->filename);
2826   free (otf);
2827 }
2828
2829 /*** (2-3) OTF_get_table() */
2830
2831 int
2832 OTF_get_table (OTF *otf, char *name)
2833 {
2834   OTF_TableInfo *table_info = get_table_info (otf, name);
2835   void *address;
2836
2837   if (! table_info)
2838     return -1;
2839   if (! table_info->stream)
2840     /* Already fully loaded.  */
2841     return 0;
2842
2843   address = (*table_info->reader) (otf, table_info, OTF_READ_FULL);
2844   free_stream (table_info->stream);
2845   table_info->stream = NULL;
2846   if (! address)
2847     {
2848       table_info->reader = NULL;
2849       return -1;
2850     }
2851   return 0;
2852 }
2853
2854 /*** (2-4) OTF_check_table() */
2855
2856 int
2857 OTF_check_table (OTF *otf, char *name)
2858 {
2859   return (get_table_info (otf, name) ? 0 : -1);
2860 }
2861
2862 /*** (2-5) OTF_get_scripts()  */
2863
2864 int
2865 OTF_get_scripts (OTF *otf, int gsubp)
2866 {
2867   OTF_TableInfo *table_info
2868     = (otf->internal_data->table_info
2869        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
2870   void *address;
2871
2872   if (! table_info->reader)
2873     return -1;
2874   if (! table_info->stream)
2875     /* Already fully loaded.  */
2876     return 0;
2877
2878   address = (*table_info->reader) (otf, table_info, OTF_READ_SCRIPTS);
2879   if (! address)
2880     {
2881       table_info->reader = NULL;
2882       return -1;
2883     }
2884   return 0;
2885 }
2886
2887 /*** (2-6) OTF_get_features()  */
2888
2889 int
2890 OTF_get_features (OTF *otf, int gsubp)
2891 {
2892   OTF_TableInfo *table_info
2893     = (otf->internal_data->table_info
2894        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
2895   void *address;
2896
2897   if (! table_info->reader)
2898     return -1;
2899   if (! table_info->stream)
2900     {
2901       if (*table_info->address)
2902         /* Already fully loaded.  */
2903         return 0;
2904       return -1;
2905     }
2906
2907   address = (*table_info->reader) (otf, table_info, OTF_READ_FEATURES);
2908   if (! address)
2909     {
2910       table_info->reader = NULL;
2911       return -1;
2912     }
2913   return 0;
2914 }
2915
2916 /*** (2-7) OTF_check_features  */
2917
2918 int
2919 OTF_check_features (OTF *otf, int gsubp,
2920                     OTF_Tag script, OTF_Tag language, OTF_Tag *features,
2921                     int n_features)
2922 {
2923   OTF_ScriptList *script_list;
2924   OTF_Script *Script = NULL;
2925   OTF_LangSys *LangSys = NULL;
2926   OTF_FeatureList *feature_list;
2927   int i, j;
2928
2929   if (OTF_get_features (otf, gsubp) < 0)
2930     {
2931       for (i = 0; i < n_features; i++)
2932         {
2933           OTF_Tag feature = features[i];
2934
2935           if (feature == 0)
2936             continue;
2937           if ((((unsigned) feature) & 0x80000000) == 0)
2938             return -1;
2939         }
2940       return 1;
2941     }
2942   if (gsubp)
2943     {
2944       script_list = &otf->gsub->ScriptList;
2945       feature_list = &otf->gsub->FeatureList;
2946     }
2947   else
2948     {
2949       script_list = &otf->gpos->ScriptList;
2950       feature_list = &otf->gpos->FeatureList;
2951     }
2952   for (i = 0; i < script_list->ScriptCount && ! Script; i++)
2953     if (script_list->Script[i].ScriptTag == script)
2954       Script = script_list->Script + i;
2955   if (! Script)
2956     return 0;
2957   if (language)
2958     {
2959       for (i = 0; i < Script->LangSysCount && ! LangSys; i++)
2960         if (Script->LangSysRecord[i].LangSysTag == language)
2961           LangSys = Script->LangSys + i;
2962     }
2963   if (! LangSys)
2964     LangSys = &Script->DefaultLangSys;
2965   for (j = 0; j < n_features; j++)
2966     {
2967       OTF_Tag feature = features[j];
2968       int negate = 0;
2969
2970       if (feature == 0)
2971         continue;
2972       if (((unsigned) feature) & 0x80000000)
2973         {
2974           feature = (OTF_Tag) (((unsigned) feature) & 0x7FFFFFFF);
2975           negate = 1;
2976         }
2977       for (i = 0; i < LangSys->FeatureCount; i++)
2978         if (feature_list->Feature[LangSys->FeatureIndex[i]].FeatureTag
2979             == feature)
2980           {
2981             if (negate)
2982               return 0;
2983             break;
2984           }
2985       if (i == LangSys->FeatureCount)
2986         return 0;
2987     }
2988   return 1;
2989 }
2990
2991 \f
2992 /*** (5) API miscellaneous ***/
2993
2994 OTF_Tag
2995 OTF_tag (char *name)
2996 {
2997   unsigned char *p = (unsigned char *) name;
2998
2999   if (! name)
3000     return (OTF_Tag) 0;
3001   return (OTF_Tag) ((p[0] << 24)
3002                     | (! p[1] ? 0
3003                        : ((p[1] << 16)
3004                           | (! p[2] ? 0
3005                              : (p[2] << 8) | p[3]))));
3006 }
3007
3008 void
3009 OTF_tag_name (OTF_Tag tag, char *name)
3010 {
3011   name[0] = (char) (tag >> 24);
3012   name[1] = (char) ((tag >> 16) & 0xFF);
3013   name[2] = (char) ((tag >> 8) & 0xFF);
3014   name[3] = (char) (tag & 0xFF);
3015   name[4] = '\0';
3016 }