Imported Upstream version 0.9.3
[platform/upstream/libHarfBuzzSharp.git] / src / hb-uniscribe.cc
1 /*
2  * Copyright © 2011,2012  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 #define _WIN32_WINNT 0x0600
28 #define WIN32_LEAN_AND_MEAN
29
30 #define HB_SHAPER uniscribe
31 #include "hb-shaper-impl-private.hh"
32
33 #include <windows.h>
34 #include <usp10.h>
35
36 typedef ULONG WIN_ULONG;
37
38 #include "hb-uniscribe.h"
39
40 #include "hb-ot-name-table.hh"
41 #include "hb-ot-tag.h"
42
43
44 #ifndef HB_DEBUG_UNISCRIBE
45 #define HB_DEBUG_UNISCRIBE (HB_DEBUG+0)
46 #endif
47
48
49 /*
50 DWORD GetFontData(
51   __in   HDC hdc,
52   __in   DWORD dwTable,
53   __in   DWORD dwOffset,
54   __out  LPVOID lpvBuffer,
55   __in   DWORD cbData
56 );
57 */
58
59
60 HB_SHAPER_DATA_ENSURE_DECLARE(uniscribe, face)
61 HB_SHAPER_DATA_ENSURE_DECLARE(uniscribe, font)
62
63
64 /*
65  * shaper face data
66  */
67
68 struct hb_uniscribe_shaper_face_data_t {
69   HANDLE fh;
70 };
71
72 hb_uniscribe_shaper_face_data_t *
73 _hb_uniscribe_shaper_face_data_create (hb_face_t *face)
74 {
75   hb_uniscribe_shaper_face_data_t *data = (hb_uniscribe_shaper_face_data_t *) calloc (1, sizeof (hb_uniscribe_shaper_face_data_t));
76   if (unlikely (!data))
77     return NULL;
78
79   hb_blob_t *blob = hb_face_reference_blob (face);
80   unsigned int blob_length;
81   const char *blob_data = hb_blob_get_data (blob, &blob_length);
82   if (unlikely (!blob_length))
83     DEBUG_MSG (UNISCRIBE, face, "Face has empty blob");
84
85   DWORD num_fonts_installed;
86   data->fh = AddFontMemResourceEx ((void *) blob_data, blob_length, 0, &num_fonts_installed);
87   hb_blob_destroy (blob);
88   if (unlikely (!data->fh)) {
89     DEBUG_MSG (UNISCRIBE, face, "Face AddFontMemResourceEx() failed");
90     free (data);
91     return NULL;
92   }
93
94   return data;
95 }
96
97 void
98 _hb_uniscribe_shaper_face_data_destroy (hb_uniscribe_shaper_face_data_t *data)
99 {
100   RemoveFontMemResourceEx (data->fh);
101   free (data);
102 }
103
104
105 /*
106  * shaper font data
107  */
108
109 struct hb_uniscribe_shaper_font_data_t {
110   HDC hdc;
111   LOGFONTW log_font;
112   HFONT hfont;
113   SCRIPT_CACHE script_cache;
114 };
115
116 static bool
117 populate_log_font (LOGFONTW  *lf,
118                    hb_font_t *font)
119 {
120   memset (lf, 0, sizeof (*lf));
121   lf->lfHeight = -font->y_scale;
122   lf->lfCharSet = DEFAULT_CHARSET;
123
124   hb_blob_t *blob = Sanitizer<name>::sanitize (hb_face_reference_table (font->face, HB_TAG ('n','a','m','e')));
125   const name *name_table = Sanitizer<name>::lock_instance (blob);
126   unsigned int len = name_table->get_name (3, 1, 0x409, 4,
127                                            lf->lfFaceName,
128                                            sizeof (lf->lfFaceName[0]) * LF_FACESIZE)
129                                           / sizeof (lf->lfFaceName[0]);
130   hb_blob_destroy (blob);
131
132   if (unlikely (!len)) {
133     DEBUG_MSG (UNISCRIBE, NULL, "Didn't find English name table entry");
134     return false;
135   }
136   if (unlikely (len >= LF_FACESIZE)) {
137     DEBUG_MSG (UNISCRIBE, NULL, "Font name too long");
138     return false;
139   }
140
141   for (unsigned int i = 0; i < len; i++)
142     lf->lfFaceName[i] = hb_be_uint16 (lf->lfFaceName[i]);
143   lf->lfFaceName[len] = 0;
144
145   return true;
146 }
147
148 hb_uniscribe_shaper_font_data_t *
149 _hb_uniscribe_shaper_font_data_create (hb_font_t *font)
150 {
151   if (unlikely (!hb_uniscribe_shaper_face_data_ensure (font->face))) return NULL;
152
153   hb_uniscribe_shaper_font_data_t *data = (hb_uniscribe_shaper_font_data_t *) calloc (1, sizeof (hb_uniscribe_shaper_font_data_t));
154   if (unlikely (!data))
155     return NULL;
156
157   data->hdc = GetDC (NULL);
158
159   if (unlikely (!populate_log_font (&data->log_font, font))) {
160     DEBUG_MSG (UNISCRIBE, font, "Font populate_log_font() failed");
161     _hb_uniscribe_shaper_font_data_destroy (data);
162     return NULL;
163   }
164
165   data->hfont = CreateFontIndirectW (&data->log_font);
166   if (unlikely (!data->hfont)) {
167     DEBUG_MSG (UNISCRIBE, font, "Font CreateFontIndirectW() failed");
168     _hb_uniscribe_shaper_font_data_destroy (data);
169      return NULL;
170   }
171
172   if (!SelectObject (data->hdc, data->hfont)) {
173     DEBUG_MSG (UNISCRIBE, font, "Font SelectObject() failed");
174     _hb_uniscribe_shaper_font_data_destroy (data);
175      return NULL;
176   }
177
178   return data;
179 }
180
181 void
182 _hb_uniscribe_shaper_font_data_destroy (hb_uniscribe_shaper_font_data_t *data)
183 {
184   if (data->hdc)
185     ReleaseDC (NULL, data->hdc);
186   if (data->hfont)
187     DeleteObject (data->hfont);
188   if (data->script_cache)
189     ScriptFreeCache (&data->script_cache);
190   free (data);
191 }
192
193
194 /*
195  * shaper shape_plan data
196  */
197
198 struct hb_uniscribe_shaper_shape_plan_data_t {};
199
200 hb_uniscribe_shaper_shape_plan_data_t *
201 _hb_uniscribe_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
202                                              const hb_feature_t *user_features HB_UNUSED,
203                                              unsigned int        num_user_features HB_UNUSED)
204 {
205   return (hb_uniscribe_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
206 }
207
208 void
209 _hb_uniscribe_shaper_shape_plan_data_destroy (hb_uniscribe_shaper_shape_plan_data_t *data HB_UNUSED)
210 {
211 }
212
213
214 /*
215  * shaper
216  */
217
218 LOGFONTW *
219 hb_uniscribe_font_get_logfontw (hb_font_t *font)
220 {
221   if (unlikely (!hb_uniscribe_shaper_font_data_ensure (font))) return NULL;
222     return NULL;
223   hb_uniscribe_shaper_font_data_t *font_data =  HB_SHAPER_DATA_GET (font);
224   return &font_data->log_font;
225 }
226
227 HFONT
228 hb_uniscribe_font_get_hfont (hb_font_t *font)
229 {
230   if (unlikely (!hb_uniscribe_shaper_font_data_ensure (font))) return NULL;
231   hb_uniscribe_shaper_font_data_t *font_data =  HB_SHAPER_DATA_GET (font);
232   return font_data->hfont;
233 }
234
235
236 hb_bool_t
237 _hb_uniscribe_shape (hb_shape_plan_t    *shape_plan,
238                      hb_font_t          *font,
239                      hb_buffer_t        *buffer,
240                      const hb_feature_t *features,
241                      unsigned int        num_features)
242 {
243   hb_face_t *face = font->face;
244   hb_uniscribe_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
245   hb_uniscribe_shaper_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
246
247 #define FAIL(...) \
248   HB_STMT_START { \
249     DEBUG_MSG (UNISCRIBE, NULL, __VA_ARGS__); \
250     return false; \
251   } HB_STMT_END;
252
253   HRESULT hr;
254
255 retry:
256
257   unsigned int scratch_size;
258   char *scratch = (char *) buffer->get_scratch_buffer (&scratch_size);
259
260   /* Allocate char buffers; they all fit */
261
262 #define ALLOCATE_ARRAY(Type, name, len) \
263   Type *name = (Type *) scratch; \
264   scratch += (len) * sizeof ((name)[0]); \
265   scratch_size -= (len) * sizeof ((name)[0]);
266
267 #define utf16_index() var1.u32
268
269   WCHAR *pchars = (WCHAR *) scratch;
270   unsigned int chars_len = 0;
271   for (unsigned int i = 0; i < buffer->len; i++) {
272     hb_codepoint_t c = buffer->info[i].codepoint;
273     buffer->info[i].utf16_index() = chars_len;
274     if (likely (c < 0x10000))
275       pchars[chars_len++] = c;
276     else if (unlikely (c >= 0x110000))
277       pchars[chars_len++] = 0xFFFD;
278     else {
279       pchars[chars_len++] = 0xD800 + ((c - 0x10000) >> 10);
280       pchars[chars_len++] = 0xDC00 + ((c - 0x10000) & ((1 << 10) - 1));
281     }
282   }
283
284   ALLOCATE_ARRAY (WCHAR, wchars, chars_len);
285   ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
286   ALLOCATE_ARRAY (SCRIPT_CHARPROP, char_props, chars_len);
287
288   /* On Windows, we don't care about alignment...*/
289   unsigned int glyphs_size = scratch_size / (sizeof (WORD) +
290                                              sizeof (SCRIPT_GLYPHPROP) +
291                                              sizeof (int) +
292                                              sizeof (GOFFSET) +
293                                              sizeof (uint32_t));
294
295   ALLOCATE_ARRAY (WORD, glyphs, glyphs_size);
296   ALLOCATE_ARRAY (SCRIPT_GLYPHPROP, glyph_props, glyphs_size);
297   ALLOCATE_ARRAY (int, advances, glyphs_size);
298   ALLOCATE_ARRAY (GOFFSET, offsets, glyphs_size);
299   ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
300
301 #undef ALLOCATE_ARRAY
302
303 #define MAX_ITEMS 256
304
305   SCRIPT_ITEM items[MAX_ITEMS + 1];
306   SCRIPT_CONTROL bidi_control = {0};
307   SCRIPT_STATE bidi_state = {0};
308   WIN_ULONG script_tags[MAX_ITEMS];
309   int item_count;
310
311   /* MinGW32 doesn't define fMergeNeutralItems, so we bruteforce */
312   //bidi_control.fMergeNeutralItems = true;
313   *(uint32_t*)&bidi_control |= 1<<24;
314
315   bidi_state.uBidiLevel = HB_DIRECTION_IS_FORWARD (buffer->props.direction) ? 0 : 1;
316   bidi_state.fOverrideDirection = 1;
317
318   hr = ScriptItemizeOpenType (wchars,
319                               chars_len,
320                               MAX_ITEMS,
321                               &bidi_control,
322                               &bidi_state,
323                               items,
324                               script_tags,
325                               &item_count);
326   if (unlikely (FAILED (hr)))
327     FAIL ("ScriptItemizeOpenType() failed: 0x%08xL", hr);
328
329 #undef MAX_ITEMS
330
331   int *range_char_counts = NULL;
332   TEXTRANGE_PROPERTIES **range_properties = NULL;
333   int range_count = 0;
334   if (num_features) {
335     /* TODO setup ranges */
336   }
337
338   OPENTYPE_TAG language_tag = hb_uint32_swap (hb_ot_tag_from_language (buffer->props.language));
339
340   unsigned int glyphs_offset = 0;
341   unsigned int glyphs_len;
342   bool backward = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
343   for (unsigned int j = 0; j < item_count; j++)
344   {
345     unsigned int i = backward ? item_count - 1 - j : j;
346     unsigned int chars_offset = items[i].iCharPos;
347     unsigned int item_chars_len = items[i + 1].iCharPos - chars_offset;
348
349   retry_shape:
350     hr = ScriptShapeOpenType (font_data->hdc,
351                               &font_data->script_cache,
352                               &items[i].a,
353                               script_tags[i],
354                               language_tag,
355                               range_char_counts,
356                               range_properties,
357                               range_count,
358                               wchars + chars_offset,
359                               item_chars_len,
360                               glyphs_size - glyphs_offset,
361                               /* out */
362                               log_clusters + chars_offset,
363                               char_props + chars_offset,
364                               glyphs + glyphs_offset,
365                               glyph_props + glyphs_offset,
366                               (int *) &glyphs_len);
367
368     if (unlikely (items[i].a.fNoGlyphIndex))
369       FAIL ("ScriptShapeOpenType() set fNoGlyphIndex");
370     if (unlikely (hr == E_OUTOFMEMORY))
371     {
372       buffer->ensure (buffer->allocated * 2);
373       if (buffer->in_error)
374         FAIL ("Buffer resize failed");
375       goto retry;
376     }
377     if (unlikely (hr == USP_E_SCRIPT_NOT_IN_FONT))
378     {
379       if (items[i].a.eScript == SCRIPT_UNDEFINED)
380         FAIL ("ScriptShapeOpenType() failed: Font doesn't support script");
381       items[i].a.eScript = SCRIPT_UNDEFINED;
382       goto retry_shape;
383     }
384     if (unlikely (FAILED (hr)))
385     {
386       FAIL ("ScriptShapeOpenType() failed: 0x%08xL", hr);
387     }
388
389     for (unsigned int j = chars_offset; j < chars_offset + item_chars_len; j++)
390       log_clusters[j] += glyphs_offset;
391
392     hr = ScriptPlaceOpenType (font_data->hdc,
393                               &font_data->script_cache,
394                               &items[i].a,
395                               script_tags[i],
396                               language_tag,
397                               range_char_counts,
398                               range_properties,
399                               range_count,
400                               wchars + chars_offset,
401                               log_clusters + chars_offset,
402                               char_props + chars_offset,
403                               item_chars_len,
404                               glyphs + glyphs_offset,
405                               glyph_props + glyphs_offset,
406                               glyphs_len,
407                               /* out */
408                               advances + glyphs_offset,
409                               offsets + glyphs_offset,
410                               NULL);
411     if (unlikely (FAILED (hr)))
412       FAIL ("ScriptPlaceOpenType() failed: 0x%08xL", hr);
413
414     glyphs_offset += glyphs_len;
415   }
416   glyphs_len = glyphs_offset;
417
418   /* Ok, we've got everything we need, now compose output buffer,
419    * very, *very*, carefully! */
420
421   /* Calculate visual-clusters.  That's what we ship. */
422   for (unsigned int i = 0; i < glyphs_len; i++)
423     vis_clusters[i] = -1;
424   for (unsigned int i = 0; i < buffer->len; i++) {
425     uint32_t *p = &vis_clusters[log_clusters[buffer->info[i].utf16_index()]];
426     *p = MIN (*p, buffer->info[i].cluster);
427   }
428   if (!backward) {
429     for (unsigned int i = 1; i < glyphs_len; i++)
430       if (vis_clusters[i] == -1)
431         vis_clusters[i] = vis_clusters[i - 1];
432   } else {
433     for (int i = glyphs_len - 2; i >= 0; i--)
434       if (vis_clusters[i] == -1)
435         vis_clusters[i] = vis_clusters[i + 1];
436   }
437
438 #undef utf16_index
439
440   buffer->ensure (glyphs_len);
441   if (buffer->in_error)
442     FAIL ("Buffer in error");
443
444 #undef FAIL
445
446   /* Set glyph infos */
447   buffer->len = 0;
448   for (unsigned int i = 0; i < glyphs_len; i++)
449   {
450     hb_glyph_info_t *info = &buffer->info[buffer->len++];
451
452     info->codepoint = glyphs[i];
453     info->cluster = vis_clusters[i];
454
455     /* The rest is crap.  Let's store position info there for now. */
456     info->mask = advances[i];
457     info->var1.u32 = offsets[i].du;
458     info->var2.u32 = offsets[i].dv;
459   }
460
461   /* Set glyph positions */
462   buffer->clear_positions ();
463   for (unsigned int i = 0; i < glyphs_len; i++)
464   {
465     hb_glyph_info_t *info = &buffer->info[i];
466     hb_glyph_position_t *pos = &buffer->pos[i];
467
468     /* TODO vertical */
469     pos->x_advance = info->mask;
470     pos->x_offset = info->var1.u32;
471     pos->y_offset = info->var2.u32;
472   }
473
474   /* Wow, done! */
475   return true;
476 }
477
478