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