]> code.delx.au - gnu-emacs/blob - src/w32uniscribe.c
Improve and future-proof OTF fonts support in w32uniscribe.c
[gnu-emacs] / src / w32uniscribe.c
1 /* Font backend for the Microsoft W32 Uniscribe API.
2 Copyright (C) 2008-2015 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19
20 #include <config.h>
21 /* Override API version - Uniscribe is only available as standard since
22 Windows 2000, though most users of older systems will have it
23 since it installs with Internet Explorer 5.0 and other software.
24 We only enable the feature if it is available, so there is no chance
25 of calling non-existent functions. */
26 #undef _WIN32_WINNT
27 #define _WIN32_WINNT 0x500
28 #include <windows.h>
29 #include <usp10.h>
30
31 #include "lisp.h"
32 #include "w32term.h"
33 #include "frame.h"
34 #include "dispextern.h"
35 #include "character.h"
36 #include "charset.h"
37 #include "composite.h"
38 #include "fontset.h"
39 #include "font.h"
40 #include "w32font.h"
41
42 struct uniscribe_font_info
43 {
44 struct w32font_info w32_font;
45 SCRIPT_CACHE cache;
46 };
47
48 int uniscribe_available = 0;
49
50 /* EnumFontFamiliesEx callback. */
51 static int CALLBACK ALIGN_STACK add_opentype_font_name_to_list (ENUMLOGFONTEX *,
52 NEWTEXTMETRICEX *,
53 DWORD, LPARAM);
54 /* Used by uniscribe_otf_capability. */
55 static Lisp_Object otf_features (HDC context, char *table);
56
57 static int
58 memq_no_quit (Lisp_Object elt, Lisp_Object list)
59 {
60 while (CONSP (list) && ! EQ (XCAR (list), elt))
61 list = XCDR (list);
62 return (CONSP (list));
63 }
64
65 \f
66 /* Font backend interface implementation. */
67 static Lisp_Object
68 uniscribe_list (struct frame *f, Lisp_Object font_spec)
69 {
70 Lisp_Object fonts = w32font_list_internal (f, font_spec, true);
71 FONT_ADD_LOG ("uniscribe-list", font_spec, fonts);
72 return fonts;
73 }
74
75 static Lisp_Object
76 uniscribe_match (struct frame *f, Lisp_Object font_spec)
77 {
78 Lisp_Object entity = w32font_match_internal (f, font_spec, true);
79 FONT_ADD_LOG ("uniscribe-match", font_spec, entity);
80 return entity;
81 }
82
83 static Lisp_Object
84 uniscribe_list_family (struct frame *f)
85 {
86 Lisp_Object list = Qnil;
87 LOGFONT font_match_pattern;
88 HDC dc;
89
90 memset (&font_match_pattern, 0, sizeof (font_match_pattern));
91 /* Limit enumerated fonts to outline fonts to save time. */
92 font_match_pattern.lfOutPrecision = OUT_OUTLINE_PRECIS;
93
94 dc = get_frame_dc (f);
95
96 EnumFontFamiliesEx (dc, &font_match_pattern,
97 (FONTENUMPROC) add_opentype_font_name_to_list,
98 (LPARAM) &list, 0);
99 release_frame_dc (f, dc);
100
101 return list;
102 }
103
104 static Lisp_Object
105 uniscribe_open (struct frame *f, Lisp_Object font_entity, int pixel_size)
106 {
107 Lisp_Object font_object
108 = font_make_object (VECSIZE (struct uniscribe_font_info),
109 font_entity, pixel_size);
110 struct uniscribe_font_info *uniscribe_font
111 = (struct uniscribe_font_info *) XFONT_OBJECT (font_object);
112
113 ASET (font_object, FONT_TYPE_INDEX, Quniscribe);
114
115 if (!w32font_open_internal (f, font_entity, pixel_size, font_object))
116 {
117 return Qnil;
118 }
119
120 /* Initialize the cache for this font. */
121 uniscribe_font->cache = NULL;
122
123 /* Uniscribe backend uses glyph indices. */
124 uniscribe_font->w32_font.glyph_idx = ETO_GLYPH_INDEX;
125
126 uniscribe_font->w32_font.font.driver = &uniscribe_font_driver;
127
128 return font_object;
129 }
130
131 static void
132 uniscribe_close (struct font *font)
133 {
134 struct uniscribe_font_info *uniscribe_font
135 = (struct uniscribe_font_info *) font;
136
137 if (uniscribe_font->cache)
138 ScriptFreeCache (&(uniscribe_font->cache));
139
140 w32font_close (font);
141 }
142
143 /* Return a list describing which scripts/languages FONT supports by
144 which GSUB/GPOS features of OpenType tables.
145
146 Implementation note: otf_features called by this function uses
147 GetFontData to access the font tables directly, instead of using
148 ScriptGetFontScriptTags etc. APIs even if those are available. The
149 reason is that font-get, which uses the result of this function,
150 expects a cons cell (GSUB . GPOS) where the features are reported
151 separately for these 2 OTF tables, while the Uniscribe APIs report
152 the features as a single list. There doesn't seem to be a reason
153 for returning the features in 2 separate parts, except for
154 compatibility with libotf; the features are disjoint (each can
155 appear only in one of the 2 slots), and no client of this data
156 discerns between the two slots: the few that request this data all
157 look in both slots. If use of the Uniscribe APIs ever becomes
158 necessary here, and the 2 separate slots are still required, it
159 should be possible to split the feature list the APIs return into 2
160 because each sub-list is alphabetically sorted, so the place where
161 the sorting order breaks is where the GSUB features end and GPOS
162 features begin. But for now, this is not necessary, so we leave
163 the original code in place. */
164 static Lisp_Object
165 uniscribe_otf_capability (struct font *font)
166 {
167 HDC context;
168 HFONT old_font;
169 struct frame *f;
170 Lisp_Object capability = Fcons (Qnil, Qnil);
171 Lisp_Object features;
172
173 f = XFRAME (selected_frame);
174 context = get_frame_dc (f);
175 old_font = SelectObject (context, FONT_HANDLE (font));
176
177 features = otf_features (context, "GSUB");
178 XSETCAR (capability, features);
179 features = otf_features (context, "GPOS");
180 XSETCDR (capability, features);
181
182 SelectObject (context, old_font);
183 release_frame_dc (f, context);
184
185 return capability;
186 }
187
188 /* Uniscribe implementation of shape for font backend.
189
190 Shape text in LGSTRING. See the docstring of
191 `composition-get-gstring' for the format of LGSTRING. If the
192 (N+1)th element of LGSTRING is nil, input of shaping is from the
193 1st to (N)th elements. In each input glyph, FROM, TO, CHAR, and
194 CODE are already set.
195
196 This function updates all fields of the input glyphs. If the
197 output glyphs (M) are more than the input glyphs (N), (N+1)th
198 through (M)th elements of LGSTRING are updated possibly by making
199 a new glyph object and storing it in LGSTRING. If (M) is greater
200 than the length of LGSTRING, nil should be returned. In that case,
201 this function is called again with a larger LGSTRING. */
202 static Lisp_Object
203 uniscribe_shape (Lisp_Object lgstring)
204 {
205 struct font *font = CHECK_FONT_GET_OBJECT (LGSTRING_FONT (lgstring));
206 struct uniscribe_font_info *uniscribe_font
207 = (struct uniscribe_font_info *) font;
208 EMACS_UINT nchars;
209 int nitems, max_items, i, max_glyphs, done_glyphs;
210 wchar_t *chars;
211 WORD *glyphs, *clusters;
212 SCRIPT_ITEM *items;
213 SCRIPT_VISATTR *attributes;
214 int *advances;
215 GOFFSET *offsets;
216 ABC overall_metrics;
217 HRESULT result;
218 struct frame * f = NULL;
219 HDC context = NULL;
220 HFONT old_font = NULL;
221
222 /* Get the chars from lgstring in a form we can use with uniscribe. */
223 max_glyphs = nchars = LGSTRING_GLYPH_LEN (lgstring);
224 done_glyphs = 0;
225 chars = (wchar_t *) alloca (nchars * sizeof (wchar_t));
226 /* FIXME: This loop assumes that characters in the input LGSTRING
227 are all inside the BMP. Need to encode characters beyond the BMP
228 as UTF-16. */
229 for (i = 0; i < nchars; i++)
230 {
231 /* lgstring can be bigger than the number of characters in it, in
232 the case where more glyphs are required to display those characters.
233 If that is the case, note the real number of characters. */
234 if (NILP (LGSTRING_GLYPH (lgstring, i)))
235 nchars = i;
236 else
237 chars[i] = LGLYPH_CHAR (LGSTRING_GLYPH (lgstring, i));
238 }
239
240 /* First we need to break up the glyph string into runs of glyphs that
241 can be treated together. First try a single run. */
242 max_items = 2;
243 items = xmalloc (sizeof (SCRIPT_ITEM) * max_items + 1);
244
245 while ((result = ScriptItemize (chars, nchars, max_items, NULL, NULL,
246 items, &nitems)) == E_OUTOFMEMORY)
247 {
248 /* If that wasn't enough, keep trying with one more run. */
249 max_items++;
250 items = (SCRIPT_ITEM *) xrealloc (items,
251 sizeof (SCRIPT_ITEM) * max_items + 1);
252 }
253
254 if (FAILED (result))
255 {
256 xfree (items);
257 return Qnil;
258 }
259
260 glyphs = alloca (max_glyphs * sizeof (WORD));
261 clusters = alloca (nchars * sizeof (WORD));
262 attributes = alloca (max_glyphs * sizeof (SCRIPT_VISATTR));
263 advances = alloca (max_glyphs * sizeof (int));
264 offsets = alloca (max_glyphs * sizeof (GOFFSET));
265
266 for (i = 0; i < nitems; i++)
267 {
268 int nglyphs, nchars_in_run;
269 nchars_in_run = items[i+1].iCharPos - items[i].iCharPos;
270 /* Force ScriptShape to generate glyphs in the same order as
271 they are in the input LGSTRING, which is in the logical
272 order. */
273 items[i].a.fLogicalOrder = 1;
274
275 /* Context may be NULL here, in which case the cache should be
276 used without needing to select the font. */
277 result = ScriptShape (context, &(uniscribe_font->cache),
278 chars + items[i].iCharPos, nchars_in_run,
279 max_glyphs - done_glyphs, &(items[i].a),
280 glyphs, clusters, attributes, &nglyphs);
281
282 if (result == E_PENDING && !context)
283 {
284 /* This assumes the selected frame is on the same display as the
285 one we are drawing. It would be better for the frame to be
286 passed in. */
287 f = XFRAME (selected_frame);
288 context = get_frame_dc (f);
289 old_font = SelectObject (context, FONT_HANDLE (font));
290
291 result = ScriptShape (context, &(uniscribe_font->cache),
292 chars + items[i].iCharPos, nchars_in_run,
293 max_glyphs - done_glyphs, &(items[i].a),
294 glyphs, clusters, attributes, &nglyphs);
295 }
296
297 if (result == E_OUTOFMEMORY)
298 {
299 /* Need a bigger lgstring. */
300 lgstring = Qnil;
301 break;
302 }
303 else if (FAILED (result))
304 {
305 /* Can't shape this run - return results so far if any. */
306 break;
307 }
308 else if (items[i].a.fNoGlyphIndex)
309 {
310 /* Glyph indices not supported by this font (or OS), means we
311 can't really do any meaningful shaping. */
312 break;
313 }
314 else
315 {
316 result = ScriptPlace (context, &(uniscribe_font->cache),
317 glyphs, nglyphs, attributes, &(items[i].a),
318 advances, offsets, &overall_metrics);
319 if (result == E_PENDING && !context)
320 {
321 /* Cache not complete... */
322 f = XFRAME (selected_frame);
323 context = get_frame_dc (f);
324 old_font = SelectObject (context, FONT_HANDLE (font));
325
326 result = ScriptPlace (context, &(uniscribe_font->cache),
327 glyphs, nglyphs, attributes, &(items[i].a),
328 advances, offsets, &overall_metrics);
329 }
330 if (SUCCEEDED (result))
331 {
332 int j, from, to, adj_offset = 0;
333
334 from = 0;
335 to = from;
336
337 for (j = 0; j < nglyphs; j++)
338 {
339 int lglyph_index = j + done_glyphs;
340 Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, lglyph_index);
341 ABC char_metric;
342 unsigned gl;
343
344 if (NILP (lglyph))
345 {
346 lglyph = LGLYPH_NEW ();
347 LGSTRING_SET_GLYPH (lgstring, lglyph_index, lglyph);
348 }
349 /* Copy to a 32-bit data type to shut up the
350 compiler warning in LGLYPH_SET_CODE about
351 comparison being always false. */
352 gl = glyphs[j];
353 LGLYPH_SET_CODE (lglyph, gl);
354
355 /* Detect clusters, for linking codes back to
356 characters. */
357 if (attributes[j].fClusterStart)
358 {
359 while (from < nchars_in_run && clusters[from] < j)
360 from++;
361 if (from >= nchars_in_run)
362 from = to = nchars_in_run - 1;
363 else
364 {
365 int k;
366 to = nchars_in_run - 1;
367 for (k = from + 1; k < nchars_in_run; k++)
368 {
369 if (clusters[k] > j)
370 {
371 to = k - 1;
372 break;
373 }
374 }
375 }
376
377 /* For RTL text, the Uniscribe shaper prepares
378 the values in ADVANCES array for layout in
379 reverse order, whereby "advance width" is
380 applied to move the pen in reverse direction
381 and _before_ drawing the glyph. Since we
382 draw glyphs in their normal left-to-right
383 order, we need to adjust the coordinates of
384 each non-base glyph in a grapheme cluster via
385 X-OFF component of the gstring's ADJUSTMENT
386 sub-vector. This loop computes, for each
387 grapheme cluster, the initial value of the
388 adjustment for the base character, which is
389 then updated for each successive glyph in the
390 grapheme cluster. */
391 if (items[i].a.fRTL)
392 {
393 int j1 = j;
394
395 adj_offset = 0;
396 while (j1 < nglyphs && !attributes[j1].fClusterStart)
397 {
398 adj_offset += advances[j1];
399 j1++;
400 }
401 }
402 }
403
404 LGLYPH_SET_CHAR (lglyph, chars[items[i].iCharPos
405 + from]);
406 LGLYPH_SET_FROM (lglyph, items[i].iCharPos + from);
407 LGLYPH_SET_TO (lglyph, items[i].iCharPos + to);
408
409 /* Metrics. */
410 LGLYPH_SET_WIDTH (lglyph, advances[j]);
411 LGLYPH_SET_ASCENT (lglyph, font->ascent);
412 LGLYPH_SET_DESCENT (lglyph, font->descent);
413
414 result = ScriptGetGlyphABCWidth (context,
415 &(uniscribe_font->cache),
416 glyphs[j], &char_metric);
417 if (result == E_PENDING && !context)
418 {
419 /* Cache incomplete... */
420 f = XFRAME (selected_frame);
421 context = get_frame_dc (f);
422 old_font = SelectObject (context, FONT_HANDLE (font));
423 result = ScriptGetGlyphABCWidth (context,
424 &(uniscribe_font->cache),
425 glyphs[j], &char_metric);
426 }
427
428 if (SUCCEEDED (result))
429 {
430 int lbearing = char_metric.abcA;
431 int rbearing = char_metric.abcA + char_metric.abcB;
432
433 LGLYPH_SET_LBEARING (lglyph, lbearing);
434 LGLYPH_SET_RBEARING (lglyph, rbearing);
435 }
436 else
437 {
438 LGLYPH_SET_LBEARING (lglyph, 0);
439 LGLYPH_SET_RBEARING (lglyph, advances[j]);
440 }
441
442 if (offsets[j].du || offsets[j].dv
443 /* For non-base glyphs of RTL grapheme clusters,
444 adjust the X offset even if both DU and DV
445 are zero. */
446 || (!attributes[j].fClusterStart && items[i].a.fRTL))
447 {
448 Lisp_Object vec = make_uninit_vector (3);
449
450 if (items[i].a.fRTL)
451 {
452 /* Empirically, it looks like Uniscribe
453 interprets DU in reverse direction for
454 RTL clusters. E.g., if we don't reverse
455 the direction, the Hebrew point HOLAM is
456 drawn above the right edge of the base
457 consonant, instead of above the left edge. */
458 ASET (vec, 0, make_number (-offsets[j].du
459 + adj_offset));
460 /* Update the adjustment value for the width
461 advance of the glyph we just emitted. */
462 adj_offset -= 2 * advances[j];
463 }
464 else
465 ASET (vec, 0, make_number (offsets[j].du + adj_offset));
466 /* In the font definition coordinate system, the
467 Y coordinate points up, while in our screen
468 coordinates Y grows downwards. So we need to
469 reverse the sign of Y-OFFSET here. */
470 ASET (vec, 1, make_number (-offsets[j].dv));
471 /* Based on what ftfont.c does... */
472 ASET (vec, 2, make_number (advances[j]));
473 LGLYPH_SET_ADJUSTMENT (lglyph, vec);
474 }
475 else
476 {
477 LGLYPH_SET_ADJUSTMENT (lglyph, Qnil);
478 /* Update the adjustment value to compensate for
479 the width of the base character. */
480 if (items[i].a.fRTL)
481 adj_offset -= advances[j];
482 }
483 }
484 }
485 }
486 done_glyphs += nglyphs;
487 }
488
489 xfree (items);
490
491 if (context)
492 {
493 SelectObject (context, old_font);
494 release_frame_dc (f, context);
495 }
496
497 if (NILP (lgstring))
498 return Qnil;
499 else
500 return make_number (done_glyphs);
501 }
502
503 /* Uniscribe implementation of encode_char for font backend.
504 Return a glyph code of FONT for character C (Unicode code point).
505 If FONT doesn't have such a glyph, return FONT_INVALID_CODE. */
506 static unsigned
507 uniscribe_encode_char (struct font *font, int c)
508 {
509 HDC context = NULL;
510 struct frame *f = NULL;
511 HFONT old_font = NULL;
512 unsigned code = FONT_INVALID_CODE;
513 wchar_t ch[2];
514 int len;
515 SCRIPT_ITEM* items;
516 int nitems;
517 struct uniscribe_font_info *uniscribe_font
518 = (struct uniscribe_font_info *)font;
519
520 if (c < 0x10000)
521 {
522 ch[0] = (wchar_t) c;
523 len = 1;
524 }
525 else
526 {
527 DWORD surrogate = c - 0x10000;
528
529 /* High surrogate: U+D800 - U+DBFF. */
530 ch[0] = 0xD800 + ((surrogate >> 10) & 0x03FF);
531 /* Low surrogate: U+DC00 - U+DFFF. */
532 ch[1] = 0xDC00 + (surrogate & 0x03FF);
533 len = 2;
534 }
535
536 /* Non BMP characters must be handled by the uniscribe shaping
537 engine as GDI functions (except blindly displaying lines of
538 Unicode text) and the promising looking ScriptGetCMap do not
539 convert surrogate pairs to glyph indexes correctly. */
540 {
541 items = (SCRIPT_ITEM *) alloca (sizeof (SCRIPT_ITEM) * 2 + 1);
542 if (SUCCEEDED (ScriptItemize (ch, len, 2, NULL, NULL, items, &nitems)))
543 {
544 HRESULT result;
545 /* Surrogates seem to need 2 here, even though only one glyph is
546 returned. Indic characters can also produce 2 or more glyphs for
547 a single code point, but they need to use uniscribe_shape
548 above for correct display. */
549 WORD glyphs[2], clusters[2];
550 SCRIPT_VISATTR attrs[2];
551 int nglyphs;
552
553 /* Force ScriptShape to generate glyphs in the logical
554 order. */
555 items[0].a.fLogicalOrder = 1;
556
557 result = ScriptShape (context, &(uniscribe_font->cache),
558 ch, len, 2, &(items[0].a),
559 glyphs, clusters, attrs, &nglyphs);
560
561 if (result == E_PENDING)
562 {
563 /* Use selected frame until API is updated to pass
564 the frame. */
565 f = XFRAME (selected_frame);
566 context = get_frame_dc (f);
567 old_font = SelectObject (context, FONT_HANDLE (font));
568 result = ScriptShape (context, &(uniscribe_font->cache),
569 ch, len, 2, &(items[0].a),
570 glyphs, clusters, attrs, &nglyphs);
571 }
572
573 if (SUCCEEDED (result) && nglyphs == 1)
574 {
575 /* Some fonts return .notdef glyphs instead of failing.
576 (TrueType spec reserves glyph code 0 for .notdef) */
577 if (glyphs[0])
578 code = glyphs[0];
579 }
580 else if (SUCCEEDED (result) || result == E_OUTOFMEMORY)
581 {
582 /* This character produces zero or more than one glyph
583 when shaped. But we still need the return from here
584 to be valid for the shaping engine to be invoked
585 later. */
586 result = ScriptGetCMap (context, &(uniscribe_font->cache),
587 ch, len, 0, glyphs);
588 if (SUCCEEDED (result) && glyphs[0])
589 code = glyphs[0];
590 }
591 }
592 }
593 if (context)
594 {
595 SelectObject (context, old_font);
596 release_frame_dc (f, context);
597 }
598
599 return code;
600 }
601
602 /*
603 Shared with w32font:
604 Lisp_Object uniscribe_get_cache (Lisp_Object frame);
605 void uniscribe_free_entity (Lisp_Object font_entity);
606 int uniscribe_has_char (Lisp_Object entity, int c);
607 void uniscribe_text_extents (struct font *font, unsigned *code,
608 int nglyphs, struct font_metrics *metrics);
609 int uniscribe_draw (struct glyph_string *s, int from, int to,
610 int x, int y, int with_background);
611
612 Unused:
613 int uniscribe_prepare_face (struct frame *f, struct face *face);
614 void uniscribe_done_face (struct frame *f, struct face *face);
615 int uniscribe_get_bitmap (struct font *font, unsigned code,
616 struct font_bitmap *bitmap, int bits_per_pixel);
617 void uniscribe_free_bitmap (struct font *font, struct font_bitmap *bitmap);
618 int uniscribe_anchor_point (struct font *font, unsigned code,
619 int index, int *x, int *y);
620 int uniscribe_start_for_frame (struct frame *f);
621 int uniscribe_end_for_frame (struct frame *f);
622
623 */
624
625 \f
626 /* Callback function for EnumFontFamiliesEx.
627 Adds the name of opentype fonts to a Lisp list (passed in as the
628 lParam arg). */
629 static int CALLBACK ALIGN_STACK
630 add_opentype_font_name_to_list (ENUMLOGFONTEX *logical_font,
631 NEWTEXTMETRICEX *physical_font,
632 DWORD font_type, LPARAM list_object)
633 {
634 Lisp_Object* list = (Lisp_Object *) list_object;
635 Lisp_Object family;
636
637 /* Skip vertical fonts (intended only for printing) */
638 if (logical_font->elfLogFont.lfFaceName[0] == '@')
639 return 1;
640
641 /* Skip non opentype fonts. Count old truetype fonts as opentype,
642 as some of them do contain GPOS and GSUB data that Uniscribe
643 can make use of. */
644 if (!(physical_font->ntmTm.ntmFlags & NTMFLAGS_OPENTYPE)
645 && font_type != TRUETYPE_FONTTYPE)
646 return 1;
647
648 /* Skip fonts that have no Unicode coverage. */
649 if (!physical_font->ntmFontSig.fsUsb[3]
650 && !physical_font->ntmFontSig.fsUsb[2]
651 && !physical_font->ntmFontSig.fsUsb[1]
652 && !(physical_font->ntmFontSig.fsUsb[0] & 0x3fffffff))
653 return 1;
654
655 family = intern_font_name (logical_font->elfLogFont.lfFaceName);
656 if (! memq_no_quit (family, *list))
657 *list = Fcons (family, *list);
658
659 return 1;
660 }
661
662 \f
663 /* :otf property handling.
664 Since the necessary Uniscribe APIs for getting font tag information
665 are only available in Vista, we may need to parse the font data directly
666 according to the OpenType Specification. */
667
668 /* Push into DWORD backwards to cope with endianness. */
669 #define OTF_TAG(STR) \
670 ((STR[3] << 24) | (STR[2] << 16) | (STR[1] << 8) | STR[0])
671
672 #define OTF_INT16_VAL(TABLE, OFFSET, PTR) \
673 do { \
674 BYTE temp, data[2]; \
675 if (GetFontData (context, TABLE, OFFSET, data, 2) != 2) \
676 goto font_table_error; \
677 temp = data[0], data[0] = data[1], data[1] = temp; \
678 memcpy (PTR, data, 2); \
679 } while (0)
680
681 /* Do not reverse the bytes, because we will compare with a OTF_TAG value
682 that has them reversed already. */
683 #define OTF_DWORDTAG_VAL(TABLE, OFFSET, PTR) \
684 do { \
685 if (GetFontData (context, TABLE, OFFSET, PTR, 4) != 4) \
686 goto font_table_error; \
687 } while (0)
688
689 #define OTF_TAG_VAL(TABLE, OFFSET, STR) \
690 do { \
691 if (GetFontData (context, TABLE, OFFSET, STR, 4) != 4) \
692 goto font_table_error; \
693 STR[4] = '\0'; \
694 } while (0)
695
696 #define SNAME(VAL) SSDATA (SYMBOL_NAME (VAL))
697
698 /* Uniscribe APIs available only since Windows Vista. */
699 typedef HRESULT (WINAPI *ScriptGetFontScriptTags_Proc)
700 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, int, OPENTYPE_TAG *, int *);
701
702 typedef HRESULT (WINAPI *ScriptGetFontLanguageTags_Proc)
703 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, OPENTYPE_TAG, int, OPENTYPE_TAG *, int *);
704
705 typedef HRESULT (WINAPI *ScriptGetFontFeatureTags_Proc)
706 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, OPENTYPE_TAG, OPENTYPE_TAG, int, OPENTYPE_TAG *, int *);
707
708 ScriptGetFontScriptTags_Proc script_get_font_scripts_fn;
709 ScriptGetFontLanguageTags_Proc script_get_font_languages_fn;
710 ScriptGetFontFeatureTags_Proc script_get_font_features_fn;
711
712 static bool uniscribe_new_apis;
713
714 /* Verify that all the required features in FEATURES, each of whose
715 elements is a list or nil, can be found among the N feature tags in
716 FTAGS. Return 'true' if the required features are supported,
717 'false' if not. Each list in FEATURES can include an element of
718 nil, which means all the elements after it must not be in FTAGS. */
719 static bool
720 uniscribe_check_features (Lisp_Object features[2], OPENTYPE_TAG *ftags, int n)
721 {
722 int j;
723
724 for (j = 0; j < 2; j++)
725 {
726 bool negative = false;
727 Lisp_Object rest;
728
729 for (rest = features[j]; CONSP (rest); rest = XCDR (rest))
730 {
731 Lisp_Object feature = XCAR (rest);
732
733 /* The font must NOT have any of the features after nil.
734 See the doc string of 'font-spec', under ':otf'. */
735 if (NILP (feature))
736 negative = true;
737 else
738 {
739 OPENTYPE_TAG feature_tag = OTF_TAG (SNAME (feature));
740 int i;
741
742 for (i = 0; i < n; i++)
743 {
744 if (ftags[i] == feature_tag)
745 {
746 /* Test fails if we find a feature that the font
747 must NOT have. */
748 if (negative)
749 return false;
750 break;
751 }
752 }
753
754 /* Test fails if we do NOT find a feature that the font
755 should have. */
756 if (i >= n && !negative)
757 return false;
758 }
759 }
760 }
761
762 return true;
763 }
764
765 /* Check if font supports the required OTF script/language/features
766 using the Unsicribe APIs available since Windows Vista. We prefer
767 these APIs as a kind of future-proofing Emacs: they seem to
768 retrieve script tags that the old code (and also libotf) doesn't
769 seem to be able to get, e.g., some fonts that claim support for
770 "dev2" script don't show "deva", but the new APIs do report it. */
771 static int
772 uniscribe_check_otf_1 (HDC context, Lisp_Object script, Lisp_Object lang,
773 Lisp_Object features[2], int *retval)
774 {
775 SCRIPT_CACHE cache = NULL;
776 OPENTYPE_TAG tags[32], script_tag, lang_tag;
777 int max_tags = ARRAYELTS (tags);
778 int ntags, i, ret = 0;
779 HRESULT rslt;
780 Lisp_Object rest;
781
782 *retval = 0;
783
784 rslt = script_get_font_scripts_fn (context, &cache, NULL, max_tags,
785 tags, &ntags);
786 if (FAILED (rslt))
787 {
788 DebPrint (("ScriptGetFontScriptTags failed with 0x%x\n", rslt));
789 ret = -1;
790 goto no_support;
791 }
792 if (NILP (script))
793 script_tag = OTF_TAG ("DFLT");
794 else
795 script_tag = OTF_TAG (SNAME (script));
796 for (i = 0; i < ntags; i++)
797 if (tags[i] == script_tag)
798 break;
799
800 if (i >= ntags)
801 goto no_support;
802
803 if (NILP (lang))
804 lang_tag = OTF_TAG ("dflt");
805 else
806 {
807 rslt = script_get_font_languages_fn (context, &cache, NULL, script_tag,
808 max_tags, tags, &ntags);
809 if (FAILED (rslt))
810 {
811 DebPrint (("ScriptGetFontLanguageTags failed with 0x%x\n", rslt));
812 ret = -1;
813 goto no_support;
814 }
815 if (ntags == 0)
816 lang_tag = OTF_TAG ("dflt");
817 else
818 {
819 lang_tag = OTF_TAG (SNAME (lang));
820 for (i = 0; i < ntags; i++)
821 if (tags[i] == lang_tag)
822 break;
823
824 if (i >= ntags)
825 goto no_support;
826 }
827 }
828
829 if (!NILP (features[0]))
830 {
831 /* Are the 2 feature lists valid? */
832 if (!CONSP (features[0])
833 || (!NILP (features[1]) && !CONSP (features[1])))
834 goto no_support;
835 rslt = script_get_font_features_fn (context, &cache, NULL,
836 script_tag, lang_tag,
837 max_tags, tags, &ntags);
838 if (FAILED (rslt))
839 {
840 DebPrint (("ScriptGetFontFeatureTags failed with 0x%x\n", rslt));
841 ret = -1;
842 goto no_support;
843 }
844
845 /* ScriptGetFontFeatureTags doesn't let us query features
846 separately for GSUB and GPOS, so we check them all together.
847 It doesn't really matter, since the features in GSUB and GPOS
848 are disjoint, i.e. no feature can appear in both tables. */
849 if (!uniscribe_check_features (features, tags, ntags))
850 goto no_support;
851 }
852
853 ret = 1;
854 *retval = 1;
855
856 no_support:
857 if (cache)
858 ScriptFreeCache (&cache);
859 return ret;
860 }
861
862 /* Check if font supports the otf script/language/features specified.
863 OTF_SPEC is in the format
864 (script lang [(gsub_feature ...)|nil] [(gpos_feature ...)]?) */
865 int
866 uniscribe_check_otf (LOGFONT *font, Lisp_Object otf_spec)
867 {
868 Lisp_Object script, lang, rest;
869 Lisp_Object features[2];
870 DWORD feature_tables[2];
871 DWORD script_tag, default_script, lang_tag = 0;
872 struct frame * f;
873 HDC context;
874 HFONT check_font, old_font;
875 int i, retval = 0;
876 struct gcpro gcpro1;
877
878 /* Check the spec is in the right format. */
879 if (!CONSP (otf_spec) || XINT (Flength (otf_spec)) < 3)
880 return 0;
881
882 /* Break otf_spec into its components. */
883 script = XCAR (otf_spec);
884 rest = XCDR (otf_spec);
885
886 lang = XCAR (rest);
887 rest = XCDR (rest);
888
889 features[0] = XCAR (rest);
890 rest = XCDR (rest);
891 if (NILP (rest))
892 features[1] = Qnil;
893 else
894 features[1] = XCAR (rest);
895
896 /* Set up graphics context so we can use the font. */
897 f = XFRAME (selected_frame);
898 context = get_frame_dc (f);
899 check_font = CreateFontIndirect (font);
900 old_font = SelectObject (context, check_font);
901
902 /* If we are on Vista or later, use the new APIs. */
903 if (uniscribe_new_apis
904 && !w32_disable_new_uniscribe_apis
905 && uniscribe_check_otf_1 (context, script, lang, features, &retval) != -1)
906 goto done;
907
908 /* Set up tags we will use in the search. */
909 feature_tables[0] = OTF_TAG ("GSUB");
910 feature_tables[1] = OTF_TAG ("GPOS");
911 default_script = OTF_TAG ("DFLT");
912 if (NILP (script))
913 script_tag = default_script;
914 else
915 script_tag = OTF_TAG (SNAME (script));
916 if (!NILP (lang))
917 lang_tag = OTF_TAG (SNAME (lang));
918
919 /* Everything else is contained within otf_spec so should get
920 marked along with it. */
921 GCPRO1 (otf_spec);
922
923 /* Scan GSUB and GPOS tables. */
924 for (i = 0; i < 2; i++)
925 {
926 int j, n_match_features;
927 unsigned short scriptlist_table, feature_table, n_scripts;
928 unsigned short script_table, langsys_table, n_langs;
929 unsigned short feature_index, n_features;
930 DWORD tbl = feature_tables[i];
931 DWORD feature_id, *ftags;
932 Lisp_Object farray[2];
933
934 /* Skip if no features requested from this table. */
935 if (NILP (features[i]))
936 continue;
937
938 /* If features is not a cons, this font spec is messed up. */
939 if (!CONSP (features[i]))
940 goto no_support;
941
942 /* Read GPOS/GSUB header. */
943 OTF_INT16_VAL (tbl, 4, &scriptlist_table);
944 OTF_INT16_VAL (tbl, 6, &feature_table);
945 OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);
946
947 /* Find the appropriate script table. */
948 script_table = 0;
949 for (j = 0; j < n_scripts; j++)
950 {
951 DWORD script_id;
952 OTF_DWORDTAG_VAL (tbl, scriptlist_table + 2 + j * 6, &script_id);
953 if (script_id == script_tag)
954 {
955 OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
956 break;
957 }
958 #if 0 /* Causes false positives. */
959 /* If there is a DFLT script defined in the font, use it
960 if the specified script is not found. */
961 else if (script_id == default_script)
962 OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
963 #endif
964 }
965 /* If no specific or default script table was found, then this font
966 does not support the script. */
967 if (!script_table)
968 goto no_support;
969
970 /* Offset is from beginning of scriptlist_table. */
971 script_table += scriptlist_table;
972
973 /* Get default langsys table. */
974 OTF_INT16_VAL (tbl, script_table, &langsys_table);
975
976 /* If lang was specified, see if font contains a specific entry. */
977 if (!NILP (lang))
978 {
979 OTF_INT16_VAL (tbl, script_table + 2, &n_langs);
980
981 for (j = 0; j < n_langs; j++)
982 {
983 DWORD lang_id;
984 OTF_DWORDTAG_VAL (tbl, script_table + 4 + j * 6, &lang_id);
985 if (lang_id == lang_tag)
986 {
987 OTF_INT16_VAL (tbl, script_table + 8 + j * 6, &langsys_table);
988 break;
989 }
990 }
991 }
992
993 if (!langsys_table)
994 goto no_support;
995
996 /* Offset is from beginning of script table. */
997 langsys_table += script_table;
998
999 /* If there are no features to check, skip checking. */
1000 if (NILP (features[i]))
1001 continue;
1002 if (!CONSP (features[i]))
1003 goto no_support;
1004
1005 n_match_features = 0;
1006
1007 /* First get required feature (if any). */
1008 OTF_INT16_VAL (tbl, langsys_table + 2, &feature_index);
1009 if (feature_index != 0xFFFF)
1010 n_match_features = 1;
1011 OTF_INT16_VAL (tbl, langsys_table + 4, &n_features);
1012 n_match_features += n_features;
1013 USE_SAFE_ALLOCA;
1014 SAFE_NALLOCA (ftags, 1, n_match_features);
1015 int k = 0;
1016 if (feature_index != 0xFFFF)
1017 {
1018 OTF_DWORDTAG_VAL (tbl, feature_table + 2 + feature_index * 6,
1019 &feature_id);
1020 ftags[k++] = feature_id;
1021 }
1022 /* Now get all the other features. */
1023 for (j = 0; j < n_features; j++)
1024 {
1025 OTF_INT16_VAL (tbl, langsys_table + 6 + j * 2, &feature_index);
1026 OTF_DWORDTAG_VAL (tbl, feature_table + 2 + feature_index * 6,
1027 &feature_id);
1028 ftags[k++] = feature_id;
1029 }
1030
1031 /* Check the features for this table. */
1032 farray[0] = features[i];
1033 farray[1] = Qnil;
1034 if (!uniscribe_check_features (farray, ftags, n_match_features))
1035 goto no_support;
1036 SAFE_FREE ();
1037 }
1038
1039 retval = 1;
1040
1041 done:
1042 no_support:
1043 font_table_error:
1044 /* restore graphics context. */
1045 SelectObject (context, old_font);
1046 DeleteObject (check_font);
1047 release_frame_dc (f, context);
1048
1049 return retval;
1050 }
1051
1052 static Lisp_Object
1053 otf_features (HDC context, char *table)
1054 {
1055 Lisp_Object script_list = Qnil;
1056 unsigned short scriptlist_table, n_scripts, feature_table;
1057 DWORD tbl = OTF_TAG (table);
1058 int i, j, k;
1059
1060 /* Look for scripts in the table. */
1061 OTF_INT16_VAL (tbl, 4, &scriptlist_table);
1062 OTF_INT16_VAL (tbl, 6, &feature_table);
1063 OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);
1064
1065 for (i = n_scripts - 1; i >= 0; i--)
1066 {
1067 char script[5], lang[5];
1068 unsigned short script_table, lang_count, langsys_table, feature_count;
1069 Lisp_Object script_tag, langsys_list, langsys_tag, feature_list;
1070 unsigned short record_offset = scriptlist_table + 2 + i * 6;
1071 OTF_TAG_VAL (tbl, record_offset, script);
1072 OTF_INT16_VAL (tbl, record_offset + 4, &script_table);
1073
1074 /* Offset is from beginning of script table. */
1075 script_table += scriptlist_table;
1076
1077 script_tag = intern (script);
1078 langsys_list = Qnil;
1079
1080 /* Optional default lang. */
1081 OTF_INT16_VAL (tbl, script_table, &langsys_table);
1082 if (langsys_table)
1083 {
1084 /* Offset is from beginning of script table. */
1085 langsys_table += script_table;
1086
1087 langsys_tag = Qnil;
1088 feature_list = Qnil;
1089 OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
1090 for (k = feature_count - 1; k >= 0; k--)
1091 {
1092 char feature[5];
1093 unsigned short index;
1094 OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
1095 OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
1096 feature_list = Fcons (intern (feature), feature_list);
1097 }
1098 langsys_list = Fcons (Fcons (langsys_tag, feature_list),
1099 langsys_list);
1100 }
1101
1102 /* List of supported languages. */
1103 OTF_INT16_VAL (tbl, script_table + 2, &lang_count);
1104
1105 for (j = lang_count - 1; j >= 0; j--)
1106 {
1107 record_offset = script_table + 4 + j * 6;
1108 OTF_TAG_VAL (tbl, record_offset, lang);
1109 OTF_INT16_VAL (tbl, record_offset + 4, &langsys_table);
1110
1111 /* Offset is from beginning of script table. */
1112 langsys_table += script_table;
1113
1114 langsys_tag = intern (lang);
1115 feature_list = Qnil;
1116 OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
1117 for (k = feature_count - 1; k >= 0; k--)
1118 {
1119 char feature[5];
1120 unsigned short index;
1121 OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
1122 OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
1123 feature_list = Fcons (intern (feature), feature_list);
1124 }
1125 langsys_list = Fcons (Fcons (langsys_tag, feature_list),
1126 langsys_list);
1127
1128 }
1129
1130 script_list = Fcons (Fcons (script_tag, langsys_list), script_list);
1131 }
1132
1133 return script_list;
1134
1135 font_table_error:
1136 return Qnil;
1137 }
1138
1139 #undef OTF_INT16_VAL
1140 #undef OTF_TAG_VAL
1141 #undef OTF_TAG
1142
1143 \f
1144 struct font_driver uniscribe_font_driver =
1145 {
1146 LISP_INITIALLY_ZERO, /* Quniscribe */
1147 0, /* case insensitive */
1148 w32font_get_cache,
1149 uniscribe_list,
1150 uniscribe_match,
1151 uniscribe_list_family,
1152 NULL, /* free_entity */
1153 uniscribe_open,
1154 uniscribe_close,
1155 NULL, /* prepare_face */
1156 NULL, /* done_face */
1157 w32font_has_char,
1158 uniscribe_encode_char,
1159 w32font_text_extents,
1160 w32font_draw,
1161 NULL, /* get_bitmap */
1162 NULL, /* free_bitmap */
1163 NULL, /* anchor_point */
1164 uniscribe_otf_capability, /* Defined so (font-get FONTOBJ :otf) works. */
1165 NULL, /* otf_drive - use shape instead. */
1166 NULL, /* start_for_frame */
1167 NULL, /* end_for_frame */
1168 uniscribe_shape,
1169 NULL, /* check */
1170 NULL, /* get_variation_glyphs */
1171 NULL, /* filter_properties */
1172 NULL, /* cached_font_ok */
1173 };
1174
1175 /* Note that this should be called at every startup, not just when dumping,
1176 as it needs to test for the existence of the Uniscribe library. */
1177 void
1178 syms_of_w32uniscribe (void)
1179 {
1180 HMODULE uniscribe;
1181
1182 /* Don't init uniscribe when dumping */
1183 if (!initialized)
1184 return;
1185
1186 /* Don't register if uniscribe is not available. */
1187 uniscribe = GetModuleHandle ("usp10");
1188 if (!uniscribe)
1189 return;
1190
1191 uniscribe_font_driver.type = Quniscribe;
1192 uniscribe_available = 1;
1193
1194 register_font_driver (&uniscribe_font_driver, NULL);
1195
1196 script_get_font_scripts_fn = (ScriptGetFontScriptTags_Proc)
1197 GetProcAddress (uniscribe, "ScriptGetFontScriptTags");
1198 script_get_font_languages_fn = (ScriptGetFontLanguageTags_Proc)
1199 GetProcAddress (uniscribe, "ScriptGetFontLanguageTags");
1200 script_get_font_features_fn = (ScriptGetFontFeatureTags_Proc)
1201 GetProcAddress (uniscribe, "ScriptGetFontFeatureTags");
1202 if (script_get_font_scripts_fn
1203 && script_get_font_languages_fn
1204 && script_get_font_features_fn)
1205 uniscribe_new_apis = true;
1206 else
1207 uniscribe_new_apis = false;
1208 }