When opening new eww buffers, use buffer names based on the host name
[emacs.git] / src / w32uniscribe.c
blob1584d80f20361057799dd28adcf80617cb3bd9ab
1 /* Font backend for the Microsoft W32 Uniscribe API.
2 Copyright (C) 2008-2017 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 <http://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 dc = get_frame_dc (f);
94 EnumFontFamiliesEx (dc, &font_match_pattern,
95 (FONTENUMPROC) add_opentype_font_name_to_list,
96 (LPARAM) &list, 0);
97 release_frame_dc (f, dc);
99 return list;
102 static Lisp_Object
103 uniscribe_open (struct frame *f, Lisp_Object font_entity, int pixel_size)
105 Lisp_Object font_object
106 = font_make_object (VECSIZE (struct uniscribe_font_info),
107 font_entity, pixel_size);
108 struct uniscribe_font_info *uniscribe_font
109 = (struct uniscribe_font_info *) XFONT_OBJECT (font_object);
111 ASET (font_object, FONT_TYPE_INDEX, Quniscribe);
113 if (!w32font_open_internal (f, font_entity, pixel_size, font_object))
115 return Qnil;
118 /* Initialize the cache for this font. */
119 uniscribe_font->cache = NULL;
121 /* Uniscribe backend uses glyph indices. */
122 uniscribe_font->w32_font.glyph_idx = ETO_GLYPH_INDEX;
124 uniscribe_font->w32_font.font.driver = &uniscribe_font_driver;
126 return font_object;
129 static void
130 uniscribe_close (struct font *font)
132 struct uniscribe_font_info *uniscribe_font
133 = (struct uniscribe_font_info *) font;
135 if (uniscribe_font->cache)
136 ScriptFreeCache (&(uniscribe_font->cache));
138 w32font_close (font);
141 /* Return a list describing which scripts/languages FONT supports by
142 which GSUB/GPOS features of OpenType tables.
144 Implementation note: otf_features called by this function uses
145 GetFontData to access the font tables directly, instead of using
146 ScriptGetFontScriptTags etc. APIs even if those are available. The
147 reason is that font-get, which uses the result of this function,
148 expects a cons cell (GSUB . GPOS) where the features are reported
149 separately for these 2 OTF tables, while the Uniscribe APIs report
150 the features as a single list. There doesn't seem to be a reason
151 for returning the features in 2 separate parts, except for
152 compatibility with libotf; the features are disjoint (each can
153 appear only in one of the 2 slots), and no client of this data
154 discerns between the two slots: the few that request this data all
155 look in both slots. If use of the Uniscribe APIs ever becomes
156 necessary here, and the 2 separate slots are still required, it
157 should be possible to split the feature list the APIs return into 2
158 because each sub-list is alphabetically sorted, so the place where
159 the sorting order breaks is where the GSUB features end and GPOS
160 features begin. But for now, this is not necessary, so we leave
161 the original code in place. */
162 static Lisp_Object
163 uniscribe_otf_capability (struct font *font)
165 HDC context;
166 HFONT old_font;
167 struct frame *f;
168 Lisp_Object capability = Fcons (Qnil, Qnil);
169 Lisp_Object features;
171 f = XFRAME (selected_frame);
172 context = get_frame_dc (f);
173 old_font = SelectObject (context, FONT_HANDLE (font));
175 features = otf_features (context, "GSUB");
176 XSETCAR (capability, features);
177 features = otf_features (context, "GPOS");
178 XSETCDR (capability, features);
180 SelectObject (context, old_font);
181 release_frame_dc (f, context);
183 return capability;
186 /* Uniscribe implementation of shape for font backend.
188 Shape text in LGSTRING. See the docstring of
189 `composition-get-gstring' for the format of LGSTRING. If the
190 (N+1)th element of LGSTRING is nil, input of shaping is from the
191 1st to (N)th elements. In each input glyph, FROM, TO, CHAR, and
192 CODE are already set.
194 This function updates all fields of the input glyphs. If the
195 output glyphs (M) are more than the input glyphs (N), (N+1)th
196 through (M)th elements of LGSTRING are updated possibly by making
197 a new glyph object and storing it in LGSTRING. If (M) is greater
198 than the length of LGSTRING, nil should be returned. In that case,
199 this function is called again with a larger LGSTRING. */
200 static Lisp_Object
201 uniscribe_shape (Lisp_Object lgstring)
203 struct font *font = CHECK_FONT_GET_OBJECT (LGSTRING_FONT (lgstring));
204 struct uniscribe_font_info *uniscribe_font
205 = (struct uniscribe_font_info *) font;
206 EMACS_UINT nchars;
207 int nitems, max_items, i, max_glyphs, done_glyphs;
208 wchar_t *chars;
209 WORD *glyphs, *clusters;
210 SCRIPT_ITEM *items;
211 SCRIPT_VISATTR *attributes;
212 int *advances;
213 GOFFSET *offsets;
214 ABC overall_metrics;
215 HRESULT result;
216 struct frame * f = NULL;
217 HDC context = NULL;
218 HFONT old_font = NULL;
220 /* Get the chars from lgstring in a form we can use with uniscribe. */
221 max_glyphs = nchars = LGSTRING_GLYPH_LEN (lgstring);
222 done_glyphs = 0;
223 chars = (wchar_t *) alloca (nchars * sizeof (wchar_t));
224 /* FIXME: This loop assumes that characters in the input LGSTRING
225 are all inside the BMP. Need to encode characters beyond the BMP
226 as UTF-16. */
227 for (i = 0; i < nchars; i++)
229 /* lgstring can be bigger than the number of characters in it, in
230 the case where more glyphs are required to display those characters.
231 If that is the case, note the real number of characters. */
232 if (NILP (LGSTRING_GLYPH (lgstring, i)))
233 nchars = i;
234 else
235 chars[i] = LGLYPH_CHAR (LGSTRING_GLYPH (lgstring, i));
238 /* First we need to break up the glyph string into runs of glyphs that
239 can be treated together. First try a single run. */
240 max_items = 2;
241 items = xmalloc (sizeof (SCRIPT_ITEM) * max_items + 1);
243 while ((result = ScriptItemize (chars, nchars, max_items, NULL, NULL,
244 items, &nitems)) == E_OUTOFMEMORY)
246 /* If that wasn't enough, keep trying with one more run. */
247 max_items++;
248 items = (SCRIPT_ITEM *) xrealloc (items,
249 sizeof (SCRIPT_ITEM) * max_items + 1);
252 if (FAILED (result))
254 xfree (items);
255 return Qnil;
258 glyphs = alloca (max_glyphs * sizeof (WORD));
259 clusters = alloca (nchars * sizeof (WORD));
260 attributes = alloca (max_glyphs * sizeof (SCRIPT_VISATTR));
261 advances = alloca (max_glyphs * sizeof (int));
262 offsets = alloca (max_glyphs * sizeof (GOFFSET));
264 for (i = 0; i < nitems; i++)
266 int nglyphs, nchars_in_run;
267 nchars_in_run = items[i+1].iCharPos - items[i].iCharPos;
268 /* Force ScriptShape to generate glyphs in the same order as
269 they are in the input LGSTRING, which is in the logical
270 order. */
271 items[i].a.fLogicalOrder = 1;
273 /* Context may be NULL here, in which case the cache should be
274 used without needing to select the font. */
275 result = ScriptShape (context, &(uniscribe_font->cache),
276 chars + items[i].iCharPos, nchars_in_run,
277 max_glyphs - done_glyphs, &(items[i].a),
278 glyphs, clusters, attributes, &nglyphs);
280 if (result == E_PENDING && !context)
282 /* This assumes the selected frame is on the same display as the
283 one we are drawing. It would be better for the frame to be
284 passed in. */
285 f = XFRAME (selected_frame);
286 context = get_frame_dc (f);
287 old_font = SelectObject (context, FONT_HANDLE (font));
289 result = ScriptShape (context, &(uniscribe_font->cache),
290 chars + items[i].iCharPos, nchars_in_run,
291 max_glyphs - done_glyphs, &(items[i].a),
292 glyphs, clusters, attributes, &nglyphs);
295 if (result == E_OUTOFMEMORY)
297 /* Need a bigger lgstring. */
298 lgstring = Qnil;
299 break;
301 else if (FAILED (result))
303 /* Can't shape this run - return results so far if any. */
304 break;
306 else if (items[i].a.fNoGlyphIndex)
308 /* Glyph indices not supported by this font (or OS), means we
309 can't really do any meaningful shaping. */
310 break;
312 else
314 result = ScriptPlace (context, &(uniscribe_font->cache),
315 glyphs, nglyphs, attributes, &(items[i].a),
316 advances, offsets, &overall_metrics);
317 if (result == E_PENDING && !context)
319 /* Cache not complete... */
320 f = XFRAME (selected_frame);
321 context = get_frame_dc (f);
322 old_font = SelectObject (context, FONT_HANDLE (font));
324 result = ScriptPlace (context, &(uniscribe_font->cache),
325 glyphs, nglyphs, attributes, &(items[i].a),
326 advances, offsets, &overall_metrics);
328 if (SUCCEEDED (result))
330 int j, from, to, adj_offset = 0;
332 from = 0;
333 to = from;
335 for (j = 0; j < nglyphs; j++)
337 int lglyph_index = j + done_glyphs;
338 Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, lglyph_index);
339 ABC char_metric;
340 unsigned gl;
342 if (NILP (lglyph))
344 lglyph = LGLYPH_NEW ();
345 LGSTRING_SET_GLYPH (lgstring, lglyph_index, lglyph);
347 /* Copy to a 32-bit data type to shut up the
348 compiler warning in LGLYPH_SET_CODE about
349 comparison being always false. */
350 gl = glyphs[j];
351 LGLYPH_SET_CODE (lglyph, gl);
353 /* Detect clusters, for linking codes back to
354 characters. */
355 if (attributes[j].fClusterStart)
357 while (from < nchars_in_run && clusters[from] < j)
358 from++;
359 if (from >= nchars_in_run)
360 from = to = nchars_in_run - 1;
361 else
363 int k;
364 to = nchars_in_run - 1;
365 for (k = from + 1; k < nchars_in_run; k++)
367 if (clusters[k] > j)
369 to = k - 1;
370 break;
375 /* For RTL text, the Uniscribe shaper prepares
376 the values in ADVANCES array for layout in
377 reverse order, whereby "advance width" is
378 applied to move the pen in reverse direction
379 and _before_ drawing the glyph. Since we
380 draw glyphs in their normal left-to-right
381 order, we need to adjust the coordinates of
382 each non-base glyph in a grapheme cluster via
383 X-OFF component of the gstring's ADJUSTMENT
384 sub-vector. This loop computes, for each
385 grapheme cluster, the initial value of the
386 adjustment for the base character, which is
387 then updated for each successive glyph in the
388 grapheme cluster. */
389 if (items[i].a.fRTL)
391 int j1 = j;
393 adj_offset = 0;
394 while (j1 < nglyphs && !attributes[j1].fClusterStart)
396 adj_offset += advances[j1];
397 j1++;
402 LGLYPH_SET_CHAR (lglyph, chars[items[i].iCharPos
403 + from]);
404 LGLYPH_SET_FROM (lglyph, items[i].iCharPos + from);
405 LGLYPH_SET_TO (lglyph, items[i].iCharPos + to);
407 /* Metrics. */
408 LGLYPH_SET_WIDTH (lglyph, advances[j]);
409 LGLYPH_SET_ASCENT (lglyph, font->ascent);
410 LGLYPH_SET_DESCENT (lglyph, font->descent);
412 result = ScriptGetGlyphABCWidth (context,
413 &(uniscribe_font->cache),
414 glyphs[j], &char_metric);
415 if (result == E_PENDING && !context)
417 /* Cache incomplete... */
418 f = XFRAME (selected_frame);
419 context = get_frame_dc (f);
420 old_font = SelectObject (context, FONT_HANDLE (font));
421 result = ScriptGetGlyphABCWidth (context,
422 &(uniscribe_font->cache),
423 glyphs[j], &char_metric);
426 if (SUCCEEDED (result))
428 int lbearing = char_metric.abcA;
429 int rbearing = char_metric.abcA + char_metric.abcB;
431 LGLYPH_SET_LBEARING (lglyph, lbearing);
432 LGLYPH_SET_RBEARING (lglyph, rbearing);
434 else
436 LGLYPH_SET_LBEARING (lglyph, 0);
437 LGLYPH_SET_RBEARING (lglyph, advances[j]);
440 if (offsets[j].du || offsets[j].dv
441 /* For non-base glyphs of RTL grapheme clusters,
442 adjust the X offset even if both DU and DV
443 are zero. */
444 || (!attributes[j].fClusterStart && items[i].a.fRTL))
446 Lisp_Object vec = make_uninit_vector (3);
448 if (items[i].a.fRTL)
450 /* Empirically, it looks like Uniscribe
451 interprets DU in reverse direction for
452 RTL clusters. E.g., if we don't reverse
453 the direction, the Hebrew point HOLAM is
454 drawn above the right edge of the base
455 consonant, instead of above the left edge. */
456 ASET (vec, 0, make_number (-offsets[j].du
457 + adj_offset));
458 /* Update the adjustment value for the width
459 advance of the glyph we just emitted. */
460 adj_offset -= 2 * advances[j];
462 else
463 ASET (vec, 0, make_number (offsets[j].du + adj_offset));
464 /* In the font definition coordinate system, the
465 Y coordinate points up, while in our screen
466 coordinates Y grows downwards. So we need to
467 reverse the sign of Y-OFFSET here. */
468 ASET (vec, 1, make_number (-offsets[j].dv));
469 /* Based on what ftfont.c does... */
470 ASET (vec, 2, make_number (advances[j]));
471 LGLYPH_SET_ADJUSTMENT (lglyph, vec);
473 else
475 LGLYPH_SET_ADJUSTMENT (lglyph, Qnil);
476 /* Update the adjustment value to compensate for
477 the width of the base character. */
478 if (items[i].a.fRTL)
479 adj_offset -= advances[j];
484 done_glyphs += nglyphs;
487 xfree (items);
489 if (context)
491 SelectObject (context, old_font);
492 release_frame_dc (f, context);
495 if (NILP (lgstring))
496 return Qnil;
497 else
498 return make_number (done_glyphs);
501 /* Uniscribe implementation of encode_char for font backend.
502 Return a glyph code of FONT for character C (Unicode code point).
503 If FONT doesn't have such a glyph, return FONT_INVALID_CODE. */
504 static unsigned
505 uniscribe_encode_char (struct font *font, int c)
507 HDC context = NULL;
508 struct frame *f = NULL;
509 HFONT old_font = NULL;
510 unsigned code = FONT_INVALID_CODE;
511 wchar_t ch[2];
512 int len;
513 SCRIPT_ITEM* items;
514 int nitems;
515 struct uniscribe_font_info *uniscribe_font
516 = (struct uniscribe_font_info *)font;
518 if (c < 0x10000)
520 ch[0] = (wchar_t) c;
521 len = 1;
523 else
525 DWORD surrogate = c - 0x10000;
527 /* High surrogate: U+D800 - U+DBFF. */
528 ch[0] = 0xD800 + ((surrogate >> 10) & 0x03FF);
529 /* Low surrogate: U+DC00 - U+DFFF. */
530 ch[1] = 0xDC00 + (surrogate & 0x03FF);
531 len = 2;
534 /* Non BMP characters must be handled by the uniscribe shaping
535 engine as GDI functions (except blindly displaying lines of
536 Unicode text) and the promising looking ScriptGetCMap do not
537 convert surrogate pairs to glyph indexes correctly. */
539 items = (SCRIPT_ITEM *) alloca (sizeof (SCRIPT_ITEM) * 2 + 1);
540 if (SUCCEEDED (ScriptItemize (ch, len, 2, NULL, NULL, items, &nitems)))
542 HRESULT result;
543 /* Surrogates seem to need 2 here, even though only one glyph is
544 returned. Indic characters can also produce 2 or more glyphs for
545 a single code point, but they need to use uniscribe_shape
546 above for correct display. */
547 WORD glyphs[2], clusters[2];
548 SCRIPT_VISATTR attrs[2];
549 int nglyphs;
551 /* Force ScriptShape to generate glyphs in the logical
552 order. */
553 items[0].a.fLogicalOrder = 1;
555 result = ScriptShape (context, &(uniscribe_font->cache),
556 ch, len, 2, &(items[0].a),
557 glyphs, clusters, attrs, &nglyphs);
559 if (result == E_PENDING)
561 /* Use selected frame until API is updated to pass
562 the frame. */
563 f = XFRAME (selected_frame);
564 context = get_frame_dc (f);
565 old_font = SelectObject (context, FONT_HANDLE (font));
566 result = ScriptShape (context, &(uniscribe_font->cache),
567 ch, len, 2, &(items[0].a),
568 glyphs, clusters, attrs, &nglyphs);
571 if (SUCCEEDED (result) && nglyphs == 1)
573 /* Some fonts return .notdef glyphs instead of failing.
574 (TrueType spec reserves glyph code 0 for .notdef) */
575 if (glyphs[0])
576 code = glyphs[0];
578 else if (SUCCEEDED (result) || result == E_OUTOFMEMORY)
580 /* This character produces zero or more than one glyph
581 when shaped. But we still need the return from here
582 to be valid for the shaping engine to be invoked
583 later. */
584 result = ScriptGetCMap (context, &(uniscribe_font->cache),
585 ch, len, 0, glyphs);
586 if (SUCCEEDED (result) && glyphs[0])
587 code = glyphs[0];
591 if (context)
593 SelectObject (context, old_font);
594 release_frame_dc (f, context);
597 return code;
601 Shared with w32font:
602 Lisp_Object uniscribe_get_cache (Lisp_Object frame);
603 void uniscribe_free_entity (Lisp_Object font_entity);
604 int uniscribe_has_char (Lisp_Object entity, int c);
605 void uniscribe_text_extents (struct font *font, unsigned *code,
606 int nglyphs, struct font_metrics *metrics);
607 int uniscribe_draw (struct glyph_string *s, int from, int to,
608 int x, int y, int with_background);
610 Unused:
611 int uniscribe_prepare_face (struct frame *f, struct face *face);
612 void uniscribe_done_face (struct frame *f, struct face *face);
613 int uniscribe_get_bitmap (struct font *font, unsigned code,
614 struct font_bitmap *bitmap, int bits_per_pixel);
615 void uniscribe_free_bitmap (struct font *font, struct font_bitmap *bitmap);
616 int uniscribe_anchor_point (struct font *font, unsigned code,
617 int index, int *x, int *y);
618 int uniscribe_start_for_frame (struct frame *f);
619 int uniscribe_end_for_frame (struct frame *f);
624 /* Callback function for EnumFontFamiliesEx.
625 Adds the name of opentype fonts to a Lisp list (passed in as the
626 lParam arg). */
627 static int CALLBACK ALIGN_STACK
628 add_opentype_font_name_to_list (ENUMLOGFONTEX *logical_font,
629 NEWTEXTMETRICEX *physical_font,
630 DWORD font_type, LPARAM list_object)
632 Lisp_Object* list = (Lisp_Object *) list_object;
633 Lisp_Object family;
635 /* Skip vertical fonts (intended only for printing) */
636 if (logical_font->elfLogFont.lfFaceName[0] == '@')
637 return 1;
639 /* Skip non opentype fonts. Count old truetype fonts as opentype,
640 as some of them do contain GPOS and GSUB data that Uniscribe
641 can make use of. */
642 if (!(physical_font->ntmTm.ntmFlags & NTMFLAGS_OPENTYPE)
643 && font_type != TRUETYPE_FONTTYPE)
644 return 1;
646 /* Skip fonts that have no Unicode coverage. */
647 if (!physical_font->ntmFontSig.fsUsb[3]
648 && !physical_font->ntmFontSig.fsUsb[2]
649 && !physical_font->ntmFontSig.fsUsb[1]
650 && !(physical_font->ntmFontSig.fsUsb[0] & 0x3fffffff))
651 return 1;
653 family = intern_font_name (logical_font->elfLogFont.lfFaceName);
654 if (! memq_no_quit (family, *list))
655 *list = Fcons (family, *list);
657 return 1;
661 /* :otf property handling.
662 Since the necessary Uniscribe APIs for getting font tag information
663 are only available in Vista, we may need to parse the font data directly
664 according to the OpenType Specification. */
666 /* Push into DWORD backwards to cope with endianness. */
667 #define OTF_TAG(STR) \
668 ((STR[3] << 24) | (STR[2] << 16) | (STR[1] << 8) | STR[0])
670 #define OTF_INT16_VAL(TABLE, OFFSET, PTR) \
671 do { \
672 BYTE temp, data[2]; \
673 if (GetFontData (context, TABLE, OFFSET, data, 2) != 2) \
674 goto font_table_error; \
675 temp = data[0], data[0] = data[1], data[1] = temp; \
676 memcpy (PTR, data, 2); \
677 } while (0)
679 /* Do not reverse the bytes, because we will compare with a OTF_TAG value
680 that has them reversed already. */
681 #define OTF_DWORDTAG_VAL(TABLE, OFFSET, PTR) \
682 do { \
683 if (GetFontData (context, TABLE, OFFSET, PTR, 4) != 4) \
684 goto font_table_error; \
685 } while (0)
687 #define OTF_TAG_VAL(TABLE, OFFSET, STR) \
688 do { \
689 if (GetFontData (context, TABLE, OFFSET, STR, 4) != 4) \
690 goto font_table_error; \
691 STR[4] = '\0'; \
692 } while (0)
694 #define SNAME(VAL) SSDATA (SYMBOL_NAME (VAL))
696 /* Uniscribe APIs available only since Windows Vista. */
697 typedef HRESULT (WINAPI *ScriptGetFontScriptTags_Proc)
698 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, int, OPENTYPE_TAG *, int *);
700 typedef HRESULT (WINAPI *ScriptGetFontLanguageTags_Proc)
701 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, OPENTYPE_TAG, int, OPENTYPE_TAG *, int *);
703 typedef HRESULT (WINAPI *ScriptGetFontFeatureTags_Proc)
704 (HDC, SCRIPT_CACHE *, SCRIPT_ANALYSIS *, OPENTYPE_TAG, OPENTYPE_TAG, int, OPENTYPE_TAG *, int *);
706 ScriptGetFontScriptTags_Proc script_get_font_scripts_fn;
707 ScriptGetFontLanguageTags_Proc script_get_font_languages_fn;
708 ScriptGetFontFeatureTags_Proc script_get_font_features_fn;
710 static bool uniscribe_new_apis;
712 /* Verify that all the required features in FEATURES, each of whose
713 elements is a list or nil, can be found among the N feature tags in
714 FTAGS. Return 'true' if the required features are supported,
715 'false' if not. Each list in FEATURES can include an element of
716 nil, which means all the elements after it must not be in FTAGS. */
717 static bool
718 uniscribe_check_features (Lisp_Object features[2], OPENTYPE_TAG *ftags, int n)
720 int j;
722 for (j = 0; j < 2; j++)
724 bool negative = false;
725 Lisp_Object rest;
727 for (rest = features[j]; CONSP (rest); rest = XCDR (rest))
729 Lisp_Object feature = XCAR (rest);
731 /* The font must NOT have any of the features after nil.
732 See the doc string of 'font-spec', under ':otf'. */
733 if (NILP (feature))
734 negative = true;
735 else
737 OPENTYPE_TAG feature_tag = OTF_TAG (SNAME (feature));
738 int i;
740 for (i = 0; i < n; i++)
742 if (ftags[i] == feature_tag)
744 /* Test fails if we find a feature that the font
745 must NOT have. */
746 if (negative)
747 return false;
748 break;
752 /* Test fails if we do NOT find a feature that the font
753 should have. */
754 if (i >= n && !negative)
755 return false;
760 return true;
763 /* Check if font supports the required OTF script/language/features
764 using the Unsicribe APIs available since Windows Vista. We prefer
765 these APIs as a kind of future-proofing Emacs: they seem to
766 retrieve script tags that the old code (and also libotf) doesn't
767 seem to be able to get, e.g., some fonts that claim support for
768 "dev2" script don't show "deva", but the new APIs do report it. */
769 static int
770 uniscribe_check_otf_1 (HDC context, Lisp_Object script, Lisp_Object lang,
771 Lisp_Object features[2], int *retval)
773 SCRIPT_CACHE cache = NULL;
774 OPENTYPE_TAG tags[32], script_tag, lang_tag;
775 int max_tags = ARRAYELTS (tags);
776 int ntags, i, ret = 0;
777 HRESULT rslt;
779 *retval = 0;
781 rslt = script_get_font_scripts_fn (context, &cache, NULL, max_tags,
782 tags, &ntags);
783 if (FAILED (rslt))
785 DebPrint (("ScriptGetFontScriptTags failed with 0x%x\n", rslt));
786 ret = -1;
787 goto no_support;
789 if (NILP (script))
790 script_tag = OTF_TAG ("DFLT");
791 else
792 script_tag = OTF_TAG (SNAME (script));
793 for (i = 0; i < ntags; i++)
794 if (tags[i] == script_tag)
795 break;
797 if (i >= ntags)
798 goto no_support;
800 if (NILP (lang))
801 lang_tag = OTF_TAG ("dflt");
802 else
804 rslt = script_get_font_languages_fn (context, &cache, NULL, script_tag,
805 max_tags, tags, &ntags);
806 if (FAILED (rslt))
808 DebPrint (("ScriptGetFontLanguageTags failed with 0x%x\n", rslt));
809 ret = -1;
810 goto no_support;
812 if (ntags == 0)
813 lang_tag = OTF_TAG ("dflt");
814 else
816 lang_tag = OTF_TAG (SNAME (lang));
817 for (i = 0; i < ntags; i++)
818 if (tags[i] == lang_tag)
819 break;
821 if (i >= ntags)
822 goto no_support;
826 if (!NILP (features[0]))
828 /* Are the 2 feature lists valid? */
829 if (!CONSP (features[0])
830 || (!NILP (features[1]) && !CONSP (features[1])))
831 goto no_support;
832 rslt = script_get_font_features_fn (context, &cache, NULL,
833 script_tag, lang_tag,
834 max_tags, tags, &ntags);
835 if (FAILED (rslt))
837 DebPrint (("ScriptGetFontFeatureTags failed with 0x%x\n", rslt));
838 ret = -1;
839 goto no_support;
842 /* ScriptGetFontFeatureTags doesn't let us query features
843 separately for GSUB and GPOS, so we check them all together.
844 It doesn't really matter, since the features in GSUB and GPOS
845 are disjoint, i.e. no feature can appear in both tables. */
846 if (!uniscribe_check_features (features, tags, ntags))
847 goto no_support;
850 ret = 1;
851 *retval = 1;
853 no_support:
854 if (cache)
855 ScriptFreeCache (&cache);
856 return ret;
859 /* Check if font supports the otf script/language/features specified.
860 OTF_SPEC is in the format
861 (script lang [(gsub_feature ...)|nil] [(gpos_feature ...)]?) */
863 uniscribe_check_otf (LOGFONT *font, Lisp_Object otf_spec)
865 Lisp_Object script, lang, rest;
866 Lisp_Object features[2];
867 DWORD feature_tables[2];
868 DWORD script_tag, default_script, lang_tag = 0;
869 struct frame * f;
870 HDC context;
871 HFONT check_font, old_font;
872 int i, retval = 0;
874 /* Check the spec is in the right format. */
875 if (!CONSP (otf_spec) || XINT (Flength (otf_spec)) < 3)
876 return 0;
878 /* Break otf_spec into its components. */
879 script = XCAR (otf_spec);
880 rest = XCDR (otf_spec);
882 lang = XCAR (rest);
883 rest = XCDR (rest);
885 features[0] = XCAR (rest);
886 rest = XCDR (rest);
887 if (NILP (rest))
888 features[1] = Qnil;
889 else
890 features[1] = XCAR (rest);
892 /* Set up graphics context so we can use the font. */
893 f = XFRAME (selected_frame);
894 context = get_frame_dc (f);
895 check_font = CreateFontIndirect (font);
896 old_font = SelectObject (context, check_font);
898 /* If we are on Vista or later, use the new APIs. */
899 if (uniscribe_new_apis
900 && !w32_disable_new_uniscribe_apis
901 && uniscribe_check_otf_1 (context, script, lang, features, &retval) != -1)
902 goto done;
904 /* Set up tags we will use in the search. */
905 feature_tables[0] = OTF_TAG ("GSUB");
906 feature_tables[1] = OTF_TAG ("GPOS");
907 default_script = OTF_TAG ("DFLT");
908 if (NILP (script))
909 script_tag = default_script;
910 else
911 script_tag = OTF_TAG (SNAME (script));
912 if (!NILP (lang))
913 lang_tag = OTF_TAG (SNAME (lang));
915 /* Scan GSUB and GPOS tables. */
916 for (i = 0; i < 2; i++)
918 int j, n_match_features;
919 unsigned short scriptlist_table, feature_table, n_scripts;
920 unsigned short script_table, langsys_table, n_langs;
921 unsigned short feature_index, n_features;
922 DWORD tbl = feature_tables[i];
923 DWORD feature_id, *ftags;
924 Lisp_Object farray[2];
926 /* Skip if no features requested from this table. */
927 if (NILP (features[i]))
928 continue;
930 /* If features is not a cons, this font spec is messed up. */
931 if (!CONSP (features[i]))
932 goto no_support;
934 /* Read GPOS/GSUB header. */
935 OTF_INT16_VAL (tbl, 4, &scriptlist_table);
936 OTF_INT16_VAL (tbl, 6, &feature_table);
937 OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);
939 /* Find the appropriate script table. */
940 script_table = 0;
941 for (j = 0; j < n_scripts; j++)
943 DWORD script_id;
944 OTF_DWORDTAG_VAL (tbl, scriptlist_table + 2 + j * 6, &script_id);
945 if (script_id == script_tag)
947 OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
948 break;
950 #if 0 /* Causes false positives. */
951 /* If there is a DFLT script defined in the font, use it
952 if the specified script is not found. */
953 else if (script_id == default_script)
954 OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
955 #endif
957 /* If no specific or default script table was found, then this font
958 does not support the script. */
959 if (!script_table)
960 goto no_support;
962 /* Offset is from beginning of scriptlist_table. */
963 script_table += scriptlist_table;
965 /* Get default langsys table. */
966 OTF_INT16_VAL (tbl, script_table, &langsys_table);
968 /* If lang was specified, see if font contains a specific entry. */
969 if (!NILP (lang))
971 OTF_INT16_VAL (tbl, script_table + 2, &n_langs);
973 for (j = 0; j < n_langs; j++)
975 DWORD lang_id;
976 OTF_DWORDTAG_VAL (tbl, script_table + 4 + j * 6, &lang_id);
977 if (lang_id == lang_tag)
979 OTF_INT16_VAL (tbl, script_table + 8 + j * 6, &langsys_table);
980 break;
985 if (!langsys_table)
986 goto no_support;
988 /* Offset is from beginning of script table. */
989 langsys_table += script_table;
991 /* If there are no features to check, skip checking. */
992 if (NILP (features[i]))
993 continue;
994 if (!CONSP (features[i]))
995 goto no_support;
997 n_match_features = 0;
999 /* First get required feature (if any). */
1000 OTF_INT16_VAL (tbl, langsys_table + 2, &feature_index);
1001 if (feature_index != 0xFFFF)
1002 n_match_features = 1;
1003 OTF_INT16_VAL (tbl, langsys_table + 4, &n_features);
1004 n_match_features += n_features;
1005 USE_SAFE_ALLOCA;
1006 SAFE_NALLOCA (ftags, 1, n_match_features);
1007 int k = 0;
1008 if (feature_index != 0xFFFF)
1010 OTF_DWORDTAG_VAL (tbl, feature_table + 2 + feature_index * 6,
1011 &feature_id);
1012 ftags[k++] = feature_id;
1014 /* Now get all the other features. */
1015 for (j = 0; j < n_features; j++)
1017 OTF_INT16_VAL (tbl, langsys_table + 6 + j * 2, &feature_index);
1018 OTF_DWORDTAG_VAL (tbl, feature_table + 2 + feature_index * 6,
1019 &feature_id);
1020 ftags[k++] = feature_id;
1023 /* Check the features for this table. */
1024 farray[0] = features[i];
1025 farray[1] = Qnil;
1026 if (!uniscribe_check_features (farray, ftags, n_match_features))
1027 goto no_support;
1028 SAFE_FREE ();
1031 retval = 1;
1033 done:
1034 no_support:
1035 font_table_error:
1036 /* restore graphics context. */
1037 SelectObject (context, old_font);
1038 DeleteObject (check_font);
1039 release_frame_dc (f, context);
1041 return retval;
1044 static Lisp_Object
1045 otf_features (HDC context, const char *table)
1047 Lisp_Object script_list = Qnil;
1048 unsigned short scriptlist_table, n_scripts, feature_table;
1049 DWORD tbl = OTF_TAG (table);
1050 int i, j, k;
1052 /* Look for scripts in the table. */
1053 OTF_INT16_VAL (tbl, 4, &scriptlist_table);
1054 OTF_INT16_VAL (tbl, 6, &feature_table);
1055 OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);
1057 for (i = n_scripts - 1; i >= 0; i--)
1059 char script[5], lang[5];
1060 unsigned short script_table, lang_count, langsys_table, feature_count;
1061 Lisp_Object script_tag, langsys_list, langsys_tag, feature_list;
1062 unsigned short record_offset = scriptlist_table + 2 + i * 6;
1063 OTF_TAG_VAL (tbl, record_offset, script);
1064 OTF_INT16_VAL (tbl, record_offset + 4, &script_table);
1066 /* Offset is from beginning of script table. */
1067 script_table += scriptlist_table;
1069 script_tag = intern (script);
1070 langsys_list = Qnil;
1072 /* Optional default lang. */
1073 OTF_INT16_VAL (tbl, script_table, &langsys_table);
1074 if (langsys_table)
1076 /* Offset is from beginning of script table. */
1077 langsys_table += script_table;
1079 langsys_tag = Qnil;
1080 feature_list = Qnil;
1081 OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
1082 for (k = feature_count - 1; k >= 0; k--)
1084 char feature[5];
1085 unsigned short index;
1086 OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
1087 OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
1088 feature_list = Fcons (intern (feature), feature_list);
1090 langsys_list = Fcons (Fcons (langsys_tag, feature_list),
1091 langsys_list);
1094 /* List of supported languages. */
1095 OTF_INT16_VAL (tbl, script_table + 2, &lang_count);
1097 for (j = lang_count - 1; j >= 0; j--)
1099 record_offset = script_table + 4 + j * 6;
1100 OTF_TAG_VAL (tbl, record_offset, lang);
1101 OTF_INT16_VAL (tbl, record_offset + 4, &langsys_table);
1103 /* Offset is from beginning of script table. */
1104 langsys_table += script_table;
1106 langsys_tag = intern (lang);
1107 feature_list = Qnil;
1108 OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
1109 for (k = feature_count - 1; k >= 0; k--)
1111 char feature[5];
1112 unsigned short index;
1113 OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
1114 OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
1115 feature_list = Fcons (intern (feature), feature_list);
1117 langsys_list = Fcons (Fcons (langsys_tag, feature_list),
1118 langsys_list);
1122 script_list = Fcons (Fcons (script_tag, langsys_list), script_list);
1125 return script_list;
1127 font_table_error:
1128 return Qnil;
1131 #undef OTF_INT16_VAL
1132 #undef OTF_TAG_VAL
1133 #undef OTF_TAG
1136 struct font_driver uniscribe_font_driver =
1138 LISPSYM_INITIALLY (Quniscribe),
1139 0, /* case insensitive */
1140 w32font_get_cache,
1141 uniscribe_list,
1142 uniscribe_match,
1143 uniscribe_list_family,
1144 NULL, /* free_entity */
1145 uniscribe_open,
1146 uniscribe_close,
1147 NULL, /* prepare_face */
1148 NULL, /* done_face */
1149 w32font_has_char,
1150 uniscribe_encode_char,
1151 w32font_text_extents,
1152 w32font_draw,
1153 NULL, /* get_bitmap */
1154 NULL, /* free_bitmap */
1155 NULL, /* anchor_point */
1156 uniscribe_otf_capability, /* Defined so (font-get FONTOBJ :otf) works. */
1157 NULL, /* otf_drive - use shape instead. */
1158 NULL, /* start_for_frame */
1159 NULL, /* end_for_frame */
1160 uniscribe_shape,
1161 NULL, /* check */
1162 NULL, /* get_variation_glyphs */
1163 NULL, /* filter_properties */
1164 NULL, /* cached_font_ok */
1167 /* Note that this should be called at every startup, not just when dumping,
1168 as it needs to test for the existence of the Uniscribe library. */
1169 void syms_of_w32uniscribe (void);
1171 void
1172 syms_of_w32uniscribe (void)
1174 HMODULE uniscribe;
1176 /* Don't init uniscribe when dumping */
1177 if (!initialized)
1178 return;
1180 /* Don't register if uniscribe is not available. */
1181 uniscribe = GetModuleHandle ("usp10");
1182 if (!uniscribe)
1183 return;
1185 uniscribe_available = 1;
1187 register_font_driver (&uniscribe_font_driver, NULL);
1189 script_get_font_scripts_fn = (ScriptGetFontScriptTags_Proc)
1190 GetProcAddress (uniscribe, "ScriptGetFontScriptTags");
1191 script_get_font_languages_fn = (ScriptGetFontLanguageTags_Proc)
1192 GetProcAddress (uniscribe, "ScriptGetFontLanguageTags");
1193 script_get_font_features_fn = (ScriptGetFontFeatureTags_Proc)
1194 GetProcAddress (uniscribe, "ScriptGetFontFeatureTags");
1195 if (script_get_font_scripts_fn
1196 && script_get_font_languages_fn
1197 && script_get_font_features_fn)
1198 uniscribe_new_apis = true;
1199 else
1200 uniscribe_new_apis = false;