hb-ot-shape-complex-indic.cc revision 3d25079f8d6be81b9b4b91d3a97016b8a572f571
1/*
2 * Copyright © 2011  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
28#include "hb-ot-shape-complex-indic-private.hh"
29
30static int
31compare_codepoint (const void *pa, const void *pb)
32{
33  hb_codepoint_t a = * (hb_codepoint_t *) pa;
34  hb_codepoint_t b = * (hb_codepoint_t *) pb;
35
36  return a < b ? -1 : a == b ? 0 : +1;
37}
38
39static indic_position_t
40consonant_position (hb_codepoint_t u)
41{
42  consonant_position_t *record;
43
44  record = (consonant_position_t *) bsearch (&u, consonant_positions,
45					     ARRAY_LENGTH (consonant_positions),
46					     sizeof (consonant_positions[0]),
47					     compare_codepoint);
48
49  return record ? record->position : POS_BASE_C;
50}
51
52static bool
53is_ra (hb_codepoint_t u)
54{
55  return !!bsearch (&u, ra_chars,
56		    ARRAY_LENGTH (ra_chars),
57		    sizeof (ra_chars[0]),
58		    compare_codepoint);
59}
60
61static bool
62is_joiner (const hb_glyph_info_t &info)
63{
64  return !!(FLAG (info.indic_category()) & (FLAG (OT_ZWJ) | FLAG (OT_ZWNJ)));
65}
66
67static bool
68is_consonant (const hb_glyph_info_t &info)
69{
70  return !!(FLAG (info.indic_category()) & (FLAG (OT_C) | FLAG (OT_Ra)));
71}
72
73static const struct {
74  hb_tag_t tag;
75  hb_bool_t is_global;
76} indic_basic_features[] =
77{
78  {HB_TAG('n','u','k','t'), true},
79  {HB_TAG('a','k','h','n'), false},
80  {HB_TAG('r','p','h','f'), false},
81  {HB_TAG('r','k','r','f'), true},
82  {HB_TAG('p','r','e','f'), false},
83  {HB_TAG('b','l','w','f'), false},
84  {HB_TAG('h','a','l','f'), false},
85  {HB_TAG('v','a','t','u'), true},
86  {HB_TAG('p','s','t','f'), false},
87  {HB_TAG('c','j','c','t'), false},
88};
89
90/* Same order as the indic_basic_features array */
91enum {
92  _NUKT,
93  AKHN,
94  RPHF,
95  _RKRF,
96  PREF,
97  BLWF,
98  HALF,
99  _VATU,
100  PSTF,
101  CJCT
102};
103
104static const hb_tag_t indic_other_features[] =
105{
106  HB_TAG('p','r','e','s'),
107  HB_TAG('a','b','v','s'),
108  HB_TAG('b','l','w','s'),
109  HB_TAG('p','s','t','s'),
110  HB_TAG('h','a','l','n'),
111
112  HB_TAG('d','i','s','t'),
113  HB_TAG('a','b','v','m'),
114  HB_TAG('b','l','w','m'),
115};
116
117
118static void
119initial_reordering (const hb_ot_map_t *map,
120		    hb_face_t *face,
121		    hb_buffer_t *buffer,
122		    void *user_data HB_UNUSED);
123static void
124final_reordering (const hb_ot_map_t *map,
125		  hb_face_t *face,
126		  hb_buffer_t *buffer,
127		  void *user_data HB_UNUSED);
128
129void
130_hb_ot_shape_complex_collect_features_indic (hb_ot_map_builder_t *map, const hb_segment_properties_t  *props)
131{
132  map->add_bool_feature (HB_TAG('l','o','c','l'));
133  /* The Indic specs do not require ccmp, but we apply it here since if
134   * there is a use of it, it's typically at the beginning. */
135  map->add_bool_feature (HB_TAG('c','c','m','p'));
136
137  map->add_gsub_pause (initial_reordering, NULL);
138
139  for (unsigned int i = 0; i < ARRAY_LENGTH (indic_basic_features); i++) {
140    map->add_bool_feature (indic_basic_features[i].tag, indic_basic_features[i].is_global);
141    map->add_gsub_pause (NULL, NULL);
142  }
143
144  map->add_gsub_pause (final_reordering, NULL);
145
146  for (unsigned int i = 0; i < ARRAY_LENGTH (indic_other_features); i++) {
147    map->add_bool_feature (indic_other_features[i], true);
148    map->add_gsub_pause (NULL, NULL);
149  }
150}
151
152
153hb_ot_shape_normalization_mode_t
154_hb_ot_shape_complex_normalization_preference_indic (void)
155{
156  /* We want split matras decomposed by the common shaping logic. */
157  return HB_OT_SHAPE_NORMALIZATION_MODE_DECOMPOSED;
158}
159
160
161void
162_hb_ot_shape_complex_setup_masks_indic (hb_ot_map_t *map, hb_buffer_t *buffer, hb_font_t *font)
163{
164  HB_BUFFER_ALLOCATE_VAR (buffer, indic_category);
165  HB_BUFFER_ALLOCATE_VAR (buffer, indic_position);
166  HB_BUFFER_ALLOCATE_VAR (buffer, indic_syllable);
167
168  /* We cannot setup masks here.  We save information about characters
169   * and setup masks later on in a pause-callback. */
170
171  unsigned int count = buffer->len;
172  for (unsigned int i = 0; i < count; i++)
173  {
174    hb_glyph_info_t &info = buffer->info[i];
175    unsigned int type = get_indic_categories (info.codepoint);
176
177    info.indic_category() = type & 0x0F;
178    info.indic_position() = type >> 4;
179
180    if (info.indic_category() == OT_C) {
181      info.indic_position() = consonant_position (info.codepoint);
182      if (is_ra (info.codepoint))
183	info.indic_category() = OT_Ra;
184    } else if (info.indic_category() == OT_SM ||
185	       info.indic_category() == OT_VD) {
186      info.indic_position() = POS_SMVD;
187    } else if (unlikely (info.codepoint == 0x200C))
188      info.indic_category() = OT_ZWNJ;
189    else if (unlikely (info.codepoint == 0x200D))
190      info.indic_category() = OT_ZWJ;
191
192    if (unlikely (info.codepoint == 0x0952)) {
193      info.indic_category() = OT_A;
194      info.indic_position() = POS_SMVD;
195    }
196  }
197}
198
199static int
200compare_indic_order (const hb_glyph_info_t *pa, const hb_glyph_info_t *pb)
201{
202  int a = pa->indic_position();
203  int b = pb->indic_position();
204
205  return a < b ? -1 : a == b ? 0 : +1;
206}
207
208static void
209initial_reordering_consonant_syllable (const hb_ot_map_t *map, hb_buffer_t *buffer, hb_mask_t *mask_array,
210				       unsigned int start, unsigned int end)
211{
212  unsigned int i;
213  hb_glyph_info_t *info = buffer->info;
214
215  /* Comments from:
216   * https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */
217
218  /* 1. Find base consonant:
219   *
220   * The shaping engine finds the base consonant of the syllable, using the
221   * following algorithm: starting from the end of the syllable, move backwards
222   * until a consonant is found that does not have a below-base or post-base
223   * form (post-base forms have to follow below-base forms), or that is not a
224   * pre-base reordering Ra, or arrive at the first consonant. The consonant
225   * stopped at will be the base.
226   *
227   *   o If the syllable starts with Ra + Halant (in a script that has Reph)
228   *     and has more than one consonant, Ra is excluded from candidates for
229   *     base consonants.
230   */
231
232  unsigned int base = end;
233  bool has_reph = false;
234
235  /* -> If the syllable starts with Ra + Halant (in a script that has Reph)
236   *    and has more than one consonant, Ra is excluded from candidates for
237   *    base consonants. */
238  unsigned int limit = start;
239  if (mask_array[RPHF] &&
240      start + 2 < end &&
241      info[start].indic_category() == OT_Ra &&
242      info[start + 1].indic_category() == OT_H)
243  {
244    limit += 2;
245    base = start;
246    has_reph = true;
247  };
248
249  /* -> starting from the end of the syllable, move backwards */
250  i = end;
251  do {
252    i--;
253    /* -> until a consonant is found */
254    if (is_consonant (info[i]))
255    {
256      /* -> that does not have a below-base or post-base form
257       * (post-base forms have to follow below-base forms), */
258      if (info[i].indic_position() != POS_BELOW_C &&
259	  info[i].indic_position() != POS_POST_C)
260      {
261        base = i;
262	break;
263      }
264
265      /* -> or that is not a pre-base reordering Ra,
266       *
267       * TODO
268       */
269
270      /* ->  o If the syllable starts with Ra + Halant (in a script that has Reph)
271       *       and has more than one consonant, Ra is excluded from candidates for
272       *       base consonants.
273       *
274       * IMPLEMENTATION NOTES:
275       *
276       * We do this by adjusting limit accordingly before entering the loop.
277       */
278
279      /* -> or arrive at the first consonant. The consonant stopped at will
280       * be the base. */
281      base = i;
282    }
283    else
284      if (is_joiner (info[i]))
285        break;
286  } while (i > limit);
287  if (base < start)
288    base = start; /* Just in case... */
289
290  /* -> If the syllable starts with Ra + Halant (in a script that has Reph)
291   *    and has more than one consonant, Ra is excluded from candidates for
292   *    base consonants. */
293  if (has_reph && base == start) {
294    /* Have no other consonant, so Reph is not formed and Ra becomes base. */
295    has_reph = false;
296  }
297
298
299
300
301  /* 2. Decompose and reorder Matras:
302   *
303   * Each matra and any syllable modifier sign in the cluster are moved to the
304   * appropriate position relative to the consonant(s) in the cluster. The
305   * shaping engine decomposes two- or three-part matras into their constituent
306   * parts before any repositioning. Matra characters are classified by which
307   * consonant in a conjunct they have affinity for and are reordered to the
308   * following positions:
309   *
310   *   o Before first half form in the syllable
311   *   o After subjoined consonants
312   *   o After post-form consonant
313   *   o After main consonant (for above marks)
314   *
315   * IMPLEMENTATION NOTES:
316   *
317   * The normalize() routine has already decomposed matras for us, so we don't
318   * need to worry about that.
319   */
320
321
322  /* 3.  Reorder marks to canonical order:
323   *
324   * Adjacent nukta and halant or nukta and vedic sign are always repositioned
325   * if necessary, so that the nukta is first.
326   *
327   * IMPLEMENTATION NOTES:
328   *
329   * We don't need to do this: the normalize() routine already did this for us.
330   */
331
332
333  /* Reorder characters */
334
335  for (i = start; i < base; i++)
336    info[i].indic_position() = POS_PRE_C;
337  info[base].indic_position() = POS_BASE_C;
338
339
340  /* Handle beginning Ra */
341  if (has_reph &&
342      start + 3 <= end &&
343      !is_joiner (info[start + 2]))
344   {
345    info[start].indic_position() = POS_REPH;
346    info[start].mask = mask_array[RPHF];
347   }
348
349  /* For old-style Indic script tags, move the first post-base Halant after
350   * last consonant. */
351  if ((map->get_chosen_script (0) & 0x000000FF) != '2') {
352    /* We should only do this for Indic scripts which have a version two I guess. */
353    for (i = base + 1; i < end; i++)
354      if (info[i].indic_category() == OT_H) {
355        unsigned int j;
356        for (j = end - 1; j > i; j--)
357	  if ((FLAG (info[j].indic_category()) & (FLAG (OT_C) | FLAG (OT_Ra))))
358	    break;
359	if (j > i) {
360	  /* Move Halant to after last consonant. */
361	  hb_glyph_info_t t = info[i];
362	  memmove (&info[i], &info[i + 1], (j - i) * sizeof (info[0]));
363	  info[j] = t;
364	}
365        break;
366      }
367  }
368
369  /* Attach ZWJ, ZWNJ, nukta, and halant to previous char to move with them. */
370  for (i = start + 1; i < end; i++)
371    if ((FLAG (info[i].indic_category()) &
372	 (FLAG (OT_ZWNJ) | FLAG (OT_ZWJ) | FLAG (OT_N) | FLAG (OT_H))))
373      info[i].indic_position() = info[i - 1].indic_position();
374
375  /* We do bubble-sort, skip malicious clusters attempts */
376  if (end - start < 64)
377  {
378    /* Sit tight, rock 'n roll! */
379    hb_bubble_sort (info + start, end - start, compare_indic_order);
380    /* Find base again */
381    base = end;
382    for (i = start; i < end; i++)
383      if (info[i].indic_position() == POS_BASE_C) {
384        base = i;
385	break;
386      }
387  }
388
389  /* Setup masks now */
390
391  {
392    hb_mask_t mask;
393
394    /* Pre-base */
395    mask = mask_array[HALF] | mask_array[AKHN] | mask_array[CJCT];
396    for (i = start; i < base; i++)
397      info[i].mask  |= mask;
398    /* Base */
399    mask = mask_array[AKHN] | mask_array[CJCT];
400    info[base].mask |= mask;
401    /* Post-base */
402    mask = mask_array[BLWF] | mask_array[PSTF] | mask_array[CJCT];
403    for (i = base + 1; i < end; i++)
404      info[i].mask  |= mask;
405  }
406
407  /* Apply ZWJ/ZWNJ effects */
408  for (i = start + 1; i < end; i++)
409    if (is_joiner (info[i])) {
410      bool non_joiner = info[i].indic_category() == OT_ZWNJ;
411      unsigned int j = i;
412
413      do {
414	j--;
415
416	/* Reading the Unicode and OpenType specs, I think the following line
417	 * is correct, but this is not what the test suite expects currently.
418	 * The test suite has been drinking, not me...  But disable while
419	 * investigating.
420	 */
421	//info[j].mask &= !mask_array[CJCT];
422	if (non_joiner)
423	  info[j].mask &= !mask_array[HALF];
424
425      } while (j > start && !is_consonant (info[j]));
426    }
427}
428
429
430static void
431initial_reordering_vowel_syllable (const hb_ot_map_t *map, hb_buffer_t *buffer, hb_mask_t *mask_array,
432				   unsigned int start, unsigned int end)
433{
434  /* TODO
435   * Not clear to me how this should work.  Do the matras move to before the
436   * independent vowel?  No idea.
437   */
438}
439
440static void
441initial_reordering_standalone_cluster (const hb_ot_map_t *map, hb_buffer_t *buffer, hb_mask_t *mask_array,
442				       unsigned int start, unsigned int end)
443{
444  /* TODO
445   * Easiest thing to do here is to convert the NBSP to consonant and
446   * call initial_reordering_consonant_syllable.
447   */
448}
449
450static void
451initial_reordering_non_indic (const hb_ot_map_t *map, hb_buffer_t *buffer, hb_mask_t *mask_array,
452		 unsigned int start, unsigned int end)
453{
454  /* Nothing to do right now.  If we ever switch to using the output
455   * buffer in the reordering process, we'd need to next_glyph() here. */
456}
457
458#include "hb-ot-shape-complex-indic-machine.hh"
459
460static void
461initial_reordering (const hb_ot_map_t *map,
462		    hb_face_t *face,
463		    hb_buffer_t *buffer,
464		    void *user_data HB_UNUSED)
465{
466  hb_mask_t mask_array[ARRAY_LENGTH (indic_basic_features)] = {0};
467  unsigned int num_masks = ARRAY_LENGTH (indic_basic_features);
468  for (unsigned int i = 0; i < num_masks; i++)
469    mask_array[i] = map->get_1_mask (indic_basic_features[i].tag);
470
471  find_syllables (map, buffer, mask_array);
472}
473
474static void
475final_reordering_syllable (hb_buffer_t *buffer,
476			   unsigned int start, unsigned int end)
477{
478  /* 4. Final reordering:
479   *
480   * After the localized forms and basic shaping forms GSUB features have been
481   * applied (see below), the shaping engine performs some final glyph
482   * reordering before applying all the remaining font features to the entire
483   * cluster.
484   *
485   *   o Reorder matras:
486   *
487   *     If a pre-base matra character had been reordered before applying basic
488   *     features, the glyph can be moved closer to the main consonant based on
489   *     whether half-forms had been formed. Actual position for the matra is
490   *     defined as “after last standalone halant glyph, after initial matra
491   *     position and before the main consonant”. If ZWJ or ZWNJ follow this
492   *     halant, position is moved after it.
493   *
494   *   o Reorder reph:
495   *
496   *     Reph’s original position is always at the beginning of the syllable,
497   *     (i.e. it is not reordered at the character reordering stage). However,
498   *     it will be reordered according to the basic-forms shaping results.
499   *     Possible positions for reph, depending on the script, are; after main,
500   *     before post-base consonant forms, and after post-base consonant forms.
501   *
502   *       1. If reph should be positioned after post-base consonant forms,
503   *          proceed to step 5.
504   *
505   *       2. If the reph repositioning class is not after post-base: target
506   *          position is after the first explicit halant glyph between the
507   *          first post-reph consonant and last main consonant. If ZWJ or ZWNJ
508   *          are following this halant, position is moved after it. If such
509   *          position is found, this is the target position. Otherwise,
510   *          proceed to the next step.
511   *
512   *          Note: in old-implementation fonts, where classifications were
513   *          fixed in shaping engine, there was no case where reph position
514   *          will be found on this step.
515   *
516   *       3. If reph should be repositioned after the main consonant: from the
517   *          first consonant not ligated with main, or find the first
518   *          consonant that is not a potential pre-base reordering Ra.
519   *
520   *
521   *       4. If reph should be positioned before post-base consonant, find
522   *          first post-base classified consonant not ligated with main. If no
523   *          consonant is found, the target position should be before the
524   *          first matra, syllable modifier sign or vedic sign.
525   *
526   *       5. If no consonant is found in steps 3 or 4, move reph to a position
527   *          immediately before the first post-base matra, syllable modifier
528   *          sign or vedic sign that has a reordering class after the intended
529   *          reph position. For example, if the reordering position for reph
530   *          is post-main, it will skip above-base matras that also have a
531   *          post-main position.
532   *
533   *       6. Otherwise, reorder reph to the end of the syllable.
534   *
535   *   o Reorder pre-base reordering consonants:
536   *
537   *     If a pre-base reordering consonant is found, reorder it according to
538   *     the following rules:
539   *
540   *       1. Only reorder a glyph produced by substitution during application
541   *          of the feature. (Note that a font may shape a Ra consonant with
542   *          the feature generally but block it in certain contexts.)
543   *
544   *       2. Try to find a target position the same way as for pre-base matra.
545   *          If it is found, reorder pre-base consonant glyph.
546   *
547   *       3. If position is not found, reorder immediately before main
548   *          consonant.
549   */
550
551  /* TODO */
552  buffer->merge_clusters (start, end);
553}
554
555
556static void
557final_reordering (const hb_ot_map_t *map,
558		  hb_face_t *face,
559		  hb_buffer_t *buffer,
560		  void *user_data HB_UNUSED)
561{
562  unsigned int count = buffer->len;
563  if (!count) return;
564
565  hb_glyph_info_t *info = buffer->info;
566  unsigned int last = 0;
567  unsigned int last_syllable = info[0].indic_syllable();
568  for (unsigned int i = 1; i < count; i++)
569    if (last_syllable != info[i].indic_syllable()) {
570      final_reordering_syllable (buffer, last, i);
571      last = i;
572      last_syllable = info[last].indic_syllable();
573    }
574  final_reordering_syllable (buffer, last, count);
575
576  HB_BUFFER_DEALLOCATE_VAR (buffer, indic_syllable);
577  HB_BUFFER_DEALLOCATE_VAR (buffer, indic_category);
578  HB_BUFFER_DEALLOCATE_VAR (buffer, indic_position);
579}
580
581
582
583