Imported Upstream version 2.6.7
[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 /**
282  * hb_coretext_face_create:
283  * @cg_font: The CGFontRef to work upon
284  *
285  * Creates an #hb_face_t face object from the specified
286  * CGFontRef.
287  *
288  * Return value: the new #hb_face_t face object
289  *
290  * Since: 0.9.10
291  */
292 hb_face_t *
293 hb_coretext_face_create (CGFontRef cg_font)
294 {
295   return hb_face_create_for_tables (_hb_cg_reference_table, CGFontRetain (cg_font), _hb_cg_font_release);
296 }
297
298 /**
299  * hb_coretext_face_get_cg_font:
300  * @face: The #hb_face_t to work upon
301  *
302  * Fetches the CGFontRef associated with an #hb_face_t
303  * face object
304  *
305  * Return value: the CGFontRef found
306  *
307  * Since: 0.9.10
308  */
309 CGFontRef
310 hb_coretext_face_get_cg_font (hb_face_t *face)
311 {
312   return (CGFontRef) (const void *) face->data.coretext;
313 }
314
315
316 hb_coretext_font_data_t *
317 _hb_coretext_shaper_font_data_create (hb_font_t *font)
318 {
319   hb_face_t *face = font->face;
320   const hb_coretext_face_data_t *face_data = face->data.coretext;
321   if (unlikely (!face_data)) return nullptr;
322   CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
323
324   CGFloat font_size = (CGFloat) (font->ptem <= 0.f ? HB_CORETEXT_DEFAULT_FONT_SIZE : font->ptem);
325   CTFontRef ct_font = create_ct_font (cg_font, font_size);
326
327   if (unlikely (!ct_font))
328   {
329     DEBUG_MSG (CORETEXT, font, "CGFont creation failed..");
330     return nullptr;
331   }
332
333   return (hb_coretext_font_data_t *) ct_font;
334 }
335
336 void
337 _hb_coretext_shaper_font_data_destroy (hb_coretext_font_data_t *data)
338 {
339   CFRelease ((CTFontRef) data);
340 }
341
342 static const hb_coretext_font_data_t *
343 hb_coretext_font_data_sync (hb_font_t *font)
344 {
345 retry:
346   const hb_coretext_font_data_t *data = font->data.coretext;
347   if (unlikely (!data)) return nullptr;
348
349   if (fabs (CTFontGetSize ((CTFontRef) data) - (CGFloat) font->ptem) > .5)
350   {
351     /* XXX-MT-bug
352      * Note that evaluating condition above can be dangerous if another thread
353      * got here first and destructed data.  That's, as always, bad use pattern.
354      * If you modify the font (change font size), other threads must not be
355      * using it at the same time.  However, since this check is delayed to
356      * when one actually tries to shape something, this is a XXX race condition
357      * (and the only one we have that I know of) right now.  Ie. you modify the
358      * font size in one thread, then (supposedly safely) try to use it from two
359      * or more threads and BOOM!  I'm not sure how to fix this.  We want RCU.
360      */
361
362     /* Drop and recreate. */
363     /* If someone dropped it in the mean time, throw it away and don't touch it.
364      * Otherwise, destruct it. */
365     if (likely (font->data.coretext.cmpexch (const_cast<hb_coretext_font_data_t *> (data), nullptr)))
366       _hb_coretext_shaper_font_data_destroy (const_cast<hb_coretext_font_data_t *> (data));
367     else
368       goto retry;
369   }
370   return font->data.coretext;
371 }
372
373 /**
374  * hb_coretext_font_create:
375  * @ct_font: The CTFontRef to work upon
376  *
377  * Creates an #hb_font_t font object from the specified
378  * CTFontRef.
379  *
380  * Return value: the new #hb_font_t font object
381  *
382  * Since: 1.7.2
383  **/
384 hb_font_t *
385 hb_coretext_font_create (CTFontRef ct_font)
386 {
387   CGFontRef cg_font = CTFontCopyGraphicsFont (ct_font, nullptr);
388   hb_face_t *face = hb_coretext_face_create (cg_font);
389   CFRelease (cg_font);
390   hb_font_t *font = hb_font_create (face);
391   hb_face_destroy (face);
392
393   if (unlikely (hb_object_is_immutable (font)))
394     return font;
395
396   hb_font_set_ptem (font, CTFontGetSize (ct_font));
397
398   /* Let there be dragons here... */
399   font->data.coretext.cmpexch (nullptr, (hb_coretext_font_data_t *) CFRetain (ct_font));
400
401   return font;
402 }
403
404 /**
405  * hb_coretext_face_get_ct_font:
406  * @font: #hb_font_t to work upon
407  *
408  * Fetches the CTFontRef associated with the specified
409  * #hb_font_t font object.
410  *
411  * Return value: the CTFontRef found
412  *
413  * Since: 0.9.10
414  */
415 CTFontRef
416 hb_coretext_font_get_ct_font (hb_font_t *font)
417 {
418   const hb_coretext_font_data_t *data = hb_coretext_font_data_sync (font);
419   return data ? (CTFontRef) data : nullptr;
420 }
421
422
423 /*
424  * shaper
425  */
426
427 struct feature_record_t {
428   unsigned int feature;
429   unsigned int setting;
430 };
431
432 struct active_feature_t {
433   feature_record_t rec;
434   unsigned int order;
435
436   HB_INTERNAL static int cmp (const void *pa, const void *pb) {
437     const active_feature_t *a = (const active_feature_t *) pa;
438     const active_feature_t *b = (const active_feature_t *) pb;
439     return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
440            a->order < b->order ? -1 : a->order > b->order ? 1 :
441            a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
442            0;
443   }
444   bool operator== (const active_feature_t *f) {
445     return cmp (this, f) == 0;
446   }
447 };
448
449 struct feature_event_t {
450   unsigned int index;
451   bool start;
452   active_feature_t feature;
453
454   HB_INTERNAL static int cmp (const void *pa, const void *pb) {
455     const feature_event_t *a = (const feature_event_t *) pa;
456     const feature_event_t *b = (const feature_event_t *) pb;
457     return a->index < b->index ? -1 : a->index > b->index ? 1 :
458            a->start < b->start ? -1 : a->start > b->start ? 1 :
459            active_feature_t::cmp (&a->feature, &b->feature);
460   }
461 };
462
463 struct range_record_t {
464   CTFontRef font;
465   unsigned int index_first; /* == start */
466   unsigned int index_last;  /* == end - 1 */
467 };
468
469
470 hb_bool_t
471 _hb_coretext_shape (hb_shape_plan_t    *shape_plan,
472                     hb_font_t          *font,
473                     hb_buffer_t        *buffer,
474                     const hb_feature_t *features,
475                     unsigned int        num_features)
476 {
477   hb_face_t *face = font->face;
478   CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
479   CTFontRef ct_font = (CTFontRef) hb_coretext_font_data_sync (font);
480
481   CGFloat ct_font_size = CTFontGetSize (ct_font);
482   CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
483   CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
484
485   /* Attach marks to their bases, to match the 'ot' shaper.
486    * Adapted from a very old version of hb-ot-shape:hb_form_clusters().
487    * Note that this only makes us be closer to the 'ot' shaper,
488    * but by no means the same.  For example, if there's
489    * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
490    * continue pointing to B2 even though B2 was merged into B1's
491    * cluster... */
492   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
493   {
494     hb_unicode_funcs_t *unicode = buffer->unicode;
495     unsigned int count = buffer->len;
496     hb_glyph_info_t *info = buffer->info;
497     for (unsigned int i = 1; i < count; i++)
498       if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
499         buffer->merge_clusters (i - 1, i + 1);
500   }
501
502   hb_vector_t<feature_record_t> feature_records;
503   hb_vector_t<range_record_t> range_records;
504
505   /*
506    * Set up features.
507    * (copied + modified from code from hb-uniscribe.cc)
508    */
509   if (num_features)
510   {
511     /* Sort features by start/end events. */
512     hb_vector_t<feature_event_t> feature_events;
513     for (unsigned int i = 0; i < num_features; i++)
514     {
515       active_feature_t feature;
516
517 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1010
518       const hb_aat_feature_mapping_t * mapping = hb_aat_layout_find_feature_mapping (features[i].tag);
519       if (!mapping)
520         continue;
521
522       feature.rec.feature = mapping->aatFeatureType;
523       feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
524 #else
525       feature.rec.feature = features[i].tag;
526       feature.rec.setting = features[i].value;
527 #endif
528       feature.order = i;
529
530       feature_event_t *event;
531
532       event = feature_events.push ();
533       event->index = features[i].start;
534       event->start = true;
535       event->feature = feature;
536
537       event = feature_events.push ();
538       event->index = features[i].end;
539       event->start = false;
540       event->feature = feature;
541     }
542     feature_events.qsort ();
543     /* Add a strategic final event. */
544     {
545       active_feature_t feature;
546       feature.rec.feature = HB_TAG_NONE;
547       feature.rec.setting = 0;
548       feature.order = num_features + 1;
549
550       feature_event_t *event = feature_events.push ();
551       event->index = 0; /* This value does magic. */
552       event->start = false;
553       event->feature = feature;
554     }
555
556     /* Scan events and save features for each range. */
557     hb_vector_t<active_feature_t> active_features;
558     unsigned int last_index = 0;
559     for (unsigned int i = 0; i < feature_events.length; i++)
560     {
561       feature_event_t *event = &feature_events[i];
562
563       if (event->index != last_index)
564       {
565         /* Save a snapshot of active features and the range. */
566         range_record_t *range = range_records.push ();
567
568         if (active_features.length)
569         {
570           CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
571
572           /* TODO sort and resolve conflicting features? */
573           /* active_features.qsort (); */
574           for (unsigned int j = 0; j < active_features.length; j++)
575           {
576 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1010
577             CFStringRef keys[] = {
578               kCTFontFeatureTypeIdentifierKey,
579               kCTFontFeatureSelectorIdentifierKey
580             };
581             CFNumberRef values[] = {
582               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
583               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
584             };
585 #else
586             char tag[5] = {HB_UNTAG (active_features[j].rec.feature)};
587             CFTypeRef keys[] = {
588               kCTFontOpenTypeFeatureTag,
589               kCTFontOpenTypeFeatureValue
590             };
591             CFTypeRef values[] = {
592               CFStringCreateWithCString (kCFAllocatorDefault, tag, kCFStringEncodingASCII),
593               CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
594             };
595 #endif
596             static_assert ((ARRAY_LENGTH_CONST (keys) == ARRAY_LENGTH_CONST (values)), "");
597             CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
598                                                        (const void **) keys,
599                                                        (const void **) values,
600                                                        ARRAY_LENGTH (keys),
601                                                        &kCFTypeDictionaryKeyCallBacks,
602                                                        &kCFTypeDictionaryValueCallBacks);
603             for (unsigned int i = 0; i < ARRAY_LENGTH (values); i++)
604               CFRelease (values[i]);
605
606             CFArrayAppendValue (features_array, dict);
607             CFRelease (dict);
608
609           }
610
611           CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
612                                                            (const void **) &kCTFontFeatureSettingsAttribute,
613                                                            (const void **) &features_array,
614                                                            1,
615                                                            &kCFTypeDictionaryKeyCallBacks,
616                                                            &kCFTypeDictionaryValueCallBacks);
617           CFRelease (features_array);
618
619           CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
620           CFRelease (attributes);
621
622           range->font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, font_desc);
623           CFRelease (font_desc);
624         }
625         else
626         {
627           range->font = nullptr;
628         }
629
630         range->index_first = last_index;
631         range->index_last  = event->index - 1;
632
633         last_index = event->index;
634       }
635
636       if (event->start)
637       {
638         active_features.push (event->feature);
639       } else {
640         active_feature_t *feature = active_features.find (&event->feature);
641         if (feature)
642           active_features.remove (feature - active_features.arrayZ);
643       }
644     }
645   }
646
647   unsigned int scratch_size;
648   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
649
650 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
651   Type *name = (Type *) scratch; \
652   do { \
653     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
654     if (unlikely (_consumed > scratch_size)) \
655     { \
656       on_no_room; \
657       assert (0); \
658     } \
659     scratch += _consumed; \
660     scratch_size -= _consumed; \
661   } while (0)
662
663   ALLOCATE_ARRAY (UniChar, pchars, buffer->len * 2, ((void)nullptr) /*nothing*/);
664   unsigned int chars_len = 0;
665   for (unsigned int i = 0; i < buffer->len; i++) {
666     hb_codepoint_t c = buffer->info[i].codepoint;
667     if (likely (c <= 0xFFFFu))
668       pchars[chars_len++] = c;
669     else if (unlikely (c > 0x10FFFFu))
670       pchars[chars_len++] = 0xFFFDu;
671     else {
672       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
673       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
674     }
675   }
676
677   ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, ((void)nullptr) /*nothing*/);
678   chars_len = 0;
679   for (unsigned int i = 0; i < buffer->len; i++)
680   {
681     hb_codepoint_t c = buffer->info[i].codepoint;
682     unsigned int cluster = buffer->info[i].cluster;
683     log_clusters[chars_len++] = cluster;
684     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
685       log_clusters[chars_len++] = cluster; /* Surrogates. */
686   }
687
688 #define FAIL(...) \
689   HB_STMT_START { \
690     DEBUG_MSG (CORETEXT, nullptr, __VA_ARGS__); \
691     ret = false; \
692     goto fail; \
693   } HB_STMT_END
694
695   bool ret = true;
696   CFStringRef string_ref = nullptr;
697   CTLineRef line = nullptr;
698
699   if (false)
700   {
701 resize_and_retry:
702     DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
703     /* string_ref uses the scratch-buffer for backing store, and line references
704      * string_ref (via attr_string).  We must release those before resizing buffer. */
705     assert (string_ref);
706     assert (line);
707     CFRelease (string_ref);
708     CFRelease (line);
709     string_ref = nullptr;
710     line = nullptr;
711
712     /* Get previous start-of-scratch-area, that we use later for readjusting
713      * our existing scratch arrays. */
714     unsigned int old_scratch_used;
715     hb_buffer_t::scratch_buffer_t *old_scratch;
716     old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
717     old_scratch_used = scratch - old_scratch;
718
719     if (unlikely (!buffer->ensure (buffer->allocated * 2)))
720       FAIL ("Buffer resize failed");
721
722     /* Adjust scratch, pchars, and log_cluster arrays.  This is ugly, but really the
723      * cleanest way to do without completely restructuring the rest of this shaper. */
724     scratch = buffer->get_scratch_buffer (&scratch_size);
725     pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
726     log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
727     scratch += old_scratch_used;
728     scratch_size -= old_scratch_used;
729   }
730   {
731     string_ref = CFStringCreateWithCharactersNoCopy (nullptr,
732                                                      pchars, chars_len,
733                                                      kCFAllocatorNull);
734     if (unlikely (!string_ref))
735       FAIL ("CFStringCreateWithCharactersNoCopy failed");
736
737     /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
738     {
739       CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
740                                                                                   chars_len);
741       if (unlikely (!attr_string))
742         FAIL ("CFAttributedStringCreateMutable failed");
743       CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
744       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
745       {
746         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
747                                         kCTVerticalFormsAttributeName, kCFBooleanTrue);
748       }
749
750       if (buffer->props.language)
751       {
752 /* What's the iOS equivalent of this check?
753  * The symbols was introduced in iOS 7.0.
754  * At any rate, our fallback is safe and works fine. */
755 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1090
756 #  define kCTLanguageAttributeName CFSTR ("NSLanguage")
757 #endif
758         CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
759                                                             hb_language_to_string (buffer->props.language),
760                                                             kCFStringEncodingUTF8,
761                                                             kCFAllocatorNull);
762         if (unlikely (!lang))
763         {
764           CFRelease (attr_string);
765           FAIL ("CFStringCreateWithCStringNoCopy failed");
766         }
767         CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
768                                         kCTLanguageAttributeName, lang);
769         CFRelease (lang);
770       }
771       CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
772                                       kCTFontAttributeName, ct_font);
773
774       if (num_features && range_records.length)
775       {
776         unsigned int start = 0;
777         range_record_t *last_range = &range_records[0];
778         for (unsigned int k = 0; k < chars_len; k++)
779         {
780           range_record_t *range = last_range;
781           while (log_clusters[k] < range->index_first)
782             range--;
783           while (log_clusters[k] > range->index_last)
784             range++;
785           if (range != last_range)
786           {
787             if (last_range->font)
788               CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
789                                               kCTFontAttributeName, last_range->font);
790
791             start = k;
792           }
793
794           last_range = range;
795         }
796         if (start != chars_len && last_range->font)
797           CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
798                                           kCTFontAttributeName, last_range->font);
799       }
800       /* Enable/disable kern if requested.
801        *
802        * Note: once kern is disabled, reenabling it doesn't currently seem to work in CoreText.
803        */
804       if (num_features)
805       {
806         unsigned int zeroint = 0;
807         CFNumberRef zero = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &zeroint);
808         for (unsigned int i = 0; i < num_features; i++)
809         {
810           const hb_feature_t &feature = features[i];
811           if (feature.tag == HB_TAG('k','e','r','n') &&
812               feature.start < chars_len && feature.start < feature.end)
813           {
814             CFRange feature_range = CFRangeMake (feature.start,
815                                                  hb_min (feature.end, chars_len) - feature.start);
816             if (feature.value)
817               CFAttributedStringRemoveAttribute (attr_string, feature_range, kCTKernAttributeName);
818             else
819               CFAttributedStringSetAttribute (attr_string, feature_range, kCTKernAttributeName, zero);
820           }
821         }
822         CFRelease (zero);
823       }
824
825       int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
826       CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
827 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
828       extern const CFStringRef kCTTypesetterOptionForcedEmbeddingLevel;
829 #endif
830       CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
831                                                     (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
832                                                     (const void **) &level_number,
833                                                     1,
834                                                     &kCFTypeDictionaryKeyCallBacks,
835                                                     &kCFTypeDictionaryValueCallBacks);
836       CFRelease (level_number);
837       if (unlikely (!options))
838       {
839         CFRelease (attr_string);
840         FAIL ("CFDictionaryCreate failed");
841       }
842
843       CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
844       CFRelease (options);
845       CFRelease (attr_string);
846       if (unlikely (!typesetter))
847         FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
848
849       line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
850       CFRelease (typesetter);
851       if (unlikely (!line))
852         FAIL ("CTTypesetterCreateLine failed");
853     }
854
855     CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
856     unsigned int num_runs = CFArrayGetCount (glyph_runs);
857     DEBUG_MSG (CORETEXT, nullptr, "Num runs: %d", num_runs);
858
859     buffer->len = 0;
860     uint32_t status_and = ~0, status_or = 0;
861     double advances_so_far = 0;
862     /* For right-to-left runs, CoreText returns the glyphs positioned such that
863      * any trailing whitespace is to the left of (0,0).  Adjust coordinate system
864      * to fix for that.  Test with any RTL string with trailing spaces.
865      * https://crbug.com/469028
866      */
867     if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
868     {
869       advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
870       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
871           advances_so_far = -advances_so_far;
872     }
873
874     const CFRange range_all = CFRangeMake (0, 0);
875
876     for (unsigned int i = 0; i < num_runs; i++)
877     {
878       CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
879       CTRunStatus run_status = CTRunGetStatus (run);
880       status_or  |= run_status;
881       status_and &= run_status;
882       DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
883       double run_advance = CTRunGetTypographicBounds (run, range_all, nullptr, nullptr, nullptr);
884       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
885           run_advance = -run_advance;
886       DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
887
888       /* CoreText does automatic font fallback (AKA "cascading") for  characters
889        * not supported by the requested font, and provides no way to turn it off,
890        * so we must detect if the returned run uses a font other than the requested
891        * one and fill in the buffer with .notdef glyphs instead of random glyph
892        * indices from a different font.
893        */
894       CFDictionaryRef attributes = CTRunGetAttributes (run);
895       CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
896       if (!CFEqual (run_ct_font, ct_font))
897       {
898         /* The run doesn't use our main font instance.  We have to figure out
899          * whether font fallback happened, or this is just CoreText giving us
900          * another CTFont using the same underlying CGFont.  CoreText seems
901          * to do that in a variety of situations, one of which being vertical
902          * text, but also perhaps for caching reasons.
903          *
904          * First, see if it uses any of our subfonts created to set font features...
905          *
906          * Next, compare the CGFont to the one we used to create our fonts.
907          * Even this doesn't work all the time.
908          *
909          * Finally, we compare PS names, which I don't think are unique...
910          *
911          * Looks like if we really want to be sure here we have to modify the
912          * font to change the name table, similar to what we do in the uniscribe
913          * backend.
914          *
915          * However, even that wouldn't work if we were passed in the CGFont to
916          * construct a hb_face to begin with.
917          *
918          * See: https://github.com/harfbuzz/harfbuzz/pull/36
919          *
920          * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
921          */
922         bool matched = false;
923         for (unsigned int i = 0; i < range_records.length; i++)
924           if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
925           {
926             matched = true;
927             break;
928           }
929         if (!matched)
930         {
931           CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, nullptr);
932           if (run_cg_font)
933           {
934             matched = CFEqual (run_cg_font, cg_font);
935             CFRelease (run_cg_font);
936           }
937         }
938         if (!matched)
939         {
940           CFStringRef font_ps_name = CTFontCopyName (ct_font, kCTFontPostScriptNameKey);
941           CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
942           CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
943           CFRelease (run_ps_name);
944           CFRelease (font_ps_name);
945           if (result == kCFCompareEqualTo)
946             matched = true;
947         }
948         if (!matched)
949         {
950           CFRange range = CTRunGetStringRange (run);
951           DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
952                      range.location, range.location + range.length);
953           if (!buffer->ensure_inplace (buffer->len + range.length))
954             goto resize_and_retry;
955           hb_glyph_info_t *info = buffer->info + buffer->len;
956
957           hb_codepoint_t notdef = 0;
958           hb_direction_t dir = buffer->props.direction;
959           hb_position_t x_advance, y_advance, x_offset, y_offset;
960           hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);
961           hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);
962           hb_position_t advance = x_advance + y_advance;
963           x_offset = -x_offset;
964           y_offset = -y_offset;
965
966           unsigned int old_len = buffer->len;
967           for (CFIndex j = range.location; j < range.location + range.length; j++)
968           {
969               UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
970               if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
971               {
972                 ch = CFStringGetCharacterAtIndex (string_ref, j - 1);
973                 if (hb_in_range<UniChar> (ch, 0xD800u, 0xDBFFu))
974                   /* This is the second of a surrogate pair.  Don't need .notdef
975                    * for this one. */
976                   continue;
977               }
978               if (buffer->unicode->is_default_ignorable (ch))
979                 continue;
980
981               info->codepoint = notdef;
982               info->cluster = log_clusters[j];
983
984               info->mask = advance;
985               info->var1.i32 = x_offset;
986               info->var2.i32 = y_offset;
987
988               info++;
989               buffer->len++;
990           }
991           if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
992             buffer->reverse_range (old_len, buffer->len);
993           advances_so_far += run_advance;
994           continue;
995         }
996       }
997
998       unsigned int num_glyphs = CTRunGetGlyphCount (run);
999       if (num_glyphs == 0)
1000         continue;
1001
1002       if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1003         goto resize_and_retry;
1004
1005       hb_glyph_info_t *run_info = buffer->info + buffer->len;
1006
1007       /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
1008        * succeed, and so copying data to our own buffer will be rare.  Reports
1009        * have it that this changed in OS X 10.10 Yosemite, and nullptr is returned
1010        * frequently.  At any rate, we can test that codepath by setting USE_PTR
1011        * to false. */
1012
1013 #define USE_PTR true
1014
1015 #define SCRATCH_SAVE() \
1016   unsigned int scratch_size_saved = scratch_size; \
1017   hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1018
1019 #define SCRATCH_RESTORE() \
1020   scratch_size = scratch_size_saved; \
1021   scratch = scratch_saved
1022
1023       { /* Setup glyphs */
1024         SCRATCH_SAVE();
1025         const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : nullptr;
1026         if (!glyphs) {
1027           ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1028           CTRunGetGlyphs (run, range_all, glyph_buf);
1029           glyphs = glyph_buf;
1030         }
1031         const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : nullptr;
1032         if (!string_indices) {
1033           ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
1034           CTRunGetStringIndices (run, range_all, index_buf);
1035           string_indices = index_buf;
1036         }
1037         hb_glyph_info_t *info = run_info;
1038         for (unsigned int j = 0; j < num_glyphs; j++)
1039         {
1040           info->codepoint = glyphs[j];
1041           info->cluster = log_clusters[string_indices[j]];
1042           info++;
1043         }
1044         SCRATCH_RESTORE();
1045       }
1046       {
1047         /* Setup positions.
1048          * Note that CoreText does not return advances for glyphs.  As such,
1049          * for all but last glyph, we use the delta position to next glyph as
1050          * advance (in the advance direction only), and for last glyph we set
1051          * whatever is needed to make the whole run's advance add up. */
1052         SCRATCH_SAVE();
1053         const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : nullptr;
1054         if (!positions) {
1055           ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1056           CTRunGetPositions (run, range_all, position_buf);
1057           positions = position_buf;
1058         }
1059         hb_glyph_info_t *info = run_info;
1060         if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1061         {
1062           hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1063           for (unsigned int j = 0; j < num_glyphs; j++)
1064           {
1065             double advance;
1066             if (likely (j + 1 < num_glyphs))
1067               advance = positions[j + 1].x - positions[j].x;
1068             else /* last glyph */
1069               advance = run_advance - (positions[j].x - positions[0].x);
1070             info->mask = advance * x_mult;
1071             info->var1.i32 = x_offset;
1072             info->var2.i32 = positions[j].y * y_mult;
1073             info++;
1074           }
1075         }
1076         else
1077         {
1078           hb_position_t y_offset = (positions[0].y - advances_so_far) * y_mult;
1079           for (unsigned int j = 0; j < num_glyphs; j++)
1080           {
1081             double advance;
1082             if (likely (j + 1 < num_glyphs))
1083               advance = positions[j + 1].y - positions[j].y;
1084             else /* last glyph */
1085               advance = run_advance - (positions[j].y - positions[0].y);
1086             info->mask = advance * y_mult;
1087             info->var1.i32 = positions[j].x * x_mult;
1088             info->var2.i32 = y_offset;
1089             info++;
1090           }
1091         }
1092         SCRATCH_RESTORE();
1093         advances_so_far += run_advance;
1094       }
1095 #undef SCRATCH_RESTORE
1096 #undef SCRATCH_SAVE
1097 #undef USE_PTR
1098 #undef ALLOCATE_ARRAY
1099
1100       buffer->len += num_glyphs;
1101     }
1102
1103     /* Mac OS 10.6 doesn't have kCTTypesetterOptionForcedEmbeddingLevel,
1104      * or if it does, it doesn't respect it.  So we get runs with wrong
1105      * directions.  As such, disable the assert...  It wouldn't crash, but
1106      * cursoring will be off...
1107      *
1108      * https://crbug.com/419769
1109      */
1110     if (false)
1111     {
1112       /* Make sure all runs had the expected direction. */
1113       HB_UNUSED bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1114       assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1115       assert (bool (status_or  & kCTRunStatusRightToLeft) == backward);
1116     }
1117
1118     buffer->clear_positions ();
1119
1120     unsigned int count = buffer->len;
1121     hb_glyph_info_t *info = buffer->info;
1122     hb_glyph_position_t *pos = buffer->pos;
1123     if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1124       for (unsigned int i = 0; i < count; i++)
1125       {
1126         pos->x_advance = info->mask;
1127         pos->x_offset = info->var1.i32;
1128         pos->y_offset = info->var2.i32;
1129
1130         info++, pos++;
1131       }
1132     else
1133       for (unsigned int i = 0; i < count; i++)
1134       {
1135         pos->y_advance = info->mask;
1136         pos->x_offset = info->var1.i32;
1137         pos->y_offset = info->var2.i32;
1138
1139         info++, pos++;
1140       }
1141
1142     /* Fix up clusters so that we never return out-of-order indices;
1143      * if core text has reordered glyphs, we'll merge them to the
1144      * beginning of the reordered cluster.  CoreText is nice enough
1145      * to tell us whenever it has produced nonmonotonic results...
1146      * Note that we assume the input clusters were nonmonotonic to
1147      * begin with.
1148      *
1149      * This does *not* mean we'll form the same clusters as Uniscribe
1150      * or the native OT backend, only that the cluster indices will be
1151      * monotonic in the output buffer. */
1152     if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1153     {
1154       hb_glyph_info_t *info = buffer->info;
1155       if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1156       {
1157         unsigned int cluster = info[count - 1].cluster;
1158         for (unsigned int i = count - 1; i > 0; i--)
1159         {
1160           cluster = hb_min (cluster, info[i - 1].cluster);
1161           info[i - 1].cluster = cluster;
1162         }
1163       }
1164       else
1165       {
1166         unsigned int cluster = info[0].cluster;
1167         for (unsigned int i = 1; i < count; i++)
1168         {
1169           cluster = hb_min (cluster, info[i].cluster);
1170           info[i].cluster = cluster;
1171         }
1172       }
1173     }
1174   }
1175
1176   buffer->unsafe_to_break_all ();
1177
1178 #undef FAIL
1179
1180 fail:
1181   if (string_ref)
1182     CFRelease (string_ref);
1183   if (line)
1184     CFRelease (line);
1185
1186   for (unsigned int i = 0; i < range_records.length; i++)
1187     if (range_records[i].font)
1188       CFRelease (range_records[i].font);
1189
1190   return ret;
1191 }
1192
1193
1194 #endif