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