1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 // This file is available under and governed by the GNU General Public
  26 // License version 2 only, as published by the Free Software Foundation.
  27 // However, the following notice accompanied the original version of this
  28 // file:
  29 //
  30 /*
  31  * Copyright © 2011,2012  Google, Inc.
  32  *
  33  *  This is part of HarfBuzz, a text shaping library.
  34  *
  35  * Permission is hereby granted, without written agreement and without
  36  * license or royalty fees, to use, copy, modify, and distribute this
  37  * software and its documentation for any purpose, provided that the
  38  * above copyright notice and the following two paragraphs appear in
  39  * all copies of this software.
  40  *
  41  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
  42  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
  43  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
  44  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  45  * DAMAGE.
  46  *
  47  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
  48  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  50  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
  51  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  52  *
  53  * Google Author(s): Behdad Esfahbod
  54  */
  55 
  56 #include "hb-ot-shape-normalize-private.hh"
  57 #include "hb-ot-shape-complex-private.hh"
  58 #include "hb-ot-shape-private.hh"
  59 
  60 
  61 /*
  62  * HIGHLEVEL DESIGN:
  63  *
  64  * This file exports one main function: _hb_ot_shape_normalize().
  65  *
  66  * This function closely reflects the Unicode Normalization Algorithm,
  67  * yet it's different.
  68  *
  69  * Each shaper specifies whether it prefers decomposed (NFD) or composed (NFC).
  70  * The logic however tries to use whatever the font can support.
  71  *
  72  * In general what happens is that: each grapheme is decomposed in a chain
  73  * of 1:2 decompositions, marks reordered, and then recomposed if desired,
  74  * so far it's like Unicode Normalization.  However, the decomposition and
  75  * recomposition only happens if the font supports the resulting characters.
  76  *
  77  * The goals are:
  78  *
  79  *   - Try to render all canonically equivalent strings similarly.  To really
  80  *     achieve this we have to always do the full decomposition and then
  81  *     selectively recompose from there.  It's kinda too expensive though, so
  82  *     we skip some cases.  For example, if composed is desired, we simply
  83  *     don't touch 1-character clusters that are supported by the font, even
  84  *     though their NFC may be different.
  85  *
  86  *   - When a font has a precomposed character for a sequence but the 'ccmp'
  87  *     feature in the font is not adequate, use the precomposed character
  88  *     which typically has better mark positioning.
  89  *
  90  *   - When a font does not support a combining mark, but supports it precomposed
  91  *     with previous base, use that.  This needs the itemizer to have this
  92  *     knowledge too.  We need to provide assistance to the itemizer.
  93  *
  94  *   - When a font does not support a character but supports its decomposition,
  95  *     well, use the decomposition (preferring the canonical decomposition, but
  96  *     falling back to the compatibility decomposition if necessary).  The
  97  *     compatibility decomposition is really nice to have, for characters like
  98  *     ellipsis, or various-sized space characters.
  99  *
 100  *   - The complex shapers can customize the compose and decompose functions to
 101  *     offload some of their requirements to the normalizer.  For example, the
 102  *     Indic shaper may want to disallow recomposing of two matras.
 103  *
 104  *   - We try compatibility decomposition if decomposing through canonical
 105  *     decomposition alone failed to find a sequence that the font supports.
 106  *     We don't try compatibility decomposition recursively during the canonical
 107  *     decomposition phase.  This has minimal impact.  There are only a handful
 108  *     of Greek letter that have canonical decompositions that include characters
 109  *     with compatibility decomposition.  Those can be found using this command:
 110  *
 111  *     egrep  "`echo -n ';('; grep ';<' UnicodeData.txt | cut -d';' -f1 | tr '\n' '|'; echo ') '`" UnicodeData.txt
 112  */
 113 
 114 static bool
 115 decompose_unicode (const hb_ot_shape_normalize_context_t *c,
 116                    hb_codepoint_t  ab,
 117                    hb_codepoint_t *a,
 118                    hb_codepoint_t *b)
 119 {
 120   return c->unicode->decompose (ab, a, b);
 121 }
 122 
 123 static bool
 124 compose_unicode (const hb_ot_shape_normalize_context_t *c,
 125                  hb_codepoint_t  a,
 126                  hb_codepoint_t  b,
 127                  hb_codepoint_t *ab)
 128 {
 129   return c->unicode->compose (a, b, ab);
 130 }
 131 
 132 static inline void
 133 set_glyph (hb_glyph_info_t &info, hb_font_t *font)
 134 {
 135   font->get_glyph (info.codepoint, 0, &info.glyph_index());
 136 }
 137 
 138 static inline void
 139 output_char (hb_buffer_t *buffer, hb_codepoint_t unichar, hb_codepoint_t glyph)
 140 {
 141   buffer->cur().glyph_index() = glyph;
 142   buffer->output_glyph (unichar);
 143   _hb_glyph_info_set_unicode_props (&buffer->prev(), buffer->unicode);
 144 }
 145 
 146 static inline void
 147 next_char (hb_buffer_t *buffer, hb_codepoint_t glyph)
 148 {
 149   buffer->cur().glyph_index() = glyph;
 150   buffer->next_glyph ();
 151 }
 152 
 153 static inline void
 154 skip_char (hb_buffer_t *buffer)
 155 {
 156   buffer->skip_glyph ();
 157 }
 158 
 159 /* Returns 0 if didn't decompose, number of resulting characters otherwise. */
 160 static inline unsigned int
 161 decompose (const hb_ot_shape_normalize_context_t *c, bool shortest, hb_codepoint_t ab)
 162 {
 163   hb_codepoint_t a, b, a_glyph, b_glyph;
 164   hb_buffer_t * const buffer = c->buffer;
 165   hb_font_t * const font = c->font;
 166 
 167   if (!c->decompose (c, ab, &a, &b) ||
 168       (b && !font->get_glyph (b, 0, &b_glyph)))
 169     return 0;
 170 
 171   bool has_a = font->get_glyph (a, 0, &a_glyph);
 172   if (shortest && has_a) {
 173     /* Output a and b */
 174     output_char (buffer, a, a_glyph);
 175     if (likely (b)) {
 176       output_char (buffer, b, b_glyph);
 177       return 2;
 178     }
 179     return 1;
 180   }
 181 
 182   unsigned int ret;
 183   if ((ret = decompose (c, shortest, a))) {
 184     if (b) {
 185       output_char (buffer, b, b_glyph);
 186       return ret + 1;
 187     }
 188     return ret;
 189   }
 190 
 191   if (has_a) {
 192     output_char (buffer, a, a_glyph);
 193     if (likely (b)) {
 194       output_char (buffer, b, b_glyph);
 195       return 2;
 196     }
 197     return 1;
 198   }
 199 
 200   return 0;
 201 }
 202 
 203 /* Returns 0 if didn't decompose, number of resulting characters otherwise. */
 204 static inline unsigned int
 205 decompose_compatibility (const hb_ot_shape_normalize_context_t *c, hb_codepoint_t u)
 206 {
 207   unsigned int len, i;
 208   hb_codepoint_t decomposed[HB_UNICODE_MAX_DECOMPOSITION_LEN];
 209   hb_codepoint_t glyphs[HB_UNICODE_MAX_DECOMPOSITION_LEN];
 210 
 211   len = c->buffer->unicode->decompose_compatibility (u, decomposed);
 212   if (!len)
 213     return 0;
 214 
 215   for (i = 0; i < len; i++)
 216     if (!c->font->get_glyph (decomposed[i], 0, &glyphs[i]))
 217       return 0;
 218 
 219   for (i = 0; i < len; i++)
 220     output_char (c->buffer, decomposed[i], glyphs[i]);
 221 
 222   return len;
 223 }
 224 
 225 static inline void
 226 decompose_current_character (const hb_ot_shape_normalize_context_t *c, bool shortest)
 227 {
 228   hb_buffer_t * const buffer = c->buffer;
 229   hb_codepoint_t u = buffer->cur().codepoint;
 230   hb_codepoint_t glyph;
 231 
 232   /* Kind of a cute waterfall here... */
 233   if (shortest && c->font->get_glyph (u, 0, &glyph))
 234     next_char (buffer, glyph);
 235   else if (decompose (c, shortest, u))
 236     skip_char (buffer);
 237   else if (!shortest && c->font->get_glyph (u, 0, &glyph))
 238     next_char (buffer, glyph);
 239   else if (decompose_compatibility (c, u))
 240     skip_char (buffer);
 241   else
 242     next_char (buffer, glyph); /* glyph is initialized in earlier branches. */
 243 }
 244 
 245 static inline void
 246 handle_variation_selector_cluster (const hb_ot_shape_normalize_context_t *c, unsigned int end, bool short_circuit)
 247 {
 248   /* TODO Currently if there's a variation-selector we give-up, it's just too hard. */
 249   hb_buffer_t * const buffer = c->buffer;
 250   hb_font_t * const font = c->font;
 251   for (; buffer->idx < end - 1;) {
 252     if (unlikely (buffer->unicode->is_variation_selector (buffer->cur(+1).codepoint))) {
 253       /* The next two lines are some ugly lines... But work. */
 254       if (font->get_glyph (buffer->cur().codepoint, buffer->cur(+1).codepoint, &buffer->cur().glyph_index()))
 255       {
 256         buffer->replace_glyphs (2, 1, &buffer->cur().codepoint);
 257       }
 258       else
 259       {
 260         /* Just pass on the two characters separately, let GSUB do its magic. */
 261         set_glyph (buffer->cur(), font);
 262         buffer->next_glyph ();
 263         set_glyph (buffer->cur(), font);
 264         buffer->next_glyph ();
 265       }
 266       /* Skip any further variation selectors. */
 267       while (buffer->idx < end && unlikely (buffer->unicode->is_variation_selector (buffer->cur().codepoint)))
 268       {
 269         set_glyph (buffer->cur(), font);
 270         buffer->next_glyph ();
 271       }
 272     } else {
 273       set_glyph (buffer->cur(), font);
 274       buffer->next_glyph ();
 275     }
 276   }
 277   if (likely (buffer->idx < end)) {
 278     set_glyph (buffer->cur(), font);
 279     buffer->next_glyph ();
 280   }
 281 }
 282 
 283 static inline void
 284 decompose_multi_char_cluster (const hb_ot_shape_normalize_context_t *c, unsigned int end, bool short_circuit)
 285 {
 286   hb_buffer_t * const buffer = c->buffer;
 287   for (unsigned int i = buffer->idx; i < end; i++)
 288     if (unlikely (buffer->unicode->is_variation_selector (buffer->info[i].codepoint))) {
 289       handle_variation_selector_cluster (c, end, short_circuit);
 290       return;
 291     }
 292 
 293   while (buffer->idx < end)
 294     decompose_current_character (c, short_circuit);
 295 }
 296 
 297 static inline void
 298 decompose_cluster (const hb_ot_shape_normalize_context_t *c, unsigned int end, bool might_short_circuit, bool always_short_circuit)
 299 {
 300   if (likely (c->buffer->idx + 1 == end))
 301     decompose_current_character (c, might_short_circuit);
 302   else
 303     decompose_multi_char_cluster (c, end, always_short_circuit);
 304 }
 305 
 306 
 307 static int
 308 compare_combining_class (const hb_glyph_info_t *pa, const hb_glyph_info_t *pb)
 309 {
 310   unsigned int a = _hb_glyph_info_get_modified_combining_class (pa);
 311   unsigned int b = _hb_glyph_info_get_modified_combining_class (pb);
 312 
 313   return a < b ? -1 : a == b ? 0 : +1;
 314 }
 315 
 316 
 317 void
 318 _hb_ot_shape_normalize (const hb_ot_shape_plan_t *plan,
 319                         hb_buffer_t *buffer,
 320                         hb_font_t *font)
 321 {
 322   if (unlikely (!buffer->len)) return;
 323 
 324   _hb_buffer_assert_unicode_vars (buffer);
 325 
 326   hb_ot_shape_normalization_mode_t mode = plan->shaper->normalization_preference;
 327   const hb_ot_shape_normalize_context_t c = {
 328     plan,
 329     buffer,
 330     font,
 331     buffer->unicode,
 332     plan->shaper->decompose ? plan->shaper->decompose : decompose_unicode,
 333     plan->shaper->compose   ? plan->shaper->compose   : compose_unicode
 334   };
 335 
 336   bool always_short_circuit = mode == HB_OT_SHAPE_NORMALIZATION_MODE_NONE;
 337   bool might_short_circuit = always_short_circuit ||
 338                              (mode != HB_OT_SHAPE_NORMALIZATION_MODE_DECOMPOSED &&
 339                               mode != HB_OT_SHAPE_NORMALIZATION_MODE_COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT);
 340   unsigned int count;
 341 
 342   /* We do a fairly straightforward yet custom normalization process in three
 343    * separate rounds: decompose, reorder, recompose (if desired).  Currently
 344    * this makes two buffer swaps.  We can make it faster by moving the last
 345    * two rounds into the inner loop for the first round, but it's more readable
 346    * this way. */
 347 
 348 
 349   /* First round, decompose */
 350 
 351   buffer->clear_output ();
 352   count = buffer->len;
 353   for (buffer->idx = 0; buffer->idx < count;)
 354   {
 355     unsigned int end;
 356     for (end = buffer->idx + 1; end < count; end++)
 357       if (likely (!HB_UNICODE_GENERAL_CATEGORY_IS_MARK (_hb_glyph_info_get_general_category (&buffer->info[end]))))
 358         break;
 359 
 360     decompose_cluster (&c, end, might_short_circuit, always_short_circuit);
 361   }
 362   buffer->swap_buffers ();
 363 
 364 
 365   /* Second round, reorder (inplace) */
 366 
 367   count = buffer->len;
 368   for (unsigned int i = 0; i < count; i++)
 369   {
 370     if (_hb_glyph_info_get_modified_combining_class (&buffer->info[i]) == 0)
 371       continue;
 372 
 373     unsigned int end;
 374     for (end = i + 1; end < count; end++)
 375       if (_hb_glyph_info_get_modified_combining_class (&buffer->info[end]) == 0)
 376         break;
 377 
 378     /* We are going to do a O(n^2).  Only do this if the sequence is short. */
 379     if (end - i > 10) {
 380       i = end;
 381       continue;
 382     }
 383 
 384     buffer->sort (i, end, compare_combining_class);
 385 
 386     i = end;
 387   }
 388 
 389 
 390   if (mode == HB_OT_SHAPE_NORMALIZATION_MODE_NONE ||
 391       mode == HB_OT_SHAPE_NORMALIZATION_MODE_DECOMPOSED)
 392     return;
 393 
 394   /* Third round, recompose */
 395 
 396   /* As noted in the comment earlier, we don't try to combine
 397    * ccc=0 chars with their previous Starter. */
 398 
 399   buffer->clear_output ();
 400   count = buffer->len;
 401   unsigned int starter = 0;
 402   buffer->next_glyph ();
 403   while (buffer->idx < count)
 404   {
 405     hb_codepoint_t composed, glyph;
 406     if (/* We don't try to compose a non-mark character with it's preceding starter.
 407          * This is both an optimization to avoid trying to compose every two neighboring
 408          * glyphs in most scripts AND a desired feature for Hangul.  Apparently Hangul
 409          * fonts are not designed to mix-and-match pre-composed syllables and Jamo. */
 410         HB_UNICODE_GENERAL_CATEGORY_IS_MARK (_hb_glyph_info_get_general_category (&buffer->cur())) &&
 411         /* If there's anything between the starter and this char, they should have CCC
 412          * smaller than this character's. */
 413         (starter == buffer->out_len - 1 ||
 414          _hb_glyph_info_get_modified_combining_class (&buffer->prev()) < _hb_glyph_info_get_modified_combining_class (&buffer->cur())) &&
 415         /* And compose. */
 416         c.compose (&c,
 417                    buffer->out_info[starter].codepoint,
 418                    buffer->cur().codepoint,
 419                    &composed) &&
 420         /* And the font has glyph for the composite. */
 421         font->get_glyph (composed, 0, &glyph))
 422     {
 423       /* Composes. */
 424       buffer->next_glyph (); /* Copy to out-buffer. */
 425       if (unlikely (buffer->in_error))
 426         return;
 427       buffer->merge_out_clusters (starter, buffer->out_len);
 428       buffer->out_len--; /* Remove the second composable. */
 429       /* Modify starter and carry on. */
 430       buffer->out_info[starter].codepoint = composed;
 431       buffer->out_info[starter].glyph_index() = glyph;
 432       _hb_glyph_info_set_unicode_props (&buffer->out_info[starter], buffer->unicode);
 433 
 434       continue;
 435     }
 436 
 437     /* Blocked, or doesn't compose. */
 438     buffer->next_glyph ();
 439 
 440     if (_hb_glyph_info_get_modified_combining_class (&buffer->prev()) == 0)
 441       starter = buffer->out_len - 1;
 442   }
 443   buffer->swap_buffers ();
 444 
 445 }