hb-aat-layout-kerx-table.hh 29.3 KB
Newer Older
1 2
/*
 * Copyright © 2018  Ebrahim Byagowi
3
 * Copyright © 2018  Google, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 *  This is part of HarfBuzz, a text shaping library.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that the
 * above copyright notice and the following two paragraphs appear in
 * all copies of this software.
 *
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Google Author(s): Behdad Esfahbod
 */

#ifndef HB_AAT_LAYOUT_KERX_TABLE_HH
#define HB_AAT_LAYOUT_KERX_TABLE_HH

31
#include "hb-kern.hh"
B
Behdad Esfahbod 已提交
32
#include "hb-aat-layout-ankr-table.hh"
33

34 35 36 37
/*
 * kerx -- Extended Kerning
 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kerx.html
 */
38
#define HB_AAT_TAG_kerx HB_TAG('k','e','r','x')
39 40


41
namespace AAT {
42

43
using namespace OT;
44 45


46 47 48 49 50 51
static inline int
kerxTupleKern (int value,
	       unsigned int tupleCount,
	       const void *base,
	       hb_aat_apply_context_t *c)
{
52
  if (likely (!tupleCount || !c)) return value;
53 54 55

  unsigned int offset = value;
  const FWORD *pv = &StructAtOffset<FWORD> (base, offset);
56
  if (unlikely (!c->sanitizer.check_array (pv, tupleCount))) return 0;
57 58 59 60
  return *pv;
}


B
Behdad Esfahbod 已提交
61
struct hb_glyph_pair_t
B
Behdad Esfahbod 已提交
62
{
B
Behdad Esfahbod 已提交
63 64 65
  hb_codepoint_t left;
  hb_codepoint_t right;
};
B
Behdad Esfahbod 已提交
66

B
Behdad Esfahbod 已提交
67 68 69 70 71 72
struct KernPair
{
  inline int get_kerning (void) const
  { return value; }

  inline int cmp (const hb_glyph_pair_t &o) const
73
  {
B
Behdad Esfahbod 已提交
74 75 76 77
    int ret = left.cmp (o.left);
    if (ret) return ret;
    return right.cmp (o.right);
  }
78

B
Behdad Esfahbod 已提交
79 80 81
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
82
    return_trace (c->check_struct (this));
B
Behdad Esfahbod 已提交
83 84
  }

B
Behdad Esfahbod 已提交
85 86 87 88
  protected:
  GlyphID	left;
  GlyphID	right;
  FWORD		value;
B
Behdad Esfahbod 已提交
89
  public:
B
Behdad Esfahbod 已提交
90
  DEFINE_SIZE_STATIC (6);
B
Behdad Esfahbod 已提交
91 92
};

93
template <typename KernSubTableHeader>
B
Behdad Esfahbod 已提交
94
struct KerxSubTableFormat0
95
{
96
  inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right,
97
			  hb_aat_apply_context_t *c = nullptr) const
98
  {
B
Behdad Esfahbod 已提交
99
    hb_glyph_pair_t pair = {left, right};
100
    int v = pairs.bsearch (pair).get_kerning ();
B
Behdad Esfahbod 已提交
101
    return kerxTupleKern (v, header.tuple_count (), this, c);
102 103
  }

104 105 106 107
  inline bool apply (hb_aat_apply_context_t *c) const
  {
    TRACE_APPLY (this);

108 109 110
    if (!c->plan->requested_kerning)
      return false;

111
    if (header.coverage & header.Backwards)
112 113
      return false;

114
    accelerator_t accel (*this, c);
115
    hb_kern_machine_t<accelerator_t> machine (accel, header.coverage & header.CrossStream);
B
Behdad Esfahbod 已提交
116
    machine.kern (c->font, c->buffer, c->plan->kern_mask);
117 118 119

    return_trace (true);
  }
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134
  struct accelerator_t
  {
    const KerxSubTableFormat0 &table;
    hb_aat_apply_context_t *c;

    inline accelerator_t (const KerxSubTableFormat0 &table_,
			  hb_aat_apply_context_t *c_) :
			    table (table_), c (c_) {}

    inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right) const
    { return table.get_kerning (left, right, c); }
  };


135 136 137
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
138
    return_trace (likely (pairs.sanitize (c)));
139 140 141
  }

  protected:
142
  KernSubTableHeader	header;
B
Behdad Esfahbod 已提交
143
  BinSearchArrayOf<KernPair, typename KernSubTableHeader::Types::HBUINT>
B
Behdad Esfahbod 已提交
144
			pairs;	/* Sorted kern records. */
145
  public:
146
  DEFINE_SIZE_ARRAY (KernSubTableHeader::static_size + 16, pairs);
147 148
};

B
Behdad Esfahbod 已提交
149 150 151 152 153 154

template <bool extended>
struct Format1Entry;

template <>
struct Format1Entry<true>
155
{
B
Behdad Esfahbod 已提交
156 157 158 159 160 161 162 163 164
  enum Flags
  {
    Push		= 0x8000,	/* If set, push this glyph on the kerning stack. */
    DontAdvance		= 0x4000,	/* If set, don't advance to the next glyph
					 * before going to the new state. */
    Reset		= 0x2000,	/* If set, reset the kerning data (clear the stack) */
    Reserved		= 0x1FFF,	/* Not used; set to 0. */
  };

165 166
  struct EntryData
  {
B
Behdad Esfahbod 已提交
167 168 169
    HBUINT16	kernActionIndex;/* Index into the kerning value array. If
				 * this index is 0xFFFF, then no kerning
				 * is to be performed. */
170 171 172
    public:
    DEFINE_SIZE_STATIC (2);
  };
173 174 175 176 177 178

  static inline bool performAction (const Entry<EntryData> *entry)
  { return entry->data.kernActionIndex != 0xFFFF; }

  static inline unsigned int kernActionIndex (const Entry<EntryData> *entry)
  { return entry->data.kernActionIndex; }
B
Behdad Esfahbod 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
};
template <>
struct Format1Entry<false>
{
  enum Flags
  {
    Push		= 0x8000,	/* If set, push this glyph on the kerning stack. */
    DontAdvance		= 0x4000,	/* If set, don't advance to the next glyph
					 * before going to the new state. */
    Offset		= 0x3FFF,	/* Byte offset from beginning of subtable to the
					 * value table for the glyphs on the kerning stack. */

    Reset		= 0x0000,	/* Not supported? */
  };

  typedef void EntryData;
195 196 197 198 199 200

  static inline bool performAction (const Entry<EntryData> *entry)
  { return entry->flags & Offset; }

  static inline unsigned int kernActionIndex (const Entry<EntryData> *entry)
  { return entry->flags & Offset; }
B
Behdad Esfahbod 已提交
201 202 203 204 205 206 207 208 209 210
};

template <typename KernSubTableHeader>
struct KerxSubTableFormat1
{
  typedef typename KernSubTableHeader::Types Types;
  typedef typename Types::HBUINT HBUINT;

  typedef Format1Entry<Types::extended> Format1EntryT;
  typedef typename Format1EntryT::EntryData EntryData;
211 212 213 214

  struct driver_context_t
  {
    static const bool in_place = true;
B
Behdad Esfahbod 已提交
215
    enum
216
    {
B
Behdad Esfahbod 已提交
217
      DontAdvance	= Format1EntryT::DontAdvance,
218 219
    };

220
    inline driver_context_t (const KerxSubTableFormat1 *table_,
B
Behdad Esfahbod 已提交
221 222
			     hb_aat_apply_context_t *c_) :
	c (c_),
223
	table (table_),
B
Behdad Esfahbod 已提交
224 225 226
	/* Apparently the offset kernAction is from the beginning of the state-machine,
	 * similar to offsets in morx table, NOT from beginning of this table, like
	 * other subtables in kerx.  Discovered via testing. */
B
Behdad Esfahbod 已提交
227
	kernAction (&table->machine + table->kernAction),
228
	depth (0),
229
	crossStream (table->header.coverage & table->header.CrossStream) {}
230

231
    inline bool is_actionable (StateTableDriver<Types, EntryData> *driver HB_UNUSED,
232 233
			       const Entry<EntryData> *entry)
    {
234
      return Format1EntryT::performAction (entry);
235
    }
236
    inline bool transition (StateTableDriver<Types, EntryData> *driver,
237 238
			    const Entry<EntryData> *entry)
    {
B
Behdad Esfahbod 已提交
239 240 241
      hb_buffer_t *buffer = driver->buffer;
      unsigned int flags = entry->flags;

B
Behdad Esfahbod 已提交
242
      if (flags & Format1EntryT::Reset)
B
Behdad Esfahbod 已提交
243
	depth = 0;
B
Behdad Esfahbod 已提交
244

B
Behdad Esfahbod 已提交
245
      if (flags & Format1EntryT::Push)
B
Behdad Esfahbod 已提交
246
      {
B
Behdad Esfahbod 已提交
247
	if (likely (depth < ARRAY_LENGTH (stack)))
B
Behdad Esfahbod 已提交
248 249 250 251 252
	  stack[depth++] = buffer->idx;
	else
	  depth = 0; /* Probably not what CoreText does, but better? */
      }

253
      if (Format1EntryT::performAction (entry) && depth)
B
Behdad Esfahbod 已提交
254
      {
255 256
	unsigned int tuple_count = MAX (1u, table->header.tuple_count ());

257 258 259
	unsigned int kern_idx = Format1EntryT::kernActionIndex (entry);
	kern_idx = Types::offsetToIndex (kern_idx, &table->machine, kernAction.arrayZ);
	const FWORD *actions = &kernAction[kern_idx];
260
	if (!c->sanitizer.check_array (actions, depth, tuple_count))
B
Behdad Esfahbod 已提交
261 262 263 264 265
	{
	  depth = 0;
	  return false;
	}

266
	hb_mask_t kern_mask = c->plan->kern_mask;
267 268 269 270

	/* From Apple 'kern' spec:
	 * "Each pops one glyph from the kerning stack and applies the kerning value to it.
	 * The end of the list is marked by an odd value... */
271
	bool last = false;
272
	while (!last && depth)
B
Behdad Esfahbod 已提交
273
	{
274
	  unsigned int idx = stack[--depth];
275 276
	  int v = *actions;
	  actions += tuple_count;
B
Behdad Esfahbod 已提交
277 278
	  if (idx >= buffer->len) continue;

279 280
	  /* "The end of the list is marked by an odd value..." */
	  last = v & 1;
281 282
	  v &= ~1;

283 284
	  hb_glyph_position_t &o = buffer->pos[idx];

B
Behdad Esfahbod 已提交
285 286 287 288
	  /* Testing shows that CoreText only applies kern (cross-stream or not)
	   * if none has been applied by previous subtables.  That is, it does
	   * NOT seem to accumulate as otherwise implied by specs. */

289 290
	  /* The following flag is undocumented in the spec, but described
	   * in the 'kern' table example. */
291
	  if (v == -0x8000)
292
	  {
293 294 295
	    o.attach_type() = ATTACH_TYPE_NONE;
	    o.attach_chain() = 0;
	    o.x_offset = o.y_offset = 0;
296
	  }
297
	  else if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
298
	  {
B
Behdad Esfahbod 已提交
299
	    if (crossStream)
B
Behdad Esfahbod 已提交
300
	    {
301 302 303 304 305
	      if (buffer->pos[idx].attach_type() && !buffer->pos[idx].y_offset)
	      {
		o.y_offset = c->font->em_scale_y (v);
		buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
	      }
B
Behdad Esfahbod 已提交
306
	    }
B
Behdad Esfahbod 已提交
307
	    else if (buffer->info[idx].mask & kern_mask)
B
Behdad Esfahbod 已提交
308
	    {
B
Behdad Esfahbod 已提交
309
	      if (!buffer->pos[idx].x_offset)
310
	      {
B
Behdad Esfahbod 已提交
311 312
		buffer->pos[idx].x_advance += c->font->em_scale_x (v);
		buffer->pos[idx].x_offset += c->font->em_scale_x (v);
313
	      }
B
Behdad Esfahbod 已提交
314 315 316 317 318 319 320
	    }
	  }
	  else
	  {
	    if (crossStream)
	    {
	      /* CoreText doesn't do crossStream kerning in vertical.  We do. */
321 322 323 324 325
	      if (buffer->pos[idx].attach_type() && !buffer->pos[idx].x_offset)
	      {
		o.x_offset = c->font->em_scale_x (v);
		buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
	      }
B
Behdad Esfahbod 已提交
326 327 328 329
	    }
	    else if (buffer->info[idx].mask & kern_mask)
	    {
	      if (!buffer->pos[idx].y_offset)
330
	      {
B
Behdad Esfahbod 已提交
331 332
		buffer->pos[idx].y_advance += c->font->em_scale_y (v);
		buffer->pos[idx].y_offset += c->font->em_scale_y (v);
333
	      }
B
Behdad Esfahbod 已提交
334
	    }
335
	  }
B
Behdad Esfahbod 已提交
336 337
	}
      }
338 339 340 341 342

      return true;
    }

    private:
B
Behdad Esfahbod 已提交
343
    hb_aat_apply_context_t *c;
344
    const KerxSubTableFormat1 *table;
B
Behdad Esfahbod 已提交
345 346 347
    const UnsizedArrayOf<FWORD> &kernAction;
    unsigned int stack[8];
    unsigned int depth;
348
    bool crossStream;
349 350
  };

351 352 353 354
  inline bool apply (hb_aat_apply_context_t *c) const
  {
    TRACE_APPLY (this);

355 356
    if (!c->plan->requested_kerning &&
	!(header.coverage & header.CrossStream))
357 358
      return false;

B
Behdad Esfahbod 已提交
359
    driver_context_t dc (this, c);
360

361
    StateTableDriver<Types, EntryData> driver (machine, c->buffer, c->font->face);
362
    driver.drive (&dc);
363 364 365 366

    return_trace (true);
  }

367 368
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
369
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
370 371 372
    /* The rest of array sanitizations are done at run-time. */
    return_trace (likely (c->check_struct (this) &&
			  machine.sanitize (c)));
373 374 375
  }

  protected:
376
  KernSubTableHeader				header;
B
Behdad Esfahbod 已提交
377 378
  StateTable<Types, EntryData>			machine;
  OffsetTo<UnsizedArrayOf<FWORD>, HBUINT, false>kernAction;
379
  public:
B
Behdad Esfahbod 已提交
380
  DEFINE_SIZE_STATIC (KernSubTableHeader::static_size + 5 * sizeof (HBUINT));
381 382
};

383
template <typename KernSubTableHeader>
384 385
struct KerxSubTableFormat2
{
B
Behdad Esfahbod 已提交
386 387 388
  typedef typename KernSubTableHeader::Types Types;
  typedef typename Types::HBUINT HBUINT;

B
Behdad Esfahbod 已提交
389
  inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right,
390
			  hb_aat_apply_context_t *c) const
391
  {
392
    unsigned int num_glyphs = c->sanitizer.get_num_glyphs ();
B
Behdad Esfahbod 已提交
393 394
    unsigned int l = (this+leftClassTable).get_class (left, num_glyphs, 0);
    unsigned int r = (this+rightClassTable).get_class (right, num_glyphs, 0);
395
    unsigned int offset = l + r;
B
Behdad Esfahbod 已提交
396 397
    const FWORD *v = &StructAtOffset<FWORD> (&(this+array), offset);
    if (unlikely (!v->sanitize (&c->sanitizer))) return 0;
B
Behdad Esfahbod 已提交
398
    return kerxTupleKern (*v, header.tuple_count (), this, c);
399 400
  }

401 402 403 404
  inline bool apply (hb_aat_apply_context_t *c) const
  {
    TRACE_APPLY (this);

405 406 407
    if (!c->plan->requested_kerning)
      return false;

408
    if (header.coverage & header.Backwards)
409 410
      return false;

411
    accelerator_t accel (*this, c);
412
    hb_kern_machine_t<accelerator_t> machine (accel, header.coverage & header.CrossStream);
B
Behdad Esfahbod 已提交
413
    machine.kern (c->font, c->buffer, c->plan->kern_mask);
414 415 416 417

    return_trace (true);
  }

B
Behdad Esfahbod 已提交
418 419 420
  struct accelerator_t
  {
    const KerxSubTableFormat2 &table;
421
    hb_aat_apply_context_t *c;
B
Behdad Esfahbod 已提交
422 423

    inline accelerator_t (const KerxSubTableFormat2 &table_,
424 425
			  hb_aat_apply_context_t *c_) :
			    table (table_), c (c_) {}
B
Behdad Esfahbod 已提交
426 427

    inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right) const
428
    { return table.get_kerning (left, right, c); }
B
Behdad Esfahbod 已提交
429 430
  };

431 432 433 434 435 436 437 438 439
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    return_trace (likely (c->check_struct (this) &&
			  leftClassTable.sanitize (c, this) &&
			  rightClassTable.sanitize (c, this) &&
			  c->check_range (this, array)));
  }

B
Behdad Esfahbod 已提交
440 441 442 443 444 445
  /* Note:
   * OT kern table specifies ClassTable as having 16-bit entries, whereas
   * AAT kern table specifies them as having 8bit entries.
   * I've not seen any fonts with this format in kern table.
   * We follow AAT. */

446
  protected:
447
  KernSubTableHeader	header;
B
Behdad Esfahbod 已提交
448 449
  HBUINT		rowWidth;	/* The width, in bytes, of a row in the table. */
  OffsetTo<typename Types::ClassType, HBUINT, false>
B
Behdad Esfahbod 已提交
450 451
			leftClassTable;	/* Offset from beginning of this subtable to
					 * left-hand class table. */
B
Behdad Esfahbod 已提交
452
  OffsetTo<typename Types::ClassType, HBUINT, false>
B
Behdad Esfahbod 已提交
453 454
			rightClassTable;/* Offset from beginning of this subtable to
					 * right-hand class table. */
B
Behdad Esfahbod 已提交
455
  OffsetTo<UnsizedArrayOf<FWORD>, HBUINT, false>
B
Behdad Esfahbod 已提交
456
			 array;		/* Offset from beginning of this subtable to
B
Behdad Esfahbod 已提交
457
					 * the start of the kerning array. */
458
  public:
B
Behdad Esfahbod 已提交
459
  DEFINE_SIZE_STATIC (KernSubTableHeader::static_size + 4 * sizeof (HBUINT));
460 461
};

462
template <typename KernSubTableHeader>
463 464
struct KerxSubTableFormat4
{
B
Behdad Esfahbod 已提交
465 466
  typedef ExtendedTypes Types;

B
Behdad Esfahbod 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
  struct EntryData
  {
    HBUINT16	ankrActionIndex;/* Either 0xFFFF (for no action) or the index of
				 * the action to perform. */
    public:
    DEFINE_SIZE_STATIC (2);
  };

  struct driver_context_t
  {
    static const bool in_place = true;
    enum Flags
    {
      Mark		= 0x8000,	/* If set, remember this glyph as the marked glyph. */
      DontAdvance	= 0x4000,	/* If set, don't advance to the next glyph before
					 * going to the new state. */
      Reserved		= 0x3FFF,	/* Not used; set to 0. */
    };

    enum SubTableFlags
    {
      ActionType	= 0xC0000000,	/* A two-bit field containing the action type. */
      Unused		= 0x3F000000,	/* Unused - must be zero. */
      Offset		= 0x00FFFFFF,	/* Masks the offset in bytes from the beginning
					 * of the subtable to the beginning of the control
					 * point table. */
    };

    inline driver_context_t (const KerxSubTableFormat4 *table,
			     hb_aat_apply_context_t *c_) :
	c (c_),
	action_type ((table->flags & ActionType) >> 30),
	ankrData ((HBUINT16 *) ((const char *) &table->machine + (table->flags & Offset))),
	mark_set (false),
	mark (0) {}

B
Behdad Esfahbod 已提交
503
    inline bool is_actionable (StateTableDriver<Types, EntryData> *driver HB_UNUSED,
B
Behdad Esfahbod 已提交
504 505 506 507
			       const Entry<EntryData> *entry)
    {
      return entry->data.ankrActionIndex != 0xFFFF;
    }
B
Behdad Esfahbod 已提交
508
    inline bool transition (StateTableDriver<Types, EntryData> *driver,
B
Behdad Esfahbod 已提交
509 510 511 512
			    const Entry<EntryData> *entry)
    {
      hb_buffer_t *buffer = driver->buffer;

513
      if (mark_set && entry->data.ankrActionIndex != 0xFFFF && buffer->idx < buffer->len)
B
Behdad Esfahbod 已提交
514
      {
515
	hb_glyph_position_t &o = buffer->cur_pos();
B
Behdad Esfahbod 已提交
516 517 518 519 520 521 522 523 524 525
	switch (action_type)
	{
	  case 0: /* Control Point Actions.*/
	  {
	    /* indexed into glyph outline. */
	    const HBUINT16 *data = &ankrData[entry->data.ankrActionIndex];
	    if (!c->sanitizer.check_array (data, 2))
	      return false;
	    HB_UNUSED unsigned int markControlPoint = *data++;
	    HB_UNUSED unsigned int currControlPoint = *data++;
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
	    hb_position_t markX = 0;
	    hb_position_t markY = 0;
	    hb_position_t currX = 0;
	    hb_position_t currY = 0;
	    if (!c->font->get_glyph_contour_point_for_origin (c->buffer->info[mark].codepoint,
							      markControlPoint,
							      HB_DIRECTION_LTR /*XXX*/,
							      &markX, &markY) ||
		!c->font->get_glyph_contour_point_for_origin (c->buffer->cur ().codepoint,
							      currControlPoint,
							      HB_DIRECTION_LTR /*XXX*/,
							      &currX, &currY))
	      return true; /* True, such that the machine continues. */

	    o.x_offset = markX - currX;
	    o.y_offset = markY - currY;
B
Behdad Esfahbod 已提交
542 543 544 545 546 547 548 549 550
	  }
	  break;

	  case 1: /* Anchor Point Actions. */
	  {
	   /* Indexed into 'ankr' table. */
	    const HBUINT16 *data = &ankrData[entry->data.ankrActionIndex];
	    if (!c->sanitizer.check_array (data, 2))
	      return false;
551 552
	    unsigned int markAnchorPoint = *data++;
	    unsigned int currAnchorPoint = *data++;
553 554 555 556 557 558 559 560
	    const Anchor markAnchor = c->ankr_table->get_anchor (c->buffer->info[mark].codepoint,
								 markAnchorPoint,
								 c->sanitizer.get_num_glyphs (),
								 c->ankr_end);
	    const Anchor currAnchor = c->ankr_table->get_anchor (c->buffer->cur ().codepoint,
								 currAnchorPoint,
								 c->sanitizer.get_num_glyphs (),
								 c->ankr_end);
561

562 563
	    o.x_offset = c->font->em_scale_x (markAnchor.xCoordinate) - c->font->em_scale_x (currAnchor.xCoordinate);
	    o.y_offset = c->font->em_scale_y (markAnchor.yCoordinate) - c->font->em_scale_y (currAnchor.yCoordinate);
B
Behdad Esfahbod 已提交
564 565 566 567 568 569 570 571
	  }
	  break;

	  case 2: /* Control Point Coordinate Actions. */
	  {
	    const FWORD *data = (const FWORD *) &ankrData[entry->data.ankrActionIndex];
	    if (!c->sanitizer.check_array (data, 4))
	      return false;
572 573 574 575 576 577 578
	    int markX = *data++;
	    int markY = *data++;
	    int currX = *data++;
	    int currY = *data++;

	    o.x_offset = c->font->em_scale_x (markX) - c->font->em_scale_x (currX);
	    o.y_offset = c->font->em_scale_y (markY) - c->font->em_scale_y (currY);
B
Behdad Esfahbod 已提交
579 580 581
	  }
	  break;
	}
582 583 584
	o.attach_type() = ATTACH_TYPE_MARK;
	o.attach_chain() = (int) mark - (int) buffer->idx;
	buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
B
Behdad Esfahbod 已提交
585 586
      }

B
Behdad Esfahbod 已提交
587
      if (entry->flags & Mark)
B
Behdad Esfahbod 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
      {
	mark_set = true;
	mark = buffer->idx;
      }

      return true;
    }

    private:
    hb_aat_apply_context_t *c;
    unsigned int action_type;
    const HBUINT16 *ankrData;
    bool mark_set;
    unsigned int mark;
  };

604 605 606 607
  inline bool apply (hb_aat_apply_context_t *c) const
  {
    TRACE_APPLY (this);

B
Behdad Esfahbod 已提交
608 609
    driver_context_t dc (this, c);

B
Behdad Esfahbod 已提交
610
    StateTableDriver<Types, EntryData> driver (machine, c->buffer, c->font->face);
B
Behdad Esfahbod 已提交
611
    driver.drive (&dc);
612 613 614 615

    return_trace (true);
  }

616 617 618
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
619
    /* The rest of array sanitizations are done at run-time. */
B
Behdad Esfahbod 已提交
620 621
    return_trace (likely (c->check_struct (this) &&
			  machine.sanitize (c)));
622 623 624
  }

  protected:
B
Behdad Esfahbod 已提交
625 626 627
  KernSubTableHeader		header;
  StateTable<Types, EntryData>	machine;
  HBUINT32			flags;
628
  public:
629
  DEFINE_SIZE_STATIC (KernSubTableHeader::static_size + 20);
630 631
};

632
template <typename KernSubTableHeader>
633 634
struct KerxSubTableFormat6
{
635 636 637 638 639 640 641
  enum Flags
  {
    ValuesAreLong	= 0x00000001,
  };

  inline bool is_long (void) const { return flags & ValuesAreLong; }

B
Behdad Esfahbod 已提交
642
  inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right,
643
			  hb_aat_apply_context_t *c) const
B
Behdad Esfahbod 已提交
644
  {
645
    unsigned int num_glyphs = c->sanitizer.get_num_glyphs ();
B
Behdad Esfahbod 已提交
646 647
    if (is_long ())
    {
648
      const typename U::Long &t = u.l;
B
Behdad Esfahbod 已提交
649 650 651
      unsigned int l = (this+t.rowIndexTable).get_value_or_null (left, num_glyphs);
      unsigned int r = (this+t.columnIndexTable).get_value_or_null (right, num_glyphs);
      unsigned int offset = l + r;
B
Behdad Esfahbod 已提交
652 653
      if (unlikely (offset < l)) return 0; /* Addition overflow. */
      if (unlikely (hb_unsigned_mul_overflows (offset, sizeof (FWORD32)))) return 0;
B
Behdad Esfahbod 已提交
654 655
      const FWORD32 *v = &StructAtOffset<FWORD32> (&(this+t.array), offset * sizeof (FWORD32));
      if (unlikely (!v->sanitize (&c->sanitizer))) return 0;
B
Behdad Esfahbod 已提交
656
      return kerxTupleKern (*v, header.tuple_count (), &(this+vector), c);
B
Behdad Esfahbod 已提交
657 658 659
    }
    else
    {
660
      const typename U::Short &t = u.s;
B
Behdad Esfahbod 已提交
661 662 663
      unsigned int l = (this+t.rowIndexTable).get_value_or_null (left, num_glyphs);
      unsigned int r = (this+t.columnIndexTable).get_value_or_null (right, num_glyphs);
      unsigned int offset = l + r;
B
Behdad Esfahbod 已提交
664 665
      const FWORD *v = &StructAtOffset<FWORD> (&(this+t.array), offset * sizeof (FWORD));
      if (unlikely (!v->sanitize (&c->sanitizer))) return 0;
B
Behdad Esfahbod 已提交
666
      return kerxTupleKern (*v, header.tuple_count (), &(this+vector), c);
B
Behdad Esfahbod 已提交
667 668 669
    }
  }

670 671 672 673
  inline bool apply (hb_aat_apply_context_t *c) const
  {
    TRACE_APPLY (this);

674 675 676
    if (!c->plan->requested_kerning)
      return false;

677
    if (header.coverage & header.Backwards)
678 679
      return false;

680
    accelerator_t accel (*this, c);
681
    hb_kern_machine_t<accelerator_t> machine (accel, header.coverage & header.CrossStream);
B
Behdad Esfahbod 已提交
682
    machine.kern (c->font, c->buffer, c->plan->kern_mask);
683 684 685 686

    return_trace (true);
  }

687 688
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
689
    TRACE_SANITIZE (this);
E
Ebrahim Byagowi 已提交
690
    return_trace (likely (c->check_struct (this) &&
B
Behdad Esfahbod 已提交
691 692 693 694 695 696 697 698 699
			  (is_long () ?
			   (
			     u.l.rowIndexTable.sanitize (c, this) &&
			     u.l.columnIndexTable.sanitize (c, this) &&
			     c->check_range (this, u.l.array)
			   ) : (
			     u.s.rowIndexTable.sanitize (c, this) &&
			     u.s.columnIndexTable.sanitize (c, this) &&
			     c->check_range (this, u.s.array)
700
			   )) &&
B
Behdad Esfahbod 已提交
701
			  (header.tuple_count () == 0 ||
702
			   c->check_range (this, vector))));
703 704
  }

B
Behdad Esfahbod 已提交
705 706 707
  struct accelerator_t
  {
    const KerxSubTableFormat6 &table;
708
    hb_aat_apply_context_t *c;
B
Behdad Esfahbod 已提交
709 710

    inline accelerator_t (const KerxSubTableFormat6 &table_,
711 712
			  hb_aat_apply_context_t *c_) :
			    table (table_), c (c_) {}
B
Behdad Esfahbod 已提交
713 714

    inline int get_kerning (hb_codepoint_t left, hb_codepoint_t right) const
715
    { return table.get_kerning (left, right, c); }
B
Behdad Esfahbod 已提交
716 717
  };

718
  protected:
719
  KernSubTableHeader		header;
B
Behdad Esfahbod 已提交
720 721 722
  HBUINT32			flags;
  HBUINT16			rowCount;
  HBUINT16			columnCount;
B
Behdad Esfahbod 已提交
723
  union U
724
  {
B
Behdad Esfahbod 已提交
725
    struct Long
726
    {
727 728 729
      LOffsetTo<Lookup<HBUINT32>, false>	rowIndexTable;
      LOffsetTo<Lookup<HBUINT32>, false>	columnIndexTable;
      LOffsetTo<UnsizedArrayOf<FWORD32>, false>	array;
730
    } l;
B
Behdad Esfahbod 已提交
731 732
    struct Short
    {
733 734 735
      LOffsetTo<Lookup<HBUINT16>, false>	rowIndexTable;
      LOffsetTo<Lookup<HBUINT16>, false>	columnIndexTable;
      LOffsetTo<UnsizedArrayOf<FWORD>, false>	array;
B
Behdad Esfahbod 已提交
736
    } s;
737
  } u;
738
  LOffsetTo<UnsizedArrayOf<FWORD>, false>	vector;
739
  public:
740
  DEFINE_SIZE_STATIC (KernSubTableHeader::static_size + 24);
741 742
};

B
Behdad Esfahbod 已提交
743 744 745

struct KerxSubTableHeader
{
B
Behdad Esfahbod 已提交
746
  typedef ExtendedTypes Types;
B
Behdad Esfahbod 已提交
747

B
Behdad Esfahbod 已提交
748
  inline unsigned int tuple_count (void) const { return tupleCount; }
749
  inline bool is_horizontal (void) const { return !(coverage & Vertical); }
B
Behdad Esfahbod 已提交
750

B
Behdad Esfahbod 已提交
751 752
  enum Coverage
  {
753 754 755 756 757 758 759 760 761 762
    Vertical	= 0x80000000u,	/* Set if table has vertical kerning values. */
    CrossStream	= 0x40000000u,	/* Set if table has cross-stream kerning values. */
    Variation	= 0x20000000u,	/* Set if table has variation kerning values. */
    Backwards	= 0x10000000u,	/* If clear, process the glyphs forwards, that
				 * is, from first to last in the glyph stream.
				 * If we, process them from last to first.
				 * This flag only applies to state-table based
				 * 'kerx' subtables (types 1 and 4). */
    Reserved	= 0x0FFFFF00u,	/* Reserved, set to zero. */
    SubtableType= 0x000000FFu,	/* Subtable type. */
B
Behdad Esfahbod 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  };

  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    return_trace (likely (c->check_struct (this)));
  }

  public:
  HBUINT32	length;
  HBUINT32	coverage;
  HBUINT32	tupleCount;
  public:
  DEFINE_SIZE_STATIC (12);
};

B
Behdad Esfahbod 已提交
779
struct KerxSubTable
780
{
B
Behdad Esfahbod 已提交
781
  friend struct kerx;
B
Behdad Esfahbod 已提交
782

B
Behdad Esfahbod 已提交
783
  inline unsigned int get_size (void) const { return u.header.length; }
784
  inline unsigned int get_type (void) const { return u.header.coverage & u.header.SubtableType; }
785 786 787 788 789 790 791

  template <typename context_t>
  inline typename context_t::return_t dispatch (context_t *c) const
  {
    unsigned int subtable_type = get_type ();
    TRACE_DISPATCH (this, subtable_type);
    switch (subtable_type) {
B
Behdad Esfahbod 已提交
792 793 794 795 796 797
    case 0:	return_trace (c->dispatch (u.format0));
    case 1:	return_trace (c->dispatch (u.format1));
    case 2:	return_trace (c->dispatch (u.format2));
    case 4:	return_trace (c->dispatch (u.format4));
    case 6:	return_trace (c->dispatch (u.format6));
    default:	return_trace (c->default_return_value ());
798
    }
799 800
  }

801
  inline bool sanitize (hb_sanitize_context_t *c) const
802 803
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
804
    if (!u.header.sanitize (c) ||
805
	u.header.length <= u.header.static_size ||
B
Behdad Esfahbod 已提交
806
	!c->check_range (this, u.header.length))
807 808
      return_trace (false);

809
    return_trace (dispatch (c));
810 811
  }

812
  public:
813
  union {
814 815 816 817 818 819
  KerxSubTableHeader				header;
  KerxSubTableFormat0<KerxSubTableHeader>	format0;
  KerxSubTableFormat1<KerxSubTableHeader>	format1;
  KerxSubTableFormat2<KerxSubTableHeader>	format2;
  KerxSubTableFormat4<KerxSubTableHeader>	format4;
  KerxSubTableFormat6<KerxSubTableHeader>	format6;
820
  } u;
821
  public:
822
  DEFINE_SIZE_MIN (12);
823 824
};

825 826 827 828 829

/*
 * The 'kerx' Table
 */

830 831
template <typename T>
struct KerxTable
832
{
833 834
  /* https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern */
  inline const T* thiz (void) const { return static_cast<const T *> (this); }
835

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
  inline bool has_state_machine (void) const
  {
    typedef typename T::SubTable SubTable;

    const SubTable *st = &thiz()->firstSubTable;
    unsigned int count = thiz()->tableCount;
    for (unsigned int i = 0; i < count; i++)
    {
      if (st->get_type () == 1)
        return true;
      st = &StructAfter<SubTable> (*st);
    }
    return false;
  }

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
  inline bool has_cross_stream (void) const
  {
    typedef typename T::SubTable SubTable;

    const SubTable *st = &thiz()->firstSubTable;
    unsigned int count = thiz()->tableCount;
    for (unsigned int i = 0; i < count; i++)
    {
      if (st->u.header.coverage & st->u.header.CrossStream)
        return true;
      st = &StructAfter<SubTable> (*st);
    }
    return false;
  }

866 867 868
  inline int get_h_kerning (hb_codepoint_t left, hb_codepoint_t right) const
  {
    typedef typename T::SubTable SubTable;
869

870 871 872 873 874 875 876 877 878 879 880 881 882
    int v = 0;
    const SubTable *st = &thiz()->firstSubTable;
    unsigned int count = thiz()->tableCount;
    for (unsigned int i = 0; i < count; i++)
    {
      if ((st->u.header.coverage & (st->u.header.Variation | st->u.header.CrossStream)) ||
	  !st->u.header.is_horizontal ())
        continue;
      v += st->get_kerning (left, right);
      st = &StructAfter<SubTable> (*st);
    }
    return v;
  }
883

B
Behdad Esfahbod 已提交
884
  inline bool apply (AAT::hb_aat_apply_context_t *c) const
885
  {
886 887
    typedef typename T::SubTable SubTable;

B
Behdad Esfahbod 已提交
888
    bool ret = false;
889
    bool seenCrossStream = false;
890
    c->set_lookup_index (0);
891 892
    const SubTable *st = &thiz()->firstSubTable;
    unsigned int count = thiz()->tableCount;
893 894
    for (unsigned int i = 0; i < count; i++)
    {
B
Behdad Esfahbod 已提交
895 896
      bool reverse;

897 898 899
      if (!T::Types::extended && (st->u.header.coverage & st->u.header.Variation))
        goto skip;

900
      if (HB_DIRECTION_IS_HORIZONTAL (c->buffer->props.direction) != st->u.header.is_horizontal ())
B
Behdad Esfahbod 已提交
901
	goto skip;
B
Behdad Esfahbod 已提交
902

903
      reverse = bool (st->u.header.coverage & st->u.header.Backwards) !=
B
Behdad Esfahbod 已提交
904 905
		HB_DIRECTION_IS_BACKWARD (c->buffer->props.direction);

906
      if (!c->buffer->message (c->font, "start %c%c%c%c subtable %d", HB_UNTAG (thiz()->tableTag), c->lookup_index))
B
Behdad Esfahbod 已提交
907
	goto skip;
B
Behdad Esfahbod 已提交
908

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
      if (!seenCrossStream &&
	  (st->u.header.coverage & st->u.header.CrossStream))
      {
        /* Attach all glyphs into a chain. */
        seenCrossStream = true;
	hb_glyph_position_t *pos = c->buffer->pos;
	unsigned int count = c->buffer->len;
	for (unsigned int i = 0; i < count; i++)
	{
	  pos[i].attach_type() = ATTACH_TYPE_CURSIVE;
	  pos[i].attach_chain() = HB_DIRECTION_IS_FORWARD (c->buffer->props.direction) ? -1 : +1;
	  /* We intentionally don't set HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT,
	   * since there needs to be a non-zero attachment for post-positioning to
	   * be needed. */
	}
      }

B
Behdad Esfahbod 已提交
926
      if (reverse)
B
Behdad Esfahbod 已提交
927
	c->buffer->reverse ();
B
Behdad Esfahbod 已提交
928

929 930 931 932 933 934
      /* See comment in sanitize() for conditional here. */
      if (i < count - 1)
	c->sanitizer.set_object (*st);
      else
	c->sanitizer.reset_object ();

B
Behdad Esfahbod 已提交
935
      ret |= st->dispatch (c);
B
Behdad Esfahbod 已提交
936 937

      if (reverse)
B
Behdad Esfahbod 已提交
938
	c->buffer->reverse ();
B
Behdad Esfahbod 已提交
939

940
      (void) c->buffer->message (c->font, "end %c%c%c%c subtable %d", HB_UNTAG (thiz()->tableTag), c->lookup_index);
B
Behdad Esfahbod 已提交
941 942

    skip:
943
      st = &StructAfter<SubTable> (*st);
B
Behdad Esfahbod 已提交
944
      c->set_lookup_index (c->lookup_index + 1);
945
    }
946
    c->sanitizer.reset_object ();
B
Behdad Esfahbod 已提交
947 948

    return ret;
949 950
  }

951
  inline bool sanitize (hb_sanitize_context_t *c) const
952
  {
953
    TRACE_SANITIZE (this);
954 955 956
    if (unlikely (!thiz()->version.sanitize (c) ||
		  thiz()->version < T::minVersion ||
		  !thiz()->tableCount.sanitize (c)))
957
      return_trace (false);
958

959 960 961 962
    typedef typename T::SubTable SubTable;

    const SubTable *st = &thiz()->firstSubTable;
    unsigned int count = thiz()->tableCount;
963
    for (unsigned int i = 0; i < count; i++)
964
    {
965 966 967 968 969 970 971 972 973 974 975 976 977
      c->reset_object ();
      if (unlikely (!st->u.header.sanitize (c)))
	return_trace (false);
      /* OpenType kern table has 2-byte subtable lengths.  That's limiting.
       * MS implementation also only supports one subtable, of format 0,
       * anyway.  Certain versions of some fonts, like Calibry, contain
       * kern subtable that exceeds 64kb.  Looks like, the subtable length
       * is simply ignored.  Which makes sense.  It's only needed if you
       * have multiple subtables.  To handle such fonts, we just ignore
       * the length for the last subtable. */
      if (i < count - 1)
	c->set_object (*st);

978
      if (unlikely (!st->sanitize (c)))
979
	return_trace (false);
980
      st = &StructAfter<SubTable> (*st);
981
    }
982
    c->reset_object ();
983 984 985

    return_trace (true);
  }
986 987 988 989 990 991 992 993 994 995 996 997 998 999
};

struct kerx : KerxTable<kerx>
{
  friend struct KerxTable<kerx>;

  static const hb_tag_t tableTag = HB_AAT_TAG_kerx;
  static const uint16_t minVersion = 2;

  typedef KerxSubTableHeader SubTableHeader;
  typedef SubTableHeader::Types Types;
  typedef KerxSubTable SubTable;

  inline bool has_data (void) const { return version; }
1000 1001

  protected:
1002 1003 1004 1005 1006
  HBUINT16	version;	/* The version number of the extended kerning table
				 * (currently 2, 3, or 4). */
  HBUINT16	unused;		/* Set to 0. */
  HBUINT32	tableCount;	/* The number of subtables included in the extended kerning
				 * table. */
1007
  SubTable	firstSubTable;	/* Subtables. */
1008 1009
/*subtableGlyphCoverageArray*/	/* Only if version >= 3. We don't use. */

1010
  public:
1011
  DEFINE_SIZE_MIN (8);
1012 1013
};

B
Behdad Esfahbod 已提交
1014

1015 1016 1017 1018
} /* namespace AAT */


#endif /* HB_AAT_LAYOUT_KERX_TABLE_HH */