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