hb-ot-shape-normalize.cc revision 07d682806349aee81f53114778ce0beb23909ed7
1/*
2 * Copyright © 2011,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-ot-shape-normalize-private.hh"
28#include "hb-ot-shape-private.hh"
29
30
31/*
32 * HIGHLEVEL DESIGN:
33 *
34 * This file exports one main function: _hb_ot_shape_normalize().
35 *
36 * This function closely reflects the Unicode Normalization Algorithm,
37 * yet it's different.
38 *
39 * Each shaper specifies whether it prefers decomposed (NFD) or composed (NFC).
40 * The logic however tries to use whatever the font can support.
41 *
42 * In general what happens is that: each grapheme is decomposed in a chain
43 * of 1:2 decompositions, marks reordered, and then recomposed if desired,
44 * so far it's like Unicode Normalization.  However, the decomposition and
45 * recomposition only happens if the font supports the resulting characters.
46 *
47 * The goals are:
48 *
49 *   - Try to render all canonically equivalent strings similarly.  To really
50 *     achieve this we have to always do the full decomposition and then
51 *     selectively recompose from there.  It's kinda too expensive though, so
52 *     we skip some cases.  For example, if composed is desired, we simply
53 *     don't touch 1-character clusters that are supported by the font, even
54 *     though their NFC may be different.
55 *
56 *   - When a font has a precomposed character for a sequence but the 'ccmp'
57 *     feature in the font is not adequate, use the precomposed character
58 *     which typically has better mark positioning.
59 *
60 *   - When a font does not support a combining mark, but supports it precomposed
61 *     with previous base, use that.  This needs the itemizer to have this
62 *     knowledge too.  We need to provide assistance to the itemizer.
63 *
64 *   - When a font does not support a character but supports its decomposition,
65 *     well, use the decomposition (preferring the canonical decomposition, but
66 *     falling back to the compatibility decomposition if necessary).  The
67 *     compatibility decomposition is really nice to have, for characters like
68 *     ellipsis, or various-sized space characters.
69 *
70 *   - The complex shapers can customize the compose and decompose functions to
71 *     offload some of their requirements to the normalizer.  For example, the
72 *     Indic shaper may want to disallow recomposing of two matras.
73 *
74 *   - We try compatibility decomposition if decomposing through canonical
75 *     decomposition alone failed to find a sequence that the font supports.
76 *     We don't try compatibility decomposition recursively during the canonical
77 *     decomposition phase.  This has minimal impact.  There are only a handful
78 *     of Greek letter that have canonical decompositions that include characters
79 *     with compatibility decomposition.  Those can be found using this command:
80 *
81 *     egrep  "`echo -n ';('; grep ';<' UnicodeData.txt | cut -d';' -f1 | tr '\n' '|'; echo ') '`" UnicodeData.txt
82 */
83
84static hb_bool_t
85decompose_func (hb_unicode_funcs_t *unicode,
86		hb_codepoint_t  ab,
87		hb_codepoint_t *a,
88		hb_codepoint_t *b)
89{
90  /* XXX FIXME, move these to complex shapers and propagage to normalizer.*/
91  switch (ab) {
92    case 0x0AC9  : return false;
93
94    case 0x0931  : return false;
95    case 0x0B94  : return false;
96
97    /* These ones have Unicode decompositions, but we do it
98     * this way to be close to what Uniscribe does. */
99    case 0x0DDA  : *a = 0x0DD9; *b= 0x0DDA; return true;
100    case 0x0DDC  : *a = 0x0DD9; *b= 0x0DDC; return true;
101    case 0x0DDD  : *a = 0x0DD9; *b= 0x0DDD; return true;
102    case 0x0DDE  : *a = 0x0DD9; *b= 0x0DDE; return true;
103
104    case 0x0F77  : *a = 0x0FB2; *b= 0x0F81; return true;
105    case 0x0F79  : *a = 0x0FB3; *b= 0x0F81; return true;
106    case 0x17BE  : *a = 0x17C1; *b= 0x17BE; return true;
107    case 0x17BF  : *a = 0x17C1; *b= 0x17BF; return true;
108    case 0x17C0  : *a = 0x17C1; *b= 0x17C0; return true;
109    case 0x17C4  : *a = 0x17C1; *b= 0x17C4; return true;
110    case 0x17C5  : *a = 0x17C1; *b= 0x17C5; return true;
111    case 0x1925  : *a = 0x1920; *b= 0x1923; return true;
112    case 0x1926  : *a = 0x1920; *b= 0x1924; return true;
113    case 0x1B3C  : *a = 0x1B42; *b= 0x1B3C; return true;
114    case 0x1112E  : *a = 0x11127; *b= 0x11131; return true;
115    case 0x1112F  : *a = 0x11127; *b= 0x11132; return true;
116#if 0
117    case 0x0B57  : *a = 0xno decomp, -> RIGHT; return true;
118    case 0x1C29  : *a = 0xno decomp, -> LEFT; return true;
119    case 0xA9C0  : *a = 0xno decomp, -> RIGHT; return true;
120    case 0x111BF  : *a = 0xno decomp, -> ABOVE; return true;
121#endif
122  }
123  return unicode->decompose (ab, a, b);
124}
125
126static hb_bool_t
127compose_func (hb_unicode_funcs_t *unicode,
128	      hb_codepoint_t  a,
129	      hb_codepoint_t  b,
130	      hb_codepoint_t *ab)
131{
132  /* XXX, this belongs to indic normalizer. */
133  if ((FLAG (unicode->general_category (a)) &
134       (FLAG (HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK) |
135	FLAG (HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK) |
136	FLAG (HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK))))
137    return false;
138  /* XXX, add composition-exclusion exceptions to Indic shaper. */
139  if (a == 0x09AF && b == 0x09BC) { *ab = 0x09DF; return true; }
140
141  /* XXX, these belong to the hebew / default shaper. */
142  /* Hebrew presentation-form shaping.
143   * https://bugzilla.mozilla.org/show_bug.cgi?id=728866 */
144  // Hebrew presentation forms with dagesh, for characters 0x05D0..0x05EA;
145  // note that some letters do not have a dagesh presForm encoded
146  static const hb_codepoint_t sDageshForms[0x05EA - 0x05D0 + 1] = {
147    0xFB30, // ALEF
148    0xFB31, // BET
149    0xFB32, // GIMEL
150    0xFB33, // DALET
151    0xFB34, // HE
152    0xFB35, // VAV
153    0xFB36, // ZAYIN
154    0, // HET
155    0xFB38, // TET
156    0xFB39, // YOD
157    0xFB3A, // FINAL KAF
158    0xFB3B, // KAF
159    0xFB3C, // LAMED
160    0, // FINAL MEM
161    0xFB3E, // MEM
162    0, // FINAL NUN
163    0xFB40, // NUN
164    0xFB41, // SAMEKH
165    0, // AYIN
166    0xFB43, // FINAL PE
167    0xFB44, // PE
168    0, // FINAL TSADI
169    0xFB46, // TSADI
170    0xFB47, // QOF
171    0xFB48, // RESH
172    0xFB49, // SHIN
173    0xFB4A // TAV
174  };
175
176  hb_bool_t found = unicode->compose (a, b, ab);
177
178  if (!found && (b & ~0x7F) == 0x0580) {
179      // special-case Hebrew presentation forms that are excluded from
180      // standard normalization, but wanted for old fonts
181      switch (b) {
182      case 0x05B4: // HIRIQ
183	  if (a == 0x05D9) { // YOD
184	      *ab = 0xFB1D;
185	      found = true;
186	  }
187	  break;
188      case 0x05B7: // patah
189	  if (a == 0x05F2) { // YIDDISH YOD YOD
190	      *ab = 0xFB1F;
191	      found = true;
192	  } else if (a == 0x05D0) { // ALEF
193	      *ab = 0xFB2E;
194	      found = true;
195	  }
196	  break;
197      case 0x05B8: // QAMATS
198	  if (a == 0x05D0) { // ALEF
199	      *ab = 0xFB2F;
200	      found = true;
201	  }
202	  break;
203      case 0x05B9: // HOLAM
204	  if (a == 0x05D5) { // VAV
205	      *ab = 0xFB4B;
206	      found = true;
207	  }
208	  break;
209      case 0x05BC: // DAGESH
210	  if (a >= 0x05D0 && a <= 0x05EA) {
211	      *ab = sDageshForms[a - 0x05D0];
212	      found = (*ab != 0);
213	  } else if (a == 0xFB2A) { // SHIN WITH SHIN DOT
214	      *ab = 0xFB2C;
215	      found = true;
216	  } else if (a == 0xFB2B) { // SHIN WITH SIN DOT
217	      *ab = 0xFB2D;
218	      found = true;
219	  }
220	  break;
221      case 0x05BF: // RAFE
222	  switch (a) {
223	  case 0x05D1: // BET
224	      *ab = 0xFB4C;
225	      found = true;
226	      break;
227	  case 0x05DB: // KAF
228	      *ab = 0xFB4D;
229	      found = true;
230	      break;
231	  case 0x05E4: // PE
232	      *ab = 0xFB4E;
233	      found = true;
234	      break;
235	  }
236	  break;
237      case 0x05C1: // SHIN DOT
238	  if (a == 0x05E9) { // SHIN
239	      *ab = 0xFB2A;
240	      found = true;
241	  } else if (a == 0xFB49) { // SHIN WITH DAGESH
242	      *ab = 0xFB2C;
243	      found = true;
244	  }
245	  break;
246      case 0x05C2: // SIN DOT
247	  if (a == 0x05E9) { // SHIN
248	      *ab = 0xFB2B;
249	      found = true;
250	  } else if (a == 0xFB49) { // SHIN WITH DAGESH
251	      *ab = 0xFB2D;
252	      found = true;
253	  }
254	  break;
255      }
256  }
257
258  return found;
259}
260
261
262static inline void
263set_glyph (hb_glyph_info_t &info, hb_font_t *font)
264{
265  font->get_glyph (info.codepoint, 0, &info.glyph_index());
266}
267
268static inline void
269output_char (hb_buffer_t *buffer, hb_codepoint_t unichar, hb_codepoint_t glyph)
270{
271  buffer->cur().glyph_index() = glyph;
272  buffer->output_glyph (unichar);
273  _hb_glyph_info_set_unicode_props (&buffer->prev(), buffer->unicode);
274}
275
276static inline void
277next_char (hb_buffer_t *buffer, hb_codepoint_t glyph)
278{
279  buffer->cur().glyph_index() = glyph;
280  buffer->next_glyph ();
281}
282
283static inline void
284skip_char (hb_buffer_t *buffer)
285{
286  buffer->skip_glyph ();
287}
288
289static bool
290decompose (hb_font_t *font, hb_buffer_t *buffer, bool shortest, hb_codepoint_t ab)
291{
292  hb_codepoint_t a, b, a_glyph, b_glyph;
293
294  if (!decompose_func (buffer->unicode, ab, &a, &b) ||
295      (b && !font->get_glyph (b, 0, &b_glyph)))
296    return false;
297
298  bool has_a = font->get_glyph (a, 0, &a_glyph);
299  if (shortest && has_a) {
300    /* Output a and b */
301    output_char (buffer, a, a_glyph);
302    if (b)
303      output_char (buffer, b, b_glyph);
304    return true;
305  }
306
307  if (decompose (font, buffer, shortest, a)) {
308    if (b)
309      output_char (buffer, b, b_glyph);
310    return true;
311  }
312
313  if (has_a) {
314    output_char (buffer, a, a_glyph);
315    if (b)
316      output_char (buffer, b, b_glyph);
317    return true;
318  }
319
320  return false;
321}
322
323static bool
324decompose_compatibility (hb_font_t *font, hb_buffer_t *buffer, hb_codepoint_t u)
325{
326  unsigned int len, i;
327  hb_codepoint_t decomposed[HB_UNICODE_MAX_DECOMPOSITION_LEN];
328  hb_codepoint_t glyphs[HB_UNICODE_MAX_DECOMPOSITION_LEN];
329
330  len = buffer->unicode->decompose_compatibility (u, decomposed);
331  if (!len)
332    return false;
333
334  for (i = 0; i < len; i++)
335    if (!font->get_glyph (decomposed[i], 0, &glyphs[i]))
336      return false;
337
338  for (i = 0; i < len; i++)
339    output_char (buffer, decomposed[i], glyphs[i]);
340
341  return true;
342}
343
344static void
345decompose_current_character (hb_font_t *font, hb_buffer_t *buffer, bool shortest)
346{
347  hb_codepoint_t glyph;
348
349  /* Kind of a cute waterfall here... */
350  if (shortest && font->get_glyph (buffer->cur().codepoint, 0, &glyph))
351    next_char (buffer, glyph);
352  else if (decompose (font, buffer, shortest, buffer->cur().codepoint))
353    skip_char (buffer);
354  else if (!shortest && font->get_glyph (buffer->cur().codepoint, 0, &glyph))
355    next_char (buffer, glyph);
356  else if (decompose_compatibility (font, buffer, buffer->cur().codepoint))
357    skip_char (buffer);
358  else
359    next_char (buffer, glyph); /* glyph is initialized in earlier branches. */
360}
361
362static inline void
363handle_variation_selector_cluster (hb_font_t *font, hb_buffer_t *buffer, unsigned int end)
364{
365  for (; buffer->idx < end - 1;) {
366    if (unlikely (buffer->unicode->is_variation_selector (buffer->cur(+1).codepoint))) {
367      /* The next two lines are some ugly lines... But work. */
368      font->get_glyph (buffer->cur().codepoint, buffer->cur(+1).codepoint, &buffer->cur().glyph_index());
369      buffer->replace_glyphs (2, 1, &buffer->cur().codepoint);
370    } else {
371      set_glyph (buffer->cur(), font);
372      buffer->next_glyph ();
373    }
374  }
375  if (likely (buffer->idx < end)) {
376    set_glyph (buffer->cur(), font);
377    buffer->next_glyph ();
378  }
379}
380
381static void
382decompose_multi_char_cluster (hb_font_t *font, hb_buffer_t *buffer, unsigned int end)
383{
384  /* TODO Currently if there's a variation-selector we give-up, it's just too hard. */
385  for (unsigned int i = buffer->idx; i < end; i++)
386    if (unlikely (buffer->unicode->is_variation_selector (buffer->info[i].codepoint))) {
387      handle_variation_selector_cluster (font, buffer, end);
388      return;
389    }
390
391  while (buffer->idx < end)
392    decompose_current_character (font, buffer, false);
393}
394
395static int
396compare_combining_class (const hb_glyph_info_t *pa, const hb_glyph_info_t *pb)
397{
398  unsigned int a = _hb_glyph_info_get_modified_combining_class (pa);
399  unsigned int b = _hb_glyph_info_get_modified_combining_class (pb);
400
401  return a < b ? -1 : a == b ? 0 : +1;
402}
403
404void
405_hb_ot_shape_normalize (hb_font_t *font, hb_buffer_t *buffer,
406			hb_ot_shape_normalization_mode_t mode)
407{
408  bool recompose = mode != HB_OT_SHAPE_NORMALIZATION_MODE_DECOMPOSED;
409  bool has_multichar_clusters = false;
410  unsigned int count;
411
412  /* We do a fairly straightforward yet custom normalization process in three
413   * separate rounds: decompose, reorder, recompose (if desired).  Currently
414   * this makes two buffer swaps.  We can make it faster by moving the last
415   * two rounds into the inner loop for the first round, but it's more readable
416   * this way. */
417
418
419  /* First round, decompose */
420
421  buffer->clear_output ();
422  count = buffer->len;
423  for (buffer->idx = 0; buffer->idx < count;)
424  {
425    unsigned int end;
426    for (end = buffer->idx + 1; end < count; end++)
427      if (buffer->cur().cluster != buffer->info[end].cluster)
428        break;
429
430    if (buffer->idx + 1 == end)
431      decompose_current_character (font, buffer, recompose);
432    else {
433      decompose_multi_char_cluster (font, buffer, end);
434      has_multichar_clusters = true;
435    }
436  }
437  buffer->swap_buffers ();
438
439
440  if (mode != HB_OT_SHAPE_NORMALIZATION_MODE_COMPOSED_FULL && !has_multichar_clusters)
441    return; /* Done! */
442
443
444  /* Second round, reorder (inplace) */
445
446  count = buffer->len;
447  for (unsigned int i = 0; i < count; i++)
448  {
449    if (_hb_glyph_info_get_modified_combining_class (&buffer->info[i]) == 0)
450      continue;
451
452    unsigned int end;
453    for (end = i + 1; end < count; end++)
454      if (_hb_glyph_info_get_modified_combining_class (&buffer->info[end]) == 0)
455        break;
456
457    /* We are going to do a bubble-sort.  Only do this if the
458     * sequence is short.  Doing it on long sequences can result
459     * in an O(n^2) DoS. */
460    if (end - i > 10) {
461      i = end;
462      continue;
463    }
464
465    hb_bubble_sort (buffer->info + i, end - i, compare_combining_class);
466
467    i = end;
468  }
469
470
471  if (!recompose)
472    return;
473
474  /* Third round, recompose */
475
476  /* As noted in the comment earlier, we don't try to combine
477   * ccc=0 chars with their previous Starter. */
478
479  buffer->clear_output ();
480  count = buffer->len;
481  unsigned int starter = 0;
482  buffer->next_glyph ();
483  while (buffer->idx < count)
484  {
485    hb_codepoint_t composed, glyph;
486    if (/* If mode is NOT COMPOSED_FULL (ie. it's COMPOSED_DIACRITICS), we don't try to
487	 * compose a CCC=0 character with it's preceding starter. */
488	(mode == HB_OT_SHAPE_NORMALIZATION_MODE_COMPOSED_FULL ||
489	 _hb_glyph_info_get_modified_combining_class (&buffer->cur()) != 0) &&
490	/* If there's anything between the starter and this char, they should have CCC
491	 * smaller than this character's. */
492	(starter == buffer->out_len - 1 ||
493	 _hb_glyph_info_get_modified_combining_class (&buffer->prev()) < _hb_glyph_info_get_modified_combining_class (&buffer->cur())) &&
494	/* And compose. */
495	compose_func (buffer->unicode,
496		      buffer->out_info[starter].codepoint,
497		      buffer->cur().codepoint,
498		      &composed) &&
499	/* And the font has glyph for the composite. */
500	font->get_glyph (composed, 0, &glyph))
501    {
502      /* Composes. */
503      buffer->next_glyph (); /* Copy to out-buffer. */
504      if (unlikely (buffer->in_error))
505        return;
506      buffer->merge_out_clusters (starter, buffer->out_len);
507      buffer->out_len--; /* Remove the second composable. */
508      buffer->out_info[starter].codepoint = composed; /* Modify starter and carry on. */
509      set_glyph (buffer->out_info[starter], font);
510      _hb_glyph_info_set_unicode_props (&buffer->out_info[starter], buffer->unicode);
511
512      continue;
513    }
514
515    /* Blocked, or doesn't compose. */
516    buffer->next_glyph ();
517
518    if (_hb_glyph_info_get_modified_combining_class (&buffer->prev()) == 0)
519      starter = buffer->out_len - 1;
520  }
521  buffer->swap_buffers ();
522
523}
524