e9d97c9b062d8b6a9fb55a78cc4950145d7d4e8d
[platform/upstream/harfbuzz.git] / src / hb-ot-shape.cc
1 /*
2  * Copyright © 2009,2010  Red Hat, Inc.
3  * Copyright © 2010,2011,2012  Google, Inc.
4  *
5  *  This is part of HarfBuzz, a text shaping library.
6  *
7  * Permission is hereby granted, without written agreement and without
8  * license or royalty fees, to use, copy, modify, and distribute this
9  * software and its documentation for any purpose, provided that the
10  * above copyright notice and the following two paragraphs appear in
11  * all copies of this software.
12  *
13  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17  * DAMAGE.
18  *
19  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
22  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24  *
25  * Red Hat Author(s): Behdad Esfahbod
26  * Google Author(s): Behdad Esfahbod
27  */
28
29 #include "hb-shaper-impl.hh"
30
31 #include "hb-ot-shape.hh"
32 #include "hb-ot-shape-complex.hh"
33 #include "hb-ot-shape-fallback.hh"
34 #include "hb-ot-shape-normalize.hh"
35
36 #include "hb-ot-face.hh"
37
38 #include "hb-set.hh"
39
40 #include "hb-aat-layout.hh"
41
42
43 /**
44  * SECTION:hb-ot-shape
45  * @title: hb-ot-shape
46  * @short_description: OpenType shaping support
47  * @include: hb-ot.h
48  *
49  * Support functions for OpenType shaping related queries.
50  **/
51
52
53 static void
54 hb_ot_shape_collect_features (hb_ot_shape_planner_t          *planner,
55                               const hb_feature_t             *user_features,
56                               unsigned int                    num_user_features);
57
58 static bool
59 _hb_apply_morx (hb_face_t *face)
60 {
61   if (hb_options ().aat &&
62       hb_aat_layout_has_substitution (face))
63     return true;
64
65   /* Ignore empty GSUB tables. */
66   return (!hb_ot_layout_has_substitution (face) ||
67           !hb_ot_layout_table_get_script_tags (face,
68                                                HB_OT_TAG_GSUB,
69                                                0, nullptr, nullptr)) &&
70          hb_aat_layout_has_substitution (face);
71 }
72
73 hb_ot_shape_planner_t::hb_ot_shape_planner_t (hb_face_t                     *face,
74                                               const hb_segment_properties_t *props) :
75                                                 face (face),
76                                                 props (*props),
77                                                 map (face, props),
78                                                 aat_map (face, props),
79                                                 apply_morx (_hb_apply_morx (face))
80 {
81   shaper = hb_ot_shape_complex_categorize (this);
82
83   script_zero_marks = shaper->zero_width_marks != HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE;
84   script_fallback_mark_positioning = shaper->fallback_position;
85
86   if (apply_morx)
87     shaper = &_hb_ot_complex_shaper_default;
88 }
89
90 void
91 hb_ot_shape_planner_t::compile (hb_ot_shape_plan_t           &plan,
92                                 const hb_ot_shape_plan_key_t &key)
93 {
94   plan.props = props;
95   plan.shaper = shaper;
96   map.compile (plan.map, key);
97   if (apply_morx)
98     aat_map.compile (plan.aat_map);
99
100   plan.frac_mask = plan.map.get_1_mask (HB_TAG ('f','r','a','c'));
101   plan.numr_mask = plan.map.get_1_mask (HB_TAG ('n','u','m','r'));
102   plan.dnom_mask = plan.map.get_1_mask (HB_TAG ('d','n','o','m'));
103   plan.has_frac = plan.frac_mask || (plan.numr_mask && plan.dnom_mask);
104   plan.rtlm_mask = plan.map.get_1_mask (HB_TAG ('r','t','l','m'));
105   hb_tag_t kern_tag = HB_DIRECTION_IS_HORIZONTAL (props.direction) ?
106                       HB_TAG ('k','e','r','n') : HB_TAG ('v','k','r','n');
107   plan.kern_mask = plan.map.get_mask (kern_tag);
108   plan.trak_mask = plan.map.get_mask (HB_TAG ('t','r','a','k'));
109
110   plan.requested_kerning = !!plan.kern_mask;
111   plan.requested_tracking = !!plan.trak_mask;
112   bool has_gpos_kern = plan.map.get_feature_index (1, kern_tag) != HB_OT_LAYOUT_NO_FEATURE_INDEX;
113   bool disable_gpos = plan.shaper->gpos_tag &&
114                       plan.shaper->gpos_tag != plan.map.chosen_script[1];
115
116   /*
117    * Decide who provides glyph classes. GDEF or Unicode.
118    */
119
120   if (!hb_ot_layout_has_glyph_classes (face))
121     plan.fallback_glyph_classes = true;
122
123   /*
124    * Decide who does substitutions. GSUB, morx, or fallback.
125    */
126
127   plan.apply_morx = apply_morx;
128
129   /*
130    * Decide who does positioning. GPOS, kerx, kern, or fallback.
131    */
132
133   if (hb_options ().aat && hb_aat_layout_has_positioning (face))
134     plan.apply_kerx = true;
135   else if (!apply_morx && !disable_gpos && hb_ot_layout_has_positioning (face))
136     plan.apply_gpos = true;
137   else if (hb_aat_layout_has_positioning (face))
138     plan.apply_kerx = true;
139
140   if (!plan.apply_kerx && !has_gpos_kern)
141   {
142     /* Apparently Apple applies kerx if GPOS kern was not applied. */
143     if (hb_aat_layout_has_positioning (face))
144       plan.apply_kerx = true;
145     else if (hb_ot_layout_has_kerning (face))
146       plan.apply_kern = true;
147   }
148
149   plan.zero_marks = script_zero_marks &&
150                     !plan.apply_kerx &&
151                     (!plan.apply_kern || !hb_ot_layout_has_machine_kerning (face));
152   plan.has_gpos_mark = !!plan.map.get_1_mask (HB_TAG ('m','a','r','k'));
153
154   plan.adjust_mark_positioning_when_zeroing = !plan.apply_gpos &&
155                                               !plan.apply_kerx &&
156                                               (!plan.apply_kern || !hb_ot_layout_has_cross_kerning (face));
157
158   plan.fallback_mark_positioning = plan.adjust_mark_positioning_when_zeroing &&
159                                    script_fallback_mark_positioning;
160
161   /* Currently we always apply trak. */
162   plan.apply_trak = plan.requested_tracking && hb_aat_layout_has_tracking (face);
163 }
164
165 bool
166 hb_ot_shape_plan_t::init0 (hb_face_t                     *face,
167                            const hb_shape_plan_key_t     *key)
168 {
169   map.init ();
170   aat_map.init ();
171
172   hb_ot_shape_planner_t planner (face,
173                                  &key->props);
174
175   hb_ot_shape_collect_features (&planner,
176                                 key->user_features,
177                                 key->num_user_features);
178
179   planner.compile (*this, key->ot);
180
181   if (shaper->data_create)
182   {
183     data = shaper->data_create (this);
184     if (unlikely (!data))
185       return false;
186   }
187
188   return true;
189 }
190
191 void
192 hb_ot_shape_plan_t::fini ()
193 {
194   if (shaper->data_destroy)
195     shaper->data_destroy (const_cast<void *> (data));
196
197   map.fini ();
198   aat_map.fini ();
199 }
200
201 void
202 hb_ot_shape_plan_t::substitute (hb_font_t   *font,
203                                 hb_buffer_t *buffer) const
204 {
205   if (unlikely (apply_morx))
206     hb_aat_layout_substitute (this, font, buffer);
207   else
208     map.substitute (this, font, buffer);
209 }
210
211 void
212 hb_ot_shape_plan_t::position (hb_font_t   *font,
213                               hb_buffer_t *buffer) const
214 {
215   if (this->apply_gpos)
216     map.position (this, font, buffer);
217   else if (this->apply_kerx)
218     hb_aat_layout_position (this, font, buffer);
219   else if (this->apply_kern)
220     hb_ot_layout_kern (this, font, buffer);
221   else
222     _hb_ot_shape_fallback_kern (this, font, buffer);
223
224   if (this->apply_trak)
225     hb_aat_layout_track (this, font, buffer);
226 }
227
228
229 static const hb_ot_map_feature_t
230 common_features[] =
231 {
232   {HB_TAG('c','c','m','p'), F_GLOBAL},
233   {HB_TAG('l','o','c','l'), F_GLOBAL},
234   {HB_TAG('m','a','r','k'), F_GLOBAL_MANUAL_JOINERS},
235   {HB_TAG('m','k','m','k'), F_GLOBAL_MANUAL_JOINERS},
236   {HB_TAG('r','l','i','g'), F_GLOBAL},
237 };
238
239
240 static const hb_ot_map_feature_t
241 horizontal_features[] =
242 {
243   {HB_TAG('c','a','l','t'), F_GLOBAL},
244   {HB_TAG('c','l','i','g'), F_GLOBAL},
245   {HB_TAG('c','u','r','s'), F_GLOBAL},
246   {HB_TAG('k','e','r','n'), F_GLOBAL_HAS_FALLBACK},
247   {HB_TAG('l','i','g','a'), F_GLOBAL},
248   {HB_TAG('r','c','l','t'), F_GLOBAL},
249 };
250
251 static void
252 hb_ot_shape_collect_features (hb_ot_shape_planner_t          *planner,
253                               const hb_feature_t             *user_features,
254                               unsigned int                    num_user_features)
255 {
256   hb_ot_map_builder_t *map = &planner->map;
257
258   map->enable_feature (HB_TAG('r','v','r','n'));
259   map->add_gsub_pause (nullptr);
260
261   switch (planner->props.direction) {
262     case HB_DIRECTION_LTR:
263       map->enable_feature (HB_TAG ('l','t','r','a'));
264       map->enable_feature (HB_TAG ('l','t','r','m'));
265       break;
266     case HB_DIRECTION_RTL:
267       map->enable_feature (HB_TAG ('r','t','l','a'));
268       map->add_feature (HB_TAG ('r','t','l','m'));
269       break;
270     case HB_DIRECTION_TTB:
271     case HB_DIRECTION_BTT:
272     case HB_DIRECTION_INVALID:
273     default:
274       break;
275   }
276
277   /* Automatic fractions. */
278   map->add_feature (HB_TAG ('f','r','a','c'));
279   map->add_feature (HB_TAG ('n','u','m','r'));
280   map->add_feature (HB_TAG ('d','n','o','m'));
281
282   /* Random! */
283   map->enable_feature (HB_TAG ('r','a','n','d'), F_RANDOM, HB_OT_MAP_MAX_VALUE);
284
285   /* Tracking.  We enable dummy feature here just to allow disabling
286    * AAT 'trak' table using features.
287    * https://github.com/harfbuzz/harfbuzz/issues/1303 */
288   map->enable_feature (HB_TAG ('t','r','a','k'), F_HAS_FALLBACK);
289
290   map->enable_feature (HB_TAG ('H','A','R','F'));
291
292   if (planner->shaper->collect_features)
293     planner->shaper->collect_features (planner);
294
295   map->enable_feature (HB_TAG ('B','U','Z','Z'));
296
297   for (unsigned int i = 0; i < ARRAY_LENGTH (common_features); i++)
298     map->add_feature (common_features[i]);
299
300   if (HB_DIRECTION_IS_HORIZONTAL (planner->props.direction))
301     for (unsigned int i = 0; i < ARRAY_LENGTH (horizontal_features); i++)
302       map->add_feature (horizontal_features[i]);
303   else
304   {
305     /* We really want to find a 'vert' feature if there's any in the font, no
306      * matter which script/langsys it is listed (or not) under.
307      * See various bugs referenced from:
308      * https://github.com/harfbuzz/harfbuzz/issues/63 */
309     map->enable_feature (HB_TAG ('v','e','r','t'), F_GLOBAL_SEARCH);
310   }
311
312   for (unsigned int i = 0; i < num_user_features; i++)
313   {
314     const hb_feature_t *feature = &user_features[i];
315     map->add_feature (feature->tag,
316                       (feature->start == HB_FEATURE_GLOBAL_START &&
317                        feature->end == HB_FEATURE_GLOBAL_END) ?  F_GLOBAL : F_NONE,
318                       feature->value);
319   }
320
321   if (planner->apply_morx)
322   {
323     hb_aat_map_builder_t *aat_map = &planner->aat_map;
324     for (unsigned int i = 0; i < num_user_features; i++)
325     {
326       const hb_feature_t *feature = &user_features[i];
327       aat_map->add_feature (feature->tag, feature->value);
328     }
329   }
330
331   if (planner->shaper->override_features)
332     planner->shaper->override_features (planner);
333 }
334
335
336 /*
337  * shaper face data
338  */
339
340 struct hb_ot_face_data_t {};
341
342 hb_ot_face_data_t *
343 _hb_ot_shaper_face_data_create (hb_face_t *face)
344 {
345   return (hb_ot_face_data_t *) HB_SHAPER_DATA_SUCCEEDED;
346 }
347
348 void
349 _hb_ot_shaper_face_data_destroy (hb_ot_face_data_t *data)
350 {
351 }
352
353
354 /*
355  * shaper font data
356  */
357
358 struct hb_ot_font_data_t {};
359
360 hb_ot_font_data_t *
361 _hb_ot_shaper_font_data_create (hb_font_t *font HB_UNUSED)
362 {
363   return (hb_ot_font_data_t *) HB_SHAPER_DATA_SUCCEEDED;
364 }
365
366 void
367 _hb_ot_shaper_font_data_destroy (hb_ot_font_data_t *data HB_UNUSED)
368 {
369 }
370
371
372 /*
373  * shaper
374  */
375
376 struct hb_ot_shape_context_t
377 {
378   hb_ot_shape_plan_t *plan;
379   hb_font_t *font;
380   hb_face_t *face;
381   hb_buffer_t  *buffer;
382   const hb_feature_t *user_features;
383   unsigned int        num_user_features;
384
385   /* Transient stuff */
386   hb_direction_t target_direction;
387 };
388
389
390
391 /* Main shaper */
392
393
394 /* Prepare */
395
396 static void
397 hb_set_unicode_props (hb_buffer_t *buffer)
398 {
399   /* Implement enough of Unicode Graphemes here that shaping
400    * in reverse-direction wouldn't break graphemes.  Namely,
401    * we mark all marks and ZWJ and ZWJ,Extended_Pictographic
402    * sequences as continuations.  The foreach_grapheme()
403    * macro uses this bit.
404    *
405    * https://www.unicode.org/reports/tr29/#Regex_Definitions
406    */
407   unsigned int count = buffer->len;
408   hb_glyph_info_t *info = buffer->info;
409   for (unsigned int i = 0; i < count; i++)
410   {
411     _hb_glyph_info_set_unicode_props (&info[i], buffer);
412
413     /* Marks are already set as continuation by the above line.
414      * Handle Emoji_Modifier and ZWJ-continuation. */
415     if (unlikely (_hb_glyph_info_get_general_category (&info[i]) == HB_UNICODE_GENERAL_CATEGORY_MODIFIER_SYMBOL &&
416                   hb_in_range<hb_codepoint_t> (info[i].codepoint, 0x1F3FBu, 0x1F3FFu)))
417     {
418         _hb_glyph_info_set_continuation (&info[i]);
419     }
420     else if (unlikely (_hb_glyph_info_is_zwj (&info[i])))
421     {
422       _hb_glyph_info_set_continuation (&info[i]);
423       if (i + 1 < count &&
424           _hb_unicode_is_emoji_Extended_Pictographic (info[i + 1].codepoint))
425       {
426         i++;
427         _hb_glyph_info_set_unicode_props (&info[i], buffer);
428         _hb_glyph_info_set_continuation (&info[i]);
429       }
430     }
431     /* Or part of the Other_Grapheme_Extend that is not marks.
432      * As of Unicode 11 that is just:
433      *
434      * 200C          ; Other_Grapheme_Extend # Cf       ZERO WIDTH NON-JOINER
435      * FF9E..FF9F    ; Other_Grapheme_Extend # Lm   [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
436      * E0020..E007F  ; Other_Grapheme_Extend # Cf  [96] TAG SPACE..CANCEL TAG
437      *
438      * ZWNJ is special, we don't want to merge it as there's no need, and keeping
439      * it separate results in more granular clusters.  Ignore Katakana for now.
440      * Tags are used for Emoji sub-region flag sequences:
441      * https://github.com/harfbuzz/harfbuzz/issues/1556
442      */
443     else if (unlikely (hb_in_range<hb_codepoint_t> (info[i].codepoint, 0xE0020u, 0xE007Fu)))
444       _hb_glyph_info_set_continuation (&info[i]);
445   }
446 }
447
448 static void
449 hb_insert_dotted_circle (hb_buffer_t *buffer, hb_font_t *font)
450 {
451   if (!(buffer->flags & HB_BUFFER_FLAG_BOT) ||
452       buffer->context_len[0] ||
453       !_hb_glyph_info_is_unicode_mark (&buffer->info[0]))
454     return;
455
456   if (!font->has_glyph (0x25CCu))
457     return;
458
459   hb_glyph_info_t dottedcircle = {0};
460   dottedcircle.codepoint = 0x25CCu;
461   _hb_glyph_info_set_unicode_props (&dottedcircle, buffer);
462
463   buffer->clear_output ();
464
465   buffer->idx = 0;
466   hb_glyph_info_t info = dottedcircle;
467   info.cluster = buffer->cur().cluster;
468   info.mask = buffer->cur().mask;
469   buffer->output_info (info);
470   while (buffer->idx < buffer->len && buffer->successful)
471     buffer->next_glyph ();
472   buffer->swap_buffers ();
473 }
474
475 static void
476 hb_form_clusters (hb_buffer_t *buffer)
477 {
478   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_NON_ASCII))
479     return;
480
481   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
482     foreach_grapheme (buffer, start, end)
483       buffer->merge_clusters (start, end);
484   else
485     foreach_grapheme (buffer, start, end)
486       buffer->unsafe_to_break (start, end);
487 }
488
489 static void
490 hb_ensure_native_direction (hb_buffer_t *buffer)
491 {
492   hb_direction_t direction = buffer->props.direction;
493   hb_direction_t horiz_dir = hb_script_get_horizontal_direction (buffer->props.script);
494
495   /* TODO vertical:
496    * The only BTT vertical script is Ogham, but it's not clear to me whether OpenType
497    * Ogham fonts are supposed to be implemented BTT or not.  Need to research that
498    * first. */
499   if ((HB_DIRECTION_IS_HORIZONTAL (direction) &&
500        direction != horiz_dir && horiz_dir != HB_DIRECTION_INVALID) ||
501       (HB_DIRECTION_IS_VERTICAL   (direction) &&
502        direction != HB_DIRECTION_TTB))
503   {
504
505     if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS)
506       foreach_grapheme (buffer, start, end)
507       {
508         buffer->merge_clusters (start, end);
509         buffer->reverse_range (start, end);
510       }
511     else
512       foreach_grapheme (buffer, start, end)
513         /* form_clusters() merged clusters already, we don't merge. */
514         buffer->reverse_range (start, end);
515
516     buffer->reverse ();
517
518     buffer->props.direction = HB_DIRECTION_REVERSE (buffer->props.direction);
519   }
520 }
521
522
523 /*
524  * Substitute
525  */
526
527 static inline void
528 hb_ot_mirror_chars (const hb_ot_shape_context_t *c)
529 {
530   if (HB_DIRECTION_IS_FORWARD (c->target_direction))
531     return;
532
533   hb_buffer_t *buffer = c->buffer;
534   hb_unicode_funcs_t *unicode = buffer->unicode;
535   hb_mask_t rtlm_mask = c->plan->rtlm_mask;
536
537   unsigned int count = buffer->len;
538   hb_glyph_info_t *info = buffer->info;
539   for (unsigned int i = 0; i < count; i++) {
540     hb_codepoint_t codepoint = unicode->mirroring (info[i].codepoint);
541     if (likely (codepoint == info[i].codepoint || !c->font->has_glyph (codepoint)))
542       info[i].mask |= rtlm_mask;
543     else
544       info[i].codepoint = codepoint;
545   }
546 }
547
548 static inline void
549 hb_ot_shape_setup_masks_fraction (const hb_ot_shape_context_t *c)
550 {
551   if (!(c->buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_NON_ASCII) ||
552       !c->plan->has_frac)
553     return;
554
555   hb_buffer_t *buffer = c->buffer;
556
557   hb_mask_t pre_mask, post_mask;
558   if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
559   {
560     pre_mask = c->plan->numr_mask | c->plan->frac_mask;
561     post_mask = c->plan->frac_mask | c->plan->dnom_mask;
562   }
563   else
564   {
565     pre_mask = c->plan->frac_mask | c->plan->dnom_mask;
566     post_mask = c->plan->numr_mask | c->plan->frac_mask;
567   }
568
569   unsigned int count = buffer->len;
570   hb_glyph_info_t *info = buffer->info;
571   for (unsigned int i = 0; i < count; i++)
572   {
573     if (info[i].codepoint == 0x2044u) /* FRACTION SLASH */
574     {
575       unsigned int start = i, end = i + 1;
576       while (start &&
577              _hb_glyph_info_get_general_category (&info[start - 1]) ==
578              HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER)
579         start--;
580       while (end < count &&
581              _hb_glyph_info_get_general_category (&info[end]) ==
582              HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER)
583         end++;
584
585       buffer->unsafe_to_break (start, end);
586
587       for (unsigned int j = start; j < i; j++)
588         info[j].mask |= pre_mask;
589       info[i].mask |= c->plan->frac_mask;
590       for (unsigned int j = i + 1; j < end; j++)
591         info[j].mask |= post_mask;
592
593       i = end - 1;
594     }
595   }
596 }
597
598 static inline void
599 hb_ot_shape_initialize_masks (const hb_ot_shape_context_t *c)
600 {
601   hb_ot_map_t *map = &c->plan->map;
602   hb_buffer_t *buffer = c->buffer;
603
604   hb_mask_t global_mask = map->get_global_mask ();
605   buffer->reset_masks (global_mask);
606 }
607
608 static inline void
609 hb_ot_shape_setup_masks (const hb_ot_shape_context_t *c)
610 {
611   hb_ot_map_t *map = &c->plan->map;
612   hb_buffer_t *buffer = c->buffer;
613
614   hb_ot_shape_setup_masks_fraction (c);
615
616   if (c->plan->shaper->setup_masks)
617     c->plan->shaper->setup_masks (c->plan, buffer, c->font);
618
619   for (unsigned int i = 0; i < c->num_user_features; i++)
620   {
621     const hb_feature_t *feature = &c->user_features[i];
622     if (!(feature->start == 0 && feature->end == (unsigned int)-1)) {
623       unsigned int shift;
624       hb_mask_t mask = map->get_mask (feature->tag, &shift);
625       buffer->set_masks (feature->value << shift, mask, feature->start, feature->end);
626     }
627   }
628 }
629
630 static void
631 hb_ot_zero_width_default_ignorables (const hb_buffer_t *buffer)
632 {
633   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_DEFAULT_IGNORABLES) ||
634       (buffer->flags & HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES) ||
635       (buffer->flags & HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES))
636     return;
637
638   unsigned int count = buffer->len;
639   hb_glyph_info_t *info = buffer->info;
640   hb_glyph_position_t *pos = buffer->pos;
641   unsigned int i = 0;
642   for (i = 0; i < count; i++)
643     if (unlikely (_hb_glyph_info_is_default_ignorable (&info[i])))
644       pos[i].x_advance = pos[i].y_advance = pos[i].x_offset = pos[i].y_offset = 0;
645 }
646
647 static void
648 hb_ot_hide_default_ignorables (hb_buffer_t *buffer,
649                                hb_font_t   *font)
650 {
651   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_DEFAULT_IGNORABLES) ||
652       (buffer->flags & HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES))
653     return;
654
655   unsigned int count = buffer->len;
656   hb_glyph_info_t *info = buffer->info;
657
658   hb_codepoint_t invisible = buffer->invisible;
659   if (!(buffer->flags & HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES) &&
660       (invisible || font->get_nominal_glyph (' ', &invisible)))
661   {
662     /* Replace default-ignorables with a zero-advance invisible glyph. */
663     for (unsigned int i = 0; i < count; i++)
664     {
665       if (_hb_glyph_info_is_default_ignorable (&info[i]))
666         info[i].codepoint = invisible;
667     }
668   }
669   else
670     hb_ot_layout_delete_glyphs_inplace (buffer, _hb_glyph_info_is_default_ignorable);
671 }
672
673
674 static inline void
675 hb_ot_map_glyphs_fast (hb_buffer_t  *buffer)
676 {
677   /* Normalization process sets up glyph_index(), we just copy it. */
678   unsigned int count = buffer->len;
679   hb_glyph_info_t *info = buffer->info;
680   for (unsigned int i = 0; i < count; i++)
681     info[i].codepoint = info[i].glyph_index();
682
683   buffer->content_type = HB_BUFFER_CONTENT_TYPE_GLYPHS;
684 }
685
686 static inline void
687 hb_synthesize_glyph_classes (hb_buffer_t *buffer)
688 {
689   unsigned int count = buffer->len;
690   hb_glyph_info_t *info = buffer->info;
691   for (unsigned int i = 0; i < count; i++)
692   {
693     hb_ot_layout_glyph_props_flags_t klass;
694
695     /* Never mark default-ignorables as marks.
696      * They won't get in the way of lookups anyway,
697      * but having them as mark will cause them to be skipped
698      * over if the lookup-flag says so, but at least for the
699      * Mongolian variation selectors, looks like Uniscribe
700      * marks them as non-mark.  Some Mongolian fonts without
701      * GDEF rely on this.  Another notable character that
702      * this applies to is COMBINING GRAPHEME JOINER. */
703     klass = (_hb_glyph_info_get_general_category (&info[i]) !=
704              HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK ||
705              _hb_glyph_info_is_default_ignorable (&info[i])) ?
706             HB_OT_LAYOUT_GLYPH_PROPS_BASE_GLYPH :
707             HB_OT_LAYOUT_GLYPH_PROPS_MARK;
708     _hb_glyph_info_set_glyph_props (&info[i], klass);
709   }
710 }
711
712 static inline void
713 hb_ot_substitute_default (const hb_ot_shape_context_t *c)
714 {
715   hb_buffer_t *buffer = c->buffer;
716
717   hb_ot_mirror_chars (c);
718
719   HB_BUFFER_ALLOCATE_VAR (buffer, glyph_index);
720
721   _hb_ot_shape_normalize (c->plan, buffer, c->font);
722
723   hb_ot_shape_setup_masks (c);
724
725   /* This is unfortunate to go here, but necessary... */
726   if (c->plan->fallback_mark_positioning)
727     _hb_ot_shape_fallback_mark_position_recategorize_marks (c->plan, c->font, buffer);
728
729   hb_ot_map_glyphs_fast (buffer);
730
731   HB_BUFFER_DEALLOCATE_VAR (buffer, glyph_index);
732 }
733
734 static inline void
735 hb_ot_substitute_complex (const hb_ot_shape_context_t *c)
736 {
737   hb_buffer_t *buffer = c->buffer;
738
739   hb_ot_layout_substitute_start (c->font, buffer);
740
741   if (c->plan->fallback_glyph_classes)
742     hb_synthesize_glyph_classes (c->buffer);
743
744   c->plan->substitute (c->font, buffer);
745 }
746
747 static inline void
748 hb_ot_substitute_pre (const hb_ot_shape_context_t *c)
749 {
750   hb_ot_substitute_default (c);
751
752   _hb_buffer_allocate_gsubgpos_vars (c->buffer);
753
754   hb_ot_substitute_complex (c);
755 }
756
757 static inline void
758 hb_ot_substitute_post (const hb_ot_shape_context_t *c)
759 {
760   hb_ot_hide_default_ignorables (c->buffer, c->font);
761   if (c->plan->apply_morx)
762     hb_aat_layout_remove_deleted_glyphs (c->buffer);
763
764   if (c->plan->shaper->postprocess_glyphs)
765     c->plan->shaper->postprocess_glyphs (c->plan, c->buffer, c->font);
766 }
767
768
769 /*
770  * Position
771  */
772
773 static inline void
774 adjust_mark_offsets (hb_glyph_position_t *pos)
775 {
776   pos->x_offset -= pos->x_advance;
777   pos->y_offset -= pos->y_advance;
778 }
779
780 static inline void
781 zero_mark_width (hb_glyph_position_t *pos)
782 {
783   pos->x_advance = 0;
784   pos->y_advance = 0;
785 }
786
787 static inline void
788 zero_mark_widths_by_gdef (hb_buffer_t *buffer, bool adjust_offsets)
789 {
790   unsigned int count = buffer->len;
791   hb_glyph_info_t *info = buffer->info;
792   for (unsigned int i = 0; i < count; i++)
793     if (_hb_glyph_info_is_mark (&info[i]))
794     {
795       if (adjust_offsets)
796         adjust_mark_offsets (&buffer->pos[i]);
797       zero_mark_width (&buffer->pos[i]);
798     }
799 }
800
801 static inline void
802 hb_ot_position_default (const hb_ot_shape_context_t *c)
803 {
804   hb_direction_t direction = c->buffer->props.direction;
805   unsigned int count = c->buffer->len;
806   hb_glyph_info_t *info = c->buffer->info;
807   hb_glyph_position_t *pos = c->buffer->pos;
808
809   if (HB_DIRECTION_IS_HORIZONTAL (direction))
810   {
811     c->font->get_glyph_h_advances (count, &info[0].codepoint, sizeof(info[0]),
812                                    &pos[0].x_advance, sizeof(pos[0]));
813     /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
814     if (c->font->has_glyph_h_origin_func ())
815       for (unsigned int i = 0; i < count; i++)
816         c->font->subtract_glyph_h_origin (info[i].codepoint,
817                                           &pos[i].x_offset,
818                                           &pos[i].y_offset);
819   }
820   else
821   {
822     c->font->get_glyph_v_advances (count, &info[0].codepoint, sizeof(info[0]),
823                                    &pos[0].y_advance, sizeof(pos[0]));
824     for (unsigned int i = 0; i < count; i++)
825     {
826       c->font->subtract_glyph_v_origin (info[i].codepoint,
827                                         &pos[i].x_offset,
828                                         &pos[i].y_offset);
829     }
830   }
831   if (c->buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_SPACE_FALLBACK)
832     _hb_ot_shape_fallback_spaces (c->plan, c->font, c->buffer);
833 }
834
835 static inline void
836 hb_ot_position_complex (const hb_ot_shape_context_t *c)
837 {
838   unsigned int count = c->buffer->len;
839   hb_glyph_info_t *info = c->buffer->info;
840   hb_glyph_position_t *pos = c->buffer->pos;
841
842   /* If the font has no GPOS and direction is forward, then when
843    * zeroing mark widths, we shift the mark with it, such that the
844    * mark is positioned hanging over the previous glyph.  When
845    * direction is backward we don't shift and it will end up
846    * hanging over the next glyph after the final reordering.
847    *
848    * Note: If fallback positinoing happens, we don't care about
849    * this as it will be overriden.
850    */
851   bool adjust_offsets_when_zeroing = c->plan->adjust_mark_positioning_when_zeroing &&
852                                      HB_DIRECTION_IS_FORWARD (c->buffer->props.direction);
853
854   /* We change glyph origin to what GPOS expects (horizontal), apply GPOS, change it back. */
855
856   /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
857   if (c->font->has_glyph_h_origin_func ())
858     for (unsigned int i = 0; i < count; i++)
859       c->font->add_glyph_h_origin (info[i].codepoint,
860                                    &pos[i].x_offset,
861                                    &pos[i].y_offset);
862
863   hb_ot_layout_position_start (c->font, c->buffer);
864
865   if (c->plan->zero_marks)
866     switch (c->plan->shaper->zero_width_marks)
867     {
868       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY:
869         zero_mark_widths_by_gdef (c->buffer, adjust_offsets_when_zeroing);
870         break;
871
872       default:
873       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE:
874       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE:
875         break;
876     }
877
878   c->plan->position (c->font, c->buffer);
879
880   if (c->plan->zero_marks)
881     switch (c->plan->shaper->zero_width_marks)
882     {
883       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE:
884         zero_mark_widths_by_gdef (c->buffer, adjust_offsets_when_zeroing);
885         break;
886
887       default:
888       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE:
889       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY:
890         break;
891     }
892
893   /* Finish off.  Has to follow a certain order. */
894   hb_ot_layout_position_finish_advances (c->font, c->buffer);
895   hb_ot_zero_width_default_ignorables (c->buffer);
896   if (c->plan->apply_morx)
897     hb_aat_layout_zero_width_deleted_glyphs (c->buffer);
898   hb_ot_layout_position_finish_offsets (c->font, c->buffer);
899
900   /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
901   if (c->font->has_glyph_h_origin_func ())
902     for (unsigned int i = 0; i < count; i++)
903       c->font->subtract_glyph_h_origin (info[i].codepoint,
904                                         &pos[i].x_offset,
905                                         &pos[i].y_offset);
906
907   if (c->plan->fallback_mark_positioning)
908     _hb_ot_shape_fallback_mark_position (c->plan, c->font, c->buffer,
909                                          adjust_offsets_when_zeroing);
910 }
911
912 static inline void
913 hb_ot_position (const hb_ot_shape_context_t *c)
914 {
915   c->buffer->clear_positions ();
916
917   hb_ot_position_default (c);
918
919   hb_ot_position_complex (c);
920
921   if (HB_DIRECTION_IS_BACKWARD (c->buffer->props.direction))
922     hb_buffer_reverse (c->buffer);
923
924   _hb_buffer_deallocate_gsubgpos_vars (c->buffer);
925 }
926
927 static inline void
928 hb_propagate_flags (hb_buffer_t *buffer)
929 {
930   /* Propagate cluster-level glyph flags to be the same on all cluster glyphs.
931    * Simplifies using them. */
932
933   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_UNSAFE_TO_BREAK))
934     return;
935
936   hb_glyph_info_t *info = buffer->info;
937
938   foreach_cluster (buffer, start, end)
939   {
940     unsigned int mask = 0;
941     for (unsigned int i = start; i < end; i++)
942       if (info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK)
943       {
944          mask = HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
945          break;
946       }
947     if (mask)
948       for (unsigned int i = start; i < end; i++)
949         info[i].mask |= mask;
950   }
951 }
952
953 /* Pull it all together! */
954
955 static void
956 hb_ot_shape_internal (hb_ot_shape_context_t *c)
957 {
958   c->buffer->deallocate_var_all ();
959   c->buffer->scratch_flags = HB_BUFFER_SCRATCH_FLAG_DEFAULT;
960   if (likely (!hb_unsigned_mul_overflows (c->buffer->len, HB_BUFFER_MAX_LEN_FACTOR)))
961   {
962     c->buffer->max_len = MAX (c->buffer->len * HB_BUFFER_MAX_LEN_FACTOR,
963                               (unsigned) HB_BUFFER_MAX_LEN_MIN);
964   }
965   if (likely (!hb_unsigned_mul_overflows (c->buffer->len, HB_BUFFER_MAX_OPS_FACTOR)))
966   {
967     c->buffer->max_ops = MAX (c->buffer->len * HB_BUFFER_MAX_OPS_FACTOR,
968                               (unsigned) HB_BUFFER_MAX_OPS_MIN);
969   }
970
971   /* Save the original direction, we use it later. */
972   c->target_direction = c->buffer->props.direction;
973
974   _hb_buffer_allocate_unicode_vars (c->buffer);
975
976   c->buffer->clear_output ();
977
978   hb_ot_shape_initialize_masks (c);
979   hb_set_unicode_props (c->buffer);
980   hb_insert_dotted_circle (c->buffer, c->font);
981
982   hb_form_clusters (c->buffer);
983
984   hb_ensure_native_direction (c->buffer);
985
986   if (c->plan->shaper->preprocess_text)
987     c->plan->shaper->preprocess_text (c->plan, c->buffer, c->font);
988
989   hb_ot_substitute_pre (c);
990   hb_ot_position (c);
991   hb_ot_substitute_post (c);
992
993   hb_propagate_flags (c->buffer);
994
995   _hb_buffer_deallocate_unicode_vars (c->buffer);
996
997   c->buffer->props.direction = c->target_direction;
998
999   c->buffer->max_len = HB_BUFFER_MAX_LEN_DEFAULT;
1000   c->buffer->max_ops = HB_BUFFER_MAX_OPS_DEFAULT;
1001   c->buffer->deallocate_var_all ();
1002 }
1003
1004
1005 hb_bool_t
1006 _hb_ot_shape (hb_shape_plan_t    *shape_plan,
1007               hb_font_t          *font,
1008               hb_buffer_t        *buffer,
1009               const hb_feature_t *features,
1010               unsigned int        num_features)
1011 {
1012   hb_ot_shape_context_t c = {&shape_plan->ot, font, font->face, buffer, features, num_features};
1013   hb_ot_shape_internal (&c);
1014
1015   return true;
1016 }
1017
1018
1019 /**
1020  * hb_ot_shape_plan_collect_lookups:
1021  *
1022  * Since: 0.9.7
1023  **/
1024 void
1025 hb_ot_shape_plan_collect_lookups (hb_shape_plan_t *shape_plan,
1026                                   hb_tag_t         table_tag,
1027                                   hb_set_t        *lookup_indexes /* OUT */)
1028 {
1029   shape_plan->ot.collect_lookups (table_tag, lookup_indexes);
1030 }
1031
1032
1033 /* TODO Move this to hb-ot-shape-normalize, make it do decompose, and make it public. */
1034 static void
1035 add_char (hb_font_t          *font,
1036           hb_unicode_funcs_t *unicode,
1037           hb_bool_t           mirror,
1038           hb_codepoint_t      u,
1039           hb_set_t           *glyphs)
1040 {
1041   hb_codepoint_t glyph;
1042   if (font->get_nominal_glyph (u, &glyph))
1043     glyphs->add (glyph);
1044   if (mirror)
1045   {
1046     hb_codepoint_t m = unicode->mirroring (u);
1047     if (m != u && font->get_nominal_glyph (m, &glyph))
1048       glyphs->add (glyph);
1049   }
1050 }
1051
1052
1053 /**
1054  * hb_ot_shape_glyphs_closure:
1055  *
1056  * Since: 0.9.2
1057  **/
1058 void
1059 hb_ot_shape_glyphs_closure (hb_font_t          *font,
1060                             hb_buffer_t        *buffer,
1061                             const hb_feature_t *features,
1062                             unsigned int        num_features,
1063                             hb_set_t           *glyphs)
1064 {
1065   const char *shapers[] = {"ot", nullptr};
1066   hb_shape_plan_t *shape_plan = hb_shape_plan_create_cached (font->face, &buffer->props,
1067                                                              features, num_features, shapers);
1068
1069   bool mirror = hb_script_get_horizontal_direction (buffer->props.script) == HB_DIRECTION_RTL;
1070
1071   unsigned int count = buffer->len;
1072   hb_glyph_info_t *info = buffer->info;
1073   for (unsigned int i = 0; i < count; i++)
1074     add_char (font, buffer->unicode, mirror, info[i].codepoint, glyphs);
1075
1076   hb_set_t *lookups = hb_set_create ();
1077   hb_ot_shape_plan_collect_lookups (shape_plan, HB_OT_TAG_GSUB, lookups);
1078   hb_ot_layout_lookups_substitute_closure (font->face, lookups, glyphs);
1079
1080   hb_set_destroy (lookups);
1081
1082   hb_shape_plan_destroy (shape_plan);
1083 }