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