nsfont.m 46.1 KB
Newer Older
1 2
/* Font back-end driver for the NeXT/Open/GNUstep and MacOSX window system.
   See font.h
3
   Copyright (C) 2006-2012 Free Software Foundation, Inc.
4 5 6

This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
11 12 13 14 15 16 17

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
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
19 20 21 22

Author: Adrian Robert (arobert@cogsci.ucsd.edu)
*/

23 24
/* This should be the first include, as it may set up #defines affecting
   interpretation of even the system includes. */
Dan Nicolaescu's avatar
Dan Nicolaescu committed
25
#include <config.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
26
#include <setjmp.h>
27 28 29 30 31 32 33 34 35 36 37 38 39

#include "lisp.h"
#include "dispextern.h"
#include "composite.h"
#include "blockinput.h"
#include "charset.h"
#include "frame.h"
#include "window.h"
#include "fontset.h"
#include "nsterm.h"
#include "frame.h"
#include "character.h"
#include "font.h"
40
#include "termchar.h"
41

42
/* TODO: Drop once we can assume gnustep-gui 0.17.1. */
43 44 45 46
#ifdef NS_IMPL_GNUSTEP
#import <AppKit/NSFontDescriptor.h>
#endif

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#define NSFONT_TRACE 0

extern Lisp_Object Qns;
extern Lisp_Object Qnormal, Qbold, Qitalic, Qcondensed, Qexpanded;
static Lisp_Object Qapple, Qroman, Qmedium;
extern Lisp_Object Qappend;
extern float ns_antialias_threshold;
extern int ns_tmp_flags;
extern struct nsfont_info *ns_tmp_font;

/* font glyph and metrics caching functions, implemented at end */
static void ns_uni_to_glyphs (struct nsfont_info *font_info,
                              unsigned char block);
static void ns_glyph_metrics (struct nsfont_info *font_info,
                              unsigned char block);


/* ==========================================================================

    Utilities

   ========================================================================== */


/* Replace spaces w/another character so emacs core font parsing routines
   aren't thrown off. */
static void
74
ns_escape_name (char *name)
75 76 77 78 79 80 81 82 83 84
{
  int i =0, len =strlen (name);
  for ( ; i<len; i++)
    if (name[i] == ' ')
      name[i] = '_';
}


/* Reconstruct spaces in a font family name passed through emacs. */
static void
85
ns_unescape_name (char *name)
86 87 88 89 90 91 92 93 94 95
{
  int i =0, len =strlen (name);
  for ( ; i<len; i++)
    if (name[i] == '_')
      name[i] = ' ';
}


/* Extract family name from a font spec. */
static NSString *
96
ns_get_family (Lisp_Object font_spec)
97 98 99 100 101 102
{
  Lisp_Object tem = AREF (font_spec, FONT_FAMILY_INDEX);
  if (NILP (tem))
      return nil;
  else
    {
103
      char *tmp = xstrdup (SSDATA (SYMBOL_NAME (tem)));
104
      NSString *family;
105
      ns_unescape_name (tmp);
106
      family = [NSString stringWithUTF8String: tmp];
107
      xfree (tmp);
108 109 110 111 112
      return family;
    }
}


113 114 115 116
/* Return 0 if attr not set, else value (which might also be 0).
   On Leopard 0 gets returned even on descriptors where the attribute
   was never set, so there's no way to distinguish between unspecified
   and set to not have.  Callers should assume 0 means unspecified. */
117 118 119
static float
ns_attribute_fvalue (NSFontDescriptor *fdesc, NSString *trait)
{
120 121
    NSDictionary *tdict = [fdesc objectForKey: NSFontTraitsAttribute];
    NSNumber *val = [tdict objectForKey: trait];
122 123
    return val == nil ? 0.0 : [val floatValue];
}
124 125


126 127 128
/* Converts FONT_WEIGHT, FONT_SLANT, FONT_WIDTH, plus family and script/lang
   to NSFont descriptor.  Information under extra only needed for matching. */
#define STYLE_REF 100
129 130
static NSFontDescriptor *
ns_spec_to_descriptor (Lisp_Object font_spec)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
{
    NSFontDescriptor *fdesc;
    NSMutableDictionary *fdAttrs = [NSMutableDictionary new];
    NSMutableDictionary *tdict = [NSMutableDictionary new];
    NSString *family = ns_get_family (font_spec);
    float n;

    /* add each attr in font_spec to fdAttrs.. */
    n = min (FONT_WEIGHT_NUMERIC (font_spec), 200);
    if (n != -1 && n != STYLE_REF)
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontWeightTrait];
    n = min (FONT_SLANT_NUMERIC (font_spec), 200);
    if (n != -1 && n != STYLE_REF)
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontSlantTrait];
    n = min (FONT_WIDTH_NUMERIC (font_spec), 200);
    if (n > -1 && (n > STYLE_REF + 10 || n < STYLE_REF - 10))
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontWidthTrait];
    if ([tdict count] > 0)
	[fdAttrs setObject: tdict forKey: NSFontTraitsAttribute];

    fdesc = [NSFontDescriptor fontDescriptorWithFontAttributes: fdAttrs];
155
    if (family != nil)
156
      {
157
	fdesc = [fdesc fontDescriptorWithFamily: family];
158 159 160 161
      }

    [fdAttrs release];
    [tdict release];
162
    return fdesc;
163 164 165
}


166
/* Converts NSFont descriptor to FONT_WEIGHT, FONT_SLANT, FONT_WIDTH, etc.. */
167
static Lisp_Object
Jan D's avatar
Jan D committed
168 169 170
ns_descriptor_to_entity (NSFontDescriptor *desc,
                         Lisp_Object extra,
                         const char *style)
171
{
172 173 174 175
    Lisp_Object font_entity = font_make_entity ();
    /*   NSString *psName = [desc postscriptName]; */
    NSString *family = [desc objectForKey: NSFontFamilyAttribute];
    unsigned int traits = [desc symbolicTraits];
176
    char *escapedFamily;
177

178 179 180 181 182 183
    /* Shouldn't happen, but on Tiger fallback desc gets name but no family. */
    if (family == nil)
      family = [desc objectForKey: NSFontNameAttribute];
    if (family == nil)
      family = [[NSFont userFixedPitchFontOfSize: 0] familyName];

184
    escapedFamily = xstrdup ([family UTF8String]);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    ns_escape_name (escapedFamily);

    ASET (font_entity, FONT_TYPE_INDEX, Qns);
    ASET (font_entity, FONT_FOUNDRY_INDEX, Qapple);
    ASET (font_entity, FONT_FAMILY_INDEX, intern (escapedFamily));
    ASET (font_entity, FONT_ADSTYLE_INDEX, style ? intern (style) : Qnil);
    ASET (font_entity, FONT_REGISTRY_INDEX, Qiso10646_1);

    FONT_SET_STYLE (font_entity, FONT_WEIGHT_INDEX,
		    traits & NSFontBoldTrait ? Qbold : Qmedium);
/*    FONT_SET_STYLE (font_entity, FONT_WEIGHT_INDEX,
		    make_number (100 + 100
			* ns_attribute_fvalue (desc, NSFontWeightTrait)));*/
    FONT_SET_STYLE (font_entity, FONT_SLANT_INDEX,
		    traits & NSFontItalicTrait ? Qitalic : Qnormal);
/*    FONT_SET_STYLE (font_entity, FONT_SLANT_INDEX,
		    make_number (100 + 100
			 * ns_attribute_fvalue (desc, NSFontSlantTrait)));*/
    FONT_SET_STYLE (font_entity, FONT_WIDTH_INDEX,
		    traits & NSFontCondensedTrait ? Qcondensed :
		    traits & NSFontExpandedTrait ? Qexpanded : Qnormal);
/*    FONT_SET_STYLE (font_entity, FONT_WIDTH_INDEX,
		    make_number (100 + 100
			 * ns_attribute_fvalue (desc, NSFontWidthTrait)));*/

    ASET (font_entity, FONT_SIZE_INDEX, make_number (0));
    ASET (font_entity, FONT_AVGWIDTH_INDEX, make_number (0));
    ASET (font_entity, FONT_SPACING_INDEX,
	  make_number([desc symbolicTraits] & NSFontMonoSpaceTrait
	      ? FONT_SPACING_MONO : FONT_SPACING_PROPORTIONAL));

    ASET (font_entity, FONT_EXTRA_INDEX, extra);
    ASET (font_entity, FONT_OBJLIST_INDEX, Qnil);

    if (NSFONT_TRACE)
      {
	fprintf (stderr, "created font_entity:\n    ");
	debug_print (font_entity);
      }
224

225
    xfree (escapedFamily);
226 227
    return font_entity;
}
228

229 230 231

/* Default font entity. */
static Lisp_Object
232
ns_fallback_entity (void)
233 234 235
{
  return ns_descriptor_to_entity ([[NSFont userFixedPitchFontOfSize: 0]
      fontDescriptor], Qnil, NULL);
236 237 238
}


239
/* Utility: get width of a char c in screen font SFONT */
240 241
static float
ns_char_width (NSFont *sfont, int c)
242
{
243 244 245
  float w = -1.0;
  NSString *cstr = [NSString stringWithFormat: @"%c", c];

246
#ifdef NS_IMPL_COCOA
247 248 249
  NSGlyph glyph = [sfont glyphWithName: cstr];
  if (glyph)
    w = [sfont advancementForGlyph: glyph].width;
250
#endif
251 252

  if (w < 0.0)
253 254 255 256 257
    {
      NSDictionary *attrsDictionary =
        [NSDictionary dictionaryWithObject: sfont forKey: NSFontAttributeName];
      w = [cstr sizeWithAttributes: attrsDictionary].width;
    }
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

  return max (w, 1.0);
}

/* Return average width over ASCII printable characters for SFONT.  */

static NSString *ascii_printable;

static int
ns_ascii_average_width (NSFont *sfont)
{
  float w = -1.0;

  if (!ascii_printable)
    {
      char chars[95];
      int ch;
      for (ch = 0; ch < 95; ch++)
	chars[ch] = ' ' + ch;

      ascii_printable = [NSString initWithFormat: @"%s", chars];
    }

#ifdef NS_IMPL_COCOA
  NSGlyph glyph = [sfont glyphWithName: ascii_printable];
  if (glyph)
    w = [sfont advancementForGlyph: glyph].width;
#endif

  if (w < 0.0)
    {
      NSDictionary *attrsDictionary =
	[NSDictionary dictionaryWithObject: sfont forKey: NSFontAttributeName];
      w = [ascii_printable sizeWithAttributes: attrsDictionary].width;
    }

  return lrint (w / 95.0);
295 296 297 298
}


/* Return whether set1 covers set2 to a reasonable extent given by pct.
Juanma Barranquero's avatar
Juanma Barranquero committed
299
   We check, out of each 16 Unicode char range containing chars in set2,
300 301 302 303 304 305 306 307 308
   whether at least one character is present in set1.
   This must be true for pct of the pairs to consider it covering. */
static BOOL
ns_charset_covers(NSCharacterSet *set1, NSCharacterSet *set2, float pct)
{
    const unsigned short *bytes1 = [[set1 bitmapRepresentation] bytes];
    const unsigned short *bytes2 = [[set2 bitmapRepresentation] bytes];
    int i, off = 0, tot = 0;

309 310 311 312 313
    /* Work around what appears to be a GNUstep bug.
       See <http://bugs.gnu.org/11853>.  */
    if (! (bytes1 && bytes2))
      return NO;

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    for (i=0; i<4096; i++, bytes1++, bytes2++)
	if (*bytes2)
	  {
	    tot++;
	    if (*bytes1 == 0)  // *bytes1 & *bytes2 != *bytes2
		off++;
	  }
//fprintf(stderr, "off = %d\ttot = %d\n", off,tot);
    return (float)off / tot < 1.0 - pct;
}


/* Convert :lang property to a script.  Use of :lang property by font backend
   seems to be limited for now (2009/05) to ja, zh, and ko. */
static NSString
*ns_lang_to_script (Lisp_Object lang)
{
331
    if (!strcmp (SSDATA (SYMBOL_NAME (lang)), "ja"))
332 333 334
	return @"han";
    /* NOTE: ja given for any hanzi that's also a kanji, but Chinese fonts
             have more characters. */
335
    else if (!strcmp (SSDATA (SYMBOL_NAME (lang)), "zh"))
336
	return @"han";
337
    else if (!strcmp (SSDATA (SYMBOL_NAME (lang)), "ko"))
338 339 340 341 342 343 344
	return @"hangul";
    else
	return @"";
}


/* Convert OTF 4-letter script code to emacs script name.  (Why can't
Juanma Barranquero's avatar
Juanma Barranquero committed
345
   everyone just use some standard Unicode names for these?) */
346 347 348 349 350
static NSString
*ns_otf_to_script (Lisp_Object otf)
{
    Lisp_Object script = assq_no_quit (XCAR (otf), Votf_script_alist);
    return CONSP (script)
351
	? [NSString stringWithUTF8String: SSDATA (SYMBOL_NAME (XCDR ((script))))]
352 353 354 355
	: @"";
}


356 357 358 359 360 361 362 363
/* Convert a font registry, such as  */
static NSString
*ns_registry_to_script (char *reg)
{
    Lisp_Object script, r, rts = Vns_reg_to_script;
    while CONSP (rts)
      {
        r = XCAR (XCAR (rts));
364
        if (!strncmp(SSDATA(r), reg, strlen(SSDATA(r))))
365 366
          {
            script = XCDR (XCAR (rts));
367
            return [NSString stringWithUTF8String: SSDATA (SYMBOL_NAME (script))];
368 369 370 371 372 373 374 375 376
          }
        rts = XCDR (rts);
      }
    return  @"";
}


/* Searches the :script, :lang, and :otf extra-bundle properties of the spec,
   plus registry regular property, for something that can be mapped to a
Juanma Barranquero's avatar
Juanma Barranquero committed
377
   Unicode script.  Empty string returned if no script spec found. */
378 379 380
static NSString
*ns_get_req_script (Lisp_Object font_spec)
{
381
    Lisp_Object reg = AREF (font_spec, FONT_REGISTRY_INDEX);
382 383
    Lisp_Object extra = AREF (font_spec, FONT_EXTRA_INDEX);

384
    /* The extra-bundle properties have priority. */
385 386 387 388 389 390 391 392
    for ( ; CONSP (extra); extra = XCDR (extra))
      {
	Lisp_Object tmp = XCAR (extra);
	if (CONSP (tmp))
	  {
	    Lisp_Object key = XCAR (tmp), val = XCDR (tmp);
	    if (EQ (key, QCscript) && SYMBOLP (val))
		return [NSString stringWithUTF8String:
393
		            SSDATA (SYMBOL_NAME (val))];
394 395 396 397 398 399
	    if (EQ (key, QClang) && SYMBOLP (val))
		return ns_lang_to_script (val);
	    if (EQ (key, QCotf) && CONSP (val) && SYMBOLP (XCAR (val)))
		return ns_otf_to_script (val);
	  }
      }
400 401 402 403 404 405 406 407 408 409 410

    /* If we get here, check the charset portion of the registry. */
    if (! NILP (reg))
      {
        /* XXX: iso10646 is passed in for non-ascii latin-1 characters
           (which causes box rendering if we don't treat it like iso8858-1)
           but also for ascii (which causes unnecessary font substitution). */
#if 0
        if (EQ (reg, Qiso10646_1))
          reg = Qiso8859_1;
#endif
411
        return ns_registry_to_script (SSDATA (SYMBOL_NAME (reg)));
412 413
      }

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    return @"";
}


/* This small function is static in fontset.c.  If it can be made public for
   all ports, remove this, but otherwise it doesn't seem worth the ifdefs. */
static void
accumulate_script_ranges (Lisp_Object arg, Lisp_Object range, Lisp_Object val)
{
    if (EQ (XCAR (arg), val))
      {
	if (CONSP (range))
	  XSETCDR (arg, Fcons (Fcons (XCAR (range), XCDR (range)), XCDR (arg)));
	else
	  XSETCDR (arg, Fcons (Fcons (range, range), XCDR (arg)));
      }
}


Juanma Barranquero's avatar
Juanma Barranquero committed
433
/* Use the Unicode range information in Vchar_script_table to convert a script
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
   name into an NSCharacterSet. */
static NSCharacterSet
*ns_script_to_charset (NSString *scriptName)
{
    NSMutableCharacterSet *charset = [NSMutableCharacterSet new];
    Lisp_Object script = intern ([scriptName UTF8String]);
    Lisp_Object script_list = XCHAR_TABLE (Vchar_script_table)->extras[0];

    if (! NILP (Fmemq (script, script_list)))
      {
	Lisp_Object ranges, range_list;

	ranges = Fcons (script, Qnil);
	map_char_table (accumulate_script_ranges, Qnil, Vchar_script_table,
			ranges);
	range_list = Fnreverse (XCDR (ranges));
	if (! NILP (range_list))
	  {
	    for (; CONSP (range_list); range_list = XCDR (range_list))
	      {
		int start = XINT (XCAR (XCAR (range_list)));
		int end = XINT (XCDR (XCAR (range_list)));
		if (NSFONT_TRACE)
		    debug_print (XCAR (range_list));
		if (end < 0x10000)
		    [charset addCharactersInRange:
			NSMakeRange (start, end-start)];
	      }
	  }
      }
    return charset;
465 466 467
}


468 469 470 471 472 473
/* Return an array of font families containing characters for the given
   script, for the given coverage criterion, including at least LastResort.
   Results are cached by script for faster access.
   If none are found, we reduce the percentage and try again, until 5%.
   This provides a font with at least some characters if such can be found.
   We don't use isSupersetOfSet: because (a) it doesn't work on Tiger, and
Juanma Barranquero's avatar
Juanma Barranquero committed
474
   (b) need approximate match as fonts covering full Unicode ranges are rare. */
475 476 477 478 479 480 481 482 483 484
static NSSet
*ns_get_covering_families (NSString *script, float pct)
{
    static NSMutableDictionary *scriptToFamilies = nil;
    NSMutableSet *families;

    if (NSFONT_TRACE)
	NSLog(@"Request covering families for script: '%@'", script);

    if (scriptToFamilies == nil)
485
        scriptToFamilies = [[NSMutableDictionary alloc] init];
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

    if ((families = [scriptToFamilies objectForKey: script]) == nil)
      {
	NSFontManager *fontMgr = [NSFontManager sharedFontManager];
	NSArray *allFamilies = [fontMgr availableFontFamilies];

	if ([script length] == 0)
	    families = [NSMutableSet setWithArray: allFamilies];
	else
	  {
	    NSCharacterSet *charset = ns_script_to_charset (script);
	    NSString *family;
	    families = [NSMutableSet setWithCapacity: 10];
	    while (1)
	      {
		NSEnumerator *allFamiliesEnum = [allFamilies objectEnumerator];
502
		while ((family = [allFamiliesEnum nextObject]))
503 504 505 506 507 508 509 510 511 512 513 514 515 516
		  {
		    NSCharacterSet *fset = [[fontMgr fontWithFamily: family
                        traits: 0 weight: 5 size: 12.0]	coveredCharacterSet];
                    /* Some fonts on OS X, maybe many on GNUstep, return nil. */
                    if (fset == nil)
                      fset = [NSCharacterSet characterSetWithRange:
                                               NSMakeRange (0, 127)];
		    if (ns_charset_covers(fset, charset, pct))
			[families addObject: family];
		  }
                pct -= 0.2;
		if ([families count] > 0 || pct < 0.05)
		    break;
	      }
517
            [charset release];
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
	  }
#ifdef NS_IMPL_COCOA
	if ([families count] == 0)
	    [families addObject: @"LastResort"];
#endif
	[scriptToFamilies setObject: families forKey: script];
      }

    if (NSFONT_TRACE)
	NSLog(@"    returning %d families", [families count]);
    return families;
}


/* Implementation for list() and match().  List() can return nil, match()
must return something.  Strategy is to drop family name from attribute
matching set for match. */
535
static Lisp_Object
536
ns_findfonts (Lisp_Object font_spec, BOOL isMatch)
537
{
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    Lisp_Object tem, list = Qnil;
    NSFontDescriptor *fdesc, *desc;
    NSMutableSet *fkeys;
    NSArray *matchingDescs;
    NSEnumerator *dEnum;
    NSString *family;
    NSSet *cFamilies;
    BOOL foundItal = NO;

    if (NSFONT_TRACE)
      {
	fprintf (stderr, "nsfont: %s for fontspec:\n    ",
		 (isMatch ? "match" : "list"));
	debug_print (font_spec);
      }

    cFamilies = ns_get_covering_families (ns_get_req_script (font_spec), 0.90);

    fdesc = ns_spec_to_descriptor (font_spec);
    fkeys = [NSMutableSet setWithArray: [[fdesc fontAttributes] allKeys]];
    if (isMatch)
	[fkeys removeObject: NSFontFamilyAttribute];

    matchingDescs = [fdesc matchingFontDescriptorsWithMandatoryKeys: fkeys];
    if (NSFONT_TRACE)
	NSLog(@"Got desc %@ and found %d matching fonts from it: ", fdesc,
	      [matchingDescs count]);

566
    for (dEnum = [matchingDescs objectEnumerator]; (desc = [dEnum nextObject]);)
567 568 569 570
      {
	if (![cFamilies containsObject:
	         [desc objectForKey: NSFontFamilyAttribute]])
	    continue;
571
        tem = ns_descriptor_to_entity (desc,
572
					 AREF (font_spec, FONT_EXTRA_INDEX),
573 574 575 576
                                       NULL);
        if (isMatch)
          return tem;
	list = Fcons (tem, list);
577
	if (fabs (ns_attribute_fvalue (desc, NSFontSlantTrait)) > 0.05)
578 579 580 581 582
	    foundItal = YES;
      }

    /* Add synthItal member if needed. */
    family = [fdesc objectForKey: NSFontFamilyAttribute];
583
    if (family != nil && !foundItal && XINT (Flength (list)) > 0)
584
      {
585 586 587 588
        NSFontDescriptor *s1 = [NSFontDescriptor new];
        NSFontDescriptor *sDesc
          = [[s1 fontDescriptorWithSymbolicTraits: NSFontItalicTrait]
              fontDescriptorWithFamily: family];
589 590 591
	list = Fcons (ns_descriptor_to_entity (sDesc,
					 AREF (font_spec, FONT_EXTRA_INDEX),
					 "synthItal"), list);
592
        [s1 release];
593 594
      }

595
    /* Return something if was a match and nothing found. */
596 597
    if (isMatch)
      return ns_fallback_entity ();
598

599
    if (NSFONT_TRACE)
600 601
	fprintf (stderr, "    Returning %"pI"d entities.\n",
                 XINT (Flength (list)));
602 603

    return list;
604 605 606
}


607

608 609 610 611 612 613
/* ==========================================================================

    Font driver implementation

   ========================================================================== */

614

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
static Lisp_Object nsfont_get_cache (FRAME_PTR frame);
static Lisp_Object nsfont_list (Lisp_Object frame, Lisp_Object font_spec);
static Lisp_Object nsfont_match (Lisp_Object frame, Lisp_Object font_spec);
static Lisp_Object nsfont_list_family (Lisp_Object frame);
static Lisp_Object nsfont_open (FRAME_PTR f, Lisp_Object font_entity,
                                 int pixel_size);
static void nsfont_close (FRAME_PTR f, struct font *font);
static int nsfont_has_char (Lisp_Object entity, int c);
static unsigned int nsfont_encode_char (struct font *font, int c);
static int nsfont_text_extents (struct font *font, unsigned int *code,
                                int nglyphs, struct font_metrics *metrics);
static int nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
                        int with_background);

struct font_driver nsfont_driver =
  {
631
    0,				/* Qns */
632 633 634 635 636 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
    1,				/* case sensitive */
    nsfont_get_cache,
    nsfont_list,
    nsfont_match,
    nsfont_list_family,
    NULL,			/*free_entity */
    nsfont_open,
    nsfont_close,
    NULL,			/* prepare_face */
    NULL,			/* done_face */
    nsfont_has_char,
    nsfont_encode_char,
    nsfont_text_extents,
    nsfont_draw,
    /* excluded: get_bitmap, free_bitmap, get_outline, free_outline,
                 anchor_point, otf_capability, otf_driver,
      		 start_for_frame, end_for_frame, shape */
  };


/* Return a cache of font-entities on FRAME.  The cache must be a
   cons whose cdr part is the actual cache area.  */
static Lisp_Object
nsfont_get_cache (FRAME_PTR frame)
{
  Display_Info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
  return (dpyinfo->name_list_element);
}


662 663 664 665 666 667 668 669 670 671 672 673
/* List fonts exactly matching with FONT_SPEC on FRAME.  The value is a
   **list** of font-entities.  This and match () are sole APIs that allocate
   font-entities.  Properties to be considered (2009/05/19) are:
   regular: foundry, family, adstyle, registry
   extended: script, lang, otf
  "Extended" properties are not part of the vector but get stored as
   lisp properties under FONT_EXTRA_INDEX.

   The returned entities should have type set (to 'ns), plus the following:
   foundry, family, adstyle, registry,
   weight, slant, width, size (0 if scalable),
   dpi, spacing, avgwidth (0 if scalable)  */
674 675 676
static Lisp_Object
nsfont_list (Lisp_Object frame, Lisp_Object font_spec)
{
677
    return ns_findfonts (font_spec, NO);
678 679 680
}


Paul Eggert's avatar
Paul Eggert committed
681
/* Return a font entity most closely matching with FONT_SPEC on
682
   FRAME.  The closeness is determined by the font backend, thus
683 684
   `face-font-selection-order' is ignored here.
   Properties to be considered are same as for list(). */
685 686 687
static Lisp_Object
nsfont_match (Lisp_Object frame, Lisp_Object font_spec)
{
688
    return ns_findfonts(font_spec, YES);
689 690 691 692 693 694 695 696 697 698 699 700 701
}


/* List available families.  The value is a list of family names
   (symbols). */
static Lisp_Object
nsfont_list_family (Lisp_Object frame)
{
  Lisp_Object list = Qnil;
  NSEnumerator *families =
    [[[NSFontManager sharedFontManager] availableFontFamilies]
      objectEnumerator];
  NSString *family;
702
  while ((family = [families nextObject]))
703
      list = Fcons (intern ([family UTF8String]), list);
704
  /* FIXME: escape the name? */
705 706

  if (NSFONT_TRACE)
707 708
    fprintf (stderr, "nsfont: list families returning %"pI"d entries\n",
	     XINT (Flength (list)));
709 710 711 712 713 714 715 716 717 718 719

  return list;
}


/* Open a font specified by FONT_ENTITY on frame F.  If the font is
   scalable, open it with PIXEL_SIZE.  */
static Lisp_Object
nsfont_open (FRAME_PTR f, Lisp_Object font_entity, int pixel_size)
{
  BOOL synthItal;
720
  unsigned int traits = 0;
721 722
  struct nsfont_info *font_info;
  struct font *font;
723
  NSFontDescriptor *fontDesc = ns_spec_to_descriptor (font_entity);
724 725 726 727 728 729 730 731
  NSFontManager *fontMgr = [NSFontManager sharedFontManager];
  NSString *family;
  NSFont *nsfont, *sfont;
  Lisp_Object tem;
  NSRect brect;
  Lisp_Object font_object;
  int fixLeopardBug;
  static NSMutableDictionary *fontCache = nil;
732
  NSNumber *cached;
733 734 735 736 737

  /* 2008/03/08: The same font may end up being requested for different
     entities, due to small differences in numeric values or other issues,
     or for different copies of the same entity.  Therefore we cache to
     avoid creating multiple struct font objects (with metrics cache, etc.)
738
     for the same NSFont object. */
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
  if (fontCache == nil)
    fontCache = [[NSMutableDictionary alloc] init];

  if (NSFONT_TRACE)
    {
      fprintf (stderr, "nsfont: open size %d of fontentity:\n    ", pixel_size);
      debug_print (font_entity);
    }

  if (pixel_size <= 0)
    {
      /* try to get it out of frame params */
        Lisp_Object tem = get_frame_param (f, Qfontsize);
        pixel_size = NILP (tem) ? 0 : XFASTINT (tem);
    }

  tem = AREF (font_entity, FONT_ADSTYLE_INDEX);
756
  synthItal = !NILP (tem) && !strncmp ("synthItal", SSDATA (SYMBOL_NAME (tem)),
757
                                       9);
758
  family = ns_get_family (font_entity);
759 760
  if (family == nil)
    family = [[NSFont userFixedPitchFontOfSize: 0] familyName];
761 762 763
  /* Should be > 0.23 as some font descriptors (e.g. Terminus) set to that
     when setting family in ns_spec_to_descriptor(). */
  if (ns_attribute_fvalue (fontDesc, NSFontWeightTrait) > 0.50)
764
      traits |= NSBoldFontMask;
765
  if (fabs (ns_attribute_fvalue (fontDesc, NSFontSlantTrait) > 0.05))
766
      traits |= NSItalicFontMask;
767

768
  /* see http://cocoadev.com/forums/comments.php?DiscussionID=74 */
769 770 771 772 773
  fixLeopardBug = traits & NSBoldFontMask ? 10 : 5;
  nsfont = [fontMgr fontWithFamily: family
                            traits: traits weight: fixLeopardBug
			      size: pixel_size];
  /* if didn't find, try synthetic italic */
774
  if (nsfont == nil && synthItal)
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    {
      nsfont = [fontMgr fontWithFamily: family
                                traits: traits & ~NSItalicFontMask
                                weight: fixLeopardBug size: pixel_size];
    }
#ifdef NS_IMPL_COCOA
  /* LastResort not really a family */
  if (nsfont == nil && [@"LastResort" isEqualToString: family])
      nsfont = [NSFont fontWithName: @"LastResort" size: pixel_size];
#endif

  if (nsfont == nil)
    {
      message_with_string ("*** Warning: font in family '%s' not found",
                          build_string ([family UTF8String]), 1);
      nsfont = [NSFont userFixedPitchFontOfSize: pixel_size];
    }

793 794
  if (NSFONT_TRACE)
    NSLog (@"%@\n", nsfont);
795

796 797 798 799 800 801
  /* Check the cache */
  cached = [fontCache objectForKey: nsfont];
  if (cached != nil && !synthItal)
    {
      if (NSFONT_TRACE)
        fprintf(stderr, "*** nsfont_open CACHE HIT!\n");
802
      /* FIXME: Cast from (unsigned long) to Lisp_Object. */
803 804
      XHASH (font_object) = [cached unsignedLongValue];
      return font_object;
805 806 807 808 809 810
    }
  else
    {
      font_object = font_make_object (VECSIZE (struct nsfont_info),
                                      font_entity, pixel_size);
      if (!synthItal)
811 812 813
        [fontCache setObject: [NSNumber numberWithUnsignedLong:
					  (unsigned long) XHASH (font_object)]
		      forKey: nsfont];
814 815 816
    }

  font_info = (struct nsfont_info *) XFONT_OBJECT (font_object);
817
  font = (struct font *) font_info;
818 819
  if (!font)
    return Qnil; /* FIXME: other terms do, but return Qnil causes segfault */
820

821 822
  font_info->glyphs = xzalloc (0x100 * sizeof *font_info->glyphs);
  font_info->metrics = xzalloc (0x100 * sizeof *font_info->metrics);
823

824
  BLOCK_INPUT;
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

  /* for metrics */
  sfont = [nsfont screenFont];
  if (sfont == nil)
    sfont = nsfont;

  /* non-metric backend font struct fields */
  font = (struct font *) font_info;
  font->pixel_size = [sfont pointSize];
  font->driver = &nsfont_driver;
  font->encoding_type = FONT_ENCODING_NOT_DECIDED;
  font->encoding_charset = -1;
  font->repertory_charset = -1;
  font->default_ascent = 0;
  font->vertical_centering = 0;
  font->baseline_offset = 0;
  font->relative_compose = 0;
  font->font_encoder = NULL;

  font->props[FONT_FORMAT_INDEX] = Qns;
  font->props[FONT_FILE_INDEX] = Qnil;

  {
    const char *fontName = [[nsfont fontName] UTF8String];

850 851 852 853 854 855 856 857
    /* The values specified by fonts are not always exact. For
     * example, a 6x8 font could specify that the descender is
     * -2.00000405... (represented by 0xc000000220000000).  Without
     * adjustment, the code below would round the descender to -3,
     * resulting in a font that would be one pixel higher than
     * intended. */
    CGFloat adjusted_descender = [sfont descender] + 0.0001;

858 859 860 861 862 863 864 865
#ifdef NS_IMPL_GNUSTEP
    font_info->nsfont = sfont;
#else
    font_info->nsfont = nsfont;
#endif
    [font_info->nsfont retain];

    /* set up ns_font (defined in nsgui.h) */
866
    font_info->name = xstrdup (fontName);
867 868 869 870 871 872 873
    font_info->bold = [fontMgr traitsOfFont: nsfont] & NSBoldFontMask;
    font_info->ital =
      synthItal || ([fontMgr traitsOfFont: nsfont] & NSItalicFontMask);

    /* Metrics etc.; some fonts return an unusually large max advance, so we
       only use it for fonts that have wide characters. */
    font_info->width = ([sfont numberOfGlyphs] > 2000) ?
874
      [sfont maximumAdvancement].width : ns_char_width (sfont, '0');
875 876 877

    brect =  [sfont boundingRectForFont];

878
    font_info->underpos = [sfont underlinePosition];
879 880 881 882
    font_info->underwidth = [sfont underlineThickness];
    font_info->size = font->pixel_size;

    /* max bounds */
883
    font_info->max_bounds.ascent = lrint ([sfont ascender]);
884
    /* Descender is usually negative.  Use floor to avoid
885
       clipping descenders. */
886
    font_info->max_bounds.descent = -lrint (floor(adjusted_descender));
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
    font_info->height =
      font_info->max_bounds.ascent + font_info->max_bounds.descent;
    font_info->max_bounds.width = lrint (font_info->width);
    font_info->max_bounds.lbearing = lrint (brect.origin.x);
    font_info->max_bounds.rbearing =
      lrint (brect.size.width - font_info->width);

#ifdef NS_IMPL_COCOA
    /* set up synthItal and the CG font */
    font_info->synthItal = synthItal;
    {
      ATSFontRef atsFont = ATSFontFindFromPostScriptName
        ((CFStringRef)[nsfont fontName], kATSOptionFlagsDefault);

      if (atsFont == kATSFontRefUnspecified)
        {
          /* see if we can get it by dropping italic (then synthesizing) */
          atsFont = ATSFontFindFromPostScriptName ((CFStringRef)
              [[fontMgr convertFont: nsfont toNotHaveTrait: NSItalicFontMask]
                fontName], kATSOptionFlagsDefault);
          if (atsFont != kATSFontRefUnspecified)
              font_info->synthItal = YES;
          else
            {
              /* last resort fallback */
              atsFont = ATSFontFindFromPostScriptName
                ((CFStringRef)@"Monaco", kATSOptionFlagsDefault);
            }
        }
      font_info->cgfont = CGFontCreateWithPlatformFont ((void*)&atsFont);
    }
#endif

    /* set up metrics portion of font struct */
921
    font->ascent = lrint([sfont ascender]);
922
    font->descent = -lrint(floor(adjusted_descender));
923
    font->space_width = lrint (ns_char_width (sfont, ' '));
924
    font->max_width = lrint (font_info->max_bounds.width);
925 926 927
    font->min_width = font->space_width;  /* Approximate.  */
    font->average_width = ns_ascii_average_width (sfont);

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
    font->height = lrint (font_info->height);
    font->underline_position = lrint (font_info->underpos);
    font->underline_thickness = lrint (font_info->underwidth);

    font->props[FONT_NAME_INDEX] = Ffont_xlfd_name (font_object, Qnil);
    font->props[FONT_FULLNAME_INDEX] =
      make_unibyte_string (font_info->name, strlen (font_info->name));
  }
  UNBLOCK_INPUT;

  return font_object;
}


/* Close FONT on frame F. */
static void
nsfont_close (FRAME_PTR f, struct font *font)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  int i;

949
  /* FIXME: this occurs apparently due to same failure to detect same font
950
            that causes need for cache in nsfont_open () */
951 952 953 954 955
  if (!font_info)
      return;

  for (i =0; i<0x100; i++)
    {
956 957
      xfree (font_info->glyphs[i]);
      xfree (font_info->metrics[i]);
958 959 960
    }
  [font_info->nsfont release];
#ifdef NS_IMPL_COCOA
961
  CGFontRelease (font_info->cgfont);
962
#endif
963 964
  xfree (font_info->name);
  xfree (font_info);
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
}


/* If FONT_ENTITY has a glyph for character C (Unicode code point),
   return 1.  If not, return 0.  If a font must be opened to check
   it, return -1. */
static int
nsfont_has_char (Lisp_Object entity, int c)
{
  return -1;
}


/* Return a glyph code of FONT for character C (Unicode code point).
   If FONT doesn't have such a glyph, return FONT_INVALID_CODE. */
static unsigned int
nsfont_encode_char (struct font *font, int c)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  unsigned char high = (c & 0xff00) >> 8, low = c & 0x00ff;
  unsigned short g;

  if (c > 0xFFFF)
    return FONT_INVALID_CODE;

  /* did we already cache this block? */
  if (!font_info->glyphs[high])
    ns_uni_to_glyphs (font_info, high);

  g = font_info->glyphs[high][low];
  return g == 0xFFFF ? FONT_INVALID_CODE : g;
}


/* Perform the size computation of glyphs of FONT and fill in members
   of METRICS.  The glyphs are specified by their glyph codes in
   CODE (length NGLYPHS). */
static int
nsfont_text_extents (struct font *font, unsigned int *code, int nglyphs,
                     struct font_metrics *metrics)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  struct font_metrics *pcm;
  unsigned char high, low;
  int totalWidth = 0;
  int i;

1012
  memset (metrics, 0, sizeof (struct font_metrics));
1013 1014 1015 1016

  for (i =0; i<nglyphs; i++)
    {
      /* get metrics for this glyph, filling cache if need be */
1017 1018
      /* TODO: get metrics for whole string from an NSLayoutManager
               (if not too slow) */
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
      high = (code[i] & 0xFF00) >> 8;
      low = code[i] & 0x00FF;
      if (!font_info->metrics[high])
        ns_glyph_metrics (font_info, high);
      pcm = &(font_info->metrics[high][low]);

      if (metrics->lbearing > totalWidth + pcm->lbearing)
	metrics->lbearing = totalWidth + pcm->lbearing;
      if (metrics->rbearing < totalWidth + pcm->rbearing)
	metrics->rbearing = totalWidth + pcm->rbearing;
      if (metrics->ascent < pcm->ascent)
	metrics->ascent = pcm->ascent;
      if (metrics->descent < pcm->descent)
	metrics->descent = pcm->descent;

      totalWidth += pcm->width;
    }

  metrics->width = totalWidth;

  return totalWidth; /* not specified in doc, but xfont.c does it */
}


/* Draw glyphs between FROM and TO of S->char2b at (X Y) pixel
   position of frame F with S->FACE and S->GC.  If WITH_BACKGROUND
   is nonzero, fill the background in advance.  It is assured that
   WITH_BACKGROUND is zero when (FROM > 0 || TO < S->nchars). */
static int
nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
             int with_background)
/* NOTE: focus and clip must be set
     also, currently assumed (true in nsterm.m call) from ==0, to ==nchars */
{
  static char cbuf[1024];
  char *c = cbuf;
#ifdef NS_IMPL_GNUSTEP
  static float advances[1024];
  float *adv = advances;
#else
  static CGSize advances[1024];
  CGSize *adv = advances;
#endif
  struct face *face;
  NSRect r;
  struct nsfont_info *font = ns_tmp_font;
  NSColor *col, *bgCol;
  unsigned short *t = s->char2b;
  int i, len;
1068 1069
  char isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
  int end = isComposite ? s->cmp_to : s->nchars;
1070 1071 1072 1073 1074 1075 1076 1077

  /* Select face based on input flags */
  switch (ns_tmp_flags)
    {
    case NS_DUMPGLYPH_CURSOR:
      face = s->face;
      break;
    case NS_DUMPGLYPH_MOUSEFACE:
1078
      face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
      if (!face)
        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
      break;
    default:
      face = s->face;
    }

  r.origin.x = s->x;
  if (s->face->box != FACE_NO_BOX && s->first_glyph->left_box_line_p)
    r.origin.x += abs (s->face->box_line_width);

  r.origin.y = s->y;
  r.size.height = FONT_HEIGHT (font);

  /* Convert UTF-16 (?) to UTF-8 and determine advances.  Note if we just ask
     NS to render the string, it will come out differently from the individual
     character widths added up because of layout processing. */
  {
    int cwidth, twidth = 0;
    int hi, lo;
1099
    /* FIXME: composition: no vertical displacement is considered. */
1100
    t += s->cmp_from; /* advance into composition */
1101
    for (i = s->cmp_from; i < end; i++, t++)
1102 1103 1104 1105 1106
      {
        hi = (*t & 0xFF00) >> 8;
        lo = *t & 0x00FF;
        if (isComposite)
          {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	    if (!s->first_glyph->u.cmp.automatic)
		cwidth = s->cmp->offsets[i * 2] /* (H offset) */ - twidth;
	    else
	      {
		Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
		Lisp_Object glyph = LGSTRING_GLYPH (gstring, i);
		if (NILP (LGLYPH_ADJUSTMENT (glyph)))
		    cwidth = LGLYPH_WIDTH (glyph);
		else
		  {
		    cwidth = LGLYPH_WADJUST (glyph);
#ifdef NS_IMPL_GNUSTEP
		    *(adv-1) += LGLYPH_XOFF (glyph);
#else
		    (*(adv-1)).width += LGLYPH_XOFF (glyph);
#endif
		  }
	      }
1125 1126 1127
          }
        else
          {
1128
            if (!font->metrics[hi]) /* FIXME: why/how can we need this now? */
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
              ns_glyph_metrics (font, hi);
            cwidth = font->metrics[hi][lo].width;
          }
        twidth += cwidth;
#ifdef NS_IMPL_GNUSTEP
        *adv++ = cwidth;
        CHAR_STRING_ADVANCE (*t, c); /* this converts the char to UTF-8 */
#else
        (*adv++).width = cwidth;
#endif
      }
    len = adv - advances;
    r.size.width = twidth;
    *c = 0;
  }

  /* fill background if requested */
1146
  if (with_background && !isComposite)
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    {
      NSRect br = r;
      int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
      int mbox_line_width = max (s->face->box_line_width, 0);

      if (s->row->full_width_p)
        {
          if (br.origin.x <= fibw + 1 + mbox_line_width)
            {
              br.size.width += br.origin.x - mbox_line_width;
              br.origin.x = mbox_line_width;
            }
          if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width)
                <= fibw+1)
            br.size.width += fibw;
        }
      if (s->face->box == FACE_NO_BOX)
        {
          /* expand unboxed top row over internal border */
          if (br.origin.y <= fibw + 1 + mbox_line_width)
            {
              br.size.height += br.origin.y;
              br.origin.y = 0;
            }
        }
      else
        {
          int correction = abs (s->face->box_line_width)+1;
          br.origin.y += correction;
          br.size.height -= 2*correction;
          br.origin.x += correction;
          br.size.width -= 2*correction;
        }

      if (!s->face->stipple)
1182
        [(NS_FACE_BACKGROUND (face) != 0
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
          ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
          : FRAME_BACKGROUND_COLOR (s->f)) set];
      else
        {
          struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
          [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
        }
      NSRectFill (br);
    }


  /* set up for character rendering */
1195
  r.origin.y = s->ybase;
1196

1197
  col = (NS_FACE_FOREGROUND (face) != 0
1198 1199
         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f)
         : FRAME_FOREGROUND_COLOR (s->f));
1200
  /* FIXME: find another way to pass this */
1201
  bgCol = (ns_tmp_flags != NS_DUMPGLYPH_FOREGROUND ? nil
1202
           : (NS_FACE_BACKGROUND (face) != 0
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
              ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
              : FRAME_BACKGROUND_COLOR (s->f)));

  /* render under GNUstep using DPS */
#ifdef NS_IMPL_GNUSTEP
  {
    NSGraphicsContext *context = GSCurrentContext ();

    DPSgsave (context);
    [font->nsfont set];

    /* do erase if "foreground" mode */
    if (bgCol != nil)
      {
        [bgCol set];
        DPSmoveto (context, r.origin.x, r.origin.y);
/*[context GSSetTextDrawingMode: GSTextFillStroke]; /// not implemented yet */
        DPSxshow (context, cbuf, advances, len);
        DPSstroke (context);
        [col set];
/*[context GSSetTextDrawingMode: GSTextFill]; /// not implemented yet */
      }

1226
    [col set];
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

    /* draw with DPSxshow () */
    DPSmoveto (context, r.origin.x, r.origin.y);
    DPSxshow (context, cbuf, advances, len);
    DPSstroke (context);

    DPSgrestore (context);
  }

#else  /* NS_IMPL_COCOA */
  {
    CGContextRef gcontext =
      [[NSGraphicsContext currentContext] graphicsPort];
    static CGAffineTransform fliptf;
    static BOOL firstTime = YES;

    if (firstTime)
      {
        firstTime = NO;
        fliptf = CGAffineTransformMakeScale (1.0, -1.0);
      }

    CGContextSaveGState (gcontext);

    fliptf.c =  font->synthItal ? Fix2X (kATSItalicQDSkew) : 0.0;

    CGContextSetFont (gcontext, font->cgfont);
    CGContextSetFontSize (gcontext, font->size);
1255
    if (NILP (ns_antialias_text) || font->size <= ns_antialias_threshold)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
      CGContextSetShouldAntialias (gcontext, 0);
    else
      CGContextSetShouldAntialias (gcontext, 1);

    CGContextSetTextMatrix (gcontext, fliptf);

    if (bgCol != nil)
      {
        /* foreground drawing; erase first to avoid overstrike */
        [bgCol set];
        CGContextSetTextDrawingMode (gcontext, kCGTextFillStroke);
        CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
        CGContextShowGlyphsWithAdvances (gcontext, s->char2b, advances, len);
        CGContextSetTextDrawingMode (gcontext, kCGTextFill);
      }

1272
    [col set];
1273 1274

    CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
1275
    CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
1276 1277 1278 1279 1280
                                    advances, len);

    if (face->overstrike)
      {
        CGContextSetTextPosition (gcontext, r.origin.x+0.5, r.origin.y);
1281
        CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
1282 1283 1284 1285 1286 1287
                                        advances, len);
      }

    CGContextRestoreGState (gcontext);
  }
#endif  /* NS_IMPL_COCOA */
1288 1289 1290 1291

  /* Draw underline, overline, strike-through. */
  ns_draw_text_decoration (s, face, col, r.size.width, r.origin.x);

1292
  return to-from;
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
}



/* ==========================================================================

    Font glyph and metrics caching functions

   ========================================================================== */

/* Find and cache corresponding glyph codes for unicode values in given
   hi-byte block of 256. */
static void
ns_uni_to_glyphs (struct nsfont_info *font_info, unsigned char block)
{
#ifdef NS_IMPL_COCOA
  static EmacsGlyphStorage *glyphStorage;
  static char firstTime = 1;
#endif
  unichar *unichars = xmalloc (0x101 * sizeof (unichar));
  unsigned int i, g, idx;
  unsigned short *glyphs;

  if (NSFONT_TRACE)
    fprintf (stderr, "%p\tFinding glyphs for glyphs in block %d\n",
            font_info, block);

 BLOCK_INPUT;

#ifdef NS_IMPL_COCOA
  if (firstTime)
    {
      firstTime = 0;
      glyphStorage = [[EmacsGlyphStorage alloc] initWithCapacity: 0x100];
    }
#endif

  font_info->glyphs[block] = xmalloc (0x100 * sizeof (unsigned short));
  if (!unichars || !(font_info->glyphs[block]))
    abort ();

Juanma Barranquero's avatar
Juanma Barranquero committed
1334
  /* create a string containing all Unicode characters in this block */
1335
  for (idx = block<<8, i = 0; i < 0x100; idx++, i++)
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    if (idx < 0xD800 || idx > 0xDFFF)
      unichars[i] = idx;
    else
      unichars[i] = 0xFEFF;
  unichars[0x100] = 0;

  {
#ifdef NS_IMPL_COCOA
    NSString *allChars = [[NSString alloc]
                               initWithCharactersNoCopy: unichars
                                                 length: 0x100
                                           freeWhenDone: NO];
    NSGlyphGenerator *glyphGenerator = [NSGlyphGenerator sharedGlyphGenerator];
    /*NSCharacterSet *coveredChars = [nsfont coveredCharacterSet]; */
    unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
1351
    NSUInteger gInd = 0, cInd = 0;
1352 1353 1354 1355 1356 1357 1358

    [glyphStorage setString: allChars font: font_info->nsfont];
    [glyphGenerator generateGlyphsForGlyphStorage: glyphStorage
                        desiredNumberOfCharacters: glyphStorage->maxChar
                                       glyphIndex: &gInd characterIndex: &cInd];
#endif
    glyphs = font_info->glyphs[block];
1359
    for (i = 0; i < 0x100; i++, glyphs++)
1360 1361 1362 1363 1364
      {
#ifdef NS_IMPL_GNUSTEP
        g = unichars[i];
#else
        g = glyphStorage->cglyphs[i];
1365
        /* TODO: is this a good check?  maybe need to use coveredChars.. */
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
        if (g > numGlyphs)
          g = 0xFFFF; /* hopefully unused... */
#endif
        *glyphs = g;
      }

#ifdef NS_IMPL_COCOA
    [allChars release];
#endif
  }

  UNBLOCK_INPUT;
  xfree (unichars);
}


/* Determine and cache metrics for corresponding glyph codes in given
   hi-byte block of 256. */
static void
ns_glyph_metrics (struct nsfont_info *font_info, unsigned char block)
{
  unsigned int i, g;
  unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
  NSFont *sfont;
  struct font_metrics *metrics;

  if (NSFONT_TRACE)
    fprintf (stderr, "%p\tComputing metrics for glyphs in block %d\n",
            font_info, block);

#ifdef NS_IMPL_GNUSTEP
  /* not implemented yet (as of startup 0.18), so punt */
  if (numGlyphs == 0)
    numGlyphs = 0x10000;
#endif

 BLOCK_INPUT;
 sfont = [font_info->nsfont screenFont];

1405
  font_info->metrics[block] = xzalloc (0x100 * sizeof (struct font_metrics));
1406 1407 1408 1409 1410 1411 1412 1413 1414
  if (!(font_info->metrics[block]))
    abort ();

  metrics = font_info->metrics[block];
  for (g = block<<8, i =0; i<0x100 && g < numGlyphs; g++, i++, metrics++)
    {
      float w, lb, rb;
      NSRect r = [sfont boundingRectForGlyph: g];

1415
      w = max ([sfont advancementForGlyph: g].width, 2.0);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
      metrics->width = lrint (w);

      lb = r.origin.x;
      rb = r.size.width - w;
      if (lb < 0)
        metrics->lbearing = round (lb);
      if (font_info->ital)
        rb += 0.22 * font_info->height;
      metrics->rbearing = lrint (w + rb);

      metrics->descent = r.origin.y < 0 ? -r.origin.y : 0;
 /*lrint (hshrink * [sfont ascender] + expand * hd/2); */
      metrics->ascent = r.size.height - metrics->descent;
/*-lrint (hshrink* [sfont descender] - expand * hd/2); */
    }
  UNBLOCK_INPUT;
}


#ifdef NS_IMPL_COCOA
/* helper for font glyph setup */
@implementation EmacsGlyphStorage

- init
{
  return [self initWithCapacity: 1024];
}

- initWithCapacity: (unsigned long) c
{
  self = [super init];
  maxChar = 0;
  maxGlyph = 0;
  dict = [NSMutableDictionary new];
1450
  cglyphs = xmalloc (c * sizeof (CGGlyph));
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
  return self;
}

- (void) dealloc
{
  if (attrStr != nil)
    [attrStr release];
  [dict release];
  xfree (cglyphs);
  [super dealloc];
}

- (void) setString: (NSString *)str font: (NSFont *)font
{
  [dict setObject: font forKey: NSFontAttributeName];
1466 1467
  if (attrStr != nil)
    [attrStr release];
1468 1469 1470 1471 1472 1473
  attrStr = [[NSAttributedString alloc] initWithString: str attributes: dict];
  maxChar = [str length];
  maxGlyph = 0;
}

/* NSGlyphStorage protocol */
1474
- (NSUInteger)layoutOptions
1475 1476 1477 1478 1479 1480 1481 1482 1483
{
  return 0;
}

- (NSAttributedString *)attributedString
{
  return attrStr;
}

1484 1485 1486
- (void)insertGlyphs: (const NSGlyph *)glyphs length: (NSUInteger)length
        forStartingGlyphAtIndex: (NSUInteger)glyphIndex
        characterIndex: (NSUInteger)charIndex
1487 1488 1489 1490 1491 1492 1493 1494
{
  len = glyphIndex+length;
  for (i =glyphIndex; i<len; i++)
    cglyphs[i] = glyphs[i-glyphIndex];
  if (len > maxGlyph)
    maxGlyph = len;
}

1495 1496
- (void)setIntAttribute: (NSInteger)attributeTag value: (NSInteger)val
        forGlyphAtIndex: (NSUInteger)glyphIndex
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
{
  return;
}

@end
#endif /* NS_IMPL_COCOA */


/* Debugging */
void