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