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"
42 * @short_description: CoreText integration
43 * @include: hb-coretext.h
45 * Functions for using HarfBuzz with the CoreText fonts.
48 /* https://developer.apple.com/documentation/coretext/1508745-ctfontcreatewithgraphicsfont */
49 #define HB_CORETEXT_DEFAULT_FONT_SIZE 12.f
52 release_table_data (void *user_data)
54 CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
59 _hb_cg_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
61 CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
62 CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
63 if (unlikely (!cf_data))
66 const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
67 const size_t length = CFDataGetLength (cf_data);
74 return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
75 reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
80 _hb_cg_font_release (void *data)
82 CGFontRelease ((CGFontRef) data);
86 static CTFontDescriptorRef
87 get_last_resort_font_desc ()
89 // TODO Handle allocation failures?
90 CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
91 CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
92 (const void **) &last_resort,
94 &kCFTypeArrayCallBacks);
95 CFRelease (last_resort);
96 CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
97 (const void **) &kCTFontCascadeListAttribute,
98 (const void **) &cascade_list,
100 &kCFTypeDictionaryKeyCallBacks,
101 &kCFTypeDictionaryValueCallBacks);
102 CFRelease (cascade_list);
104 CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
105 CFRelease (attributes);
110 release_data (void *info, const void *data, size_t size)
112 assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
113 hb_blob_get_data ((hb_blob_t *) info, nullptr) == data);
115 hb_blob_destroy ((hb_blob_t *) info);
119 create_cg_font (hb_face_t *face)
121 CGFontRef cg_font = nullptr;
122 if (face->destroy == _hb_cg_font_release)
124 cg_font = CGFontRetain ((CGFontRef) face->user_data);
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");
134 CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
135 if (likely (provider))
137 cg_font = CGFontCreateWithDataProvider (provider);
138 if (unlikely (!cg_font))
139 DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
140 CGDataProviderRelease (provider);
147 create_ct_font (CGFontRef cg_font, CGFloat font_size)
149 CTFontRef ct_font = nullptr;
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")))
158 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1080
159 # define kCTFontUIFontSystem kCTFontSystemFontType
160 # define kCTFontUIFontEmphasizedSystem kCTFontEmphasizedSystemFontType
162 CTFontUIFontType font_type = kCTFontUIFontSystem;
163 if (CFStringHasSuffix (cg_postscript_name, CFSTR ("-Bold")))
164 font_type = kCTFontUIFontEmphasizedSystem;
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)
173 CFRelease (ct_result_name);
175 CFRelease (cg_postscript_name);
178 ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, nullptr, nullptr);
180 if (unlikely (!ct_font)) {
181 DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
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);
203 CFURLRef original_url = nullptr;
204 #if !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && MAC_OS_X_VERSION_MIN_REQUIRED < 1060
208 atsFont = CTFontGetPlatformFont (ct_font, NULL);
209 status = ATSFontGetFileReference (atsFont, &fsref);
211 original_url = CFURLCreateFromFSRef (NULL, &fsref);
213 original_url = (CFURLRef) CTFontCopyAttribute (ct_font, kCTFontURLAttribute);
216 /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
217 * font fallback which we don't need anyway. */
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);
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.
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);
238 new_url = CFURLCreateFromFSRef (NULL, &fsref);
240 new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
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)) {
246 ct_font = new_ct_font;
248 CFRelease (new_ct_font);
249 DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
255 DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
259 CFRelease (original_url);
263 hb_coretext_face_data_t *
264 _hb_coretext_shaper_face_data_create (hb_face_t *face)
266 CGFontRef cg_font = create_cg_font (face);
268 if (unlikely (!cg_font))
270 DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
274 return (hb_coretext_face_data_t *) cg_font;
278 _hb_coretext_shaper_face_data_destroy (hb_coretext_face_data_t *data)
280 CFRelease ((CGFontRef) data);
284 * hb_coretext_face_create:
285 * @cg_font: The CGFontRef to work upon
287 * Creates an #hb_face_t face object from the specified
290 * Return value: the new #hb_face_t face object
295 hb_coretext_face_create (CGFontRef cg_font)
297 return hb_face_create_for_tables (_hb_cg_reference_table, CGFontRetain (cg_font), _hb_cg_font_release);
301 * hb_coretext_face_get_cg_font:
302 * @face: The #hb_face_t to work upon
304 * Fetches the CGFontRef associated with an #hb_face_t
307 * Return value: the CGFontRef found
312 hb_coretext_face_get_cg_font (hb_face_t *face)
314 return (CGFontRef) (const void *) face->data.coretext;
318 hb_coretext_font_data_t *
319 _hb_coretext_shaper_font_data_create (hb_font_t *font)
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;
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);
329 if (unlikely (!ct_font))
331 DEBUG_MSG (CORETEXT, font, "CGFont creation failed..");
337 CFMutableDictionaryRef variations =
338 CFDictionaryCreateMutable (kCFAllocatorDefault,
340 &kCFTypeDictionaryKeyCallBacks,
341 &kCFTypeDictionaryValueCallBacks);
343 for (unsigned i = 0; i < font->num_coords; i++)
345 if (font->coords[i] == 0.) continue;
347 hb_ot_var_axis_info_t info;
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])
356 CFDictionaryRef attributes =
357 CFDictionaryCreate (kCFAllocatorDefault,
358 (const void **) &kCTFontVariationAttribute,
359 (const void **) &variations,
361 &kCFTypeDictionaryKeyCallBacks,
362 &kCFTypeDictionaryValueCallBacks);
364 CTFontDescriptorRef varDesc = CTFontDescriptorCreateWithAttributes (attributes);
365 CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0, nullptr, varDesc);
368 CFRelease (attributes);
369 CFRelease (variations);
370 ct_font = new_ct_font;
373 return (hb_coretext_font_data_t *) ct_font;
377 _hb_coretext_shaper_font_data_destroy (hb_coretext_font_data_t *data)
379 CFRelease ((CTFontRef) data);
382 static const hb_coretext_font_data_t *
383 hb_coretext_font_data_sync (hb_font_t *font)
386 const hb_coretext_font_data_t *data = font->data.coretext;
387 if (unlikely (!data)) return nullptr;
389 if (fabs (CTFontGetSize ((CTFontRef) data) - (CGFloat) font->ptem) > (CGFloat) .5)
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.
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));
410 return font->data.coretext;
414 * hb_coretext_font_create:
415 * @ct_font: The CTFontRef to work upon
417 * Creates an #hb_font_t font object from the specified
420 * Return value: the new #hb_font_t font object
425 hb_coretext_font_create (CTFontRef ct_font)
427 CGFontRef cg_font = CTFontCopyGraphicsFont (ct_font, nullptr);
428 hb_face_t *face = hb_coretext_face_create (cg_font);
430 hb_font_t *font = hb_font_create (face);
431 hb_face_destroy (face);
433 if (unlikely (hb_object_is_immutable (font)))
436 hb_font_set_ptem (font, CTFontGetSize (ct_font));
438 /* Let there be dragons here... */
439 font->data.coretext.cmpexch (nullptr, (hb_coretext_font_data_t *) CFRetain (ct_font));
445 * hb_coretext_font_get_ct_font:
446 * @font: #hb_font_t to work upon
448 * Fetches the CTFontRef associated with the specified
449 * #hb_font_t font object.
451 * Return value: the CTFontRef found
456 hb_coretext_font_get_ct_font (hb_font_t *font)
458 const hb_coretext_font_data_t *data = hb_coretext_font_data_sync (font);
459 return data ? (CTFontRef) data : nullptr;
467 struct feature_record_t {
468 unsigned int feature;
469 unsigned int setting;
472 struct active_feature_t {
473 feature_record_t rec;
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 :
484 bool operator== (const active_feature_t& f) const {
485 return cmp (this, &f) == 0;
489 struct feature_event_t {
492 active_feature_t feature;
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);
503 struct range_record_t {
505 unsigned int index_first; /* == start */
506 unsigned int index_last; /* == end - 1 */
511 _hb_coretext_shape (hb_shape_plan_t *shape_plan,
514 const hb_feature_t *features,
515 unsigned int num_features)
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);
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;
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
532 if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
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);
542 hb_vector_t<feature_record_t> feature_records;
543 hb_vector_t<range_record_t> range_records;
547 * (copied + modified from code from hb-uniscribe.cc)
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++)
555 active_feature_t feature;
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);
562 feature.rec.feature = mapping->aatFeatureType;
563 feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
565 feature.rec.feature = features[i].tag;
566 feature.rec.setting = features[i].value;
570 feature_event_t *event;
572 event = feature_events.push ();
573 event->index = features[i].start;
575 event->feature = feature;
577 event = feature_events.push ();
578 event->index = features[i].end;
579 event->start = false;
580 event->feature = feature;
582 feature_events.qsort ();
583 /* Add a strategic final event. */
585 active_feature_t feature;
586 feature.rec.feature = HB_TAG_NONE;
587 feature.rec.setting = 0;
588 feature.order = num_features + 1;
590 feature_event_t *event = feature_events.push ();
591 event->index = 0; /* This value does magic. */
592 event->start = false;
593 event->feature = feature;
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++)
601 feature_event_t *event = &feature_events[i];
603 if (event->index != last_index)
605 /* Save a snapshot of active features and the range. */
606 range_record_t *range = range_records.push ();
608 if (active_features.length)
610 CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
612 /* TODO sort and resolve conflicting features? */
613 /* active_features.qsort (); */
614 for (unsigned int j = 0; j < active_features.length; j++)
616 #if MAC_OS_X_VERSION_MIN_REQUIRED < 101000
617 CFStringRef keys[] = {
618 kCTFontFeatureTypeIdentifierKey,
619 kCTFontFeatureSelectorIdentifierKey
621 CFNumberRef values[] = {
622 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
623 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
626 char tag[5] = {HB_UNTAG (active_features[j].rec.feature)};
628 kCTFontOpenTypeFeatureTag,
629 kCTFontOpenTypeFeatureValue
631 CFTypeRef values[] = {
632 CFStringCreateWithCString (kCFAllocatorDefault, tag, kCFStringEncodingASCII),
633 CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
636 static_assert ((ARRAY_LENGTH_CONST (keys) == ARRAY_LENGTH_CONST (values)), "");
637 CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
638 (const void **) keys,
639 (const void **) values,
641 &kCFTypeDictionaryKeyCallBacks,
642 &kCFTypeDictionaryValueCallBacks);
643 for (unsigned int i = 0; i < ARRAY_LENGTH (values); i++)
644 CFRelease (values[i]);
646 CFArrayAppendValue (features_array, dict);
651 CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
652 (const void **) &kCTFontFeatureSettingsAttribute,
653 (const void **) &features_array,
655 &kCFTypeDictionaryKeyCallBacks,
656 &kCFTypeDictionaryValueCallBacks);
657 CFRelease (features_array);
659 CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
660 CFRelease (attributes);
662 range->font = CTFontCreateCopyWithAttributes (ct_font, 0.0, nullptr, font_desc);
663 CFRelease (font_desc);
667 range->font = nullptr;
670 range->index_first = last_index;
671 range->index_last = event->index - 1;
673 last_index = event->index;
678 active_features.push (event->feature);
680 active_feature_t *feature = active_features.lsearch (event->feature);
682 active_features.remove (feature - active_features.arrayZ);
687 unsigned int scratch_size;
688 hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
690 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
691 Type *name = (Type *) scratch; \
693 unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
694 if (unlikely (_consumed > scratch_size)) \
699 scratch += _consumed; \
700 scratch_size -= _consumed; \
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;
712 pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
713 pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
717 ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, ((void)nullptr) /*nothing*/);
719 for (unsigned int i = 0; i < buffer->len; i++)
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. */
730 DEBUG_MSG (CORETEXT, nullptr, __VA_ARGS__); \
736 CFStringRef string_ref = nullptr;
737 CTLineRef line = nullptr;
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. */
747 CFRelease (string_ref);
749 string_ref = nullptr;
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;
759 if (unlikely (!buffer->ensure (buffer->allocated * 2)))
760 FAIL ("Buffer resize failed");
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;
771 string_ref = CFStringCreateWithCharactersNoCopy (nullptr,
774 if (unlikely (!string_ref))
775 FAIL ("CFStringCreateWithCharactersNoCopy failed");
777 /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
779 CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
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))
786 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
787 kCTVerticalFormsAttributeName, kCFBooleanTrue);
790 if (buffer->props.language)
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")
798 CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
799 hb_language_to_string (buffer->props.language),
800 kCFStringEncodingUTF8,
802 if (unlikely (!lang))
804 CFRelease (attr_string);
805 FAIL ("CFStringCreateWithCStringNoCopy failed");
807 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
808 kCTLanguageAttributeName, lang);
811 CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
812 kCTFontAttributeName, ct_font);
814 if (num_features && range_records.length)
816 unsigned int start = 0;
817 range_record_t *last_range = &range_records[0];
818 for (unsigned int k = 0; k < chars_len; k++)
820 range_record_t *range = last_range;
821 while (log_clusters[k] < range->index_first)
823 while (log_clusters[k] > range->index_last)
825 if (range != last_range)
827 if (last_range->font)
828 CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
829 kCTFontAttributeName, last_range->font);
836 if (start != chars_len && last_range->font)
837 CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
838 kCTFontAttributeName, last_range->font);
840 /* Enable/disable kern if requested.
842 * Note: once kern is disabled, reenabling it doesn't currently seem to work in CoreText.
846 unsigned int zeroint = 0;
847 CFNumberRef zero = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &zeroint);
848 for (unsigned int i = 0; i < num_features; i++)
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)
854 CFRange feature_range = CFRangeMake (feature.start,
855 hb_min (feature.end, chars_len) - feature.start);
857 CFAttributedStringRemoveAttribute (attr_string, feature_range, kCTKernAttributeName);
859 CFAttributedStringSetAttribute (attr_string, feature_range, kCTKernAttributeName, zero);
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;
870 CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
871 (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
872 (const void **) &level_number,
874 &kCFTypeDictionaryKeyCallBacks,
875 &kCFTypeDictionaryValueCallBacks);
876 CFRelease (level_number);
877 if (unlikely (!options))
879 CFRelease (attr_string);
880 FAIL ("CFDictionaryCreate failed");
883 CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
885 CFRelease (attr_string);
886 if (unlikely (!typesetter))
887 FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
889 line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
890 CFRelease (typesetter);
891 if (unlikely (!line))
892 FAIL ("CTTypesetterCreateLine failed");
895 CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
896 unsigned int num_runs = CFArrayGetCount (glyph_runs);
897 DEBUG_MSG (CORETEXT, nullptr, "Num runs: %d", num_runs);
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
907 if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
909 advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
910 if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
911 advances_so_far = -advances_so_far;
914 const CFRange range_all = CFRangeMake (0, 0);
916 for (unsigned int i = 0; i < num_runs; i++)
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);
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.
934 CFDictionaryRef attributes = CTRunGetAttributes (run);
935 CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
936 if (!CFEqual (run_ct_font, ct_font))
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.
944 * First, see if it uses any of our subfonts created to set font features...
946 * Next, compare the CGFont to the one we used to create our fonts.
947 * Even this doesn't work all the time.
949 * Finally, we compare PS names, which I don't think are unique...
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
955 * However, even that wouldn't work if we were passed in the CGFont to
956 * construct a hb_face to begin with.
958 * See: https://github.com/harfbuzz/harfbuzz/pull/36
960 * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
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))
971 CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, nullptr);
974 matched = CFEqual (run_cg_font, cg_font);
975 CFRelease (run_cg_font);
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)
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;
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;
1006 unsigned int old_len = buffer->len;
1007 for (CFIndex j = range.location; j < range.location + range.length; j++)
1009 UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
1010 if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
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
1018 if (buffer->unicode->is_default_ignorable (ch))
1021 info->codepoint = notdef;
1022 info->cluster = log_clusters[j];
1024 info->mask = advance;
1025 info->var1.i32 = x_offset;
1026 info->var2.i32 = y_offset;
1031 if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
1032 buffer->reverse_range (old_len, buffer->len);
1033 advances_so_far += run_advance;
1038 unsigned int num_glyphs = CTRunGetGlyphCount (run);
1039 if (num_glyphs == 0)
1042 if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1043 goto resize_and_retry;
1045 hb_glyph_info_t *run_info = buffer->info + buffer->len;
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
1053 #define USE_PTR true
1055 #define SCRATCH_SAVE() \
1056 unsigned int scratch_size_saved = scratch_size; \
1057 hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1059 #define SCRATCH_RESTORE() \
1060 scratch_size = scratch_size_saved; \
1061 scratch = scratch_saved
1063 { /* Setup glyphs */
1065 const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : nullptr;
1067 ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1068 CTRunGetGlyphs (run, range_all, glyph_buf);
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;
1077 hb_glyph_info_t *info = run_info;
1078 for (unsigned int j = 0; j < num_glyphs; j++)
1080 info->codepoint = glyphs[j];
1081 info->cluster = log_clusters[string_indices[j]];
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. */
1093 const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : nullptr;
1095 ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1096 CTRunGetPositions (run, range_all, position_buf);
1097 positions = position_buf;
1099 hb_glyph_info_t *info = run_info;
1100 if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
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++)
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);
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++)
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;
1133 advances_so_far += run_advance;
1135 #undef SCRATCH_RESTORE
1138 #undef ALLOCATE_ARRAY
1140 buffer->len += num_glyphs;
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...
1148 * https://crbug.com/419769
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);
1158 buffer->clear_positions ();
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++)
1166 pos->x_advance = info->mask;
1167 pos->x_offset = info->var1.i32;
1168 pos->y_offset = info->var2.i32;
1173 for (unsigned int i = 0; i < count; i++)
1175 pos->y_advance = info->mask;
1176 pos->x_offset = info->var1.i32;
1177 pos->y_offset = info->var2.i32;
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
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))
1194 hb_glyph_info_t *info = buffer->info;
1195 if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1197 unsigned int cluster = info[count - 1].cluster;
1198 for (unsigned int i = count - 1; i > 0; i--)
1200 cluster = hb_min (cluster, info[i - 1].cluster);
1201 info[i - 1].cluster = cluster;
1206 unsigned int cluster = info[0].cluster;
1207 for (unsigned int i = 1; i < count; i++)
1209 cluster = hb_min (cluster, info[i].cluster);
1210 info[i].cluster = cluster;
1216 buffer->clear_glyph_flags ();
1217 buffer->unsafe_to_break ();
1223 CFRelease (string_ref);
1227 for (unsigned int i = 0; i < range_records.length; i++)
1228 if (range_records[i].font)
1229 CFRelease (range_records[i].font);