8885cfe73043742e65f8f2c14e54f5fecad5f42c
[platform/upstream/harfbuzz.git] / src / hb-coretext.cc
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 #include "hb.hh"
30
31 #ifdef HAVE_CORETEXT
32
33 #include "hb-shaper-impl.hh"
34
35 #include "hb-coretext.h"
36 #include "hb-aat-layout.hh"
37 #include <math.h>
38
39
40 /**
41  * SECTION:hb-coretext
42  * @title: hb-coretext
43  * @short_description: CoreText integration
44  * @include: hb-coretext.h
45  *
46  * Functions for using HarfBuzz with the CoreText fonts.
47  **/
48
49 /* https://developer.apple.com/documentation/coretext/1508745-ctfontcreatewithgraphicsfont */
50 #define HB_CORETEXT_DEFAULT_FONT_SIZE 12.f
51
52 static void
53 release_table_data (void *user_data)
54 {
55   CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
56   CFRelease(cf_data);
57 }
58
59 static hb_blob_t *
60 _hb_cg_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
61 {
62   CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
63   CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
64   if (unlikely (!cf_data))
65     return nullptr;
66
67   const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
68   const size_t length = CFDataGetLength (cf_data);
69   if (!data || !length)
70   {
71     CFRelease (cf_data);
72     return nullptr;
73   }
74
75   return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
76                          reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
77                          release_table_data);
78 }
79
80 static void
81 _hb_cg_font_release (void *data)
82 {
83   CGFontRelease ((CGFontRef) data);
84 }
85
86
87 static CTFontDescriptorRef
88 get_last_resort_font_desc ()
89 {
90   // TODO Handle allocation failures?
91   CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
92   CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
93                                            (const void **) &last_resort,
94                                            1,
95                                            &kCFTypeArrayCallBacks);
96   CFRelease (last_resort);
97   CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
98                                                    (const void **) &kCTFontCascadeListAttribute,
99                                                    (const void **) &cascade_list,
100                                                    1,
101                                                    &kCFTypeDictionaryKeyCallBacks,
102                                                    &kCFTypeDictionaryValueCallBacks);
103   CFRelease (cascade_list);
104
105   CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
106   CFRelease (attributes);
107   return font_desc;
108 }
109
110 static void
111 release_data (void *info, const void *data, size_t size)
112 {
113   assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
114           hb_blob_get_data ((hb_blob_t *) info, nullptr) == data);
115
116   hb_blob_destroy ((hb_blob_t *) info);
117 }
118
119 static CGFontRef
120 create_cg_font (hb_face_t *face)
121 {
122   CGFontRef cg_font = nullptr;
123   if (face->destroy == _hb_cg_font_release)
124   {
125     cg_font = CGFontRetain ((CGFontRef) face->user_data);
126   }
127   else
128   {
129     hb_blob_t *blob = hb_face_reference_blob (face);
130     unsigned int blob_length;
131     const char *blob_data = hb_blob_get_data (blob, &blob_length);
132     if (unlikely (!blob_length))
133       DEBUG_MSG (CORETEXT, face, "Face has empty blob");
134
135     CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
136     if (likely (provider))
137     {
138       cg_font = CGFontCreateWithDataProvider (provider);
139       if (unlikely (!cg_font))
140         DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
141       CGDataProviderRelease (provider);
142     }
143   }
144   return cg_font;
145 }
146
147 static CTFontRef
148 create_ct_font (CGFontRef cg_font, CGFloat font_size)
149 {
150   CTFontRef ct_font = nullptr;
151
152   /* CoreText does not enable trak table usage / tracking when creating a CTFont
153    * using CTFontCreateWithGraphicsFont. The only way of enabling tracking seems
154    * to be through the CTFontCreateUIFontForLanguage call. */
155   CFStringRef cg_postscript_name = CGFontCopyPostScriptName (cg_font);
156   if (CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSText")) ||
157       CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSDisplay")))
158   {
159 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1080
160 # define kCTFontUIFontSystem kCTFontSystemFontType
161 # define kCTFontUIFontEmphasizedSystem kCTFontEmphasizedSystemFontType
162 #endif
163     CTFontUIFontType font_type = kCTFontUIFontSystem;
164     if (CFStringHasSuffix (cg_postscript_name, CFSTR ("-Bold")))
165       font_type = kCTFontUIFontEmphasizedSystem;
166
167     ct_font = CTFontCreateUIFontForLanguage (font_type, font_size, nullptr);
168     CFStringRef ct_result_name = CTFontCopyPostScriptName(ct_font);
169     if (CFStringCompare (ct_result_name, cg_postscript_name, 0) != kCFCompareEqualTo)
170     {
171       CFRelease(ct_font);
172       ct_font = nullptr;
173     }
174     CFRelease (ct_result_name);
175   }
176   CFRelease (cg_postscript_name);
177
178   if (!ct_font)
179     ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, nullptr, nullptr);
180
181   if (unlikely (!ct_font)) {
182     DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
183     return nullptr;
184   }
185
186   /* crbug.com/576941 and crbug.com/625902 and the investigation in the latter
187    * bug indicate that the cascade list reconfiguration occasionally causes
188    * crashes in CoreText on OS X 10.9, thus let's skip this step on older
189    * operating system versions. Except for the emoji font, where _not_
190    * reconfiguring the cascade list causes CoreText crashes. For details, see
191    * crbug.com/549610 */
192   // 0x00070000 stands for "kCTVersionNumber10_10", see CoreText.h
193   if (&CTGetCoreTextVersion != nullptr && CTGetCoreTextVersion() < 0x00070000) {
194     CFStringRef fontName = CTFontCopyPostScriptName (ct_font);
195     bool isEmojiFont = CFStringCompare (fontName, CFSTR("AppleColorEmoji"), 0) == kCFCompareEqualTo;
196     CFRelease (fontName);
197     if (!isEmojiFont)
198       return ct_font;
199   }
200
201   CFURLRef original_url = nullptr;
202 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
203   ATSFontRef atsFont;
204   FSRef fsref;
205   OSStatus status;
206   atsFont = CTFontGetPlatformFont (ct_font, NULL);
207   status = ATSFontGetFileReference (atsFont, &fsref);
208   if (status == noErr)
209     original_url = CFURLCreateFromFSRef (NULL, &fsref);
210 #else
211   original_url = (CFURLRef) CTFontCopyAttribute (ct_font, kCTFontURLAttribute);
212 #endif
213
214   /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
215    * font fallback which we don't need anyway. */
216   {
217     CTFontDescriptorRef last_resort_font_desc = get_last_resort_font_desc ();
218     CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, last_resort_font_desc);
219     CFRelease (last_resort_font_desc);
220     if (new_ct_font)
221     {
222       /* The CTFontCreateCopyWithAttributes call fails to stay on the same font
223        * when reconfiguring the cascade list and may switch to a different font
224        * when there are fonts that go by the same name, since the descriptor is
225        * just name and size.
226        *
227        * Avoid reconfiguring the cascade lists if the new font is outside the
228        * system locations that we cannot access from the sandboxed renderer
229        * process in Blink. This can be detected by the new file URL location
230        * that the newly found font points to. */
231       CFURLRef new_url = nullptr;
232 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
233       atsFont = CTFontGetPlatformFont (new_ct_font, NULL);
234       status = ATSFontGetFileReference (atsFont, &fsref);
235       if (status == noErr)
236         new_url = CFURLCreateFromFSRef (NULL, &fsref);
237 #else
238       new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
239 #endif
240       // Keep reconfigured font if URL cannot be retrieved (seems to be the case
241       // on Mac OS 10.12 Sierra), speculative fix for crbug.com/625606
242       if (!original_url || !new_url || CFEqual (original_url, new_url)) {
243         CFRelease (ct_font);
244         ct_font = new_ct_font;
245       } else {
246         CFRelease (new_ct_font);
247         DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
248       }
249       if (new_url)
250         CFRelease (new_url);
251     }
252     else
253       DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
254   }
255
256   if (original_url)
257     CFRelease (original_url);
258   return ct_font;
259 }
260
261 hb_coretext_face_data_t *
262 _hb_coretext_shaper_face_data_create (hb_face_t *face)
263 {
264   CGFontRef cg_font = create_cg_font (face);
265
266   if (unlikely (!cg_font))
267   {
268     DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
269     return nullptr;
270   }
271
272   return (hb_coretext_face_data_t *) cg_font;
273 }
274
275 void
276 _hb_coretext_shaper_face_data_destroy (hb_coretext_face_data_t *data)
277 {
278   CFRelease ((CGFontRef) data);
279 }
280
281 hb_face_t *
282 hb_coretext_face_create (CGFontRef cg_font)
283 {
284   return hb_face_create_for_tables (_hb_cg_reference_table, CGFontRetain (cg_font), _hb_cg_font_release);
285 }
286
287 /*
288  * Since: 0.9.10
289  */
290 CGFontRef
291 hb_coretext_face_get_cg_font (hb_face_t *face)
292 {
293   return (CGFontRef) (const void *) face->data.coretext;
294 }
295
296
297 hb_coretext_font_data_t *
298 _hb_coretext_shaper_font_data_create (hb_font_t *font)
299 {
300   hb_face_t *face = font->face;
301   const hb_coretext_face_data_t *face_data = face->data.coretext;
302   if (unlikely (!face_data)) return nullptr;
303   CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
304
305   CGFloat font_size = (CGFloat) (font->ptem <= 0.f ? HB_CORETEXT_DEFAULT_FONT_SIZE : font->ptem);
306   CTFontRef ct_font = create_ct_font (cg_font, font_size);
307
308   if (unlikely (!ct_font))
309   {
310     DEBUG_MSG (CORETEXT, font, "CGFont creation failed..");
311     return nullptr;
312   }
313
314   return (hb_coretext_font_data_t *) ct_font;
315 }
316
317 void
318 _hb_coretext_shaper_font_data_destroy (hb_coretext_font_data_t *data)
319 {
320   CFRelease ((CTFontRef) data);
321 }
322
323 static const hb_coretext_font_data_t *
324 hb_coretext_font_data_sync (hb_font_t *font)
325 {
326 retry:
327   const hb_coretext_font_data_t *data = font->data.coretext;
328   if (unlikely (!data)) return nullptr;
329
330   if (fabs (CTFontGetSize ((CTFontRef) data) - (CGFloat) font->ptem) > .5)
331   {
332     /* XXX-MT-bug
333      * Note that evaluating condition above can be dangerous if another thread
334      * got here first and destructed data.  That's, as always, bad use pattern.
335      * If you modify the font (change font size), other threads must not be
336      * using it at the same time.  However, since this check is delayed to
337      * when one actually tries to shape something, this is a XXX race condition
338      * (and the only one we have that I know of) right now.  Ie. you modify the
339      * font size in one thread, then (supposedly safely) try to use it from two
340      * or more threads and BOOM!  I'm not sure how to fix this.  We want RCU.
341      */
342
343     /* Drop and recreate. */
344     /* If someone dropped it in the mean time, throw it away and don't touch it.
345      * Otherwise, destruct it. */
346     if (likely (font->data.coretext.cmpexch (const_cast<hb_coretext_font_data_t *> (data), nullptr)))
347       _hb_coretext_shaper_font_data_destroy (const_cast<hb_coretext_font_data_t *> (data));
348     else
349       goto retry;
350   }
351   return font->data.coretext;
352 }
353
354
355 /*
356  * Since: 1.7.2
357  */
358 hb_font_t *
359 hb_coretext_font_create (CTFontRef ct_font)
360 {
361   CGFontRef cg_font = CTFontCopyGraphicsFont (ct_font, nullptr);
362   hb_face_t *face = hb_coretext_face_create (cg_font);
363   CFRelease (cg_font);
364   hb_font_t *font = hb_font_create (face);
365   hb_face_destroy (face);
366
367   if (unlikely (hb_object_is_immutable (font)))
368     return font;
369
370   hb_font_set_ptem (font, CTFontGetSize (ct_font));
371
372   /* Let there be dragons here... */
373   font->data.coretext.cmpexch (nullptr, (hb_coretext_font_data_t *) CFRetain (ct_font));
374
375   return font;
376 }
377
378 CTFontRef
379 hb_coretext_font_get_ct_font (hb_font_t *font)
380 {
381   const hb_coretext_font_data_t *data = hb_coretext_font_data_sync (font);
382   return data ? (CTFontRef) data : nullptr;
383 }
384
385
386 /*
387  * shaper
388  */
389
390 struct feature_record_t {
391   unsigned int feature;
392   unsigned int setting;
393 };
394
395 struct active_feature_t {
396   feature_record_t rec;
397   unsigned int order;
398
399   HB_INTERNAL static int cmp (const void *pa, const void *pb) {
400     const active_feature_t *a = (const active_feature_t *) pa;
401     const active_feature_t *b = (const active_feature_t *) pb;
402     return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
403            a->order < b->order ? -1 : a->order > b->order ? 1 :
404            a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
405            0;
406   }
407   bool operator== (const active_feature_t *f) {
408     return cmp (this, f) == 0;
409   }
410 };
411
412 struct feature_event_t {
413   unsigned int index;
414   bool start;
415   active_feature_t feature;
416
417   HB_INTERNAL static int cmp (const void *pa, const void *pb) {
418     const feature_event_t *a = (const feature_event_t *) pa;
419     const feature_event_t *b = (const feature_event_t *) pb;
420     return a->index < b->index ? -1 : a->index > b->index ? 1 :
421            a->start < b->start ? -1 : a->start > b->start ? 1 :
422            active_feature_t::cmp (&a->feature, &b->feature);
423   }
424 };
425
426 struct range_record_t {
427   CTFontRef font;
428   unsigned int index_first; /* == start */
429   unsigned int index_last;  /* == end - 1 */
430 };
431
432
433 hb_bool_t
434 _hb_coretext_shape (hb_shape_plan_t    *shape_plan,
435                     hb_font_t          *font,
436                     hb_buffer_t        *buffer,
437                     const hb_feature_t *features,
438                     unsigned int        num_features)
439 {
440   hb_face_t *face = font->face;
441   CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
442   CTFontRef ct_font = (CTFontRef) hb_coretext_font_data_sync (font);
443
444   CGFloat ct_font_size = CTFontGetSize (ct_font);
445   CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
446   CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
447
448   /* Attach marks to their bases, to match the 'ot' shaper.
449    * Adapted from a very old version of hb-ot-shape:hb_form_clusters().
450    * Note that this only makes us be closer to the 'ot' shaper,
451    * but by no means the same.  For example, if there's
452    * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
453    * continue pointing to B2 even though B2 was merged into B1's
454    * cluster... */
455   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
456   {
457     hb_unicode_funcs_t *unicode = buffer->unicode;
458     unsigned int count = buffer->len;
459     hb_glyph_info_t *info = buffer->info;
460     for (unsigned int i = 1; i < count; i++)
461       if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
462         buffer->merge_clusters (i - 1, i + 1);
463   }
464
465   hb_vector_t<feature_record_t> feature_records;
466   hb_vector_t<range_record_t> range_records;
467
468   /*
469    * Set up features.
470    * (copied + modified from code from hb-uniscribe.cc)
471    */
472   if (num_features)
473   {
474     /* Sort features by start/end events. */
475     hb_vector_t<feature_event_t> feature_events;
476     for (unsigned int i = 0; i < num_features; i++)
477     {
478       const hb_aat_feature_mapping_t * mapping = hb_aat_layout_find_feature_mapping (features[i].tag);
479       if (!mapping)
480         continue;
481
482       active_feature_t feature;
483       feature.rec.feature = mapping->aatFeatureType;
484       feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
485       feature.order = i;
486
487       feature_event_t *event;
488
489       event = feature_events.push ();
490       event->index = features[i].start;
491       event->start = true;
492       event->feature = feature;
493
494       event = feature_events.push ();
495       event->index = features[i].end;
496       event->start = false;
497       event->feature = feature;
498     }
499     feature_events.qsort ();
500     /* Add a strategic final event. */
501     {
502       active_feature_t feature;
503       feature.rec.feature = HB_TAG_NONE;
504       feature.rec.setting = 0;
505       feature.order = num_features + 1;
506
507       feature_event_t *event = feature_events.push ();
508       event->index = 0; /* This value does magic. */
509       event->start = false;
510       event->feature = feature;
511     }
512
513     /* Scan events and save features for each range. */
514     hb_vector_t<active_feature_t> active_features;
515     unsigned int last_index = 0;
516     for (unsigned int i = 0; i < feature_events.length; i++)
517     {
518       feature_event_t *event = &feature_events[i];
519
520       if (event->index != last_index)
521       {
522         /* Save a snapshot of active features and the range. */
523         range_record_t *range = range_records.push ();
524
525         if (active_features.length)
526         {
527           CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
528
529           /* TODO sort and resolve conflicting features? */
530           /* active_features.qsort (); */
531           for (unsigned int j = 0; j < active_features.length; j++)
532           {
533             CFStringRef keys[] = {
534               kCTFontFeatureTypeIdentifierKey,
535               kCTFontFeatureSelectorIdentifierKey
536             };
537             CFNumberRef values[] = {
538               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
539               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
540             };
541             static_assert ((ARRAY_LENGTH_CONST (keys) == ARRAY_LENGTH_CONST (values)), "");
542             CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
543                                                        (const void **) keys,
544                                                        (const void **) values,
545                                                        ARRAY_LENGTH (keys),
546                                                        &kCFTypeDictionaryKeyCallBacks,
547                                                        &kCFTypeDictionaryValueCallBacks);
548             for (unsigned int i = 0; i < ARRAY_LENGTH (values); i++)
549               CFRelease (values[i]);
550
551             CFArrayAppendValue (features_array, dict);
552             CFRelease (dict);
553
554           }
555
556           CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
557                                                            (const void **) &kCTFontFeatureSettingsAttribute,
558                                                            (const void **) &features_array,
559                                                            1,
560                                                            &kCFTypeDictionaryKeyCallBacks,
561                                                            &kCFTypeDictionaryValueCallBacks);
562           CFRelease (features_array);
563
564           CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
565           CFRelease (attributes);
566
567           range->font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, font_desc);
568           CFRelease (font_desc);
569         }
570         else
571         {
572           range->font = nullptr;
573         }
574
575         range->index_first = last_index;
576         range->index_last  = event->index - 1;
577
578         last_index = event->index;
579       }
580
581       if (event->start)
582       {
583         active_features.push (event->feature);
584       } else {
585         active_feature_t *feature = active_features.find (&event->feature);
586         if (feature)
587           active_features.remove (feature - active_features.arrayZ);
588       }
589     }
590   }
591
592   unsigned int scratch_size;
593   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
594
595 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
596   Type *name = (Type *) scratch; \
597   do { \
598     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
599     if (unlikely (_consumed > scratch_size)) \
600     { \
601       on_no_room; \
602       assert (0); \
603     } \
604     scratch += _consumed; \
605     scratch_size -= _consumed; \
606   } while (0)
607
608   ALLOCATE_ARRAY (UniChar, pchars, buffer->len * 2, /*nothing*/);
609   unsigned int chars_len = 0;
610   for (unsigned int i = 0; i < buffer->len; i++) {
611     hb_codepoint_t c = buffer->info[i].codepoint;
612     if (likely (c <= 0xFFFFu))
613       pchars[chars_len++] = c;
614     else if (unlikely (c > 0x10FFFFu))
615       pchars[chars_len++] = 0xFFFDu;
616     else {
617       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
618       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
619     }
620   }
621
622   ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, /*nothing*/);
623   chars_len = 0;
624   for (unsigned int i = 0; i < buffer->len; i++)
625   {
626     hb_codepoint_t c = buffer->info[i].codepoint;
627     unsigned int cluster = buffer->info[i].cluster;
628     log_clusters[chars_len++] = cluster;
629     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
630       log_clusters[chars_len++] = cluster; /* Surrogates. */
631   }
632
633 #define FAIL(...) \
634   HB_STMT_START { \
635     DEBUG_MSG (CORETEXT, nullptr, __VA_ARGS__); \
636     ret = false; \
637     goto fail; \
638   } HB_STMT_END
639
640   bool ret = true;
641   CFStringRef string_ref = nullptr;
642   CTLineRef line = nullptr;
643
644   if (false)
645   {
646 resize_and_retry:
647     DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
648     /* string_ref uses the scratch-buffer for backing store, and line references
649      * string_ref (via attr_string).  We must release those before resizing buffer. */
650     assert (string_ref);
651     assert (line);
652     CFRelease (string_ref);
653     CFRelease (line);
654     string_ref = nullptr;
655     line = nullptr;
656
657     /* Get previous start-of-scratch-area, that we use later for readjusting
658      * our existing scratch arrays. */
659     unsigned int old_scratch_used;
660     hb_buffer_t::scratch_buffer_t *old_scratch;
661     old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
662     old_scratch_used = scratch - old_scratch;
663
664     if (unlikely (!buffer->ensure (buffer->allocated * 2)))
665       FAIL ("Buffer resize failed");
666
667     /* Adjust scratch, pchars, and log_cluster arrays.  This is ugly, but really the
668      * cleanest way to do without completely restructuring the rest of this shaper. */
669     scratch = buffer->get_scratch_buffer (&scratch_size);
670     pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
671     log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
672     scratch += old_scratch_used;
673     scratch_size -= old_scratch_used;
674   }
675   {
676     string_ref = CFStringCreateWithCharactersNoCopy (nullptr,
677                                                      pchars, chars_len,
678                                                      kCFAllocatorNull);
679     if (unlikely (!string_ref))
680       FAIL ("CFStringCreateWithCharactersNoCopy failed");
681
682     /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
683     {
684       CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
685                                                                                   chars_len);
686       if (unlikely (!attr_string))
687         FAIL ("CFAttributedStringCreateMutable failed");
688       CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
689       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
690       {
691         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
692                                         kCTVerticalFormsAttributeName, kCFBooleanTrue);
693       }
694
695       if (buffer->props.language)
696       {
697 /* What's the iOS equivalent of this check?
698  * The symbols was introduced in iOS 7.0.
699  * At any rate, our fallback is safe and works fine. */
700 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1090
701 #  define kCTLanguageAttributeName CFSTR ("NSLanguage")
702 #endif
703         CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
704                                                             hb_language_to_string (buffer->props.language),
705                                                             kCFStringEncodingUTF8,
706                                                             kCFAllocatorNull);
707         if (unlikely (!lang))
708         {
709           CFRelease (attr_string);
710           FAIL ("CFStringCreateWithCStringNoCopy failed");
711         }
712         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
713                                         kCTLanguageAttributeName, lang);
714         CFRelease (lang);
715       }
716       CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
717                                       kCTFontAttributeName, ct_font);
718
719       if (num_features && range_records.length)
720       {
721         unsigned int start = 0;
722         range_record_t *last_range = &range_records[0];
723         for (unsigned int k = 0; k < chars_len; k++)
724         {
725           range_record_t *range = last_range;
726           while (log_clusters[k] < range->index_first)
727             range--;
728           while (log_clusters[k] > range->index_last)
729             range++;
730           if (range != last_range)
731           {
732             if (last_range->font)
733               CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
734                                               kCTFontAttributeName, last_range->font);
735
736             start = k;
737           }
738
739           last_range = range;
740         }
741         if (start != chars_len && last_range->font)
742           CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
743                                           kCTFontAttributeName, last_range->font);
744       }
745       /* Enable/disable kern if requested.
746        *
747        * Note: once kern is disabled, reenabling it doesn't currently seem to work in CoreText.
748        */
749       if (num_features)
750       {
751         unsigned int zeroint = 0;
752         CFNumberRef zero = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &zeroint);
753         for (unsigned int i = 0; i < num_features; i++)
754         {
755           const hb_feature_t &feature = features[i];
756           if (feature.tag == HB_TAG('k','e','r','n') &&
757               feature.start < chars_len && feature.start < feature.end)
758           {
759             CFRange feature_range = CFRangeMake (feature.start,
760                                                  hb_min (feature.end, chars_len) - feature.start);
761             if (feature.value)
762               CFAttributedStringRemoveAttribute (attr_string, feature_range, kCTKernAttributeName);
763             else
764               CFAttributedStringSetAttribute (attr_string, feature_range, kCTKernAttributeName, zero);
765           }
766         }
767         CFRelease (zero);
768       }
769
770       int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
771       CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
772 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
773       extern const CFStringRef kCTTypesetterOptionForcedEmbeddingLevel;
774 #endif
775       CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
776                                                     (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
777                                                     (const void **) &level_number,
778                                                     1,
779                                                     &kCFTypeDictionaryKeyCallBacks,
780                                                     &kCFTypeDictionaryValueCallBacks);
781       CFRelease (level_number);
782       if (unlikely (!options))
783       {
784         CFRelease (attr_string);
785         FAIL ("CFDictionaryCreate failed");
786       }
787
788       CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
789       CFRelease (options);
790       CFRelease (attr_string);
791       if (unlikely (!typesetter))
792         FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
793
794       line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
795       CFRelease (typesetter);
796       if (unlikely (!line))
797         FAIL ("CTTypesetterCreateLine failed");
798     }
799
800     CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
801     unsigned int num_runs = CFArrayGetCount (glyph_runs);
802     DEBUG_MSG (CORETEXT, nullptr, "Num runs: %d", num_runs);
803
804     buffer->len = 0;
805     uint32_t status_and = ~0, status_or = 0;
806     double advances_so_far = 0;
807     /* For right-to-left runs, CoreText returns the glyphs positioned such that
808      * any trailing whitespace is to the left of (0,0).  Adjust coordinate system
809      * to fix for that.  Test with any RTL string with trailing spaces.
810      * https://crbug.com/469028
811      */
812     if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
813     {
814       advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
815       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
816           advances_so_far = -advances_so_far;
817     }
818
819     const CFRange range_all = CFRangeMake (0, 0);
820
821     for (unsigned int i = 0; i < num_runs; i++)
822     {
823       CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
824       CTRunStatus run_status = CTRunGetStatus (run);
825       status_or  |= run_status;
826       status_and &= run_status;
827       DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
828       double run_advance = CTRunGetTypographicBounds (run, range_all, nullptr, nullptr, nullptr);
829       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
830           run_advance = -run_advance;
831       DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
832
833       /* CoreText does automatic font fallback (AKA "cascading") for  characters
834        * not supported by the requested font, and provides no way to turn it off,
835        * so we must detect if the returned run uses a font other than the requested
836        * one and fill in the buffer with .notdef glyphs instead of random glyph
837        * indices from a different font.
838        */
839       CFDictionaryRef attributes = CTRunGetAttributes (run);
840       CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
841       if (!CFEqual (run_ct_font, ct_font))
842       {
843         /* The run doesn't use our main font instance.  We have to figure out
844          * whether font fallback happened, or this is just CoreText giving us
845          * another CTFont using the same underlying CGFont.  CoreText seems
846          * to do that in a variety of situations, one of which being vertical
847          * text, but also perhaps for caching reasons.
848          *
849          * First, see if it uses any of our subfonts created to set font features...
850          *
851          * Next, compare the CGFont to the one we used to create our fonts.
852          * Even this doesn't work all the time.
853          *
854          * Finally, we compare PS names, which I don't think are unique...
855          *
856          * Looks like if we really want to be sure here we have to modify the
857          * font to change the name table, similar to what we do in the uniscribe
858          * backend.
859          *
860          * However, even that wouldn't work if we were passed in the CGFont to
861          * construct a hb_face to begin with.
862          *
863          * See: https://github.com/harfbuzz/harfbuzz/pull/36
864          *
865          * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
866          */
867         bool matched = false;
868         for (unsigned int i = 0; i < range_records.length; i++)
869           if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
870           {
871             matched = true;
872             break;
873           }
874         if (!matched)
875         {
876           CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, nullptr);
877           if (run_cg_font)
878           {
879             matched = CFEqual (run_cg_font, cg_font);
880             CFRelease (run_cg_font);
881           }
882         }
883         if (!matched)
884         {
885           CFStringRef font_ps_name = CTFontCopyName (ct_font, kCTFontPostScriptNameKey);
886           CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
887           CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
888           CFRelease (run_ps_name);
889           CFRelease (font_ps_name);
890           if (result == kCFCompareEqualTo)
891             matched = true;
892         }
893         if (!matched)
894         {
895           CFRange range = CTRunGetStringRange (run);
896           DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
897                      range.location, range.location + range.length);
898           if (!buffer->ensure_inplace (buffer->len + range.length))
899             goto resize_and_retry;
900           hb_glyph_info_t *info = buffer->info + buffer->len;
901
902           hb_codepoint_t notdef = 0;
903           hb_direction_t dir = buffer->props.direction;
904           hb_position_t x_advance, y_advance, x_offset, y_offset;
905           hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);
906           hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);
907           hb_position_t advance = x_advance + y_advance;
908           x_offset = -x_offset;
909           y_offset = -y_offset;
910
911           unsigned int old_len = buffer->len;
912           for (CFIndex j = range.location; j < range.location + range.length; j++)
913           {
914               UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
915               if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
916               {
917                 ch = CFStringGetCharacterAtIndex (string_ref, j - 1);
918                 if (hb_in_range<UniChar> (ch, 0xD800u, 0xDBFFu))
919                   /* This is the second of a surrogate pair.  Don't need .notdef
920                    * for this one. */
921                   continue;
922               }
923               if (buffer->unicode->is_default_ignorable (ch))
924                 continue;
925
926               info->codepoint = notdef;
927               info->cluster = log_clusters[j];
928
929               info->mask = advance;
930               info->var1.i32 = x_offset;
931               info->var2.i32 = y_offset;
932
933               info++;
934               buffer->len++;
935           }
936           if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
937             buffer->reverse_range (old_len, buffer->len);
938           advances_so_far += run_advance;
939           continue;
940         }
941       }
942
943       unsigned int num_glyphs = CTRunGetGlyphCount (run);
944       if (num_glyphs == 0)
945         continue;
946
947       if (!buffer->ensure_inplace (buffer->len + num_glyphs))
948         goto resize_and_retry;
949
950       hb_glyph_info_t *run_info = buffer->info + buffer->len;
951
952       /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
953        * succeed, and so copying data to our own buffer will be rare.  Reports
954        * have it that this changed in OS X 10.10 Yosemite, and nullptr is returned
955        * frequently.  At any rate, we can test that codepath by setting USE_PTR
956        * to false. */
957
958 #define USE_PTR true
959
960 #define SCRATCH_SAVE() \
961   unsigned int scratch_size_saved = scratch_size; \
962   hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
963
964 #define SCRATCH_RESTORE() \
965   scratch_size = scratch_size_saved; \
966   scratch = scratch_saved
967
968       { /* Setup glyphs */
969         SCRATCH_SAVE();
970         const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : nullptr;
971         if (!glyphs) {
972           ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
973           CTRunGetGlyphs (run, range_all, glyph_buf);
974           glyphs = glyph_buf;
975         }
976         const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : nullptr;
977         if (!string_indices) {
978           ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
979           CTRunGetStringIndices (run, range_all, index_buf);
980           string_indices = index_buf;
981         }
982         hb_glyph_info_t *info = run_info;
983         for (unsigned int j = 0; j < num_glyphs; j++)
984         {
985           info->codepoint = glyphs[j];
986           info->cluster = log_clusters[string_indices[j]];
987           info++;
988         }
989         SCRATCH_RESTORE();
990       }
991       {
992         /* Setup positions.
993          * Note that CoreText does not return advances for glyphs.  As such,
994          * for all but last glyph, we use the delta position to next glyph as
995          * advance (in the advance direction only), and for last glyph we set
996          * whatever is needed to make the whole run's advance add up. */
997         SCRATCH_SAVE();
998         const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : nullptr;
999         if (!positions) {
1000           ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1001           CTRunGetPositions (run, range_all, position_buf);
1002           positions = position_buf;
1003         }
1004         hb_glyph_info_t *info = run_info;
1005         if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1006         {
1007           hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1008           for (unsigned int j = 0; j < num_glyphs; j++)
1009           {
1010             double advance;
1011             if (likely (j + 1 < num_glyphs))
1012               advance = positions[j + 1].x - positions[j].x;
1013             else /* last glyph */
1014               advance = run_advance - (positions[j].x - positions[0].x);
1015             info->mask = advance * x_mult;
1016             info->var1.i32 = x_offset;
1017             info->var2.i32 = positions[j].y * y_mult;
1018             info++;
1019           }
1020         }
1021         else
1022         {
1023           hb_position_t y_offset = (positions[0].y - advances_so_far) * y_mult;
1024           for (unsigned int j = 0; j < num_glyphs; j++)
1025           {
1026             double advance;
1027             if (likely (j + 1 < num_glyphs))
1028               advance = positions[j + 1].y - positions[j].y;
1029             else /* last glyph */
1030               advance = run_advance - (positions[j].y - positions[0].y);
1031             info->mask = advance * y_mult;
1032             info->var1.i32 = positions[j].x * x_mult;
1033             info->var2.i32 = y_offset;
1034             info++;
1035           }
1036         }
1037         SCRATCH_RESTORE();
1038         advances_so_far += run_advance;
1039       }
1040 #undef SCRATCH_RESTORE
1041 #undef SCRATCH_SAVE
1042 #undef USE_PTR
1043 #undef ALLOCATE_ARRAY
1044
1045       buffer->len += num_glyphs;
1046     }
1047
1048     /* Mac OS 10.6 doesn't have kCTTypesetterOptionForcedEmbeddingLevel,
1049      * or if it does, it doesn't respect it.  So we get runs with wrong
1050      * directions.  As such, disable the assert...  It wouldn't crash, but
1051      * cursoring will be off...
1052      *
1053      * https://crbug.com/419769
1054      */
1055     if (false)
1056     {
1057       /* Make sure all runs had the expected direction. */
1058       HB_UNUSED bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1059       assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1060       assert (bool (status_or  & kCTRunStatusRightToLeft) == backward);
1061     }
1062
1063     buffer->clear_positions ();
1064
1065     unsigned int count = buffer->len;
1066     hb_glyph_info_t *info = buffer->info;
1067     hb_glyph_position_t *pos = buffer->pos;
1068     if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1069       for (unsigned int i = 0; i < count; i++)
1070       {
1071         pos->x_advance = info->mask;
1072         pos->x_offset = info->var1.i32;
1073         pos->y_offset = info->var2.i32;
1074
1075         info++, pos++;
1076       }
1077     else
1078       for (unsigned int i = 0; i < count; i++)
1079       {
1080         pos->y_advance = info->mask;
1081         pos->x_offset = info->var1.i32;
1082         pos->y_offset = info->var2.i32;
1083
1084         info++, pos++;
1085       }
1086
1087     /* Fix up clusters so that we never return out-of-order indices;
1088      * if core text has reordered glyphs, we'll merge them to the
1089      * beginning of the reordered cluster.  CoreText is nice enough
1090      * to tell us whenever it has produced nonmonotonic results...
1091      * Note that we assume the input clusters were nonmonotonic to
1092      * begin with.
1093      *
1094      * This does *not* mean we'll form the same clusters as Uniscribe
1095      * or the native OT backend, only that the cluster indices will be
1096      * monotonic in the output buffer. */
1097     if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1098     {
1099       hb_glyph_info_t *info = buffer->info;
1100       if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1101       {
1102         unsigned int cluster = info[count - 1].cluster;
1103         for (unsigned int i = count - 1; i > 0; i--)
1104         {
1105           cluster = hb_min (cluster, info[i - 1].cluster);
1106           info[i - 1].cluster = cluster;
1107         }
1108       }
1109       else
1110       {
1111         unsigned int cluster = info[0].cluster;
1112         for (unsigned int i = 1; i < count; i++)
1113         {
1114           cluster = hb_min (cluster, info[i].cluster);
1115           info[i].cluster = cluster;
1116         }
1117       }
1118     }
1119   }
1120
1121   buffer->unsafe_to_break_all ();
1122
1123 #undef FAIL
1124
1125 fail:
1126   if (string_ref)
1127     CFRelease (string_ref);
1128   if (line)
1129     CFRelease (line);
1130
1131   for (unsigned int i = 0; i < range_records.length; i++)
1132     if (range_records[i].font)
1133       CFRelease (range_records[i].font);
1134
1135   return ret;
1136 }
1137
1138
1139 #endif