1 /* Font back-end driver for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
5 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 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 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/>.
20 Author: Adrian Robert (arobert@cogsci.ucsd.edu)
26 #include "dispextern.h"
27 #include "composite.h"
28 #include "blockinput.h"
35 #include "character.h"
38 #define NSFONT_TRACE 0
40 extern Lisp_Object Qns;
41 extern Lisp_Object Qnormal, Qbold, Qitalic, Qcondensed, Qexpanded;
42 static Lisp_Object Qapple, Qroman, Qmedium;
43 extern Lisp_Object ns_expand_space;
44 extern Lisp_Object Qappend;
45 extern int ns_antialias_text, ns_use_qd_smoothing;
46 extern float ns_antialias_threshold;
47 extern int ns_tmp_flags;
48 extern struct nsfont_info *ns_tmp_font;
50 /* font glyph and metrics caching functions, implemented at end */
51 static void ns_uni_to_glyphs (struct nsfont_info *font_info,
53 static void ns_glyph_metrics (struct nsfont_info *font_info,
57 /* ==========================================================================
61 ========================================================================== */
64 /* Replace spaces w/another character so emacs core font parsing routines
67 nsfont_escape_name (char *name)
69 int i =0, len =strlen (name);
76 /* Reconstruct spaces in a font family name passed through emacs. */
78 nsfont_unescape_name (char *name)
80 int i =0, len =strlen (name);
87 /* Extract family name from a font spec. */
89 nsfont_get_family (Lisp_Object font_spec)
91 Lisp_Object tem = AREF (font_spec, FONT_FAMILY_INDEX);
96 char *tmp = strdup (SDATA (SYMBOL_NAME (tem)));
98 nsfont_unescape_name (tmp);
99 /* TODO: this seems to be needed only for font names that are
100 hard-coded into emacs, like 'helvetica' for splash screen */
102 tmp[0] = toupper (tmp[0]);
103 family = [NSString stringWithUTF8String: tmp];
110 /* Converts FONT_WEIGHT, FONT_SLANT, FONT_WIDTH to NSFont traits. */
111 /* TODO (20080601): The font backend's strategy for handling font
112 styles continues to evolve. When/if this stabilizes, we
113 can change the code here to be more sophisticated and accurate.
114 For now, we rely on "normal/plain" style being numeric 100. */
115 #define STYLE_REF 100
117 nsfont_spec_to_traits (Lisp_Object font_spec)
119 unsigned int traits = 0;
122 n = FONT_WEIGHT_NUMERIC (font_spec);
124 traits |= (n > STYLE_REF) ? NSBoldFontMask : NSUnboldFontMask;
126 n = FONT_SLANT_NUMERIC (font_spec);
128 traits |= (n > STYLE_REF) ? NSItalicFontMask : NSUnitalicFontMask;
130 n = FONT_WIDTH_NUMERIC (font_spec);
133 if (n < STYLE_REF - 10)
134 traits |= NSCondensedFontMask;
135 else if (n > STYLE_REF + 10)
136 traits |= NSExpandedFontMask;
139 /*fprintf (stderr, " returning traits = %u\n", traits); */
144 /* Converts NSArray of PS name, non-family part, weight, and traits to a
145 font backend font-entity. */
147 nsfont_fmember_to_entity (NSString *family, NSArray *famMember)
149 Lisp_Object font_entity = font_make_entity ();
150 unsigned int traits = [[famMember objectAtIndex: 3] unsignedIntValue];
151 /* NSString *psName = [famMember objectAtIndex: 0]; */
152 NSMutableString *suffix = [[famMember objectAtIndex: 1] mutableCopy];
153 char *escapedFamily = strdup ([family UTF8String]);
155 nsfont_escape_name (escapedFamily);
156 [suffix replaceOccurrencesOfString: @" " withString: @"" options: 0
157 range: NSMakeRange (0, [suffix length])];
159 ASET (font_entity, FONT_TYPE_INDEX, Qns);
160 ASET (font_entity, FONT_FOUNDRY_INDEX, Qapple);
161 ASET (font_entity, FONT_FAMILY_INDEX, intern (escapedFamily));
162 ASET (font_entity, FONT_ADSTYLE_INDEX, intern ([suffix UTF8String]));
163 ASET (font_entity, FONT_REGISTRY_INDEX, Qiso10646_1);
165 FONT_SET_STYLE (font_entity, FONT_WEIGHT_INDEX,
166 traits & NSBoldFontMask ? Qbold : Qmedium);
167 FONT_SET_STYLE (font_entity, FONT_SLANT_INDEX,
168 traits & NSItalicFontMask ? Qitalic : Qnormal); /*XXX: should be Qroman */
169 FONT_SET_STYLE (font_entity, FONT_WIDTH_INDEX,
170 traits & NSCondensedFontMask ? Qcondensed :
171 traits & NSExpandedFontMask ? Qexpanded : Qnormal);
173 ASET (font_entity, FONT_SIZE_INDEX, make_number (0));
174 ASET (font_entity, FONT_EXTRA_INDEX, Qnil);
175 ASET (font_entity, FONT_OBJLIST_INDEX, Qnil);
179 fprintf (stderr, "created font_entity:\n ");
180 debug_print (font_entity);
184 free (escapedFamily);
189 /* Computes Hamming distance btwn two "vectors" of 0's and 1's. */
191 nsfont_trait_distance (unsigned int traits1, unsigned int traits2)
194 for (i = 0; i < sizeof (unsigned int) * 8; i++)
196 d += (traits1 & 0x1) ^ (traits2 & 0x1);
204 /* Default font entity based on Monaco. */
206 nsfont_fallback_entity ()
208 NSString *family = [[NSFont userFixedPitchFontOfSize: 0] familyName];
209 NSArray *famMemberSpec = [NSArray arrayWithObjects: family, @"",
210 [NSNumber numberWithUnsignedInt: 5],
211 [NSNumber numberWithUnsignedInt: 0], nil];
212 return nsfont_fmember_to_entity (family, famMemberSpec);
216 /* ==========================================================================
218 Font driver implementation
220 ========================================================================== */
222 static Lisp_Object nsfont_get_cache (FRAME_PTR frame);
223 static Lisp_Object nsfont_list (Lisp_Object frame, Lisp_Object font_spec);
224 static Lisp_Object nsfont_match (Lisp_Object frame, Lisp_Object font_spec);
225 static Lisp_Object nsfont_list_family (Lisp_Object frame);
226 static Lisp_Object nsfont_open (FRAME_PTR f, Lisp_Object font_entity,
228 static void nsfont_close (FRAME_PTR f, struct font *font);
229 static int nsfont_has_char (Lisp_Object entity, int c);
230 static unsigned int nsfont_encode_char (struct font *font, int c);
231 static int nsfont_text_extents (struct font *font, unsigned int *code,
232 int nglyphs, struct font_metrics *metrics);
233 static int nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
234 int with_background);
236 struct font_driver nsfont_driver =
239 1, /* case sensitive */
244 NULL, /*free_entity */
247 NULL, /* prepare_face */
248 NULL, /* done_face */
253 /* excluded: get_bitmap, free_bitmap, get_outline, free_outline,
254 anchor_point, otf_capability, otf_driver,
255 start_for_frame, end_for_frame, shape */
259 /* Return a cache of font-entities on FRAME. The cache must be a
260 cons whose cdr part is the actual cache area. */
262 nsfont_get_cache (FRAME_PTR frame)
264 Display_Info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
265 return (dpyinfo->name_list_element);
269 /* List fonts exactly matching with FONT_SPEC on FRAME. The value
270 is a **list** of font-entities. This is the sole API that
271 allocates font-entities. */
273 nsfont_list (Lisp_Object frame, Lisp_Object font_spec)
275 Lisp_Object list = Qnil;
279 NSEnumerator *famEnum;
280 NSFontManager *fontMgr;
281 unsigned int traits = nsfont_spec_to_traits (font_spec);
285 fprintf (stderr, "nsfont: list for fontspec:\n ");
286 debug_print (font_spec);
289 /* if has non-unicode registry, give up */
290 tem = AREF (font_spec, FONT_REGISTRY_INDEX);
291 if (!EQ (tem, Qiso10646_1) && !EQ (tem, Qunicode_bmp))
294 fontMgr = [NSFontManager sharedFontManager];
296 family = nsfont_get_family (font_spec);
299 families = [NSArray arrayWithObject: family];
301 families = [fontMgr availableFontFamilies];
303 for (famEnum = [families objectEnumerator]; family = [famEnum nextObject]; )
306 NSArray *fmember, *firstMember = nil;
307 unsigned int mtraits;
308 BOOL foundItal = NO || (traits & NSUnitalicFontMask);
309 NSArray *famMembers = [fontMgr availableMembersOfFontFamily: family];
311 /* LastResort is special: not a family but a font name only */
312 if ([@"LastResort" isEqualToString: family] && [famMembers count] == 0)
314 famMembers = [NSArray arrayWithObject: [NSArray arrayWithObjects:
315 @"LastResort", @"", [NSNumber numberWithUnsignedInt: 5],
316 [NSNumber numberWithUnsignedInt: 0], nil]];
320 /* fmember = [postscriptName style weight traits] */
321 fm = [famMembers objectEnumerator];
322 while (fmember = [fm nextObject])
324 mtraits = [[fmember objectAtIndex: 3] unsignedIntValue];
325 if ((mtraits & traits) == traits)
327 list = Fcons (nsfont_fmember_to_entity (family, fmember), list);
328 if (mtraits & NSItalicFontMask)
330 if (firstMember == nil)
331 firstMember = fmember;
334 if (foundItal == NO && firstMember != nil)
336 /* no italic member found; add a synthesized one */
337 NSMutableArray *smember = [firstMember mutableCopy];
338 [smember replaceObjectAtIndex: 1 withObject: @"synthItal" ];
339 mtraits = [[fmember objectAtIndex: 3] unsignedIntValue];
340 mtraits |= NSItalicFontMask;
341 [smember replaceObjectAtIndex: 3
342 withObject: [NSNumber numberWithUnsignedInt: mtraits]];
343 /*NSLog (@"-- adding synthItal member: %@", smember); */
344 list = Fcons (nsfont_fmember_to_entity (family, smember), list);
350 fprintf (stderr, " Returning %d entities.\n", XINT (Flength (list)));
356 /* Return a font entity most closely maching with FONT_SPEC on
357 FRAME. The closeness is determined by the font backend, thus
358 `face-font-selection-order' is ignored here. */
360 nsfont_match (Lisp_Object frame, Lisp_Object font_spec)
362 long traits = nsfont_spec_to_traits (font_spec);
363 NSFontManager *fontMgr = [NSFontManager sharedFontManager];
369 fprintf (stderr, "nsfont: match for fontspec:\n ");
370 debug_print (font_spec);
373 /* if has non-unicode registry, just return fallback */
375 tem = AREF (font_spec, FONT_ADSTYLE_INDEX);
377 fprintf (stderr, "adstyle: '%s'\n", SDATA (tem));
379 tem = AREF (font_spec, FONT_REGISTRY_INDEX);
380 if (!EQ (tem, Qiso10646_1) && !EQ (tem, Qunicode_bmp))
381 return nsfont_fallback_entity ();
383 family = nsfont_get_family (font_spec);
387 /* try to find close font in family */
388 NSArray *famMembers = [fontMgr availableMembersOfFontFamily: family];
389 NSEnumerator *fm = [famMembers objectEnumerator];
391 int minDist = sizeof (unsigned int) * 8 + 1;
392 int bestMatchIdx = -1;
395 for (i =0; fmember = [fm nextObject]; i++)
397 unsigned int mtraits = [[fmember objectAtIndex: 3] unsignedIntValue];
398 int dist = nsfont_trait_distance ((mtraits & traits), traits);
405 if (bestMatchIdx != -1)
406 return nsfont_fmember_to_entity
407 (family, [famMembers objectAtIndex: bestMatchIdx]);
410 /* no family that had members was given; find any font matching traits */
412 NSArray *fontNames = [fontMgr availableFontNamesWithTraits: traits];
413 if (fontNames && [fontNames count] > 0)
415 NSString *fontName = [fontNames objectAtIndex: 0];
416 /* XXX: is there a more efficient way to get family name? */
417 NSFont *font = [NSFont fontWithName: fontName size: 0];
420 /* now need to get suffix part of name.. */
421 NSString *family = [font familyName];
422 NSEnumerator *fm = [[fontMgr availableMembersOfFontFamily: family]
425 while (fmember = [fm nextObject])
427 unsigned int mtraits =
428 [[fmember objectAtIndex: 3] unsignedIntValue];
429 if (mtraits & traits == traits)
430 return nsfont_fmember_to_entity (family, fmember);
436 /* if we get here, return the fallback */
438 fprintf (stderr, " *** returning fallback\n");
440 return nsfont_fallback_entity ();
444 /* List available families. The value is a list of family names
447 nsfont_list_family (Lisp_Object frame)
449 Lisp_Object list = Qnil;
450 NSEnumerator *families =
451 [[[NSFontManager sharedFontManager] availableFontFamilies]
454 while (family = [families nextObject])
455 list = Fcons (intern ([family UTF8String]), list);
456 /* FIXME: escape the name? */
459 fprintf (stderr, "nsfont: list families returning %d entries\n",
460 XINT (Flength (list)));
466 /* utility: get width of a char c in screen font sfont */
468 nsfont_char_width (NSFont *sfont, int c)
471 NSString *cstr = [NSString stringWithFormat: @"%c", c];
473 NSGlyph glyph = [sfont glyphWithName: cstr];
476 float w = [sfont advancementForGlyph: glyph].width;
481 w = [sfont widthOfString: cstr];
486 /* Open a font specified by FONT_ENTITY on frame F. If the font is
487 scalable, open it with PIXEL_SIZE. */
489 nsfont_open (FRAME_PTR f, Lisp_Object font_entity, int pixel_size)
492 struct nsfont_info *font_info;
494 unsigned int traits = nsfont_spec_to_traits (font_entity);
495 NSFontManager *fontMgr = [NSFontManager sharedFontManager];
497 NSFont *nsfont, *sfont;
500 Lisp_Object font_object;
504 static NSMutableDictionary *fontCache = nil;
506 /* 2008/03/08: The same font may end up being requested for different
507 entities, due to small differences in numeric values or other issues,
508 or for different copies of the same entity. Therefore we cache to
509 avoid creating multiple struct font objects (with metrics cache, etc.)
510 for the same NSFont object.
511 2008/06/01: This is still an issue, but after font backend refactoring
512 caching will be more difficult, needs to be reworked before enabling. */
513 if (fontCache == nil)
514 fontCache = [[NSMutableDictionary alloc] init];
517 font_object = font_make_object (VECSIZE (struct nsfont_info), font_entity,
519 font_info = (struct nsfont_info *) XFONT_OBJECT (font_object);
520 font = (struct font *)font_info;
522 return Qnil; /* FIXME: this copies w32, but causes a segfault */
526 fprintf (stderr, "nsfont: open size %d of fontentity:\n ", pixel_size);
527 debug_print (font_entity);
532 /* try to get it out of frame params */
533 Lisp_Object tem = get_frame_param (f, Qfontsize);
534 pixel_size = NILP (tem) ? 0 : XFASTINT (tem);
537 tem = AREF (font_entity, FONT_ADSTYLE_INDEX);
538 synthItal = !NILP (tem) && !strncmp ("synthItal", SDATA (SYMBOL_NAME (tem)),
540 family = nsfont_get_family (font_entity);
543 fprintf (stderr, "family: '%s'\ttraits = %ld\tbold = %d\titalic = %d\n",
544 [family UTF8String], traits, traits & NSBoldFontMask,
545 traits & NSItalicFontMask);
548 /* see http://cocoadev.com/forums/comments.php?DiscussionID =74 */
549 fixLeopardBug = traits & NSBoldFontMask ? 10 : 5;
550 nsfont = [fontMgr fontWithFamily: family
551 traits: traits weight: fixLeopardBug
553 /* if didn't find, try synthetic italic */
554 if (nsfont == nil && synthItal && (traits & NSItalicFontMask))
556 nsfont = [fontMgr fontWithFamily: family
557 traits: traits & ~NSItalicFontMask
558 weight: fixLeopardBug size: pixel_size];
561 /* LastResort not really a family */
562 if (nsfont == nil && [@"LastResort" isEqualToString: family])
564 nsfont = [NSFont fontWithName: @"LastResort" size: pixel_size];
570 message_with_string ("*** Warning: font in family '%s' not found",
571 build_string ([family UTF8String]), 1);
572 nsfont = [NSFont userFixedPitchFontOfSize: pixel_size];
575 fprintf (stderr, "*** Emacs.app: unable to load backup font\n");
580 //NSLog(@"%@\n",nsfont);
584 NSNumber *cached = [fontCache objectForKey: nsfont];
585 if (cached != nil && !synthItal)
587 fprintf (stderr, "*** CACHE HIT!\n");
588 struct font_info *existing =
589 (struct nsfont_info *)[cached unsignedLongValue];
596 setObject: [NSNumber numberWithUnsignedLong:
597 (unsigned long)font_info]
603 font_info->glyphs = (unsigned short **)
604 xmalloc (0x100 * sizeof (unsigned short *));
605 font_info->metrics = (struct font_metrics **)
606 xmalloc (0x100 * sizeof (struct font_metrics *));
607 if (!font_info->glyphs || !font_info->metrics)
609 bzero (font_info->glyphs, 0x100 * sizeof (unsigned short *));
610 bzero (font_info->metrics, 0x100 * sizeof (struct font_metrics *));
616 sfont = [nsfont screenFont];
620 /* non-metric backend font struct fields */
621 font = (struct font *) font_info;
622 font->pixel_size = [sfont pointSize];
623 font->driver = &nsfont_driver;
624 font->encoding_type = FONT_ENCODING_NOT_DECIDED;
625 font->encoding_charset = -1;
626 font->repertory_charset = -1;
627 font->default_ascent = 0;
628 font->vertical_centering = 0;
629 font->baseline_offset = 0;
630 font->relative_compose = 0;
631 font->font_encoder = NULL;
633 /* TODO: does anything care about this? */
634 font->props[FONT_FORMAT_INDEX] = Qns;
635 font->props[FONT_FILE_INDEX] = Qnil;
638 double expand, shrink, hshrink;
639 float full_height, min_height, hd;
640 const char *fontName = [[nsfont fontName] UTF8String];
641 int len = strlen (fontName);
643 #ifdef NS_IMPL_GNUSTEP
644 font_info->nsfont = sfont;
646 font_info->nsfont = nsfont;
648 [font_info->nsfont retain];
650 /* set up ns_font (defined in nsgui.h) */
651 font_info->name = (char *)xmalloc (strlen (fontName)+1);
652 bcopy (fontName, font_info->name, strlen (fontName)+1);
653 font_info->bold = [fontMgr traitsOfFont: nsfont] & NSBoldFontMask;
655 synthItal || ([fontMgr traitsOfFont: nsfont] & NSItalicFontMask);
657 /* Metrics etc.; some fonts return an unusually large max advance, so we
658 only use it for fonts that have wide characters. */
659 font_info->width = ([sfont numberOfGlyphs] > 2000) ?
660 [sfont maximumAdvancement].width : nsfont_char_width (sfont, '0');
662 brect = [sfont boundingRectForFont];
663 full_height = brect.size.height;
664 min_height = [sfont ascender] - [sfont descender];
665 hd = full_height - min_height;
667 if (!NUMBERP (ns_expand_space))
668 error ("No expand space defined");
670 /* ns_expand_space = 0.0 is use standard height; less shrink, more expand */
671 expand = XFLOATINT (ns_expand_space) + 0.5;
676 hshrink = 1 + expand / 2.0;
680 shrink = hshrink = 1.0;
682 font_info->underpos = 2; /*[sfont underlinePosition] is often clipped out */
683 font_info->underwidth = [sfont underlineThickness];
684 font_info->size = font->pixel_size;
685 font_info->voffset = lrint (hshrink * [sfont ascender] + expand * hd / 2);
688 font_info->max_bounds.ascent =
689 lrint (hshrink * [sfont ascender] + expand * hd/2);
690 font_info->max_bounds.descent =
691 -lrint (hshrink* [sfont descender] - expand*hd/2);
693 font_info->max_bounds.ascent + font_info->max_bounds.descent;
694 font_info->max_bounds.width = lrint (font_info->width);
695 font_info->max_bounds.lbearing = lrint (brect.origin.x);
696 font_info->max_bounds.rbearing =
697 lrint (brect.size.width - font_info->width);
698 /*font_info->width + (font_info->ital ? 0.2 * font_info->height : 0); */
701 /* set up synthItal and the CG font */
702 font_info->synthItal = synthItal;
704 ATSFontRef atsFont = ATSFontFindFromPostScriptName
705 ((CFStringRef)[nsfont fontName], kATSOptionFlagsDefault);
707 if (atsFont == kATSFontRefUnspecified)
709 /* see if we can get it by dropping italic (then synthesizing) */
710 atsFont = ATSFontFindFromPostScriptName ((CFStringRef)
711 [[fontMgr convertFont: nsfont toNotHaveTrait: NSItalicFontMask]
712 fontName], kATSOptionFlagsDefault);
713 if (atsFont != kATSFontRefUnspecified)
714 font_info->synthItal = YES;
717 /* last resort fallback */
718 atsFont = ATSFontFindFromPostScriptName
719 ((CFStringRef)@"Monaco", kATSOptionFlagsDefault);
722 font_info->cgfont = CGFontCreateWithPlatformFont ((void*)&atsFont);
726 /* set up metrics portion of font struct */
727 font->ascent = [sfont ascender];
728 font->descent = -[sfont descender];
729 font->min_width = [sfont widthOfString: @"|"]; /* FIXME */
730 font->space_width = lrint (nsfont_char_width (sfont, ' '));
731 font->average_width = lrint (font_info->width);
732 font->max_width = lrint (font_info->max_bounds.width);
733 font->height = lrint (font_info->height);
734 font->underline_position = lrint (font_info->underpos);
735 font->underline_thickness = lrint (font_info->underwidth);
737 font->props[FONT_NAME_INDEX] = Ffont_xlfd_name (font_object, Qnil);
738 font->props[FONT_FULLNAME_INDEX] =
739 make_unibyte_string (font_info->name, strlen (font_info->name));
747 /* Close FONT on frame F. */
749 nsfont_close (FRAME_PTR f, struct font *font)
751 struct nsfont_info *font_info = (struct nsfont_info *)font;
754 /* FIXME: this occurs apparently due to same failure to detect same font
755 that causes need for cache in nsfont_open ()
756 (came after unicode-2 -> trunk) */
760 for (i =0; i<0x100; i++)
762 if (font_info->glyphs[i])
763 xfree (font_info->glyphs[i]);
764 if (font_info->metrics[i])
765 xfree (font_info->metrics[i]);
767 [font_info->nsfont release];
769 CGFontRelease (font_info->cgfont);
771 xfree (font_info->name);
776 /* If FONT_ENTITY has a glyph for character C (Unicode code point),
777 return 1. If not, return 0. If a font must be opened to check
780 nsfont_has_char (Lisp_Object entity, int c)
786 /* Return a glyph code of FONT for character C (Unicode code point).
787 If FONT doesn't have such a glyph, return FONT_INVALID_CODE. */
789 nsfont_encode_char (struct font *font, int c)
791 struct nsfont_info *font_info = (struct nsfont_info *)font;
792 unsigned char high = (c & 0xff00) >> 8, low = c & 0x00ff;
796 return FONT_INVALID_CODE;
798 /* did we already cache this block? */
799 if (!font_info->glyphs[high])
800 ns_uni_to_glyphs (font_info, high);
802 g = font_info->glyphs[high][low];
803 /*fprintf (stderr, "mapping char %d -> %d\n", c, g); */
804 return g == 0xFFFF ? FONT_INVALID_CODE : g;
808 /* Perform the size computation of glyphs of FONT and fill in members
809 of METRICS. The glyphs are specified by their glyph codes in
810 CODE (length NGLYPHS). */
812 nsfont_text_extents (struct font *font, unsigned int *code, int nglyphs,
813 struct font_metrics *metrics)
815 struct nsfont_info *font_info = (struct nsfont_info *)font;
816 struct font_metrics *pcm;
817 unsigned char high, low;
821 bzero (metrics, sizeof (struct font_metrics));
823 for (i =0; i<nglyphs; i++)
825 /* get metrics for this glyph, filling cache if need be */
826 /* TODO: get metrics for whole string from an NSLayoutManager
828 high = (code[i] & 0xFF00) >> 8;
829 low = code[i] & 0x00FF;
830 if (!font_info->metrics[high])
831 ns_glyph_metrics (font_info, high);
832 pcm = &(font_info->metrics[high][low]);
834 if (metrics->lbearing > totalWidth + pcm->lbearing)
835 metrics->lbearing = totalWidth + pcm->lbearing;
836 if (metrics->rbearing < totalWidth + pcm->rbearing)
837 metrics->rbearing = totalWidth + pcm->rbearing;
838 if (metrics->ascent < pcm->ascent)
839 metrics->ascent = pcm->ascent;
840 if (metrics->descent < pcm->descent)
841 metrics->descent = pcm->descent;
843 totalWidth += pcm->width;
846 metrics->width = totalWidth;
848 return totalWidth; /* not specified in doc, but xfont.c does it */
852 /* Draw glyphs between FROM and TO of S->char2b at (X Y) pixel
853 position of frame F with S->FACE and S->GC. If WITH_BACKGROUND
854 is nonzero, fill the background in advance. It is assured that
855 WITH_BACKGROUND is zero when (FROM > 0 || TO < S->nchars). */
857 nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
859 /* NOTE: focus and clip must be set
860 also, currently assumed (true in nsterm.m call) from ==0, to ==nchars */
862 static char cbuf[1024];
864 #ifdef NS_IMPL_GNUSTEP
865 static float advances[1024];
866 float *adv = advances;
868 static CGSize advances[1024];
869 CGSize *adv = advances;
873 struct nsfont_info *font = ns_tmp_font;
874 NSColor *col, *bgCol;
875 unsigned short *t = s->char2b;
878 /* Select face based on input flags */
879 switch (ns_tmp_flags)
881 case NS_DUMPGLYPH_CURSOR:
884 case NS_DUMPGLYPH_MOUSEFACE:
885 face = FACE_FROM_ID (s->f,
886 FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
888 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
895 if (s->face->box != FACE_NO_BOX && s->first_glyph->left_box_line_p)
896 r.origin.x += abs (s->face->box_line_width);
899 r.size.height = FONT_HEIGHT (font);
901 /* Convert UTF-16 (?) to UTF-8 and determine advances. Note if we just ask
902 NS to render the string, it will come out differently from the individual
903 character widths added up because of layout processing. */
906 int cwidth, twidth = 0;
908 char isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
909 /* FIXME: composition: no vertical displacement is considered. */
910 t += s->cmp_from; /* advance into composition */
911 for (i = s->cmp_from; i < s->nchars; i++, t++)
913 hi = (*t & 0xFF00) >> 8;
917 cwidth = s->cmp->offsets[i * 2] /* (H offset) */ - twidth;
921 if (!font->metrics[hi]) /* FIXME: why/how can we need this now? */
922 ns_glyph_metrics (font, hi);
923 cwidth = font->metrics[hi][lo].width;
926 #ifdef NS_IMPL_GNUSTEP
928 CHAR_STRING_ADVANCE (*t, c); /* this converts the char to UTF-8 */
930 (*adv++).width = cwidth;
933 len = adv - advances;
934 r.size.width = twidth;
938 /* fill background if requested */
942 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
943 int mbox_line_width = max (s->face->box_line_width, 0);
945 if (s->row->full_width_p)
947 if (br.origin.x <= fibw + 1 + mbox_line_width)
949 br.size.width += br.origin.x - mbox_line_width;
950 br.origin.x = mbox_line_width;
952 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width)
954 br.size.width += fibw;
956 if (s->face->box == FACE_NO_BOX)
958 /* expand unboxed top row over internal border */
959 if (br.origin.y <= fibw + 1 + mbox_line_width)
961 br.size.height += br.origin.y;
967 int correction = abs (s->face->box_line_width)+1;
968 br.origin.y += correction;
969 br.size.height -= 2*correction;
970 br.origin.x += correction;
971 br.size.width -= 2*correction;
974 if (!s->face->stipple)
975 [(NS_FACE_BACKGROUND (face) != 0
976 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
977 : FRAME_BACKGROUND_COLOR (s->f)) set];
980 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
981 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
987 /* set up for character rendering */
988 r.origin.y += font->voffset + (s->height - font->height)/2;
990 col = (NS_FACE_FOREGROUND (face) != 0
991 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f)
992 : FRAME_FOREGROUND_COLOR (s->f));
993 /* FIXME: find another way to pass this */
994 bgCol = (ns_tmp_flags != NS_DUMPGLYPH_FOREGROUND ? nil
995 : (NS_FACE_BACKGROUND (face) != 0
996 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
997 : FRAME_BACKGROUND_COLOR (s->f)));
999 /* render under GNUstep using DPS */
1000 #ifdef NS_IMPL_GNUSTEP
1002 NSGraphicsContext *context = GSCurrentContext ();
1007 /* do erase if "foreground" mode */
1011 DPSmoveto (context, r.origin.x, r.origin.y);
1012 /*[context GSSetTextDrawingMode: GSTextFillStroke]; /// not implemented yet */
1013 DPSxshow (context, cbuf, advances, len);
1014 DPSstroke (context);
1016 /*[context GSSetTextDrawingMode: GSTextFill]; /// not implemented yet */
1020 if (face->underline_p)
1022 if (face->underline_color != 0)
1023 [ns_lookup_indexed_color (face->underline_color, s->f) set];
1026 DPSmoveto (context, r.origin.x, r.origin.y + font->underpos);
1027 DPSlineto (context, r.origin.x+r.size.width, r.origin.y+font->underpos);
1028 if (face->underline_color != 0)
1034 /* draw with DPSxshow () */
1035 DPSmoveto (context, r.origin.x, r.origin.y);
1036 DPSxshow (context, cbuf, advances, len);
1037 DPSstroke (context);
1039 DPSgrestore (context);
1043 #else /* NS_IMPL_COCOA */
1045 CGContextRef gcontext =
1046 [[NSGraphicsContext currentContext] graphicsPort];
1047 static CGAffineTransform fliptf;
1048 static BOOL firstTime = YES;
1053 fliptf = CGAffineTransformMakeScale (1.0, -1.0);
1056 CGContextSaveGState (gcontext);
1058 fliptf.c = font->synthItal ? Fix2X (kATSItalicQDSkew) : 0.0;
1060 CGContextSetFont (gcontext, font->cgfont);
1061 CGContextSetFontSize (gcontext, font->size);
1062 if (ns_antialias_text == NO || font->size <= ns_antialias_threshold)
1063 CGContextSetShouldAntialias (gcontext, 0);
1065 CGContextSetShouldAntialias (gcontext, 1);
1066 if (EQ (ns_use_qd_smoothing, Qt))
1067 CGContextSetFontRenderingMode (gcontext, 2); /* 0 is Cocoa, 2 is QD */
1069 CGContextSetTextMatrix (gcontext, fliptf);
1073 /* foreground drawing; erase first to avoid overstrike */
1075 CGContextSetTextDrawingMode (gcontext, kCGTextFillStroke);
1076 CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
1077 CGContextShowGlyphsWithAdvances (gcontext, s->char2b, advances, len);
1078 CGContextSetTextDrawingMode (gcontext, kCGTextFill);
1081 if (face->underline_p)
1083 if (face->underline_color != 0)
1084 [ns_lookup_indexed_color (face->underline_color, s->f) set];
1087 CGContextBeginPath (gcontext);
1088 CGContextMoveToPoint (gcontext,
1089 r.origin.x, r.origin.y + font->underpos);
1090 CGContextAddLineToPoint (gcontext, r.origin.x + r.size.width,
1091 r.origin.y + font->underpos);
1092 CGContextStrokePath (gcontext);
1093 if (face->underline_color != 0)
1099 CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
1100 CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
1103 if (face->overstrike)
1105 CGContextSetTextPosition (gcontext, r.origin.x+0.5, r.origin.y);
1106 CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
1110 CGContextRestoreGState (gcontext);
1113 #endif /* NS_IMPL_COCOA */
1118 /* Auto-creates a fontset built around the font in font_object,
1119 by creating an attributed string with characters from each
1120 script, then requesting the NS text system to fix attributes
1122 void nsfont_make_fontset_for_font (Lisp_Object name, Lisp_Object font_object)
1124 Lisp_Object script, famAndReg;
1125 struct nsfont_info *font_info =
1126 (struct nsfont_info *)XFONT_OBJECT (font_object);
1128 /* NS text system (and char buf) init */
1129 static NSTextStorage *store;
1130 static NSLayoutManager *layout;
1131 static NSRange range;
1132 static NSMutableDictionary *attribs;
1133 static Lisp_Object *scripts;
1134 static int nscripts;
1135 static int *scriptsNchars;
1136 static BOOL firstTime = YES;
1137 Lisp_Object regString = build_string ("iso10646-1");
1140 if (firstTime == YES)
1142 nscripts = XINT (Flength (Vscript_representative_chars));
1143 scriptsNchars = (int *) malloc (nscripts * sizeof (int));
1144 unsigned char *buf = malloc (4*nscripts*sizeof (char));
1145 Lisp_Object scriptsChars = Vscript_representative_chars;
1146 unsigned char *tpos = buf;
1148 scripts = (Lisp_Object *) malloc (nscripts * sizeof (Lisp_Object));
1150 for (i =0; i<nscripts; i++)
1152 Lisp_Object sChars = XCAR (scriptsChars);
1153 Lisp_Object chars = XCDR (sChars);
1154 unsigned int ch, c =0;
1155 scripts[i] = XCAR (sChars);
1157 while (CONSP (chars))
1159 ch = XUINT (XCAR (chars));
1160 chars = XCDR (chars);
1161 CHAR_STRING_ADVANCE (ch, tpos);
1164 scriptsNchars[i] = c;
1166 scriptsChars = XCDR (scriptsChars);
1170 store = [[NSTextStorage alloc] init];
1171 layout = [[NSLayoutManager alloc] init];
1172 [store addLayoutManager: layout];
1175 [store beginEditing];
1176 [[store mutableString] appendString:
1177 [NSString stringWithUTF8String: buf]];
1181 range = NSMakeRange (0, [store length]);
1183 attribs = [[NSMutableDictionary alloc] init];
1188 [store beginEditing];
1189 [store removeAttribute: NSFontAttributeName range: range];
1190 [attribs setObject: font_info->nsfont forKey: NSFontAttributeName];
1191 [store addAttributes: attribs range: range];
1196 NSMutableDictionary *map =
1197 [NSMutableDictionary dictionaryWithCapacity: nscripts * 4];
1198 NSEnumerator *fonts;
1199 NSFont *cfont = nil, *tfont;
1203 for (i =0; i<nscripts; i++)
1205 [map removeAllObjects];
1206 for (j =0; j<scriptsNchars[i]; j++)
1208 cfont = [store attribute: NSFontAttributeName atIndex: idx++
1209 effectiveRange: NULL];
1210 n = [map objectForKey: cfont];
1212 n = [NSNumber numberWithInt: 1];
1214 n = [NSNumber numberWithInt: [n intValue] + 1];
1215 [map setObject: n forKey: cfont];
1218 /* majority rules */
1220 fonts = [map keyEnumerator];
1221 while (tfont = [fonts nextObject])
1223 n = [map objectForKey: tfont];
1224 if ([n intValue] > max)
1233 char *family = strdup([[cfont familyName] UTF8String]);
1234 Lisp_Object famAndReg;
1236 nsfont_escape_name (family);
1237 famAndReg = Fcons (build_string (family), regString);
1240 fprintf (stderr, "%s fontset: use '%s' for script '%s'\n",
1241 font_info->name, family,
1242 SDATA (SYMBOL_NAME (scripts[i])));
1244 Fset_fontset_font (name, scripts[i], famAndReg, Qnil, Qnil);
1249 fprintf (stderr, "%s fontset: none found for script '%s'\n",
1250 font_info->name, SDATA (SYMBOL_NAME (scripts[i])));
1252 } /* for i = script */
1258 /* ==========================================================================
1260 Font glyph and metrics caching functions
1262 ========================================================================== */
1264 /* Find and cache corresponding glyph codes for unicode values in given
1265 hi-byte block of 256. */
1267 ns_uni_to_glyphs (struct nsfont_info *font_info, unsigned char block)
1269 #ifdef NS_IMPL_COCOA
1270 static EmacsGlyphStorage *glyphStorage;
1271 static char firstTime = 1;
1273 unichar *unichars = xmalloc (0x101 * sizeof (unichar));
1274 unsigned int i, g, idx;
1275 unsigned short *glyphs;
1278 fprintf (stderr, "%p\tFinding glyphs for glyphs in block %d\n",
1283 #ifdef NS_IMPL_COCOA
1287 glyphStorage = [[EmacsGlyphStorage alloc] initWithCapacity: 0x100];
1291 font_info->glyphs[block] = xmalloc (0x100 * sizeof (unsigned short));
1292 if (!unichars || !(font_info->glyphs[block]))
1295 /* create a string containing all unicode characters in this block */
1296 for (idx = block<<8, i =0; i<0x100; idx++, i++)
1297 if (idx < 0xD800 || idx > 0xDFFF)
1300 unichars[i] = 0xFEFF;
1301 unichars[0x100] = 0;
1304 #ifdef NS_IMPL_COCOA
1305 NSString *allChars = [[NSString alloc]
1306 initWithCharactersNoCopy: unichars
1309 NSGlyphGenerator *glyphGenerator = [NSGlyphGenerator sharedGlyphGenerator];
1310 /*NSCharacterSet *coveredChars = [nsfont coveredCharacterSet]; */
1311 unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
1312 unsigned int gInd =0, cInd =0;
1314 [glyphStorage setString: allChars font: font_info->nsfont];
1315 [glyphGenerator generateGlyphsForGlyphStorage: glyphStorage
1316 desiredNumberOfCharacters: glyphStorage->maxChar
1317 glyphIndex: &gInd characterIndex: &cInd];
1319 glyphs = font_info->glyphs[block];
1320 for (i =0; i<0x100; i++, glyphs++)
1322 #ifdef NS_IMPL_GNUSTEP
1325 g = glyphStorage->cglyphs[i];
1326 /* TODO: is this a good check? maybe need to use coveredChars.. */
1328 g = 0xFFFF; /* hopefully unused... */
1333 #ifdef NS_IMPL_COCOA
1343 /* Determine and cache metrics for corresponding glyph codes in given
1344 hi-byte block of 256. */
1346 ns_glyph_metrics (struct nsfont_info *font_info, unsigned char block)
1349 unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
1351 struct font_metrics *metrics;
1354 fprintf (stderr, "%p\tComputing metrics for glyphs in block %d\n",
1357 #ifdef NS_IMPL_GNUSTEP
1358 /* not implemented yet (as of startup 0.18), so punt */
1360 numGlyphs = 0x10000;
1364 sfont = [font_info->nsfont screenFont];
1366 font_info->metrics[block] = xmalloc (0x100 * sizeof (struct font_metrics));
1367 bzero (font_info->metrics[block], 0x100 * sizeof (struct font_metrics));
1368 if (!(font_info->metrics[block]))
1371 metrics = font_info->metrics[block];
1372 for (g = block<<8, i =0; i<0x100 && g < numGlyphs; g++, i++, metrics++)
1375 NSRect r = [sfont boundingRectForGlyph: g];
1377 #ifdef NS_IMPL_GNUSTEP
1380 NSString *s = [NSString stringWithFormat: @"%c", g];
1381 w = [sfont widthOfString: s];
1384 w = [sfont advancementForGlyph: g].width;
1387 metrics->width = lrint (w);
1390 rb = r.size.width - w;
1392 metrics->lbearing = round (lb);
1393 if (font_info->ital)
1394 rb += 0.22 * font_info->height;
1395 metrics->rbearing = lrint (w + rb);
1397 metrics->descent = r.origin.y < 0 ? -r.origin.y : 0;
1398 /*lrint (hshrink * [sfont ascender] + expand * hd/2); */
1399 metrics->ascent = r.size.height - metrics->descent;
1400 /*-lrint (hshrink* [sfont descender] - expand * hd/2); */
1406 #ifdef NS_IMPL_COCOA
1407 /* helper for font glyph setup */
1408 @implementation EmacsGlyphStorage
1412 return [self initWithCapacity: 1024];
1415 - initWithCapacity: (unsigned long) c
1417 self = [super init];
1420 dict = [NSMutableDictionary new];
1421 cglyphs = (CGGlyph *)xmalloc (c * sizeof (CGGlyph));
1434 - (void) setString: (NSString *)str font: (NSFont *)font
1436 [dict setObject: font forKey: NSFontAttributeName];
1437 attrStr = [[NSAttributedString alloc] initWithString: str attributes: dict];
1438 maxChar = [str length];
1442 /* NSGlyphStorage protocol */
1443 - (unsigned int)layoutOptions
1448 - (NSAttributedString *)attributedString
1453 - (void)insertGlyphs: (const NSGlyph *)glyphs length: (unsigned int)length
1454 forStartingGlyphAtIndex: (unsigned int)glyphIndex
1455 characterIndex: (unsigned int)charIndex
1457 len = glyphIndex+length;
1458 for (i =glyphIndex; i<len; i++)
1459 cglyphs[i] = glyphs[i-glyphIndex];
1464 - (void)setIntAttribute: (int)attributeTag value: (int)val
1465 forGlyphAtIndex: (unsigned)glyphIndex
1471 #endif /* NS_IMPL_COCOA */
1476 dump_glyphstring (struct glyph_string *s)
1480 fprintf (stderr, "Glyph string len = %d at (%d, %d) overhang (%d, %d), overlap = %d, bg_filled = %d:",
1481 s->nchars, s->x, s->y, s->left_overhang, s->right_overhang,
1482 s->row->overlapping_p, s->background_filled_p);
1483 for (i =0; i<s->nchars; i++)
1484 fprintf (stderr, "%c", s->first_glyph[i].u.ch);
1485 fprintf (stderr, "\n");
1493 nsfont_driver.type = Qns;
1494 register_font_driver (&nsfont_driver, NULL);
1495 DEFSYM (Qapple, "apple");
1496 DEFSYM (Qroman, "roman");
1497 DEFSYM (Qmedium, "medium");
1500 // arch-tag: d6c3c6f0-62de-4978-8b1e-b7966fe02cae