Imported Upstream version 2.4.0
[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 (unlikely (buffer->flags & HB_BUFFER_FLAG_DO_NOT_INSERT_DOTTED_CIRCLE))
452     return;
453
454   if (!(buffer->flags & HB_BUFFER_FLAG_BOT) ||
455       buffer->context_len[0] ||
456       !_hb_glyph_info_is_unicode_mark (&buffer->info[0]))
457     return;
458
459   if (!font->has_glyph (0x25CCu))
460     return;
461
462   hb_glyph_info_t dottedcircle = {0};
463   dottedcircle.codepoint = 0x25CCu;
464   _hb_glyph_info_set_unicode_props (&dottedcircle, buffer);
465
466   buffer->clear_output ();
467
468   buffer->idx = 0;
469   hb_glyph_info_t info = dottedcircle;
470   info.cluster = buffer->cur().cluster;
471   info.mask = buffer->cur().mask;
472   buffer->output_info (info);
473   while (buffer->idx < buffer->len && buffer->successful)
474     buffer->next_glyph ();
475   buffer->swap_buffers ();
476 }
477
478 static void
479 hb_form_clusters (hb_buffer_t *buffer)
480 {
481   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_NON_ASCII))
482     return;
483
484   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
485     foreach_grapheme (buffer, start, end)
486       buffer->merge_clusters (start, end);
487   else
488     foreach_grapheme (buffer, start, end)
489       buffer->unsafe_to_break (start, end);
490 }
491
492 static void
493 hb_ensure_native_direction (hb_buffer_t *buffer)
494 {
495   hb_direction_t direction = buffer->props.direction;
496   hb_direction_t horiz_dir = hb_script_get_horizontal_direction (buffer->props.script);
497
498   /* TODO vertical:
499    * The only BTT vertical script is Ogham, but it's not clear to me whether OpenType
500    * Ogham fonts are supposed to be implemented BTT or not.  Need to research that
501    * first. */
502   if ((HB_DIRECTION_IS_HORIZONTAL (direction) &&
503        direction != horiz_dir && horiz_dir != HB_DIRECTION_INVALID) ||
504       (HB_DIRECTION_IS_VERTICAL   (direction) &&
505        direction != HB_DIRECTION_TTB))
506   {
507
508     if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS)
509       foreach_grapheme (buffer, start, end)
510       {
511         buffer->merge_clusters (start, end);
512         buffer->reverse_range (start, end);
513       }
514     else
515       foreach_grapheme (buffer, start, end)
516         /* form_clusters() merged clusters already, we don't merge. */
517         buffer->reverse_range (start, end);
518
519     buffer->reverse ();
520
521     buffer->props.direction = HB_DIRECTION_REVERSE (buffer->props.direction);
522   }
523 }
524
525
526 /*
527  * Substitute
528  */
529
530 static inline void
531 hb_ot_mirror_chars (const hb_ot_shape_context_t *c)
532 {
533   if (HB_DIRECTION_IS_FORWARD (c->target_direction))
534     return;
535
536   hb_buffer_t *buffer = c->buffer;
537   hb_unicode_funcs_t *unicode = buffer->unicode;
538   hb_mask_t rtlm_mask = c->plan->rtlm_mask;
539
540   unsigned int count = buffer->len;
541   hb_glyph_info_t *info = buffer->info;
542   for (unsigned int i = 0; i < count; i++) {
543     hb_codepoint_t codepoint = unicode->mirroring (info[i].codepoint);
544     if (likely (codepoint == info[i].codepoint || !c->font->has_glyph (codepoint)))
545       info[i].mask |= rtlm_mask;
546     else
547       info[i].codepoint = codepoint;
548   }
549 }
550
551 static inline void
552 hb_ot_shape_setup_masks_fraction (const hb_ot_shape_context_t *c)
553 {
554   if (!(c->buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_NON_ASCII) ||
555       !c->plan->has_frac)
556     return;
557
558   hb_buffer_t *buffer = c->buffer;
559
560   hb_mask_t pre_mask, post_mask;
561   if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
562   {
563     pre_mask = c->plan->numr_mask | c->plan->frac_mask;
564     post_mask = c->plan->frac_mask | c->plan->dnom_mask;
565   }
566   else
567   {
568     pre_mask = c->plan->frac_mask | c->plan->dnom_mask;
569     post_mask = c->plan->numr_mask | c->plan->frac_mask;
570   }
571
572   unsigned int count = buffer->len;
573   hb_glyph_info_t *info = buffer->info;
574   for (unsigned int i = 0; i < count; i++)
575   {
576     if (info[i].codepoint == 0x2044u) /* FRACTION SLASH */
577     {
578       unsigned int start = i, end = i + 1;
579       while (start &&
580              _hb_glyph_info_get_general_category (&info[start - 1]) ==
581              HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER)
582         start--;
583       while (end < count &&
584              _hb_glyph_info_get_general_category (&info[end]) ==
585              HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER)
586         end++;
587
588       buffer->unsafe_to_break (start, end);
589
590       for (unsigned int j = start; j < i; j++)
591         info[j].mask |= pre_mask;
592       info[i].mask |= c->plan->frac_mask;
593       for (unsigned int j = i + 1; j < end; j++)
594         info[j].mask |= post_mask;
595
596       i = end - 1;
597     }
598   }
599 }
600
601 static inline void
602 hb_ot_shape_initialize_masks (const hb_ot_shape_context_t *c)
603 {
604   hb_ot_map_t *map = &c->plan->map;
605   hb_buffer_t *buffer = c->buffer;
606
607   hb_mask_t global_mask = map->get_global_mask ();
608   buffer->reset_masks (global_mask);
609 }
610
611 static inline void
612 hb_ot_shape_setup_masks (const hb_ot_shape_context_t *c)
613 {
614   hb_ot_map_t *map = &c->plan->map;
615   hb_buffer_t *buffer = c->buffer;
616
617   hb_ot_shape_setup_masks_fraction (c);
618
619   if (c->plan->shaper->setup_masks)
620     c->plan->shaper->setup_masks (c->plan, buffer, c->font);
621
622   for (unsigned int i = 0; i < c->num_user_features; i++)
623   {
624     const hb_feature_t *feature = &c->user_features[i];
625     if (!(feature->start == 0 && feature->end == (unsigned int)-1)) {
626       unsigned int shift;
627       hb_mask_t mask = map->get_mask (feature->tag, &shift);
628       buffer->set_masks (feature->value << shift, mask, feature->start, feature->end);
629     }
630   }
631 }
632
633 static void
634 hb_ot_zero_width_default_ignorables (const hb_buffer_t *buffer)
635 {
636   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_DEFAULT_IGNORABLES) ||
637       (buffer->flags & HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES) ||
638       (buffer->flags & HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES))
639     return;
640
641   unsigned int count = buffer->len;
642   hb_glyph_info_t *info = buffer->info;
643   hb_glyph_position_t *pos = buffer->pos;
644   unsigned int i = 0;
645   for (i = 0; i < count; i++)
646     if (unlikely (_hb_glyph_info_is_default_ignorable (&info[i])))
647       pos[i].x_advance = pos[i].y_advance = pos[i].x_offset = pos[i].y_offset = 0;
648 }
649
650 static void
651 hb_ot_hide_default_ignorables (hb_buffer_t *buffer,
652                                hb_font_t   *font)
653 {
654   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_DEFAULT_IGNORABLES) ||
655       (buffer->flags & HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES))
656     return;
657
658   unsigned int count = buffer->len;
659   hb_glyph_info_t *info = buffer->info;
660
661   hb_codepoint_t invisible = buffer->invisible;
662   if (!(buffer->flags & HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES) &&
663       (invisible || font->get_nominal_glyph (' ', &invisible)))
664   {
665     /* Replace default-ignorables with a zero-advance invisible glyph. */
666     for (unsigned int i = 0; i < count; i++)
667     {
668       if (_hb_glyph_info_is_default_ignorable (&info[i]))
669         info[i].codepoint = invisible;
670     }
671   }
672   else
673     hb_ot_layout_delete_glyphs_inplace (buffer, _hb_glyph_info_is_default_ignorable);
674 }
675
676
677 static inline void
678 hb_ot_map_glyphs_fast (hb_buffer_t  *buffer)
679 {
680   /* Normalization process sets up glyph_index(), we just copy it. */
681   unsigned int count = buffer->len;
682   hb_glyph_info_t *info = buffer->info;
683   for (unsigned int i = 0; i < count; i++)
684     info[i].codepoint = info[i].glyph_index();
685
686   buffer->content_type = HB_BUFFER_CONTENT_TYPE_GLYPHS;
687 }
688
689 static inline void
690 hb_synthesize_glyph_classes (hb_buffer_t *buffer)
691 {
692   unsigned int count = buffer->len;
693   hb_glyph_info_t *info = buffer->info;
694   for (unsigned int i = 0; i < count; i++)
695   {
696     hb_ot_layout_glyph_props_flags_t klass;
697
698     /* Never mark default-ignorables as marks.
699      * They won't get in the way of lookups anyway,
700      * but having them as mark will cause them to be skipped
701      * over if the lookup-flag says so, but at least for the
702      * Mongolian variation selectors, looks like Uniscribe
703      * marks them as non-mark.  Some Mongolian fonts without
704      * GDEF rely on this.  Another notable character that
705      * this applies to is COMBINING GRAPHEME JOINER. */
706     klass = (_hb_glyph_info_get_general_category (&info[i]) !=
707              HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK ||
708              _hb_glyph_info_is_default_ignorable (&info[i])) ?
709             HB_OT_LAYOUT_GLYPH_PROPS_BASE_GLYPH :
710             HB_OT_LAYOUT_GLYPH_PROPS_MARK;
711     _hb_glyph_info_set_glyph_props (&info[i], klass);
712   }
713 }
714
715 static inline void
716 hb_ot_substitute_default (const hb_ot_shape_context_t *c)
717 {
718   hb_buffer_t *buffer = c->buffer;
719
720   hb_ot_mirror_chars (c);
721
722   HB_BUFFER_ALLOCATE_VAR (buffer, glyph_index);
723
724   _hb_ot_shape_normalize (c->plan, buffer, c->font);
725
726   hb_ot_shape_setup_masks (c);
727
728   /* This is unfortunate to go here, but necessary... */
729   if (c->plan->fallback_mark_positioning)
730     _hb_ot_shape_fallback_mark_position_recategorize_marks (c->plan, c->font, buffer);
731
732   hb_ot_map_glyphs_fast (buffer);
733
734   HB_BUFFER_DEALLOCATE_VAR (buffer, glyph_index);
735 }
736
737 static inline void
738 hb_ot_substitute_complex (const hb_ot_shape_context_t *c)
739 {
740   hb_buffer_t *buffer = c->buffer;
741
742   hb_ot_layout_substitute_start (c->font, buffer);
743
744   if (c->plan->fallback_glyph_classes)
745     hb_synthesize_glyph_classes (c->buffer);
746
747   c->plan->substitute (c->font, buffer);
748 }
749
750 static inline void
751 hb_ot_substitute_pre (const hb_ot_shape_context_t *c)
752 {
753   hb_ot_substitute_default (c);
754
755   _hb_buffer_allocate_gsubgpos_vars (c->buffer);
756
757   hb_ot_substitute_complex (c);
758 }
759
760 static inline void
761 hb_ot_substitute_post (const hb_ot_shape_context_t *c)
762 {
763   hb_ot_hide_default_ignorables (c->buffer, c->font);
764   if (c->plan->apply_morx)
765     hb_aat_layout_remove_deleted_glyphs (c->buffer);
766
767   if (c->plan->shaper->postprocess_glyphs)
768     c->plan->shaper->postprocess_glyphs (c->plan, c->buffer, c->font);
769 }
770
771
772 /*
773  * Position
774  */
775
776 static inline void
777 adjust_mark_offsets (hb_glyph_position_t *pos)
778 {
779   pos->x_offset -= pos->x_advance;
780   pos->y_offset -= pos->y_advance;
781 }
782
783 static inline void
784 zero_mark_width (hb_glyph_position_t *pos)
785 {
786   pos->x_advance = 0;
787   pos->y_advance = 0;
788 }
789
790 static inline void
791 zero_mark_widths_by_gdef (hb_buffer_t *buffer, bool adjust_offsets)
792 {
793   unsigned int count = buffer->len;
794   hb_glyph_info_t *info = buffer->info;
795   for (unsigned int i = 0; i < count; i++)
796     if (_hb_glyph_info_is_mark (&info[i]))
797     {
798       if (adjust_offsets)
799         adjust_mark_offsets (&buffer->pos[i]);
800       zero_mark_width (&buffer->pos[i]);
801     }
802 }
803
804 static inline void
805 hb_ot_position_default (const hb_ot_shape_context_t *c)
806 {
807   hb_direction_t direction = c->buffer->props.direction;
808   unsigned int count = c->buffer->len;
809   hb_glyph_info_t *info = c->buffer->info;
810   hb_glyph_position_t *pos = c->buffer->pos;
811
812   if (HB_DIRECTION_IS_HORIZONTAL (direction))
813   {
814     c->font->get_glyph_h_advances (count, &info[0].codepoint, sizeof(info[0]),
815                                    &pos[0].x_advance, sizeof(pos[0]));
816     /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
817     if (c->font->has_glyph_h_origin_func ())
818       for (unsigned int i = 0; i < count; i++)
819         c->font->subtract_glyph_h_origin (info[i].codepoint,
820                                           &pos[i].x_offset,
821                                           &pos[i].y_offset);
822   }
823   else
824   {
825     c->font->get_glyph_v_advances (count, &info[0].codepoint, sizeof(info[0]),
826                                    &pos[0].y_advance, sizeof(pos[0]));
827     for (unsigned int i = 0; i < count; i++)
828     {
829       c->font->subtract_glyph_v_origin (info[i].codepoint,
830                                         &pos[i].x_offset,
831                                         &pos[i].y_offset);
832     }
833   }
834   if (c->buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_SPACE_FALLBACK)
835     _hb_ot_shape_fallback_spaces (c->plan, c->font, c->buffer);
836 }
837
838 static inline void
839 hb_ot_position_complex (const hb_ot_shape_context_t *c)
840 {
841   unsigned int count = c->buffer->len;
842   hb_glyph_info_t *info = c->buffer->info;
843   hb_glyph_position_t *pos = c->buffer->pos;
844
845   /* If the font has no GPOS and direction is forward, then when
846    * zeroing mark widths, we shift the mark with it, such that the
847    * mark is positioned hanging over the previous glyph.  When
848    * direction is backward we don't shift and it will end up
849    * hanging over the next glyph after the final reordering.
850    *
851    * Note: If fallback positinoing happens, we don't care about
852    * this as it will be overriden.
853    */
854   bool adjust_offsets_when_zeroing = c->plan->adjust_mark_positioning_when_zeroing &&
855                                      HB_DIRECTION_IS_FORWARD (c->buffer->props.direction);
856
857   /* We change glyph origin to what GPOS expects (horizontal), apply GPOS, change it back. */
858
859   /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
860   if (c->font->has_glyph_h_origin_func ())
861     for (unsigned int i = 0; i < count; i++)
862       c->font->add_glyph_h_origin (info[i].codepoint,
863                                    &pos[i].x_offset,
864                                    &pos[i].y_offset);
865
866   hb_ot_layout_position_start (c->font, c->buffer);
867
868   if (c->plan->zero_marks)
869     switch (c->plan->shaper->zero_width_marks)
870     {
871       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY:
872         zero_mark_widths_by_gdef (c->buffer, adjust_offsets_when_zeroing);
873         break;
874
875       default:
876       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE:
877       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE:
878         break;
879     }
880
881   c->plan->position (c->font, c->buffer);
882
883   if (c->plan->zero_marks)
884     switch (c->plan->shaper->zero_width_marks)
885     {
886       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE:
887         zero_mark_widths_by_gdef (c->buffer, adjust_offsets_when_zeroing);
888         break;
889
890       default:
891       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE:
892       case HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_EARLY:
893         break;
894     }
895
896   /* Finish off.  Has to follow a certain order. */
897   hb_ot_layout_position_finish_advances (c->font, c->buffer);
898   hb_ot_zero_width_default_ignorables (c->buffer);
899   if (c->plan->apply_morx)
900     hb_aat_layout_zero_width_deleted_glyphs (c->buffer);
901   hb_ot_layout_position_finish_offsets (c->font, c->buffer);
902
903   /* The nil glyph_h_origin() func returns 0, so no need to apply it. */
904   if (c->font->has_glyph_h_origin_func ())
905     for (unsigned int i = 0; i < count; i++)
906       c->font->subtract_glyph_h_origin (info[i].codepoint,
907                                         &pos[i].x_offset,
908                                         &pos[i].y_offset);
909
910   if (c->plan->fallback_mark_positioning)
911     _hb_ot_shape_fallback_mark_position (c->plan, c->font, c->buffer,
912                                          adjust_offsets_when_zeroing);
913 }
914
915 static inline void
916 hb_ot_position (const hb_ot_shape_context_t *c)
917 {
918   c->buffer->clear_positions ();
919
920   hb_ot_position_default (c);
921
922   hb_ot_position_complex (c);
923
924   if (HB_DIRECTION_IS_BACKWARD (c->buffer->props.direction))
925     hb_buffer_reverse (c->buffer);
926
927   _hb_buffer_deallocate_gsubgpos_vars (c->buffer);
928 }
929
930 static inline void
931 hb_propagate_flags (hb_buffer_t *buffer)
932 {
933   /* Propagate cluster-level glyph flags to be the same on all cluster glyphs.
934    * Simplifies using them. */
935
936   if (!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_HAS_UNSAFE_TO_BREAK))
937     return;
938
939   hb_glyph_info_t *info = buffer->info;
940
941   foreach_cluster (buffer, start, end)
942   {
943     unsigned int mask = 0;
944     for (unsigned int i = start; i < end; i++)
945       if (info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK)
946       {
947          mask = HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
948          break;
949       }
950     if (mask)
951       for (unsigned int i = start; i < end; i++)
952         info[i].mask |= mask;
953   }
954 }
955
956 /* Pull it all together! */
957
958 static void
959 hb_ot_shape_internal (hb_ot_shape_context_t *c)
960 {
961   c->buffer->deallocate_var_all ();
962   c->buffer->scratch_flags = HB_BUFFER_SCRATCH_FLAG_DEFAULT;
963   if (likely (!hb_unsigned_mul_overflows (c->buffer->len, HB_BUFFER_MAX_LEN_FACTOR)))
964   {
965     c->buffer->max_len = MAX (c->buffer->len * HB_BUFFER_MAX_LEN_FACTOR,
966                               (unsigned) HB_BUFFER_MAX_LEN_MIN);
967   }
968   if (likely (!hb_unsigned_mul_overflows (c->buffer->len, HB_BUFFER_MAX_OPS_FACTOR)))
969   {
970     c->buffer->max_ops = MAX (c->buffer->len * HB_BUFFER_MAX_OPS_FACTOR,
971                               (unsigned) HB_BUFFER_MAX_OPS_MIN);
972   }
973
974   /* Save the original direction, we use it later. */
975   c->target_direction = c->buffer->props.direction;
976
977   _hb_buffer_allocate_unicode_vars (c->buffer);
978
979   c->buffer->clear_output ();
980
981   hb_ot_shape_initialize_masks (c);
982   hb_set_unicode_props (c->buffer);
983   hb_insert_dotted_circle (c->buffer, c->font);
984
985   hb_form_clusters (c->buffer);
986
987   hb_ensure_native_direction (c->buffer);
988
989   if (c->plan->shaper->preprocess_text)
990     c->plan->shaper->preprocess_text (c->plan, c->buffer, c->font);
991
992   hb_ot_substitute_pre (c);
993   hb_ot_position (c);
994   hb_ot_substitute_post (c);
995
996   hb_propagate_flags (c->buffer);
997
998   _hb_buffer_deallocate_unicode_vars (c->buffer);
999
1000   c->buffer->props.direction = c->target_direction;
1001
1002   c->buffer->max_len = HB_BUFFER_MAX_LEN_DEFAULT;
1003   c->buffer->max_ops = HB_BUFFER_MAX_OPS_DEFAULT;
1004   c->buffer->deallocate_var_all ();
1005 }
1006
1007
1008 hb_bool_t
1009 _hb_ot_shape (hb_shape_plan_t    *shape_plan,
1010               hb_font_t          *font,
1011               hb_buffer_t        *buffer,
1012               const hb_feature_t *features,
1013               unsigned int        num_features)
1014 {
1015   hb_ot_shape_context_t c = {&shape_plan->ot, font, font->face, buffer, features, num_features};
1016   hb_ot_shape_internal (&c);
1017
1018   return true;
1019 }
1020
1021
1022 /**
1023  * hb_ot_shape_plan_collect_lookups:
1024  *
1025  * Since: 0.9.7
1026  **/
1027 void
1028 hb_ot_shape_plan_collect_lookups (hb_shape_plan_t *shape_plan,
1029                                   hb_tag_t         table_tag,
1030                                   hb_set_t        *lookup_indexes /* OUT */)
1031 {
1032   shape_plan->ot.collect_lookups (table_tag, lookup_indexes);
1033 }
1034
1035
1036 /* TODO Move this to hb-ot-shape-normalize, make it do decompose, and make it public. */
1037 static void
1038 add_char (hb_font_t          *font,
1039           hb_unicode_funcs_t *unicode,
1040           hb_bool_t           mirror,
1041           hb_codepoint_t      u,
1042           hb_set_t           *glyphs)
1043 {
1044   hb_codepoint_t glyph;
1045   if (font->get_nominal_glyph (u, &glyph))
1046     glyphs->add (glyph);
1047   if (mirror)
1048   {
1049     hb_codepoint_t m = unicode->mirroring (u);
1050     if (m != u && font->get_nominal_glyph (m, &glyph))
1051       glyphs->add (glyph);
1052   }
1053 }
1054
1055
1056 /**
1057  * hb_ot_shape_glyphs_closure:
1058  *
1059  * Since: 0.9.2
1060  **/
1061 void
1062 hb_ot_shape_glyphs_closure (hb_font_t          *font,
1063                             hb_buffer_t        *buffer,
1064                             const hb_feature_t *features,
1065                             unsigned int        num_features,
1066                             hb_set_t           *glyphs)
1067 {
1068   const char *shapers[] = {"ot", nullptr};
1069   hb_shape_plan_t *shape_plan = hb_shape_plan_create_cached (font->face, &buffer->props,
1070                                                              features, num_features, shapers);
1071
1072   bool mirror = hb_script_get_horizontal_direction (buffer->props.script) == HB_DIRECTION_RTL;
1073
1074   unsigned int count = buffer->len;
1075   hb_glyph_info_t *info = buffer->info;
1076   for (unsigned int i = 0; i < count; i++)
1077     add_char (font, buffer->unicode, mirror, info[i].codepoint, glyphs);
1078
1079   hb_set_t *lookups = hb_set_create ();
1080   hb_ot_shape_plan_collect_lookups (shape_plan, HB_OT_TAG_GSUB, lookups);
1081   hb_ot_layout_lookups_substitute_closure (font->face, lookups, glyphs);
1082
1083   hb_set_destroy (lookups);
1084
1085   hb_shape_plan_destroy (shape_plan);
1086 }