Imported Upstream version 1.8.1
[platform/upstream/harfbuzz.git] / src / hb-uniscribe.cc
1 /*
2  * Copyright © 2011,2012,2013  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Behdad Esfahbod
25  */
26
27 #include "hb-private.hh"
28 #include "hb-debug.hh"
29 #define HB_SHAPER uniscribe
30 #include "hb-shaper-impl-private.hh"
31
32 #include <windows.h>
33 #include <usp10.h>
34 #include <rpc.h>
35
36 #include "hb-uniscribe.h"
37
38 #include "hb-open-file-private.hh"
39 #include "hb-ot-name-table.hh"
40 #include "hb-ot-tag.h"
41
42
43 static inline uint16_t hb_uint16_swap (const uint16_t v)
44 { return (v >> 8) | (v << 8); }
45 static inline uint32_t hb_uint32_swap (const uint32_t v)
46 { return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); }
47
48
49 typedef HRESULT (WINAPI *SIOT) /*ScriptItemizeOpenType*/(
50   const WCHAR *pwcInChars,
51   int cInChars,
52   int cMaxItems,
53   const SCRIPT_CONTROL *psControl,
54   const SCRIPT_STATE *psState,
55   SCRIPT_ITEM *pItems,
56   OPENTYPE_TAG *pScriptTags,
57   int *pcItems
58 );
59
60 typedef HRESULT (WINAPI *SSOT) /*ScriptShapeOpenType*/(
61   HDC hdc,
62   SCRIPT_CACHE *psc,
63   SCRIPT_ANALYSIS *psa,
64   OPENTYPE_TAG tagScript,
65   OPENTYPE_TAG tagLangSys,
66   int *rcRangeChars,
67   TEXTRANGE_PROPERTIES **rpRangeProperties,
68   int cRanges,
69   const WCHAR *pwcChars,
70   int cChars,
71   int cMaxGlyphs,
72   WORD *pwLogClust,
73   SCRIPT_CHARPROP *pCharProps,
74   WORD *pwOutGlyphs,
75   SCRIPT_GLYPHPROP *pOutGlyphProps,
76   int *pcGlyphs
77 );
78
79 typedef HRESULT (WINAPI *SPOT) /*ScriptPlaceOpenType*/(
80   HDC hdc,
81   SCRIPT_CACHE *psc,
82   SCRIPT_ANALYSIS *psa,
83   OPENTYPE_TAG tagScript,
84   OPENTYPE_TAG tagLangSys,
85   int *rcRangeChars,
86   TEXTRANGE_PROPERTIES **rpRangeProperties,
87   int cRanges,
88   const WCHAR *pwcChars,
89   WORD *pwLogClust,
90   SCRIPT_CHARPROP *pCharProps,
91   int cChars,
92   const WORD *pwGlyphs,
93   const SCRIPT_GLYPHPROP *pGlyphProps,
94   int cGlyphs,
95   int *piAdvance,
96   GOFFSET *pGoffset,
97   ABC *pABC
98 );
99
100
101 /* Fallback implementations. */
102
103 static HRESULT WINAPI
104 hb_ScriptItemizeOpenType(
105   const WCHAR *pwcInChars,
106   int cInChars,
107   int cMaxItems,
108   const SCRIPT_CONTROL *psControl,
109   const SCRIPT_STATE *psState,
110   SCRIPT_ITEM *pItems,
111   OPENTYPE_TAG *pScriptTags,
112   int *pcItems
113 )
114 {
115 {
116   return ScriptItemize (pwcInChars,
117                         cInChars,
118                         cMaxItems,
119                         psControl,
120                         psState,
121                         pItems,
122                         pcItems);
123 }
124 }
125
126 static HRESULT WINAPI
127 hb_ScriptShapeOpenType(
128   HDC hdc,
129   SCRIPT_CACHE *psc,
130   SCRIPT_ANALYSIS *psa,
131   OPENTYPE_TAG tagScript,
132   OPENTYPE_TAG tagLangSys,
133   int *rcRangeChars,
134   TEXTRANGE_PROPERTIES **rpRangeProperties,
135   int cRanges,
136   const WCHAR *pwcChars,
137   int cChars,
138   int cMaxGlyphs,
139   WORD *pwLogClust,
140   SCRIPT_CHARPROP *pCharProps,
141   WORD *pwOutGlyphs,
142   SCRIPT_GLYPHPROP *pOutGlyphProps,
143   int *pcGlyphs
144 )
145 {
146   SCRIPT_VISATTR *psva = (SCRIPT_VISATTR *) pOutGlyphProps;
147   return ScriptShape (hdc,
148                       psc,
149                       pwcChars,
150                       cChars,
151                       cMaxGlyphs,
152                       psa,
153                       pwOutGlyphs,
154                       pwLogClust,
155                       psva,
156                       pcGlyphs);
157 }
158
159 static HRESULT WINAPI
160 hb_ScriptPlaceOpenType(
161   HDC hdc,
162   SCRIPT_CACHE *psc,
163   SCRIPT_ANALYSIS *psa,
164   OPENTYPE_TAG tagScript,
165   OPENTYPE_TAG tagLangSys,
166   int *rcRangeChars,
167   TEXTRANGE_PROPERTIES **rpRangeProperties,
168   int cRanges,
169   const WCHAR *pwcChars,
170   WORD *pwLogClust,
171   SCRIPT_CHARPROP *pCharProps,
172   int cChars,
173   const WORD *pwGlyphs,
174   const SCRIPT_GLYPHPROP *pGlyphProps,
175   int cGlyphs,
176   int *piAdvance,
177   GOFFSET *pGoffset,
178   ABC *pABC
179 )
180 {
181   SCRIPT_VISATTR *psva = (SCRIPT_VISATTR *) pGlyphProps;
182   return ScriptPlace (hdc,
183                       psc,
184                       pwGlyphs,
185                       cGlyphs,
186                       psva,
187                       psa,
188                       piAdvance,
189                       pGoffset,
190                       pABC);
191 }
192
193
194 struct hb_uniscribe_shaper_funcs_t {
195   SIOT ScriptItemizeOpenType;
196   SSOT ScriptShapeOpenType;
197   SPOT ScriptPlaceOpenType;
198
199   inline void init (void)
200   {
201     HMODULE hinstLib;
202     this->ScriptItemizeOpenType = nullptr;
203     this->ScriptShapeOpenType   = nullptr;
204     this->ScriptPlaceOpenType   = nullptr;
205
206     hinstLib = GetModuleHandle (TEXT ("usp10.dll"));
207     if (hinstLib)
208     {
209       this->ScriptItemizeOpenType = (SIOT) GetProcAddress (hinstLib, "ScriptItemizeOpenType");
210       this->ScriptShapeOpenType   = (SSOT) GetProcAddress (hinstLib, "ScriptShapeOpenType");
211       this->ScriptPlaceOpenType   = (SPOT) GetProcAddress (hinstLib, "ScriptPlaceOpenType");
212     }
213     if (!this->ScriptItemizeOpenType ||
214         !this->ScriptShapeOpenType   ||
215         !this->ScriptPlaceOpenType)
216     {
217       DEBUG_MSG (UNISCRIBE, nullptr, "OpenType versions of functions not found; falling back.");
218       this->ScriptItemizeOpenType = hb_ScriptItemizeOpenType;
219       this->ScriptShapeOpenType   = hb_ScriptShapeOpenType;
220       this->ScriptPlaceOpenType   = hb_ScriptPlaceOpenType;
221     }
222   }
223 };
224 static hb_uniscribe_shaper_funcs_t *uniscribe_funcs;
225
226 #ifdef HB_USE_ATEXIT
227 static inline void
228 free_uniscribe_funcs (void)
229 {
230 retry:
231   hb_uniscribe_shaper_funcs_t *local_uniscribe_funcs =
232     (hb_uniscribe_shaper_funcs_t *) hb_atomic_ptr_get (&uniscribe_funcs);
233   if (!hb_atomic_ptr_cmpexch (&uniscribe_funcs, local_uniscribe_funcs, nullptr))
234     goto retry;
235
236   free (uniscribe_funcs);
237 }
238 #endif
239
240 static hb_uniscribe_shaper_funcs_t *
241 hb_uniscribe_shaper_get_funcs (void)
242 {
243 retry:
244   hb_uniscribe_shaper_funcs_t *funcs = (hb_uniscribe_shaper_funcs_t *) hb_atomic_ptr_get (&uniscribe_funcs);
245
246   if (unlikely (!funcs))
247   {
248     funcs = (hb_uniscribe_shaper_funcs_t *) calloc (1, sizeof (hb_uniscribe_shaper_funcs_t));
249     if (unlikely (!funcs))
250       return nullptr;
251
252     funcs->init ();
253
254     if (!hb_atomic_ptr_cmpexch (&uniscribe_funcs, nullptr, funcs)) {
255       free (funcs);
256       goto retry;
257     }
258
259 #ifdef HB_USE_ATEXIT
260     atexit (free_uniscribe_funcs); /* First person registers atexit() callback. */
261 #endif
262   }
263
264   return funcs;
265 }
266
267
268 struct active_feature_t {
269   OPENTYPE_FEATURE_RECORD rec;
270   unsigned int order;
271
272   static int cmp (const void *pa, const void *pb) {
273     const active_feature_t *a = (const active_feature_t *) pa;
274     const active_feature_t *b = (const active_feature_t *) pb;
275     return a->rec.tagFeature < b->rec.tagFeature ? -1 : a->rec.tagFeature > b->rec.tagFeature ? 1 :
276            a->order < b->order ? -1 : a->order > b->order ? 1 :
277            a->rec.lParameter < b->rec.lParameter ? -1 : a->rec.lParameter > b->rec.lParameter ? 1 :
278            0;
279   }
280   bool operator== (const active_feature_t *f) {
281     return cmp (this, f) == 0;
282   }
283 };
284
285 struct feature_event_t {
286   unsigned int index;
287   bool start;
288   active_feature_t feature;
289
290   static int cmp (const void *pa, const void *pb) {
291     const feature_event_t *a = (const feature_event_t *) pa;
292     const feature_event_t *b = (const feature_event_t *) pb;
293     return a->index < b->index ? -1 : a->index > b->index ? 1 :
294            a->start < b->start ? -1 : a->start > b->start ? 1 :
295            active_feature_t::cmp (&a->feature, &b->feature);
296   }
297 };
298
299 struct range_record_t {
300   TEXTRANGE_PROPERTIES props;
301   unsigned int index_first; /* == start */
302   unsigned int index_last;  /* == end - 1 */
303 };
304
305 HB_SHAPER_DATA_ENSURE_DEFINE(uniscribe, face)
306 HB_SHAPER_DATA_ENSURE_DEFINE(uniscribe, font)
307
308
309 /*
310  * shaper face data
311  */
312
313 struct hb_uniscribe_shaper_face_data_t {
314   HANDLE fh;
315   hb_uniscribe_shaper_funcs_t *funcs;
316   wchar_t face_name[LF_FACESIZE];
317 };
318
319 /* face_name should point to a wchar_t[LF_FACESIZE] object. */
320 static void
321 _hb_generate_unique_face_name (wchar_t *face_name, unsigned int *plen)
322 {
323   /* We'll create a private name for the font from a UUID using a simple,
324    * somewhat base64-like encoding scheme */
325   const char *enc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-";
326   UUID id;
327   UuidCreate ((UUID*) &id);
328   static_assert ((2 + 3 * (16/2) < LF_FACESIZE), "");
329   unsigned int name_str_len = 0;
330   face_name[name_str_len++] = 'F';
331   face_name[name_str_len++] = '_';
332   unsigned char *p = (unsigned char *) &id;
333   for (unsigned int i = 0; i < 16; i += 2)
334   {
335     /* Spread the 16 bits from two bytes of the UUID across three chars of face_name,
336      * using the bits in groups of 5,5,6 to select chars from enc.
337      * This will generate 24 characters; with the 'F_' prefix we already provided,
338      * the name will be 26 chars (plus the NUL terminator), so will always fit within
339      * face_name (LF_FACESIZE = 32). */
340     face_name[name_str_len++] = enc[p[i] >> 3];
341     face_name[name_str_len++] = enc[((p[i] << 2) | (p[i + 1] >> 6)) & 0x1f];
342     face_name[name_str_len++] = enc[p[i + 1] & 0x3f];
343   }
344   face_name[name_str_len] = 0;
345   if (plen)
346     *plen = name_str_len;
347 }
348
349 /* Destroys blob. */
350 static hb_blob_t *
351 _hb_rename_font (hb_blob_t *blob, wchar_t *new_name)
352 {
353   /* Create a copy of the font data, with the 'name' table replaced by a
354    * table that names the font with our private F_* name created above.
355    * For simplicity, we just append a new 'name' table and update the
356    * sfnt directory; the original table is left in place, but unused.
357    *
358    * The new table will contain just 5 name IDs: family, style, unique,
359    * full, PS. All of them point to the same name data with our unique name.
360    */
361
362   blob = OT::Sanitizer<OT::OpenTypeFontFile>().sanitize (blob);
363
364   unsigned int length, new_length, name_str_len;
365   const char *orig_sfnt_data = hb_blob_get_data (blob, &length);
366
367   _hb_generate_unique_face_name (new_name, &name_str_len);
368
369   static const uint16_t name_IDs[] = { 1, 2, 3, 4, 6 };
370
371   unsigned int name_table_length = OT::name::min_size +
372                                    ARRAY_LENGTH (name_IDs) * OT::NameRecord::static_size +
373                                    name_str_len * 2; /* for name data in UTF16BE form */
374   unsigned int padded_name_table_length = ((name_table_length + 3) & ~3);
375   unsigned int name_table_offset = (length + 3) & ~3;
376
377   new_length = name_table_offset + padded_name_table_length;
378   void *new_sfnt_data = calloc (1, new_length);
379   if (!new_sfnt_data)
380   {
381     hb_blob_destroy (blob);
382     return nullptr;
383   }
384
385   memcpy(new_sfnt_data, orig_sfnt_data, length);
386
387   OT::name &name = OT::StructAtOffset<OT::name> (new_sfnt_data, name_table_offset);
388   name.format.set (0);
389   name.count.set (ARRAY_LENGTH (name_IDs));
390   name.stringOffset.set (name.get_size ());
391   for (unsigned int i = 0; i < ARRAY_LENGTH (name_IDs); i++)
392   {
393     OT::NameRecord &record = name.nameRecord[i];
394     record.platformID.set (3);
395     record.encodingID.set (1);
396     record.languageID.set (0x0409u); /* English */
397     record.nameID.set (name_IDs[i]);
398     record.length.set (name_str_len * 2);
399     record.offset.set (0);
400   }
401
402   /* Copy string data from new_name, converting wchar_t to UTF16BE. */
403   unsigned char *p = &OT::StructAfter<unsigned char> (name);
404   for (unsigned int i = 0; i < name_str_len; i++)
405   {
406     *p++ = new_name[i] >> 8;
407     *p++ = new_name[i] & 0xff;
408   }
409
410   /* Adjust name table entry to point to new name table */
411   const OT::OpenTypeFontFile &file = * (OT::OpenTypeFontFile *) (new_sfnt_data);
412   unsigned int face_count = file.get_face_count ();
413   for (unsigned int face_index = 0; face_index < face_count; face_index++)
414   {
415     /* Note: doing multiple edits (ie. TTC) can be unsafe.  There may be
416      * toe-stepping.  But we don't really care. */
417     const OT::OpenTypeFontFace &face = file.get_face (face_index);
418     unsigned int index;
419     if (face.find_table_index (HB_OT_TAG_name, &index))
420     {
421       OT::TableRecord &record = const_cast<OT::TableRecord &> (face.get_table (index));
422       record.checkSum.set_for_data (&name, padded_name_table_length);
423       record.offset.set (name_table_offset);
424       record.length.set (name_table_length);
425     }
426     else if (face_index == 0) /* Fail if first face doesn't have 'name' table. */
427     {
428       free (new_sfnt_data);
429       hb_blob_destroy (blob);
430       return nullptr;
431     }
432   }
433
434   /* The checkSumAdjustment field in the 'head' table is now wrong,
435    * but that doesn't actually seem to cause any problems so we don't
436    * bother. */
437
438   hb_blob_destroy (blob);
439   return hb_blob_create ((const char *) new_sfnt_data, new_length,
440                          HB_MEMORY_MODE_WRITABLE, nullptr, free);
441 }
442
443 hb_uniscribe_shaper_face_data_t *
444 _hb_uniscribe_shaper_face_data_create (hb_face_t *face)
445 {
446   hb_uniscribe_shaper_face_data_t *data = (hb_uniscribe_shaper_face_data_t *) calloc (1, sizeof (hb_uniscribe_shaper_face_data_t));
447   if (unlikely (!data))
448     return nullptr;
449
450   data->funcs = hb_uniscribe_shaper_get_funcs ();
451   if (unlikely (!data->funcs))
452   {
453     free (data);
454     return nullptr;
455   }
456
457   hb_blob_t *blob = hb_face_reference_blob (face);
458   if (unlikely (!hb_blob_get_length (blob)))
459     DEBUG_MSG (UNISCRIBE, face, "Face has empty blob");
460
461   blob = _hb_rename_font (blob, data->face_name);
462   if (unlikely (!blob))
463   {
464     free (data);
465     return nullptr;
466   }
467
468   DWORD num_fonts_installed;
469   data->fh = AddFontMemResourceEx ((void *) hb_blob_get_data (blob, nullptr),
470                                    hb_blob_get_length (blob),
471                                    0, &num_fonts_installed);
472   if (unlikely (!data->fh))
473   {
474     DEBUG_MSG (UNISCRIBE, face, "Face AddFontMemResourceEx() failed");
475     free (data);
476     return nullptr;
477   }
478
479   return data;
480 }
481
482 void
483 _hb_uniscribe_shaper_face_data_destroy (hb_uniscribe_shaper_face_data_t *data)
484 {
485   RemoveFontMemResourceEx (data->fh);
486   free (data);
487 }
488
489
490 /*
491  * shaper font data
492  */
493
494 struct hb_uniscribe_shaper_font_data_t {
495   HDC hdc;
496   LOGFONTW log_font;
497   HFONT hfont;
498   SCRIPT_CACHE script_cache;
499   double x_mult, y_mult; /* From LOGFONT space to HB space. */
500 };
501
502 static bool
503 populate_log_font (LOGFONTW  *lf,
504                    hb_font_t *font,
505                    unsigned int font_size)
506 {
507   memset (lf, 0, sizeof (*lf));
508   lf->lfHeight = - (int) font_size;
509   lf->lfCharSet = DEFAULT_CHARSET;
510
511   hb_face_t *face = font->face;
512   hb_uniscribe_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
513
514   memcpy (lf->lfFaceName, face_data->face_name, sizeof (lf->lfFaceName));
515
516   return true;
517 }
518
519 hb_uniscribe_shaper_font_data_t *
520 _hb_uniscribe_shaper_font_data_create (hb_font_t *font)
521 {
522   if (unlikely (!hb_uniscribe_shaper_face_data_ensure (font->face))) return nullptr;
523
524   hb_uniscribe_shaper_font_data_t *data = (hb_uniscribe_shaper_font_data_t *) calloc (1, sizeof (hb_uniscribe_shaper_font_data_t));
525   if (unlikely (!data))
526     return nullptr;
527
528   int font_size = font->face->get_upem (); /* Default... */
529   /* No idea if the following is even a good idea. */
530   if (font->y_ppem)
531     font_size = font->y_ppem;
532
533   if (font_size < 0)
534     font_size = -font_size;
535   data->x_mult = (double) font->x_scale / font_size;
536   data->y_mult = (double) font->y_scale / font_size;
537
538   data->hdc = GetDC (nullptr);
539
540   if (unlikely (!populate_log_font (&data->log_font, font, font_size))) {
541     DEBUG_MSG (UNISCRIBE, font, "Font populate_log_font() failed");
542     _hb_uniscribe_shaper_font_data_destroy (data);
543     return nullptr;
544   }
545
546   data->hfont = CreateFontIndirectW (&data->log_font);
547   if (unlikely (!data->hfont)) {
548     DEBUG_MSG (UNISCRIBE, font, "Font CreateFontIndirectW() failed");
549     _hb_uniscribe_shaper_font_data_destroy (data);
550      return nullptr;
551   }
552
553   if (!SelectObject (data->hdc, data->hfont)) {
554     DEBUG_MSG (UNISCRIBE, font, "Font SelectObject() failed");
555     _hb_uniscribe_shaper_font_data_destroy (data);
556      return nullptr;
557   }
558
559   return data;
560 }
561
562 void
563 _hb_uniscribe_shaper_font_data_destroy (hb_uniscribe_shaper_font_data_t *data)
564 {
565   if (data->hdc)
566     ReleaseDC (nullptr, data->hdc);
567   if (data->hfont)
568     DeleteObject (data->hfont);
569   if (data->script_cache)
570     ScriptFreeCache (&data->script_cache);
571   free (data);
572 }
573
574 LOGFONTW *
575 hb_uniscribe_font_get_logfontw (hb_font_t *font)
576 {
577   if (unlikely (!hb_uniscribe_shaper_font_data_ensure (font))) return nullptr;
578   hb_uniscribe_shaper_font_data_t *font_data =  HB_SHAPER_DATA_GET (font);
579   return &font_data->log_font;
580 }
581
582 HFONT
583 hb_uniscribe_font_get_hfont (hb_font_t *font)
584 {
585   if (unlikely (!hb_uniscribe_shaper_font_data_ensure (font))) return nullptr;
586   hb_uniscribe_shaper_font_data_t *font_data =  HB_SHAPER_DATA_GET (font);
587   return font_data->hfont;
588 }
589
590
591 /*
592  * shaper shape_plan data
593  */
594
595 struct hb_uniscribe_shaper_shape_plan_data_t {};
596
597 hb_uniscribe_shaper_shape_plan_data_t *
598 _hb_uniscribe_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
599                                              const hb_feature_t *user_features HB_UNUSED,
600                                              unsigned int        num_user_features HB_UNUSED,
601                                              const int          *coords HB_UNUSED,
602                                              unsigned int        num_coords HB_UNUSED)
603 {
604   return (hb_uniscribe_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
605 }
606
607 void
608 _hb_uniscribe_shaper_shape_plan_data_destroy (hb_uniscribe_shaper_shape_plan_data_t *data HB_UNUSED)
609 {
610 }
611
612
613 /*
614  * shaper
615  */
616
617
618 hb_bool_t
619 _hb_uniscribe_shape (hb_shape_plan_t    *shape_plan,
620                      hb_font_t          *font,
621                      hb_buffer_t        *buffer,
622                      const hb_feature_t *features,
623                      unsigned int        num_features)
624 {
625   hb_face_t *face = font->face;
626   hb_uniscribe_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
627   hb_uniscribe_shaper_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
628   hb_uniscribe_shaper_funcs_t *funcs = face_data->funcs;
629
630   /*
631    * Set up features.
632    */
633   hb_auto_t<hb_vector_t<OPENTYPE_FEATURE_RECORD> > feature_records;
634   hb_auto_t<hb_vector_t<range_record_t> > range_records;
635   if (num_features)
636   {
637     /* Sort features by start/end events. */
638     hb_auto_t<hb_vector_t<feature_event_t> > feature_events;
639     for (unsigned int i = 0; i < num_features; i++)
640     {
641       active_feature_t feature;
642       feature.rec.tagFeature = hb_uint32_swap (features[i].tag);
643       feature.rec.lParameter = features[i].value;
644       feature.order = i;
645
646       feature_event_t *event;
647
648       event = feature_events.push ();
649       event->index = features[i].start;
650       event->start = true;
651       event->feature = feature;
652
653       event = feature_events.push ();
654       event->index = features[i].end;
655       event->start = false;
656       event->feature = feature;
657     }
658     feature_events.qsort ();
659     /* Add a strategic final event. */
660     {
661       active_feature_t feature;
662       feature.rec.tagFeature = 0;
663       feature.rec.lParameter = 0;
664       feature.order = num_features + 1;
665
666       feature_event_t *event = feature_events.push ();
667       event->index = 0; /* This value does magic. */
668       event->start = false;
669       event->feature = feature;
670     }
671
672     /* Scan events and save features for each range. */
673     hb_auto_t<hb_vector_t<active_feature_t> > active_features;
674     unsigned int last_index = 0;
675     for (unsigned int i = 0; i < feature_events.len; i++)
676     {
677       feature_event_t *event = &feature_events[i];
678
679       if (event->index != last_index)
680       {
681         /* Save a snapshot of active features and the range. */
682         range_record_t *range = range_records.push ();
683
684         unsigned int offset = feature_records.len;
685
686         active_features.qsort ();
687         for (unsigned int j = 0; j < active_features.len; j++)
688         {
689           if (!j || active_features[j].rec.tagFeature != feature_records[feature_records.len - 1].tagFeature)
690           {
691             feature_records.push (active_features[j].rec);
692           }
693           else
694           {
695             /* Overrides value for existing feature. */
696             feature_records[feature_records.len - 1].lParameter = active_features[j].rec.lParameter;
697           }
698         }
699
700         /* Will convert to pointer after all is ready, since feature_records.array
701          * may move as we grow it. */
702         range->props.potfRecords = reinterpret_cast<OPENTYPE_FEATURE_RECORD *> (offset);
703         range->props.cotfRecords = feature_records.len - offset;
704         range->index_first = last_index;
705         range->index_last  = event->index - 1;
706
707         last_index = event->index;
708       }
709
710       if (event->start)
711       {
712         active_features.push (event->feature);
713       }
714       else
715       {
716         active_feature_t *feature = active_features.find (&event->feature);
717         if (feature)
718           active_features.remove (feature - active_features.arrayZ);
719       }
720     }
721
722     if (!range_records.len) /* No active feature found. */
723       num_features = 0;
724
725     /* Fixup the pointers. */
726     for (unsigned int i = 0; i < range_records.len; i++)
727     {
728       range_record_t *range = &range_records[i];
729       range->props.potfRecords = feature_records.arrayZ + reinterpret_cast<uintptr_t> (range->props.potfRecords);
730     }
731   }
732
733 #define FAIL(...) \
734   HB_STMT_START { \
735     DEBUG_MSG (UNISCRIBE, nullptr, __VA_ARGS__); \
736     return false; \
737   } HB_STMT_END;
738
739   HRESULT hr;
740
741 retry:
742
743   unsigned int scratch_size;
744   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
745
746 #define ALLOCATE_ARRAY(Type, name, len) \
747   Type *name = (Type *) scratch; \
748   { \
749     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
750     assert (_consumed <= scratch_size); \
751     scratch += _consumed; \
752     scratch_size -= _consumed; \
753   }
754
755 #define utf16_index() var1.u32
756
757   ALLOCATE_ARRAY (WCHAR, pchars, buffer->len * 2);
758
759   unsigned int chars_len = 0;
760   for (unsigned int i = 0; i < buffer->len; i++)
761   {
762     hb_codepoint_t c = buffer->info[i].codepoint;
763     buffer->info[i].utf16_index() = chars_len;
764     if (likely (c <= 0xFFFFu))
765       pchars[chars_len++] = c;
766     else if (unlikely (c > 0x10FFFFu))
767       pchars[chars_len++] = 0xFFFDu;
768     else {
769       pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
770       pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
771     }
772   }
773
774   ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
775   ALLOCATE_ARRAY (SCRIPT_CHARPROP, char_props, chars_len);
776
777   if (num_features)
778   {
779     /* Need log_clusters to assign features. */
780     chars_len = 0;
781     for (unsigned int i = 0; i < buffer->len; i++)
782     {
783       hb_codepoint_t c = buffer->info[i].codepoint;
784       unsigned int cluster = buffer->info[i].cluster;
785       log_clusters[chars_len++] = cluster;
786       if (hb_in_range (c, 0x10000u, 0x10FFFFu))
787         log_clusters[chars_len++] = cluster; /* Surrogates. */
788     }
789   }
790
791   /* The -2 in the following is to compensate for possible
792    * alignment needed after the WORD array.  sizeof(WORD) == 2. */
793   unsigned int glyphs_size = (scratch_size * sizeof (int) - 2)
794                            / (sizeof (WORD) +
795                               sizeof (SCRIPT_GLYPHPROP) +
796                               sizeof (int) +
797                               sizeof (GOFFSET) +
798                               sizeof (uint32_t));
799
800   ALLOCATE_ARRAY (WORD, glyphs, glyphs_size);
801   ALLOCATE_ARRAY (SCRIPT_GLYPHPROP, glyph_props, glyphs_size);
802   ALLOCATE_ARRAY (int, advances, glyphs_size);
803   ALLOCATE_ARRAY (GOFFSET, offsets, glyphs_size);
804   ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
805
806   /* Note:
807    * We can't touch the contents of glyph_props.  Our fallback
808    * implementations of Shape and Place functions use that buffer
809    * by casting it to a different type.  It works because they
810    * both agree about it, but if we want to access it here we
811    * need address that issue first.
812    */
813
814 #undef ALLOCATE_ARRAY
815
816 #define MAX_ITEMS 256
817
818   SCRIPT_ITEM items[MAX_ITEMS + 1];
819   SCRIPT_CONTROL bidi_control = {0};
820   SCRIPT_STATE bidi_state = {0};
821   ULONG script_tags[MAX_ITEMS];
822   int item_count;
823
824   /* MinGW32 doesn't define fMergeNeutralItems, so we bruteforce */
825   //bidi_control.fMergeNeutralItems = true;
826   *(uint32_t*)&bidi_control |= 1u<<24;
827
828   bidi_state.uBidiLevel = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
829   bidi_state.fOverrideDirection = 1;
830
831   hr = funcs->ScriptItemizeOpenType (pchars,
832                                      chars_len,
833                                      MAX_ITEMS,
834                                      &bidi_control,
835                                      &bidi_state,
836                                      items,
837                                      script_tags,
838                                      &item_count);
839   if (unlikely (FAILED (hr)))
840     FAIL ("ScriptItemizeOpenType() failed: 0x%08xL", hr);
841
842 #undef MAX_ITEMS
843
844   OPENTYPE_TAG language_tag = hb_uint32_swap (hb_ot_tag_from_language (buffer->props.language));
845   hb_auto_t<hb_vector_t<TEXTRANGE_PROPERTIES*> > range_properties;
846   hb_auto_t<hb_vector_t<int> > range_char_counts;
847
848   unsigned int glyphs_offset = 0;
849   unsigned int glyphs_len;
850   bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
851   for (int i = 0; i < item_count; i++)
852   {
853     unsigned int chars_offset = items[i].iCharPos;
854     unsigned int item_chars_len = items[i + 1].iCharPos - chars_offset;
855
856     if (num_features)
857     {
858       range_properties.shrink (0);
859       range_char_counts.shrink (0);
860
861       range_record_t *last_range = &range_records[0];
862
863       for (unsigned int k = chars_offset; k < chars_offset + item_chars_len; k++)
864       {
865         range_record_t *range = last_range;
866         while (log_clusters[k] < range->index_first)
867           range--;
868         while (log_clusters[k] > range->index_last)
869           range++;
870         if (!range_properties.len ||
871             &range->props != range_properties[range_properties.len - 1])
872         {
873           TEXTRANGE_PROPERTIES **props = range_properties.push ();
874           int *c = range_char_counts.push ();
875           if (unlikely (!props || !c))
876           {
877             range_properties.shrink (0);
878             range_char_counts.shrink (0);
879             break;
880           }
881           *props = &range->props;
882           *c = 1;
883         }
884         else
885         {
886           range_char_counts[range_char_counts.len - 1]++;
887         }
888
889         last_range = range;
890       }
891     }
892
893     /* Asking for glyphs in logical order circumvents at least
894      * one bug in Uniscribe. */
895     items[i].a.fLogicalOrder = true;
896
897   retry_shape:
898     hr = funcs->ScriptShapeOpenType (font_data->hdc,
899                                      &font_data->script_cache,
900                                      &items[i].a,
901                                      script_tags[i],
902                                      language_tag,
903                                      range_char_counts.arrayZ,
904                                      range_properties.arrayZ,
905                                      range_properties.len,
906                                      pchars + chars_offset,
907                                      item_chars_len,
908                                      glyphs_size - glyphs_offset,
909                                      /* out */
910                                      log_clusters + chars_offset,
911                                      char_props + chars_offset,
912                                      glyphs + glyphs_offset,
913                                      glyph_props + glyphs_offset,
914                                      (int *) &glyphs_len);
915
916     if (unlikely (items[i].a.fNoGlyphIndex))
917       FAIL ("ScriptShapeOpenType() set fNoGlyphIndex");
918     if (unlikely (hr == E_OUTOFMEMORY || hr == E_NOT_SUFFICIENT_BUFFER))
919     {
920       if (unlikely (!buffer->ensure (buffer->allocated * 2)))
921         FAIL ("Buffer resize failed");
922       goto retry;
923     }
924     if (unlikely (hr == USP_E_SCRIPT_NOT_IN_FONT))
925     {
926       if (items[i].a.eScript == SCRIPT_UNDEFINED)
927         FAIL ("ScriptShapeOpenType() failed: Font doesn't support script");
928       items[i].a.eScript = SCRIPT_UNDEFINED;
929       goto retry_shape;
930     }
931     if (unlikely (FAILED (hr)))
932     {
933       FAIL ("ScriptShapeOpenType() failed: 0x%08xL", hr);
934     }
935
936     for (unsigned int j = chars_offset; j < chars_offset + item_chars_len; j++)
937       log_clusters[j] += glyphs_offset;
938
939     hr = funcs->ScriptPlaceOpenType (font_data->hdc,
940                                      &font_data->script_cache,
941                                      &items[i].a,
942                                      script_tags[i],
943                                      language_tag,
944                                      range_char_counts.arrayZ,
945                                      range_properties.arrayZ,
946                                      range_properties.len,
947                                      pchars + chars_offset,
948                                      log_clusters + chars_offset,
949                                      char_props + chars_offset,
950                                      item_chars_len,
951                                      glyphs + glyphs_offset,
952                                      glyph_props + glyphs_offset,
953                                      glyphs_len,
954                                      /* out */
955                                      advances + glyphs_offset,
956                                      offsets + glyphs_offset,
957                                      nullptr);
958     if (unlikely (FAILED (hr)))
959       FAIL ("ScriptPlaceOpenType() failed: 0x%08xL", hr);
960
961     if (DEBUG_ENABLED (UNISCRIBE))
962       fprintf (stderr, "Item %d RTL %d LayoutRTL %d LogicalOrder %d ScriptTag %c%c%c%c\n",
963                i,
964                items[i].a.fRTL,
965                items[i].a.fLayoutRTL,
966                items[i].a.fLogicalOrder,
967                HB_UNTAG (hb_uint32_swap (script_tags[i])));
968
969     glyphs_offset += glyphs_len;
970   }
971   glyphs_len = glyphs_offset;
972
973   /* Ok, we've got everything we need, now compose output buffer,
974    * very, *very*, carefully! */
975
976   /* Calculate visual-clusters.  That's what we ship. */
977   for (unsigned int i = 0; i < glyphs_len; i++)
978     vis_clusters[i] = -1;
979   for (unsigned int i = 0; i < buffer->len; i++) {
980     uint32_t *p = &vis_clusters[log_clusters[buffer->info[i].utf16_index()]];
981     *p = MIN (*p, buffer->info[i].cluster);
982   }
983   for (unsigned int i = 1; i < glyphs_len; i++)
984     if (vis_clusters[i] == -1)
985       vis_clusters[i] = vis_clusters[i - 1];
986
987 #undef utf16_index
988
989   if (unlikely (!buffer->ensure (glyphs_len)))
990     FAIL ("Buffer in error");
991
992 #undef FAIL
993
994   /* Set glyph infos */
995   buffer->len = 0;
996   for (unsigned int i = 0; i < glyphs_len; i++)
997   {
998     hb_glyph_info_t *info = &buffer->info[buffer->len++];
999
1000     info->codepoint = glyphs[i];
1001     info->cluster = vis_clusters[i];
1002
1003     /* The rest is crap.  Let's store position info there for now. */
1004     info->mask = advances[i];
1005     info->var1.i32 = offsets[i].du;
1006     info->var2.i32 = offsets[i].dv;
1007   }
1008
1009   /* Set glyph positions */
1010   buffer->clear_positions ();
1011   double x_mult = font_data->x_mult, y_mult = font_data->y_mult;
1012   for (unsigned int i = 0; i < glyphs_len; i++)
1013   {
1014     hb_glyph_info_t *info = &buffer->info[i];
1015     hb_glyph_position_t *pos = &buffer->pos[i];
1016
1017     /* TODO vertical */
1018     pos->x_advance = x_mult * (int32_t) info->mask;
1019     pos->x_offset = x_mult * (backward ? -info->var1.i32 : info->var1.i32);
1020     pos->y_offset = y_mult * info->var2.i32;
1021   }
1022
1023   if (backward)
1024     hb_buffer_reverse (buffer);
1025
1026   buffer->unsafe_to_break_all ();
1027
1028   /* Wow, done! */
1029   return true;
1030 }
1031
1032