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