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