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