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