• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define HB_SHAPER coretext
30 #include "hb-shaper-impl-private.hh"
31 
32 #include "hb-coretext.h"
33 
34 
35 #ifndef HB_DEBUG_CORETEXT
36 #define HB_DEBUG_CORETEXT (HB_DEBUG+0)
37 #endif
38 
39 
40 static void
release_table_data(void * user_data)41 release_table_data (void *user_data)
42 {
43   CFDataRef cf_data = reinterpret_cast<CFDataRef> (user_data);
44   CFRelease(cf_data);
45 }
46 
47 static hb_blob_t *
reference_table(hb_face_t * face HB_UNUSED,hb_tag_t tag,void * user_data)48 reference_table  (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
49 {
50   CGFontRef cg_font = reinterpret_cast<CGFontRef> (user_data);
51   CFDataRef cf_data = CGFontCopyTableForTag (cg_font, tag);
52   if (unlikely (!cf_data))
53     return NULL;
54 
55   const char *data = reinterpret_cast<const char*> (CFDataGetBytePtr (cf_data));
56   const size_t length = CFDataGetLength (cf_data);
57   if (!data || !length)
58     return NULL;
59 
60   return hb_blob_create (data, length, HB_MEMORY_MODE_READONLY,
61 			 reinterpret_cast<void *> (const_cast<__CFData *> (cf_data)),
62 			 release_table_data);
63 }
64 
65 hb_face_t *
hb_coretext_face_create(CGFontRef cg_font)66 hb_coretext_face_create (CGFontRef cg_font)
67 {
68   return hb_face_create_for_tables (reference_table, CGFontRetain (cg_font), (hb_destroy_func_t) CGFontRelease);
69 }
70 
71 
HB_SHAPER_DATA_ENSURE_DECLARE(coretext,face)72 HB_SHAPER_DATA_ENSURE_DECLARE(coretext, face)
73 HB_SHAPER_DATA_ENSURE_DECLARE(coretext, font)
74 
75 
76 /*
77  * shaper face data
78  */
79 
80 static CTFontDescriptorRef
81 get_last_resort_font_desc (void)
82 {
83   // TODO Handle allocation failures?
84   CTFontDescriptorRef last_resort = CTFontDescriptorCreateWithNameAndSize (CFSTR("LastResort"), 0);
85   CFArrayRef cascade_list = CFArrayCreate (kCFAllocatorDefault,
86 					   (const void **) &last_resort,
87 					   1,
88 					   &kCFTypeArrayCallBacks);
89   CFRelease (last_resort);
90   CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
91 						   (const void **) &kCTFontCascadeListAttribute,
92 						   (const void **) &cascade_list,
93 						   1,
94 						   &kCFTypeDictionaryKeyCallBacks,
95 						   &kCFTypeDictionaryValueCallBacks);
96   CFRelease (cascade_list);
97 
98   CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
99   CFRelease (attributes);
100   return font_desc;
101 }
102 
103 static void
release_data(void * info,const void * data,size_t size)104 release_data (void *info, const void *data, size_t size)
105 {
106   assert (hb_blob_get_length ((hb_blob_t *) info) == size &&
107           hb_blob_get_data ((hb_blob_t *) info, NULL) == data);
108 
109   hb_blob_destroy ((hb_blob_t *) info);
110 }
111 
112 static CGFontRef
create_cg_font(hb_face_t * face)113 create_cg_font (hb_face_t *face)
114 {
115   CGFontRef cg_font = NULL;
116   if (face->destroy == (hb_destroy_func_t) CGFontRelease)
117   {
118     cg_font = CGFontRetain ((CGFontRef) face->user_data);
119   }
120   else
121   {
122     hb_blob_t *blob = hb_face_reference_blob (face);
123     unsigned int blob_length;
124     const char *blob_data = hb_blob_get_data (blob, &blob_length);
125     if (unlikely (!blob_length))
126       DEBUG_MSG (CORETEXT, face, "Face has empty blob");
127 
128     CGDataProviderRef provider = CGDataProviderCreateWithData (blob, blob_data, blob_length, &release_data);
129     if (likely (provider))
130     {
131       cg_font = CGFontCreateWithDataProvider (provider);
132       if (unlikely (!cg_font))
133 	DEBUG_MSG (CORETEXT, face, "Face CGFontCreateWithDataProvider() failed");
134       CGDataProviderRelease (provider);
135     }
136   }
137   return cg_font;
138 }
139 
140 static CTFontRef
create_ct_font(CGFontRef cg_font,CGFloat font_size)141 create_ct_font (CGFontRef cg_font, CGFloat font_size)
142 {
143   CTFontRef ct_font = CTFontCreateWithGraphicsFont (cg_font, font_size, NULL, NULL);
144   if (unlikely (!ct_font)) {
145     DEBUG_MSG (CORETEXT, cg_font, "Font CTFontCreateWithGraphicsFont() failed");
146     return NULL;
147   }
148 
149   /* crbug.com/576941 and crbug.com/625902 and the investigation in the latter
150    * bug indicate that the cascade list reconfiguration occasionally causes
151    * crashes in CoreText on OS X 10.9, thus let's skip this step on older
152    * operating system versions. Except for the emoji font, where _not_
153    * reconfiguring the cascade list causes CoreText crashes. For details, see
154    * crbug.com/549610 */
155   // 0x00070000 stands for "kCTVersionNumber10_10", see CoreText.h
156   if (&CTGetCoreTextVersion != NULL && CTGetCoreTextVersion() < 0x00070000) {
157     CFStringRef fontName = CTFontCopyPostScriptName (ct_font);
158     bool isEmojiFont = CFStringCompare (fontName, CFSTR("AppleColorEmoji"), 0) == kCFCompareEqualTo;
159     CFRelease (fontName);
160     if (!isEmojiFont)
161       return ct_font;
162   }
163 
164   CFURLRef original_url = (CFURLRef)CTFontCopyAttribute(ct_font, kCTFontURLAttribute);
165 
166   /* Create font copy with cascade list that has LastResort first; this speeds up CoreText
167    * font fallback which we don't need anyway. */
168   {
169     CTFontDescriptorRef last_resort_font_desc = get_last_resort_font_desc ();
170     CTFontRef new_ct_font = CTFontCreateCopyWithAttributes (ct_font, 0.0, NULL, last_resort_font_desc);
171     CFRelease (last_resort_font_desc);
172     if (new_ct_font)
173     {
174       /* The CTFontCreateCopyWithAttributes call fails to stay on the same font
175        * when reconfiguring the cascade list and may switch to a different font
176        * when there are fonts that go by the same name, since the descriptor is
177        * just name and size.
178        *
179        * Avoid reconfiguring the cascade lists if the new font is outside the
180        * system locations that we cannot access from the sandboxed renderer
181        * process in Blink. This can be detected by the new file URL location
182        * that the newly found font points to. */
183       CFURLRef new_url = (CFURLRef) CTFontCopyAttribute (new_ct_font, kCTFontURLAttribute);
184       // Keep reconfigured font if URL cannot be retrieved (seems to be the case
185       // on Mac OS 10.12 Sierra), speculative fix for crbug.com/625606
186       if (!original_url || !new_url || CFEqual (original_url, new_url)) {
187         CFRelease (ct_font);
188         ct_font = new_ct_font;
189       } else {
190         CFRelease (new_ct_font);
191         DEBUG_MSG (CORETEXT, ct_font, "Discarding reconfigured CTFont, location changed.");
192       }
193       if (new_url)
194         CFRelease (new_url);
195     }
196     else
197       DEBUG_MSG (CORETEXT, ct_font, "Font copy with empty cascade list failed");
198   }
199 
200   if (original_url)
201     CFRelease (original_url);
202   return ct_font;
203 }
204 
205 struct hb_coretext_shaper_face_data_t {
206   CGFontRef cg_font;
207   CTFontRef ct_font;
208 };
209 
210 hb_coretext_shaper_face_data_t *
_hb_coretext_shaper_face_data_create(hb_face_t * face)211 _hb_coretext_shaper_face_data_create (hb_face_t *face)
212 {
213   hb_coretext_shaper_face_data_t *data = (hb_coretext_shaper_face_data_t *) calloc (1, sizeof (hb_coretext_shaper_face_data_t));
214   if (unlikely (!data))
215     return NULL;
216 
217   data->cg_font = create_cg_font (face);
218   if (unlikely (!data->cg_font))
219   {
220     DEBUG_MSG (CORETEXT, face, "CGFont creation failed..");
221     free (data);
222     return NULL;
223   }
224 
225   /* We use 36pt size instead of UPEM, because CoreText implements the 'trak' table,
226    * which can make the font too tight at large sizes.  36pt should be a good semi-neutral
227    * size.
228    *
229    * Since we always create CTFont at a fixed size, our CTFont lives in face_data
230    * instead of font_data.  Which is good, because when people change scale on
231    * hb_font_t, we won't need to update our CTFont. */
232   data->ct_font = create_ct_font (data->cg_font, 36.);
233   if (unlikely (!data->ct_font))
234   {
235     DEBUG_MSG (CORETEXT, face, "CTFont creation failed.");
236     CFRelease (data->cg_font);
237     free (data);
238     return NULL;
239   }
240 
241   return data;
242 }
243 
244 void
_hb_coretext_shaper_face_data_destroy(hb_coretext_shaper_face_data_t * data)245 _hb_coretext_shaper_face_data_destroy (hb_coretext_shaper_face_data_t *data)
246 {
247   CFRelease (data->ct_font);
248   CFRelease (data->cg_font);
249   free (data);
250 }
251 
252 /*
253  * Since: 0.9.10
254  */
255 CGFontRef
hb_coretext_face_get_cg_font(hb_face_t * face)256 hb_coretext_face_get_cg_font (hb_face_t *face)
257 {
258   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return NULL;
259   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
260   return face_data->cg_font;
261 }
262 
263 
264 /*
265  * shaper font data
266  */
267 
268 struct hb_coretext_shaper_font_data_t {};
269 
270 hb_coretext_shaper_font_data_t *
_hb_coretext_shaper_font_data_create(hb_font_t * font HB_UNUSED)271 _hb_coretext_shaper_font_data_create (hb_font_t *font HB_UNUSED)
272 {
273   return (hb_coretext_shaper_font_data_t *) HB_SHAPER_DATA_SUCCEEDED;
274 }
275 
276 void
_hb_coretext_shaper_font_data_destroy(hb_coretext_shaper_font_data_t * data)277 _hb_coretext_shaper_font_data_destroy (hb_coretext_shaper_font_data_t *data)
278 {
279 }
280 
281 
282 /*
283  * shaper shape_plan data
284  */
285 
286 struct hb_coretext_shaper_shape_plan_data_t {};
287 
288 hb_coretext_shaper_shape_plan_data_t *
_hb_coretext_shaper_shape_plan_data_create(hb_shape_plan_t * shape_plan HB_UNUSED,const hb_feature_t * user_features HB_UNUSED,unsigned int num_user_features HB_UNUSED,const int * coords HB_UNUSED,unsigned int num_coords HB_UNUSED)289 _hb_coretext_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
290 					     const hb_feature_t *user_features HB_UNUSED,
291 					     unsigned int        num_user_features HB_UNUSED,
292 					     const int          *coords HB_UNUSED,
293 					     unsigned int        num_coords HB_UNUSED)
294 {
295   return (hb_coretext_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
296 }
297 
298 void
_hb_coretext_shaper_shape_plan_data_destroy(hb_coretext_shaper_shape_plan_data_t * data HB_UNUSED)299 _hb_coretext_shaper_shape_plan_data_destroy (hb_coretext_shaper_shape_plan_data_t *data HB_UNUSED)
300 {
301 }
302 
303 CTFontRef
hb_coretext_font_get_ct_font(hb_font_t * font)304 hb_coretext_font_get_ct_font (hb_font_t *font)
305 {
306   hb_face_t *face = font->face;
307   if (unlikely (!hb_coretext_shaper_face_data_ensure (face))) return NULL;
308   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
309   return face_data->ct_font;
310 }
311 
312 
313 /*
314  * shaper
315  */
316 
317 struct feature_record_t {
318   unsigned int feature;
319   unsigned int setting;
320 };
321 
322 struct active_feature_t {
323   feature_record_t rec;
324   unsigned int order;
325 
cmpactive_feature_t326   static int cmp (const active_feature_t *a, const active_feature_t *b) {
327     return a->rec.feature < b->rec.feature ? -1 : a->rec.feature > b->rec.feature ? 1 :
328 	   a->order < b->order ? -1 : a->order > b->order ? 1 :
329 	   a->rec.setting < b->rec.setting ? -1 : a->rec.setting > b->rec.setting ? 1 :
330 	   0;
331   }
operator ==active_feature_t332   bool operator== (const active_feature_t *f) {
333     return cmp (this, f) == 0;
334   }
335 };
336 
337 struct feature_event_t {
338   unsigned int index;
339   bool start;
340   active_feature_t feature;
341 
cmpfeature_event_t342   static int cmp (const feature_event_t *a, const feature_event_t *b) {
343     return a->index < b->index ? -1 : a->index > b->index ? 1 :
344 	   a->start < b->start ? -1 : a->start > b->start ? 1 :
345 	   active_feature_t::cmp (&a->feature, &b->feature);
346   }
347 };
348 
349 struct range_record_t {
350   CTFontRef font;
351   unsigned int index_first; /* == start */
352   unsigned int index_last;  /* == end - 1 */
353 };
354 
355 
356 /* The following enum members are added in OS X 10.8. */
357 #define kAltHalfWidthTextSelector		6
358 #define kAltProportionalTextSelector		5
359 #define kAlternateHorizKanaOffSelector		1
360 #define kAlternateHorizKanaOnSelector		0
361 #define kAlternateKanaType			34
362 #define kAlternateVertKanaOffSelector		3
363 #define kAlternateVertKanaOnSelector		2
364 #define kCaseSensitiveLayoutOffSelector		1
365 #define kCaseSensitiveLayoutOnSelector		0
366 #define kCaseSensitiveLayoutType		33
367 #define kCaseSensitiveSpacingOffSelector	3
368 #define kCaseSensitiveSpacingOnSelector		2
369 #define kContextualAlternatesOffSelector	1
370 #define kContextualAlternatesOnSelector		0
371 #define kContextualAlternatesType		36
372 #define kContextualLigaturesOffSelector		19
373 #define kContextualLigaturesOnSelector		18
374 #define kContextualSwashAlternatesOffSelector	5
375 #define kContextualSwashAlternatesOnSelector	4
376 #define kDefaultLowerCaseSelector		0
377 #define kDefaultUpperCaseSelector		0
378 #define kHistoricalLigaturesOffSelector		21
379 #define kHistoricalLigaturesOnSelector		20
380 #define kHojoCharactersSelector			12
381 #define kJIS2004CharactersSelector		11
382 #define kLowerCasePetiteCapsSelector		2
383 #define kLowerCaseSmallCapsSelector		1
384 #define kLowerCaseType				37
385 #define kMathematicalGreekOffSelector		11
386 #define kMathematicalGreekOnSelector		10
387 #define kNLCCharactersSelector			13
388 #define kQuarterWidthTextSelector		4
389 #define kScientificInferiorsSelector		4
390 #define kStylisticAltEightOffSelector		17
391 #define kStylisticAltEightOnSelector		16
392 #define kStylisticAltEighteenOffSelector	37
393 #define kStylisticAltEighteenOnSelector		36
394 #define kStylisticAltElevenOffSelector		23
395 #define kStylisticAltElevenOnSelector		22
396 #define kStylisticAltFifteenOffSelector		31
397 #define kStylisticAltFifteenOnSelector		30
398 #define kStylisticAltFiveOffSelector		11
399 #define kStylisticAltFiveOnSelector		10
400 #define kStylisticAltFourOffSelector		9
401 #define kStylisticAltFourOnSelector		8
402 #define kStylisticAltFourteenOffSelector	29
403 #define kStylisticAltFourteenOnSelector		28
404 #define kStylisticAltNineOffSelector		19
405 #define kStylisticAltNineOnSelector		18
406 #define kStylisticAltNineteenOffSelector	39
407 #define kStylisticAltNineteenOnSelector		38
408 #define kStylisticAltOneOffSelector		3
409 #define kStylisticAltOneOnSelector		2
410 #define kStylisticAltSevenOffSelector		15
411 #define kStylisticAltSevenOnSelector		14
412 #define kStylisticAltSeventeenOffSelector	35
413 #define kStylisticAltSeventeenOnSelector	34
414 #define kStylisticAltSixOffSelector		13
415 #define kStylisticAltSixOnSelector		12
416 #define kStylisticAltSixteenOffSelector		33
417 #define kStylisticAltSixteenOnSelector		32
418 #define kStylisticAltTenOffSelector		21
419 #define kStylisticAltTenOnSelector		20
420 #define kStylisticAltThirteenOffSelector	27
421 #define kStylisticAltThirteenOnSelector		26
422 #define kStylisticAltThreeOffSelector		7
423 #define kStylisticAltThreeOnSelector		6
424 #define kStylisticAltTwelveOffSelector		25
425 #define kStylisticAltTwelveOnSelector		24
426 #define kStylisticAltTwentyOffSelector		41
427 #define kStylisticAltTwentyOnSelector		40
428 #define kStylisticAltTwoOffSelector		5
429 #define kStylisticAltTwoOnSelector		4
430 #define kStylisticAlternativesType		35
431 #define kSwashAlternatesOffSelector		3
432 #define kSwashAlternatesOnSelector		2
433 #define kThirdWidthTextSelector			3
434 #define kTraditionalNamesCharactersSelector	14
435 #define kUpperCasePetiteCapsSelector		2
436 #define kUpperCaseSmallCapsSelector		1
437 #define kUpperCaseType				38
438 
439 /* Table data courtesy of Apple. */
440 static const struct feature_mapping_t {
441     FourCharCode otFeatureTag;
442     uint16_t aatFeatureType;
443     uint16_t selectorToEnable;
444     uint16_t selectorToDisable;
445 } feature_mappings[] = {
446     { 'c2pc',   kUpperCaseType,             kUpperCasePetiteCapsSelector,           kDefaultUpperCaseSelector },
447     { 'c2sc',   kUpperCaseType,             kUpperCaseSmallCapsSelector,            kDefaultUpperCaseSelector },
448     { 'calt',   kContextualAlternatesType,  kContextualAlternatesOnSelector,        kContextualAlternatesOffSelector },
449     { 'case',   kCaseSensitiveLayoutType,   kCaseSensitiveLayoutOnSelector,         kCaseSensitiveLayoutOffSelector },
450     { 'clig',   kLigaturesType,             kContextualLigaturesOnSelector,         kContextualLigaturesOffSelector },
451     { 'cpsp',   kCaseSensitiveLayoutType,   kCaseSensitiveSpacingOnSelector,        kCaseSensitiveSpacingOffSelector },
452     { 'cswh',   kContextualAlternatesType,  kContextualSwashAlternatesOnSelector,   kContextualSwashAlternatesOffSelector },
453     { 'dlig',   kLigaturesType,             kRareLigaturesOnSelector,               kRareLigaturesOffSelector },
454     { 'expt',   kCharacterShapeType,        kExpertCharactersSelector,              16 },
455     { 'frac',   kFractionsType,             kDiagonalFractionsSelector,             kNoFractionsSelector },
456     { 'fwid',   kTextSpacingType,           kMonospacedTextSelector,                7 },
457     { 'halt',   kTextSpacingType,           kAltHalfWidthTextSelector,              7 },
458     { 'hist',   kLigaturesType,             kHistoricalLigaturesOnSelector,         kHistoricalLigaturesOffSelector },
459     { 'hkna',   kAlternateKanaType,         kAlternateHorizKanaOnSelector,          kAlternateHorizKanaOffSelector, },
460     { 'hlig',   kLigaturesType,             kHistoricalLigaturesOnSelector,         kHistoricalLigaturesOffSelector },
461     { 'hngl',   kTransliterationType,       kHanjaToHangulSelector,                 kNoTransliterationSelector },
462     { 'hojo',   kCharacterShapeType,        kHojoCharactersSelector,                16 },
463     { 'hwid',   kTextSpacingType,           kHalfWidthTextSelector,                 7 },
464     { 'ital',   kItalicCJKRomanType,        kCJKItalicRomanOnSelector,              kCJKItalicRomanOffSelector },
465     { 'jp04',   kCharacterShapeType,        kJIS2004CharactersSelector,             16 },
466     { 'jp78',   kCharacterShapeType,        kJIS1978CharactersSelector,             16 },
467     { 'jp83',   kCharacterShapeType,        kJIS1983CharactersSelector,             16 },
468     { 'jp90',   kCharacterShapeType,        kJIS1990CharactersSelector,             16 },
469     { 'liga',   kLigaturesType,             kCommonLigaturesOnSelector,             kCommonLigaturesOffSelector },
470     { 'lnum',   kNumberCaseType,            kUpperCaseNumbersSelector,              2 },
471     { 'mgrk',   kMathematicalExtrasType,    kMathematicalGreekOnSelector,           kMathematicalGreekOffSelector },
472     { 'nlck',   kCharacterShapeType,        kNLCCharactersSelector,                 16 },
473     { 'onum',   kNumberCaseType,            kLowerCaseNumbersSelector,              2 },
474     { 'ordn',   kVerticalPositionType,      kOrdinalsSelector,                      kNormalPositionSelector },
475     { 'palt',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
476     { 'pcap',   kLowerCaseType,             kLowerCasePetiteCapsSelector,           kDefaultLowerCaseSelector },
477     { 'pkna',   kTextSpacingType,           kProportionalTextSelector,              7 },
478     { 'pnum',   kNumberSpacingType,         kProportionalNumbersSelector,           4 },
479     { 'pwid',   kTextSpacingType,           kProportionalTextSelector,              7 },
480     { 'qwid',   kTextSpacingType,           kQuarterWidthTextSelector,              7 },
481     { 'ruby',   kRubyKanaType,              kRubyKanaOnSelector,                    kRubyKanaOffSelector },
482     { 'sinf',   kVerticalPositionType,      kScientificInferiorsSelector,           kNormalPositionSelector },
483     { 'smcp',   kLowerCaseType,             kLowerCaseSmallCapsSelector,            kDefaultLowerCaseSelector },
484     { 'smpl',   kCharacterShapeType,        kSimplifiedCharactersSelector,          16 },
485     { 'ss01',   kStylisticAlternativesType, kStylisticAltOneOnSelector,             kStylisticAltOneOffSelector },
486     { 'ss02',   kStylisticAlternativesType, kStylisticAltTwoOnSelector,             kStylisticAltTwoOffSelector },
487     { 'ss03',   kStylisticAlternativesType, kStylisticAltThreeOnSelector,           kStylisticAltThreeOffSelector },
488     { 'ss04',   kStylisticAlternativesType, kStylisticAltFourOnSelector,            kStylisticAltFourOffSelector },
489     { 'ss05',   kStylisticAlternativesType, kStylisticAltFiveOnSelector,            kStylisticAltFiveOffSelector },
490     { 'ss06',   kStylisticAlternativesType, kStylisticAltSixOnSelector,             kStylisticAltSixOffSelector },
491     { 'ss07',   kStylisticAlternativesType, kStylisticAltSevenOnSelector,           kStylisticAltSevenOffSelector },
492     { 'ss08',   kStylisticAlternativesType, kStylisticAltEightOnSelector,           kStylisticAltEightOffSelector },
493     { 'ss09',   kStylisticAlternativesType, kStylisticAltNineOnSelector,            kStylisticAltNineOffSelector },
494     { 'ss10',   kStylisticAlternativesType, kStylisticAltTenOnSelector,             kStylisticAltTenOffSelector },
495     { 'ss11',   kStylisticAlternativesType, kStylisticAltElevenOnSelector,          kStylisticAltElevenOffSelector },
496     { 'ss12',   kStylisticAlternativesType, kStylisticAltTwelveOnSelector,          kStylisticAltTwelveOffSelector },
497     { 'ss13',   kStylisticAlternativesType, kStylisticAltThirteenOnSelector,        kStylisticAltThirteenOffSelector },
498     { 'ss14',   kStylisticAlternativesType, kStylisticAltFourteenOnSelector,        kStylisticAltFourteenOffSelector },
499     { 'ss15',   kStylisticAlternativesType, kStylisticAltFifteenOnSelector,         kStylisticAltFifteenOffSelector },
500     { 'ss16',   kStylisticAlternativesType, kStylisticAltSixteenOnSelector,         kStylisticAltSixteenOffSelector },
501     { 'ss17',   kStylisticAlternativesType, kStylisticAltSeventeenOnSelector,       kStylisticAltSeventeenOffSelector },
502     { 'ss18',   kStylisticAlternativesType, kStylisticAltEighteenOnSelector,        kStylisticAltEighteenOffSelector },
503     { 'ss19',   kStylisticAlternativesType, kStylisticAltNineteenOnSelector,        kStylisticAltNineteenOffSelector },
504     { 'ss20',   kStylisticAlternativesType, kStylisticAltTwentyOnSelector,          kStylisticAltTwentyOffSelector },
505     { 'subs',   kVerticalPositionType,      kInferiorsSelector,                     kNormalPositionSelector },
506     { 'sups',   kVerticalPositionType,      kSuperiorsSelector,                     kNormalPositionSelector },
507     { 'swsh',   kContextualAlternatesType,  kSwashAlternatesOnSelector,             kSwashAlternatesOffSelector },
508     { 'titl',   kStyleOptionsType,          kTitlingCapsSelector,                   kNoStyleOptionsSelector },
509     { 'tnam',   kCharacterShapeType,        kTraditionalNamesCharactersSelector,    16 },
510     { 'tnum',   kNumberSpacingType,         kMonospacedNumbersSelector,             4 },
511     { 'trad',   kCharacterShapeType,        kTraditionalCharactersSelector,         16 },
512     { 'twid',   kTextSpacingType,           kThirdWidthTextSelector,                7 },
513     { 'unic',   kLetterCaseType,            14,                                     15 },
514     { 'valt',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
515     { 'vert',   kVerticalSubstitutionType,  kSubstituteVerticalFormsOnSelector,     kSubstituteVerticalFormsOffSelector },
516     { 'vhal',   kTextSpacingType,           kAltHalfWidthTextSelector,              7 },
517     { 'vkna',   kAlternateKanaType,         kAlternateVertKanaOnSelector,           kAlternateVertKanaOffSelector },
518     { 'vpal',   kTextSpacingType,           kAltProportionalTextSelector,           7 },
519     { 'vrt2',   kVerticalSubstitutionType,  kSubstituteVerticalFormsOnSelector,     kSubstituteVerticalFormsOffSelector },
520     { 'zero',   kTypographicExtrasType,     kSlashedZeroOnSelector,                 kSlashedZeroOffSelector },
521 };
522 
523 static int
_hb_feature_mapping_cmp(const void * key_,const void * entry_)524 _hb_feature_mapping_cmp (const void *key_, const void *entry_)
525 {
526   unsigned int key = * (unsigned int *) key_;
527   const feature_mapping_t * entry = (const feature_mapping_t *) entry_;
528   return key < entry->otFeatureTag ? -1 :
529 	 key > entry->otFeatureTag ? 1 :
530 	 0;
531 }
532 
533 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)534 _hb_coretext_shape (hb_shape_plan_t    *shape_plan,
535 		    hb_font_t          *font,
536                     hb_buffer_t        *buffer,
537                     const hb_feature_t *features,
538                     unsigned int        num_features)
539 {
540   hb_face_t *face = font->face;
541   hb_coretext_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
542 
543   CGFloat ct_font_size = CTFontGetSize (face_data->ct_font);
544   CGFloat x_mult = (CGFloat) font->x_scale / ct_font_size;
545   CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;
546 
547   /* Attach marks to their bases, to match the 'ot' shaper.
548    * Adapted from hb-ot-shape:hb_form_clusters().
549    * Note that this only makes us be closer to the 'ot' shaper,
550    * but by no means the same.  For example, if there's
551    * B1 M1 B2 M2, and B1-B2 form a ligature, M2's cluster will
552    * continue pointing to B2 even though B2 was merged into B1's
553    * cluster... */
554   if (buffer->cluster_level == HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES)
555   {
556     hb_unicode_funcs_t *unicode = buffer->unicode;
557     unsigned int count = buffer->len;
558     hb_glyph_info_t *info = buffer->info;
559     for (unsigned int i = 1; i < count; i++)
560       if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (unicode->general_category (info[i].codepoint)))
561 	buffer->merge_clusters (i - 1, i + 1);
562   }
563 
564   hb_auto_array_t<feature_record_t> feature_records;
565   hb_auto_array_t<range_record_t> range_records;
566 
567   /*
568    * Set up features.
569    * (copied + modified from code from hb-uniscribe.cc)
570    */
571   if (num_features)
572   {
573     /* Sort features by start/end events. */
574     hb_auto_array_t<feature_event_t> feature_events;
575     for (unsigned int i = 0; i < num_features; i++)
576     {
577       const feature_mapping_t * mapping = (const feature_mapping_t *) bsearch (&features[i].tag,
578 									       feature_mappings,
579 									       ARRAY_LENGTH (feature_mappings),
580 									       sizeof (feature_mappings[0]),
581 									       _hb_feature_mapping_cmp);
582       if (!mapping)
583         continue;
584 
585       active_feature_t feature;
586       feature.rec.feature = mapping->aatFeatureType;
587       feature.rec.setting = features[i].value ? mapping->selectorToEnable : mapping->selectorToDisable;
588       feature.order = i;
589 
590       feature_event_t *event;
591 
592       event = feature_events.push ();
593       if (unlikely (!event))
594 	goto fail_features;
595       event->index = features[i].start;
596       event->start = true;
597       event->feature = feature;
598 
599       event = feature_events.push ();
600       if (unlikely (!event))
601 	goto fail_features;
602       event->index = features[i].end;
603       event->start = false;
604       event->feature = feature;
605     }
606     feature_events.qsort ();
607     /* Add a strategic final event. */
608     {
609       active_feature_t feature;
610       feature.rec.feature = HB_TAG_NONE;
611       feature.rec.setting = 0;
612       feature.order = num_features + 1;
613 
614       feature_event_t *event = feature_events.push ();
615       if (unlikely (!event))
616 	goto fail_features;
617       event->index = 0; /* This value does magic. */
618       event->start = false;
619       event->feature = feature;
620     }
621 
622     /* Scan events and save features for each range. */
623     hb_auto_array_t<active_feature_t> active_features;
624     unsigned int last_index = 0;
625     for (unsigned int i = 0; i < feature_events.len; i++)
626     {
627       feature_event_t *event = &feature_events[i];
628 
629       if (event->index != last_index)
630       {
631         /* Save a snapshot of active features and the range. */
632 	range_record_t *range = range_records.push ();
633 	if (unlikely (!range))
634 	  goto fail_features;
635 
636 	if (active_features.len)
637 	{
638 	  CFMutableArrayRef features_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
639 
640 	  /* TODO sort and resolve conflicting features? */
641 	  /* active_features.qsort (); */
642 	  for (unsigned int j = 0; j < active_features.len; j++)
643 	  {
644 	    CFStringRef keys[2] = {
645 	      kCTFontFeatureTypeIdentifierKey,
646 	      kCTFontFeatureSelectorIdentifierKey
647 	    };
648 	    CFNumberRef values[2] = {
649 	      CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.feature),
650 	      CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &active_features[j].rec.setting)
651 	    };
652 	    CFDictionaryRef dict = CFDictionaryCreate (kCFAllocatorDefault,
653 						       (const void **) keys,
654 						       (const void **) values,
655 						       2,
656 						       &kCFTypeDictionaryKeyCallBacks,
657 						       &kCFTypeDictionaryValueCallBacks);
658 	    CFRelease (values[0]);
659 	    CFRelease (values[1]);
660 
661 	    CFArrayAppendValue (features_array, dict);
662 	    CFRelease (dict);
663 
664 	  }
665 
666 	  CFDictionaryRef attributes = CFDictionaryCreate (kCFAllocatorDefault,
667 							   (const void **) &kCTFontFeatureSettingsAttribute,
668 							   (const void **) &features_array,
669 							   1,
670 							   &kCFTypeDictionaryKeyCallBacks,
671 							   &kCFTypeDictionaryValueCallBacks);
672 	  CFRelease (features_array);
673 
674 	  CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes (attributes);
675 	  CFRelease (attributes);
676 
677 	  range->font = CTFontCreateCopyWithAttributes (face_data->ct_font, 0.0, NULL, font_desc);
678 	  CFRelease (font_desc);
679 	}
680 	else
681 	{
682 	  range->font = NULL;
683 	}
684 
685 	range->index_first = last_index;
686 	range->index_last  = event->index - 1;
687 
688 	last_index = event->index;
689       }
690 
691       if (event->start) {
692         active_feature_t *feature = active_features.push ();
693 	if (unlikely (!feature))
694 	  goto fail_features;
695 	*feature = event->feature;
696       } else {
697         active_feature_t *feature = active_features.find (&event->feature);
698 	if (feature)
699 	  active_features.remove (feature - active_features.array);
700       }
701     }
702 
703     if (!range_records.len) /* No active feature found. */
704       goto fail_features;
705   }
706   else
707   {
708   fail_features:
709     num_features = 0;
710   }
711 
712   unsigned int scratch_size;
713   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
714 
715 #define ALLOCATE_ARRAY(Type, name, len, on_no_room) \
716   Type *name = (Type *) scratch; \
717   { \
718     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
719     if (unlikely (_consumed > scratch_size)) \
720     { \
721       on_no_room; \
722       assert (0); \
723     } \
724     scratch += _consumed; \
725     scratch_size -= _consumed; \
726   }
727 
728   ALLOCATE_ARRAY (UniChar, pchars, buffer->len * 2, /*nothing*/);
729   unsigned int chars_len = 0;
730   for (unsigned int i = 0; i < buffer->len; i++) {
731     hb_codepoint_t c = buffer->info[i].codepoint;
732     if (likely (c <= 0xFFFFu))
733       pchars[chars_len++] = c;
734     else if (unlikely (c > 0x10FFFFu))
735       pchars[chars_len++] = 0xFFFDu;
736     else {
737       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
738       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
739     }
740   }
741 
742   ALLOCATE_ARRAY (unsigned int, log_clusters, chars_len, /*nothing*/);
743   chars_len = 0;
744   for (unsigned int i = 0; i < buffer->len; i++)
745   {
746     hb_codepoint_t c = buffer->info[i].codepoint;
747     unsigned int cluster = buffer->info[i].cluster;
748     log_clusters[chars_len++] = cluster;
749     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
750       log_clusters[chars_len++] = cluster; /* Surrogates. */
751   }
752 
753 #define FAIL(...) \
754   HB_STMT_START { \
755     DEBUG_MSG (CORETEXT, NULL, __VA_ARGS__); \
756     ret = false; \
757     goto fail; \
758   } HB_STMT_END;
759 
760   bool ret = true;
761   CFStringRef string_ref = NULL;
762   CTLineRef line = NULL;
763 
764   if (0)
765   {
766 resize_and_retry:
767     DEBUG_MSG (CORETEXT, buffer, "Buffer resize");
768     /* string_ref uses the scratch-buffer for backing store, and line references
769      * string_ref (via attr_string).  We must release those before resizing buffer. */
770     assert (string_ref);
771     assert (line);
772     CFRelease (string_ref);
773     CFRelease (line);
774     string_ref = NULL;
775     line = NULL;
776 
777     /* Get previous start-of-scratch-area, that we use later for readjusting
778      * our existing scratch arrays. */
779     unsigned int old_scratch_used;
780     hb_buffer_t::scratch_buffer_t *old_scratch;
781     old_scratch = buffer->get_scratch_buffer (&old_scratch_used);
782     old_scratch_used = scratch - old_scratch;
783 
784     if (unlikely (!buffer->ensure (buffer->allocated * 2)))
785       FAIL ("Buffer resize failed");
786 
787     /* Adjust scratch, pchars, and log_cluster arrays.  This is ugly, but really the
788      * cleanest way to do without completely restructuring the rest of this shaper. */
789     scratch = buffer->get_scratch_buffer (&scratch_size);
790     pchars = reinterpret_cast<UniChar *> (((char *) scratch + ((char *) pchars - (char *) old_scratch)));
791     log_clusters = reinterpret_cast<unsigned int *> (((char *) scratch + ((char *) log_clusters - (char *) old_scratch)));
792     scratch += old_scratch_used;
793     scratch_size -= old_scratch_used;
794   }
795   {
796     string_ref = CFStringCreateWithCharactersNoCopy (NULL,
797 						     pchars, chars_len,
798 						     kCFAllocatorNull);
799     if (unlikely (!string_ref))
800       FAIL ("CFStringCreateWithCharactersNoCopy failed");
801 
802     /* Create an attributed string, populate it, and create a line from it, then release attributed string. */
803     {
804       CFMutableAttributedStringRef attr_string = CFAttributedStringCreateMutable (kCFAllocatorDefault,
805 										  chars_len);
806       if (unlikely (!attr_string))
807 	FAIL ("CFAttributedStringCreateMutable failed");
808       CFAttributedStringReplaceString (attr_string, CFRangeMake (0, 0), string_ref);
809       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
810       {
811 	CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
812 					kCTVerticalFormsAttributeName, kCFBooleanTrue);
813       }
814 
815       if (buffer->props.language)
816       {
817 /* What's the iOS equivalent of this check?
818  * The symbols was introduced in iOS 7.0.
819  * At any rate, our fallback is safe and works fine. */
820 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
821 #  define kCTLanguageAttributeName CFSTR ("NSLanguage")
822 #endif
823         CFStringRef lang = CFStringCreateWithCStringNoCopy (kCFAllocatorDefault,
824 							    hb_language_to_string (buffer->props.language),
825 							    kCFStringEncodingUTF8,
826 							    kCFAllocatorNull);
827 	if (unlikely (!lang))
828 	  FAIL ("CFStringCreateWithCStringNoCopy failed");
829 	CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
830 					kCTLanguageAttributeName, lang);
831 	CFRelease (lang);
832       }
833       CFAttributedStringSetAttribute (attr_string, CFRangeMake (0, chars_len),
834 				      kCTFontAttributeName, face_data->ct_font);
835 
836       if (num_features)
837       {
838 	unsigned int start = 0;
839 	range_record_t *last_range = &range_records[0];
840 	for (unsigned int k = 0; k < chars_len; k++)
841 	{
842 	  range_record_t *range = last_range;
843 	  while (log_clusters[k] < range->index_first)
844 	    range--;
845 	  while (log_clusters[k] > range->index_last)
846 	    range++;
847 	  if (range != last_range)
848 	  {
849 	    if (last_range->font)
850 	      CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, k - start),
851 					      kCTFontAttributeName, last_range->font);
852 
853 	    start = k;
854 	  }
855 
856 	  last_range = range;
857 	}
858 	if (start != chars_len && last_range->font)
859 	  CFAttributedStringSetAttribute (attr_string, CFRangeMake (start, chars_len - start),
860 					  kCTFontAttributeName, last_range->font);
861       }
862 
863       int level = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
864       CFNumberRef level_number = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &level);
865       CFDictionaryRef options = CFDictionaryCreate (kCFAllocatorDefault,
866 						    (const void **) &kCTTypesetterOptionForcedEmbeddingLevel,
867 						    (const void **) &level_number,
868 						    1,
869 						    &kCFTypeDictionaryKeyCallBacks,
870 						    &kCFTypeDictionaryValueCallBacks);
871       if (unlikely (!options))
872         FAIL ("CFDictionaryCreate failed");
873 
874       CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedStringAndOptions (attr_string, options);
875       CFRelease (options);
876       CFRelease (attr_string);
877       if (unlikely (!typesetter))
878 	FAIL ("CTTypesetterCreateWithAttributedStringAndOptions failed");
879 
880       line = CTTypesetterCreateLine (typesetter, CFRangeMake(0, 0));
881       CFRelease (typesetter);
882       if (unlikely (!line))
883 	FAIL ("CTTypesetterCreateLine failed");
884     }
885 
886     CFArrayRef glyph_runs = CTLineGetGlyphRuns (line);
887     unsigned int num_runs = CFArrayGetCount (glyph_runs);
888     DEBUG_MSG (CORETEXT, NULL, "Num runs: %d", num_runs);
889 
890     buffer->len = 0;
891     uint32_t status_and = ~0, status_or = 0;
892     double advances_so_far = 0;
893     /* For right-to-left runs, CoreText returns the glyphs positioned such that
894      * any trailing whitespace is to the left of (0,0).  Adjust coordinate system
895      * to fix for that.  Test with any RTL string with trailing spaces.
896      * https://code.google.com/p/chromium/issues/detail?id=469028
897      */
898     if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
899     {
900       advances_so_far -= CTLineGetTrailingWhitespaceWidth (line);
901       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
902 	  advances_so_far = -advances_so_far;
903     }
904 
905     const CFRange range_all = CFRangeMake (0, 0);
906 
907     for (unsigned int i = 0; i < num_runs; i++)
908     {
909       CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex (glyph_runs, i));
910       CTRunStatus run_status = CTRunGetStatus (run);
911       status_or  |= run_status;
912       status_and &= run_status;
913       DEBUG_MSG (CORETEXT, run, "CTRunStatus: %x", run_status);
914       double run_advance = CTRunGetTypographicBounds (run, range_all, NULL, NULL, NULL);
915       if (HB_DIRECTION_IS_VERTICAL (buffer->props.direction))
916 	  run_advance = -run_advance;
917       DEBUG_MSG (CORETEXT, run, "Run advance: %g", run_advance);
918 
919       /* CoreText does automatic font fallback (AKA "cascading") for  characters
920        * not supported by the requested font, and provides no way to turn it off,
921        * so we must detect if the returned run uses a font other than the requested
922        * one and fill in the buffer with .notdef glyphs instead of random glyph
923        * indices from a different font.
924        */
925       CFDictionaryRef attributes = CTRunGetAttributes (run);
926       CTFontRef run_ct_font = static_cast<CTFontRef>(CFDictionaryGetValue (attributes, kCTFontAttributeName));
927       if (!CFEqual (run_ct_font, face_data->ct_font))
928       {
929 	/* The run doesn't use our main font instance.  We have to figure out
930 	 * whether font fallback happened, or this is just CoreText giving us
931 	 * another CTFont using the same underlying CGFont.  CoreText seems
932 	 * to do that in a variety of situations, one of which being vertical
933 	 * text, but also perhaps for caching reasons.
934 	 *
935 	 * First, see if it uses any of our subfonts created to set font features...
936 	 *
937 	 * Next, compare the CGFont to the one we used to create our fonts.
938 	 * Even this doesn't work all the time.
939 	 *
940 	 * Finally, we compare PS names, which I don't think are unique...
941 	 *
942 	 * Looks like if we really want to be sure here we have to modify the
943 	 * font to change the name table, similar to what we do in the uniscribe
944 	 * backend.
945 	 *
946 	 * However, even that wouldn't work if we were passed in the CGFont to
947 	 * construct a hb_face to begin with.
948 	 *
949 	 * See: http://github.com/behdad/harfbuzz/pull/36
950 	 *
951 	 * Also see: https://bugs.chromium.org/p/chromium/issues/detail?id=597098
952 	 */
953 	bool matched = false;
954 	for (unsigned int i = 0; i < range_records.len; i++)
955 	  if (range_records[i].font && CFEqual (run_ct_font, range_records[i].font))
956 	  {
957 	    matched = true;
958 	    break;
959 	  }
960 	if (!matched)
961 	{
962 	  CGFontRef run_cg_font = CTFontCopyGraphicsFont (run_ct_font, 0);
963 	  if (run_cg_font)
964 	  {
965 	    matched = CFEqual (run_cg_font, face_data->cg_font);
966 	    CFRelease (run_cg_font);
967 	  }
968 	}
969 	if (!matched)
970 	{
971 	  CFStringRef font_ps_name = CTFontCopyName (face_data->ct_font, kCTFontPostScriptNameKey);
972 	  CFStringRef run_ps_name = CTFontCopyName (run_ct_font, kCTFontPostScriptNameKey);
973 	  CFComparisonResult result = CFStringCompare (run_ps_name, font_ps_name, 0);
974 	  CFRelease (run_ps_name);
975 	  CFRelease (font_ps_name);
976 	  if (result == kCFCompareEqualTo)
977 	    matched = true;
978 	}
979 	if (!matched)
980 	{
981 	  CFRange range = CTRunGetStringRange (run);
982           DEBUG_MSG (CORETEXT, run, "Run used fallback font: %ld..%ld",
983 		     range.location, range.location + range.length);
984 	  if (!buffer->ensure_inplace (buffer->len + range.length))
985 	    goto resize_and_retry;
986 	  hb_glyph_info_t *info = buffer->info + buffer->len;
987 
988 	  hb_codepoint_t notdef = 0;
989 	  hb_direction_t dir = buffer->props.direction;
990 	  hb_position_t x_advance, y_advance, x_offset, y_offset;
991 	  hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);
992 	  hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);
993 	  hb_position_t advance = x_advance + y_advance;
994 	  x_offset = -x_offset;
995 	  y_offset = -y_offset;
996 
997 	  unsigned int old_len = buffer->len;
998 	  for (CFIndex j = range.location; j < range.location + range.length; j++)
999 	  {
1000 	      UniChar ch = CFStringGetCharacterAtIndex (string_ref, j);
1001 	      if (hb_in_range<UniChar> (ch, 0xDC00u, 0xDFFFu) && range.location < j)
1002 	      {
1003 		ch = CFStringGetCharacterAtIndex (string_ref, j - 1);
1004 		if (hb_in_range<UniChar> (ch, 0xD800u, 0xDBFFu))
1005 		  /* This is the second of a surrogate pair.  Don't need .notdef
1006 		   * for this one. */
1007 		  continue;
1008 	      }
1009 	      if (buffer->unicode->is_default_ignorable (ch))
1010 	        continue;
1011 
1012 	      info->codepoint = notdef;
1013 	      info->cluster = log_clusters[j];
1014 
1015 	      info->mask = advance;
1016 	      info->var1.i32 = x_offset;
1017 	      info->var2.i32 = y_offset;
1018 
1019 	      info++;
1020 	      buffer->len++;
1021 	  }
1022 	  if (HB_DIRECTION_IS_BACKWARD (buffer->props.direction))
1023 	    buffer->reverse_range (old_len, buffer->len);
1024 	  advances_so_far += run_advance;
1025 	  continue;
1026 	}
1027       }
1028 
1029       unsigned int num_glyphs = CTRunGetGlyphCount (run);
1030       if (num_glyphs == 0)
1031 	continue;
1032 
1033       if (!buffer->ensure_inplace (buffer->len + num_glyphs))
1034 	goto resize_and_retry;
1035 
1036       hb_glyph_info_t *run_info = buffer->info + buffer->len;
1037 
1038       /* Testing used to indicate that CTRunGetGlyphsPtr, etc (almost?) always
1039        * succeed, and so copying data to our own buffer will be rare.  Reports
1040        * have it that this changed in OS X 10.10 Yosemite, and NULL is returned
1041        * frequently.  At any rate, we can test that codepath by setting USE_PTR
1042        * to false. */
1043 
1044 #define USE_PTR true
1045 
1046 #define SCRATCH_SAVE() \
1047   unsigned int scratch_size_saved = scratch_size; \
1048   hb_buffer_t::scratch_buffer_t *scratch_saved = scratch
1049 
1050 #define SCRATCH_RESTORE() \
1051   scratch_size = scratch_size_saved; \
1052   scratch = scratch_saved;
1053 
1054       { /* Setup glyphs */
1055         SCRATCH_SAVE();
1056 	const CGGlyph* glyphs = USE_PTR ? CTRunGetGlyphsPtr (run) : NULL;
1057 	if (!glyphs) {
1058 	  ALLOCATE_ARRAY (CGGlyph, glyph_buf, num_glyphs, goto resize_and_retry);
1059 	  CTRunGetGlyphs (run, range_all, glyph_buf);
1060 	  glyphs = glyph_buf;
1061 	}
1062 	const CFIndex* string_indices = USE_PTR ? CTRunGetStringIndicesPtr (run) : NULL;
1063 	if (!string_indices) {
1064 	  ALLOCATE_ARRAY (CFIndex, index_buf, num_glyphs, goto resize_and_retry);
1065 	  CTRunGetStringIndices (run, range_all, index_buf);
1066 	  string_indices = index_buf;
1067 	}
1068 	hb_glyph_info_t *info = run_info;
1069 	for (unsigned int j = 0; j < num_glyphs; j++)
1070 	{
1071 	  info->codepoint = glyphs[j];
1072 	  info->cluster = log_clusters[string_indices[j]];
1073 	  info++;
1074 	}
1075 	SCRATCH_RESTORE();
1076       }
1077       {
1078         /* Setup positions.
1079 	 * Note that CoreText does not return advances for glyphs.  As such,
1080 	 * for all but last glyph, we use the delta position to next glyph as
1081 	 * advance (in the advance direction only), and for last glyph we set
1082 	 * whatever is needed to make the whole run's advance add up. */
1083         SCRATCH_SAVE();
1084 	const CGPoint* positions = USE_PTR ? CTRunGetPositionsPtr (run) : NULL;
1085 	if (!positions) {
1086 	  ALLOCATE_ARRAY (CGPoint, position_buf, num_glyphs, goto resize_and_retry);
1087 	  CTRunGetPositions (run, range_all, position_buf);
1088 	  positions = position_buf;
1089 	}
1090 	hb_glyph_info_t *info = run_info;
1091 	if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1092 	{
1093 	  hb_position_t x_offset = (positions[0].x - advances_so_far) * x_mult;
1094 	  for (unsigned int j = 0; j < num_glyphs; j++)
1095 	  {
1096 	    double advance;
1097 	    if (likely (j + 1 < num_glyphs))
1098 	      advance = positions[j + 1].x - positions[j].x;
1099 	    else /* last glyph */
1100 	      advance = run_advance - (positions[j].x - positions[0].x);
1101 	    info->mask = advance * x_mult;
1102 	    info->var1.i32 = x_offset;
1103 	    info->var2.i32 = positions[j].y * y_mult;
1104 	    info++;
1105 	  }
1106 	}
1107 	else
1108 	{
1109 	  hb_position_t y_offset = (positions[0].y - advances_so_far) * y_mult;
1110 	  for (unsigned int j = 0; j < num_glyphs; j++)
1111 	  {
1112 	    double advance;
1113 	    if (likely (j + 1 < num_glyphs))
1114 	      advance = positions[j + 1].y - positions[j].y;
1115 	    else /* last glyph */
1116 	      advance = run_advance - (positions[j].y - positions[0].y);
1117 	    info->mask = advance * y_mult;
1118 	    info->var1.i32 = positions[j].x * x_mult;
1119 	    info->var2.i32 = y_offset;
1120 	    info++;
1121 	  }
1122 	}
1123 	SCRATCH_RESTORE();
1124 	advances_so_far += run_advance;
1125       }
1126 #undef SCRATCH_RESTORE
1127 #undef SCRATCH_SAVE
1128 #undef USE_PTR
1129 #undef ALLOCATE_ARRAY
1130 
1131       buffer->len += num_glyphs;
1132     }
1133 
1134     /* Mac OS 10.6 doesn't have kCTTypesetterOptionForcedEmbeddingLevel,
1135      * or if it does, it doesn't resepct it.  So we get runs with wrong
1136      * directions.  As such, disable the assert...  It wouldn't crash, but
1137      * cursoring will be off...
1138      *
1139      * http://crbug.com/419769
1140      */
1141     if (0)
1142     {
1143       /* Make sure all runs had the expected direction. */
1144       bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
1145       assert (bool (status_and & kCTRunStatusRightToLeft) == backward);
1146       assert (bool (status_or  & kCTRunStatusRightToLeft) == backward);
1147     }
1148 
1149     buffer->clear_positions ();
1150 
1151     unsigned int count = buffer->len;
1152     hb_glyph_info_t *info = buffer->info;
1153     hb_glyph_position_t *pos = buffer->pos;
1154     if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))
1155       for (unsigned int i = 0; i < count; i++)
1156       {
1157 	pos->x_advance = info->mask;
1158 	pos->x_offset = info->var1.i32;
1159 	pos->y_offset = info->var2.i32;
1160 	info++, pos++;
1161       }
1162     else
1163       for (unsigned int i = 0; i < count; i++)
1164       {
1165 	pos->y_advance = info->mask;
1166 	pos->x_offset = info->var1.i32;
1167 	pos->y_offset = info->var2.i32;
1168 	info++, pos++;
1169       }
1170 
1171     /* Fix up clusters so that we never return out-of-order indices;
1172      * if core text has reordered glyphs, we'll merge them to the
1173      * beginning of the reordered cluster.  CoreText is nice enough
1174      * to tell us whenever it has produced nonmonotonic results...
1175      * Note that we assume the input clusters were nonmonotonic to
1176      * begin with.
1177      *
1178      * This does *not* mean we'll form the same clusters as Uniscribe
1179      * or the native OT backend, only that the cluster indices will be
1180      * monotonic in the output buffer. */
1181     if (count > 1 && (status_or & kCTRunStatusNonMonotonic))
1182     {
1183       hb_glyph_info_t *info = buffer->info;
1184       if (HB_DIRECTION_IS_FORWARD (buffer->props.direction))
1185       {
1186 	unsigned int cluster = info[count - 1].cluster;
1187 	for (unsigned int i = count - 1; i > 0; i--)
1188 	{
1189 	  cluster = MIN (cluster, info[i - 1].cluster);
1190 	  info[i - 1].cluster = cluster;
1191 	}
1192       }
1193       else
1194       {
1195 	unsigned int cluster = info[0].cluster;
1196 	for (unsigned int i = 1; i < count; i++)
1197 	{
1198 	  cluster = MIN (cluster, info[i].cluster);
1199 	  info[i].cluster = cluster;
1200 	}
1201       }
1202     }
1203   }
1204 
1205 #undef FAIL
1206 
1207 fail:
1208   if (string_ref)
1209     CFRelease (string_ref);
1210   if (line)
1211     CFRelease (line);
1212 
1213   for (unsigned int i = 0; i < range_records.len; i++)
1214     if (range_records[i].font)
1215       CFRelease (range_records[i].font);
1216 
1217   return ret;
1218 }
1219 
1220 
1221 /*
1222  * AAT shaper
1223  */
1224 
1225 /*
1226  * shaper face data
1227  */
1228 
1229 struct hb_coretext_aat_shaper_face_data_t {};
1230 
1231 hb_coretext_aat_shaper_face_data_t *
_hb_coretext_aat_shaper_face_data_create(hb_face_t * face)1232 _hb_coretext_aat_shaper_face_data_create (hb_face_t *face)
1233 {
1234   hb_blob_t *mort_blob = face->reference_table (HB_CORETEXT_TAG_MORT);
1235   /* Umm, we just reference the table to check whether it exists.
1236    * Maybe add better API for this? */
1237   if (!hb_blob_get_length (mort_blob))
1238   {
1239     hb_blob_destroy (mort_blob);
1240     mort_blob = face->reference_table (HB_CORETEXT_TAG_MORX);
1241     if (!hb_blob_get_length (mort_blob))
1242     {
1243       hb_blob_destroy (mort_blob);
1244       return NULL;
1245     }
1246   }
1247   hb_blob_destroy (mort_blob);
1248 
1249   return hb_coretext_shaper_face_data_ensure (face) ? (hb_coretext_aat_shaper_face_data_t *) HB_SHAPER_DATA_SUCCEEDED : NULL;
1250 }
1251 
1252 void
_hb_coretext_aat_shaper_face_data_destroy(hb_coretext_aat_shaper_face_data_t * data HB_UNUSED)1253 _hb_coretext_aat_shaper_face_data_destroy (hb_coretext_aat_shaper_face_data_t *data HB_UNUSED)
1254 {
1255 }
1256 
1257 
1258 /*
1259  * shaper font data
1260  */
1261 
1262 struct hb_coretext_aat_shaper_font_data_t {};
1263 
1264 hb_coretext_aat_shaper_font_data_t *
_hb_coretext_aat_shaper_font_data_create(hb_font_t * font)1265 _hb_coretext_aat_shaper_font_data_create (hb_font_t *font)
1266 {
1267   return hb_coretext_shaper_font_data_ensure (font) ? (hb_coretext_aat_shaper_font_data_t *) HB_SHAPER_DATA_SUCCEEDED : NULL;
1268 }
1269 
1270 void
_hb_coretext_aat_shaper_font_data_destroy(hb_coretext_aat_shaper_font_data_t * data HB_UNUSED)1271 _hb_coretext_aat_shaper_font_data_destroy (hb_coretext_aat_shaper_font_data_t *data HB_UNUSED)
1272 {
1273 }
1274 
1275 
1276 /*
1277  * shaper shape_plan data
1278  */
1279 
1280 struct hb_coretext_aat_shaper_shape_plan_data_t {};
1281 
1282 hb_coretext_aat_shaper_shape_plan_data_t *
_hb_coretext_aat_shaper_shape_plan_data_create(hb_shape_plan_t * shape_plan HB_UNUSED,const hb_feature_t * user_features HB_UNUSED,unsigned int num_user_features HB_UNUSED,const int * coords HB_UNUSED,unsigned int num_coords HB_UNUSED)1283 _hb_coretext_aat_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
1284 					     const hb_feature_t *user_features HB_UNUSED,
1285 					     unsigned int        num_user_features HB_UNUSED,
1286 					     const int          *coords HB_UNUSED,
1287 					     unsigned int        num_coords HB_UNUSED)
1288 {
1289   return (hb_coretext_aat_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
1290 }
1291 
1292 void
_hb_coretext_aat_shaper_shape_plan_data_destroy(hb_coretext_aat_shaper_shape_plan_data_t * data HB_UNUSED)1293 _hb_coretext_aat_shaper_shape_plan_data_destroy (hb_coretext_aat_shaper_shape_plan_data_t *data HB_UNUSED)
1294 {
1295 }
1296 
1297 
1298 /*
1299  * shaper
1300  */
1301 
1302 hb_bool_t
_hb_coretext_aat_shape(hb_shape_plan_t * shape_plan,hb_font_t * font,hb_buffer_t * buffer,const hb_feature_t * features,unsigned int num_features)1303 _hb_coretext_aat_shape (hb_shape_plan_t    *shape_plan,
1304 			hb_font_t          *font,
1305 			hb_buffer_t        *buffer,
1306 			const hb_feature_t *features,
1307 			unsigned int        num_features)
1308 {
1309   return _hb_coretext_shape (shape_plan, font, buffer, features, num_features);
1310 }
1311