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-complex-indic-private.hh"
  57 #include "hb-ot-layout-private.hh"
  58 
  59 /* buffer var allocations */
  60 #define indic_category() complex_var_u8_0() /* indic_category_t */
  61 #define indic_position() complex_var_u8_1() /* indic_position_t */
  62 
  63 
  64 /*
  65  * Indic shaper.
  66  */
  67 
  68 
  69 #define IN_HALF_BLOCK(u, Base) (((u) & ~0x7Fu) == (Base))
  70 
  71 #define IS_DEVA(u) (IN_HALF_BLOCK (u, 0x0900u))
  72 #define IS_BENG(u) (IN_HALF_BLOCK (u, 0x0980u))
  73 #define IS_GURU(u) (IN_HALF_BLOCK (u, 0x0A00u))
  74 #define IS_GUJR(u) (IN_HALF_BLOCK (u, 0x0A80u))
  75 #define IS_ORYA(u) (IN_HALF_BLOCK (u, 0x0B00u))
  76 #define IS_TAML(u) (IN_HALF_BLOCK (u, 0x0B80u))
  77 #define IS_TELU(u) (IN_HALF_BLOCK (u, 0x0C00u))
  78 #define IS_KNDA(u) (IN_HALF_BLOCK (u, 0x0C80u))
  79 #define IS_MLYM(u) (IN_HALF_BLOCK (u, 0x0D00u))
  80 #define IS_SINH(u) (IN_HALF_BLOCK (u, 0x0D80u))
  81 #define IS_KHMR(u) (IN_HALF_BLOCK (u, 0x1780u))
  82 
  83 
  84 #define MATRA_POS_LEFT(u)       POS_PRE_M
  85 #define MATRA_POS_RIGHT(u)      ( \
  86                                   IS_DEVA(u) ? POS_AFTER_SUB  : \
  87                                   IS_BENG(u) ? POS_AFTER_POST : \
  88                                   IS_GURU(u) ? POS_AFTER_POST : \
  89                                   IS_GUJR(u) ? POS_AFTER_POST : \
  90                                   IS_ORYA(u) ? POS_AFTER_POST : \
  91                                   IS_TAML(u) ? POS_AFTER_POST : \
  92                                   IS_TELU(u) ? (u <= 0x0C42u ? POS_BEFORE_SUB : POS_AFTER_SUB) : \
  93                                   IS_KNDA(u) ? (u < 0x0CC3u || u > 0xCD6u ? POS_BEFORE_SUB : POS_AFTER_SUB) : \
  94                                   IS_MLYM(u) ? POS_AFTER_POST : \
  95                                   IS_SINH(u) ? POS_AFTER_SUB  : \
  96                                   IS_KHMR(u) ? POS_AFTER_POST : \
  97                                   /*default*/  POS_AFTER_SUB    \
  98                                 )
  99 #define MATRA_POS_TOP(u)        ( /* BENG and MLYM don't have top matras. */ \
 100                                   IS_DEVA(u) ? POS_AFTER_SUB  : \
 101                                   IS_GURU(u) ? POS_AFTER_POST : /* Deviate from spec */ \
 102                                   IS_GUJR(u) ? POS_AFTER_SUB  : \
 103                                   IS_ORYA(u) ? POS_AFTER_MAIN : \
 104                                   IS_TAML(u) ? POS_AFTER_SUB  : \
 105                                   IS_TELU(u) ? POS_BEFORE_SUB : \
 106                                   IS_KNDA(u) ? POS_BEFORE_SUB : \
 107                                   IS_SINH(u) ? POS_AFTER_SUB  : \
 108                                   IS_KHMR(u) ? POS_AFTER_POST : \
 109                                   /*default*/  POS_AFTER_SUB    \
 110                                 )
 111 #define MATRA_POS_BOTTOM(u)     ( \
 112                                   IS_DEVA(u) ? POS_AFTER_SUB  : \
 113                                   IS_BENG(u) ? POS_AFTER_SUB  : \
 114                                   IS_GURU(u) ? POS_AFTER_POST : \
 115                                   IS_GUJR(u) ? POS_AFTER_POST : \
 116                                   IS_ORYA(u) ? POS_AFTER_SUB  : \
 117                                   IS_TAML(u) ? POS_AFTER_POST : \
 118                                   IS_TELU(u) ? POS_BEFORE_SUB : \
 119                                   IS_KNDA(u) ? POS_BEFORE_SUB : \
 120                                   IS_MLYM(u) ? POS_AFTER_POST : \
 121                                   IS_SINH(u) ? POS_AFTER_SUB  : \
 122                                   IS_KHMR(u) ? POS_AFTER_POST : \
 123                                   /*default*/  POS_AFTER_SUB    \
 124                                 )
 125 
 126 static inline indic_position_t
 127 matra_position (hb_codepoint_t u, indic_position_t side)
 128 {
 129   switch ((int) side)
 130   {
 131     case POS_PRE_C:     return MATRA_POS_LEFT (u);
 132     case POS_POST_C:    return MATRA_POS_RIGHT (u);
 133     case POS_ABOVE_C:   return MATRA_POS_TOP (u);
 134     case POS_BELOW_C:   return MATRA_POS_BOTTOM (u);
 135   };
 136   return side;
 137 }
 138 
 139 /* XXX
 140  * This is a hack for now.  We should move this data into the main Indic table.
 141  * Or completely remove it and just check in the tables.
 142  */
 143 static const hb_codepoint_t ra_chars[] = {
 144   0x0930u, /* Devanagari */
 145   0x09B0u, /* Bengali */
 146   0x09F0u, /* Bengali */
 147   0x0A30u, /* Gurmukhi */       /* No Reph */
 148   0x0AB0u, /* Gujarati */
 149   0x0B30u, /* Oriya */
 150   0x0BB0u, /* Tamil */          /* No Reph */
 151   0x0C30u, /* Telugu */         /* Reph formed only with ZWJ */
 152   0x0CB0u, /* Kannada */
 153   0x0D30u, /* Malayalam */      /* No Reph, Logical Repha */
 154 
 155   0x0DBBu, /* Sinhala */                /* Reph formed only with ZWJ */
 156 
 157   0x179Au, /* Khmer */          /* No Reph, Visual Repha */
 158 };
 159 
 160 static inline bool
 161 is_ra (hb_codepoint_t u)
 162 {
 163   for (unsigned int i = 0; i < ARRAY_LENGTH (ra_chars); i++)
 164     if (u == ra_chars[i])
 165       return true;
 166   return false;
 167 }
 168 
 169 static inline bool
 170 is_one_of (const hb_glyph_info_t &info, unsigned int flags)
 171 {
 172   /* If it ligated, all bets are off. */
 173   if (_hb_glyph_info_ligated (&info)) return false;
 174   return !!(FLAG_SAFE (info.indic_category()) & flags);
 175 }
 176 
 177 static inline bool
 178 is_joiner (const hb_glyph_info_t &info)
 179 {
 180   return is_one_of (info, JOINER_FLAGS);
 181 }
 182 
 183 static inline bool
 184 is_consonant (const hb_glyph_info_t &info)
 185 {
 186   return is_one_of (info, CONSONANT_FLAGS);
 187 }
 188 
 189 static inline bool
 190 is_halant_or_coeng (const hb_glyph_info_t &info)
 191 {
 192   return is_one_of (info, HALANT_OR_COENG_FLAGS);
 193 }
 194 
 195 static inline void
 196 set_indic_properties (hb_glyph_info_t &info)
 197 {
 198   hb_codepoint_t u = info.codepoint;
 199   unsigned int type = hb_indic_get_categories (u);
 200   indic_category_t cat = (indic_category_t) (type & 0x7Fu);
 201   indic_position_t pos = (indic_position_t) (type >> 8);
 202 
 203 
 204   /*
 205    * Re-assign category
 206    */
 207 
 208 
 209   /* The spec says U+0952 is OT_A.  However, testing shows that Uniscribe
 210    * treats a whole bunch of characters similarly.
 211    * TESTS: For example, for U+0951:
 212    * U+092E,U+0947,U+0952
 213    * U+092E,U+0952,U+0947
 214    * U+092E,U+0947,U+0951
 215    * U+092E,U+0951,U+0947
 216    * U+092E,U+0951,U+0952
 217    * U+092E,U+0952,U+0951
 218    */
 219   if (unlikely (hb_in_ranges (u, 0x0951u, 0x0952u,
 220                                  0x1CD0u, 0x1CD2u,
 221                                  0x1CD4u, 0x1CE1u) ||
 222                             u == 0x1CF4u))
 223     cat = OT_A;
 224   /* The following act more like the Bindus. */
 225   else if (unlikely (hb_in_range (u, 0x0953u, 0x0954u)))
 226     cat = OT_SM;
 227   /* The following act like consonants. */
 228   else if (unlikely (hb_in_ranges (u, 0x0A72u, 0x0A73u,
 229                                       0x1CF5u, 0x1CF6u)))
 230     cat = OT_C;
 231   /* TODO: The following should only be allowed after a Visarga.
 232    * For now, just treat them like regular tone marks. */
 233   else if (unlikely (hb_in_range (u, 0x1CE2u, 0x1CE8u)))
 234     cat = OT_A;
 235   /* TODO: The following should only be allowed after some of
 236    * the nasalization marks, maybe only for U+1CE9..U+1CF1.
 237    * For now, just treat them like tone marks. */
 238   else if (unlikely (u == 0x1CEDu))
 239     cat = OT_A;
 240   /* The following take marks in standalone clusters, similar to Avagraha. */
 241   else if (unlikely (hb_in_ranges (u, 0xA8F2u, 0xA8F7u,
 242                                       0x1CE9u, 0x1CECu,
 243                                       0x1CEEu, 0x1CF1u)))
 244   {
 245     cat = OT_Symbol;
 246     ASSERT_STATIC ((int) INDIC_SYLLABIC_CATEGORY_AVAGRAHA == OT_Symbol);
 247   }
 248   else if (unlikely (hb_in_range (u, 0x17CDu, 0x17D1u) ||
 249                      u == 0x17CBu || u == 0x17D3u || u == 0x17DDu)) /* Khmer Various signs */
 250   {
 251     /* These are like Top Matras. */
 252     cat = OT_M;
 253     pos = POS_ABOVE_C;
 254   }
 255   else if (unlikely (u == 0x17C6u)) cat = OT_N; /* Khmer Bindu doesn't like to be repositioned. */
 256   else if (unlikely (u == 0x17D2u)) cat = OT_Coeng; /* Khmer coeng */
 257   else if (unlikely (hb_in_range (u, 0x2010u, 0x2011u)))
 258                                     cat = OT_PLACEHOLDER;
 259   else if (unlikely (u == 0x25CCu)) cat = OT_DOTTEDCIRCLE;
 260   else if (unlikely (u == 0xA982u)) cat = OT_SM; /* Javanese repha. */
 261   else if (unlikely (u == 0xA9BEu)) cat = OT_CM2; /* Javanese medial ya. */
 262   else if (unlikely (u == 0xA9BDu)) { cat = OT_M; pos = POS_POST_C; } /* Javanese vocalic r. */
 263 
 264 
 265   /*
 266    * Re-assign position.
 267    */
 268 
 269   if ((FLAG_SAFE (cat) & CONSONANT_FLAGS))
 270   {
 271     pos = POS_BASE_C;
 272     if (is_ra (u))
 273       cat = OT_Ra;
 274   }
 275   else if (cat == OT_M)
 276   {
 277     pos = matra_position (u, pos);
 278   }
 279   else if ((FLAG_SAFE (cat) & (FLAG (OT_SM) | FLAG (OT_VD) | FLAG (OT_A) | FLAG (OT_Symbol))))
 280   {
 281     pos = POS_SMVD;
 282   }
 283 
 284   if (unlikely (u == 0x0B01u)) pos = POS_BEFORE_SUB; /* Oriya Bindu is BeforeSub in the spec. */
 285 
 286 
 287 
 288   info.indic_category() = cat;
 289   info.indic_position() = pos;
 290 }
 291 
 292 /*
 293  * Things above this line should ideally be moved to the Indic table itself.
 294  */
 295 
 296 
 297 /*
 298  * Indic configurations.  Note that we do not want to keep every single script-specific
 299  * behavior in these tables necessarily.  This should mainly be used for per-script
 300  * properties that are cheaper keeping here, than in the code.  Ie. if, say, one and
 301  * only one script has an exception, that one script can be if'ed directly in the code,
 302  * instead of adding a new flag in these structs.
 303  */
 304 
 305 enum base_position_t {
 306   BASE_POS_FIRST,
 307   BASE_POS_LAST_SINHALA,
 308   BASE_POS_LAST
 309 };
 310 enum reph_position_t {
 311   REPH_POS_AFTER_MAIN  = POS_AFTER_MAIN,
 312   REPH_POS_BEFORE_SUB  = POS_BEFORE_SUB,
 313   REPH_POS_AFTER_SUB   = POS_AFTER_SUB,
 314   REPH_POS_BEFORE_POST = POS_BEFORE_POST,
 315   REPH_POS_AFTER_POST  = POS_AFTER_POST,
 316   REPH_POS_DONT_CARE   = POS_RA_TO_BECOME_REPH
 317 };
 318 enum reph_mode_t {
 319   REPH_MODE_IMPLICIT,  /* Reph formed out of initial Ra,H sequence. */
 320   REPH_MODE_EXPLICIT,  /* Reph formed out of initial Ra,H,ZWJ sequence. */
 321   REPH_MODE_VIS_REPHA, /* Encoded Repha character, no reordering needed. */
 322   REPH_MODE_LOG_REPHA  /* Encoded Repha character, needs reordering. */
 323 };
 324 enum blwf_mode_t {
 325   BLWF_MODE_PRE_AND_POST, /* Below-forms feature applied to pre-base and post-base. */
 326   BLWF_MODE_POST_ONLY     /* Below-forms feature applied to post-base only. */
 327 };
 328 enum pref_len_t {
 329   PREF_LEN_1 = 1,
 330   PREF_LEN_2 = 2,
 331   PREF_LEN_DONT_CARE = PREF_LEN_2
 332 };
 333 struct indic_config_t
 334 {
 335   hb_script_t     script;
 336   bool            has_old_spec;
 337   hb_codepoint_t  virama;
 338   base_position_t base_pos;
 339   reph_position_t reph_pos;
 340   reph_mode_t     reph_mode;
 341   blwf_mode_t     blwf_mode;
 342   pref_len_t      pref_len;
 343 };
 344 
 345 static const indic_config_t indic_configs[] =
 346 {
 347   /* Default.  Should be first. */
 348   {HB_SCRIPT_INVALID,   false,      0,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_1},
 349   {HB_SCRIPT_DEVANAGARI,true, 0x094Du,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 350   {HB_SCRIPT_BENGALI,   true, 0x09CDu,BASE_POS_LAST, REPH_POS_AFTER_SUB,  REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 351   {HB_SCRIPT_GURMUKHI,  true, 0x0A4Du,BASE_POS_LAST, REPH_POS_BEFORE_SUB, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 352   {HB_SCRIPT_GUJARATI,  true, 0x0ACDu,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 353   {HB_SCRIPT_ORIYA,     true, 0x0B4Du,BASE_POS_LAST, REPH_POS_AFTER_MAIN, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 354   {HB_SCRIPT_TAMIL,     true, 0x0BCDu,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
 355   {HB_SCRIPT_TELUGU,    true, 0x0C4Du,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_EXPLICIT, BLWF_MODE_POST_ONLY,    PREF_LEN_2},
 356   {HB_SCRIPT_KANNADA,   true, 0x0CCDu,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_IMPLICIT, BLWF_MODE_POST_ONLY,    PREF_LEN_2},
 357   {HB_SCRIPT_MALAYALAM, true, 0x0D4Du,BASE_POS_LAST, REPH_POS_AFTER_MAIN, REPH_MODE_LOG_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
 358   {HB_SCRIPT_SINHALA,   false,0x0DCAu,BASE_POS_LAST_SINHALA,
 359                                                      REPH_POS_AFTER_MAIN, REPH_MODE_EXPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
 360   {HB_SCRIPT_KHMER,     false,0x17D2u,BASE_POS_FIRST,REPH_POS_DONT_CARE,  REPH_MODE_VIS_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
 361   {HB_SCRIPT_JAVANESE,  false,0xA9C0u,BASE_POS_FIRST,REPH_POS_DONT_CARE,  REPH_MODE_VIS_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_1},
 362 };
 363 
 364 
 365 
 366 /*
 367  * Indic shaper.
 368  */
 369 
 370 struct feature_list_t {
 371   hb_tag_t tag;
 372   hb_ot_map_feature_flags_t flags;
 373 };
 374 
 375 static const feature_list_t
 376 indic_features[] =
 377 {
 378   /*
 379    * Basic features.
 380    * These features are applied in order, one at a time, after initial_reordering.
 381    */
 382   {HB_TAG('n','u','k','t'), F_GLOBAL},
 383   {HB_TAG('a','k','h','n'), F_GLOBAL},
 384   {HB_TAG('r','p','h','f'), F_NONE},
 385   {HB_TAG('r','k','r','f'), F_GLOBAL},
 386   {HB_TAG('p','r','e','f'), F_NONE},
 387   {HB_TAG('b','l','w','f'), F_NONE},
 388   {HB_TAG('a','b','v','f'), F_NONE},
 389   {HB_TAG('h','a','l','f'), F_NONE},
 390   {HB_TAG('p','s','t','f'), F_NONE},
 391   {HB_TAG('v','a','t','u'), F_GLOBAL},
 392   {HB_TAG('c','j','c','t'), F_GLOBAL},
 393   {HB_TAG('c','f','a','r'), F_NONE},
 394   /*
 395    * Other features.
 396    * These features are applied all at once, after final_reordering.
 397    * Default Bengali font in Windows for example has intermixed
 398    * lookups for init,pres,abvs,blws features.
 399    */
 400   {HB_TAG('i','n','i','t'), F_NONE},
 401   {HB_TAG('p','r','e','s'), F_GLOBAL},
 402   {HB_TAG('a','b','v','s'), F_GLOBAL},
 403   {HB_TAG('b','l','w','s'), F_GLOBAL},
 404   {HB_TAG('p','s','t','s'), F_GLOBAL},
 405   {HB_TAG('h','a','l','n'), F_GLOBAL},
 406   /* Positioning features, though we don't care about the types. */
 407   {HB_TAG('d','i','s','t'), F_GLOBAL},
 408   {HB_TAG('a','b','v','m'), F_GLOBAL},
 409   {HB_TAG('b','l','w','m'), F_GLOBAL},
 410 };
 411 
 412 /*
 413  * Must be in the same order as the indic_features array.
 414  */
 415 enum {
 416   _NUKT,
 417   _AKHN,
 418   RPHF,
 419   _RKRF,
 420   PREF,
 421   BLWF,
 422   ABVF,
 423   HALF,
 424   PSTF,
 425   _VATU,
 426   _CJCT,
 427   CFAR,
 428 
 429   INIT,
 430   _PRES,
 431   _ABVS,
 432   _BLWS,
 433   _PSTS,
 434   _HALN,
 435   _DIST,
 436   _ABVM,
 437   _BLWM,
 438 
 439   INDIC_NUM_FEATURES,
 440   INDIC_BASIC_FEATURES = INIT /* Don't forget to update this! */
 441 };
 442 
 443 static void
 444 setup_syllables (const hb_ot_shape_plan_t *plan,
 445                  hb_font_t *font,
 446                  hb_buffer_t *buffer);
 447 static void
 448 initial_reordering (const hb_ot_shape_plan_t *plan,
 449                     hb_font_t *font,
 450                     hb_buffer_t *buffer);
 451 static void
 452 final_reordering (const hb_ot_shape_plan_t *plan,
 453                   hb_font_t *font,
 454                   hb_buffer_t *buffer);
 455 static void
 456 clear_syllables (const hb_ot_shape_plan_t *plan,
 457                  hb_font_t *font,
 458                  hb_buffer_t *buffer);
 459 
 460 static void
 461 collect_features_indic (hb_ot_shape_planner_t *plan)
 462 {
 463   hb_ot_map_builder_t *map = &plan->map;
 464 
 465   /* Do this before any lookups have been applied. */
 466   map->add_gsub_pause (setup_syllables);
 467 
 468   map->add_global_bool_feature (HB_TAG('l','o','c','l'));
 469   /* The Indic specs do not require ccmp, but we apply it here since if
 470    * there is a use of it, it's typically at the beginning. */
 471   map->add_global_bool_feature (HB_TAG('c','c','m','p'));
 472 
 473 
 474   unsigned int i = 0;
 475   map->add_gsub_pause (initial_reordering);
 476   for (; i < INDIC_BASIC_FEATURES; i++) {
 477     map->add_feature (indic_features[i].tag, 1, indic_features[i].flags | F_MANUAL_ZWJ);
 478     map->add_gsub_pause (NULL);
 479   }
 480   map->add_gsub_pause (final_reordering);
 481   for (; i < INDIC_NUM_FEATURES; i++) {
 482     map->add_feature (indic_features[i].tag, 1, indic_features[i].flags | F_MANUAL_ZWJ);
 483   }
 484 
 485   map->add_global_bool_feature (HB_TAG('c','a','l','t'));
 486   map->add_global_bool_feature (HB_TAG('c','l','i','g'));
 487 
 488   map->add_gsub_pause (clear_syllables);
 489 }
 490 
 491 static void
 492 override_features_indic (hb_ot_shape_planner_t *plan)
 493 {
 494   /* Uniscribe does not apply 'kern' in Khmer. */
 495   if (hb_options ().uniscribe_bug_compatible)
 496   {
 497     switch ((hb_tag_t) plan->props.script)
 498     {
 499       case HB_SCRIPT_KHMER:
 500         plan->map.add_feature (HB_TAG('k','e','r','n'), 0, F_GLOBAL);
 501         break;
 502     }
 503   }
 504 
 505   plan->map.add_feature (HB_TAG('l','i','g','a'), 0, F_GLOBAL);
 506 }
 507 
 508 
 509 struct would_substitute_feature_t
 510 {
 511   inline void init (const hb_ot_map_t *map, hb_tag_t feature_tag, bool zero_context_)
 512   {
 513     zero_context = zero_context_;
 514     map->get_stage_lookups (0/*GSUB*/,
 515                             map->get_feature_stage (0/*GSUB*/, feature_tag),
 516                             &lookups, &count);
 517   }
 518 
 519   inline bool would_substitute (const hb_codepoint_t *glyphs,
 520                                 unsigned int          glyphs_count,
 521                                 hb_face_t            *face) const
 522   {
 523     for (unsigned int i = 0; i < count; i++)
 524       if (hb_ot_layout_lookup_would_substitute_fast (face, lookups[i].index, glyphs, glyphs_count, zero_context))
 525         return true;
 526     return false;
 527   }
 528 
 529   private:
 530   const hb_ot_map_t::lookup_map_t *lookups;
 531   unsigned int count;
 532   bool zero_context;
 533 };
 534 
 535 struct indic_shape_plan_t
 536 {
 537   ASSERT_POD ();
 538 
 539   inline bool get_virama_glyph (hb_font_t *font, hb_codepoint_t *pglyph) const
 540   {
 541     hb_codepoint_t glyph = virama_glyph;
 542     if (unlikely (virama_glyph == (hb_codepoint_t) -1))
 543     {
 544       if (!config->virama || !font->get_glyph (config->virama, 0, &glyph))
 545         glyph = 0;
 546       /* Technically speaking, the spec says we should apply 'locl' to virama too.
 547        * Maybe one day... */
 548 
 549       /* Our get_glyph() function needs a font, so we can't get the virama glyph
 550        * during shape planning...  Instead, overwrite it here.  It's safe.  Don't worry! */
 551       (const_cast<indic_shape_plan_t *> (this))->virama_glyph = glyph;
 552     }
 553 
 554     *pglyph = glyph;
 555     return glyph != 0;
 556   }
 557 
 558   const indic_config_t *config;
 559 
 560   bool is_old_spec;
 561   hb_codepoint_t virama_glyph;
 562 
 563   would_substitute_feature_t rphf;
 564   would_substitute_feature_t pref;
 565   would_substitute_feature_t blwf;
 566   would_substitute_feature_t pstf;
 567 
 568   hb_mask_t mask_array[INDIC_NUM_FEATURES];
 569 };
 570 
 571 static void *
 572 data_create_indic (const hb_ot_shape_plan_t *plan)
 573 {
 574   indic_shape_plan_t *indic_plan = (indic_shape_plan_t *) calloc (1, sizeof (indic_shape_plan_t));
 575   if (unlikely (!indic_plan))
 576     return NULL;
 577 
 578   indic_plan->config = &indic_configs[0];
 579   for (unsigned int i = 1; i < ARRAY_LENGTH (indic_configs); i++)
 580     if (plan->props.script == indic_configs[i].script) {
 581       indic_plan->config = &indic_configs[i];
 582       break;
 583     }
 584 
 585   indic_plan->is_old_spec = indic_plan->config->has_old_spec && ((plan->map.chosen_script[0] & 0x000000FFu) != '2');
 586   indic_plan->virama_glyph = (hb_codepoint_t) -1;
 587 
 588   /* Use zero-context would_substitute() matching for new-spec of the main
 589    * Indic scripts, and scripts with one spec only, but not for old-specs. */
 590   bool zero_context = !indic_plan->is_old_spec;
 591   indic_plan->rphf.init (&plan->map, HB_TAG('r','p','h','f'), zero_context);
 592   indic_plan->pref.init (&plan->map, HB_TAG('p','r','e','f'), zero_context);
 593   indic_plan->blwf.init (&plan->map, HB_TAG('b','l','w','f'), zero_context);
 594   indic_plan->pstf.init (&plan->map, HB_TAG('p','s','t','f'), zero_context);
 595 
 596   for (unsigned int i = 0; i < ARRAY_LENGTH (indic_plan->mask_array); i++)
 597     indic_plan->mask_array[i] = (indic_features[i].flags & F_GLOBAL) ?
 598                                  0 : plan->map.get_1_mask (indic_features[i].tag);
 599 
 600   return indic_plan;
 601 }
 602 
 603 static void
 604 data_destroy_indic (void *data)
 605 {
 606   free (data);
 607 }
 608 
 609 static indic_position_t
 610 consonant_position_from_face (const indic_shape_plan_t *indic_plan,
 611                               const hb_codepoint_t consonant,
 612                               const hb_codepoint_t virama,
 613                               hb_face_t *face)
 614 {
 615   /* For old-spec, the order of glyphs is Consonant,Virama,
 616    * whereas for new-spec, it's Virama,Consonant.  However,
 617    * some broken fonts (like Free Sans) simply copied lookups
 618    * from old-spec to new-spec without modification.
 619    * And oddly enough, Uniscribe seems to respect those lookups.
 620    * Eg. in the sequence U+0924,U+094D,U+0930, Uniscribe finds
 621    * base at 0.  The font however, only has lookups matching
 622    * 930,94D in 'blwf', not the expected 94D,930 (with new-spec
 623    * table).  As such, we simply match both sequences.  Seems
 624    * to work. */
 625   hb_codepoint_t glyphs[3] = {virama, consonant, virama};
 626   if (indic_plan->blwf.would_substitute (glyphs  , 2, face) ||
 627       indic_plan->blwf.would_substitute (glyphs+1, 2, face))
 628     return POS_BELOW_C;
 629   if (indic_plan->pstf.would_substitute (glyphs  , 2, face) ||
 630       indic_plan->pstf.would_substitute (glyphs+1, 2, face))
 631     return POS_POST_C;
 632   unsigned int pref_len = indic_plan->config->pref_len;
 633   if ((pref_len == PREF_LEN_2 &&
 634        (indic_plan->pref.would_substitute (glyphs  , 2, face) ||
 635         indic_plan->pref.would_substitute (glyphs+1, 2, face)))
 636    || (pref_len == PREF_LEN_1 &&
 637        indic_plan->pref.would_substitute (glyphs+1, 1, face)))
 638     return POS_POST_C;
 639   return POS_BASE_C;
 640 }
 641 
 642 
 643 enum syllable_type_t {
 644   consonant_syllable,
 645   vowel_syllable,
 646   standalone_cluster,
 647   symbol_cluster,
 648   broken_cluster,
 649   non_indic_cluster,
 650 };
 651 
 652 #include "hb-ot-shape-complex-indic-machine.hh"
 653 
 654 
 655 static void
 656 setup_masks_indic (const hb_ot_shape_plan_t *plan HB_UNUSED,
 657                    hb_buffer_t              *buffer,
 658                    hb_font_t                *font HB_UNUSED)
 659 {
 660   HB_BUFFER_ALLOCATE_VAR (buffer, indic_category);
 661   HB_BUFFER_ALLOCATE_VAR (buffer, indic_position);
 662 
 663   /* We cannot setup masks here.  We save information about characters
 664    * and setup masks later on in a pause-callback. */
 665 
 666   unsigned int count = buffer->len;
 667   hb_glyph_info_t *info = buffer->info;
 668   for (unsigned int i = 0; i < count; i++)
 669     set_indic_properties (info[i]);
 670 }
 671 
 672 static void
 673 setup_syllables (const hb_ot_shape_plan_t *plan HB_UNUSED,
 674                  hb_font_t *font HB_UNUSED,
 675                  hb_buffer_t *buffer)
 676 {
 677   find_syllables (buffer);
 678 }
 679 
 680 static int
 681 compare_indic_order (const hb_glyph_info_t *pa, const hb_glyph_info_t *pb)
 682 {
 683   int a = pa->indic_position();
 684   int b = pb->indic_position();
 685 
 686   return a < b ? -1 : a == b ? 0 : +1;
 687 }
 688 
 689 
 690 
 691 static void
 692 update_consonant_positions (const hb_ot_shape_plan_t *plan,
 693                             hb_font_t         *font,
 694                             hb_buffer_t       *buffer)
 695 {
 696   const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
 697 
 698   if (indic_plan->config->base_pos != BASE_POS_LAST)
 699     return;
 700 
 701   hb_codepoint_t virama;
 702   if (indic_plan->get_virama_glyph (font, &virama))
 703   {
 704     hb_face_t *face = font->face;
 705     unsigned int count = buffer->len;
 706     hb_glyph_info_t *info = buffer->info;
 707     for (unsigned int i = 0; i < count; i++)
 708       if (info[i].indic_position() == POS_BASE_C)
 709       {
 710         hb_codepoint_t consonant = info[i].codepoint;
 711         info[i].indic_position() = consonant_position_from_face (indic_plan, consonant, virama, face);
 712       }
 713   }
 714 }
 715 
 716 
 717 /* Rules from:
 718  * https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */
 719 
 720 static void
 721 initial_reordering_consonant_syllable (const hb_ot_shape_plan_t *plan,
 722                                        hb_face_t *face,
 723                                        hb_buffer_t *buffer,
 724                                        unsigned int start, unsigned int end)
 725 {
 726   const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
 727   hb_glyph_info_t *info = buffer->info;
 728 
 729 
 730   /* 1. Find base consonant:
 731    *
 732    * The shaping engine finds the base consonant of the syllable, using the
 733    * following algorithm: starting from the end of the syllable, move backwards
 734    * until a consonant is found that does not have a below-base or post-base
 735    * form (post-base forms have to follow below-base forms), or that is not a
 736    * pre-base reordering Ra, or arrive at the first consonant. The consonant
 737    * stopped at will be the base.
 738    *
 739    *   o If the syllable starts with Ra + Halant (in a script that has Reph)
 740    *     and has more than one consonant, Ra is excluded from candidates for
 741    *     base consonants.
 742    */
 743 
 744   unsigned int base = end;
 745   bool has_reph = false;
 746 
 747   {
 748     /* -> If the syllable starts with Ra + Halant (in a script that has Reph)
 749      *    and has more than one consonant, Ra is excluded from candidates for
 750      *    base consonants. */
 751     unsigned int limit = start;
 752     if (indic_plan->config->reph_pos != REPH_POS_DONT_CARE &&
 753         indic_plan->mask_array[RPHF] &&
 754         start + 3 <= end &&
 755         (
 756          (indic_plan->config->reph_mode == REPH_MODE_IMPLICIT && !is_joiner (info[start + 2])) ||
 757          (indic_plan->config->reph_mode == REPH_MODE_EXPLICIT && info[start + 2].indic_category() == OT_ZWJ)
 758         ))
 759     {
 760       /* See if it matches the 'rphf' feature. */
 761       hb_codepoint_t glyphs[3] = {info[start].codepoint,
 762                                   info[start + 1].codepoint,
 763                                   indic_plan->config->reph_mode == REPH_MODE_EXPLICIT ?
 764                                     info[start + 2].codepoint : 0};
 765       if (indic_plan->rphf.would_substitute (glyphs, 2, face) ||
 766           (indic_plan->config->reph_mode == REPH_MODE_EXPLICIT &&
 767            indic_plan->rphf.would_substitute (glyphs, 3, face)))
 768       {
 769         limit += 2;
 770         while (limit < end && is_joiner (info[limit]))
 771           limit++;
 772         base = start;
 773         has_reph = true;
 774       }
 775     } else if (indic_plan->config->reph_mode == REPH_MODE_LOG_REPHA && info[start].indic_category() == OT_Repha)
 776     {
 777         limit += 1;
 778         while (limit < end && is_joiner (info[limit]))
 779           limit++;
 780         base = start;
 781         has_reph = true;
 782     }
 783 
 784     switch (indic_plan->config->base_pos)
 785     {
 786       default:
 787         assert (false);
 788         /* fallthrough */
 789 
 790       case BASE_POS_LAST:
 791       {
 792         /* -> starting from the end of the syllable, move backwards */
 793         unsigned int i = end;
 794         bool seen_below = false;
 795         do {
 796           i--;
 797           /* -> until a consonant is found */
 798           if (is_consonant (info[i]))
 799           {
 800             /* -> that does not have a below-base or post-base form
 801              * (post-base forms have to follow below-base forms), */
 802             if (info[i].indic_position() != POS_BELOW_C &&
 803                 (info[i].indic_position() != POS_POST_C || seen_below))
 804             {
 805               base = i;
 806               break;
 807             }
 808             if (info[i].indic_position() == POS_BELOW_C)
 809               seen_below = true;
 810 
 811             /* -> or that is not a pre-base reordering Ra,
 812              *
 813              * IMPLEMENTATION NOTES:
 814              *
 815              * Our pre-base reordering Ra's are marked POS_POST_C, so will be skipped
 816              * by the logic above already.
 817              */
 818 
 819             /* -> or arrive at the first consonant. The consonant stopped at will
 820              * be the base. */
 821             base = i;
 822           }
 823           else
 824           {
 825             /* A ZWJ after a Halant stops the base search, and requests an explicit
 826              * half form.
 827              * A ZWJ before a Halant, requests a subjoined form instead, and hence
 828              * search continues.  This is particularly important for Bengali
 829              * sequence Ra,H,Ya that should form Ya-Phalaa by subjoining Ya. */
 830             if (start < i &&
 831                 info[i].indic_category() == OT_ZWJ &&
 832                 info[i - 1].indic_category() == OT_H)
 833               break;
 834           }
 835         } while (i > limit);
 836       }
 837       break;
 838 
 839       case BASE_POS_LAST_SINHALA:
 840       {
 841         /* Sinhala base positioning is slightly different from main Indic, in that:
 842          * 1. Its ZWJ behavior is different,
 843          * 2. We don't need to look into the font for consonant positions.
 844          */
 845 
 846         if (!has_reph)
 847           base = limit;
 848 
 849         /* Find the last base consonant that is not blocked by ZWJ.  If there is
 850          * a ZWJ right before a base consonant, that would request a subjoined form. */
 851         for (unsigned int i = limit; i < end; i++)
 852           if (is_consonant (info[i]))
 853           {
 854             if (limit < i && info[i - 1].indic_category() == OT_ZWJ)
 855               break;
 856             else
 857               base = i;
 858           }
 859 
 860         /* Mark all subsequent consonants as below. */
 861         for (unsigned int i = base + 1; i < end; i++)
 862           if (is_consonant (info[i]))
 863             info[i].indic_position() = POS_BELOW_C;
 864       }
 865       break;
 866 
 867       case BASE_POS_FIRST:
 868       {
 869         /* The first consonant is always the base. */
 870 
 871         assert (indic_plan->config->reph_mode == REPH_MODE_VIS_REPHA);
 872         assert (!has_reph);
 873 
 874         base = start;
 875 
 876         /* Mark all subsequent consonants as below. */
 877         for (unsigned int i = base + 1; i < end; i++)
 878           if (is_consonant (info[i]))
 879             info[i].indic_position() = POS_BELOW_C;
 880       }
 881       break;
 882     }
 883 
 884     /* -> If the syllable starts with Ra + Halant (in a script that has Reph)
 885      *    and has more than one consonant, Ra is excluded from candidates for
 886      *    base consonants.
 887      *
 888      *  Only do this for unforced Reph. (ie. not for Ra,H,ZWJ. */
 889     if (has_reph && base == start && limit - base <= 2) {
 890       /* Have no other consonant, so Reph is not formed and Ra becomes base. */
 891       has_reph = false;
 892     }
 893   }
 894 
 895 
 896   /* 2. Decompose and reorder Matras:
 897    *
 898    * Each matra and any syllable modifier sign in the cluster are moved to the
 899    * appropriate position relative to the consonant(s) in the cluster. The
 900    * shaping engine decomposes two- or three-part matras into their constituent
 901    * parts before any repositioning. Matra characters are classified by which
 902    * consonant in a conjunct they have affinity for and are reordered to the
 903    * following positions:
 904    *
 905    *   o Before first half form in the syllable
 906    *   o After subjoined consonants
 907    *   o After post-form consonant
 908    *   o After main consonant (for above marks)
 909    *
 910    * IMPLEMENTATION NOTES:
 911    *
 912    * The normalize() routine has already decomposed matras for us, so we don't
 913    * need to worry about that.
 914    */
 915 
 916 
 917   /* 3.  Reorder marks to canonical order:
 918    *
 919    * Adjacent nukta and halant or nukta and vedic sign are always repositioned
 920    * if necessary, so that the nukta is first.
 921    *
 922    * IMPLEMENTATION NOTES:
 923    *
 924    * We don't need to do this: the normalize() routine already did this for us.
 925    */
 926 
 927 
 928   /* Reorder characters */
 929 
 930   for (unsigned int i = start; i < base; i++)
 931     info[i].indic_position() = MIN (POS_PRE_C, (indic_position_t) info[i].indic_position());
 932 
 933   if (base < end)
 934     info[base].indic_position() = POS_BASE_C;
 935 
 936   /* Mark final consonants.  A final consonant is one appearing after a matra,
 937    * like in Khmer. */
 938   for (unsigned int i = base + 1; i < end; i++)
 939     if (info[i].indic_category() == OT_M) {
 940       for (unsigned int j = i + 1; j < end; j++)
 941         if (is_consonant (info[j])) {
 942           info[j].indic_position() = POS_FINAL_C;
 943           break;
 944         }
 945       break;
 946     }
 947 
 948   /* Handle beginning Ra */
 949   if (has_reph)
 950     info[start].indic_position() = POS_RA_TO_BECOME_REPH;
 951 
 952   /* For old-style Indic script tags, move the first post-base Halant after
 953    * last consonant.
 954    *
 955    * Reports suggest that in some scripts Uniscribe does this only if there
 956    * is *not* a Halant after last consonant already (eg. Kannada), while it
 957    * does it unconditionally in other scripts (eg. Malayalam).  We don't
 958    * currently know about other scripts, so we single out Malayalam for now.
 959    *
 960    * Kannada test case:
 961    * U+0C9A,U+0CCD,U+0C9A,U+0CCD
 962    * With some versions of Lohit Kannada.
 963    * https://bugs.freedesktop.org/show_bug.cgi?id=59118
 964    *
 965    * Malayalam test case:
 966    * U+0D38,U+0D4D,U+0D31,U+0D4D,U+0D31,U+0D4D
 967    * With lohit-ttf-20121122/Lohit-Malayalam.ttf
 968    */
 969   if (indic_plan->is_old_spec)
 970   {
 971     bool disallow_double_halants = buffer->props.script != HB_SCRIPT_MALAYALAM;
 972     for (unsigned int i = base + 1; i < end; i++)
 973       if (info[i].indic_category() == OT_H)
 974       {
 975         unsigned int j;
 976         for (j = end - 1; j > i; j--)
 977           if (is_consonant (info[j]) ||
 978               (disallow_double_halants && info[j].indic_category() == OT_H))
 979             break;
 980         if (info[j].indic_category() != OT_H && j > i) {
 981           /* Move Halant to after last consonant. */
 982           hb_glyph_info_t t = info[i];
 983           memmove (&info[i], &info[i + 1], (j - i) * sizeof (info[0]));
 984           info[j] = t;
 985         }
 986         break;
 987       }
 988   }
 989 
 990   /* Attach misc marks to previous char to move with them. */
 991   {
 992     indic_position_t last_pos = POS_START;
 993     for (unsigned int i = start; i < end; i++)
 994     {
 995       if ((FLAG_SAFE (info[i].indic_category()) & (JOINER_FLAGS | FLAG (OT_N) | FLAG (OT_RS) | MEDIAL_FLAGS | HALANT_OR_COENG_FLAGS)))
 996       {
 997         info[i].indic_position() = last_pos;
 998         if (unlikely (info[i].indic_category() == OT_H &&
 999                       info[i].indic_position() == POS_PRE_M))
1000         {
1001           /*
1002            * Uniscribe doesn't move the Halant with Left Matra.
1003            * TEST: U+092B,U+093F,U+094DE
1004            * We follow.  This is important for the Sinhala
1005            * U+0DDA split matra since it decomposes to U+0DD9,U+0DCA
1006            * where U+0DD9 is a left matra and U+0DCA is the virama.
1007            * We don't want to move the virama with the left matra.
1008            * TEST: U+0D9A,U+0DDA
1009            */
1010           for (unsigned int j = i; j > start; j--)
1011             if (info[j - 1].indic_position() != POS_PRE_M) {
1012               info[i].indic_position() = info[j - 1].indic_position();
1013               break;
1014             }
1015         }
1016       } else if (info[i].indic_position() != POS_SMVD) {
1017         last_pos = (indic_position_t) info[i].indic_position();
1018       }
1019     }
1020   }
1021   /* For post-base consonants let them own anything before them
1022    * since the last consonant or matra. */
1023   {
1024     unsigned int last = base;
1025     for (unsigned int i = base + 1; i < end; i++)
1026       if (is_consonant (info[i]))
1027       {
1028         for (unsigned int j = last + 1; j < i; j++)
1029           if (info[j].indic_position() < POS_SMVD)
1030             info[j].indic_position() = info[i].indic_position();
1031         last = i;
1032       } else if (info[i].indic_category() == OT_M)
1033         last = i;
1034   }
1035 
1036 
1037   {
1038     /* Use syllable() for sort accounting temporarily. */
1039     unsigned int syllable = info[start].syllable();
1040     for (unsigned int i = start; i < end; i++)
1041       info[i].syllable() = i - start;
1042 
1043     /* Sit tight, rock 'n roll! */
1044     hb_stable_sort (info + start, end - start, compare_indic_order);
1045     /* Find base again */
1046     base = end;
1047     for (unsigned int i = start; i < end; i++)
1048       if (info[i].indic_position() == POS_BASE_C)
1049       {
1050         base = i;
1051         break;
1052       }
1053     /* Things are out-of-control for post base positions, they may shuffle
1054      * around like crazy.  In old-spec mode, we move halants around, so in
1055      * that case merge all clusters after base.  Otherwise, check the sort
1056      * order and merge as needed.
1057      * For pre-base stuff, we handle cluster issues in final reordering.
1058      *
1059      * We could use buffer->sort() for this, if there was no special
1060      * reordering of pre-base stuff happening later...
1061      */
1062     if (indic_plan->is_old_spec || end - base > 127)
1063       buffer->merge_clusters (base, end);
1064     else
1065     {
1066       /* Note!  syllable() is a one-byte field. */
1067       for (unsigned int i = base; i < end; i++)
1068         if (info[i].syllable() != 255)
1069         {
1070           unsigned int max = i;
1071           unsigned int j = start + info[i].syllable();
1072           while (j != i)
1073           {
1074             max = MAX (max, j);
1075             unsigned int next = start + info[j].syllable();
1076             info[j].syllable() = 255; /* So we don't process j later again. */
1077             j = next;
1078           }
1079           if (i != max)
1080             buffer->merge_clusters (i, max + 1);
1081         }
1082     }
1083 
1084     /* Put syllable back in. */
1085     for (unsigned int i = start; i < end; i++)
1086       info[i].syllable() = syllable;
1087   }
1088 
1089   /* Setup masks now */
1090 
1091   {
1092     hb_mask_t mask;
1093 
1094     /* Reph */
1095     for (unsigned int i = start; i < end && info[i].indic_position() == POS_RA_TO_BECOME_REPH; i++)
1096       info[i].mask |= indic_plan->mask_array[RPHF];
1097 
1098     /* Pre-base */
1099     mask = indic_plan->mask_array[HALF];
1100     if (!indic_plan->is_old_spec &&
1101         indic_plan->config->blwf_mode == BLWF_MODE_PRE_AND_POST)
1102       mask |= indic_plan->mask_array[BLWF];
1103     for (unsigned int i = start; i < base; i++)
1104       info[i].mask  |= mask;
1105     /* Base */
1106     mask = 0;
1107     if (base < end)
1108       info[base].mask |= mask;
1109     /* Post-base */
1110     mask = indic_plan->mask_array[BLWF] | indic_plan->mask_array[ABVF] | indic_plan->mask_array[PSTF];
1111     for (unsigned int i = base + 1; i < end; i++)
1112       info[i].mask  |= mask;
1113   }
1114 
1115   if (indic_plan->is_old_spec &&
1116       buffer->props.script == HB_SCRIPT_DEVANAGARI)
1117   {
1118     /* Old-spec eye-lash Ra needs special handling.  From the
1119      * spec:
1120      *
1121      * "The feature 'below-base form' is applied to consonants
1122      * having below-base forms and following the base consonant.
1123      * The exception is vattu, which may appear below half forms
1124      * as well as below the base glyph. The feature 'below-base
1125      * form' will be applied to all such occurrences of Ra as well."
1126      *
1127      * Test case: U+0924,U+094D,U+0930,U+094d,U+0915
1128      * with Sanskrit 2003 font.
1129      *
1130      * However, note that Ra,Halant,ZWJ is the correct way to
1131      * request eyelash form of Ra, so we wouldbn't inhibit it
1132      * in that sequence.
1133      *
1134      * Test case: U+0924,U+094D,U+0930,U+094d,U+200D,U+0915
1135      */
1136     for (unsigned int i = start; i + 1 < base; i++)
1137       if (info[i  ].indic_category() == OT_Ra &&
1138           info[i+1].indic_category() == OT_H  &&
1139           (i + 2 == base ||
1140            info[i+2].indic_category() != OT_ZWJ))
1141       {
1142         info[i  ].mask |= indic_plan->mask_array[BLWF];
1143         info[i+1].mask |= indic_plan->mask_array[BLWF];
1144       }
1145   }
1146 
1147   unsigned int pref_len = indic_plan->config->pref_len;
1148   if (indic_plan->mask_array[PREF] && base + pref_len < end)
1149   {
1150     assert (1 <= pref_len && pref_len <= 2);
1151     /* Find a Halant,Ra sequence and mark it for pre-base reordering processing. */
1152     for (unsigned int i = base + 1; i + pref_len - 1 < end; i++) {
1153       hb_codepoint_t glyphs[2];
1154       for (unsigned int j = 0; j < pref_len; j++)
1155         glyphs[j] = info[i + j].codepoint;
1156       if (indic_plan->pref.would_substitute (glyphs, pref_len, face))
1157       {
1158         for (unsigned int j = 0; j < pref_len; j++)
1159           info[i++].mask |= indic_plan->mask_array[PREF];
1160 
1161         /* Mark the subsequent stuff with 'cfar'.  Used in Khmer.
1162          * Read the feature spec.
1163          * This allows distinguishing the following cases with MS Khmer fonts:
1164          * U+1784,U+17D2,U+179A,U+17D2,U+1782
1165          * U+1784,U+17D2,U+1782,U+17D2,U+179A
1166          */
1167         if (indic_plan->mask_array[CFAR])
1168           for (; i < end; i++)
1169             info[i].mask |= indic_plan->mask_array[CFAR];
1170 
1171         break;
1172       }
1173     }
1174   }
1175 
1176   /* Apply ZWJ/ZWNJ effects */
1177   for (unsigned int i = start + 1; i < end; i++)
1178     if (is_joiner (info[i])) {
1179       bool non_joiner = info[i].indic_category() == OT_ZWNJ;
1180       unsigned int j = i;
1181 
1182       do {
1183         j--;
1184 
1185         /* ZWJ/ZWNJ should disable CJCT.  They do that by simply
1186          * being there, since we don't skip them for the CJCT
1187          * feature (ie. F_MANUAL_ZWJ) */
1188 
1189         /* A ZWNJ disables HALF. */
1190         if (non_joiner)
1191           info[j].mask &= ~indic_plan->mask_array[HALF];
1192 
1193       } while (j > start && !is_consonant (info[j]));
1194     }
1195 }
1196 
1197 static void
1198 initial_reordering_standalone_cluster (const hb_ot_shape_plan_t *plan,
1199                                        hb_face_t *face,
1200                                        hb_buffer_t *buffer,
1201                                        unsigned int start, unsigned int end)
1202 {
1203   /* We treat placeholder/dotted-circle as if they are consonants, so we
1204    * should just chain.  Only if not in compatibility mode that is... */
1205 
1206   if (hb_options ().uniscribe_bug_compatible)
1207   {
1208     /* For dotted-circle, this is what Uniscribe does:
1209      * If dotted-circle is the last glyph, it just does nothing.
1210      * Ie. It doesn't form Reph. */
1211     if (buffer->info[end - 1].indic_category() == OT_DOTTEDCIRCLE)
1212       return;
1213   }
1214 
1215   initial_reordering_consonant_syllable (plan, face, buffer, start, end);
1216 }
1217 
1218 static void
1219 initial_reordering_syllable (const hb_ot_shape_plan_t *plan,
1220                              hb_face_t *face,
1221                              hb_buffer_t *buffer,
1222                              unsigned int start, unsigned int end)
1223 {
1224   syllable_type_t syllable_type = (syllable_type_t) (buffer->info[start].syllable() & 0x0F);
1225   switch (syllable_type)
1226   {
1227     case vowel_syllable: /* We made the vowels look like consonants.  So let's call the consonant logic! */
1228     case consonant_syllable:
1229      initial_reordering_consonant_syllable (plan, face, buffer, start, end);
1230      break;
1231 
1232     case broken_cluster: /* We already inserted dotted-circles, so just call the standalone_cluster. */
1233     case standalone_cluster:
1234      initial_reordering_standalone_cluster (plan, face, buffer, start, end);
1235      break;
1236 
1237     case symbol_cluster:
1238     case non_indic_cluster:
1239       break;
1240   }
1241 }
1242 
1243 static inline void
1244 insert_dotted_circles (const hb_ot_shape_plan_t *plan HB_UNUSED,
1245                        hb_font_t *font,
1246                        hb_buffer_t *buffer)
1247 {
1248   /* Note: This loop is extra overhead, but should not be measurable. */
1249   bool has_broken_syllables = false;
1250   unsigned int count = buffer->len;
1251   hb_glyph_info_t *info = buffer->info;
1252   for (unsigned int i = 0; i < count; i++)
1253     if ((info[i].syllable() & 0x0F) == broken_cluster)
1254     {
1255       has_broken_syllables = true;
1256       break;
1257     }
1258   if (likely (!has_broken_syllables))
1259     return;
1260 
1261 
1262   hb_codepoint_t dottedcircle_glyph;
1263   if (!font->get_glyph (0x25CCu, 0, &dottedcircle_glyph))
1264     return;
1265 
1266   hb_glyph_info_t dottedcircle = {0};
1267   dottedcircle.codepoint = 0x25CCu;
1268   set_indic_properties (dottedcircle);
1269   dottedcircle.codepoint = dottedcircle_glyph;
1270 
1271   buffer->clear_output ();
1272 
1273   buffer->idx = 0;
1274   unsigned int last_syllable = 0;
1275   while (buffer->idx < buffer->len)
1276   {
1277     unsigned int syllable = buffer->cur().syllable();
1278     syllable_type_t syllable_type = (syllable_type_t) (syllable & 0x0F);
1279     if (unlikely (last_syllable != syllable && syllable_type == broken_cluster))
1280     {
1281       last_syllable = syllable;
1282 
1283       hb_glyph_info_t info = dottedcircle;
1284       info.cluster = buffer->cur().cluster;
1285       info.mask = buffer->cur().mask;
1286       info.syllable() = buffer->cur().syllable();
1287       /* TODO Set glyph_props? */
1288 
1289       /* Insert dottedcircle after possible Repha. */
1290       while (buffer->idx < buffer->len &&
1291              last_syllable == buffer->cur().syllable() &&
1292              buffer->cur().indic_category() == OT_Repha)
1293         buffer->next_glyph ();
1294 
1295       buffer->output_info (info);
1296     }
1297     else
1298       buffer->next_glyph ();
1299   }
1300 
1301   buffer->swap_buffers ();
1302 }
1303 
1304 static void
1305 initial_reordering (const hb_ot_shape_plan_t *plan,
1306                     hb_font_t *font,
1307                     hb_buffer_t *buffer)
1308 {
1309   update_consonant_positions (plan, font, buffer);
1310   insert_dotted_circles (plan, font, buffer);
1311 
1312   foreach_syllable (buffer, start, end)
1313     initial_reordering_syllable (plan, font->face, buffer, start, end);
1314 }
1315 
1316 static void
1317 final_reordering_syllable (const hb_ot_shape_plan_t *plan,
1318                            hb_buffer_t *buffer,
1319                            unsigned int start, unsigned int end)
1320 {
1321   const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
1322   hb_glyph_info_t *info = buffer->info;
1323 
1324 
1325   /* This function relies heavily on halant glyphs.  Lots of ligation
1326    * and possibly multiplication substitutions happened prior to this
1327    * phase, and that might have messed up our properties.  Recover
1328    * from a particular case of that where we're fairly sure that a
1329    * class of OT_H is desired but has been lost. */
1330   if (indic_plan->virama_glyph)
1331   {
1332     unsigned int virama_glyph = indic_plan->virama_glyph;
1333     for (unsigned int i = start; i < end; i++)
1334       if (info[i].codepoint == virama_glyph &&
1335           _hb_glyph_info_ligated (&info[i]) &&
1336           _hb_glyph_info_multiplied (&info[i]))
1337       {
1338         /* This will make sure that this glyph passes is_halant_or_coeng() test. */
1339         info[i].indic_category() = OT_H;
1340         _hb_glyph_info_clear_ligated_and_multiplied (&info[i]);
1341       }
1342   }
1343 
1344 
1345   /* 4. Final reordering:
1346    *
1347    * After the localized forms and basic shaping forms GSUB features have been
1348    * applied (see below), the shaping engine performs some final glyph
1349    * reordering before applying all the remaining font features to the entire
1350    * cluster.
1351    */
1352 
1353   bool try_pref = !!indic_plan->mask_array[PREF];
1354 
1355   /* Find base again */
1356   unsigned int base;
1357   for (base = start; base < end; base++)
1358     if (info[base].indic_position() >= POS_BASE_C)
1359     {
1360       if (try_pref && base + 1 < end && indic_plan->config->pref_len == 2)
1361       {
1362         for (unsigned int i = base + 1; i < end; i++)
1363           if ((info[i].mask & indic_plan->mask_array[PREF]) != 0)
1364           {
1365             if (!(_hb_glyph_info_substituted (&info[i]) &&
1366                   _hb_glyph_info_ligated_and_didnt_multiply (&info[i])))
1367             {
1368               /* Ok, this was a 'pref' candidate but didn't form any.
1369                * Base is around here... */
1370               base = i;
1371               while (base < end && is_halant_or_coeng (info[base]))
1372                 base++;
1373               info[base].indic_position() = POS_BASE_C;
1374 
1375               try_pref = false;
1376             }
1377             break;
1378           }
1379       }
1380 
1381       if (start < base && info[base].indic_position() > POS_BASE_C)
1382         base--;
1383       break;
1384     }
1385   if (base == end && start < base &&
1386       is_one_of (info[base - 1], FLAG (OT_ZWJ)))
1387     base--;
1388   if (base < end)
1389     while (start < base &&
1390            is_one_of (info[base], (FLAG (OT_N) | HALANT_OR_COENG_FLAGS)))
1391       base--;
1392 
1393 
1394   /*   o Reorder matras:
1395    *
1396    *     If a pre-base matra character had been reordered before applying basic
1397    *     features, the glyph can be moved closer to the main consonant based on
1398    *     whether half-forms had been formed. Actual position for the matra is
1399    *     defined as “after last standalone halant glyph, after initial matra
1400    *     position and before the main consonant”. If ZWJ or ZWNJ follow this
1401    *     halant, position is moved after it.
1402    */
1403 
1404   if (start + 1 < end && start < base) /* Otherwise there can't be any pre-base matra characters. */
1405   {
1406     /* If we lost track of base, alas, position before last thingy. */
1407     unsigned int new_pos = base == end ? base - 2 : base - 1;
1408 
1409     /* Malayalam / Tamil do not have "half" forms or explicit virama forms.
1410      * The glyphs formed by 'half' are Chillus or ligated explicit viramas.
1411      * We want to position matra after them.
1412      */
1413     if (buffer->props.script != HB_SCRIPT_MALAYALAM && buffer->props.script != HB_SCRIPT_TAMIL)
1414     {
1415       while (new_pos > start &&
1416              !(is_one_of (info[new_pos], (FLAG (OT_M) | HALANT_OR_COENG_FLAGS))))
1417         new_pos--;
1418 
1419       /* If we found no Halant we are done.
1420        * Otherwise only proceed if the Halant does
1421        * not belong to the Matra itself! */
1422       if (is_halant_or_coeng (info[new_pos]) &&
1423           info[new_pos].indic_position() != POS_PRE_M)
1424       {
1425         /* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */
1426         if (new_pos + 1 < end && is_joiner (info[new_pos + 1]))
1427           new_pos++;
1428       }
1429       else
1430         new_pos = start; /* No move. */
1431     }
1432 
1433     if (start < new_pos && info[new_pos].indic_position () != POS_PRE_M)
1434     {
1435       /* Now go see if there's actually any matras... */
1436       for (unsigned int i = new_pos; i > start; i--)
1437         if (info[i - 1].indic_position () == POS_PRE_M)
1438         {
1439           unsigned int old_pos = i - 1;
1440           if (old_pos < base && base <= new_pos) /* Shouldn't actually happen. */
1441             base--;
1442 
1443           hb_glyph_info_t tmp = info[old_pos];
1444           memmove (&info[old_pos], &info[old_pos + 1], (new_pos - old_pos) * sizeof (info[0]));
1445           info[new_pos] = tmp;
1446 
1447           /* Note: this merge_clusters() is intentionally *after* the reordering.
1448            * Indic matra reordering is special and tricky... */
1449           buffer->merge_clusters (new_pos, MIN (end, base + 1));
1450 
1451           new_pos--;
1452         }
1453     } else {
1454       for (unsigned int i = start; i < base; i++)
1455         if (info[i].indic_position () == POS_PRE_M) {
1456           buffer->merge_clusters (i, MIN (end, base + 1));
1457           break;
1458         }
1459     }
1460   }
1461 
1462 
1463   /*   o Reorder reph:
1464    *
1465    *     Reph’s original position is always at the beginning of the syllable,
1466    *     (i.e. it is not reordered at the character reordering stage). However,
1467    *     it will be reordered according to the basic-forms shaping results.
1468    *     Possible positions for reph, depending on the script, are; after main,
1469    *     before post-base consonant forms, and after post-base consonant forms.
1470    */
1471 
1472   /* Two cases:
1473    *
1474    * - If repha is encoded as a sequence of characters (Ra,H or Ra,H,ZWJ), then
1475    *   we should only move it if the sequence ligated to the repha form.
1476    *
1477    * - If repha is encoded separately and in the logical position, we should only
1478    *   move it if it did NOT ligate.  If it ligated, it's probably the font trying
1479    *   to make it work without the reordering.
1480    */
1481   if (start + 1 < end &&
1482       info[start].indic_position() == POS_RA_TO_BECOME_REPH &&
1483       ((info[start].indic_category() == OT_Repha) ^
1484        _hb_glyph_info_ligated_and_didnt_multiply (&info[start])))
1485   {
1486     unsigned int new_reph_pos;
1487     reph_position_t reph_pos = indic_plan->config->reph_pos;
1488 
1489     assert (reph_pos != REPH_POS_DONT_CARE);
1490 
1491     /*       1. If reph should be positioned after post-base consonant forms,
1492      *          proceed to step 5.
1493      */
1494     if (reph_pos == REPH_POS_AFTER_POST)
1495     {
1496       goto reph_step_5;
1497     }
1498 
1499     /*       2. If the reph repositioning class is not after post-base: target
1500      *          position is after the first explicit halant glyph between the
1501      *          first post-reph consonant and last main consonant. If ZWJ or ZWNJ
1502      *          are following this halant, position is moved after it. If such
1503      *          position is found, this is the target position. Otherwise,
1504      *          proceed to the next step.
1505      *
1506      *          Note: in old-implementation fonts, where classifications were
1507      *          fixed in shaping engine, there was no case where reph position
1508      *          will be found on this step.
1509      */
1510     {
1511       new_reph_pos = start + 1;
1512       while (new_reph_pos < base && !is_halant_or_coeng (info[new_reph_pos]))
1513         new_reph_pos++;
1514 
1515       if (new_reph_pos < base && is_halant_or_coeng (info[new_reph_pos]))
1516       {
1517         /* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */
1518         if (new_reph_pos + 1 < base && is_joiner (info[new_reph_pos + 1]))
1519           new_reph_pos++;
1520         goto reph_move;
1521       }
1522     }
1523 
1524     /*       3. If reph should be repositioned after the main consonant: find the
1525      *          first consonant not ligated with main, or find the first
1526      *          consonant that is not a potential pre-base reordering Ra.
1527      */
1528     if (reph_pos == REPH_POS_AFTER_MAIN)
1529     {
1530       new_reph_pos = base;
1531       while (new_reph_pos + 1 < end && info[new_reph_pos + 1].indic_position() <= POS_AFTER_MAIN)
1532         new_reph_pos++;
1533       if (new_reph_pos < end)
1534         goto reph_move;
1535     }
1536 
1537     /*       4. If reph should be positioned before post-base consonant, find
1538      *          first post-base classified consonant not ligated with main. If no
1539      *          consonant is found, the target position should be before the
1540      *          first matra, syllable modifier sign or vedic sign.
1541      */
1542     /* This is our take on what step 4 is trying to say (and failing, BADLY). */
1543     if (reph_pos == REPH_POS_AFTER_SUB)
1544     {
1545       new_reph_pos = base;
1546       while (new_reph_pos < end &&
1547              !( FLAG_SAFE (info[new_reph_pos + 1].indic_position()) & (FLAG (POS_POST_C) | FLAG (POS_AFTER_POST) | FLAG (POS_SMVD))))
1548         new_reph_pos++;
1549       if (new_reph_pos < end)
1550         goto reph_move;
1551     }
1552 
1553     /*       5. If no consonant is found in steps 3 or 4, move reph to a position
1554      *          immediately before the first post-base matra, syllable modifier
1555      *          sign or vedic sign that has a reordering class after the intended
1556      *          reph position. For example, if the reordering position for reph
1557      *          is post-main, it will skip above-base matras that also have a
1558      *          post-main position.
1559      */
1560     reph_step_5:
1561     {
1562       /* Copied from step 2. */
1563       new_reph_pos = start + 1;
1564       while (new_reph_pos < base && !is_halant_or_coeng (info[new_reph_pos]))
1565         new_reph_pos++;
1566 
1567       if (new_reph_pos < base && is_halant_or_coeng (info[new_reph_pos]))
1568       {
1569         /* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */
1570         if (new_reph_pos + 1 < base && is_joiner (info[new_reph_pos + 1]))
1571           new_reph_pos++;
1572         goto reph_move;
1573       }
1574     }
1575 
1576     /*       6. Otherwise, reorder reph to the end of the syllable.
1577      */
1578     {
1579       new_reph_pos = end - 1;
1580       while (new_reph_pos > start && info[new_reph_pos].indic_position() == POS_SMVD)
1581         new_reph_pos--;
1582 
1583       /*
1584        * If the Reph is to be ending up after a Matra,Halant sequence,
1585        * position it before that Halant so it can interact with the Matra.
1586        * However, if it's a plain Consonant,Halant we shouldn't do that.
1587        * Uniscribe doesn't do this.
1588        * TEST: U+0930,U+094D,U+0915,U+094B,U+094D
1589        */
1590       if (!hb_options ().uniscribe_bug_compatible &&
1591           unlikely (is_halant_or_coeng (info[new_reph_pos]))) {
1592         for (unsigned int i = base + 1; i < new_reph_pos; i++)
1593           if (info[i].indic_category() == OT_M) {
1594             /* Ok, got it. */
1595             new_reph_pos--;
1596           }
1597       }
1598       goto reph_move;
1599     }
1600 
1601     reph_move:
1602     {
1603       /* Move */
1604       buffer->merge_clusters (start, new_reph_pos + 1);
1605       hb_glyph_info_t reph = info[start];
1606       memmove (&info[start], &info[start + 1], (new_reph_pos - start) * sizeof (info[0]));
1607       info[new_reph_pos] = reph;
1608 
1609       if (start < base && base <= new_reph_pos)
1610         base--;
1611     }
1612   }
1613 
1614 
1615   /*   o Reorder pre-base reordering consonants:
1616    *
1617    *     If a pre-base reordering consonant is found, reorder it according to
1618    *     the following rules:
1619    */
1620 
1621   if (try_pref && base + 1 < end) /* Otherwise there can't be any pre-base reordering Ra. */
1622   {
1623     unsigned int pref_len = indic_plan->config->pref_len;
1624     for (unsigned int i = base + 1; i < end; i++)
1625       if ((info[i].mask & indic_plan->mask_array[PREF]) != 0)
1626       {
1627         /*       1. Only reorder a glyph produced by substitution during application
1628          *          of the <pref> feature. (Note that a font may shape a Ra consonant with
1629          *          the feature generally but block it in certain contexts.)
1630          */
1631         /* Note: We just check that something got substituted.  We don't check that
1632          * the <pref> feature actually did it...
1633          *
1634          * If pref len is longer than one, then only reorder if it ligated.  If
1635          * pref len is one, only reorder if it didn't ligate with other things. */
1636         if (_hb_glyph_info_substituted (&info[i]) &&
1637             ((pref_len == 1) ^ _hb_glyph_info_ligated_and_didnt_multiply (&info[i])))
1638         {
1639           /*
1640            *       2. Try to find a target position the same way as for pre-base matra.
1641            *          If it is found, reorder pre-base consonant glyph.
1642            *
1643            *       3. If position is not found, reorder immediately before main
1644            *          consonant.
1645            */
1646 
1647           unsigned int new_pos = base;
1648           /* Malayalam / Tamil do not have "half" forms or explicit virama forms.
1649            * The glyphs formed by 'half' are Chillus or ligated explicit viramas.
1650            * We want to position matra after them.
1651            */
1652           if (buffer->props.script != HB_SCRIPT_MALAYALAM && buffer->props.script != HB_SCRIPT_TAMIL)
1653           {
1654             while (new_pos > start &&
1655                    !(is_one_of (info[new_pos - 1], FLAG(OT_M) | HALANT_OR_COENG_FLAGS)))
1656               new_pos--;
1657 
1658             /* In Khmer coeng model, a H,Ra can go *after* matras.  If it goes after a
1659              * split matra, it should be reordered to *before* the left part of such matra. */
1660             if (new_pos > start && info[new_pos - 1].indic_category() == OT_M)
1661             {
1662               unsigned int old_pos = i;
1663               for (unsigned int i = base + 1; i < old_pos; i++)
1664                 if (info[i].indic_category() == OT_M)
1665                 {
1666                   new_pos--;
1667                   break;
1668                 }
1669             }
1670           }
1671 
1672           if (new_pos > start && is_halant_or_coeng (info[new_pos - 1]))
1673           {
1674             /* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */
1675             if (new_pos < end && is_joiner (info[new_pos]))
1676               new_pos++;
1677           }
1678 
1679           {
1680             unsigned int old_pos = i;
1681 
1682             buffer->merge_clusters (new_pos, old_pos + 1);
1683             hb_glyph_info_t tmp = info[old_pos];
1684             memmove (&info[new_pos + 1], &info[new_pos], (old_pos - new_pos) * sizeof (info[0]));
1685             info[new_pos] = tmp;
1686 
1687             if (new_pos <= base && base < old_pos)
1688               base++;
1689           }
1690         }
1691 
1692         break;
1693       }
1694   }
1695 
1696 
1697   /* Apply 'init' to the Left Matra if it's a word start. */
1698   if (info[start].indic_position () == POS_PRE_M &&
1699       (!start ||
1700        !(FLAG_SAFE (_hb_glyph_info_get_general_category (&info[start - 1])) &
1701          FLAG_RANGE (HB_UNICODE_GENERAL_CATEGORY_FORMAT, HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK))))
1702     info[start].mask |= indic_plan->mask_array[INIT];
1703 
1704 
1705   /*
1706    * Finish off the clusters and go home!
1707    */
1708   if (hb_options ().uniscribe_bug_compatible)
1709   {
1710     switch ((hb_tag_t) plan->props.script)
1711     {
1712       case HB_SCRIPT_TAMIL:
1713       case HB_SCRIPT_SINHALA:
1714         break;
1715 
1716       default:
1717         /* Uniscribe merges the entire cluster... Except for Tamil & Sinhala.
1718          * This means, half forms are submerged into the main consonants cluster.
1719          * This is unnecessary, and makes cursor positioning harder, but that's what
1720          * Uniscribe does. */
1721         buffer->merge_clusters (start, end);
1722         break;
1723     }
1724   }
1725 }
1726 
1727 
1728 static void
1729 final_reordering (const hb_ot_shape_plan_t *plan,
1730                   hb_font_t *font HB_UNUSED,
1731                   hb_buffer_t *buffer)
1732 {
1733   unsigned int count = buffer->len;
1734   if (unlikely (!count)) return;
1735 
1736   foreach_syllable (buffer, start, end)
1737     final_reordering_syllable (plan, buffer, start, end);
1738 
1739   HB_BUFFER_DEALLOCATE_VAR (buffer, indic_category);
1740   HB_BUFFER_DEALLOCATE_VAR (buffer, indic_position);
1741 }
1742 
1743 
1744 static void
1745 clear_syllables (const hb_ot_shape_plan_t *plan HB_UNUSED,
1746                  hb_font_t *font HB_UNUSED,
1747                  hb_buffer_t *buffer)
1748 {
1749   hb_glyph_info_t *info = buffer->info;
1750   unsigned int count = buffer->len;
1751   for (unsigned int i = 0; i < count; i++)
1752     info[i].syllable() = 0;
1753 }
1754 
1755 
1756 static bool
1757 decompose_indic (const hb_ot_shape_normalize_context_t *c,
1758                  hb_codepoint_t  ab,
1759                  hb_codepoint_t *a,
1760                  hb_codepoint_t *b)
1761 {
1762   switch (ab)
1763   {
1764     /* Don't decompose these. */
1765     case 0x0931u  : return false;
1766     case 0x0B94u  : return false;
1767 
1768 
1769     /*
1770      * Decompose split matras that don't have Unicode decompositions.
1771      */
1772 
1773     case 0x0F77u  : *a = 0x0FB2u; *b= 0x0F81u; return true;
1774     case 0x0F79u  : *a = 0x0FB3u; *b= 0x0F81u; return true;
1775     case 0x17BEu  : *a = 0x17C1u; *b= 0x17BEu; return true;
1776     case 0x17BFu  : *a = 0x17C1u; *b= 0x17BFu; return true;
1777     case 0x17C0u  : *a = 0x17C1u; *b= 0x17C0u; return true;
1778     case 0x17C4u  : *a = 0x17C1u; *b= 0x17C4u; return true;
1779     case 0x17C5u  : *a = 0x17C1u; *b= 0x17C5u; return true;
1780     case 0x1925u  : *a = 0x1920u; *b= 0x1923u; return true;
1781     case 0x1926u  : *a = 0x1920u; *b= 0x1924u; return true;
1782     case 0x1B3Cu  : *a = 0x1B42u; *b= 0x1B3Cu; return true;
1783     case 0x1112Eu  : *a = 0x11127u; *b= 0x11131u; return true;
1784     case 0x1112Fu  : *a = 0x11127u; *b= 0x11132u; return true;
1785 #if 0
1786     /* This one has no decomposition in Unicode, but needs no decomposition either. */
1787     /* case 0x0AC9u  : return false; */
1788     case 0x0B57u  : *a = no decomp, -> RIGHT; return true;
1789     case 0x1C29u  : *a = no decomp, -> LEFT; return true;
1790     case 0xA9C0u  : *a = no decomp, -> RIGHT; return true;
1791     case 0x111BuF  : *a = no decomp, -> ABOVE; return true;
1792 #endif
1793   }
1794 
1795   if ((ab == 0x0DDAu || hb_in_range (ab, 0x0DDCu, 0x0DDEu)))
1796   {
1797     /*
1798      * Sinhala split matras...  Let the fun begin.
1799      *
1800      * These four characters have Unicode decompositions.  However, Uniscribe
1801      * decomposes them "Khmer-style", that is, it uses the character itself to
1802      * get the second half.  The first half of all four decompositions is always
1803      * U+0DD9.
1804      *
1805      * Now, there are buggy fonts, namely, the widely used lklug.ttf, that are
1806      * broken with Uniscribe.  But we need to support them.  As such, we only
1807      * do the Uniscribe-style decomposition if the character is transformed into
1808      * its "sec.half" form by the 'pstf' feature.  Otherwise, we fall back to
1809      * Unicode decomposition.
1810      *
1811      * Note that we can't unconditionally use Unicode decomposition.  That would
1812      * break some other fonts, that are designed to work with Uniscribe, and
1813      * don't have positioning features for the Unicode-style decomposition.
1814      *
1815      * Argh...
1816      *
1817      * The Uniscribe behavior is now documented in the newly published Sinhala
1818      * spec in 2012:
1819      *
1820      *   http://www.microsoft.com/typography/OpenTypeDev/sinhala/intro.htm#shaping
1821      */
1822 
1823     const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) c->plan->data;
1824 
1825     hb_codepoint_t glyph;
1826 
1827     if (hb_options ().uniscribe_bug_compatible ||
1828         (c->font->get_glyph (ab, 0, &glyph) &&
1829          indic_plan->pstf.would_substitute (&glyph, 1, c->font->face)))
1830     {
1831       /* Ok, safe to use Uniscribe-style decomposition. */
1832       *a = 0x0DD9u;
1833       *b = ab;
1834       return true;
1835     }
1836   }
1837 
1838   return c->unicode->decompose (ab, a, b);
1839 }
1840 
1841 static bool
1842 compose_indic (const hb_ot_shape_normalize_context_t *c,
1843                hb_codepoint_t  a,
1844                hb_codepoint_t  b,
1845                hb_codepoint_t *ab)
1846 {
1847   /* Avoid recomposing split matras. */
1848   if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (c->unicode->general_category (a)))
1849     return false;
1850 
1851   /* Composition-exclusion exceptions that we want to recompose. */
1852   if (a == 0x09AFu && b == 0x09BCu) { *ab = 0x09DFu; return true; }
1853 
1854   return c->unicode->compose (a, b, ab);
1855 }
1856 
1857 
1858 const hb_ot_complex_shaper_t _hb_ot_complex_shaper_indic =
1859 {
1860   "indic",
1861   collect_features_indic,
1862   override_features_indic,
1863   data_create_indic,
1864   data_destroy_indic,
1865   NULL, /* preprocess_text */
1866   HB_OT_SHAPE_NORMALIZATION_MODE_COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT,
1867   decompose_indic,
1868   compose_indic,
1869   setup_masks_indic,
1870   HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE,
1871   false, /* fallback_position */
1872 };