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