1 /*
   2  * Copyright © 2012,2013  Mozilla Foundation.
   3  * Copyright © 2012,2013  Google, Inc.
   4  *
   5  *  This is part of HarfBuzz, a text shaping library.
   6  *
   7  * Permission is hereby granted, without written agreement and without
   8  * license or royalty fees, to use, copy, modify, and distribute this
   9  * software and its documentation for any purpose, provided that the
  10  * above copyright notice and the following two paragraphs appear in
  11  * all copies of this software.
  12  *
  13  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
  14  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
  15  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
  16  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  17  * DAMAGE.
  18  *
  19  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
  20  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  21  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  22  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
  23  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  24  *
  25  * Mozilla Author(s): Jonathan Kew
  26  * Google Author(s): Behdad Esfahbod
  27  */
  28 
  29 #define HB_SHAPER coretext
  30 
  31 #include "hb-private.hh"
  32 #include "hb-debug.hh"
  33 #include "hb-shaper-impl-private.hh"
  34 
  35 #include "hb-coretext.h"
  36 #include <math.h>
  37 
  38 /* https://developer.apple.com/documentation/coretext/1508745-ctfontcreatewithgraphicsfont */
  39 #define HB_CORETEXT_DEFAULT_FONT_SIZE 12.f
  40 
  41 static CGFloat
  42 coretext_font_size (float ptem)
  43 {
  44   /* CoreText points are CSS pixels (96 per inch),
  45    * NOT typographic points (72 per inch).
  46    *
  47    * https://developer.apple.com/library/content/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html
  48    */
  49   ptem *= 96.f / 72.f;
  50   return ptem <= 0.f ? HB_CORETEXT_DEFAULT_FONT_SIZE : ptem;
  51 }
  52 
  53 static void
  54 release_table_data (void *user_data)
  55 {
  56   CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
  57   CFRelease(cf_data);
  58 }
  59 
  60 static hb_blob_t *
  61 reference_table  (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
  62 {
  63   CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
  64   CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
  65   if (unlikely (!cf_data))
  66     return nullptr;
  67 
  68   const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
  69   const size_t length = CFDataGetLength (cf_data);
  70   if (!data || !length)
  71     return nullptr;
  72 
  73   return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
  74                          reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
  75                          release_table_data);
  76 }
  77 
  78 static void
  79 _hb_cg_font_release (void *data)
  80 {
  81   CGFontRelease ((CGFontRef) data);
  82 }
  83 
  84 hb_face_t *
  85 hb_coretext_face_create (CGFontRef cg_font)
  86 {
  87   return hb_face_create_for_tables (reference_table, CGFontRetain (cg_font), _hb_cg_font_release);
  88 }
  89 
  90 HB_SHAPER_DATA_ENSURE_DEFINE(coretext, face)
  91 HB_SHAPER_DATA_ENSURE_DEFINE_WITH_CONDITION(coretext, font,
  92         fabs (CTFontGetSize((CTFontRef) data) - coretext_font_size (font->ptem)) <= .5
  93 )
  94 
  95 /*
  96  * shaper face data
  97  */
  98 
  99 static CTFontDescriptorRef
 100 get_last_resort_font_desc (void)
 101 {
 102   // TODO Handle allocation failures?
 103   CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
 104   CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
 105                                            (const void **) &last_resort,
 106                                            1,
 107                                            &kCFTypeArrayCallBacks);
 108   CFRelease (last_resort);
 109   CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
 110                                                    (const void **) &kCTFontCascadeListAttribute,
 111                                                    (const void **) &cascade_list,
 112                                                    1,
 113                                                    &kCFTypeDictionaryKeyCallBacks,
 114                                                    &kCFTypeDictionaryValueCallBacks);
 115   CFRelease (cascade_list);
 116 
 117   CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
 118   CFRelease (attributes);
 119   return font_desc;
 120 }
 121 
 122 static void
 123 release_data (void *info, const void *data, size_t size)
 124 {
 125   assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
 126           hb_blob_get_data ((hb_blob_t *) info, nullptr) == data);
 127 
 128   hb_blob_destroy ((hb_blob_t *) info);
 129 }
 130 
 131 static CGFontRef
 132 create_cg_font (hb_face_t *face)
 133 {
 134   CGFontRef cg_font = nullptr;
 135   if (face->destroy == _hb_cg_font_release)
 136   {
 137     cg_font = CGFontRetain ((CGFontRef) face->user_data);
 138   }
 139   else
 140   {
 141     hb_blob_t *blob = hb_face_reference_blob (face);
 142     unsigned int blob_length;
 143     const char *blob_data = hb_blob_get_data (blob, &blob_length);
 144     if (unlikely (!blob_length))
 145       DEBUG_MSG (CORETEXT, face, "Face has empty blob");
 146 
 147     CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
 148     if (likely (provider))
 149     {
 150       cg_font = CGFontCreateWithDataProvider (provider);
 151       if (unlikely (!cg_font))
 152         DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
 153       CGDataProviderRelease (provider);
 154     }
 155   }
 156   return cg_font;
 157 }
 158 
 159 static CTFontRef
 160 create_ct_font (CGFontRef cg_font, CGFloat font_size)
 161 {
 162   CTFontRef ct_font = nullptr;
 163 
 164   /* CoreText does not enable trak table usage / tracking when creating a CTFont
 165    * using CTFontCreateWithGraphicsFont. The only way of enabling tracking seems
 166    * to be through the CTFontCreateUIFontForLanguage call. */
 167   CFStringRef cg_postscript_name = CGFontCopyPostScriptName (cg_font);
 168   if (CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSText")) ||
 169       CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSDisplay")))
 170   {
 171     CTFontUIFontType font_type = kCTFontUIFontSystem;
 172     if (CFStringHasSuffix (cg_postscript_name, CFSTR ("-Bold")))
 173       font_type = kCTFontUIFontEmphasizedSystem;
 174 
 175     ct_font = CTFontCreateUIFontForLanguage (font_type, font_size, nullptr);
 176     CFStringRef ct_result_name = CTFontCopyPostScriptName(ct_font);
 177     if (CFStringCompare (ct_result_name, cg_postscript_name, 0) != kCFCompareEqualTo)
 178     {
 179       CFRelease(ct_font);
 180       ct_font = nullptr;
 181     }
 182     CFRelease (ct_result_name);
 183   }
 184   CFRelease (cg_postscript_name);
 185 
 186   if (!ct_font)
 187     ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, nullptr, nullptr);
 188 
 189   if (unlikely (!ct_font)) {
 190     DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
 191     return nullptr;
 192   }
 193 
 194   /* crbug.com/576941 and crbug.com/625902 and the investigation in the latter
 195    * bug indicate that the cascade list reconfiguration occasionally causes
 196    * crashes in CoreText on OS X 10.9, thus let's skip this step on older
 197    * operating system versions. Except for the emoji font, where _not_
 198    * reconfiguring the cascade list causes CoreText crashes. For details, see
 199    * crbug.com/549610 */
 200   // 0x00070000 stands for "kCTVersionNumber10_10", see CoreText.h
 201   if (&CTGetCoreTextVersion != nullptr && CTGetCoreTextVersion() < 0x00070000) {
 202     CFStringRef fontName = CTFontCopyPostScriptName (ct_font);
 203     bool isEmojiFont = CFStringCompare (fontName, CFSTR("AppleColorEmoji"), 0) == kCFCompareEqualTo;
 204     CFRelease (fontName);
 205     if (!isEmojiFont)
 206       return ct_font;
 207   }
 208 
 209   CFURLRef original_url = (CFURLRef)CTFontCopyAttribute(ct_font, kCTFontURLAttribute);
 210 
 211   /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
 212    * font fallback which we don't need anyway. */
 213   {
 214     CTFontDescriptorRef last_resort_font_desc = get_last_resort_font_desc ();
 215     CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, last_resort_font_desc);
 216     CFRelease (last_resort_font_desc);
 217     if (new_ct_font)
 218     {
 219       /* The CTFontCreateCopyWithAttributes call fails to stay on the same font
 220        * when reconfiguring the cascade list and may switch to a different font
 221        * when there are fonts that go by the same name, since the descriptor is
 222        * just name and size.
 223        *
 224        * Avoid reconfiguring the cascade lists if the new font is outside the
 225        * system locations that we cannot access from the sandboxed renderer
 226        * process in Blink. This can be detected by the new file URL location
 227        * that the newly found font points to. */
 228       CFURLRef new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
 229       // Keep reconfigured font if URL cannot be retrieved (seems to be the case
 230       // on Mac OS 10.12 Sierra), speculative fix for crbug.com/625606
 231       if (!original_url || !new_url || CFEqual (original_url, new_url)) {
 232         CFRelease (ct_font);
 233         ct_font = new_ct_font;
 234       } else {
 235         CFRelease (new_ct_font);
 236         DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
 237       }
 238       if (new_url)
 239         CFRelease (new_url);
 240     }
 241     else
 242       DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
 243   }
 244 
 245   if (original_url)
 246     CFRelease (original_url);
 247   return ct_font;
 248 }
 249 
 250 hb_coretext_shaper_face_data_t *
 251 _hb_coretext_shaper_face_data_create (hb_face_t *face)
 252 {
 253   CGFontRef cg_font = create_cg_font (face);
 254 
 255   if (unlikely (!cg_font))
 256   {
 257     DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
 258     return nullptr;
 259   }
 260 
 261   return (hb_coretext_shaper_face_data_t *) cg_font;
 262 }
 263 
 264 void
 265 _hb_coretext_shaper_face_data_destroy (hb_coretext_shaper_face_data_t *data)
 266 {
 267   CFRelease ((CGFontRef) data);
 268 }
 269 
 270 /*
 271  * Since: 0.9.10
 272  */
 273 CGFontRef
 274 hb_coretext_face_get_cg_font (hb_face_t *face)
 275 {
 276   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return nullptr;
 277   return (CGFontRef) HB_SHAPER_DATA_GET (face);
 278 }
 279 
 280 
 281 /*
 282  * shaper font data
 283  */
 284 
 285 hb_coretext_shaper_font_data_t *
 286 _hb_coretext_shaper_font_data_create (hb_font_t *font)
 287 {
 288   hb_face_t *face = font->face;
 289   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return nullptr;
 290   CGFontRef cg_font = (CGFontRef) HB_SHAPER_DATA_GET (face);
 291 
 292   CTFontRef ct_font = create_ct_font (cg_font, coretext_font_size (font->ptem));
 293 
 294   if (unlikely (!ct_font))
 295   {
 296     DEBUG_MSG (CORETEXT, font, "CGFont creation failed..");
 297     return nullptr;
 298   }
 299 
 300   return (hb_coretext_shaper_font_data_t *) ct_font;
 301 }
 302 
 303 void
 304 _hb_coretext_shaper_font_data_destroy (hb_coretext_shaper_font_data_t *data)
 305 {
 306   CFRelease ((CTFontRef) data);
 307 }
 308 
 309 
 310 /*
 311  * shaper shape_plan data
 312  */
 313 
 314 struct hb_coretext_shaper_shape_plan_data_t {};
 315 
 316 hb_coretext_shaper_shape_plan_data_t *
 317 _hb_coretext_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
 318                                              const hb_feature_t *user_features HB_UNUSED,
 319                                              unsigned int        num_user_features HB_UNUSED,
 320                                              const int          *coords HB_UNUSED,
 321                                              unsigned int        num_coords HB_UNUSED)
 322 {
 323   return (hb_coretext_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
 324 }
 325 
 326 void
 327 _hb_coretext_shaper_shape_plan_data_destroy (hb_coretext_shaper_shape_plan_data_t *data HB_UNUSED)
 328 {
 329 }
 330 
 331 CTFontRef
 332 hb_coretext_font_get_ct_font (hb_font_t *font)
 333 {
 334   if (unlikely (!hb_coretext_shaper_font_data_ensure (font))) return nullptr;
 335   return (CTFontRef)HB_SHAPER_DATA_GET (font);
 336 }
 337 
 338 
 339 /*
 340  * shaper
 341  */
 342 
 343 struct feature_record_t {
 344   unsigned int feature;
 345   unsigned int setting;
 346 };
 347 
 348 struct active_feature_t {
 349   feature_record_t rec;
 350   unsigned int order;
 351 
 352   static int cmp (const void *pa, const void *pb) {
 353     const active_feature_t *a = (const active_feature_t *) pa;
 354     const active_feature_t *b = (const active_feature_t *) pb;
 355     return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
 356            a->order < b->order ? -1 : a->order > b->order ? 1 :
 357            a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
 358            0;
 359   }
 360   bool operator== (const active_feature_t *f) {
 361     return cmp (this, f) == 0;
 362   }
 363 };
 364 
 365 struct feature_event_t {
 366   unsigned int index;
 367   bool start;
 368   active_feature_t feature;
 369 
 370   static int cmp (const void *pa, const void *pb) {
 371     const feature_event_t *a = (const feature_event_t *) pa;
 372     const feature_event_t *b = (const feature_event_t *) pb;
 373     return a->index < b->index ? -1 : a->index > b->index ? 1 :
 374            a->start < b->start ? -1 : a->start > b->start ? 1 :
 375            active_feature_t::cmp (&a->feature, &b->feature);
 376   }
 377 };
 378 
 379 struct range_record_t {
 380   CTFontRef font;
 381   unsigned int index_first; /* == start */
 382   unsigned int index_last;  /* == end - 1 */
 383 };
 384 
 385 
 386 /* The following enum members are added in OS X 10.8. */
 387 #define kAltHalfWidthTextSelector               6
 388 #define kAltProportionalTextSelector            5
 389 #define kAlternateHorizKanaOffSelector          1
 390 #define kAlternateHorizKanaOnSelector           0
 391 #define kAlternateKanaType                      34
 392 #define kAlternateVertKanaOffSelector           3
 393 #define kAlternateVertKanaOnSelector            2
 394 #define kCaseSensitiveLayoutOffSelector         1
 395 #define kCaseSensitiveLayoutOnSelector          0
 396 #define kCaseSensitiveLayoutType                33
 397 #define kCaseSensitiveSpacingOffSelector        3
 398 #define kCaseSensitiveSpacingOnSelector         2
 399 #define kContextualAlternatesOffSelector        1
 400 #define kContextualAlternatesOnSelector         0
 401 #define kContextualAlternatesType               36
 402 #define kContextualLigaturesOffSelector         19
 403 #define kContextualLigaturesOnSelector          18
 404 #define kContextualSwashAlternatesOffSelector   5
 405 #define kContextualSwashAlternatesOnSelector    4
 406 #define kDefaultLowerCaseSelector               0
 407 #define kDefaultUpperCaseSelector               0
 408 #define kHistoricalLigaturesOffSelector         21
 409 #define kHistoricalLigaturesOnSelector          20
 410 #define kHojoCharactersSelector                 12
 411 #define kJIS2004CharactersSelector              11
 412 #define kLowerCasePetiteCapsSelector            2
 413 #define kLowerCaseSmallCapsSelector             1
 414 #define kLowerCaseType                          37
 415 #define kMathematicalGreekOffSelector           11
 416 #define kMathematicalGreekOnSelector            10
 417 #define kNLCCharactersSelector                  13
 418 #define kQuarterWidthTextSelector               4
 419 #define kScientificInferiorsSelector            4
 420 #define kStylisticAltEightOffSelector           17
 421 #define kStylisticAltEightOnSelector            16
 422 #define kStylisticAltEighteenOffSelector        37
 423 #define kStylisticAltEighteenOnSelector         36
 424 #define kStylisticAltElevenOffSelector          23
 425 #define kStylisticAltElevenOnSelector           22
 426 #define kStylisticAltFifteenOffSelector         31
 427 #define kStylisticAltFifteenOnSelector          30
 428 #define kStylisticAltFiveOffSelector            11
 429 #define kStylisticAltFiveOnSelector             10
 430 #define kStylisticAltFourOffSelector            9
 431 #define kStylisticAltFourOnSelector             8
 432 #define kStylisticAltFourteenOffSelector        29
 433 #define kStylisticAltFourteenOnSelector         28
 434 #define kStylisticAltNineOffSelector            19
 435 #define kStylisticAltNineOnSelector             18
 436 #define kStylisticAltNineteenOffSelector        39
 437 #define kStylisticAltNineteenOnSelector         38
 438 #define kStylisticAltOneOffSelector             3
 439 #define kStylisticAltOneOnSelector              2
 440 #define kStylisticAltSevenOffSelector           15
 441 #define kStylisticAltSevenOnSelector            14
 442 #define kStylisticAltSeventeenOffSelector       35
 443 #define kStylisticAltSeventeenOnSelector        34
 444 #define kStylisticAltSixOffSelector             13
 445 #define kStylisticAltSixOnSelector              12
 446 #define kStylisticAltSixteenOffSelector         33
 447 #define kStylisticAltSixteenOnSelector          32
 448 #define kStylisticAltTenOffSelector             21
 449 #define kStylisticAltTenOnSelector              20
 450 #define kStylisticAltThirteenOffSelector        27
 451 #define kStylisticAltThirteenOnSelector         26
 452 #define kStylisticAltThreeOffSelector           7
 453 #define kStylisticAltThreeOnSelector            6
 454 #define kStylisticAltTwelveOffSelector          25
 455 #define kStylisticAltTwelveOnSelector           24
 456 #define kStylisticAltTwentyOffSelector          41
 457 #define kStylisticAltTwentyOnSelector           40
 458 #define kStylisticAltTwoOffSelector             5
 459 #define kStylisticAltTwoOnSelector              4
 460 #define kStylisticAlternativesType              35
 461 #define kSwashAlternatesOffSelector             3
 462 #define kSwashAlternatesOnSelector              2
 463 #define kThirdWidthTextSelector                 3
 464 #define kTraditionalNamesCharactersSelector     14
 465 #define kUpperCasePetiteCapsSelector            2
 466 #define kUpperCaseSmallCapsSelector             1
 467 #define kUpperCaseType                          38
 468 
 469 /* Table data courtesy of Apple. */
 470 static const struct feature_mapping_t {
 471     FourCharCode otFeatureTag;
 472     uint16_t aatFeatureType;
 473     uint16_t selectorToEnable;
 474     uint16_t selectorToDisable;
 475 } feature_mappings[] = {
 476     { 'c2pc',   kUpperCaseType,             kUpperCasePetiteCapsSelector,           kDefaultUpperCaseSelector },
 477     { 'c2sc',   kUpperCaseType,             kUpperCaseSmallCapsSelector,            kDefaultUpperCaseSelector },
 478     { 'calt',   kContextualAlternatesType,  kContextualAlternatesOnSelector,        kContextualAlternatesOffSelector },
 479     { 'case',   kCaseSensitiveLayoutType,   kCaseSensitiveLayoutOnSelector,         kCaseSensitiveLayoutOffSelector },
 480     { 'clig',   kLigaturesType,             kContextualLigaturesOnSelector,         kContextualLigaturesOffSelector },
 481     { 'cpsp',   kCaseSensitiveLayoutType,   kCaseSensitiveSpacingOnSelector,        kCaseSensitiveSpacingOffSelector },
 482     { 'cswh',   kContextualAlternatesType,  kContextualSwashAlternatesOnSelector,   kContextualSwashAlternatesOffSelector },
 483     { 'dlig',   kLigaturesType,             kRareLigaturesOnSelector,               kRareLigaturesOffSelector },
 484     { 'expt',   kCharacterShapeType,        kExpertCharactersSelector,              16 },
 485     { 'frac',   kFractionsType,             kDiagonalFractionsSelector,             kNoFractionsSelector },
 486     { 'fwid',   kTextSpacingType,           kMonospacedTextSelector,                7 },
 487     { 'halt',   kTextSpacingType,           kAltHalfWidthTextSelector,              7 },
 488     { 'hist',   kLigaturesType,             kHistoricalLigaturesOnSelector,         kHistoricalLigaturesOffSelector },
 489     { 'hkna',   kAlternateKanaType,         kAlternateHorizKanaOnSelector,          kAlternateHorizKanaOffSelector, },
 490     { 'hlig',   kLigaturesType,             kHistoricalLigaturesOnSelector,         kHistoricalLigaturesOffSelector },
 491     { 'hngl',   kTransliterationType,       kHanjaToHangulSelector,                 kNoTransliterationSelector },
 492     { 'hojo',   kCharacterShapeType,        kHojoCharactersSelector,                16 },
 493     { 'hwid',   kTextSpacingType,           kHalfWidthTextSelector,                 7 },
 494     { 'ital',   kItalicCJKRomanType,        kCJKItalicRomanOnSelector,              kCJKItalicRomanOffSelector },
 495     { 'jp04',   kCharacterShapeType,        kJIS2004CharactersSelector,             16 },
 496     { 'jp78',   kCharacterShapeType,        kJIS1978CharactersSelector,             16 },
 497     { 'jp83',   kCharacterShapeType,        kJIS1983CharactersSelector,             16 },
 498     { 'jp90',   kCharacterShapeType,        kJIS1990CharactersSelector,             16 },
 499     { 'liga',   kLigaturesType,             kCommonLigaturesOnSelector,             kCommonLigaturesOffSelector },
 500     { 'lnum',   kNumberCaseType,            kUpperCaseNumbersSelector,              2 },
 501     { 'mgrk',   kMathematicalExtrasType,    kMathematicalGreekOnSelector,           kMathematicalGreekOffSelector },
 502     { 'nlck',   kCharacterShapeType,        kNLCCharactersSelector,                 16 },
 503     { 'onum',   kNumberCaseType,            kLowerCaseNumbersSelector,              2 },
 504     { 'ordn',   kVerticalPositionType,      kOrdinalsSelector,                      kNormalPositionSelector },
 505     { 'palt',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
 506     { 'pcap',   kLowerCaseType,             kLowerCasePetiteCapsSelector,           kDefaultLowerCaseSelector },
 507     { 'pkna',   kTextSpacingType,           kProportionalTextSelector,              7 },
 508     { 'pnum',   kNumberSpacingType,         kProportionalNumbersSelector,           4 },
 509     { 'pwid',   kTextSpacingType,           kProportionalTextSelector,              7 },
 510     { 'qwid',   kTextSpacingType,           kQuarterWidthTextSelector,              7 },
 511     { 'ruby',   kRubyKanaType,              kRubyKanaOnSelector,                    kRubyKanaOffSelector },
 512     { 'sinf',   kVerticalPositionType,      kScientificInferiorsSelector,           kNormalPositionSelector },
 513     { 'smcp',   kLowerCaseType,             kLowerCaseSmallCapsSelector,            kDefaultLowerCaseSelector },
 514     { 'smpl',   kCharacterShapeType,        kSimplifiedCharactersSelector,          16 },
 515     { 'ss01',   kStylisticAlternativesType, kStylisticAltOneOnSelector,             kStylisticAltOneOffSelector },
 516     { 'ss02',   kStylisticAlternativesType, kStylisticAltTwoOnSelector,             kStylisticAltTwoOffSelector },
 517     { 'ss03',   kStylisticAlternativesType, kStylisticAltThreeOnSelector,           kStylisticAltThreeOffSelector },
 518     { 'ss04',   kStylisticAlternativesType, kStylisticAltFourOnSelector,            kStylisticAltFourOffSelector },
 519     { 'ss05',   kStylisticAlternativesType, kStylisticAltFiveOnSelector,            kStylisticAltFiveOffSelector },
 520     { 'ss06',   kStylisticAlternativesType, kStylisticAltSixOnSelector,             kStylisticAltSixOffSelector },
 521     { 'ss07',   kStylisticAlternativesType, kStylisticAltSevenOnSelector,           kStylisticAltSevenOffSelector },
 522     { 'ss08',   kStylisticAlternativesType, kStylisticAltEightOnSelector,           kStylisticAltEightOffSelector },
 523     { 'ss09',   kStylisticAlternativesType, kStylisticAltNineOnSelector,            kStylisticAltNineOffSelector },
 524     { 'ss10',   kStylisticAlternativesType, kStylisticAltTenOnSelector,             kStylisticAltTenOffSelector },
 525     { 'ss11',   kStylisticAlternativesType, kStylisticAltElevenOnSelector,          kStylisticAltElevenOffSelector },
 526     { 'ss12',   kStylisticAlternativesType, kStylisticAltTwelveOnSelector,          kStylisticAltTwelveOffSelector },
 527     { 'ss13',   kStylisticAlternativesType, kStylisticAltThirteenOnSelector,        kStylisticAltThirteenOffSelector },
 528     { 'ss14',   kStylisticAlternativesType, kStylisticAltFourteenOnSelector,        kStylisticAltFourteenOffSelector },
 529     { 'ss15',   kStylisticAlternativesType, kStylisticAltFifteenOnSelector,         kStylisticAltFifteenOffSelector },
 530     { 'ss16',   kStylisticAlternativesType, kStylisticAltSixteenOnSelector,         kStylisticAltSixteenOffSelector },
 531     { 'ss17',   kStylisticAlternativesType, kStylisticAltSeventeenOnSelector,       kStylisticAltSeventeenOffSelector },
 532     { 'ss18',   kStylisticAlternativesType, kStylisticAltEighteenOnSelector,        kStylisticAltEighteenOffSelector },
 533     { 'ss19',   kStylisticAlternativesType, kStylisticAltNineteenOnSelector,        kStylisticAltNineteenOffSelector },
 534     { 'ss20',   kStylisticAlternativesType, kStylisticAltTwentyOnSelector,          kStylisticAltTwentyOffSelector },
 535     { 'subs',   kVerticalPositionType,      kInferiorsSelector,                     kNormalPositionSelector },
 536     { 'sups',   kVerticalPositionType,      kSuperiorsSelector,                     kNormalPositionSelector },
 537     { 'swsh',   kContextualAlternatesType,  kSwashAlternatesOnSelector,             kSwashAlternatesOffSelector },
 538     { 'titl',   kStyleOptionsType,          kTitlingCapsSelector,                   kNoStyleOptionsSelector },
 539     { 'tnam',   kCharacterShapeType,        kTraditionalNamesCharactersSelector,    16 },
 540     { 'tnum',   kNumberSpacingType,         kMonospacedNumbersSelector,             4 },
 541     { 'trad',   kCharacterShapeType,        kTraditionalCharactersSelector,         16 },
 542     { 'twid',   kTextSpacingType,           kThirdWidthTextSelector,                7 },
 543     { 'unic',   kLetterCaseType,            14,                                     15 },
 544     { 'valt',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
 545     { 'vert',   kVerticalSubstitutionType,  kSubstituteVerticalFormsOnSelector,     kSubstituteVerticalFormsOffSelector },
 546     { 'vhal',   kTextSpacingType,           kAltHalfWidthTextSelector,              7 },
 547     { 'vkna',   kAlternateKanaType,         kAlternateVertKanaOnSelector,           kAlternateVertKanaOffSelector },
 548     { 'vpal',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
 549     { 'vrt2',   kVerticalSubstitutionType,  kSubstituteVerticalFormsOnSelector,     kSubstituteVerticalFormsOffSelector },
 550     { 'zero',   kTypographicExtrasType,     kSlashedZeroOnSelector,                 kSlashedZeroOffSelector },
 551 };
 552 
 553 static int
 554 _hb_feature_mapping_cmp (const void *key_, const void *entry_)
 555 {
 556   unsigned int key = * (unsigned int *) key_;
 557   const feature_mapping_t * entry = (const feature_mapping_t *) entry_;
 558   return key < entry->otFeatureTag ? -1 :
 559          key > entry->otFeatureTag ? 1 :
 560          0;
 561 }
 562 
 563 hb_bool_t
 564 _hb_coretext_shape (hb_shape_plan_t    *shape_plan,
 565                     hb_font_t          *font,
 566                     hb_buffer_t        *buffer,
 567                     const hb_feature_t *features,
 568                     unsigned int        num_features)
 569 {
 570   hb_face_t *face = font->face;
 571   CGFontRef cg_font = (CGFontRef) HB_SHAPER_DATA_GET (face);
 572   CTFontRef ct_font = (CTFontRef) HB_SHAPER_DATA_GET (font);
 573 
 574   CGFloat ct_font_size = CTFontGetSize (ct_font);
 575   CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
 576   CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
 577 
 578   /* Attach marks to their bases, to match the 'ot' shaper.
 579    * Adapted from hb-ot-shape:hb_form_clusters().
 580    * Note that this only makes us be closer to the 'ot' shaper,
 581    * but by no means the same.  For example, if there's
 582    * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
 583    * continue pointing to B2 even though B2 was merged into B1's
 584    * cluster... */
 585   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
 586   {
 587     hb_unicode_funcs_t *unicode = buffer->unicode;
 588     unsigned int count = buffer->len;
 589     hb_glyph_info_t *info = buffer->info;
 590     for (unsigned int i = 1; i < count; i++)
 591       if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
 592         buffer->merge_clusters (i - 1, i + 1);
 593   }
 594 
 595   hb_auto_array_t<feature_record_t> feature_records;
 596   hb_auto_array_t<range_record_t> range_records;
 597 
 598   /*
 599    * Set up features.
 600    * (copied + modified from code from hb-uniscribe.cc)
 601    */
 602   if (num_features)
 603   {
 604     /* Sort features by start/end events. */
 605     hb_auto_array_t<feature_event_t> feature_events;
 606     for (unsigned int i = 0; i < num_features; i++)
 607     {
 608       const feature_mapping_t * mapping = (const feature_mapping_t *) bsearch (&features[i].tag,
 609                                                                                feature_mappings,
 610                                                                                ARRAY_LENGTH (feature_mappings),
 611                                                                                sizeof (feature_mappings[0]),
 612                                                                                _hb_feature_mapping_cmp);
 613       if (!mapping)
 614         continue;
 615 
 616       active_feature_t feature;
 617       feature.rec.feature = mapping->aatFeatureType;
 618       feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
 619       feature.order = i;
 620 
 621       feature_event_t *event;
 622 
 623       event = feature_events.push ();
 624       if (unlikely (!event))
 625         goto fail_features;
 626       event->index = features[i].start;
 627       event->start = true;
 628       event->feature = feature;
 629 
 630       event = feature_events.push ();
 631       if (unlikely (!event))
 632         goto fail_features;
 633       event->index = features[i].end;
 634       event->start = false;
 635       event->feature = feature;
 636     }
 637     feature_events.qsort ();
 638     /* Add a strategic final event. */
 639     {
 640       active_feature_t feature;
 641       feature.rec.feature = HB_TAG_NONE;
 642       feature.rec.setting = 0;
 643       feature.order = num_features + 1;
 644 
 645       feature_event_t *event = feature_events.push ();
 646       if (unlikely (!event))
 647         goto fail_features;
 648       event->index = 0; /* This value does magic. */
 649       event->start = false;
 650       event->feature = feature;
 651     }
 652 
 653     /* Scan events and save features for each range. */
 654     hb_auto_array_t<active_feature_t> active_features;
 655     unsigned int last_index = 0;
 656     for (unsigned int i = 0; i < feature_events.len; i++)
 657     {
 658       feature_event_t *event = &feature_events[i];
 659 
 660       if (event->index != last_index)
 661       {
 662         /* Save a snapshot of active features and the range. */
 663         range_record_t *range = range_records.push ();
 664         if (unlikely (!range))
 665           goto fail_features;
 666 
 667         if (active_features.len)
 668         {
 669           CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
 670 
 671           /* TODO sort and resolve conflicting features? */
 672           /* active_features.qsort (); */
 673           for (unsigned int j = 0; j < active_features.len; j++)
 674           {
 675             CFStringRef keys[] = {
 676               kCTFontFeatureTypeIdentifierKey,
 677               kCTFontFeatureSelectorIdentifierKey
 678             };
 679             CFNumberRef values[] = {
 680               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
 681               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
 682             };
 683             static_assert ((ARRAY_LENGTH_CONST (keys) == ARRAY_LENGTH_CONST (values)), "");
 684             CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
 685                                                        (const void **) keys,
 686                                                        (const void **) values,
 687                                                        ARRAY_LENGTH (keys),
 688                                                        &kCFTypeDictionaryKeyCallBacks,
 689                                                        &kCFTypeDictionaryValueCallBacks);
 690             for (unsigned int i = 0; i < ARRAY_LENGTH (values); i++)
 691               CFRelease (values[i]);
 692 
 693             CFArrayAppendValue (features_array, dict);
 694             CFRelease (dict);
 695 
 696           }
 697 
 698           CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
 699                                                            (const void **) &kCTFontFeatureSettingsAttribute,
 700                                                            (const void **) &features_array,
 701                                                            1,
 702                                                            &kCFTypeDictionaryKeyCallBacks,
 703                                                            &kCFTypeDictionaryValueCallBacks);
 704           CFRelease (features_array);
 705 
 706           CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
 707           CFRelease (attributes);
 708 
 709           range->font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, font_desc);
 710           CFRelease (font_desc);
 711         }
 712         else
 713         {
 714           range->font = nullptr;
 715         }
 716 
 717         range->index_first = last_index;
 718         range->index_last  = event->index - 1;
 719 
 720         last_index = event->index;
 721       }
 722 
 723       if (event->start) {
 724         active_feature_t *feature = active_features.push ();
 725         if (unlikely (!feature))
 726           goto fail_features;
 727         *feature = event->feature;
 728       } else {
 729         active_feature_t *feature = active_features.find (&event->feature);
 730         if (feature)
 731           active_features.remove (feature - active_features.array);
 732       }
 733     }
 734   }
 735   else
 736   {
 737   fail_features:
 738     num_features = 0;
 739   }
 740 
 741   unsigned int scratch_size;
 742   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
 743 
 744 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
 745   Type *name = (Type *) scratch; \
 746   { \
 747     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
 748     if (unlikely (_consumed > scratch_size)) \
 749     { \
 750       on_no_room; \
 751       assert (0); \
 752     } \
 753     scratch += _consumed; \
 754     scratch_size -= _consumed; \
 755   }
 756 
 757   ALLOCATE_ARRAY (UniChar, pchars, buffer->len * 2, /*nothing*/);
 758   unsigned int chars_len = 0;
 759   for (unsigned int i = 0; i < buffer->len; i++) {
 760     hb_codepoint_t c = buffer->info[i].codepoint;
 761     if (likely (c <= 0xFFFFu))
 762       pchars[chars_len++] = c;
 763     else if (unlikely (c > 0x10FFFFu))
 764       pchars[chars_len++] = 0xFFFDu;
 765     else {
 766       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
 767       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
 768     }
 769   }
 770 
 771   ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, /*nothing*/);
 772   chars_len = 0;
 773   for (unsigned int i = 0; i < buffer->len; i++)
 774   {
 775     hb_codepoint_t c = buffer->info[i].codepoint;
 776     unsigned int cluster = buffer->info[i].cluster;
 777     log_clusters[chars_len++] = cluster;
 778     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
 779       log_clusters[chars_len++] = cluster; /* Surrogates. */
 780   }
 781 
 782 #define FAIL(...) \
 783   HB_STMT_START { \
 784     DEBUG_MSG (CORETEXT, nullptr, __VA_ARGS__); \
 785     ret = false; \
 786     goto fail; \
 787   } HB_STMT_END;
 788 
 789   bool ret = true;
 790   CFStringRef string_ref = nullptr;
 791   CTLineRef line = nullptr;
 792 
 793   if (0)
 794   {
 795 resize_and_retry:
 796     DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
 797     /* string_ref uses the scratch-buffer for backing store, and line references
 798      * string_ref (via attr_string).  We must release those before resizing buffer. */
 799     assert (string_ref);
 800     assert (line);
 801     CFRelease (string_ref);
 802     CFRelease (line);
 803     string_ref = nullptr;
 804     line = nullptr;
 805 
 806     /* Get previous start-of-scratch-area, that we use later for readjusting
 807      * our existing scratch arrays. */
 808     unsigned int old_scratch_used;
 809     hb_buffer_t::scratch_buffer_t *old_scratch;
 810     old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
 811     old_scratch_used = scratch - old_scratch;
 812 
 813     if (unlikely (!buffer->ensure (buffer->allocated * 2)))
 814       FAIL ("Buffer resize failed");
 815 
 816     /* Adjust scratch, pchars, and log_cluster arrays.  This is ugly, but really the
 817      * cleanest way to do without completely restructuring the rest of this shaper. */
 818     scratch = buffer->get_scratch_buffer (&scratch_size);
 819     pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
 820     log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
 821     scratch += old_scratch_used;
 822     scratch_size -= old_scratch_used;
 823   }
 824   {
 825     string_ref = CFStringCreateWithCharactersNoCopy (nullptr,
 826                                                      pchars, chars_len,
 827                                                      kCFAllocatorNull);
 828     if (unlikely (!string_ref))
 829       FAIL ("CFStringCreateWithCharactersNoCopy failed");
 830 
 831     /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
 832     {
 833       CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
 834                                                                                   chars_len);
 835       if (unlikely (!attr_string))
 836         FAIL ("CFAttributedStringCreateMutable failed");
 837       CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
 838       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 839       {
 840         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 841                                         kCTVerticalFormsAttributeName, kCFBooleanTrue);
 842       }
 843 
 844       if (buffer->props.language)
 845       {
 846 /* What's the iOS equivalent of this check?
 847  * The symbols was introduced in iOS 7.0.
 848  * At any rate, our fallback is safe and works fine. */
 849 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
 850 #  define kCTLanguageAttributeName CFSTR ("NSLanguage")
 851 #endif
 852         CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
 853                                                             hb_language_to_string (buffer->props.language),
 854                                                             kCFStringEncodingUTF8,
 855                                                             kCFAllocatorNull);
 856         if (unlikely (!lang))
 857           FAIL ("CFStringCreateWithCStringNoCopy failed");
 858         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 859                                         kCTLanguageAttributeName, lang);
 860         CFRelease (lang);
 861       }
 862       CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 863                                       kCTFontAttributeName, ct_font);
 864 
 865       if (num_features && range_records.len)
 866       {
 867         unsigned int start = 0;
 868         range_record_t *last_range = &range_records[0];
 869         for (unsigned int k = 0; k < chars_len; k++)
 870         {
 871           range_record_t *range = last_range;
 872           while (log_clusters[k] < range->index_first)
 873             range--;
 874           while (log_clusters[k] > range->index_last)
 875             range++;
 876           if (range != last_range)
 877           {
 878             if (last_range->font)
 879               CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
 880                                               kCTFontAttributeName, last_range->font);
 881 
 882             start = k;
 883           }
 884 
 885           last_range = range;
 886         }
 887         if (start != chars_len && last_range->font)
 888           CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
 889                                           kCTFontAttributeName, last_range->font);
 890       }
 891       /* Enable/disable kern if requested.
 892        *
 893        * Note: once kern is disabled, reenabling it doesn't currently seem to work in CoreText.
 894        */
 895       if (num_features)
 896       {
 897         unsigned int zeroint = 0;
 898         CFNumberRef zero = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &zeroint);
 899         for (unsigned int i = 0; i < num_features; i++)
 900         {
 901           const hb_feature_t &feature = features[i];
 902           if (feature.tag == HB_TAG('k','e','r','n') &&
 903               feature.start < chars_len && feature.start < feature.end)
 904           {
 905             CFRange feature_range = CFRangeMake (feature.start,
 906                                                  MIN (feature.end, chars_len) - feature.start);
 907             if (feature.value)
 908               CFAttributedStringRemoveAttribute (attr_string, feature_range, kCTKernAttributeName);
 909             else
 910               CFAttributedStringSetAttribute (attr_string, feature_range, kCTKernAttributeName, zero);
 911           }
 912         }
 913         CFRelease (zero);
 914       }
 915 
 916       int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
 917       CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
 918       CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
 919                                                     (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
 920                                                     (const void **) &level_number,
 921                                                     1,
 922                                                     &kCFTypeDictionaryKeyCallBacks,
 923                                                     &kCFTypeDictionaryValueCallBacks);
 924       CFRelease (level_number);
 925       if (unlikely (!options))
 926         FAIL ("CFDictionaryCreate failed");
 927 
 928       CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
 929       CFRelease (options);
 930       CFRelease (attr_string);
 931       if (unlikely (!typesetter))
 932         FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
 933 
 934       line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
 935       CFRelease (typesetter);
 936       if (unlikely (!line))
 937         FAIL ("CTTypesetterCreateLine failed");
 938     }
 939 
 940     CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
 941     unsigned int num_runs = CFArrayGetCount (glyph_runs);
 942     DEBUG_MSG (CORETEXT, nullptr, "Num runs: %d", num_runs);
 943 
 944     buffer->len = 0;
 945     uint32_t status_and = ~0, status_or = 0;
 946     double advances_so_far = 0;
 947     /* For right-to-left runs, CoreText returns the glyphs positioned such that
 948      * any trailing whitespace is to the left of (0,0).  Adjust coordinate system
 949      * to fix for that.  Test with any RTL string with trailing spaces.
 950      * https://code.google.com/p/chromium/issues/detail?id=469028
 951      */
 952     if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
 953     {
 954       advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
 955       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 956           advances_so_far = -advances_so_far;
 957     }
 958 
 959     const CFRange range_all = CFRangeMake (0, 0);
 960 
 961     for (unsigned int i = 0; i < num_runs; i++)
 962     {
 963       CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
 964       CTRunStatus run_status = CTRunGetStatus (run);
 965       status_or  |= run_status;
 966       status_and &= run_status;
 967       DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
 968       double run_advance = CTRunGetTypographicBounds (run, range_all, nullptr, nullptr, nullptr);
 969       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 970           run_advance = -run_advance;
 971       DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
 972 
 973       /* CoreText does automatic font fallback (AKA "cascading") for  characters
 974        * not supported by the requested font, and provides no way to turn it off,
 975        * so we must detect if the returned run uses a font other than the requested
 976        * one and fill in the buffer with .notdef glyphs instead of random glyph
 977        * indices from a different font.
 978        */
 979       CFDictionaryRef attributes = CTRunGetAttributes (run);
 980       CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
 981       if (!CFEqual (run_ct_font, ct_font))
 982       {
 983         /* The run doesn't use our main font instance.  We have to figure out
 984          * whether font fallback happened, or this is just CoreText giving us
 985          * another CTFont using the same underlying CGFont.  CoreText seems
 986          * to do that in a variety of situations, one of which being vertical
 987          * text, but also perhaps for caching reasons.
 988          *
 989          * First, see if it uses any of our subfonts created to set font features...
 990          *
 991          * Next, compare the CGFont to the one we used to create our fonts.
 992          * Even this doesn't work all the time.
 993          *
 994          * Finally, we compare PS names, which I don't think are unique...
 995          *
 996          * Looks like if we really want to be sure here we have to modify the
 997          * font to change the name table, similar to what we do in the uniscribe
 998          * backend.
 999          *
1000          * However, even that wouldn't work if we were passed in the CGFont to
1001          * construct a hb_face to begin with.
1002          *
1003          * See: http://github.com/behdad/harfbuzz/pull/36
1004          *
1005          * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
1006          */
1007         bool matched = false;
1008         for (unsigned int i = 0; i < range_records.len; i++)
1009           if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
1010           {
1011             matched = true;
1012             break;
1013           }
1014         if (!matched)
1015         {
1016           CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, 0);
1017           if (run_cg_font)
1018           {
1019             matched = CFEqual (run_cg_font, cg_font);
1020             CFRelease (run_cg_font);
1021           }
1022         }
1023         if (!matched)
1024         {
1025           CFStringRef font_ps_name = CTFontCopyName (ct_font, kCTFontPostScriptNameKey);
1026           CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
1027           CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
1028           CFRelease (run_ps_name);
1029           CFRelease (font_ps_name);
1030           if (result == kCFCompareEqualTo)
1031             matched = true;
1032         }
1033         if (!matched)
1034         {
1035           CFRange range = CTRunGetStringRange (run);
1036           DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
1037                      range.location, range.location + range.length);
1038           if (!buffer->ensure_inplace (buffer->len + range.length))
1039             goto resize_and_retry;
1040           hb_glyph_info_t *info = buffer->info + buffer->len;
1041 
1042           hb_codepoint_t notdef = 0;
1043           hb_direction_t dir = buffer->props.direction;
1044           hb_position_t x_advance, y_advance, x_offset, y_offset;
1045           hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);
1046           hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);
1047           hb_position_t advance = x_advance + y_advance;
1048           x_offset = -x_offset;
1049           y_offset = -y_offset;
1050 
1051           unsigned int old_len = buffer->len;
1052           for (CFIndex j = range.location; j < range.location + range.length; j++)
1053           {
1054               UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
1055               if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
1056               {
1057                 ch = CFStringGetCharacterAtIndex (string_ref, j - 1);
1058                 if (hb_in_range<UniChar> (ch, 0xD800u, 0xDBFFu))
1059                   /* This is the second of a surrogate pair.  Don't need .notdef
1060                    * for this one. */
1061                   continue;
1062               }
1063               if (buffer->unicode->is_default_ignorable (ch))
1064                 continue;
1065 
1066               info->codepoint = notdef;
1067               info->cluster = log_clusters[j];
1068 
1069               info->mask = advance;
1070               info->var1.i32 = x_offset;
1071               info->var2.i32 = y_offset;
1072 
1073               info++;
1074               buffer->len++;
1075           }
1076           if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
1077             buffer->reverse_range (old_len, buffer->len);
1078           advances_so_far += run_advance;
1079           continue;
1080         }
1081       }
1082 
1083       unsigned int num_glyphs = CTRunGetGlyphCount (run);
1084       if (num_glyphs == 0)
1085         continue;
1086 
1087       if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1088         goto resize_and_retry;
1089 
1090       hb_glyph_info_t *run_info = buffer->info + buffer->len;
1091 
1092       /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
1093        * succeed, and so copying data to our own buffer will be rare.  Reports
1094        * have it that this changed in OS X 10.10 Yosemite, and nullptr is returned
1095        * frequently.  At any rate, we can test that codepath by setting USE_PTR
1096        * to false. */
1097 
1098 #define USE_PTR true
1099 
1100 #define SCRATCH_SAVE() \
1101   unsigned int scratch_size_saved = scratch_size; \
1102   hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1103 
1104 #define SCRATCH_RESTORE() \
1105   scratch_size = scratch_size_saved; \
1106   scratch = scratch_saved;
1107 
1108       { /* Setup glyphs */
1109         SCRATCH_SAVE();
1110         const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : nullptr;
1111         if (!glyphs) {
1112           ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1113           CTRunGetGlyphs (run, range_all, glyph_buf);
1114           glyphs = glyph_buf;
1115         }
1116         const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : nullptr;
1117         if (!string_indices) {
1118           ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
1119           CTRunGetStringIndices (run, range_all, index_buf);
1120           string_indices = index_buf;
1121         }
1122         hb_glyph_info_t *info = run_info;
1123         for (unsigned int j = 0; j < num_glyphs; j++)
1124         {
1125           info->codepoint = glyphs[j];
1126           info->cluster = log_clusters[string_indices[j]];
1127           info++;
1128         }
1129         SCRATCH_RESTORE();
1130       }
1131       {
1132         /* Setup positions.
1133          * Note that CoreText does not return advances for glyphs.  As such,
1134          * for all but last glyph, we use the delta position to next glyph as
1135          * advance (in the advance direction only), and for last glyph we set
1136          * whatever is needed to make the whole run's advance add up. */
1137         SCRATCH_SAVE();
1138         const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : nullptr;
1139         if (!positions) {
1140           ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1141           CTRunGetPositions (run, range_all, position_buf);
1142           positions = position_buf;
1143         }
1144         hb_glyph_info_t *info = run_info;
1145         if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1146         {
1147           hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1148           for (unsigned int j = 0; j < num_glyphs; j++)
1149           {
1150             double advance;
1151             if (likely (j + 1 < num_glyphs))
1152               advance = positions[j + 1].x - positions[j].x;
1153             else /* last glyph */
1154               advance = run_advance - (positions[j].x - positions[0].x);
1155             info->mask = advance * x_mult;
1156             info->var1.i32 = x_offset;
1157             info->var2.i32 = positions[j].y * y_mult;
1158             info++;
1159           }
1160         }
1161         else
1162         {
1163           hb_position_t y_offset = (positions[0].y - advances_so_far) * y_mult;
1164           for (unsigned int j = 0; j < num_glyphs; j++)
1165           {
1166             double advance;
1167             if (likely (j + 1 < num_glyphs))
1168               advance = positions[j + 1].y - positions[j].y;
1169             else /* last glyph */
1170               advance = run_advance - (positions[j].y - positions[0].y);
1171             info->mask = advance * y_mult;
1172             info->var1.i32 = positions[j].x * x_mult;
1173             info->var2.i32 = y_offset;
1174             info++;
1175           }
1176         }
1177         SCRATCH_RESTORE();
1178         advances_so_far += run_advance;
1179       }
1180 #undef SCRATCH_RESTORE
1181 #undef SCRATCH_SAVE
1182 #undef USE_PTR
1183 #undef ALLOCATE_ARRAY
1184 
1185       buffer->len += num_glyphs;
1186     }
1187 
1188     /* Mac OS 10.6 doesn't have kCTTypesetterOptionForcedEmbeddingLevel,
1189      * or if it does, it doesn't resepct it.  So we get runs with wrong
1190      * directions.  As such, disable the assert...  It wouldn't crash, but
1191      * cursoring will be off...
1192      *
1193      * http://crbug.com/419769
1194      */
1195     if (0)
1196     {
1197       /* Make sure all runs had the expected direction. */
1198       bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1199       assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1200       assert (bool (status_or  & kCTRunStatusRightToLeft) == backward);
1201     }
1202 
1203     buffer->clear_positions ();
1204 
1205     unsigned int count = buffer->len;
1206     hb_glyph_info_t *info = buffer->info;
1207     hb_glyph_position_t *pos = buffer->pos;
1208     if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1209       for (unsigned int i = 0; i < count; i++)
1210       {
1211         pos->x_advance = info->mask;
1212         pos->x_offset = info->var1.i32;
1213         pos->y_offset = info->var2.i32;
1214 
1215         info->mask = HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1216 
1217         info++, pos++;
1218       }
1219     else
1220       for (unsigned int i = 0; i < count; i++)
1221       {
1222         pos->y_advance = info->mask;
1223         pos->x_offset = info->var1.i32;
1224         pos->y_offset = info->var2.i32;
1225 
1226         info->mask = HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1227 
1228         info++, pos++;
1229       }
1230 
1231     /* Fix up clusters so that we never return out-of-order indices;
1232      * if core text has reordered glyphs, we'll merge them to the
1233      * beginning of the reordered cluster.  CoreText is nice enough
1234      * to tell us whenever it has produced nonmonotonic results...
1235      * Note that we assume the input clusters were nonmonotonic to
1236      * begin with.
1237      *
1238      * This does *not* mean we'll form the same clusters as Uniscribe
1239      * or the native OT backend, only that the cluster indices will be
1240      * monotonic in the output buffer. */
1241     if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1242     {
1243       hb_glyph_info_t *info = buffer->info;
1244       if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1245       {
1246         unsigned int cluster = info[count - 1].cluster;
1247         for (unsigned int i = count - 1; i > 0; i--)
1248         {
1249           cluster = MIN (cluster, info[i - 1].cluster);
1250           info[i - 1].cluster = cluster;
1251         }
1252       }
1253       else
1254       {
1255         unsigned int cluster = info[0].cluster;
1256         for (unsigned int i = 1; i < count; i++)
1257         {
1258           cluster = MIN (cluster, info[i].cluster);
1259           info[i].cluster = cluster;
1260         }
1261       }
1262     }
1263   }
1264 
1265   buffer->unsafe_to_break_all ();
1266 
1267 #undef FAIL
1268 
1269 fail:
1270   if (string_ref)
1271     CFRelease (string_ref);
1272   if (line)
1273     CFRelease (line);
1274 
1275   for (unsigned int i = 0; i < range_records.len; i++)
1276     if (range_records[i].font)
1277       CFRelease (range_records[i].font);
1278 
1279   return ret;
1280 }
1281 
1282 
1283 /*
1284  * AAT shaper
1285  */
1286 
1287 HB_SHAPER_DATA_ENSURE_DEFINE(coretext_aat, face)
1288 HB_SHAPER_DATA_ENSURE_DEFINE(coretext_aat, font)
1289 
1290 /*
1291  * shaper face data
1292  */
1293 
1294 struct hb_coretext_aat_shaper_face_data_t {};
1295 
1296 hb_coretext_aat_shaper_face_data_t *
1297 _hb_coretext_aat_shaper_face_data_create (hb_face_t *face)
1298 {
1299   static const hb_tag_t tags[] = {HB_CORETEXT_TAG_MORX, HB_CORETEXT_TAG_MORT, HB_CORETEXT_TAG_KERX};
1300 
1301   for (unsigned int i = 0; i < ARRAY_LENGTH (tags); i++)
1302   {
1303     hb_blob_t *blob = face->reference_table (tags[i]);
1304     if (hb_blob_get_length (blob))
1305     {
1306       hb_blob_destroy (blob);
1307       return hb_coretext_shaper_face_data_ensure (face) ? (hb_coretext_aat_shaper_face_data_t *) HB_SHAPER_DATA_SUCCEEDED : nullptr;
1308     }
1309     hb_blob_destroy (blob);
1310   }
1311 
1312   return nullptr;
1313 }
1314 
1315 void
1316 _hb_coretext_aat_shaper_face_data_destroy (hb_coretext_aat_shaper_face_data_t *data HB_UNUSED)
1317 {
1318 }
1319 
1320 
1321 /*
1322  * shaper font data
1323  */
1324 
1325 struct hb_coretext_aat_shaper_font_data_t {};
1326 
1327 hb_coretext_aat_shaper_font_data_t *
1328 _hb_coretext_aat_shaper_font_data_create (hb_font_t *font)
1329 {
1330   return hb_coretext_shaper_font_data_ensure (font) ? (hb_coretext_aat_shaper_font_data_t *) HB_SHAPER_DATA_SUCCEEDED : nullptr;
1331 }
1332 
1333 void
1334 _hb_coretext_aat_shaper_font_data_destroy (hb_coretext_aat_shaper_font_data_t *data HB_UNUSED)
1335 {
1336 }
1337 
1338 
1339 /*
1340  * shaper shape_plan data
1341  */
1342 
1343 struct hb_coretext_aat_shaper_shape_plan_data_t {};
1344 
1345 hb_coretext_aat_shaper_shape_plan_data_t *
1346 _hb_coretext_aat_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
1347                                              const hb_feature_t *user_features HB_UNUSED,
1348                                              unsigned int        num_user_features HB_UNUSED,
1349                                              const int          *coords HB_UNUSED,
1350                                              unsigned int        num_coords HB_UNUSED)
1351 {
1352   return (hb_coretext_aat_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
1353 }
1354 
1355 void
1356 _hb_coretext_aat_shaper_shape_plan_data_destroy (hb_coretext_aat_shaper_shape_plan_data_t *data HB_UNUSED)
1357 {
1358 }
1359 
1360 
1361 /*
1362  * shaper
1363  */
1364 
1365 hb_bool_t
1366 _hb_coretext_aat_shape (hb_shape_plan_t    *shape_plan,
1367                         hb_font_t          *font,
1368                         hb_buffer_t        *buffer,
1369                         const hb_feature_t *features,
1370                         unsigned int        num_features)
1371 {
1372   return _hb_coretext_shape (shape_plan, font, buffer, features, num_features);
1373 }