1 /*
2  * Copyright © 2010,2012  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Behdad Esfahbod
25  */
26 
27 #include "hb.hh"
28 
29 #ifndef HB_NO_OT_SHAPE
30 
31 #include "hb-ot-shape-complex-arabic.hh"
32 #include "hb-ot-shape.hh"
33 
34 /* buffer var allocations */
35 #define arabic_shaping_action() complex_var_u8_0() /* arabic shaping action */
36 
37 #define HB_BUFFER_SCRATCH_FLAG_ARABIC_HAS_STCH HB_BUFFER_SCRATCH_FLAG_COMPLEX0
38 
39 /* See:
40  * https://github.com/harfbuzz/harfbuzz/commit/6e6f82b6f3dde0fc6c3c7d991d9ec6cfff57823d#commitcomment-14248516 */
41 #define HB_ARABIC_GENERAL_CATEGORY_IS_WORD(gen_cat)                                                                                                               \
42     (FLAG_UNSAFE(gen_cat) &                                                                                                                                       \
43      (FLAG(HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED) |                                                                                                              \
44       FLAG(HB_UNICODE_GENERAL_CATEGORY_PRIVATE_USE) | /*FLAG (HB_UNICODE_GENERAL_CATEGORY_LOWERCASE_LETTER) |*/                                                   \
45       FLAG(HB_UNICODE_GENERAL_CATEGORY_MODIFIER_LETTER) |                                                                                                         \
46       FLAG(                                                                                                                                                       \
47           HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER) | /*FLAG (HB_UNICODE_GENERAL_CATEGORY_TITLECASE_LETTER) |*/ /*FLAG                                            \
48                                                                                                                    (HB_UNICODE_GENERAL_CATEGORY_UPPERCASE_LETTER) \
49                                                                                                                    |*/                                            \
50       FLAG(HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK) |                                                                                                            \
51       FLAG(HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK) | FLAG(HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) |                                                     \
52       FLAG(HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER) | FLAG(HB_UNICODE_GENERAL_CATEGORY_LETTER_NUMBER) |                                                        \
53       FLAG(HB_UNICODE_GENERAL_CATEGORY_OTHER_NUMBER) | FLAG(HB_UNICODE_GENERAL_CATEGORY_CURRENCY_SYMBOL) |                                                        \
54       FLAG(HB_UNICODE_GENERAL_CATEGORY_MODIFIER_SYMBOL) | FLAG(HB_UNICODE_GENERAL_CATEGORY_MATH_SYMBOL) |                                                         \
55       FLAG(HB_UNICODE_GENERAL_CATEGORY_OTHER_SYMBOL)))
56 
57 /*
58  * Joining types:
59  */
60 
61 /*
62  * Bits used in the joining tables
63  */
64 enum hb_arabic_joining_type_t {
65     JOINING_TYPE_U = 0,
66     JOINING_TYPE_L = 1,
67     JOINING_TYPE_R = 2,
68     JOINING_TYPE_D = 3,
69     JOINING_TYPE_C = JOINING_TYPE_D,
70     JOINING_GROUP_ALAPH = 4,
71     JOINING_GROUP_DALATH_RISH = 5,
72     NUM_STATE_MACHINE_COLS = 6,
73 
74     JOINING_TYPE_T = 7,
75     JOINING_TYPE_X = 8 /* means: use general-category to choose between U or T. */
76 };
77 
78 #include "hb-ot-shape-complex-arabic-table.hh"
79 
get_joining_type(hb_codepoint_t u,hb_unicode_general_category_t gen_cat)80 static unsigned int get_joining_type(hb_codepoint_t u, hb_unicode_general_category_t gen_cat)
81 {
82     unsigned int j_type = joining_type(u);
83     if (likely(j_type != JOINING_TYPE_X))
84         return j_type;
85 
86     return (FLAG_UNSAFE(gen_cat) &
87             (FLAG(HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) | FLAG(HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK) |
88              FLAG(HB_UNICODE_GENERAL_CATEGORY_FORMAT)))
89                ? JOINING_TYPE_T
90                : JOINING_TYPE_U;
91 }
92 
93 #define FEATURE_IS_SYRIAC(tag) hb_in_range<unsigned char>((unsigned char)(tag), '2', '3')
94 
95 static const hb_tag_t arabic_features[] = {HB_TAG('i', 's', 'o', 'l'),
96                                            HB_TAG('f', 'i', 'n', 'a'),
97                                            HB_TAG('f', 'i', 'n', '2'),
98                                            HB_TAG('f', 'i', 'n', '3'),
99                                            HB_TAG('m', 'e', 'd', 'i'),
100                                            HB_TAG('m', 'e', 'd', '2'),
101                                            HB_TAG('i', 'n', 'i', 't'),
102                                            HB_TAG_NONE};
103 
104 /* Same order as the feature array */
105 enum arabic_action_t {
106     ISOL,
107     FINA,
108     FIN2,
109     FIN3,
110     MEDI,
111     MED2,
112     INIT,
113 
114     NONE,
115 
116     ARABIC_NUM_FEATURES = NONE,
117 
118     /* We abuse the same byte for other things... */
119     STCH_FIXED,
120     STCH_REPEATING,
121 };
122 
123 static const struct arabic_state_table_entry
124 {
125     uint8_t prev_action;
126     uint8_t curr_action;
127     uint16_t next_state;
128 } arabic_state_table[][NUM_STATE_MACHINE_COLS] = {
129     /*   jt_U,          jt_L,          jt_R,          jt_D,          jg_ALAPH,      jg_DALATH_RISH */
130 
131     /* State 0: prev was U, not willing to join. */
132     {
133         {NONE, NONE, 0},
134         {NONE, ISOL, 2},
135         {NONE, ISOL, 1},
136         {NONE, ISOL, 2},
137         {NONE, ISOL, 1},
138         {NONE, ISOL, 6},
139     },
140 
141     /* State 1: prev was R or ISOL/ALAPH, not willing to join. */
142     {
143         {NONE, NONE, 0},
144         {NONE, ISOL, 2},
145         {NONE, ISOL, 1},
146         {NONE, ISOL, 2},
147         {NONE, FIN2, 5},
148         {NONE, ISOL, 6},
149     },
150 
151     /* State 2: prev was D/L in ISOL form, willing to join. */
152     {
153         {NONE, NONE, 0},
154         {NONE, ISOL, 2},
155         {INIT, FINA, 1},
156         {INIT, FINA, 3},
157         {INIT, FINA, 4},
158         {INIT, FINA, 6},
159     },
160 
161     /* State 3: prev was D in FINA form, willing to join. */
162     {
163         {NONE, NONE, 0},
164         {NONE, ISOL, 2},
165         {MEDI, FINA, 1},
166         {MEDI, FINA, 3},
167         {MEDI, FINA, 4},
168         {MEDI, FINA, 6},
169     },
170 
171     /* State 4: prev was FINA ALAPH, not willing to join. */
172     {
173         {NONE, NONE, 0},
174         {NONE, ISOL, 2},
175         {MED2, ISOL, 1},
176         {MED2, ISOL, 2},
177         {MED2, FIN2, 5},
178         {MED2, ISOL, 6},
179     },
180 
181     /* State 5: prev was FIN2/FIN3 ALAPH, not willing to join. */
182     {
183         {NONE, NONE, 0},
184         {NONE, ISOL, 2},
185         {ISOL, ISOL, 1},
186         {ISOL, ISOL, 2},
187         {ISOL, FIN2, 5},
188         {ISOL, ISOL, 6},
189     },
190 
191     /* State 6: prev was DALATH/RISH, not willing to join. */
192     {
193         {NONE, NONE, 0},
194         {NONE, ISOL, 2},
195         {NONE, ISOL, 1},
196         {NONE, ISOL, 2},
197         {NONE, FIN3, 5},
198         {NONE, ISOL, 6},
199     }};
200 
201 static void arabic_fallback_shape(const hb_ot_shape_plan_t *plan, hb_font_t *font, hb_buffer_t *buffer);
202 
203 static void record_stch(const hb_ot_shape_plan_t *plan, hb_font_t *font, hb_buffer_t *buffer);
204 
collect_features_arabic(hb_ot_shape_planner_t * plan)205 static void collect_features_arabic(hb_ot_shape_planner_t *plan)
206 {
207     hb_ot_map_builder_t *map = &plan->map;
208 
209     /* We apply features according to the Arabic spec, with pauses
210      * in between most.
211      *
212      * The pause between init/medi/... and rlig is required.  See eg:
213      * https://bugzilla.mozilla.org/show_bug.cgi?id=644184
214      *
215      * The pauses between init/medi/... themselves are not necessarily
216      * needed as only one of those features is applied to any character.
217      * The only difference it makes is when fonts have contextual
218      * substitutions.  We now follow the order of the spec, which makes
219      * for better experience if that's what Uniscribe is doing.
220      *
221      * At least for Arabic, looks like Uniscribe has a pause between
222      * rlig and calt.  Otherwise the IranNastaliq's ALLAH ligature won't
223      * work.  However, testing shows that rlig and calt are applied
224      * together for Mongolian in Uniscribe.  As such, we only add a
225      * pause for Arabic, not other scripts.
226      *
227      * A pause after calt is required to make KFGQPC Uthmanic Script HAFS
228      * work correctly.  See https://github.com/harfbuzz/harfbuzz/issues/505
229      */
230 
231     map->enable_feature(HB_TAG('s', 't', 'c', 'h'));
232     map->add_gsub_pause(record_stch);
233 
234     map->enable_feature(HB_TAG('c', 'c', 'm', 'p'));
235     map->enable_feature(HB_TAG('l', 'o', 'c', 'l'));
236 
237     map->add_gsub_pause(nullptr);
238 
239     for (unsigned int i = 0; i < ARABIC_NUM_FEATURES; i++) {
240         bool has_fallback = plan->props.script == HB_SCRIPT_ARABIC && !FEATURE_IS_SYRIAC(arabic_features[i]);
241         map->add_feature(arabic_features[i], has_fallback ? F_HAS_FALLBACK : F_NONE);
242         map->add_gsub_pause(nullptr);
243     }
244 
245     /* Normally, Unicode says a ZWNJ means "don't ligate".  In Arabic script
246      * however, it says a ZWJ should also mean "don't ligate".  So we run
247      * the main ligating features as MANUAL_ZWJ. */
248 
249     map->enable_feature(HB_TAG('r', 'l', 'i', 'g'), F_MANUAL_ZWJ | F_HAS_FALLBACK);
250 
251     if (plan->props.script == HB_SCRIPT_ARABIC)
252         map->add_gsub_pause(arabic_fallback_shape);
253 
254     /* No pause after rclt.  See 98460779bae19e4d64d29461ff154b3527bf8420. */
255     map->enable_feature(HB_TAG('r', 'c', 'l', 't'), F_MANUAL_ZWJ);
256     map->enable_feature(HB_TAG('c', 'a', 'l', 't'), F_MANUAL_ZWJ);
257     map->add_gsub_pause(nullptr);
258 
259     /* And undo here. */
260 
261     /* The spec includes 'cswh'.  Earlier versions of Windows
262      * used to enable this by default, but testing suggests
263      * that Windows 8 and later do not enable it by default,
264      * and spec now says 'Off by default'.
265      * We disabled this in ae23c24c32.
266      * Note that IranNastaliq uses this feature extensively
267      * to fixup broken glyph sequences.  Oh well...
268      * Test case: U+0643,U+0640,U+0631. */
269     // map->enable_feature (HB_TAG('c','s','w','h'));
270     map->enable_feature(HB_TAG('m', 's', 'e', 't'));
271 }
272 
273 #include "hb-ot-shape-complex-arabic-fallback.hh"
274 
275 struct arabic_shape_plan_t
276 {
277     /* The "+ 1" in the next array is to accommodate for the "NONE" command,
278      * which is not an OpenType feature, but this simplifies the code by not
279      * having to do a "if (... < NONE) ..." and just rely on the fact that
280      * mask_array[NONE] == 0. */
281     hb_mask_t mask_array[ARABIC_NUM_FEATURES + 1];
282 
283     unsigned int do_fallback : 1;
284     unsigned int has_stch : 1;
285 };
286 
data_create_arabic(const hb_ot_shape_plan_t * plan)287 void *data_create_arabic(const hb_ot_shape_plan_t *plan)
288 {
289     arabic_shape_plan_t *arabic_plan = (arabic_shape_plan_t *)calloc(1, sizeof(arabic_shape_plan_t));
290     if (unlikely(!arabic_plan))
291         return nullptr;
292 
293     arabic_plan->do_fallback = plan->props.script == HB_SCRIPT_ARABIC;
294     arabic_plan->has_stch = !!plan->map.get_1_mask(HB_TAG('s', 't', 'c', 'h'));
295     for (unsigned int i = 0; i < ARABIC_NUM_FEATURES; i++) {
296         arabic_plan->mask_array[i] = plan->map.get_1_mask(arabic_features[i]);
297         arabic_plan->do_fallback = arabic_plan->do_fallback && (FEATURE_IS_SYRIAC(arabic_features[i]) ||
298                                                                 plan->map.needs_fallback(arabic_features[i]));
299     }
300 
301     return arabic_plan;
302 }
303 
data_destroy_arabic(void * data)304 void data_destroy_arabic(void *data)
305 {
306     free(data);
307 }
308 
arabic_joining(hb_buffer_t * buffer)309 static void arabic_joining(hb_buffer_t *buffer)
310 {
311     unsigned int count = buffer->len;
312     hb_glyph_info_t *info = buffer->info;
313     unsigned int prev = UINT_MAX, state = 0;
314 
315     /* Check pre-context */
316     for (unsigned int i = 0; i < buffer->context_len[0]; i++) {
317         unsigned int this_type =
318             get_joining_type(buffer->context[0][i], buffer->unicode->general_category(buffer->context[0][i]));
319 
320         if (unlikely(this_type == JOINING_TYPE_T))
321             continue;
322 
323         const arabic_state_table_entry *entry = &arabic_state_table[state][this_type];
324         state = entry->next_state;
325         break;
326     }
327 
328     for (unsigned int i = 0; i < count; i++) {
329         unsigned int this_type = get_joining_type(info[i].codepoint, _hb_glyph_info_get_general_category(&info[i]));
330 
331         if (unlikely(this_type == JOINING_TYPE_T)) {
332             info[i].arabic_shaping_action() = NONE;
333             continue;
334         }
335 
336         const arabic_state_table_entry *entry = &arabic_state_table[state][this_type];
337 
338         if (entry->prev_action != NONE && prev != UINT_MAX) {
339             info[prev].arabic_shaping_action() = entry->prev_action;
340             buffer->unsafe_to_break(prev, i + 1);
341         }
342 
343         info[i].arabic_shaping_action() = entry->curr_action;
344 
345         prev = i;
346         state = entry->next_state;
347     }
348 
349     for (unsigned int i = 0; i < buffer->context_len[1]; i++) {
350         unsigned int this_type =
351             get_joining_type(buffer->context[1][i], buffer->unicode->general_category(buffer->context[1][i]));
352 
353         if (unlikely(this_type == JOINING_TYPE_T))
354             continue;
355 
356         const arabic_state_table_entry *entry = &arabic_state_table[state][this_type];
357         if (entry->prev_action != NONE && prev != UINT_MAX)
358             info[prev].arabic_shaping_action() = entry->prev_action;
359         break;
360     }
361 }
362 
mongolian_variation_selectors(hb_buffer_t * buffer)363 static void mongolian_variation_selectors(hb_buffer_t *buffer)
364 {
365     /* Copy arabic_shaping_action() from base to Mongolian variation selectors. */
366     unsigned int count = buffer->len;
367     hb_glyph_info_t *info = buffer->info;
368     for (unsigned int i = 1; i < count; i++)
369         if (unlikely(hb_in_range<hb_codepoint_t>(info[i].codepoint, 0x180Bu, 0x180Du)))
370             info[i].arabic_shaping_action() = info[i - 1].arabic_shaping_action();
371 }
372 
setup_masks_arabic_plan(const arabic_shape_plan_t * arabic_plan,hb_buffer_t * buffer,hb_script_t script)373 void setup_masks_arabic_plan(const arabic_shape_plan_t *arabic_plan, hb_buffer_t *buffer, hb_script_t script)
374 {
375     HB_BUFFER_ALLOCATE_VAR(buffer, arabic_shaping_action);
376 
377     arabic_joining(buffer);
378     if (script == HB_SCRIPT_MONGOLIAN)
379         mongolian_variation_selectors(buffer);
380 
381     unsigned int count = buffer->len;
382     hb_glyph_info_t *info = buffer->info;
383     for (unsigned int i = 0; i < count; i++)
384         info[i].mask |= arabic_plan->mask_array[info[i].arabic_shaping_action()];
385 }
386 
setup_masks_arabic(const hb_ot_shape_plan_t * plan,hb_buffer_t * buffer,hb_font_t * font HB_UNUSED)387 static void setup_masks_arabic(const hb_ot_shape_plan_t *plan, hb_buffer_t *buffer, hb_font_t *font HB_UNUSED)
388 {
389     const arabic_shape_plan_t *arabic_plan = (const arabic_shape_plan_t *)plan->data;
390     setup_masks_arabic_plan(arabic_plan, buffer, plan->props.script);
391 }
392 
arabic_fallback_shape(const hb_ot_shape_plan_t * plan HB_UNUSED,hb_font_t * font HB_UNUSED,hb_buffer_t * buffer HB_UNUSED)393 static void arabic_fallback_shape(const hb_ot_shape_plan_t *plan HB_UNUSED, hb_font_t *font HB_UNUSED, hb_buffer_t *buffer HB_UNUSED)
394 {
395     return;
396 }
397 
398 /*
399  * Stretch feature: "stch".
400  * See example here:
401  * https://docs.microsoft.com/en-us/typography/script-development/syriac
402  * We implement this in a generic way, such that the Arabic subtending
403  * marks can use it as well.
404  */
405 
record_stch(const hb_ot_shape_plan_t * plan,hb_font_t * font HB_UNUSED,hb_buffer_t * buffer)406 static void record_stch(const hb_ot_shape_plan_t *plan, hb_font_t *font HB_UNUSED, hb_buffer_t *buffer)
407 {
408     const arabic_shape_plan_t *arabic_plan = (const arabic_shape_plan_t *)plan->data;
409     if (!arabic_plan->has_stch)
410         return;
411 
412     /* 'stch' feature was just applied.  Look for anything that multiplied,
413      * and record it for stch treatment later.  Note that rtlm, frac, etc
414      * are applied before stch, but we assume that they didn't result in
415      * anything multiplying into 5 pieces, so it's safe-ish... */
416 
417     unsigned int count = buffer->len;
418     hb_glyph_info_t *info = buffer->info;
419     for (unsigned int i = 0; i < count; i++)
420         if (unlikely(_hb_glyph_info_multiplied(&info[i]))) {
421             unsigned int comp = _hb_glyph_info_get_lig_comp(&info[i]);
422             info[i].arabic_shaping_action() = comp % 2 ? STCH_REPEATING : STCH_FIXED;
423             buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_ARABIC_HAS_STCH;
424         }
425 }
426 
apply_stch(const hb_ot_shape_plan_t * plan HB_UNUSED,hb_buffer_t * buffer,hb_font_t * font)427 static void apply_stch(const hb_ot_shape_plan_t *plan HB_UNUSED, hb_buffer_t *buffer, hb_font_t *font)
428 {
429     if (likely(!(buffer->scratch_flags & HB_BUFFER_SCRATCH_FLAG_ARABIC_HAS_STCH)))
430         return;
431 
432     /* The Arabic shaper currently always processes in RTL mode, so we should
433      * stretch / position the stretched pieces to the left / preceding glyphs. */
434 
435     /* We do a two pass implementation:
436      * First pass calculates the exact number of extra glyphs we need,
437      * We then enlarge buffer to have that much room,
438      * Second pass applies the stretch, copying things to the end of buffer.
439      */
440 
441     int sign = font->x_scale < 0 ? -1 : +1;
442     unsigned int extra_glyphs_needed = 0; // Set during MEASURE, used during CUT
443     enum { MEASURE, CUT } /* step_t */;
444 
445     for (unsigned int step = MEASURE; step <= CUT; step = step + 1) {
446         unsigned int count = buffer->len;
447         hb_glyph_info_t *info = buffer->info;
448         hb_glyph_position_t *pos = buffer->pos;
449         unsigned int new_len = count + extra_glyphs_needed; // write head during CUT
450         unsigned int j = new_len;
451         for (unsigned int i = count; i; i--) {
452             if (!hb_in_range<uint8_t>(info[i - 1].arabic_shaping_action(), STCH_FIXED, STCH_REPEATING)) {
453                 if (step == CUT) {
454                     --j;
455                     info[j] = info[i - 1];
456                     pos[j] = pos[i - 1];
457                 }
458                 continue;
459             }
460 
461             /* Yay, justification! */
462 
463             hb_position_t w_total = 0;     // Total to be filled
464             hb_position_t w_fixed = 0;     // Sum of fixed tiles
465             hb_position_t w_repeating = 0; // Sum of repeating tiles
466             int n_fixed = 0;
467             int n_repeating = 0;
468 
469             unsigned int end = i;
470             while (i && hb_in_range<uint8_t>(info[i - 1].arabic_shaping_action(), STCH_FIXED, STCH_REPEATING)) {
471                 i--;
472                 hb_position_t width = font->get_glyph_h_advance(info[i].codepoint);
473                 if (info[i].arabic_shaping_action() == STCH_FIXED) {
474                     w_fixed += width;
475                     n_fixed++;
476                 } else {
477                     w_repeating += width;
478                     n_repeating++;
479                 }
480             }
481             unsigned int start = i;
482             unsigned int context = i;
483             while (context &&
484                    !hb_in_range<uint8_t>(info[context - 1].arabic_shaping_action(), STCH_FIXED, STCH_REPEATING) &&
485                    (_hb_glyph_info_is_default_ignorable(&info[context - 1]) ||
486                     HB_ARABIC_GENERAL_CATEGORY_IS_WORD(_hb_glyph_info_get_general_category(&info[context - 1])))) {
487                 context--;
488                 w_total += pos[context].x_advance;
489             }
490             i++; // Don't touch i again.
491 
492             DEBUG_MSG(ARABIC,
493                       nullptr,
494                       "%s stretch at (%d,%d,%d)",
495                       step == MEASURE ? "measuring" : "cutting",
496                       context,
497                       start,
498                       end);
499             DEBUG_MSG(ARABIC, nullptr, "rest of word:    count=%d width %d", start - context, w_total);
500             DEBUG_MSG(ARABIC, nullptr, "fixed tiles:     count=%d width=%d", n_fixed, w_fixed);
501             DEBUG_MSG(ARABIC, nullptr, "repeating tiles: count=%d width=%d", n_repeating, w_repeating);
502 
503             /* Number of additional times to repeat each repeating tile. */
504             int n_copies = 0;
505 
506             hb_position_t w_remaining = w_total - w_fixed;
507             if (sign * w_remaining > sign * w_repeating && sign * w_repeating > 0)
508                 n_copies = (sign * w_remaining) / (sign * w_repeating) - 1;
509 
510             /* See if we can improve the fit by adding an extra repeat and squeezing them together a bit. */
511             hb_position_t extra_repeat_overlap = 0;
512             hb_position_t shortfall = sign * w_remaining - sign * w_repeating * (n_copies + 1);
513             if (shortfall > 0 && n_repeating > 0) {
514                 ++n_copies;
515                 hb_position_t excess = (n_copies + 1) * sign * w_repeating - sign * w_remaining;
516                 if (excess > 0)
517                     extra_repeat_overlap = excess / (n_copies * n_repeating);
518             }
519 
520             if (step == MEASURE) {
521                 extra_glyphs_needed += n_copies * n_repeating;
522                 DEBUG_MSG(ARABIC, nullptr, "will add extra %d copies of repeating tiles", n_copies);
523             } else {
524                 buffer->unsafe_to_break(context, end);
525                 hb_position_t x_offset = 0;
526                 for (unsigned int k = end; k > start; k--) {
527                     hb_position_t width = font->get_glyph_h_advance(info[k - 1].codepoint);
528 
529                     unsigned int repeat = 1;
530                     if (info[k - 1].arabic_shaping_action() == STCH_REPEATING)
531                         repeat += n_copies;
532 
533                     DEBUG_MSG(
534                         ARABIC, nullptr, "appending %d copies of glyph %d; j=%d", repeat, info[k - 1].codepoint, j);
535                     for (unsigned int n = 0; n < repeat; n++) {
536                         x_offset -= width;
537                         if (n > 0)
538                             x_offset += extra_repeat_overlap;
539                         pos[k - 1].x_offset = x_offset;
540                         /* Append copy. */
541                         --j;
542                         info[j] = info[k - 1];
543                         pos[j] = pos[k - 1];
544                     }
545                 }
546             }
547         }
548 
549         if (step == MEASURE) {
550             if (unlikely(!buffer->ensure(count + extra_glyphs_needed)))
551                 break;
552         } else {
553             assert(j == 0);
554             buffer->len = new_len;
555         }
556     }
557 }
558 
postprocess_glyphs_arabic(const hb_ot_shape_plan_t * plan,hb_buffer_t * buffer,hb_font_t * font)559 static void postprocess_glyphs_arabic(const hb_ot_shape_plan_t *plan, hb_buffer_t *buffer, hb_font_t *font)
560 {
561     apply_stch(plan, buffer, font);
562 
563     HB_BUFFER_DEALLOCATE_VAR(buffer, arabic_shaping_action);
564 }
565 
566 /* https://www.unicode.org/reports/tr53/ */
567 
568 static hb_codepoint_t modifier_combining_marks[] = {
569     0x0654u, /* ARABIC HAMZA ABOVE */
570     0x0655u, /* ARABIC HAMZA BELOW */
571     0x0658u, /* ARABIC MARK NOON GHUNNA */
572     0x06DCu, /* ARABIC SMALL HIGH SEEN */
573     0x06E3u, /* ARABIC SMALL LOW SEEN */
574     0x06E7u, /* ARABIC SMALL HIGH YEH */
575     0x06E8u, /* ARABIC SMALL HIGH NOON */
576     0x08D3u, /* ARABIC SMALL LOW WAW */
577     0x08F3u, /* ARABIC SMALL HIGH WAW */
578 };
579 
info_is_mcm(const hb_glyph_info_t & info)580 static inline bool info_is_mcm(const hb_glyph_info_t &info)
581 {
582     hb_codepoint_t u = info.codepoint;
583     for (unsigned int i = 0; i < ARRAY_LENGTH(modifier_combining_marks); i++)
584         if (u == modifier_combining_marks[i])
585             return true;
586     return false;
587 }
588 
reorder_marks_arabic(const hb_ot_shape_plan_t * plan HB_UNUSED,hb_buffer_t * buffer,unsigned int start,unsigned int end)589 static void reorder_marks_arabic(const hb_ot_shape_plan_t *plan HB_UNUSED,
590                                  hb_buffer_t *buffer,
591                                  unsigned int start,
592                                  unsigned int end)
593 {
594     hb_glyph_info_t *info = buffer->info;
595 
596     DEBUG_MSG(ARABIC, buffer, "Reordering marks from %d to %d", start, end);
597 
598     unsigned int i = start;
599     for (unsigned int cc = 220; cc <= 230; cc += 10) {
600         DEBUG_MSG(ARABIC, buffer, "Looking for %d's starting at %d", cc, i);
601         while (i < end && info_cc(info[i]) < cc)
602             i++;
603         DEBUG_MSG(ARABIC, buffer, "Looking for %d's stopped at %d", cc, i);
604 
605         if (i == end)
606             break;
607 
608         if (info_cc(info[i]) > cc)
609             continue;
610 
611         unsigned int j = i;
612         while (j < end && info_cc(info[j]) == cc && info_is_mcm(info[j]))
613             j++;
614 
615         if (i == j)
616             continue;
617 
618         DEBUG_MSG(ARABIC, buffer, "Found %d's from %d to %d", cc, i, j);
619 
620         /* Shift it! */
621         DEBUG_MSG(ARABIC, buffer, "Shifting %d's: %d %d", cc, i, j);
622         hb_glyph_info_t temp[HB_OT_SHAPE_COMPLEX_MAX_COMBINING_MARKS];
623         assert(j - i <= ARRAY_LENGTH(temp));
624         buffer->merge_clusters(start, j);
625         memmove(temp, &info[i], (j - i) * sizeof(hb_glyph_info_t));
626         memmove(&info[start + j - i], &info[start], (i - start) * sizeof(hb_glyph_info_t));
627         memmove(&info[start], temp, (j - i) * sizeof(hb_glyph_info_t));
628 
629         /* Renumber CC such that the reordered sequence is still sorted.
630          * 22 and 26 are chosen because they are smaller than all Arabic categories,
631          * and are folded back to 220/230 respectively during fallback mark positioning.
632          *
633          * We do this because the CGJ-handling logic in the normalizer relies on
634          * mark sequences having an increasing order even after this reordering.
635          * https://github.com/harfbuzz/harfbuzz/issues/554
636          * This, however, does break some obscure sequences, where the normalizer
637          * might compose a sequence that it should not.  For example, in the seequence
638          * ALEF, HAMZAH, MADDAH, we should NOT try to compose ALEF+MADDAH, but with this
639          * renumbering, we will.
640          */
641         unsigned int new_start = start + j - i;
642         unsigned int new_cc = cc == 220 ? HB_MODIFIED_COMBINING_CLASS_CCC22 : HB_MODIFIED_COMBINING_CLASS_CCC26;
643         while (start < new_start) {
644             _hb_glyph_info_set_modified_combining_class(&info[start], new_cc);
645             start++;
646         }
647 
648         i = j;
649     }
650 }
651 
652 const hb_ot_complex_shaper_t _hb_ot_complex_shaper_arabic = {
653     collect_features_arabic,
654     nullptr, /* override_features */
655     data_create_arabic,
656     data_destroy_arabic,
657     nullptr, /* preprocess_text */
658     postprocess_glyphs_arabic,
659     HB_OT_SHAPE_NORMALIZATION_MODE_DEFAULT,
660     nullptr, /* decompose */
661     nullptr, /* compose */
662     setup_masks_arabic,
663     HB_TAG_NONE, /* gpos_tag */
664     reorder_marks_arabic,
665     HB_OT_SHAPE_ZERO_WIDTH_MARKS_BY_GDEF_LATE,
666     true, /* fallback_position */
667 };
668 
669 #endif
670