< prev index next >

src/java.desktop/share/native/libfontmanager/harfbuzz/hb-coretext.cc

Print this page




  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 #include "hb-shaper-impl-private.hh"
  31 
  32 #include "hb-coretext.h"

  33 


  34 
  35 #ifndef HB_DEBUG_CORETEXT
  36 #define HB_DEBUG_CORETEXT (HB_DEBUG+0)
  37 #endif
  38 







  39 
  40 static void
  41 release_table_data (void *user_data)
  42 {
  43   CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
  44   CFRelease(cf_data);
  45 }
  46 
  47 static hb_blob_t *
  48 reference_table  (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
  49 {
  50   CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
  51   CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
  52   if (unlikely (!cf_data))
  53     return NULL;
  54 
  55   const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
  56   const size_t length = CFDataGetLength (cf_data);
  57   if (!data || !length)
  58     return NULL;
  59 
  60   return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
  61                          reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
  62                          release_table_data);
  63 }
  64 






  65 hb_face_t *
  66 hb_coretext_face_create (CGFontRef cg_font)
  67 {
  68   return hb_face_create_for_tables (reference_table, CGFontRetain (cg_font), (hb_destroy_func_t) CGFontRelease);
  69 }
  70 
  71 
  72 HB_SHAPER_DATA_ENSURE_DECLARE(coretext, face)
  73 HB_SHAPER_DATA_ENSURE_DECLARE(coretext, font)
  74 
  75 
  76 /*
  77  * shaper face data
  78  */
  79 
  80 static CTFontDescriptorRef
  81 get_last_resort_font_desc (void)
  82 {
  83   // TODO Handle allocation failures?
  84   CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
  85   CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
  86                                            (const void **) &last_resort,
  87                                            1,
  88                                            &kCFTypeArrayCallBacks);
  89   CFRelease (last_resort);
  90   CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
  91                                                    (const void **) &kCTFontCascadeListAttribute,
  92                                                    (const void **) &cascade_list,
  93                                                    1,
  94                                                    &kCFTypeDictionaryKeyCallBacks,
  95                                                    &kCFTypeDictionaryValueCallBacks);
  96   CFRelease (cascade_list);
  97 
  98   CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
  99   CFRelease (attributes);
 100   return font_desc;
 101 }
 102 
 103 static void
 104 release_data (void *info, const void *data, size_t size)
 105 {
 106   assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
 107           hb_blob_get_data ((hb_blob_t *) info, NULL) == data);
 108 
 109   hb_blob_destroy ((hb_blob_t *) info);
 110 }
 111 
 112 static CGFontRef
 113 create_cg_font (hb_face_t *face)
 114 {
 115   CGFontRef cg_font = NULL;
 116   if (face->destroy == (hb_destroy_func_t) CGFontRelease)
 117   {
 118     cg_font = CGFontRetain ((CGFontRef) face->user_data);
 119   }
 120   else
 121   {
 122     hb_blob_t *blob = hb_face_reference_blob (face);
 123     unsigned int blob_length;
 124     const char *blob_data = hb_blob_get_data (blob, &blob_length);
 125     if (unlikely (!blob_length))
 126       DEBUG_MSG (CORETEXT, face, "Face has empty blob");
 127 
 128     CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
 129     if (likely (provider))
 130     {
 131       cg_font = CGFontCreateWithDataProvider (provider);
 132       if (unlikely (!cg_font))
 133         DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
 134       CGDataProviderRelease (provider);
 135     }
 136   }
 137   return cg_font;
 138 }
 139 
 140 static CTFontRef
 141 create_ct_font (CGFontRef cg_font, CGFloat font_size)
 142 {
 143   CTFontRef ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, NULL, NULL);


























 144   if (unlikely (!ct_font)) {
 145     DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
 146     return NULL;
 147   }
 148 
 149   /* crbug.com/576941 and crbug.com/625902 and the investigation in the latter
 150    * bug indicate that the cascade list reconfiguration occasionally causes
 151    * crashes in CoreText on OS X 10.9, thus let's skip this step on older
 152    * operating system versions. Except for the emoji font, where _not_
 153    * reconfiguring the cascade list causes CoreText crashes. For details, see
 154    * crbug.com/549610 */
 155   // 0x00070000 stands for "kCTVersionNumber10_10", see CoreText.h
 156   if (&CTGetCoreTextVersion != NULL && CTGetCoreTextVersion() < 0x00070000) {
 157     CFStringRef fontName = CTFontCopyPostScriptName (ct_font);
 158     bool isEmojiFont = CFStringCompare (fontName, CFSTR("AppleColorEmoji"), 0) == kCFCompareEqualTo;
 159     CFRelease (fontName);
 160     if (!isEmojiFont)
 161       return ct_font;
 162   }
 163 
 164   CFURLRef original_url = (CFURLRef)CTFontCopyAttribute(ct_font, kCTFontURLAttribute);
 165 
 166   /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
 167    * font fallback which we don't need anyway. */
 168   {
 169     CTFontDescriptorRef last_resort_font_desc = get_last_resort_font_desc ();
 170     CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0.0, NULL, last_resort_font_desc);
 171     CFRelease (last_resort_font_desc);
 172     if (new_ct_font)
 173     {
 174       /* The CTFontCreateCopyWithAttributes call fails to stay on the same font
 175        * when reconfiguring the cascade list and may switch to a different font
 176        * when there are fonts that go by the same name, since the descriptor is
 177        * just name and size.
 178        *
 179        * Avoid reconfiguring the cascade lists if the new font is outside the
 180        * system locations that we cannot access from the sandboxed renderer
 181        * process in Blink. This can be detected by the new file URL location
 182        * that the newly found font points to. */
 183       CFURLRef new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
 184       // Keep reconfigured font if URL cannot be retrieved (seems to be the case
 185       // on Mac OS 10.12 Sierra), speculative fix for crbug.com/625606
 186       if (!original_url || !new_url || CFEqual (original_url, new_url)) {
 187         CFRelease (ct_font);
 188         ct_font = new_ct_font;
 189       } else {
 190         CFRelease (new_ct_font);
 191         DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
 192       }
 193       if (new_url)
 194         CFRelease (new_url);
 195     }
 196     else
 197       DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
 198   }
 199 
 200   if (original_url)
 201     CFRelease (original_url);
 202   return ct_font;
 203 }
 204 
 205 struct hb_coretext_shaper_face_data_t {
 206   CGFontRef cg_font;
 207   CTFontRef ct_font;
 208 };
 209 
 210 hb_coretext_shaper_face_data_t *
 211 _hb_coretext_shaper_face_data_create (hb_face_t *face)
 212 {
 213   hb_coretext_shaper_face_data_t *data = (hb_coretext_shaper_face_data_t *) calloc (1, sizeof (hb_coretext_shaper_face_data_t));
 214   if (unlikely (!data))
 215     return NULL;
 216 
 217   data->cg_font = create_cg_font (face);
 218   if (unlikely (!data->cg_font))
 219   {
 220     DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
 221     free (data);
 222     return NULL;
 223   }
 224 
 225   /* We use 36pt size instead of UPEM, because CoreText implements the 'trak' table,
 226    * which can make the font too tight at large sizes.  36pt should be a good semi-neutral
 227    * size.
 228    *
 229    * Since we always create CTFont at a fixed size, our CTFont lives in face_data
 230    * instead of font_data.  Which is good, because when people change scale on
 231    * hb_font_t, we won't need to update our CTFont. */
 232   data->ct_font = create_ct_font (data->cg_font, 36.);
 233   if (unlikely (!data->ct_font))
 234   {
 235     DEBUG_MSG (CORETEXT, face, "CTFont creation failed.");
 236     CFRelease (data->cg_font);
 237     free (data);
 238     return NULL;
 239   }
 240 
 241   return data;
 242 }
 243 
 244 void
 245 _hb_coretext_shaper_face_data_destroy (hb_coretext_shaper_face_data_t *data)
 246 {
 247   CFRelease (data->ct_font);
 248   CFRelease (data->cg_font);
 249   free (data);
 250 }
 251 
 252 /*
 253  * Since: 0.9.10
 254  */
 255 CGFontRef
 256 hb_coretext_face_get_cg_font (hb_face_t *face)
 257 {
 258   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return NULL;
 259   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
 260   return face_data->cg_font;
 261 }
 262 
 263 
 264 /*
 265  * shaper font data
 266  */
 267 
 268 struct hb_coretext_shaper_font_data_t {};
 269 
 270 hb_coretext_shaper_font_data_t *
 271 _hb_coretext_shaper_font_data_create (hb_font_t *font HB_UNUSED)
 272 {
 273   return (hb_coretext_shaper_font_data_t *) HB_SHAPER_DATA_SUCCEEDED;












 274 }
 275 
 276 void
 277 _hb_coretext_shaper_font_data_destroy (hb_coretext_shaper_font_data_t *data)
 278 {

 279 }
 280 
 281 
 282 /*
 283  * shaper shape_plan data
 284  */
 285 
 286 struct hb_coretext_shaper_shape_plan_data_t {};
 287 
 288 hb_coretext_shaper_shape_plan_data_t *
 289 _hb_coretext_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
 290                                              const hb_feature_t *user_features HB_UNUSED,
 291                                              unsigned int        num_user_features HB_UNUSED,
 292                                              const int          *coords HB_UNUSED,
 293                                              unsigned int        num_coords HB_UNUSED)
 294 {
 295   return (hb_coretext_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
 296 }
 297 
 298 void
 299 _hb_coretext_shaper_shape_plan_data_destroy (hb_coretext_shaper_shape_plan_data_t *data HB_UNUSED)
 300 {
 301 }
 302 
 303 CTFontRef
 304 hb_coretext_font_get_ct_font (hb_font_t *font)
 305 {
 306   hb_face_t *face = font->face;
 307   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return NULL;
 308   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
 309   return face_data->ct_font;
 310 }
 311 
 312 
 313 /*
 314  * shaper
 315  */
 316 
 317 struct feature_record_t {
 318   unsigned int feature;
 319   unsigned int setting;
 320 };
 321 
 322 struct active_feature_t {
 323   feature_record_t rec;
 324   unsigned int order;
 325 
 326   static int cmp (const active_feature_t *a, const active_feature_t *b) {


 327     return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
 328            a->order < b->order ? -1 : a->order > b->order ? 1 :
 329            a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
 330            0;
 331   }
 332   bool operator== (const active_feature_t *f) {
 333     return cmp (this, f) == 0;
 334   }
 335 };
 336 
 337 struct feature_event_t {
 338   unsigned int index;
 339   bool start;
 340   active_feature_t feature;
 341 
 342   static int cmp (const feature_event_t *a, const feature_event_t *b) {


 343     return a->index < b->index ? -1 : a->index > b->index ? 1 :
 344            a->start < b->start ? -1 : a->start > b->start ? 1 :
 345            active_feature_t::cmp (&a->feature, &b->feature);
 346   }
 347 };
 348 
 349 struct range_record_t {
 350   CTFontRef font;
 351   unsigned int index_first; /* == start */
 352   unsigned int index_last;  /* == end - 1 */
 353 };
 354 
 355 
 356 /* The following enum members are added in OS X 10.8. */
 357 #define kAltHalfWidthTextSelector               6
 358 #define kAltProportionalTextSelector            5
 359 #define kAlternateHorizKanaOffSelector          1
 360 #define kAlternateHorizKanaOnSelector           0
 361 #define kAlternateKanaType                      34
 362 #define kAlternateVertKanaOffSelector           3


 521 };
 522 
 523 static int
 524 _hb_feature_mapping_cmp (const void *key_, const void *entry_)
 525 {
 526   unsigned int key = * (unsigned int *) key_;
 527   const feature_mapping_t * entry = (const feature_mapping_t *) entry_;
 528   return key < entry->otFeatureTag ? -1 :
 529          key > entry->otFeatureTag ? 1 :
 530          0;
 531 }
 532 
 533 hb_bool_t
 534 _hb_coretext_shape (hb_shape_plan_t    *shape_plan,
 535                     hb_font_t          *font,
 536                     hb_buffer_t        *buffer,
 537                     const hb_feature_t *features,
 538                     unsigned int        num_features)
 539 {
 540   hb_face_t *face = font->face;
 541   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);

 542 
 543   CGFloat ct_font_size = CTFontGetSize (face_data->ct_font);
 544   CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
 545   CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
 546 
 547   /* Attach marks to their bases, to match the 'ot' shaper.
 548    * Adapted from hb-ot-shape:hb_form_clusters().
 549    * Note that this only makes us be closer to the 'ot' shaper,
 550    * but by no means the same.  For example, if there's
 551    * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
 552    * continue pointing to B2 even though B2 was merged into B1's
 553    * cluster... */
 554   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
 555   {
 556     hb_unicode_funcs_t *unicode = buffer->unicode;
 557     unsigned int count = buffer->len;
 558     hb_glyph_info_t *info = buffer->info;
 559     for (unsigned int i = 1; i < count; i++)
 560       if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
 561         buffer->merge_clusters (i - 1, i + 1);
 562   }
 563 


 624     unsigned int last_index = 0;
 625     for (unsigned int i = 0; i < feature_events.len; i++)
 626     {
 627       feature_event_t *event = &feature_events[i];
 628 
 629       if (event->index != last_index)
 630       {
 631         /* Save a snapshot of active features and the range. */
 632         range_record_t *range = range_records.push ();
 633         if (unlikely (!range))
 634           goto fail_features;
 635 
 636         if (active_features.len)
 637         {
 638           CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
 639 
 640           /* TODO sort and resolve conflicting features? */
 641           /* active_features.qsort (); */
 642           for (unsigned int j = 0; j < active_features.len; j++)
 643           {
 644             CFStringRef keys[2] = {
 645               kCTFontFeatureTypeIdentifierKey,
 646               kCTFontFeatureSelectorIdentifierKey
 647             };
 648             CFNumberRef values[2] = {
 649               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
 650               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
 651             };

 652             CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
 653                                                        (const void **) keys,
 654                                                        (const void **) values,
 655                                                        2,
 656                                                        &kCFTypeDictionaryKeyCallBacks,
 657                                                        &kCFTypeDictionaryValueCallBacks);
 658             CFRelease (values[0]);
 659             CFRelease (values[1]);
 660 
 661             CFArrayAppendValue (features_array, dict);
 662             CFRelease (dict);
 663 
 664           }
 665 
 666           CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
 667                                                            (const void **) &kCTFontFeatureSettingsAttribute,
 668                                                            (const void **) &features_array,
 669                                                            1,
 670                                                            &kCFTypeDictionaryKeyCallBacks,
 671                                                            &kCFTypeDictionaryValueCallBacks);
 672           CFRelease (features_array);
 673 
 674           CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
 675           CFRelease (attributes);
 676 
 677           range->font = CTFontCreateCopyWithAttributes (face_data->ct_font, 0.0, NULL, font_desc);
 678           CFRelease (font_desc);
 679         }
 680         else
 681         {
 682           range->font = NULL;
 683         }
 684 
 685         range->index_first = last_index;
 686         range->index_last  = event->index - 1;
 687 
 688         last_index = event->index;
 689       }
 690 
 691       if (event->start) {
 692         active_feature_t *feature = active_features.push ();
 693         if (unlikely (!feature))
 694           goto fail_features;
 695         *feature = event->feature;
 696       } else {
 697         active_feature_t *feature = active_features.find (&event->feature);
 698         if (feature)
 699           active_features.remove (feature - active_features.array);
 700       }
 701     }
 702 
 703     if (!range_records.len) /* No active feature found. */
 704       goto fail_features;
 705   }
 706   else
 707   {
 708   fail_features:
 709     num_features = 0;
 710   }
 711 
 712   unsigned int scratch_size;
 713   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
 714 
 715 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
 716   Type *name = (Type *) scratch; \
 717   { \
 718     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
 719     if (unlikely (_consumed > scratch_size)) \
 720     { \
 721       on_no_room; \
 722       assert (0); \
 723     } \
 724     scratch += _consumed; \


 735       pchars[chars_len++] = 0xFFFDu;
 736     else {
 737       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
 738       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
 739     }
 740   }
 741 
 742   ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, /*nothing*/);
 743   chars_len = 0;
 744   for (unsigned int i = 0; i < buffer->len; i++)
 745   {
 746     hb_codepoint_t c = buffer->info[i].codepoint;
 747     unsigned int cluster = buffer->info[i].cluster;
 748     log_clusters[chars_len++] = cluster;
 749     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
 750       log_clusters[chars_len++] = cluster; /* Surrogates. */
 751   }
 752 
 753 #define FAIL(...) \
 754   HB_STMT_START { \
 755     DEBUG_MSG (CORETEXT, NULL, __VA_ARGS__); \
 756     ret = false; \
 757     goto fail; \
 758   } HB_STMT_END;
 759 
 760   bool ret = true;
 761   CFStringRef string_ref = NULL;
 762   CTLineRef line = NULL;
 763 
 764   if (0)
 765   {
 766 resize_and_retry:
 767     DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
 768     /* string_ref uses the scratch-buffer for backing store, and line references
 769      * string_ref (via attr_string).  We must release those before resizing buffer. */
 770     assert (string_ref);
 771     assert (line);
 772     CFRelease (string_ref);
 773     CFRelease (line);
 774     string_ref = NULL;
 775     line = NULL;
 776 
 777     /* Get previous start-of-scratch-area, that we use later for readjusting
 778      * our existing scratch arrays. */
 779     unsigned int old_scratch_used;
 780     hb_buffer_t::scratch_buffer_t *old_scratch;
 781     old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
 782     old_scratch_used = scratch - old_scratch;
 783 
 784     if (unlikely (!buffer->ensure (buffer->allocated * 2)))
 785       FAIL ("Buffer resize failed");
 786 
 787     /* Adjust scratch, pchars, and log_cluster arrays.  This is ugly, but really the
 788      * cleanest way to do without completely restructuring the rest of this shaper. */
 789     scratch = buffer->get_scratch_buffer (&scratch_size);
 790     pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
 791     log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
 792     scratch += old_scratch_used;
 793     scratch_size -= old_scratch_used;
 794   }
 795   {
 796     string_ref = CFStringCreateWithCharactersNoCopy (NULL,
 797                                                      pchars, chars_len,
 798                                                      kCFAllocatorNull);
 799     if (unlikely (!string_ref))
 800       FAIL ("CFStringCreateWithCharactersNoCopy failed");
 801 
 802     /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
 803     {
 804       CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
 805                                                                                   chars_len);
 806       if (unlikely (!attr_string))
 807         FAIL ("CFAttributedStringCreateMutable failed");
 808       CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
 809       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 810       {
 811         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 812                                         kCTVerticalFormsAttributeName, kCFBooleanTrue);
 813       }
 814 
 815       if (buffer->props.language)
 816       {
 817 /* What's the iOS equivalent of this check?
 818  * The symbols was introduced in iOS 7.0.
 819  * At any rate, our fallback is safe and works fine. */
 820 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
 821 #  define kCTLanguageAttributeName CFSTR ("NSLanguage")
 822 #endif
 823         CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
 824                                                             hb_language_to_string (buffer->props.language),
 825                                                             kCFStringEncodingUTF8,
 826                                                             kCFAllocatorNull);
 827         if (unlikely (!lang))
 828           FAIL ("CFStringCreateWithCStringNoCopy failed");
 829         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 830                                         kCTLanguageAttributeName, lang);
 831         CFRelease (lang);
 832       }
 833       CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
 834                                       kCTFontAttributeName, face_data->ct_font);
 835 
 836       if (num_features)
 837       {
 838         unsigned int start = 0;
 839         range_record_t *last_range = &range_records[0];
 840         for (unsigned int k = 0; k < chars_len; k++)
 841         {
 842           range_record_t *range = last_range;
 843           while (log_clusters[k] < range->index_first)
 844             range--;
 845           while (log_clusters[k] > range->index_last)
 846             range++;
 847           if (range != last_range)
 848           {
 849             if (last_range->font)
 850               CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
 851                                               kCTFontAttributeName, last_range->font);
 852 
 853             start = k;
 854           }
 855 
 856           last_range = range;
 857         }
 858         if (start != chars_len && last_range->font)
 859           CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
 860                                           kCTFontAttributeName, last_range->font);
 861       }
























 862 
 863       int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
 864       CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
 865       CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
 866                                                     (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
 867                                                     (const void **) &level_number,
 868                                                     1,
 869                                                     &kCFTypeDictionaryKeyCallBacks,
 870                                                     &kCFTypeDictionaryValueCallBacks);

 871       if (unlikely (!options))
 872         FAIL ("CFDictionaryCreate failed");
 873 
 874       CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
 875       CFRelease (options);
 876       CFRelease (attr_string);
 877       if (unlikely (!typesetter))
 878         FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
 879 
 880       line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
 881       CFRelease (typesetter);
 882       if (unlikely (!line))
 883         FAIL ("CTTypesetterCreateLine failed");
 884     }
 885 
 886     CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
 887     unsigned int num_runs = CFArrayGetCount (glyph_runs);
 888     DEBUG_MSG (CORETEXT, NULL, "Num runs: %d", num_runs);
 889 
 890     buffer->len = 0;
 891     uint32_t status_and = ~0, status_or = 0;
 892     double advances_so_far = 0;
 893     /* For right-to-left runs, CoreText returns the glyphs positioned such that
 894      * any trailing whitespace is to the left of (0,0).  Adjust coordinate system
 895      * to fix for that.  Test with any RTL string with trailing spaces.
 896      * https://code.google.com/p/chromium/issues/detail?id=469028
 897      */
 898     if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
 899     {
 900       advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
 901       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 902           advances_so_far = -advances_so_far;
 903     }
 904 
 905     const CFRange range_all = CFRangeMake (0, 0);
 906 
 907     for (unsigned int i = 0; i < num_runs; i++)
 908     {
 909       CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
 910       CTRunStatus run_status = CTRunGetStatus (run);
 911       status_or  |= run_status;
 912       status_and &= run_status;
 913       DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
 914       double run_advance = CTRunGetTypographicBounds (run, range_all, NULL, NULL, NULL);
 915       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
 916           run_advance = -run_advance;
 917       DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
 918 
 919       /* CoreText does automatic font fallback (AKA "cascading") for  characters
 920        * not supported by the requested font, and provides no way to turn it off,
 921        * so we must detect if the returned run uses a font other than the requested
 922        * one and fill in the buffer with .notdef glyphs instead of random glyph
 923        * indices from a different font.
 924        */
 925       CFDictionaryRef attributes = CTRunGetAttributes (run);
 926       CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
 927       if (!CFEqual (run_ct_font, face_data->ct_font))
 928       {
 929         /* The run doesn't use our main font instance.  We have to figure out
 930          * whether font fallback happened, or this is just CoreText giving us
 931          * another CTFont using the same underlying CGFont.  CoreText seems
 932          * to do that in a variety of situations, one of which being vertical
 933          * text, but also perhaps for caching reasons.
 934          *
 935          * First, see if it uses any of our subfonts created to set font features...
 936          *
 937          * Next, compare the CGFont to the one we used to create our fonts.
 938          * Even this doesn't work all the time.
 939          *
 940          * Finally, we compare PS names, which I don't think are unique...
 941          *
 942          * Looks like if we really want to be sure here we have to modify the
 943          * font to change the name table, similar to what we do in the uniscribe
 944          * backend.
 945          *
 946          * However, even that wouldn't work if we were passed in the CGFont to
 947          * construct a hb_face to begin with.
 948          *
 949          * See: http://github.com/behdad/harfbuzz/pull/36
 950          *
 951          * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
 952          */
 953         bool matched = false;
 954         for (unsigned int i = 0; i < range_records.len; i++)
 955           if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
 956           {
 957             matched = true;
 958             break;
 959           }
 960         if (!matched)
 961         {
 962           CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, 0);
 963           if (run_cg_font)
 964           {
 965             matched = CFEqual (run_cg_font, face_data->cg_font);
 966             CFRelease (run_cg_font);
 967           }
 968         }
 969         if (!matched)
 970         {
 971           CFStringRef font_ps_name = CTFontCopyName (face_data->ct_font, kCTFontPostScriptNameKey);
 972           CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
 973           CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
 974           CFRelease (run_ps_name);
 975           CFRelease (font_ps_name);
 976           if (result == kCFCompareEqualTo)
 977             matched = true;
 978         }
 979         if (!matched)
 980         {
 981           CFRange range = CTRunGetStringRange (run);
 982           DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
 983                      range.location, range.location + range.length);
 984           if (!buffer->ensure_inplace (buffer->len + range.length))
 985             goto resize_and_retry;
 986           hb_glyph_info_t *info = buffer->info + buffer->len;
 987 
 988           hb_codepoint_t notdef = 0;
 989           hb_direction_t dir = buffer->props.direction;
 990           hb_position_t x_advance, y_advance, x_offset, y_offset;
 991           hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);


1020               buffer->len++;
1021           }
1022           if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
1023             buffer->reverse_range (old_len, buffer->len);
1024           advances_so_far += run_advance;
1025           continue;
1026         }
1027       }
1028 
1029       unsigned int num_glyphs = CTRunGetGlyphCount (run);
1030       if (num_glyphs == 0)
1031         continue;
1032 
1033       if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1034         goto resize_and_retry;
1035 
1036       hb_glyph_info_t *run_info = buffer->info + buffer->len;
1037 
1038       /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
1039        * succeed, and so copying data to our own buffer will be rare.  Reports
1040        * have it that this changed in OS X 10.10 Yosemite, and NULL is returned
1041        * frequently.  At any rate, we can test that codepath by setting USE_PTR
1042        * to false. */
1043 
1044 #define USE_PTR true
1045 
1046 #define SCRATCH_SAVE() \
1047   unsigned int scratch_size_saved = scratch_size; \
1048   hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1049 
1050 #define SCRATCH_RESTORE() \
1051   scratch_size = scratch_size_saved; \
1052   scratch = scratch_saved;
1053 
1054       { /* Setup glyphs */
1055         SCRATCH_SAVE();
1056         const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : NULL;
1057         if (!glyphs) {
1058           ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1059           CTRunGetGlyphs (run, range_all, glyph_buf);
1060           glyphs = glyph_buf;
1061         }
1062         const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : NULL;
1063         if (!string_indices) {
1064           ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
1065           CTRunGetStringIndices (run, range_all, index_buf);
1066           string_indices = index_buf;
1067         }
1068         hb_glyph_info_t *info = run_info;
1069         for (unsigned int j = 0; j < num_glyphs; j++)
1070         {
1071           info->codepoint = glyphs[j];
1072           info->cluster = log_clusters[string_indices[j]];
1073           info++;
1074         }
1075         SCRATCH_RESTORE();
1076       }
1077       {
1078         /* Setup positions.
1079          * Note that CoreText does not return advances for glyphs.  As such,
1080          * for all but last glyph, we use the delta position to next glyph as
1081          * advance (in the advance direction only), and for last glyph we set
1082          * whatever is needed to make the whole run's advance add up. */
1083         SCRATCH_SAVE();
1084         const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : NULL;
1085         if (!positions) {
1086           ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1087           CTRunGetPositions (run, range_all, position_buf);
1088           positions = position_buf;
1089         }
1090         hb_glyph_info_t *info = run_info;
1091         if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1092         {
1093           hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1094           for (unsigned int j = 0; j < num_glyphs; j++)
1095           {
1096             double advance;
1097             if (likely (j + 1 < num_glyphs))
1098               advance = positions[j + 1].x - positions[j].x;
1099             else /* last glyph */
1100               advance = run_advance - (positions[j].x - positions[0].x);
1101             info->mask = advance * x_mult;
1102             info->var1.i32 = x_offset;
1103             info->var2.i32 = positions[j].y * y_mult;
1104             info++;


1140      */
1141     if (0)
1142     {
1143       /* Make sure all runs had the expected direction. */
1144       bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1145       assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1146       assert (bool (status_or  & kCTRunStatusRightToLeft) == backward);
1147     }
1148 
1149     buffer->clear_positions ();
1150 
1151     unsigned int count = buffer->len;
1152     hb_glyph_info_t *info = buffer->info;
1153     hb_glyph_position_t *pos = buffer->pos;
1154     if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1155       for (unsigned int i = 0; i < count; i++)
1156       {
1157         pos->x_advance = info->mask;
1158         pos->x_offset = info->var1.i32;
1159         pos->y_offset = info->var2.i32;



1160         info++, pos++;
1161       }
1162     else
1163       for (unsigned int i = 0; i < count; i++)
1164       {
1165         pos->y_advance = info->mask;
1166         pos->x_offset = info->var1.i32;
1167         pos->y_offset = info->var2.i32;



1168         info++, pos++;
1169       }
1170 
1171     /* Fix up clusters so that we never return out-of-order indices;
1172      * if core text has reordered glyphs, we'll merge them to the
1173      * beginning of the reordered cluster.  CoreText is nice enough
1174      * to tell us whenever it has produced nonmonotonic results...
1175      * Note that we assume the input clusters were nonmonotonic to
1176      * begin with.
1177      *
1178      * This does *not* mean we'll form the same clusters as Uniscribe
1179      * or the native OT backend, only that the cluster indices will be
1180      * monotonic in the output buffer. */
1181     if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1182     {
1183       hb_glyph_info_t *info = buffer->info;
1184       if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1185       {
1186         unsigned int cluster = info[count - 1].cluster;
1187         for (unsigned int i = count - 1; i > 0; i--)
1188         {
1189           cluster = MIN (cluster, info[i - 1].cluster);
1190           info[i - 1].cluster = cluster;
1191         }
1192       }
1193       else
1194       {
1195         unsigned int cluster = info[0].cluster;
1196         for (unsigned int i = 1; i < count; i++)
1197         {
1198           cluster = MIN (cluster, info[i].cluster);
1199           info[i].cluster = cluster;
1200         }
1201       }
1202     }
1203   }
1204 


1205 #undef FAIL
1206 
1207 fail:
1208   if (string_ref)
1209     CFRelease (string_ref);
1210   if (line)
1211     CFRelease (line);
1212 
1213   for (unsigned int i = 0; i < range_records.len; i++)
1214     if (range_records[i].font)
1215       CFRelease (range_records[i].font);
1216 
1217   return ret;
1218 }
1219 
1220 
1221 /*
1222  * AAT shaper
1223  */
1224 



1225 /*
1226  * shaper face data
1227  */
1228 
1229 struct hb_coretext_aat_shaper_face_data_t {};
1230 
1231 hb_coretext_aat_shaper_face_data_t *
1232 _hb_coretext_aat_shaper_face_data_create (hb_face_t *face)
1233 {
1234   hb_blob_t *mort_blob = face->reference_table (HB_CORETEXT_TAG_MORT);
1235   /* Umm, we just reference the table to check whether it exists.
1236    * Maybe add better API for this? */
1237   if (!hb_blob_get_length (mort_blob))
1238   {
1239     hb_blob_destroy (mort_blob);
1240     mort_blob = face->reference_table (HB_CORETEXT_TAG_MORX);
1241     if (!hb_blob_get_length (mort_blob))
1242     {
1243       hb_blob_destroy (mort_blob);
1244       return NULL;
1245     }

1246   }
1247   hb_blob_destroy (mort_blob);
1248 
1249   return hb_coretext_shaper_face_data_ensure (face) ? (hb_coretext_aat_shaper_face_data_t *) HB_SHAPER_DATA_SUCCEEDED : NULL;
1250 }
1251 
1252 void
1253 _hb_coretext_aat_shaper_face_data_destroy (hb_coretext_aat_shaper_face_data_t *data HB_UNUSED)
1254 {
1255 }
1256 
1257 
1258 /*
1259  * shaper font data
1260  */
1261 
1262 struct hb_coretext_aat_shaper_font_data_t {};
1263 
1264 hb_coretext_aat_shaper_font_data_t *
1265 _hb_coretext_aat_shaper_font_data_create (hb_font_t *font)
1266 {
1267   return hb_coretext_shaper_font_data_ensure (font) ? (hb_coretext_aat_shaper_font_data_t *) HB_SHAPER_DATA_SUCCEEDED : NULL;
1268 }
1269 
1270 void
1271 _hb_coretext_aat_shaper_font_data_destroy (hb_coretext_aat_shaper_font_data_t *data HB_UNUSED)
1272 {
1273 }
1274 
1275 
1276 /*
1277  * shaper shape_plan data
1278  */
1279 
1280 struct hb_coretext_aat_shaper_shape_plan_data_t {};
1281 
1282 hb_coretext_aat_shaper_shape_plan_data_t *
1283 _hb_coretext_aat_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
1284                                              const hb_feature_t *user_features HB_UNUSED,
1285                                              unsigned int        num_user_features HB_UNUSED,
1286                                              const int          *coords HB_UNUSED,
1287                                              unsigned int        num_coords HB_UNUSED)




  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


 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 


 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; \


 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);


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++;


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)


< prev index next >