2 * Copyright © 2012,2013 Mozilla Foundation.
3 * Copyright © 2012,2013 Google, Inc.
5 * This is part of HarfBuzz, a text shaping library.
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.
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
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.
25 * Mozilla Author(s): Jonathan Kew
26 * Google Author(s): Behdad Esfahbod
33 #include "hb-shaper-impl.hh"
35 #include "hb-coretext.h"
36 #include "hb-aat-layout.hh"
43 * @short_description: CoreText integration
44 * @include: hb-coretext.h
46 * Functions for using HarfBuzz with the CoreText fonts.
49 /* https://developer.apple.com/documentation/coretext/1508745-ctfontcreatewithgraphicsfont */
50 #define HB_CORETEXT_DEFAULT_FONT_SIZE 12.f
53 release_table_data (void *user_data)
55 CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
60 _hb_cg_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
62 CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
63 CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
64 if (unlikely (!cf_data))
67 const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
68 const size_t length = CFDataGetLength (cf_data);
75 return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
76 reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
81 _hb_cg_font_release (void *data)
83 CGFontRelease ((CGFontRef) data);
87 static CTFontDescriptorRef
88 get_last_resort_font_desc ()
90 // TODO Handle allocation failures?
91 CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
92 CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
93 (const void **) &last_resort,
95 &kCFTypeArrayCallBacks);
96 CFRelease (last_resort);
97 CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
98 (const void **) &kCTFontCascadeListAttribute,
99 (const void **) &cascade_list,
101 &kCFTypeDictionaryKeyCallBacks,
102 &kCFTypeDictionaryValueCallBacks);
103 CFRelease (cascade_list);
105 CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
106 CFRelease (attributes);
111 release_data (void *info, const void *data, size_t size)
113 assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
114 hb_blob_get_data ((hb_blob_t *) info, nullptr) == data);
116 hb_blob_destroy ((hb_blob_t *) info);
120 create_cg_font (hb_face_t *face)
122 CGFontRef cg_font = nullptr;
123 if (face->destroy == _hb_cg_font_release)
125 cg_font = CGFontRetain ((CGFontRef) face->user_data);
129 hb_blob_t *blob = hb_face_reference_blob (face);
130 unsigned int blob_length;
131 const char *blob_data = hb_blob_get_data (blob, &blob_length);
132 if (unlikely (!blob_length))
133 DEBUG_MSG (CORETEXT, face, "Face has empty blob");
135 CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
136 if (likely (provider))
138 cg_font = CGFontCreateWithDataProvider (provider);
139 if (unlikely (!cg_font))
140 DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
141 CGDataProviderRelease (provider);
148 create_ct_font (CGFontRef cg_font, CGFloat font_size)
150 CTFontRef ct_font = nullptr;
152 /* CoreText does not enable trak table usage / tracking when creating a CTFont
153 * using CTFontCreateWithGraphicsFont. The only way of enabling tracking seems
154 * to be through the CTFontCreateUIFontForLanguage call. */
155 CFStringRef cg_postscript_name = CGFontCopyPostScriptName (cg_font);
156 if (CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSText")) ||
157 CFStringHasPrefix (cg_postscript_name, CFSTR (".SFNSDisplay")))
159 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1080
160 # define kCTFontUIFontSystem kCTFontSystemFontType
161 # define kCTFontUIFontEmphasizedSystem kCTFontEmphasizedSystemFontType
163 CTFontUIFontType font_type = kCTFontUIFontSystem;
164 if (CFStringHasSuffix (cg_postscript_name, CFSTR ("-Bold")))
165 font_type = kCTFontUIFontEmphasizedSystem;
167 ct_font = CTFontCreateUIFontForLanguage (font_type, font_size, nullptr);
168 CFStringRef ct_result_name = CTFontCopyPostScriptName(ct_font);
169 if (CFStringCompare (ct_result_name, cg_postscript_name, 0) != kCFCompareEqualTo)
174 CFRelease (ct_result_name);
176 CFRelease (cg_postscript_name);
179 ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, nullptr, nullptr);
181 if (unlikely (!ct_font)) {
182 DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
186 /* crbug.com/576941 and crbug.com/625902 and the investigation in the latter
187 * bug indicate that the cascade list reconfiguration occasionally causes
188 * crashes in CoreText on OS X 10.9, thus let's skip this step on older
189 * operating system versions. Except for the emoji font, where _not_
190 * reconfiguring the cascade list causes CoreText crashes. For details, see
191 * crbug.com/549610 */
192 // 0x00070000 stands for "kCTVersionNumber10_10", see CoreText.h
193 if (&CTGetCoreTextVersion != nullptr && CTGetCoreTextVersion() < 0x00070000) {
194 CFStringRef fontName = CTFontCopyPostScriptName (ct_font);
195 bool isEmojiFont = CFStringCompare (fontName, CFSTR("AppleColorEmoji"), 0) == kCFCompareEqualTo;
196 CFRelease (fontName);
201 CFURLRef original_url = nullptr;
202 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
206 atsFont = CTFontGetPlatformFont (ct_font, NULL);
207 status = ATSFontGetFileReference (atsFont, &fsref);
209 original_url = CFURLCreateFromFSRef (NULL, &fsref);
211 original_url = (CFURLRef) CTFontCopyAttribute (ct_font, kCTFontURLAttribute);
214 /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
215 * font fallback which we don't need anyway. */
217 CTFontDescriptorRef last_resort_font_desc = get_last_resort_font_desc ();
218 CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, last_resort_font_desc);
219 CFRelease (last_resort_font_desc);
222 /* The CTFontCreateCopyWithAttributes call fails to stay on the same font
223 * when reconfiguring the cascade list and may switch to a different font
224 * when there are fonts that go by the same name, since the descriptor is
225 * just name and size.
227 * Avoid reconfiguring the cascade lists if the new font is outside the
228 * system locations that we cannot access from the sandboxed renderer
229 * process in Blink. This can be detected by the new file URL location
230 * that the newly found font points to. */
231 CFURLRef new_url = nullptr;
232 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
233 atsFont = CTFontGetPlatformFont (new_ct_font, NULL);
234 status = ATSFontGetFileReference (atsFont, &fsref);
236 new_url = CFURLCreateFromFSRef (NULL, &fsref);
238 new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
240 // Keep reconfigured font if URL cannot be retrieved (seems to be the case
241 // on Mac OS 10.12 Sierra), speculative fix for crbug.com/625606
242 if (!original_url || !new_url || CFEqual (original_url, new_url)) {
244 ct_font = new_ct_font;
246 CFRelease (new_ct_font);
247 DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
253 DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
257 CFRelease (original_url);
261 hb_coretext_face_data_t *
262 _hb_coretext_shaper_face_data_create (hb_face_t *face)
264 CGFontRef cg_font = create_cg_font (face);
266 if (unlikely (!cg_font))
268 DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
272 return (hb_coretext_face_data_t *) cg_font;
276 _hb_coretext_shaper_face_data_destroy (hb_coretext_face_data_t *data)
278 CFRelease ((CGFontRef) data);
282 * hb_coretext_face_create:
283 * @cg_font: The CGFontRef to work upon
285 * Creates an #hb_face_t face object from the specified
288 * Return value: the new #hb_face_t face object
293 hb_coretext_face_create (CGFontRef cg_font)
295 return hb_face_create_for_tables (_hb_cg_reference_table, CGFontRetain (cg_font), _hb_cg_font_release);
299 * hb_coretext_face_get_cg_font:
300 * @face: The #hb_face_t to work upon
302 * Fetches the CGFontRef associated with an #hb_face_t
305 * Return value: the CGFontRef found
310 hb_coretext_face_get_cg_font (hb_face_t *face)
312 return (CGFontRef) (const void *) face->data.coretext;
316 hb_coretext_font_data_t *
317 _hb_coretext_shaper_font_data_create (hb_font_t *font)
319 hb_face_t *face = font->face;
320 const hb_coretext_face_data_t *face_data = face->data.coretext;
321 if (unlikely (!face_data)) return nullptr;
322 CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
324 CGFloat font_size = (CGFloat) (font->ptem <= 0.f ? HB_CORETEXT_DEFAULT_FONT_SIZE : font->ptem);
325 CTFontRef ct_font = create_ct_font (cg_font, font_size);
327 if (unlikely (!ct_font))
329 DEBUG_MSG (CORETEXT, font, "CGFont creation failed..");
333 return (hb_coretext_font_data_t *) ct_font;
337 _hb_coretext_shaper_font_data_destroy (hb_coretext_font_data_t *data)
339 CFRelease ((CTFontRef) data);
342 static const hb_coretext_font_data_t *
343 hb_coretext_font_data_sync (hb_font_t *font)
346 const hb_coretext_font_data_t *data = font->data.coretext;
347 if (unlikely (!data)) return nullptr;
349 if (fabs (CTFontGetSize ((CTFontRef) data) - (CGFloat) font->ptem) > .5)
352 * Note that evaluating condition above can be dangerous if another thread
353 * got here first and destructed data. That's, as always, bad use pattern.
354 * If you modify the font (change font size), other threads must not be
355 * using it at the same time. However, since this check is delayed to
356 * when one actually tries to shape something, this is a XXX race condition
357 * (and the only one we have that I know of) right now. Ie. you modify the
358 * font size in one thread, then (supposedly safely) try to use it from two
359 * or more threads and BOOM! I'm not sure how to fix this. We want RCU.
362 /* Drop and recreate. */
363 /* If someone dropped it in the mean time, throw it away and don't touch it.
364 * Otherwise, destruct it. */
365 if (likely (font->data.coretext.cmpexch (const_cast<hb_coretext_font_data_t *> (data), nullptr)))
366 _hb_coretext_shaper_font_data_destroy (const_cast<hb_coretext_font_data_t *> (data));
370 return font->data.coretext;
374 * hb_coretext_font_create:
375 * @ct_font: The CTFontRef to work upon
377 * Creates an #hb_font_t font object from the specified
380 * Return value: the new #hb_font_t font object
385 hb_coretext_font_create (CTFontRef ct_font)
387 CGFontRef cg_font = CTFontCopyGraphicsFont (ct_font, nullptr);
388 hb_face_t *face = hb_coretext_face_create (cg_font);
390 hb_font_t *font = hb_font_create (face);
391 hb_face_destroy (face);
393 if (unlikely (hb_object_is_immutable (font)))
396 hb_font_set_ptem (font, CTFontGetSize (ct_font));
398 /* Let there be dragons here... */
399 font->data.coretext.cmpexch (nullptr, (hb_coretext_font_data_t *) CFRetain (ct_font));
405 * hb_coretext_face_get_ct_font:
406 * @font: #hb_font_t to work upon
408 * Fetches the CTFontRef associated with the specified
409 * #hb_font_t font object.
411 * Return value: the CTFontRef found
416 hb_coretext_font_get_ct_font (hb_font_t *font)
418 const hb_coretext_font_data_t *data = hb_coretext_font_data_sync (font);
419 return data ? (CTFontRef) data : nullptr;
427 struct feature_record_t {
428 unsigned int feature;
429 unsigned int setting;
432 struct active_feature_t {
433 feature_record_t rec;
436 HB_INTERNAL static int cmp (const void *pa, const void *pb) {
437 const active_feature_t *a = (const active_feature_t *) pa;
438 const active_feature_t *b = (const active_feature_t *) pb;
439 return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
440 a->order < b->order ? -1 : a->order > b->order ? 1 :
441 a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
444 bool operator== (const active_feature_t *f) {
445 return cmp (this, f) == 0;
449 struct feature_event_t {
452 active_feature_t feature;
454 HB_INTERNAL static int cmp (const void *pa, const void *pb) {
455 const feature_event_t *a = (const feature_event_t *) pa;
456 const feature_event_t *b = (const feature_event_t *) pb;
457 return a->index < b->index ? -1 : a->index > b->index ? 1 :
458 a->start < b->start ? -1 : a->start > b->start ? 1 :
459 active_feature_t::cmp (&a->feature, &b->feature);
463 struct range_record_t {
465 unsigned int index_first; /* == start */
466 unsigned int index_last; /* == end - 1 */
471 _hb_coretext_shape (hb_shape_plan_t *shape_plan,
474 const hb_feature_t *features,
475 unsigned int num_features)
477 hb_face_t *face = font->face;
478 CGFontRef cg_font = (CGFontRef) (const void *) face->data.coretext;
479 CTFontRef ct_font = (CTFontRef) hb_coretext_font_data_sync (font);
481 CGFloat ct_font_size = CTFontGetSize (ct_font);
482 CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
483 CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
485 /* Attach marks to their bases, to match the 'ot' shaper.
486 * Adapted from a very old version of hb-ot-shape:hb_form_clusters().
487 * Note that this only makes us be closer to the 'ot' shaper,
488 * but by no means the same. For example, if there's
489 * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
490 * continue pointing to B2 even though B2 was merged into B1's
492 if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
494 hb_unicode_funcs_t *unicode = buffer->unicode;
495 unsigned int count = buffer->len;
496 hb_glyph_info_t *info = buffer->info;
497 for (unsigned int i = 1; i < count; i++)
498 if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
499 buffer->merge_clusters (i - 1, i + 1);
502 hb_vector_t<feature_record_t> feature_records;
503 hb_vector_t<range_record_t> range_records;
507 * (copied + modified from code from hb-uniscribe.cc)
511 /* Sort features by start/end events. */
512 hb_vector_t<feature_event_t> feature_events;
513 for (unsigned int i = 0; i < num_features; i++)
515 active_feature_t feature;
517 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1010
518 const hb_aat_feature_mapping_t * mapping = hb_aat_layout_find_feature_mapping (features[i].tag);
522 feature.rec.feature = mapping->aatFeatureType;
523 feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
525 feature.rec.feature = features[i].tag;
526 feature.rec.setting = features[i].value;
530 feature_event_t *event;
532 event = feature_events.push ();
533 event->index = features[i].start;
535 event->feature = feature;
537 event = feature_events.push ();
538 event->index = features[i].end;
539 event->start = false;
540 event->feature = feature;
542 feature_events.qsort ();
543 /* Add a strategic final event. */
545 active_feature_t feature;
546 feature.rec.feature = HB_TAG_NONE;
547 feature.rec.setting = 0;
548 feature.order = num_features + 1;
550 feature_event_t *event = feature_events.push ();
551 event->index = 0; /* This value does magic. */
552 event->start = false;
553 event->feature = feature;
556 /* Scan events and save features for each range. */
557 hb_vector_t<active_feature_t> active_features;
558 unsigned int last_index = 0;
559 for (unsigned int i = 0; i < feature_events.length; i++)
561 feature_event_t *event = &feature_events[i];
563 if (event->index != last_index)
565 /* Save a snapshot of active features and the range. */
566 range_record_t *range = range_records.push ();
568 if (active_features.length)
570 CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
572 /* TODO sort and resolve conflicting features? */
573 /* active_features.qsort (); */
574 for (unsigned int j = 0; j < active_features.length; j++)
576 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1010
577 CFStringRef keys[] = {
578 kCTFontFeatureTypeIdentifierKey,
579 kCTFontFeatureSelectorIdentifierKey
581 CFNumberRef values[] = {
582 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
583 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
586 char tag[5] = {HB_UNTAG (active_features[j].rec.feature)};
588 kCTFontOpenTypeFeatureTag,
589 kCTFontOpenTypeFeatureValue
591 CFTypeRef values[] = {
592 CFStringCreateWithCString (kCFAllocatorDefault, tag, kCFStringEncodingASCII),
593 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
596 static_assert ((ARRAY_LENGTH_CONST (keys) == ARRAY_LENGTH_CONST (values)), "");
597 CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
598 (const void **) keys,
599 (const void **) values,
601 &kCFTypeDictionaryKeyCallBacks,
602 &kCFTypeDictionaryValueCallBacks);
603 for (unsigned int i = 0; i < ARRAY_LENGTH (values); i++)
604 CFRelease (values[i]);
606 CFArrayAppendValue (features_array, dict);
611 CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
612 (const void **) &kCTFontFeatureSettingsAttribute,
613 (const void **) &features_array,
615 &kCFTypeDictionaryKeyCallBacks,
616 &kCFTypeDictionaryValueCallBacks);
617 CFRelease (features_array);
619 CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
620 CFRelease (attributes);
622 range->font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, font_desc);
623 CFRelease (font_desc);
627 range->font = nullptr;
630 range->index_first = last_index;
631 range->index_last = event->index - 1;
633 last_index = event->index;
638 active_features.push (event->feature);
640 active_feature_t *feature = active_features.find (&event->feature);
642 active_features.remove (feature - active_features.arrayZ);
647 unsigned int scratch_size;
648 hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
650 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
651 Type *name = (Type *) scratch; \
653 unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
654 if (unlikely (_consumed > scratch_size)) \
659 scratch += _consumed; \
660 scratch_size -= _consumed; \
663 ALLOCATE_ARRAY (UniChar, pchars, buffer->len * 2, ((void)nullptr) /*nothing*/);
664 unsigned int chars_len = 0;
665 for (unsigned int i = 0; i < buffer->len; i++) {
666 hb_codepoint_t c = buffer->info[i].codepoint;
667 if (likely (c <= 0xFFFFu))
668 pchars[chars_len++] = c;
669 else if (unlikely (c > 0x10FFFFu))
670 pchars[chars_len++] = 0xFFFDu;
672 pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
673 pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
677 ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, ((void)nullptr) /*nothing*/);
679 for (unsigned int i = 0; i < buffer->len; i++)
681 hb_codepoint_t c = buffer->info[i].codepoint;
682 unsigned int cluster = buffer->info[i].cluster;
683 log_clusters[chars_len++] = cluster;
684 if (hb_in_range (c, 0x10000u, 0x10FFFFu))
685 log_clusters[chars_len++] = cluster; /* Surrogates. */
690 DEBUG_MSG (CORETEXT, nullptr, __VA_ARGS__); \
696 CFStringRef string_ref = nullptr;
697 CTLineRef line = nullptr;
702 DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
703 /* string_ref uses the scratch-buffer for backing store, and line references
704 * string_ref (via attr_string). We must release those before resizing buffer. */
707 CFRelease (string_ref);
709 string_ref = nullptr;
712 /* Get previous start-of-scratch-area, that we use later for readjusting
713 * our existing scratch arrays. */
714 unsigned int old_scratch_used;
715 hb_buffer_t::scratch_buffer_t *old_scratch;
716 old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
717 old_scratch_used = scratch - old_scratch;
719 if (unlikely (!buffer->ensure (buffer->allocated * 2)))
720 FAIL ("Buffer resize failed");
722 /* Adjust scratch, pchars, and log_cluster arrays. This is ugly, but really the
723 * cleanest way to do without completely restructuring the rest of this shaper. */
724 scratch = buffer->get_scratch_buffer (&scratch_size);
725 pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
726 log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
727 scratch += old_scratch_used;
728 scratch_size -= old_scratch_used;
731 string_ref = CFStringCreateWithCharactersNoCopy (nullptr,
734 if (unlikely (!string_ref))
735 FAIL ("CFStringCreateWithCharactersNoCopy failed");
737 /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
739 CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
741 if (unlikely (!attr_string))
742 FAIL ("CFAttributedStringCreateMutable failed");
743 CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
744 if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
746 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
747 kCTVerticalFormsAttributeName, kCFBooleanTrue);
750 if (buffer->props.language)
752 /* What's the iOS equivalent of this check?
753 * The symbols was introduced in iOS 7.0.
754 * At any rate, our fallback is safe and works fine. */
755 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1090
756 # define kCTLanguageAttributeName CFSTR ("NSLanguage")
758 CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
759 hb_language_to_string (buffer->props.language),
760 kCFStringEncodingUTF8,
762 if (unlikely (!lang))
764 CFRelease (attr_string);
765 FAIL ("CFStringCreateWithCStringNoCopy failed");
767 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
768 kCTLanguageAttributeName, lang);
771 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
772 kCTFontAttributeName, ct_font);
774 if (num_features && range_records.length)
776 unsigned int start = 0;
777 range_record_t *last_range = &range_records[0];
778 for (unsigned int k = 0; k < chars_len; k++)
780 range_record_t *range = last_range;
781 while (log_clusters[k] < range->index_first)
783 while (log_clusters[k] > range->index_last)
785 if (range != last_range)
787 if (last_range->font)
788 CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
789 kCTFontAttributeName, last_range->font);
796 if (start != chars_len && last_range->font)
797 CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
798 kCTFontAttributeName, last_range->font);
800 /* Enable/disable kern if requested.
802 * Note: once kern is disabled, reenabling it doesn't currently seem to work in CoreText.
806 unsigned int zeroint = 0;
807 CFNumberRef zero = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &zeroint);
808 for (unsigned int i = 0; i < num_features; i++)
810 const hb_feature_t &feature = features[i];
811 if (feature.tag == HB_TAG('k','e','r','n') &&
812 feature.start < chars_len && feature.start < feature.end)
814 CFRange feature_range = CFRangeMake (feature.start,
815 hb_min (feature.end, chars_len) - feature.start);
817 CFAttributedStringRemoveAttribute (attr_string, feature_range, kCTKernAttributeName);
819 CFAttributedStringSetAttribute (attr_string, feature_range, kCTKernAttributeName, zero);
825 int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
826 CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
827 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
828 extern const CFStringRef kCTTypesetterOptionForcedEmbeddingLevel;
830 CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
831 (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
832 (const void **) &level_number,
834 &kCFTypeDictionaryKeyCallBacks,
835 &kCFTypeDictionaryValueCallBacks);
836 CFRelease (level_number);
837 if (unlikely (!options))
839 CFRelease (attr_string);
840 FAIL ("CFDictionaryCreate failed");
843 CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
845 CFRelease (attr_string);
846 if (unlikely (!typesetter))
847 FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
849 line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
850 CFRelease (typesetter);
851 if (unlikely (!line))
852 FAIL ("CTTypesetterCreateLine failed");
855 CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
856 unsigned int num_runs = CFArrayGetCount (glyph_runs);
857 DEBUG_MSG (CORETEXT, nullptr, "Num runs: %d", num_runs);
860 uint32_t status_and = ~0, status_or = 0;
861 double advances_so_far = 0;
862 /* For right-to-left runs, CoreText returns the glyphs positioned such that
863 * any trailing whitespace is to the left of (0,0). Adjust coordinate system
864 * to fix for that. Test with any RTL string with trailing spaces.
865 * https://crbug.com/469028
867 if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
869 advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
870 if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
871 advances_so_far = -advances_so_far;
874 const CFRange range_all = CFRangeMake (0, 0);
876 for (unsigned int i = 0; i < num_runs; i++)
878 CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
879 CTRunStatus run_status = CTRunGetStatus (run);
880 status_or |= run_status;
881 status_and &= run_status;
882 DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
883 double run_advance = CTRunGetTypographicBounds (run, range_all, nullptr, nullptr, nullptr);
884 if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
885 run_advance = -run_advance;
886 DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
888 /* CoreText does automatic font fallback (AKA "cascading") for characters
889 * not supported by the requested font, and provides no way to turn it off,
890 * so we must detect if the returned run uses a font other than the requested
891 * one and fill in the buffer with .notdef glyphs instead of random glyph
892 * indices from a different font.
894 CFDictionaryRef attributes = CTRunGetAttributes (run);
895 CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
896 if (!CFEqual (run_ct_font, ct_font))
898 /* The run doesn't use our main font instance. We have to figure out
899 * whether font fallback happened, or this is just CoreText giving us
900 * another CTFont using the same underlying CGFont. CoreText seems
901 * to do that in a variety of situations, one of which being vertical
902 * text, but also perhaps for caching reasons.
904 * First, see if it uses any of our subfonts created to set font features...
906 * Next, compare the CGFont to the one we used to create our fonts.
907 * Even this doesn't work all the time.
909 * Finally, we compare PS names, which I don't think are unique...
911 * Looks like if we really want to be sure here we have to modify the
912 * font to change the name table, similar to what we do in the uniscribe
915 * However, even that wouldn't work if we were passed in the CGFont to
916 * construct a hb_face to begin with.
918 * See: https://github.com/harfbuzz/harfbuzz/pull/36
920 * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
922 bool matched = false;
923 for (unsigned int i = 0; i < range_records.length; i++)
924 if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
931 CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, nullptr);
934 matched = CFEqual (run_cg_font, cg_font);
935 CFRelease (run_cg_font);
940 CFStringRef font_ps_name = CTFontCopyName (ct_font, kCTFontPostScriptNameKey);
941 CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
942 CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
943 CFRelease (run_ps_name);
944 CFRelease (font_ps_name);
945 if (result == kCFCompareEqualTo)
950 CFRange range = CTRunGetStringRange (run);
951 DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
952 range.location, range.location + range.length);
953 if (!buffer->ensure_inplace (buffer->len + range.length))
954 goto resize_and_retry;
955 hb_glyph_info_t *info = buffer->info + buffer->len;
957 hb_codepoint_t notdef = 0;
958 hb_direction_t dir = buffer->props.direction;
959 hb_position_t x_advance, y_advance, x_offset, y_offset;
960 hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);
961 hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);
962 hb_position_t advance = x_advance + y_advance;
963 x_offset = -x_offset;
964 y_offset = -y_offset;
966 unsigned int old_len = buffer->len;
967 for (CFIndex j = range.location; j < range.location + range.length; j++)
969 UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
970 if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
972 ch = CFStringGetCharacterAtIndex (string_ref, j - 1);
973 if (hb_in_range<UniChar> (ch, 0xD800u, 0xDBFFu))
974 /* This is the second of a surrogate pair. Don't need .notdef
978 if (buffer->unicode->is_default_ignorable (ch))
981 info->codepoint = notdef;
982 info->cluster = log_clusters[j];
984 info->mask = advance;
985 info->var1.i32 = x_offset;
986 info->var2.i32 = y_offset;
991 if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
992 buffer->reverse_range (old_len, buffer->len);
993 advances_so_far += run_advance;
998 unsigned int num_glyphs = CTRunGetGlyphCount (run);
1002 if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1003 goto resize_and_retry;
1005 hb_glyph_info_t *run_info = buffer->info + buffer->len;
1007 /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
1008 * succeed, and so copying data to our own buffer will be rare. Reports
1009 * have it that this changed in OS X 10.10 Yosemite, and nullptr is returned
1010 * frequently. At any rate, we can test that codepath by setting USE_PTR
1013 #define USE_PTR true
1015 #define SCRATCH_SAVE() \
1016 unsigned int scratch_size_saved = scratch_size; \
1017 hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1019 #define SCRATCH_RESTORE() \
1020 scratch_size = scratch_size_saved; \
1021 scratch = scratch_saved
1023 { /* Setup glyphs */
1025 const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : nullptr;
1027 ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1028 CTRunGetGlyphs (run, range_all, glyph_buf);
1031 const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : nullptr;
1032 if (!string_indices) {
1033 ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
1034 CTRunGetStringIndices (run, range_all, index_buf);
1035 string_indices = index_buf;
1037 hb_glyph_info_t *info = run_info;
1038 for (unsigned int j = 0; j < num_glyphs; j++)
1040 info->codepoint = glyphs[j];
1041 info->cluster = log_clusters[string_indices[j]];
1048 * Note that CoreText does not return advances for glyphs. As such,
1049 * for all but last glyph, we use the delta position to next glyph as
1050 * advance (in the advance direction only), and for last glyph we set
1051 * whatever is needed to make the whole run's advance add up. */
1053 const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : nullptr;
1055 ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1056 CTRunGetPositions (run, range_all, position_buf);
1057 positions = position_buf;
1059 hb_glyph_info_t *info = run_info;
1060 if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1062 hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1063 for (unsigned int j = 0; j < num_glyphs; j++)
1066 if (likely (j + 1 < num_glyphs))
1067 advance = positions[j + 1].x - positions[j].x;
1068 else /* last glyph */
1069 advance = run_advance - (positions[j].x - positions[0].x);
1070 info->mask = advance * x_mult;
1071 info->var1.i32 = x_offset;
1072 info->var2.i32 = positions[j].y * y_mult;
1078 hb_position_t y_offset = (positions[0].y - advances_so_far) * y_mult;
1079 for (unsigned int j = 0; j < num_glyphs; j++)
1082 if (likely (j + 1 < num_glyphs))
1083 advance = positions[j + 1].y - positions[j].y;
1084 else /* last glyph */
1085 advance = run_advance - (positions[j].y - positions[0].y);
1086 info->mask = advance * y_mult;
1087 info->var1.i32 = positions[j].x * x_mult;
1088 info->var2.i32 = y_offset;
1093 advances_so_far += run_advance;
1095 #undef SCRATCH_RESTORE
1098 #undef ALLOCATE_ARRAY
1100 buffer->len += num_glyphs;
1103 /* Mac OS 10.6 doesn't have kCTTypesetterOptionForcedEmbeddingLevel,
1104 * or if it does, it doesn't respect it. So we get runs with wrong
1105 * directions. As such, disable the assert... It wouldn't crash, but
1106 * cursoring will be off...
1108 * https://crbug.com/419769
1112 /* Make sure all runs had the expected direction. */
1113 HB_UNUSED bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1114 assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1115 assert (bool (status_or & kCTRunStatusRightToLeft) == backward);
1118 buffer->clear_positions ();
1120 unsigned int count = buffer->len;
1121 hb_glyph_info_t *info = buffer->info;
1122 hb_glyph_position_t *pos = buffer->pos;
1123 if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1124 for (unsigned int i = 0; i < count; i++)
1126 pos->x_advance = info->mask;
1127 pos->x_offset = info->var1.i32;
1128 pos->y_offset = info->var2.i32;
1133 for (unsigned int i = 0; i < count; i++)
1135 pos->y_advance = info->mask;
1136 pos->x_offset = info->var1.i32;
1137 pos->y_offset = info->var2.i32;
1142 /* Fix up clusters so that we never return out-of-order indices;
1143 * if core text has reordered glyphs, we'll merge them to the
1144 * beginning of the reordered cluster. CoreText is nice enough
1145 * to tell us whenever it has produced nonmonotonic results...
1146 * Note that we assume the input clusters were nonmonotonic to
1149 * This does *not* mean we'll form the same clusters as Uniscribe
1150 * or the native OT backend, only that the cluster indices will be
1151 * monotonic in the output buffer. */
1152 if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1154 hb_glyph_info_t *info = buffer->info;
1155 if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1157 unsigned int cluster = info[count - 1].cluster;
1158 for (unsigned int i = count - 1; i > 0; i--)
1160 cluster = hb_min (cluster, info[i - 1].cluster);
1161 info[i - 1].cluster = cluster;
1166 unsigned int cluster = info[0].cluster;
1167 for (unsigned int i = 1; i < count; i++)
1169 cluster = hb_min (cluster, info[i].cluster);
1170 info[i].cluster = cluster;
1176 buffer->unsafe_to_break_all ();
1182 CFRelease (string_ref);
1186 for (unsigned int i = 0; i < range_records.length; i++)
1187 if (range_records[i].font)
1188 CFRelease (range_records[i].font);