hb-aat-layout-morx-table.hh 32.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Copyright © 2017  Google, Inc.
 *
 *  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_MORX_TABLE_HH
#define HB_AAT_LAYOUT_MORX_TABLE_HH

30 31 32
#include "hb-open-type.hh"
#include "hb-aat-layout-common.hh"
#include "hb-ot-layout-common.hh"
33
#include "hb-aat-map.hh"
34

35 36 37
/*
 * morx -- Extended Glyph Metamorphosis
 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html
38
 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6mort.html
39
 */
40
#define HB_AAT_TAG_morx HB_TAG('m','o','r','x')
41
#define HB_AAT_TAG_mort HB_TAG('m','o','r','t')
42 43 44 45 46 47


namespace AAT {

using namespace OT;

48
template <typename Types>
49 50
struct RearrangementSubtable
{
51 52
  typedef typename Types::HBUINT HBUINT;

B
Minor  
Behdad Esfahbod 已提交
53 54
  typedef void EntryData;

55
  struct driver_context_t
56
  {
57
    static const bool in_place = true;
58 59
    enum Flags
    {
B
Behdad Esfahbod 已提交
60 61
      MarkFirst		= 0x8000,	/* If set, make the current glyph the first
					 * glyph to be rearranged. */
62
      DontAdvance	= 0x4000,	/* If set, don't advance to the next glyph
B
Behdad Esfahbod 已提交
63 64 65 66 67 68 69
					 * before going to the new state. This means
					 * that the glyph index doesn't change, even
					 * if the glyph at that index has changed. */
      MarkLast		= 0x2000,	/* If set, make the current glyph the last
					 * glyph to be rearranged. */
      Reserved		= 0x1FF0,	/* These bits are reserved and should be set to 0. */
      Verb		= 0x000F,	/* The type of rearrangement specified. */
70 71
    };

72
    inline driver_context_t (const RearrangementSubtable *table HB_UNUSED) :
73
	ret (false),
B
Behdad Esfahbod 已提交
74
	start (0), end (0) {}
75

76
    inline bool is_actionable (StateTableDriver<MorxTypes, EntryData> *driver HB_UNUSED,
B
Minor  
Behdad Esfahbod 已提交
77
			       const Entry<EntryData> *entry)
B
Behdad Esfahbod 已提交
78 79 80
    {
      return (entry->flags & Verb) && start < end;
    }
81
    inline bool transition (StateTableDriver<MorxTypes, EntryData> *driver,
B
Minor  
Behdad Esfahbod 已提交
82
			    const Entry<EntryData> *entry)
83
    {
84
      hb_buffer_t *buffer = driver->buffer;
85 86 87
      unsigned int flags = entry->flags;

      if (flags & MarkFirst)
88
	start = buffer->idx;
89

90
      if (flags & MarkLast)
91
	end = MIN (buffer->idx + 1, buffer->len);
92 93 94 95 96 97 98

      if ((flags & Verb) && start < end)
      {
	/* The following map has two nibbles, for start-side
	 * and end-side. Values of 0,1,2 mean move that many
	 * to the other side. Value of 3 means move 2 and
	 * flip them. */
B
Behdad Esfahbod 已提交
99
	const unsigned char map[16] =
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	{
	  0x00,	/* 0	no change */
	  0x10,	/* 1	Ax => xA */
	  0x01,	/* 2	xD => Dx */
	  0x11,	/* 3	AxD => DxA */
	  0x20,	/* 4	ABx => xAB */
	  0x30,	/* 5	ABx => xBA */
	  0x02,	/* 6	xCD => CDx */
	  0x03,	/* 7	xCD => DCx */
	  0x12,	/* 8	AxCD => CDxA */
	  0x13,	/* 9	AxCD => DCxA */
	  0x21,	/* 10	ABxD => DxAB */
	  0x31,	/* 11	ABxD => DxBA */
	  0x22,	/* 12	ABxCD => CDxAB */
	  0x32,	/* 13	ABxCD => CDxBA */
	  0x23,	/* 14	ABxCD => DCxAB */
	  0x33,	/* 15	ABxCD => DCxBA */
	};

	unsigned int m = map[flags & Verb];
	unsigned int l = MIN<unsigned int> (2, m >> 4);
	unsigned int r = MIN<unsigned int> (2, m & 0x0F);
	bool reverse_l = 3 == (m >> 4);
	bool reverse_r = 3 == (m & 0x0F);

	if (end - start >= l + r)
	{
B
Behdad Esfahbod 已提交
127
	  buffer->merge_clusters (start, MIN (buffer->idx + 1, buffer->len));
128
	  buffer->merge_clusters (start, end);
129

130
	  hb_glyph_info_t *info = buffer->info;
131
	  hb_glyph_info_t buf[4];
132

133 134 135 136
	  memcpy (buf, info + start, l * sizeof (buf[0]));
	  memcpy (buf + 2, info + end - r, r * sizeof (buf[0]));

	  if (l != r)
137
	    memmove (info + start + r, info + start + l, (end - start - l - r) * sizeof (buf[0]));
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

	  memcpy (info + start, buf + 2, r * sizeof (buf[0]));
	  memcpy (info + end - l, buf, l * sizeof (buf[0]));
	  if (reverse_l)
	  {
	    buf[0] = info[end - 1];
	    info[end - 1] = info[end - 2];
	    info[end - 2] = buf[0];
	  }
	  if (reverse_r)
	  {
	    buf[0] = info[start];
	    info[start] = info[start + 1];
	    info[start + 1] = buf[0];
	  }
	}
      }
155 156

      return true;
157 158 159 160 161
    }

    public:
    bool ret;
    private:
B
Behdad Esfahbod 已提交
162 163
    unsigned int start;
    unsigned int end;
164
  };
165

166
  inline bool apply (hb_aat_apply_context_t *c) const
167 168
  {
    TRACE_APPLY (this);
169

170 171
    driver_context_t dc (this);

172
    StateTableDriver<MorxTypes, EntryData> driver (machine, c->buffer, c->face);
173
    driver.drive (&dc);
174

175
    return_trace (dc.ret);
176 177
  }

178 179 180
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
181
    return_trace (machine.sanitize (c));
182
  }
183 184

  protected:
185
  StateTable<Types, EntryData>	machine;
186
  public:
B
Behdad Esfahbod 已提交
187
  DEFINE_SIZE_STATIC (16);
188 189
};

190
template <typename Types>
191 192
struct ContextualSubtable
{
193 194
  typedef typename Types::HBUINT HBUINT;

195 196 197 198 199 200
  struct EntryData
  {
    HBUINT16	markIndex;	/* Index of the substitution table for the
				 * marked glyph (use 0xFFFF for none). */
    HBUINT16	currentIndex;	/* Index of the substitution table for the
				 * current glyph (use 0xFFFF for none). */
B
Behdad Esfahbod 已提交
201
    public:
202
    DEFINE_SIZE_STATIC (4);
203 204
  };

205
  struct driver_context_t
206
  {
207
    static const bool in_place = true;
208 209
    enum Flags
    {
210 211 212 213 214 215 216 217
      SetMark		= 0x8000,	/* If set, make the current glyph the marked glyph. */
      DontAdvance	= 0x4000,	/* If set, don't advance to the next glyph before
					 * going to the new state. */
      Reserved		= 0x3FFF,	/* These bits are reserved and should be set to 0. */
    };

    inline driver_context_t (const ContextualSubtable *table) :
	ret (false),
218
	mark_set (false),
219 220 221
	mark (0),
	subs (table+table->substitutionTables) {}

222
    inline bool is_actionable (StateTableDriver<MorxTypes, EntryData> *driver,
B
Behdad Esfahbod 已提交
223 224 225 226 227 228 229 230 231
			       const Entry<EntryData> *entry)
    {
      hb_buffer_t *buffer = driver->buffer;

      if (buffer->idx == buffer->len && !mark_set)
        return false;

      return entry->data.markIndex != 0xFFFF || entry->data.currentIndex != 0xFFFF;
    }
232
    inline bool transition (StateTableDriver<MorxTypes, EntryData> *driver,
233
			    const Entry<EntryData> *entry)
234
    {
235
      hb_buffer_t *buffer = driver->buffer;
236

237 238 239 240 241
      /* Looks like CoreText applies neither mark nor current substitution for
       * end-of-text if mark was not explicitly set. */
      if (buffer->idx == buffer->len && !mark_set)
        return true;

B
Behdad Esfahbod 已提交
242
      if (entry->data.markIndex != 0xFFFF)
243
      {
244
	const Lookup<GlyphID> &lookup = subs[entry->data.markIndex];
245 246
	hb_glyph_info_t *info = buffer->info;
	const GlyphID *replacement = lookup.get_value (info[mark].codepoint, driver->num_glyphs);
247 248
	if (replacement)
	{
B
Behdad Esfahbod 已提交
249
	  buffer->unsafe_to_break (mark, MIN (buffer->idx + 1, buffer->len));
250 251 252 253
	  info[mark].codepoint = *replacement;
	  ret = true;
	}
      }
254
      if (entry->data.currentIndex != 0xFFFF)
255
      {
256
        unsigned int idx = MIN (buffer->idx, buffer->len - 1);
257
	const Lookup<GlyphID> &lookup = subs[entry->data.currentIndex];
258
	hb_glyph_info_t *info = buffer->info;
259
	const GlyphID *replacement = lookup.get_value (info[idx].codepoint, driver->num_glyphs);
260 261
	if (replacement)
	{
262
	  info[idx].codepoint = *replacement;
263 264 265
	  ret = true;
	}
      }
266

267 268
      if (entry->flags & SetMark)
      {
269
	mark_set = true;
270 271 272
	mark = buffer->idx;
      }

273
      return true;
274
    }
275

276 277 278
    public:
    bool ret;
    private:
279
    bool mark_set;
280
    unsigned int mark;
281
    const UnsizedOffsetListOf<Lookup<GlyphID>, HBUINT32, false> &subs;
282
  };
283

284
  inline bool apply (hb_aat_apply_context_t *c) const
285 286
  {
    TRACE_APPLY (this);
287

288 289
    driver_context_t dc (this);

290
    StateTableDriver<MorxTypes, EntryData> driver (machine, c->buffer, c->face);
291 292 293
    driver.drive (&dc);

    return_trace (dc.ret);
294 295
  }

296 297 298
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
299

B
Behdad Esfahbod 已提交
300
    unsigned int num_entries = 0;
B
Behdad Esfahbod 已提交
301
    if (unlikely (!machine.sanitize (c, &num_entries))) return_trace (false);
302 303 304 305 306 307 308 309

    unsigned int num_lookups = 0;

    const Entry<EntryData> *entries = machine.get_entries ();
    for (unsigned int i = 0; i < num_entries; i++)
    {
      const EntryData &data = entries[i].data;

310 311 312 313
      if (data.markIndex != 0xFFFF)
	num_lookups = MAX<unsigned int> (num_lookups, 1 + data.markIndex);
      if (data.currentIndex != 0xFFFF)
	num_lookups = MAX<unsigned int> (num_lookups, 1 + data.currentIndex);
314 315 316
    }

    return_trace (substitutionTables.sanitize (c, this, num_lookups));
317
  }
318 319

  protected:
320
  StateTable<Types, EntryData>
321
		machine;
322
  OffsetTo<UnsizedOffsetListOf<Lookup<GlyphID>, HBUINT, false>, HBUINT, false>
323
		substitutionTables;
324
  public:
B
Behdad Esfahbod 已提交
325
  DEFINE_SIZE_STATIC (20);
326 327
};

328
template <typename Types>
329 330
struct LigatureSubtable
{
331 332
  typedef typename Types::HBUINT HBUINT;

333 334 335 336 337 338 339 340 341 342 343 344
  struct EntryData
  {
    HBUINT16	ligActionIndex;	/* Index to the first ligActionTable entry
				 * for processing this group, if indicated
				 * by the flags. */
    public:
    DEFINE_SIZE_STATIC (2);
  };

  struct driver_context_t
  {
    static const bool in_place = false;
345 346
    enum Flags
    {
347 348 349 350 351 352 353 354
      SetComponent	= 0x8000,	/* Push this glyph onto the component stack for
					 * eventual processing. */
      DontAdvance	= 0x4000,	/* Leave the glyph pointer at this glyph for the
					   next iteration. */
      PerformAction	= 0x2000,	/* Use the ligActionIndex to process a ligature
					 * group. */
      Reserved		= 0x1FFF,	/* These bits are reserved and should be set to 0. */
    };
355 356
    enum LigActionFlags
    {
357 358 359 360 361 362 363 364 365
      LigActionLast	= 0x80000000,	/* This is the last action in the list. This also
					 * implies storage. */
      LigActionStore	= 0x40000000,	/* Store the ligature at the current cumulated index
					 * in the ligature table in place of the marked
					 * (i.e. currently-popped) glyph. */
      LigActionOffset	= 0x3FFFFFFF,	/* A 30-bit value which is sign-extended to 32-bits
					 * and added to the glyph ID, resulting in an index
					 * into the component table. */
    };
366

367 368 369 370 371 372 373 374
    inline driver_context_t (const LigatureSubtable *table,
			     hb_aat_apply_context_t *c_) :
	ret (false),
	c (c_),
	ligAction (table+table->ligAction),
	component (table+table->component),
	ligature (table+table->ligature),
	match_length (0) {}
375

376
    inline bool is_actionable (StateTableDriver<MorxTypes, EntryData> *driver HB_UNUSED,
B
Behdad Esfahbod 已提交
377 378
			       const Entry<EntryData> *entry)
    {
B
Behdad Esfahbod 已提交
379
      return entry->flags & PerformAction;
B
Behdad Esfahbod 已提交
380
    }
381
    inline bool transition (StateTableDriver<MorxTypes, EntryData> *driver,
382 383 384
			    const Entry<EntryData> *entry)
    {
      hb_buffer_t *buffer = driver->buffer;
385 386
      unsigned int flags = entry->flags;

387
      DEBUG_MSG (APPLY, nullptr, "Ligature transition at %d", buffer->idx);
388 389 390 391 392 393 394 395 396 397
      if (flags & SetComponent)
      {
        if (unlikely (match_length >= ARRAY_LENGTH (match_positions)))
	  return false;

	/* Never mark same index twice, in case DontAdvance was used... */
	if (match_length && match_positions[match_length - 1] == buffer->out_len)
	  match_length--;

	match_positions[match_length++] = buffer->out_len;
398
	DEBUG_MSG (APPLY, nullptr, "Set component at %d", buffer->out_len);
399 400 401 402
      }

      if (flags & PerformAction)
      {
403
	DEBUG_MSG (APPLY, nullptr, "Perform action with %d", match_length);
404 405 406 407
	unsigned int end = buffer->out_len;
	unsigned int action_idx = entry->data.ligActionIndex;
	unsigned int action;
	unsigned int ligature_idx = 0;
408 409

	if (unlikely (!match_length))
B
Behdad Esfahbod 已提交
410
	  return true;
411

412 413 414
	if (buffer->idx >= buffer->len)
	  return false; // TODO Work on previous instead?

B
Behdad Esfahbod 已提交
415
	unsigned int cursor = match_length;
416 417
        do
	{
B
Behdad Esfahbod 已提交
418
	  if (unlikely (!cursor))
419 420
	  {
	    /* Stack underflow.  Clear the stack. */
421
	    DEBUG_MSG (APPLY, nullptr, "Stack underflow");
422
	    match_length = 0;
B
Behdad Esfahbod 已提交
423
	    break;
424
	  }
425

426
	  DEBUG_MSG (APPLY, nullptr, "Moving to stack position %d", cursor - 1);
B
Behdad Esfahbod 已提交
427
	  buffer->move_to (match_positions[--cursor]);
428

429 430 431 432 433 434
	  const HBUINT32 &actionData = ligAction[action_idx];
	  if (unlikely (!actionData.sanitize (&c->sanitizer))) return false;
	  action = actionData;

	  uint32_t uoffset = action & LigActionOffset;
	  if (uoffset & 0x20000000)
B
Behdad Esfahbod 已提交
435
	    uoffset |= 0xC0000000; /* Sign-extend. */
436 437 438 439 440 441 442
	  int32_t offset = (int32_t) uoffset;
	  unsigned int component_idx = buffer->cur().codepoint + offset;

	  const HBUINT16 &componentData = component[component_idx];
	  if (unlikely (!componentData.sanitize (&c->sanitizer))) return false;
	  ligature_idx += componentData;

443 444 445
	  DEBUG_MSG (APPLY, nullptr, "Action store %d last %d",
		     bool (action & LigActionStore),
		     bool (action & LigActionLast));
446 447
	  if (action & (LigActionStore | LigActionLast))
	  {
448

449 450 451 452
	    const GlyphID &ligatureData = ligature[ligature_idx];
	    if (unlikely (!ligatureData.sanitize (&c->sanitizer))) return false;
	    hb_codepoint_t lig = ligatureData;

453
	    DEBUG_MSG (APPLY, nullptr, "Produced ligature %d", lig);
454 455
	    buffer->replace_glyph (lig);

456
	    unsigned int lig_end = match_positions[match_length - 1] + 1;
B
Behdad Esfahbod 已提交
457 458 459
	    /* Now go and delete all subsequent components. */
	    while (match_length - 1 > cursor)
	    {
460
	      DEBUG_MSG (APPLY, nullptr, "Skipping ligature component");
B
Behdad Esfahbod 已提交
461
	      buffer->move_to (match_positions[--match_length]);
462
	      buffer->replace_glyph (DELETED_GLYPH);
B
Behdad Esfahbod 已提交
463
	    }
464

465
	    buffer->move_to (lig_end);
466
	    buffer->merge_out_clusters (match_positions[cursor], buffer->out_len);
467 468 469 470 471 472 473 474 475
	  }

	  action_idx++;
	}
	while (!(action & LigActionLast));
	buffer->move_to (end);
      }

      return true;
476 477 478 479 480
    }

    public:
    bool ret;
    private:
481 482 483 484 485 486
    hb_aat_apply_context_t *c;
    const UnsizedArrayOf<HBUINT32> &ligAction;
    const UnsizedArrayOf<HBUINT16> &component;
    const UnsizedArrayOf<GlyphID> &ligature;
    unsigned int match_length;
    unsigned int match_positions[HB_MAX_CONTEXT_LENGTH];
487 488
  };

489
  inline bool apply (hb_aat_apply_context_t *c) const
490 491
  {
    TRACE_APPLY (this);
492

493
    driver_context_t dc (this, c);
494

495
    StateTableDriver<MorxTypes, EntryData> driver (machine, c->buffer, c->face);
496 497 498
    driver.drive (&dc);

    return_trace (dc.ret);
499 500
  }

501 502 503
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
504
    /* The rest of array sanitizations are done at run-time. */
B
Behdad Esfahbod 已提交
505 506
    return_trace (c->check_struct (this) && machine.sanitize (c) &&
		  ligAction && component && ligature);
507
  }
508 509

  protected:
510
  StateTable<Types, EntryData>
511
		machine;
512
  OffsetTo<UnsizedArrayOf<HBUINT32>, HBUINT, false>
513
		ligAction;	/* Offset to the ligature action table. */
514
  OffsetTo<UnsizedArrayOf<HBUINT16>, HBUINT, false>
515
		component;	/* Offset to the component table. */
516
  OffsetTo<UnsizedArrayOf<GlyphID>, HBUINT, false>
517 518 519
		ligature;	/* Offset to the actual ligature lists. */
  public:
  DEFINE_SIZE_STATIC (28);
520 521
};

522
template <typename Types>
523 524
struct NoncontextualSubtable
{
525
  inline bool apply (hb_aat_apply_context_t *c) const
526 527
  {
    TRACE_APPLY (this);
528

529
    bool ret = false;
530 531 532 533
    unsigned int num_glyphs = c->face->get_num_glyphs ();

    hb_glyph_info_t *info = c->buffer->info;
    unsigned int count = c->buffer->len;
534 535 536 537 538 539 540 541 542
    for (unsigned int i = 0; i < count; i++)
    {
      const GlyphID *replacement = substitute.get_value (info[i].codepoint, num_glyphs);
      if (replacement)
      {
	info[i].codepoint = *replacement;
	ret = true;
      }
    }
543

544 545 546
    return_trace (ret);
  }

547 548 549
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
550
    return_trace (substitute.sanitize (c));
551
  }
B
Behdad Esfahbod 已提交
552 553 554 555 556

  protected:
  Lookup<GlyphID>	substitute;
  public:
  DEFINE_SIZE_MIN (2);
557 558
};

559
template <typename Types>
560 561
struct InsertionSubtable
{
562 563
  typedef typename Types::HBUINT HBUINT;

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  struct EntryData
  {
    HBUINT16	currentInsertIndex;	/* Zero-based index into the insertion glyph table.
					 * The number of glyphs to be inserted is contained
					 * in the currentInsertCount field in the flags.
					 * A value of 0xFFFF indicates no insertion is to
					 * be done. */
    HBUINT16	markedInsertIndex;	/* Zero-based index into the insertion glyph table.
					 * The number of glyphs to be inserted is contained
					 * in the markedInsertCount field in the flags.
					 * A value of 0xFFFF indicates no insertion is to
					 * be done. */
    public:
    DEFINE_SIZE_STATIC (4);
  };

  struct driver_context_t
  {
    static const bool in_place = false;
    enum Flags
    {
      SetMark		= 0x8000,	/* If set, mark the current glyph. */
      DontAdvance	= 0x4000,	/* If set, don't advance to the next glyph before
					 * going to the new state.  This does not mean
					 * that the glyph pointed to is the same one as
					 * before. If you've made insertions immediately
					 * downstream of the current glyph, the next glyph
					 * processed would in fact be the first one
					 * inserted. */
      CurrentIsKashidaLike= 0x2000,	/* If set, and the currentInsertList is nonzero,
					 * then the specified glyph list will be inserted
					 * as a kashida-like insertion, either before or
					 * after the current glyph (depending on the state
					 * of the currentInsertBefore flag). If clear, and
					 * the currentInsertList is nonzero, then the
					 * specified glyph list will be inserted as a
					 * split-vowel-like insertion, either before or
					 * after the current glyph (depending on the state
					 * of the currentInsertBefore flag). */
      MarkedIsKashidaLike= 0x1000,	/* If set, and the markedInsertList is nonzero,
					 * then the specified glyph list will be inserted
					 * as a kashida-like insertion, either before or
					 * after the marked glyph (depending on the state
					 * of the markedInsertBefore flag). If clear, and
					 * the markedInsertList is nonzero, then the
					 * specified glyph list will be inserted as a
					 * split-vowel-like insertion, either before or
					 * after the marked glyph (depending on the state
					 * of the markedInsertBefore flag). */
      CurrentInsertBefore= 0x0800,	/* If set, specifies that insertions are to be made
					 * to the left of the current glyph. If clear,
					 * they're made to the right of the current glyph. */
      MarkedInsertBefore= 0x0400,	/* If set, specifies that insertions are to be
					 * made to the left of the marked glyph. If clear,
					 * they're made to the right of the marked glyph. */
      CurrentInsertCount= 0x3E0,	/* This 5-bit field is treated as a count of the
					 * number of glyphs to insert at the current
					 * position. Since zero means no insertions, the
					 * largest number of insertions at any given
					 * current location is 31 glyphs. */
      MarkedInsertCount= 0x001F,	/* This 5-bit field is treated as a count of the
					 * number of glyphs to insert at the marked
					 * position. Since zero means no insertions, the
					 * largest number of insertions at any given
					 * marked location is 31 glyphs. */
    };

    inline driver_context_t (const InsertionSubtable *table,
			     hb_aat_apply_context_t *c_) :
	ret (false),
	c (c_),
635
	mark_set (false),
636 637 638
	mark (0),
	insertionAction (table+table->insertionAction) {}

639
    inline bool is_actionable (StateTableDriver<MorxTypes, EntryData> *driver HB_UNUSED,
640 641 642 643 644
			       const Entry<EntryData> *entry)
    {
      return (entry->flags & (CurrentInsertCount | MarkedInsertCount)) &&
	     (entry->data.currentInsertIndex != 0xFFFF ||entry->data.markedInsertIndex != 0xFFFF);
    }
645
    inline bool transition (StateTableDriver<MorxTypes, EntryData> *driver,
646 647 648 649 650
			    const Entry<EntryData> *entry)
    {
      hb_buffer_t *buffer = driver->buffer;
      unsigned int flags = entry->flags;

651
      if (entry->data.markedInsertIndex != 0xFFFF && mark_set)
652
      {
653
	unsigned int count = (flags & MarkedInsertCount);
654 655 656
	unsigned int start = entry->data.markedInsertIndex;
	const GlyphID *glyphs = &insertionAction[start];
	if (unlikely (!c->sanitizer.check_array (glyphs, count))) return false;
657

658
	bool before = flags & MarkedInsertBefore;
659 660

	unsigned int end = buffer->out_len;
661
	buffer->move_to (mark);
662

663
	if (buffer->idx < buffer->len && !before)
664 665 666 667
	  buffer->copy_glyph ();
	/* TODO We ignore KashidaLike setting. */
	for (unsigned int i = 0; i < count; i++)
	  buffer->output_glyph (glyphs[i]);
668
	if (buffer->idx < buffer->len && !before)
669
	  buffer->skip_glyph ();
670

671
	buffer->move_to (end + count);
672 673

	buffer->unsafe_to_break_from_outbuffer (mark, MIN (buffer->idx + 1, buffer->len));
674
      }
675

676 677
      if (entry->data.currentInsertIndex != 0xFFFF)
      {
678
	unsigned int count = (flags & CurrentInsertCount) >> 5;
679 680 681
	unsigned int start = entry->data.currentInsertIndex;
	const GlyphID *glyphs = &insertionAction[start];
	if (unlikely (!c->sanitizer.check_array (glyphs, count))) return false;
682

683
	bool before = flags & CurrentInsertBefore;
684

685
	unsigned int end = buffer->out_len;
686

687
	if (buffer->idx < buffer->len && !before)
688 689 690 691
	  buffer->copy_glyph ();
	/* TODO We ignore KashidaLike setting. */
	for (unsigned int i = 0; i < count; i++)
	  buffer->output_glyph (glyphs[i]);
692
	if (buffer->idx < buffer->len && !before)
693
	  buffer->skip_glyph ();
694

695 696 697 698 699 700 701 702 703
	/* Humm. Not sure where to move to.  There's this wording under
	 * DontAdvance flag:
	 *
	 * "If set, don't update the glyph index before going to the new state.
	 * This does not mean that the glyph pointed to is the same one as
	 * before. If you've made insertions immediately downstream of the
	 * current glyph, the next glyph processed would in fact be the first
	 * one inserted."
	 *
B
Behdad Esfahbod 已提交
704 705 706
	 * This suggests that if DontAdvance is NOT set, we should move to
	 * end+count.  If it *was*, then move to end, such that newly inserted
	 * glyphs are now visible.
B
Behdad Esfahbod 已提交
707
	 *
B
Behdad Esfahbod 已提交
708
	 * https://github.com/harfbuzz/harfbuzz/issues/1224#issuecomment-427691417
709
	 */
B
Behdad Esfahbod 已提交
710
	buffer->move_to ((flags & DontAdvance) ? end : end + count);
711 712 713
      }

      if (flags & SetMark)
714 715
      {
	mark_set = true;
716
	mark = buffer->out_len;
717
      }
718 719 720 721 722 723 724 725

      return true;
    }

    public:
    bool ret;
    private:
    hb_aat_apply_context_t *c;
726
    bool mark_set;
727 728 729 730
    unsigned int mark;
    const UnsizedArrayOf<GlyphID> &insertionAction;
  };

731
  inline bool apply (hb_aat_apply_context_t *c) const
732 733
  {
    TRACE_APPLY (this);
734 735 736

    driver_context_t dc (this, c);

737
    StateTableDriver<MorxTypes, EntryData> driver (machine, c->buffer, c->face);
738 739 740
    driver.drive (&dc);

    return_trace (dc.ret);
741 742
  }

743 744 745
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
746 747 748
    /* The rest of array sanitizations are done at run-time. */
    return_trace (c->check_struct (this) && machine.sanitize (c) &&
		  insertionAction);
749
  }
750 751

  protected:
752
  StateTable<Types, EntryData>
753
		machine;
754
  OffsetTo<UnsizedArrayOf<GlyphID>, HBUINT, false>
755 756 757 758
		insertionAction;	/* Byte offset from stateHeader to the start of
					 * the insertion glyph table. */
  public:
  DEFINE_SIZE_STATIC (20);
759 760 761 762 763 764 765 766 767 768 769 770
};


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

  public:
B
Behdad Esfahbod 已提交
771 772 773
  HBUINT16	featureType;	/* The type of feature. */
  HBUINT16	featureSetting;	/* The feature's setting (aka selector). */
  HBUINT32	enableFlags;	/* Flags for the settings that this feature
774
				 * and setting enables. */
B
Behdad Esfahbod 已提交
775
  HBUINT32	disableFlags;	/* Complement of flags for the settings that this
776 777 778 779 780 781
				 * feature and setting disable. */

  public:
  DEFINE_SIZE_STATIC (12);
};

782
template <typename Types>
783 784
struct ChainSubtable
{
785
  template <typename T>
B
Behdad Esfahbod 已提交
786
  friend struct Chain;
787 788

  inline unsigned int get_size (void) const { return length; }
789
  inline unsigned int get_type (void) const { return coverage & SubtableType; }
790

791 792 793 794 795
  enum Coverage
  {
    Vertical		= 0x80000000,	/* If set, this subtable will only be applied
					 * to vertical text. If clear, this subtable
					 * will only be applied to horizontal text. */
B
Behdad Esfahbod 已提交
796
    Backwards		= 0x40000000,	/* If set, this subtable will process glyphs
797 798 799 800 801 802 803 804 805 806 807
					 * in descending order. If clear, it will
					 * process the glyphs in ascending order. */
    AllDirections	= 0x20000000,	/* If set, this subtable will be applied to
					 * both horizontal and vertical text (i.e.
					 * the state of bit 0x80000000 is ignored). */
    Logical		= 0x10000000,	/* If set, this subtable will process glyphs
					 * in logical order (or reverse logical order,
					 * depending on the value of bit 0x80000000). */
    Reserved		= 0x0FFFFF00,	/* Reserved, set to zero. */
    SubtableType	= 0x000000FF,	/* Subtable type; see following table. */
  };
808 809
  enum Type
  {
810 811 812 813 814 815 816 817
    Rearrangement	= 0,
    Contextual		= 1,
    Ligature		= 2,
    Noncontextual	= 4,
    Insertion		= 5
  };

  template <typename context_t>
818
  inline typename context_t::return_t dispatch (context_t *c) const
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
  {
    unsigned int subtable_type = get_type ();
    TRACE_DISPATCH (this, subtable_type);
    switch (subtable_type) {
    case Rearrangement:		return_trace (c->dispatch (u.rearrangement));
    case Contextual:		return_trace (c->dispatch (u.contextual));
    case Ligature:		return_trace (c->dispatch (u.ligature));
    case Noncontextual:		return_trace (c->dispatch (u.noncontextual));
    case Insertion:		return_trace (c->dispatch (u.insertion));
    default:			return_trace (c->default_return_value ());
    }
  }

  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    if (!length.sanitize (c) ||
	length < min_size ||
	!c->check_range (this, length))
      return_trace (false);

840
    return_trace (dispatch (c));
841 842 843
  }

  protected:
B
Behdad Esfahbod 已提交
844 845 846
  HBUINT32	length;		/* Total subtable length, including this header. */
  HBUINT32	coverage;	/* Coverage flags and subtable type. */
  HBUINT32	subFeatureFlags;/* The 32-bit mask identifying which subtable this is. */
847
  union {
848 849 850 851 852
  RearrangementSubtable<Types>	rearrangement;
  ContextualSubtable<Types>	contextual;
  LigatureSubtable<Types>	ligature;
  NoncontextualSubtable<Types>	noncontextual;
  InsertionSubtable<Types>	insertion;
853 854
  } u;
  public:
855
  DEFINE_SIZE_MIN (2 * sizeof (HBUINT32) + 4);
856 857
};

858
template <typename Types>
859 860
struct Chain
{
861 862
  typedef typename Types::HBUINT HBUINT;

863
  inline hb_mask_t compile_flags (const hb_aat_map_builder_t *map) const
864
  {
865
    hb_mask_t flags = defaultFlags;
866 867 868 869 870 871 872
    {
      /* Compute applicable flags.  TODO Should move this to planning
       * stage and take user-requested features into account. */
      unsigned int count = featureCount;
      for (unsigned i = 0; i < count; i++)
      {
        const Feature &feature = featureZ[i];
873 874 875 876
        uint16_t type = feature.featureType;
	uint16_t setting = feature.featureSetting;
	const hb_aat_map_builder_t::feature_info_t *info = map->features.bsearch (type);
	if (info && info->setting == setting)
877 878 879 880 881 882
	{
	  flags &= feature.disableFlags;
	  flags |= feature.enableFlags;
	}
      }
    }
883 884
    return flags;
  }
885

886 887 888
  inline void apply (hb_aat_apply_context_t *c,
		     hb_mask_t flags) const
  {
889
    const ChainSubtable<Types> *subtable = &StructAtOffset<ChainSubtable<Types> > (&featureZ, featureZ[0].static_size * featureCount);
890 891 892
    unsigned int count = subtableCount;
    for (unsigned int i = 0; i < count; i++)
    {
893 894
      bool reverse;

895 896 897
      if (!(subtable->subFeatureFlags & flags))
        goto skip;

898
      if (!(subtable->coverage & ChainSubtable<Types>::AllDirections) &&
899
	  HB_DIRECTION_IS_VERTICAL (c->buffer->props.direction) !=
900
	  bool (subtable->coverage & ChainSubtable<Types>::Vertical))
901 902
        goto skip;

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
      /* Buffer contents is always in logical direction.  Determine if
       * we need to reverse before applying this subtable.  We reverse
       * back after if we did reverse indeed.
       *
       * Quoting the spac:
       * """
       * Bits 28 and 30 of the coverage field control the order in which
       * glyphs are processed when the subtable is run by the layout engine.
       * Bit 28 is used to indicate if the glyph processing direction is
       * the same as logical order or layout order. Bit 30 is used to
       * indicate whether glyphs are processed forwards or backwards within
       * that order.

		Bit 30	Bit 28	Interpretation for Horizontal Text
		0	0	The subtable is processed in layout order
				(the same order as the glyphs, which is
				always left-to-right).
		1	0	The subtable is processed in reverse layout order
				(the order opposite that of the glyphs, which is
				always right-to-left).
		0	1	The subtable is processed in logical order
				(the same order as the characters, which may be
				left-to-right or right-to-left).
		1	1	The subtable is processed in reverse logical order
				(the order opposite that of the characters, which
				may be right-to-left or left-to-right).
       */
930 931 932
      reverse = subtable->coverage & ChainSubtable<Types>::Logical ?
		bool (subtable->coverage & ChainSubtable<Types>::Backwards) :
		bool (subtable->coverage & ChainSubtable<Types>::Backwards) !=
933 934
		HB_DIRECTION_IS_BACKWARD (c->buffer->props.direction);

B
Behdad Esfahbod 已提交
935
      if (!c->buffer->message (c->font, "start chain subtable %d", c->lookup_index))
936
        goto skip;
B
Behdad Esfahbod 已提交
937

938 939 940
      if (reverse)
        c->buffer->reverse ();

941 942
      c->sanitizer.set_object (*subtable);

943
      subtable->dispatch (c);
B
Behdad Esfahbod 已提交
944

945 946 947
      if (reverse)
        c->buffer->reverse ();

B
Behdad Esfahbod 已提交
948 949
      (void) c->buffer->message (c->font, "end chain subtable %d", c->lookup_index);

950 951
      if (unlikely (!c->buffer->successful)) return;

952
    skip:
953
      subtable = &StructAfter<ChainSubtable<Types> > (*subtable);
B
Behdad Esfahbod 已提交
954
      c->set_lookup_index (c->lookup_index + 1);
955 956
    }
  }
957 958 959

  inline unsigned int get_size (void) const { return length; }

960
  inline bool sanitize (hb_sanitize_context_t *c, unsigned int version HB_UNUSED) const
961 962 963 964 965 966 967
  {
    TRACE_SANITIZE (this);
    if (!length.sanitize (c) ||
	length < min_size ||
	!c->check_range (this, length))
      return_trace (false);

968
    if (!c->check_array (featureZ.arrayZ, featureCount))
969 970
      return_trace (false);

971
    const ChainSubtable<Types> *subtable = &StructAtOffset<ChainSubtable<Types> > (&featureZ, featureZ[0].static_size * featureCount);
972 973 974 975 976
    unsigned int count = subtableCount;
    for (unsigned int i = 0; i < count; i++)
    {
      if (!subtable->sanitize (c))
	return_trace (false);
977
      subtable = &StructAfter<ChainSubtable<Types> > (*subtable);
978 979 980 981 982 983
    }

    return_trace (true);
  }

  protected:
984 985 986 987
  HBUINT	defaultFlags;	/* The default specification for subtables. */
  HBUINT	length;		/* Total byte count, including this header. */
  HBUINT	featureCount;	/* Number of feature subtable entries. */
  HBUINT	subtableCount;	/* The number of subtables in the chain. */
988

989 990
  UnsizedArrayOf<Feature>	featureZ;	/* Features. */
/*ChainSubtable	firstSubtable;*//* Subtables. */
B
Behdad Esfahbod 已提交
991
/*subtableGlyphCoverageArray*/	/* Only if version >= 3. We don't use. */
992 993

  public:
994
  DEFINE_SIZE_MIN (2 * sizeof (HBUINT) + 4);
995 996 997 998
};


/*
999
 * The 'mort'/'morx' Table
1000 1001
 */

1002 1003
template <typename Types>
struct mortmorx
1004
{
1005
  static const hb_tag_t tableTag = HB_AAT_TAG_morx;
1006

1007 1008
  inline bool has_data (void) const { return version != 0; }

1009 1010 1011
  inline void compile_flags (const hb_aat_map_builder_t *mapper,
			     hb_aat_map_t *map) const
  {
1012
    const Chain<Types> *chain = &firstChain;
1013 1014 1015 1016
    unsigned int count = chainCount;
    for (unsigned int i = 0; i < count; i++)
    {
      map->chain_flags.push (chain->compile_flags (mapper));
1017
      chain = &StructAfter<Chain<Types> > (*chain);
1018 1019 1020
    }
  }

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  inline static void remove_deleted_glyphs (hb_buffer_t *buffer)
  {
    if (unlikely (!buffer->successful)) return;

    buffer->clear_output ();
    for (buffer->idx = 0; buffer->idx < buffer->len && buffer->successful;)
    {
      if (unlikely (buffer->cur().codepoint == DELETED_GLYPH))
        buffer->skip_glyph ();
      else
        buffer->next_glyph ();
    }
    if (likely (buffer->successful))
      buffer->swap_buffers ();
  }

1037
  inline void apply (hb_aat_apply_context_t *c) const
1038
  {
1039
    if (unlikely (!c->buffer->successful)) return;
B
Behdad Esfahbod 已提交
1040
    c->set_lookup_index (0);
1041
    const Chain<Types> *chain = &firstChain;
1042 1043 1044
    unsigned int count = chainCount;
    for (unsigned int i = 0; i < count; i++)
    {
1045
      chain->apply (c, c->plan->aat_map.chain_flags[i]);
1046
      if (unlikely (!c->buffer->successful)) return;
1047
      chain = &StructAfter<Chain<Types> > (*chain);
1048
    }
1049
    remove_deleted_glyphs (c->buffer);
1050 1051
  }

1052 1053 1054
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
B
Behdad Esfahbod 已提交
1055
    if (!version.sanitize (c) || version < 2 ||
1056 1057 1058
	!chainCount.sanitize (c))
      return_trace (false);

1059
    const Chain<Types> *chain = &firstChain;
1060 1061 1062
    unsigned int count = chainCount;
    for (unsigned int i = 0; i < count; i++)
    {
B
Behdad Esfahbod 已提交
1063
      if (!chain->sanitize (c, version))
1064
	return_trace (false);
1065
      chain = &StructAfter<Chain<Types> > (*chain);
1066 1067 1068 1069 1070 1071
    }

    return_trace (true);
  }

  protected:
B
Behdad Esfahbod 已提交
1072 1073 1074
  HBUINT16	version;	/* Version number of the glyph metamorphosis table.
				 * 2 or 3. */
  HBUINT16	unused;		/* Set to 0. */
B
Behdad Esfahbod 已提交
1075
  HBUINT32	chainCount;	/* Number of metamorphosis chains contained in this
1076
				 * table. */
1077
  Chain<Types>	firstChain;	/* Chains. */
1078 1079 1080 1081 1082

  public:
  DEFINE_SIZE_MIN (8);
};

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
struct morx : mortmorx<MorxTypes>
{
  static const hb_tag_t tableTag	= HB_AAT_TAG_morx;
};
struct mort : mortmorx<MortTypes>
{
  static const hb_tag_t tableTag	= HB_AAT_TAG_mort;
};


1093 1094 1095 1096
} /* namespace AAT */


#endif /* HB_AAT_LAYOUT_MORX_TABLE_HH */