w32uniscribe.c 30.4 KB
Newer Older
1
/* Font backend for the Microsoft W32 Uniscribe API.
Paul Eggert's avatar
Paul Eggert committed
2
   Copyright (C) 2008-2015 Free Software Foundation, Inc.
3 4 5

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 9
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
10 11 12 13 14 15 16

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

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 21 22 23 24


#include <config.h>
/* Override API version - Uniscribe is only available as standard since
   Windows 2000, though most users of older systems will have it
   since it installs with Internet Explorer 5.0 and other software.
   We only enable the feature if it is available, so there is no chance
Juanma Barranquero's avatar
Juanma Barranquero committed
25
   of calling non-existent functions.  */
26 27 28 29 30 31 32 33 34 35 36
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x500
#include <windows.h>
#include <usp10.h>

#include "lisp.h"
#include "w32term.h"
#include "frame.h"
#include "dispextern.h"
#include "character.h"
#include "charset.h"
37
#include "composite.h"
38 39 40 41 42 43 44 45 46 47 48 49 50
#include "fontset.h"
#include "font.h"
#include "w32font.h"

struct uniscribe_font_info
{
  struct w32font_info w32_font;
  SCRIPT_CACHE cache;
};

int uniscribe_available = 0;

/* EnumFontFamiliesEx callback.  */
51 52 53
static int CALLBACK ALIGN_STACK add_opentype_font_name_to_list (ENUMLOGFONTEX *,
								NEWTEXTMETRICEX *,
								DWORD, LPARAM);
54 55 56 57
/* Used by uniscribe_otf_capability.  */
static Lisp_Object otf_features (HDC context, char *table);

static int
58
memq_no_quit (Lisp_Object elt, Lisp_Object list)
59 60 61 62 63 64 65 66 67
{
  while (CONSP (list) && ! EQ (XCAR (list), elt))
    list = XCDR (list);
  return (CONSP (list));
}


/* Font backend interface implementation.  */
static Lisp_Object
Dmitry Antipov's avatar
Dmitry Antipov committed
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
Dmitry Antipov's avatar
Dmitry Antipov committed
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
Dmitry Antipov's avatar
Dmitry Antipov committed
84
uniscribe_list_family (struct frame *f)
85 86 87 88 89
{
  Lisp_Object list = Qnil;
  LOGFONT font_match_pattern;
  HDC dc;

90
  memset (&font_match_pattern, 0, sizeof (font_match_pattern));
91 92 93 94 95 96 97 98 99 100 101 102 103
  /* Limit enumerated fonts to outline fonts to save time.  */
  font_match_pattern.lfOutPrecision = OUT_OUTLINE_PRECIS;

  dc = get_frame_dc (f);

  EnumFontFamiliesEx (dc, &font_match_pattern,
                      (FONTENUMPROC) add_opentype_font_name_to_list,
                      (LPARAM) &list, 0);
  release_frame_dc (f, dc);

  return list;
}

104
static Lisp_Object
Dmitry Antipov's avatar
Dmitry Antipov committed
105
uniscribe_open (struct frame *f, Lisp_Object font_entity, int pixel_size)
106
{
107
  Lisp_Object font_object
108 109
    = font_make_object (VECSIZE (struct uniscribe_font_info),
			font_entity, pixel_size);
110
  struct uniscribe_font_info *uniscribe_font
111
    = (struct uniscribe_font_info *) XFONT_OBJECT (font_object);
112

113 114
  ASET (font_object, FONT_TYPE_INDEX, Quniscribe);

115
  if (!w32font_open_internal (f, font_entity, pixel_size, font_object))
116
    {
117
      return Qnil;
118 119 120 121
    }

  /* Initialize the cache for this font.  */
  uniscribe_font->cache = NULL;
122

123 124 125
  /* Uniscribe backend uses glyph indices.  */
  uniscribe_font->w32_font.glyph_idx = ETO_GLYPH_INDEX;

126 127
  uniscribe_font->w32_font.font.driver = &uniscribe_font_driver;

128
  return font_object;
129 130 131
}

static void
132
uniscribe_close (struct font *font)
133 134 135 136 137
{
  struct uniscribe_font_info *uniscribe_font
    = (struct uniscribe_font_info *) font;

  if (uniscribe_font->cache)
138
    ScriptFreeCache (&(uniscribe_font->cache));
139

140
  w32font_close (font);
141 142 143 144 145
}

/* Return a list describing which scripts/languages FONT supports by
   which GSUB/GPOS features of OpenType tables.  */
static Lisp_Object
146
uniscribe_otf_capability (struct font *font)
147 148 149 150 151 152 153 154 155
{
  HDC context;
  HFONT old_font;
  struct frame *f;
  Lisp_Object capability = Fcons (Qnil, Qnil);
  Lisp_Object features;

  f = XFRAME (selected_frame);
  context = get_frame_dc (f);
156
  old_font = SelectObject (context, FONT_HANDLE (font));
157 158 159 160 161 162 163 164 165 166 167 168 169 170

  features = otf_features (context, "GSUB");
  XSETCAR (capability, features);
  features = otf_features (context, "GPOS");
  XSETCDR (capability, features);

  SelectObject (context, old_font);
  release_frame_dc (f, context);

  return capability;
}

/* Uniscribe implementation of shape for font backend.

171 172 173 174 175
   Shape text in LGSTRING.  See the docstring of
   `composition-get-gstring' for the format of LGSTRING.  If the
   (N+1)th element of LGSTRING is nil, input of shaping is from the
   1st to (N)th elements.  In each input glyph, FROM, TO, CHAR, and
   CODE are already set.
176 177 178 179 180

   This function updates all fields of the input glyphs.  If the
   output glyphs (M) are more than the input glyphs (N), (N+1)th
   through (M)th elements of LGSTRING are updated possibly by making
   a new glyph object and storing it in LGSTRING.  If (M) is greater
181 182
   than the length of LGSTRING, nil should be returned.  In that case,
   this function is called again with a larger LGSTRING.  */
183
static Lisp_Object
184
uniscribe_shape (Lisp_Object lgstring)
185
{
186 187 188
  struct font *font = CHECK_FONT_GET_OBJECT (LGSTRING_FONT (lgstring));
  struct uniscribe_font_info *uniscribe_font
    = (struct uniscribe_font_info *) font;
189
  EMACS_UINT nchars;
190
  int nitems, max_items, i, max_glyphs, done_glyphs;
191 192 193 194 195 196 197 198
  wchar_t *chars;
  WORD *glyphs, *clusters;
  SCRIPT_ITEM *items;
  SCRIPT_VISATTR *attributes;
  int *advances;
  GOFFSET *offsets;
  ABC overall_metrics;
  HRESULT result;
199 200 201
  struct frame * f = NULL;
  HDC context = NULL;
  HFONT old_font = NULL;
202 203

  /* Get the chars from lgstring in a form we can use with uniscribe.  */
204
  max_glyphs = nchars = LGSTRING_GLYPH_LEN (lgstring);
205
  done_glyphs = 0;
206
  chars = (wchar_t *) alloca (nchars * sizeof (wchar_t));
207 208 209
  /* FIXME: This loop assumes that characters in the input LGSTRING
     are all inside the BMP.  Need to encode characters beyond the BMP
     as UTF-16.  */
210 211 212 213 214 215 216 217 218 219 220 221 222 223
  for (i = 0; i < nchars; i++)
    {
      /* lgstring can be bigger than the number of characters in it, in
	 the case where more glyphs are required to display those characters.
         If that is the case, note the real number of characters.  */
      if (NILP (LGSTRING_GLYPH (lgstring, i)))
	nchars = i;
      else
	chars[i] = LGLYPH_CHAR (LGSTRING_GLYPH (lgstring, i));
    }

  /* First we need to break up the glyph string into runs of glyphs that
     can be treated together.  First try a single run.  */
  max_items = 2;
Dmitry Antipov's avatar
Dmitry Antipov committed
224
  items = xmalloc (sizeof (SCRIPT_ITEM) * max_items + 1);
225

226
  while ((result = ScriptItemize (chars, nchars, max_items, NULL, NULL,
227 228 229 230 231
				  items, &nitems)) == E_OUTOFMEMORY)
    {
      /* If that wasn't enough, keep trying with one more run.  */
      max_items++;
      items = (SCRIPT_ITEM *) xrealloc (items,
232
					sizeof (SCRIPT_ITEM) * max_items + 1);
233 234
    }

235
  if (FAILED (result))
236 237 238 239 240 241 242 243 244 245 246 247 248
    {
      xfree (items);
      return Qnil;
    }

  glyphs = alloca (max_glyphs * sizeof (WORD));
  clusters = alloca (nchars * sizeof (WORD));
  attributes = alloca (max_glyphs * sizeof (SCRIPT_VISATTR));
  advances = alloca (max_glyphs * sizeof (int));
  offsets = alloca (max_glyphs * sizeof (GOFFSET));

  for (i = 0; i < nitems; i++)
    {
249
      int nglyphs, nchars_in_run;
250
      nchars_in_run = items[i+1].iCharPos - items[i].iCharPos;
251 252 253 254
      /* Force ScriptShape to generate glyphs in the same order as
	 they are in the input LGSTRING, which is in the logical
	 order.  */
      items[i].a.fLogicalOrder = 1;
255

256 257
      /* Context may be NULL here, in which case the cache should be
         used without needing to select the font.  */
258 259 260 261
      result = ScriptShape (context, &(uniscribe_font->cache),
			    chars + items[i].iCharPos, nchars_in_run,
			    max_glyphs - done_glyphs, &(items[i].a),
			    glyphs, clusters, attributes, &nglyphs);
262 263 264 265 266 267 268 269

      if (result == E_PENDING && !context)
	{
	  /* This assumes the selected frame is on the same display as the
	     one we are drawing.  It would be better for the frame to be
	     passed in.  */
	  f = XFRAME (selected_frame);
	  context = get_frame_dc (f);
270
	  old_font = SelectObject (context, FONT_HANDLE (font));
271 272 273 274 275 276 277

	  result = ScriptShape (context, &(uniscribe_font->cache),
				chars + items[i].iCharPos, nchars_in_run,
				max_glyphs - done_glyphs, &(items[i].a),
				glyphs, clusters, attributes, &nglyphs);
	}

278 279 280 281 282 283
      if (result == E_OUTOFMEMORY)
	{
	  /* Need a bigger lgstring.  */
	  lgstring = Qnil;
	  break;
	}
284
      else if (FAILED (result))
285 286 287 288
	{
	  /* Can't shape this run - return results so far if any.  */
	  break;
	}
289 290 291 292 293 294
      else if (items[i].a.fNoGlyphIndex)
	{
	  /* Glyph indices not supported by this font (or OS), means we
	     can't really do any meaningful shaping.  */
	  break;
	}
295 296 297 298 299
      else
	{
	  result = ScriptPlace (context, &(uniscribe_font->cache),
				glyphs, nglyphs, attributes, &(items[i].a),
				advances, offsets, &overall_metrics);
300 301 302 303 304
	  if (result == E_PENDING && !context)
	    {
	      /* Cache not complete...  */
	      f = XFRAME (selected_frame);
	      context = get_frame_dc (f);
305
	      old_font = SelectObject (context, FONT_HANDLE (font));
306 307 308 309 310 311

	      result = ScriptPlace (context, &(uniscribe_font->cache),
				    glyphs, nglyphs, attributes, &(items[i].a),
				    advances, offsets, &overall_metrics);
	    }
          if (SUCCEEDED (result))
312
	    {
313 314
	      int j, from, to, adj_offset = 0;

315
	      from = 0;
316
	      to = from;
317 318 319 320 321

	      for (j = 0; j < nglyphs; j++)
		{
		  int lglyph_index = j + done_glyphs;
		  Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, lglyph_index);
322
		  ABC char_metric;
323
		  unsigned gl;
324 325 326

		  if (NILP (lglyph))
		    {
327
		      lglyph = LGLYPH_NEW ();
328 329
		      LGSTRING_SET_GLYPH (lgstring, lglyph_index, lglyph);
		    }
330 331 332 333 334
		  /* Copy to a 32-bit data type to shut up the
		     compiler warning in LGLYPH_SET_CODE about
		     comparison being always false.  */
		  gl = glyphs[j];
		  LGLYPH_SET_CODE (lglyph, gl);
335

336 337
		  /* Detect clusters, for linking codes back to
		     characters.  */
338
		  if (attributes[j].fClusterStart)
339
		    {
340 341 342
		      while (from < nchars_in_run && clusters[from] < j)
			from++;
		      if (from >= nchars_in_run)
343
			from = to = nchars_in_run - 1;
344 345 346
		      else
			{
			  int k;
347 348
			  to = nchars_in_run - 1;
			  for (k = from + 1; k < nchars_in_run; k++)
349 350 351
			    {
			      if (clusters[k] > j)
				{
352
				  to = k - 1;
353 354 355 356
				  break;
				}
			    }
			}
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

		      /* For RTL text, the Uniscribe shaper prepares
			 the values in ADVANCES array for layout in
			 reverse order, whereby "advance width" is
			 applied to move the pen in reverse direction
			 and _before_ drawing the glyph.  Since we
			 draw glyphs in their normal left-to-right
			 order, we need to adjust the coordinates of
			 each non-base glyph in a grapheme cluster via
			 X-OFF component of the gstring's ADJUSTMENT
			 sub-vector.  This loop computes, for each
			 grapheme cluster, the initial value of the
			 adjustment for the base character, which is
			 then updated for each successive glyph in the
			 grapheme cluster.  */
		      if (items[i].a.fRTL)
			{
			  int j1 = j;

			  adj_offset = 0;
			  while (j1 < nglyphs && !attributes[j1].fClusterStart)
			    {
			      adj_offset += advances[j1];
			      j1++;
			    }
			}
383 384
		    }

385 386 387 388
		  LGLYPH_SET_CHAR (lglyph, chars[items[i].iCharPos
						 + from]);
		  LGLYPH_SET_FROM (lglyph, items[i].iCharPos + from);
		  LGLYPH_SET_TO (lglyph, items[i].iCharPos + to);
389

390 391 392 393 394 395 396 397
		  /* Metrics.  */
		  LGLYPH_SET_WIDTH (lglyph, advances[j]);
		  LGLYPH_SET_ASCENT (lglyph, font->ascent);
		  LGLYPH_SET_DESCENT (lglyph, font->descent);

		  result = ScriptGetGlyphABCWidth (context,
						   &(uniscribe_font->cache),
						   glyphs[j], &char_metric);
398 399 400 401 402
		  if (result == E_PENDING && !context)
		    {
		      /* Cache incomplete... */
		      f = XFRAME (selected_frame);
		      context = get_frame_dc (f);
403
		      old_font = SelectObject (context, FONT_HANDLE (font));
404 405 406 407
		      result = ScriptGetGlyphABCWidth (context,
						       &(uniscribe_font->cache),
						       glyphs[j], &char_metric);
		    }
408

409
		  if (SUCCEEDED (result))
410
		    {
411 412 413 414 415
		      int lbearing = char_metric.abcA;
		      int rbearing = char_metric.abcA + char_metric.abcB;

		      LGLYPH_SET_LBEARING (lglyph, lbearing);
		      LGLYPH_SET_RBEARING (lglyph, rbearing);
416 417
		    }
		  else
418
		    {
419 420
		      LGLYPH_SET_LBEARING (lglyph, 0);
		      LGLYPH_SET_RBEARING (lglyph, advances[j]);
421
		    }
422

423 424 425 426 427
		  if (offsets[j].du || offsets[j].dv
		      /* For non-base glyphs of RTL grapheme clusters,
			 adjust the X offset even if both DU and DV
			 are zero.  */
		      || (!attributes[j].fClusterStart && items[i].a.fRTL))
428
		    {
429 430
		      Lisp_Object vec = make_uninit_vector (3);

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
		      if (items[i].a.fRTL)
			{
			  /* Empirically, it looks like Uniscribe
			     interprets DU in reverse direction for
			     RTL clusters.  E.g., if we don't reverse
			     the direction, the Hebrew point HOLAM is
			     drawn above the right edge of the base
			     consonant, instead of above the left edge.  */
			  ASET (vec, 0, make_number (-offsets[j].du
						     + adj_offset));
			  /* Update the adjustment value for the width
			     advance of the glyph we just emitted.  */
			  adj_offset -= 2 * advances[j];
			}
		      else
			ASET (vec, 0, make_number (offsets[j].du + adj_offset));
447 448 449 450 451
		      /* In the font definition coordinate system, the
			 Y coordinate points up, while in our screen
			 coordinates Y grows downwards.  So we need to
			 reverse the sign of Y-OFFSET here.  */
		      ASET (vec, 1, make_number (-offsets[j].dv));
452 453 454
		      /* Based on what ftfont.c does... */
		      ASET (vec, 2, make_number (advances[j]));
		      LGLYPH_SET_ADJUSTMENT (lglyph, vec);
455
		    }
456
		  else
457 458 459 460 461 462 463
		    {
		      LGLYPH_SET_ADJUSTMENT (lglyph, Qnil);
		      /* Update the adjustment value to compensate for
			 the width of the base character.  */
		      if (items[i].a.fRTL)
			adj_offset -= advances[j];
		    }
464 465
		}
	    }
466 467 468 469 470
	}
      done_glyphs += nglyphs;
    }

  xfree (items);
471 472 473 474 475 476

  if (context)
    {
      SelectObject (context, old_font);
      release_frame_dc (f, context);
    }
477 478 479 480

  if (NILP (lgstring))
    return Qnil;
  else
481
    return make_number (done_glyphs);
482 483 484
}

/* Uniscribe implementation of encode_char for font backend.
485
   Return a glyph code of FONT for character C (Unicode code point).
486 487
   If FONT doesn't have such a glyph, return FONT_INVALID_CODE.  */
static unsigned
488
uniscribe_encode_char (struct font *font, int c)
489
{
490 491 492
  HDC context = NULL;
  struct frame *f = NULL;
  HFONT old_font = NULL;
493
  unsigned code = FONT_INVALID_CODE;
494 495 496 497 498 499
  wchar_t ch[2];
  int len;
  SCRIPT_ITEM* items;
  int nitems;
  struct uniscribe_font_info *uniscribe_font
    = (struct uniscribe_font_info *)font;
500 501 502

  if (c < 0x10000)
    {
503 504
      ch[0] = (wchar_t) c;
      len = 1;
505 506
    }
  else
507 508
    {
      DWORD surrogate = c - 0x10000;
509

510
      /* High surrogate: U+D800 - U+DBFF.  */
511
      ch[0] = 0xD800 + ((surrogate >> 10) & 0x03FF);
512
      /* Low surrogate: U+DC00 - U+DFFF.  */
513
      ch[1] = 0xDC00 + (surrogate & 0x03FF);
514 515
      len = 2;
    }
516

517 518
  /* Non BMP characters must be handled by the uniscribe shaping
     engine as GDI functions (except blindly displaying lines of
Juanma Barranquero's avatar
Juanma Barranquero committed
519
     Unicode text) and the promising looking ScriptGetCMap do not
520 521
     convert surrogate pairs to glyph indexes correctly.  */
    {
522
      items = (SCRIPT_ITEM *) alloca (sizeof (SCRIPT_ITEM) * 2 + 1);
523 524 525
      if (SUCCEEDED (ScriptItemize (ch, len, 2, NULL, NULL, items, &nitems)))
	{
	  HRESULT result;
526 527 528 529 530 531
          /* Surrogates seem to need 2 here, even though only one glyph is
	     returned.  Indic characters can also produce 2 or more glyphs for
	     a single code point, but they need to use uniscribe_shape
	     above for correct display.  */
          WORD glyphs[2], clusters[2];
          SCRIPT_VISATTR attrs[2];
532 533
          int nglyphs;

534 535 536 537
	  /* Force ScriptShape to generate glyphs in the logical
	     order.  */
	  items[0].a.fLogicalOrder = 1;

538
          result = ScriptShape (context, &(uniscribe_font->cache),
539
                                ch, len, 2, &(items[0].a),
540 541 542 543 544 545 546 547
                                glyphs, clusters, attrs, &nglyphs);

          if (result == E_PENDING)
            {
              /* Use selected frame until API is updated to pass
                 the frame.  */
              f = XFRAME (selected_frame);
              context = get_frame_dc (f);
548
              old_font = SelectObject (context, FONT_HANDLE (font));
549 550 551 552 553 554
              result = ScriptShape (context, &(uniscribe_font->cache),
                                    ch, len, 2, &(items[0].a),
                                    glyphs, clusters, attrs, &nglyphs);
            }

          if (SUCCEEDED (result) && nglyphs == 1)
555
            {
556
	      /* Some fonts return .notdef glyphs instead of failing.
Juanma Barranquero's avatar
Juanma Barranquero committed
557
	         (TrueType spec reserves glyph code 0 for .notdef)  */
558 559
	      if (glyphs[0])
		code = glyphs[0];
560
            }
561 562 563 564 565 566 567 568
          else if (SUCCEEDED (result) || result == E_OUTOFMEMORY)
            {
              /* This character produces zero or more than one glyph
                 when shaped. But we still need the return from here
                 to be valid for the shaping engine to be invoked
                 later.  */
              result = ScriptGetCMap (context, &(uniscribe_font->cache),
                                      ch, len, 0, glyphs);
569
              if (SUCCEEDED (result) && glyphs[0])
570
                code = glyphs[0];
571 572
            }
	}
573
    }
574 575 576 577 578
    if (context)
      {
	SelectObject (context, old_font);
	release_frame_dc (f, context);
      }
579

580
    return code;
581 582 583 584 585 586 587
}

/*
   Shared with w32font:
   Lisp_Object uniscribe_get_cache (Lisp_Object frame);
   void uniscribe_free_entity (Lisp_Object font_entity);
   int uniscribe_has_char (Lisp_Object entity, int c);
588 589
   void uniscribe_text_extents (struct font *font, unsigned *code,
                                int nglyphs, struct font_metrics *metrics);
590 591 592 593
   int uniscribe_draw (struct glyph_string *s, int from, int to,
                       int x, int y, int with_background);

   Unused:
Dmitry Antipov's avatar
Dmitry Antipov committed
594 595
   int uniscribe_prepare_face (struct frame *f, struct face *face);
   void uniscribe_done_face (struct frame *f, struct face *face);
596 597 598 599 600
   int uniscribe_get_bitmap (struct font *font, unsigned code,
                             struct font_bitmap *bitmap, int bits_per_pixel);
   void uniscribe_free_bitmap (struct font *font, struct font_bitmap *bitmap);
   int uniscribe_anchor_point (struct font *font, unsigned code,
                               int index, int *x, int *y);
Dmitry Antipov's avatar
Dmitry Antipov committed
601 602
   int uniscribe_start_for_frame (struct frame *f);
   int uniscribe_end_for_frame (struct frame *f);
603 604 605 606 607 608 609

*/


/* Callback function for EnumFontFamiliesEx.
   Adds the name of opentype fonts to a Lisp list (passed in as the
   lParam arg). */
610
static int CALLBACK ALIGN_STACK
611 612 613
add_opentype_font_name_to_list (ENUMLOGFONTEX *logical_font,
				NEWTEXTMETRICEX *physical_font,
				DWORD font_type, LPARAM list_object)
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
{
  Lisp_Object* list = (Lisp_Object *) list_object;
  Lisp_Object family;

  /* Skip vertical fonts (intended only for printing)  */
  if (logical_font->elfLogFont.lfFaceName[0] == '@')
    return 1;

  /* Skip non opentype fonts.  Count old truetype fonts as opentype,
     as some of them do contain GPOS and GSUB data that Uniscribe
     can make use of.  */
  if (!(physical_font->ntmTm.ntmFlags & NTMFLAGS_OPENTYPE)
      && font_type != TRUETYPE_FONTTYPE)
    return 1;

Juanma Barranquero's avatar
Juanma Barranquero committed
629
  /* Skip fonts that have no Unicode coverage.  */
630 631 632 633 634 635
  if (!physical_font->ntmFontSig.fsUsb[3]
      && !physical_font->ntmFontSig.fsUsb[2]
      && !physical_font->ntmFontSig.fsUsb[1]
      && !(physical_font->ntmFontSig.fsUsb[0] & 0x3fffffff))
    return 1;

636
  family = intern_font_name (logical_font->elfLogFont.lfFaceName);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
  if (! memq_no_quit (family, *list))
    *list = Fcons (family, *list);

  return 1;
}


/* :otf property handling.
   Since the necessary Uniscribe APIs for getting font tag information
   are only available in Vista, we need to parse the font data directly
   according to the OpenType Specification.  */

/* Push into DWORD backwards to cope with endianness.  */
#define OTF_TAG(STR)                                          \
  ((STR[3] << 24) | (STR[2] << 16) | (STR[1] << 8) | STR[0])

#define OTF_INT16_VAL(TABLE, OFFSET, PTR)		     \
  do {							     \
    BYTE temp, data[2];					     \
    if (GetFontData (context, TABLE, OFFSET, data, 2) != 2)  \
      goto font_table_error;				     \
    temp = data[0], data[0] = data[1], data[1] = temp;	     \
    memcpy (PTR, data, 2);				     \
  } while (0)

/* Do not reverse the bytes, because we will compare with a OTF_TAG value
   that has them reversed already.  */
#define OTF_DWORDTAG_VAL(TABLE, OFFSET, PTR)                    \
  do {								\
    if (GetFontData (context, TABLE, OFFSET, PTR, 4) != 4)	\
      goto font_table_error;					\
  } while (0)

#define OTF_TAG_VAL(TABLE, OFFSET, STR)			     \
  do {							     \
    if (GetFontData (context, TABLE, OFFSET, STR, 4) != 4)   \
      goto font_table_error;				     \
    STR[4] = '\0';                                           \
  } while (0)

677
#define SNAME(VAL) SDATA (SYMBOL_NAME (VAL))
678 679 680 681

/* Check if font supports the otf script/language/features specified.
   OTF_SPEC is in the format
     (script lang [(gsub_feature ...)|nil] [(gpos_feature ...)]?) */
682 683
int
uniscribe_check_otf (LOGFONT *font, Lisp_Object otf_spec)
684 685 686 687 688 689 690 691 692
{
  Lisp_Object script, lang, rest;
  Lisp_Object features[2];
  DWORD feature_tables[2];
  DWORD script_tag, default_script, lang_tag = 0;
  struct frame * f;
  HDC context;
  HFONT check_font, old_font;
  int i, retval = 0;
693
  struct gcpro gcpro1;
694

695
  /* Check the spec is in the right format.  */
696
  if (!CONSP (otf_spec) || XINT (Flength (otf_spec)) < 3)
697 698
    return 0;

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  /* Break otf_spec into its components.  */
  script = XCAR (otf_spec);
  rest = XCDR (otf_spec);

  lang = XCAR (rest);
  rest = XCDR (rest);

  features[0] = XCAR (rest);
  rest = XCDR (rest);
  if (NILP (rest))
    features[1] = Qnil;
  else
    features[1] = XCAR (rest);

  /* Set up tags we will use in the search.  */
  feature_tables[0] = OTF_TAG ("GSUB");
  feature_tables[1] = OTF_TAG ("GPOS");
  default_script = OTF_TAG ("DFLT");
  if (NILP (script))
    script_tag = default_script;
  else
    script_tag = OTF_TAG (SNAME (script));
  if (!NILP (lang))
    lang_tag = OTF_TAG (SNAME (lang));

  /* Set up graphics context so we can use the font.  */
  f = XFRAME (selected_frame);
  context = get_frame_dc (f);
  check_font = CreateFontIndirect (font);
  old_font = SelectObject (context, check_font);

730 731 732 733
  /* Everything else is contained within otf_spec so should get
     marked along with it.  */
  GCPRO1 (otf_spec);

734 735 736 737 738 739 740 741 742 743 744 745 746
  /* Scan GSUB and GPOS tables.  */
  for (i = 0; i < 2; i++)
    {
      int j, n_match_features;
      unsigned short scriptlist_table, feature_table, n_scripts;
      unsigned short script_table, langsys_table, n_langs;
      unsigned short feature_index, n_features;
      DWORD tbl = feature_tables[i];

      /* Skip if no features requested from this table.  */
      if (NILP (features[i]))
	continue;

747 748 749 750
      /* If features is not a cons, this font spec is messed up.  */
      if (!CONSP (features[i]))
	goto no_support;

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
      /* Read GPOS/GSUB header.  */
      OTF_INT16_VAL (tbl, 4, &scriptlist_table);
      OTF_INT16_VAL (tbl, 6, &feature_table);
      OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);

      /* Find the appropriate script table.  */
      script_table = 0;
      for (j = 0; j < n_scripts; j++)
	{
	  DWORD script_id;
	  OTF_DWORDTAG_VAL (tbl, scriptlist_table + 2 + j * 6, &script_id);
	  if (script_id == script_tag)
	    {
	      OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
	      break;
	    }
767
#if 0	  /* Causes false positives.  */
768 769 770 771
	  /* If there is a DFLT script defined in the font, use it
	     if the specified script is not found.  */
	  else if (script_id == default_script)
	    OTF_INT16_VAL (tbl, scriptlist_table + 6 + j * 6, &script_table);
772
#endif
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	}
      /* If no specific or default script table was found, then this font
	 does not support the script.  */
      if (!script_table)
	goto no_support;

      /* Offset is from beginning of scriptlist_table.  */
      script_table += scriptlist_table;

      /* Get default langsys table.  */
      OTF_INT16_VAL (tbl, script_table, &langsys_table);

      /* If lang was specified, see if font contains a specific entry.  */
      if (!NILP (lang))
	{
	  OTF_INT16_VAL (tbl, script_table + 2, &n_langs);

	  for (j = 0; j < n_langs; j++)
	    {
	      DWORD lang_id;
	      OTF_DWORDTAG_VAL (tbl, script_table + 4 + j * 6, &lang_id);
	      if (lang_id == lang_tag)
		{
		  OTF_INT16_VAL (tbl, script_table + 8 + j * 6, &langsys_table);
		  break;
		}
	    }
	}

      if (!langsys_table)
	goto no_support;

      /* Offset is from beginning of script table.  */
      langsys_table += script_table;

      /* Check the features.  Features may contain nil according to
	 documentation in font_prop_validate_otf, so count them.  */
      n_match_features = 0;
811
      for (rest = features[i]; CONSP (rest); rest = XCDR (rest))
812
	{
813
	  Lisp_Object feature = XCAR (rest);
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
	  if (!NILP (feature))
	    n_match_features++;
	}

      /* If there are no features to check, skip checking.  */
      if (!n_match_features)
	continue;

      /* First check required feature (if any).  */
      OTF_INT16_VAL (tbl, langsys_table + 2, &feature_index);
      if (feature_index != 0xFFFF)
	{
	  char feature_id[5];
	  OTF_TAG_VAL (tbl, feature_table + 2 + feature_index * 6, feature_id);
	  OTF_TAG_VAL (tbl, feature_table + 2 + feature_index * 6, feature_id);
	  /* Assume no duplicates in the font table. This allows us to mark
	     the features off by simply decrementing a counter.  */
	  if (!NILP (Fmemq (intern (feature_id), features[i])))
	    n_match_features--;
	}
      /* Now check all the other features.  */
      OTF_INT16_VAL (tbl, langsys_table + 4, &n_features);
      for (j = 0; j < n_features; j++)
	{
	  char feature_id[5];
	  OTF_INT16_VAL (tbl, langsys_table + 6 + j * 2, &feature_index);
	  OTF_TAG_VAL (tbl, feature_table + 2 + feature_index * 6, feature_id);
	  /* Assume no duplicates in the font table. This allows us to mark
	     the features off by simply decrementing a counter.  */
	  if (!NILP (Fmemq (intern (feature_id), features[i])))
	    n_match_features--;
	}

      if (n_match_features > 0)
	goto no_support;
    }

  retval = 1;

 no_support:
 font_table_error:
  /* restore graphics context.  */
  SelectObject (context, old_font);
  DeleteObject (check_font);
  release_frame_dc (f, context);

  return retval;
}

static Lisp_Object
otf_features (HDC context, char *table)
{
  Lisp_Object script_list = Qnil;
  unsigned short scriptlist_table, n_scripts, feature_table;
  DWORD tbl = OTF_TAG (table);
  int i, j, k;

  /* Look for scripts in the table.  */
  OTF_INT16_VAL (tbl, 4, &scriptlist_table);
  OTF_INT16_VAL (tbl, 6, &feature_table);
  OTF_INT16_VAL (tbl, scriptlist_table, &n_scripts);

  for (i = 0; i < n_scripts; i++)
    {
      char script[5], lang[5];
      unsigned short script_table, lang_count, langsys_table, feature_count;
      Lisp_Object script_tag, langsys_list, langsys_tag, feature_list;
      unsigned short record_offset = scriptlist_table + 2 + i * 6;
      OTF_TAG_VAL (tbl, record_offset, script);
      OTF_INT16_VAL (tbl, record_offset + 4, &script_table);

      /* Offset is from beginning of script table.  */
      script_table += scriptlist_table;

      script_tag = intern (script);
      langsys_list = Qnil;

      /* Optional default lang.  */
      OTF_INT16_VAL (tbl, script_table, &langsys_table);
      if (langsys_table)
	{
	  /* Offset is from beginning of script table.  */
	  langsys_table += script_table;

	  langsys_tag = Qnil;
	  feature_list = Qnil;
	  OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
	  for (k = 0; k < feature_count; k++)
	    {
	      char feature[5];
	      unsigned short index;
	      OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
	      OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
	      feature_list = Fcons (intern (feature), feature_list);
	    }
	  langsys_list = Fcons (Fcons (langsys_tag, feature_list),
				langsys_list);
	}

      /* List of supported languages.  */
      OTF_INT16_VAL (tbl, script_table + 2, &lang_count);

      for (j = 0; j < lang_count; j++)
	{
	  record_offset = script_table + 4 + j * 6;
	  OTF_TAG_VAL (tbl, record_offset, lang);
	  OTF_INT16_VAL (tbl, record_offset + 4, &langsys_table);

	  /* Offset is from beginning of script table.  */
	  langsys_table += script_table;

	  langsys_tag = intern (lang);
	  feature_list = Qnil;
	  OTF_INT16_VAL (tbl, langsys_table + 4, &feature_count);
	  for (k = 0; k < feature_count; k++)
	    {
	      char feature[5];
	      unsigned short index;
	      OTF_INT16_VAL (tbl, langsys_table + 6 + k * 2, &index);
	      OTF_TAG_VAL (tbl, feature_table + 2 + index * 6, feature);
	      feature_list = Fcons (intern (feature), feature_list);
	    }
	  langsys_list = Fcons (Fcons (langsys_tag, feature_list),
				langsys_list);

	}

      script_list = Fcons (Fcons (script_tag, langsys_list), script_list);
    }

  return script_list;

font_table_error:
  return Qnil;
}

#undef OTF_INT16_VAL
#undef OTF_TAG_VAL
#undef OTF_TAG


struct font_driver uniscribe_font_driver =
  {
957
    LISP_INITIALLY_ZERO, /* Quniscribe */
958
    0, /* case insensitive */
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
    w32font_get_cache,
    uniscribe_list,
    uniscribe_match,
    uniscribe_list_family,
    NULL, /* free_entity */
    uniscribe_open,
    uniscribe_close,
    NULL, /* prepare_face */
    NULL, /* done_face */
    w32font_has_char,
    uniscribe_encode_char,
    w32font_text_extents,
    w32font_draw,
    NULL, /* get_bitmap */
    NULL, /* free_bitmap */
    NULL, /* anchor_point */
975
    uniscribe_otf_capability, /* Defined so (font-get FONTOBJ :otf) works.  */
976 977 978
    NULL, /* otf_drive - use shape instead.  */
    NULL, /* start_for_frame */
    NULL, /* end_for_frame */
979 980 981 982 983
    uniscribe_shape,
    NULL, /* check */
    NULL, /* get_variation_glyphs */
    NULL, /* filter_properties */
    NULL, /* cached_font_ok */
984 985 986 987 988
  };

/* Note that this should be called at every startup, not just when dumping,
   as it needs to test for the existence of the Uniscribe library.  */
void
989
syms_of_w32uniscribe (void)
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
{
  HMODULE uniscribe;

  /* Don't init uniscribe when dumping */
  if (!initialized)
    return;

  /* Don't register if uniscribe is not available.  */
  uniscribe = GetModuleHandle ("usp10");
  if (!uniscribe)
    return;

  uniscribe_font_driver.type = Quniscribe;
  uniscribe_available = 1;

  register_font_driver (&uniscribe_font_driver, NULL);
}