macterm.c 291 KB
Newer Older
1
/* Implementation of GUI terminal on the Mac OS.
2
   Copyright (C) 2000, 2001, 2002, 2003, 2004,
3
                 2005, 2006 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

This file is part of GNU Emacs.

GNU Emacs is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

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
along with GNU Emacs; see the file COPYING.  If not, write to
Lute Kamstra's avatar
Lute Kamstra committed
19 20
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.  */
21

22
/* Contributed by Andrew Choi (akochoi@mac.com).  */
23 24 25

#include <config.h>
#include <signal.h>
26

27
#include <stdio.h>
28

29 30 31 32 33
#include "lisp.h"
#include "blockinput.h"

#include "macterm.h"

34
#ifndef MAC_OSX
35
#include <alloca.h>
36
#endif
37

38
#if TARGET_API_MAC_CARBON
Andrew Choi's avatar
In src:  
Andrew Choi committed
39 40 41 42
/* USE_CARBON_EVENTS determines if the Carbon Event Manager is used to
   obtain events from the event queue.  If set to 0, WaitNextEvent is
   used instead.  */
#define USE_CARBON_EVENTS 1
43
#else /* not TARGET_API_MAC_CARBON */
44 45 46 47 48 49 50 51 52 53
#include <Quickdraw.h>
#include <ToolUtils.h>
#include <Sound.h>
#include <Events.h>
#include <Script.h>
#include <Resources.h>
#include <Fonts.h>
#include <TextUtils.h>
#include <LowMem.h>
#include <Controls.h>
54
#include <Windows.h>
55
#if defined (__MRC__) || (__MSL__ >= 0x6000)
56 57 58 59 60 61
#include <ControlDefinitions.h>
#endif

#if __profile__
#include <profiler.h>
#endif
62
#endif /* not TARGET_API_MAC_CARBON */
63 64 65 66 67 68 69 70 71

#include "systty.h"
#include "systime.h"

#include <ctype.h>
#include <errno.h>
#include <setjmp.h>
#include <sys/stat.h>

72 73
#include "charset.h"
#include "coding.h"
74 75 76 77 78 79 80 81 82 83
#include "frame.h"
#include "dispextern.h"
#include "fontset.h"
#include "termhooks.h"
#include "termopts.h"
#include "termchar.h"
#include "gnu.h"
#include "disptab.h"
#include "buffer.h"
#include "window.h"
84
#include "keyboard.h"
85
#include "intervals.h"
86 87
#include "atimer.h"
#include "keymap.h"
88

89 90


91
/* Non-nil means Emacs uses toolkit scroll bars.  */
92

93
Lisp_Object Vx_toolkit_scroll_bars;
94

95 96 97
/* If non-zero, the text will be rendered using Core Graphics text
   rendering which may anti-alias the text.  */
int mac_use_core_graphics;
98 99


100 101 102 103 104
/* Non-zero means that a HELP_EVENT has been generated since Emacs
   start.  */

static int any_help_event_p;

105 106
/* Last window where we saw the mouse.  Used by mouse-autoselect-window.  */
static Lisp_Object last_window;
107

108 109 110 111
/* Non-zero means make use of UNDERLINE_POSITION font properties.
   (Not yet supported.)  */
int x_use_underline_position_properties;

112 113 114 115 116 117
/* This is a chain of structures for all the X displays currently in
   use.  */

struct x_display_info *x_display_list;

/* This is a list of cons cells, each of the form (NAME
118 119 120 121 122 123
   FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
   x_display_list and in the same order.  NAME is the name of the
   frame.  FONT-LIST-CACHE records previous values returned by
   x-list-fonts.  RESOURCE-DATABASE preserves the X Resource Database
   equivalent, which is implemented with a Lisp object, for the
   display. */
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

Lisp_Object x_display_name_list;

/* This is display since Mac does not support multiple ones.  */
struct mac_display_info one_mac_display_info;

/* Frame being updated by update_frame.  This is declared in term.c.
   This is set by update_begin and looked at by all the XT functions.
   It is zero while not inside an update.  In that case, the XT
   functions assume that `selected_frame' is the frame to apply to.  */

extern struct frame *updating_frame;

/* This is a frame waiting to be auto-raised, within XTread_socket.  */

struct frame *pending_autoraise_frame;

/* Mouse movement.

   Formerly, we used PointerMotionHintMask (in standard_event_mask)
   so that we would have to call XQueryPointer after each MotionNotify
   event to ask for another such event.  However, this made mouse tracking
   slow, and there was a bug that made it eventually stop.

   Simply asking for MotionNotify all the time seems to work better.

   In order to avoid asking for motion events and then throwing most
   of them away or busy-polling the server for mouse positions, we ask
   the server for pointer motion hints.  This means that we get only
   one event per group of mouse movements.  "Groups" are delimited by
   other kinds of events (focus changes and button clicks, for
   example), or by XQueryPointer calls; when one of these happens, we
   get another MotionNotify event the next time the mouse moves.  This
   is at least as efficient as getting motion events when mouse
   tracking is on, and I suspect only negligibly worse when tracking
   is off.  */

/* Where the mouse was last time we reported a mouse event.  */

static Rect last_mouse_glyph;
164
static FRAME_PTR last_mouse_glyph_frame;
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

/* The scroll bar in which the last X motion event occurred.

   If the last X motion event occurred in a scroll bar, we set this so
   XTmouse_position can know whether to report a scroll bar motion or
   an ordinary motion.

   If the last X motion event didn't occur in a scroll bar, we set
   this to Qnil, to tell XTmouse_position to return an ordinary motion
   event.  */

static Lisp_Object last_mouse_scroll_bar;

/* This is a hack.  We would really prefer that XTmouse_position would
   return the time associated with the position it returns, but there
   doesn't seem to be any way to wrest the time-stamp from the server
   along with the position query.  So, we just keep track of the time
   of the last movement we received, and return that in hopes that
   it's somewhat accurate.  */

static Time last_mouse_movement_time;

struct scroll_bar *tracked_scroll_bar = NULL;

/* Incremented by XTread_socket whenever it really tries to read
   events.  */

#ifdef __STDC__
static int volatile input_signal_count;
#else
static int input_signal_count;
#endif

198
extern Lisp_Object Vsystem_name;
199 200 201

/* A mask of extra modifier bits to put into every keyboard char.  */

202
extern EMACS_INT extra_keyboard_modifiers;
203

204 205
/* The keysyms to use for the various modifiers.  */

206
static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
207

208
extern int inhibit_window_system;
209

210
#if __MRC__ && !TARGET_API_MAC_CARBON
211 212 213
QDGlobals qd;  /* QuickDraw global information structure.  */
#endif

214
#define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
215 216 217 218 219 220 221 222 223 224 225 226 227 228

struct mac_display_info *mac_display_info_for_display (Display *);
static void x_update_window_end P_ ((struct window *, int, int));
static int x_io_error_quitter P_ ((Display *));
int x_catch_errors P_ ((Display *));
void x_uncatch_errors P_ ((Display *, int));
void x_lower_frame P_ ((struct frame *));
void x_scroll_bar_clear P_ ((struct frame *));
int x_had_errors_p P_ ((Display *));
void x_wm_set_size_hint P_ ((struct frame *, long, int));
void x_raise_frame P_ ((struct frame *));
void x_set_window_size P_ ((struct frame *, int, int, int));
void x_wm_set_window_state P_ ((struct frame *, int));
void x_wm_set_icon_pixmap P_ ((struct frame *, int));
229
void mac_initialize P_ ((void));
230 231 232 233 234 235 236 237 238 239
static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
static int x_compute_min_glyph_bounds P_ ((struct frame *));
static void x_update_end P_ ((struct frame *));
static void XTframe_up_to_date P_ ((struct frame *));
static void XTset_terminal_modes P_ ((void));
static void XTreset_terminal_modes P_ ((void));
static void x_clear_frame P_ ((void));
static void frame_highlight P_ ((struct frame *));
static void frame_unhighlight P_ ((struct frame *));
static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
240 241 242 243
static void mac_focus_changed P_ ((int, struct mac_display_info *,
				   struct frame *, struct input_event *));
static void x_detect_focus_change P_ ((struct mac_display_info *,
				       EventRecord *, struct input_event *));
244 245 246
static void XTframe_rehighlight P_ ((struct frame *));
static void x_frame_rehighlight P_ ((struct x_display_info *));
static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
247 248 249
static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
				   enum text_cursor_kinds));

250
static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
251 252 253 254
static void x_flush P_ ((struct frame *f));
static void x_update_begin P_ ((struct frame *));
static void x_update_window_begin P_ ((struct window *));
static void x_after_update_window_line P_ ((struct glyph_row *));
255 256 257 258
static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
					    enum scroll_bar_part *,
					    Lisp_Object *, Lisp_Object *,
					    unsigned long *));
259

260
static int is_emacs_window P_ ((WindowPtr));
261
static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
262
static void XSetFont P_ ((Display *, GC, XFontStruct *));
263 264 265 266

/* Defined in macmenu.h.  */
extern void menubar_selection_callback (FRAME_PTR, int);

267 268 269
#define GC_FORE_COLOR(gc)	(&(gc)->fore_color)
#define GC_BACK_COLOR(gc)	(&(gc)->back_color)
#define GC_FONT(gc)		((gc)->xgcv.font)
270
#define FRAME_NORMAL_GC(f)	((f)->output_data.mac->normal_gc)
271

272 273 274
static RgnHandle saved_port_clip_region = NULL;

static void
275 276
mac_begin_clip (gc)
     GC gc;
277 278 279 280 281 282 283 284
{
  static RgnHandle new_region = NULL;

  if (saved_port_clip_region == NULL)
    saved_port_clip_region = NewRgn ();
  if (new_region == NULL)
    new_region = NewRgn ();

285
  if (gc->n_clip_rects)
286 287
    {
      GetClip (saved_port_clip_region);
288
      SectRgn (saved_port_clip_region, gc->clip_region, new_region);
289 290 291 292 293
      SetClip (new_region);
    }
}

static void
294 295
mac_end_clip (gc)
     GC gc;
296
{
297
  if (gc->n_clip_rects)
298 299 300
    SetClip (saved_port_clip_region);
}

301

302 303
/* X display function emulation */

304
void
305
XFreePixmap (display, pixmap)
306
     Display *display;		/* not used */
307 308
     Pixmap pixmap;
{
309
  DisposeGWorld (pixmap);
310 311 312 313 314 315
}


/* Mac version of XDrawLine.  */

static void
316 317
mac_draw_line (f, gc, x1, y1, x2, y2)
     struct frame *f;
318 319 320
     GC gc;
     int x1, y1, x2, y2;
{
321
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
322

323
  RGBForeColor (GC_FORE_COLOR (gc));
324

325
  mac_begin_clip (gc);
326 327
  MoveTo (x1, y1);
  LineTo (x2, y2);
328
  mac_end_clip (gc);
329 330
}

331 332 333 334 335 336 337
void
mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
     Display *display;
     Pixmap p;
     GC gc;
     int x1, y1, x2, y2;
{
338 339 340 341
  CGrafPtr old_port;
  GDHandle old_gdh;

  GetGWorld (&old_port, &old_gdh);
342 343
  SetGWorld (p, NULL);

344
  RGBForeColor (GC_FORE_COLOR (gc));
345 346 347 348 349

  LockPixels (GetGWorldPixMap (p));
  MoveTo (x1, y1);
  LineTo (x2, y2);
  UnlockPixels (GetGWorldPixMap (p));
350 351

  SetGWorld (old_port, old_gdh);
352 353
}

354

355
static void
356 357
mac_erase_rectangle (f, gc, x, y, width, height)
     struct frame *f;
358
     GC gc;
359 360 361 362 363
     int x, y;
     unsigned int width, height;
{
  Rect r;

364
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
365

366
  RGBBackColor (GC_BACK_COLOR (gc));
367 368
  SetRect (&r, x, y, x + width, y + height);

369
  mac_begin_clip (gc);
370
  EraseRect (&r);
371
  mac_end_clip (gc);
372

373
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
374 375 376 377 378 379
}


/* Mac version of XClearArea.  */

void
380 381
mac_clear_area (f, x, y, width, height)
     struct frame *f;
382 383 384
     int x, y;
     unsigned int width, height;
{
385
  mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
386 387 388 389 390
}

/* Mac version of XClearWindow.  */

static void
391 392
mac_clear_window (f)
     struct frame *f;
393
{
394
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
395

396
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
397

398 399 400
#if TARGET_API_MAC_CARBON
  {
    Rect r;
401

402
    GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
403 404 405
    EraseRect (&r);
  }
#else /* not TARGET_API_MAC_CARBON */
406
  EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
407
#endif /* not TARGET_API_MAC_CARBON */
408 409 410 411 412 413
}


/* Mac replacement for XCopyArea.  */

static void
414 415
mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
     struct frame *f;
416
     GC gc;
417 418
     int x, y, width, height;
     unsigned short *bits;
419
     int overlay_p;
420
{
421
  BitMap bitmap;
422 423
  Rect r;

424
  bitmap.rowBytes = sizeof(unsigned short);
425
  bitmap.baseAddr = (char *)bits;
426 427
  SetRect (&(bitmap.bounds), 0, 0, width, height);

428
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
429

430 431
  RGBForeColor (GC_FORE_COLOR (gc));
  RGBBackColor (GC_BACK_COLOR (gc));
432
  SetRect (&r, x, y, x + width, y + height);
433

434
  mac_begin_clip (gc);
435
#if TARGET_API_MAC_CARBON
436 437 438 439 440 441 442 443 444
  {
    CGrafPtr port;

    GetPort (&port);
    LockPortBits (port);
    CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
	      &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
    UnlockPortBits (port);
  }
445
#else /* not TARGET_API_MAC_CARBON */
446
  CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
447
	    overlay_p ? srcOr : srcCopy, 0);
448
#endif /* not TARGET_API_MAC_CARBON */
449
  mac_end_clip (gc);
450

451
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
452 453 454 455 456 457 458 459 460 461 462
}


/* Mac replacement for XCreateBitmapFromBitmapData.  */

static void
mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
     BitMap *bitmap;
     char *bits;
     int w, h;
{
463 464 465 466 467
  static unsigned char swap_nibble[16]
    = { 0x0, 0x8, 0x4, 0xc,    /* 0000 1000 0100 1100 */
	0x2, 0xa, 0x6, 0xe,    /* 0010 1010 0110 1110 */
	0x1, 0x9, 0x5, 0xd,    /* 0001 1001 0101 1101 */
	0x3, 0xb, 0x7, 0xf };  /* 0011 1011 0111 1111 */
468 469
  int i, j, w1;
  char *p;
470

471 472
  w1 = (w + 7) / 8;         /* nb of 8bits elt in X bitmap */
  bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
473 474 475
  bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
  bzero (bitmap->baseAddr, bitmap->rowBytes * h);
  for (i = 0; i < h; i++)
476 477 478
    {
      p = bitmap->baseAddr + i * bitmap->rowBytes;
      for (j = 0; j < w1; j++)
479 480 481 482 483 484
	{
	  /* Bitswap XBM bytes to match how Mac does things.  */
	  unsigned char c = *bits++;
	  *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
				 | (swap_nibble[(c>>4) & 0xf]));;
	}
485
    }
486 487 488 489 490 491 492 493 494 495 496 497

  SetRect (&(bitmap->bounds), 0, 0, w, h);
}


static void
mac_free_bitmap (bitmap)
     BitMap *bitmap;
{
  xfree (bitmap->baseAddr);
}

498 499 500 501 502 503

Pixmap
XCreatePixmap (display, w, width, height, depth)
     Display *display;		/* not used */
     WindowPtr w;
     unsigned int width, height;
Steven Tamm's avatar
Steven Tamm committed
504
     unsigned int depth;
505 506 507 508 509
{
  Pixmap pixmap;
  Rect r;
  QDErr err;

510
  SetPortWindowPort (w);
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

  SetRect (&r, 0, 0, width, height);
  err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
  if (err != noErr)
    return NULL;
  return pixmap;
}


Pixmap
XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
     Display *display;		/* not used */
     WindowPtr w;
     char *data;
     unsigned int width, height;
     unsigned long fg, bg;
527
     unsigned int depth;
528 529 530
{
  Pixmap pixmap;
  BitMap bitmap;
531 532
  CGrafPtr old_port;
  GDHandle old_gdh;
533 534 535 536
  static GC gc = NULL;		/* not reentrant */

  if (gc == NULL)
    gc = XCreateGC (display, w, 0, NULL);
537 538 539 540 541

  pixmap = XCreatePixmap (display, w, width, height, depth);
  if (pixmap == NULL)
    return NULL;

542
  GetGWorld (&old_port, &old_gdh);
543 544
  SetGWorld (pixmap, NULL);
  mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
545 546 547 548
  XSetForeground (display, gc, fg);
  XSetBackground (display, gc, bg);
  RGBForeColor (GC_FORE_COLOR (gc));
  RGBBackColor (GC_BACK_COLOR (gc));
549 550 551 552 553 554 555 556 557
  LockPixels (GetGWorldPixMap (pixmap));
#if TARGET_API_MAC_CARBON
  CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
	    &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
#else /* not TARGET_API_MAC_CARBON */
  CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
	    &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
#endif /* not TARGET_API_MAC_CARBON */
  UnlockPixels (GetGWorldPixMap (pixmap));
558
  SetGWorld (old_port, old_gdh);
559 560 561 562 563 564
  mac_free_bitmap (&bitmap);

  return pixmap;
}


565 566 567
/* Mac replacement for XFillRectangle.  */

static void
568 569
mac_fill_rectangle (f, gc, x, y, width, height)
     struct frame *f;
570 571 572 573 574 575
     GC gc;
     int x, y;
     unsigned int width, height;
{
  Rect r;

576
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
577

578
  RGBForeColor (GC_FORE_COLOR (gc));
579 580
  SetRect (&r, x, y, x + width, y + height);

581
  mac_begin_clip (gc);
582
  PaintRect (&r); /* using foreground color of gc */
583
  mac_end_clip (gc);
584 585 586 587 588 589
}


/* Mac replacement for XDrawRectangle: dest is a window.  */

static void
590 591
mac_draw_rectangle (f, gc, x, y, width, height)
     struct frame *f;
592 593 594 595 596 597
     GC gc;
     int x, y;
     unsigned int width, height;
{
  Rect r;

598
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
599

600
  RGBForeColor (GC_FORE_COLOR (gc));
601
  SetRect (&r, x, y, x + width, y + height);
602

603
  mac_begin_clip (gc);
604
  FrameRect (&r); /* using foreground color of gc */
605
  mac_end_clip (gc);
606 607 608
}


609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
#if USE_ATSUI
static OSStatus
atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
     ConstUniCharArrayPtr text;
     UniCharCount text_length;
     ATSUStyle style;
     ATSUTextLayout *text_layout;
{
  OSStatus err;
  static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */

  if (saved_text_layout == NULL)
    {
      UniCharCount lengths[] = {kATSUToTextEnd};
      ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
      ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
      static ATSLineLayoutOptions line_layout =
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
627
	kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
628
	| kATSLineUseQDRendering
629
#else
630
	kATSLineIsDisplayOnly | kATSLineFractDisable
631 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 662 663 664 665
#endif
	;
      ATSUAttributeValuePtr values[] = {&line_layout};

      err = ATSUCreateTextLayoutWithTextPtr (text,
					     kATSUFromTextBeginning,
					     kATSUToTextEnd,
					     text_length,
					     1, lengths, &style,
					     &saved_text_layout);
      if (err == noErr)
	err = ATSUSetLayoutControls (saved_text_layout,
				     sizeof (tags) / sizeof (tags[0]),
				     tags, sizes, values);
      /* XXX: Should we do this? */
      if (err == noErr)
	err = ATSUSetTransientFontMatching (saved_text_layout, true);
    }
  else
    {
      err = ATSUSetRunStyle (saved_text_layout, style,
			     kATSUFromTextBeginning, kATSUToTextEnd);
      if (err == noErr)
	err = ATSUSetTextPointerLocation (saved_text_layout, text,
					  kATSUFromTextBeginning,
					  kATSUToTextEnd,
					  text_length);
    }

  if (err == noErr)
    *text_layout = saved_text_layout;
  return err;
}
#endif

666

667
static void
668 669
mac_invert_rectangle (f, x, y, width, height)
     struct frame *f;
670 671 672 673 674
     int x, y;
     unsigned int width, height;
{
  Rect r;

675
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
676 677 678 679 680 681 682

  SetRect (&r, x, y, x + width, y + height);

  InvertRect (&r);
}


683
static void
684
mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, bytes_per_char)
685
     struct frame *f;
686 687 688
     GC gc;
     int x, y;
     char *buf;
689
     int nchars, bg_width, bytes_per_char;
690
{
691
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
692

693 694 695 696 697 698 699 700 701 702 703
#if USE_ATSUI
  if (GC_FONT (gc)->mac_style)
    {
      OSErr err;
      ATSUTextLayout text_layout;

      xassert (bytes_per_char == 2);

#ifndef WORDS_BIG_ENDIAN
      {
	int i;
704
	UniChar *text = (UniChar *)buf;
705 706

	for (i = 0; i < nchars; i++)
707
	  text[i] = EndianU16_BtoN (text[i]);
708 709 710 711 712 713
      }
#endif
      err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
						nchars,
						GC_FONT (gc)->mac_style,
						&text_layout);
714 715
      if (err != noErr)
	return;
716
#ifdef MAC_OSX
717 718
      if (!mac_use_core_graphics)
	{
719
#endif
720
	  mac_begin_clip (gc);
721 722 723 724 725 726 727 728 729 730
	  RGBForeColor (GC_FORE_COLOR (gc));
	  if (bg_width)
	    {
	      Rect r;

	      SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
		       x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
	      RGBBackColor (GC_BACK_COLOR (gc));
	      EraseRect (&r);
	      RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
731
	    }
732 733 734 735
	  MoveTo (x, y);
	  ATSUDrawText (text_layout,
			kATSUFromTextBeginning, kATSUToTextEnd,
			kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
736
	  mac_end_clip (gc);
737 738 739 740 741 742 743 744 745 746 747 748 749 750
#ifdef MAC_OSX
	}
      else
	{
	  CGrafPtr port;
	  CGContextRef context;
	  float port_height = FRAME_PIXEL_HEIGHT (f);
	  ATSUAttributeTag tags[] = {kATSUCGContextTag};
	  ByteCount sizes[] = {sizeof (CGContextRef)};
	  ATSUAttributeValuePtr values[] = {&context};

	  GetPort (&port);
	  QDBeginCGContext (port, &context);
	  if (gc->n_clip_rects || bg_width)
751
	    {
752 753
	      CGContextTranslateCTM (context, 0, port_height);
	      CGContextScaleCTM (context, 1, -1);
754
	      if (gc->n_clip_rects)
755 756 757
		CGContextClipToRects (context, gc->clip_rects,
				      gc->n_clip_rects);
	      if (bg_width)
758
		{
759 760 761 762 763 764 765 766 767 768
		  CGContextSetRGBFillColor
		    (context,
		     RED_FROM_ULONG (gc->xgcv.background) / 255.0f,
		     GREEN_FROM_ULONG (gc->xgcv.background) / 255.0f,
		     BLUE_FROM_ULONG (gc->xgcv.background) / 255.0f,
		     1.0);
		  CGContextFillRect
		    (context,
		     CGRectMake (x, y - FONT_BASE (GC_FONT (gc)),
				 bg_width, FONT_HEIGHT (GC_FONT (gc))));
769
		}
770 771 772 773 774 775 776 777 778 779
	      CGContextScaleCTM (context, 1, -1);
	      CGContextTranslateCTM (context, 0, -port_height);
	    }
	  CGContextSetRGBFillColor
	    (context,
	     RED_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
	     GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
	     BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
	     1.0);
	  err = ATSUSetLayoutControls (text_layout,
780
				       sizeof (tags) / sizeof (tags[0]),
781 782 783 784 785 786 787 788 789 790 791
				       tags, sizes, values);
	  if (err == noErr)
	    ATSUDrawText (text_layout,
			  kATSUFromTextBeginning, kATSUToTextEnd,
			  Long2Fix (x), Long2Fix (port_height - y));
	  CGContextSynchronize (context);
	  QDEndCGContext (port, &context);
#if 0
	  /* This doesn't work on Mac OS X 10.1.  */
	  ATSUClearLayoutControls (text_layout,
				   sizeof (tags) / sizeof (tags[0]), tags);
792
#else
793 794 795
	  ATSUSetLayoutControls (text_layout,
				 sizeof (tags) / sizeof (tags[0]),
				 tags, sizes, values);
796 797
#endif
	}
798
#endif	/* MAC_OSX */
799 800
    }
  else
801
#endif	/* USE_ATSUI */
802
    {
803 804 805 806 807
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
      UInt32 savedFlags;

      if (mac_use_core_graphics)
	savedFlags = SwapQDTextFlags (kQDUseCGTextRendering);
808
#endif
809
      mac_begin_clip (gc);
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
      RGBForeColor (GC_FORE_COLOR (gc));
#ifdef MAC_OS8
      if (bg_width)
	{
	  RGBBackColor (GC_BACK_COLOR (gc));
	  TextMode (srcCopy);
	}
      else
	TextMode (srcOr);
#else
      /* We prefer not to use srcCopy text transfer mode on Mac OS X
	 because:
	 - Screen is double-buffered.  (In srcCopy mode, a text is
	   drawn into an offscreen graphics world first.  So
	   performance gain cannot be expected.)
	 - It lowers rendering quality.
	 - Some fonts leave garbage on cursor movement.  */
      if (bg_width)
	{
	  Rect r;
830

831 832 833 834 835 836
	  RGBBackColor (GC_BACK_COLOR (gc));
	  SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
		   x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
	  EraseRect (&r);
	}
      TextMode (srcOr);
837
#endif
838 839 840 841 842 843 844
      TextFont (GC_FONT (gc)->mac_fontnum);
      TextSize (GC_FONT (gc)->mac_fontsize);
      TextFace (GC_FONT (gc)->mac_fontface);
      MoveTo (x, y);
      DrawText (buf, 0, nchars * bytes_per_char);
      if (bg_width)
	RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
845
      mac_end_clip (gc);
846

847
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
848 849
      if (mac_use_core_graphics)
	SwapQDTextFlags(savedFlags);
850
#endif
851
    }
852 853 854 855 856 857
}


/* Mac replacement for XDrawString.  */

static void
858 859
mac_draw_string (f, gc, x, y, buf, nchars)
     struct frame *f;
860 861 862 863 864
     GC gc;
     int x, y;
     char *buf;
     int nchars;
{
865
  mac_draw_string_common (f, gc, x, y, buf, nchars, 0, 1);
866 867 868 869 870 871
}


/* Mac replacement for XDrawString16. */

static void
872 873
mac_draw_string_16 (f, gc, x, y, buf, nchars)
     struct frame *f;
874 875 876 877 878
     GC gc;
     int x, y;
     XChar2b *buf;
     int nchars;
{
879
  mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, 0, 2);
880 881 882 883 884 885
}


/* Mac replacement for XDrawImageString.  */

static void
886
mac_draw_image_string (f, gc, x, y, buf, nchars, bg_width)
887
     struct frame *f;
888 889 890
     GC gc;
     int x, y;
     char *buf;
891
     int nchars, bg_width;
892
{
893
  mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, 1);
894 895 896 897 898 899
}


/* Mac replacement for XDrawString16.  */

static void
900
mac_draw_image_string_16 (f, gc, x, y, buf, nchars, bg_width)
901
     struct frame *f;
902 903 904
     GC gc;
     int x, y;
     XChar2b *buf;
905
     int nchars, bg_width;
906
{
907
  mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, bg_width, 2);
908 909 910
}


911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
/* Mac replacement for XQueryTextExtents, but takes a character.  If
   STYLE is NULL, measurement is done by QuickDraw Text routines for
   the font of the current graphics port.  If CG_GLYPH is not NULL,
   *CG_GLYPH is set to the glyph ID or 0 if it cannot be obtained.  */

static OSErr
mac_query_char_extents (style, c,
			font_ascent_return, font_descent_return,
			overall_return, cg_glyph)
#if USE_ATSUI
     ATSUStyle style;
#else
     void *style;
#endif
     int c;
     int *font_ascent_return, *font_descent_return;
     XCharStruct *overall_return;
928
#if USE_CG_TEXT_DRAWING
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
     CGGlyph *cg_glyph;
#else
     void *cg_glyph;
#endif
{
  OSErr err = noErr;
  int width;
  Rect char_bounds;

#if USE_ATSUI
  if (style)
    {
      ATSUTextLayout text_layout;
      UniChar ch = c;

      err = atsu_get_text_layout_with_text_ptr (&ch, 1, style, &text_layout);
      if (err == noErr)
	{
	  ATSTrapezoid glyph_bounds;
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 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 1012 1013 1014 1015 1016 1017 1018 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
	  err = ATSUGetGlyphBounds (text_layout, 0, 0,
				    kATSUFromTextBeginning, kATSUToTextEnd,
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
				    kATSUseFractionalOrigins,
#else
				    kATSUseDeviceOrigins,
#endif
				    1, &glyph_bounds, NULL);
	  if (err == noErr)
	    {
	      xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
		       == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);

	      width = Fix2Long (glyph_bounds.upperRight.x
				- glyph_bounds.upperLeft.x);
	      if (font_ascent_return)
		*font_ascent_return = -Fix2Long (glyph_bounds.upperLeft.y);
	      if (font_descent_return)
		*font_descent_return = Fix2Long (glyph_bounds.lowerLeft.y);
	    }
	}
      if (err == noErr && overall_return)
	{
	  err = ATSUMeasureTextImage (text_layout,
				      kATSUFromTextBeginning, kATSUToTextEnd,
				      0, 0, &char_bounds);
	  if (err == noErr)
	    STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
#if USE_CG_TEXT_DRAWING
	  if (err == noErr && cg_glyph)
	    {
	      OSErr err1;
	      ATSUGlyphInfoArray glyph_info_array;
	      ByteCount count = sizeof (ATSUGlyphInfoArray);

	      err1 = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
					   kATSUToTextEnd, NULL, NULL, NULL);
	      if (err1 == noErr)
		err1 = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
					 kATSUToTextEnd, &count,
					 &glyph_info_array);
	      if (err1 == noErr)
		{
		  xassert (glyph_info_array.glyphs[0].glyphID);
		  *cg_glyph = glyph_info_array.glyphs[0].glyphID;
		}
	      else
		*cg_glyph = 0;
	    }
#endif
	}
    }
  else
#endif
    {
      if (font_ascent_return || font_descent_return)
	{
	  FontInfo font_info;

	  GetFontInfo (&font_info);
	  if (font_ascent_return)
	    *font_ascent_return = font_info.ascent;
	  if (font_descent_return)
	    *font_descent_return = font_info.descent;
	}
      if (overall_return)
	{
	  char ch = c;

	  width = CharWidth (ch);
	  QDTextBounds (1, &ch, &char_bounds);
	  STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
	}
    }

  return err;
}


/* Mac replacement for XTextExtents16.  Only sets horizontal metrics.  */

static int
mac_text_extents_16 (font_struct, string, nchars, overall_return)
     XFontStruct *font_struct;
     XChar2b *string;
     int nchars;
     XCharStruct *overall_return;
{
  int i;
  short width = 0, lbearing = 0, rbearing = 0;
  XCharStruct *pcm;

  for (i = 0; i < nchars; i++)
    {
      pcm = mac_per_char_metric (font_struct, string, 0);
      if (pcm == NULL)
	width += FONT_WIDTH (font_struct);
      else
	{
	  lbearing = min (lbearing, width + pcm->lbearing);
	  rbearing = max (rbearing, width + pcm->rbearing);
	  width += pcm->width;
	}
      string++;
    }

  overall_return->lbearing = lbearing;
  overall_return->rbearing = rbearing;
  overall_return->width = width;

  /* What's the meaning of the return value of XTextExtents16?  */
}


#if USE_CG_TEXT_DRAWING
1064 1065 1066 1067 1068
static int cg_text_anti_aliasing_threshold = 8;

static void
init_cg_text_anti_aliasing_threshold ()
{
1069 1070
  int threshold;
  Boolean valid_p;
1071

1072 1073 1074 1075 1076 1077
  threshold =
    CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
				     kCFPreferencesCurrentApplication,
				     &valid_p);
  if (valid_p)
    cg_text_anti_aliasing_threshold = threshold;
1078 1079
}

1080
static int
1081
mac_draw_image_string_cg (f, gc, x, y, buf, nchars, bg_width)
1082 1083 1084 1085
     struct frame *f;
     GC gc;
     int x, y;
     XChar2b *buf;
1086
     int nchars, bg_width;
1087 1088 1089 1090 1091 1092 1093 1094
{
  CGrafPtr port;
  float port_height, gx, gy;
  int i;
  CGContextRef context;
  CGGlyph *glyphs;
  CGSize *advances;

1095
  if (!mac_use_core_graphics || GC_FONT (gc)->cg_font == NULL)
1096 1097 1098 1099 1100 1101 1102
    return 0;

  port = GetWindowPort (FRAME_MAC_WINDOW (f));
  port_height = FRAME_PIXEL_HEIGHT (f);
  gx = x;
  gy = port_height - y;
  glyphs = (CGGlyph *)buf;
1103 1104 1105
  advances = alloca (sizeof (CGSize) * nchars);
  if (advances == NULL)
    return 0;
1106 1107
  for (i = 0; i < nchars; i++)
    {
1108 1109 1110
      XCharStruct *pcm = mac_per_char_metric (GC_FONT (gc), buf, 0);

      advances[i].width = pcm->width;
1111 1112 1113 1114 1115 1116
      advances[i].height = 0;
      glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
      buf++;
    }

  QDBeginCGContext (port, &context);
1117
  if (gc->n_clip_rects || bg_width)
1118 1119 1120
    {
      CGContextTranslateCTM (context, 0, port_height);
      CGContextScaleCTM (context, 1, -1);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      if (gc->n_clip_rects)
	CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
      if (bg_width)
	{
	  CGContextSetRGBFillColor
	    (context,
	     RED_FROM_ULONG (gc->xgcv.background) / 255.0f,
	     GREEN_FROM_ULONG (gc->xgcv.background) / 255.0f,
	     BLUE_FROM_ULONG (gc->xgcv.background) / 255.0f,
	     1.0);
	  CGContextFillRect
	    (context,
	     CGRectMake (gx, y - FONT_BASE (GC_FONT (gc)),
			 bg_width, FONT_HEIGHT (GC_FONT (gc))));
	}
1136 1137 1138 1139
      CGContextScaleCTM (context, 1, -1);
      CGContextTranslateCTM (context, 0, -port_height);
    }
  CGContextSetRGBFillColor (context,
1140 1141 1142
			    RED_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
			    GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
			    BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0f,
1143 1144 1145
			    1.0);
  CGContextSetFont (context, GC_FONT (gc)->cg_font);
  CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
1146 1147
  if (GC_FONT (gc)->mac_fontsize <= cg_text_anti_aliasing_threshold)
    CGContextSetShouldAntialias (context, false);
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
  CGContextSetTextPosition (context, gx, gy);
  CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
#else
  for (i = 0; i < nchars; i++)
    {
      CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
      gx += advances[i].width;
    }
#endif
  CGContextSynchronize (context);
  QDEndCGContext (port, &context);

  return 1;
}
#endif


1166 1167 1168
/* Mac replacement for XCopyArea: dest must be window.  */

static void
1169
mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
1170
     Pixmap src;
1171
     struct frame *f;
1172 1173 1174 1175 1176 1177 1178
     GC gc;
     int src_x, src_y;
     unsigned int width, height;
     int dest_x, dest_y;
{
  Rect src_r, dest_r;

1179
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
1180

1181 1182 1183
  SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
  SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);

1184 1185 1186
  ForeColor (blackColor);
  BackColor (whiteColor);

1187
  mac_begin_clip (gc);
1188
  LockPixels (GetGWorldPixMap (src));
1189
#if TARGET_API_MAC_CARBON
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  {
    CGrafPtr port;

    GetPort (&port);
    LockPortBits (port);
    CopyBits (GetPortBitMapForCopyBits (src),
	      GetPortBitMapForCopyBits (port),
	      &src_r, &dest_r, srcCopy, 0);
    UnlockPortBits (port);
  }
1200
#else /* not TARGET_API_MAC_CARBON */
1201
  CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
1202 1203 1204
	    &src_r, &dest_r, srcCopy, 0);
#endif /* not TARGET_API_MAC_CARBON */
  UnlockPixels (GetGWorldPixMap (src));
1205
  mac_end_clip (gc);
1206

1207
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1208
}
1209

1210 1211

static void
1212
mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
1213 1214
			 width, height, dest_x, dest_y)
     Pixmap src, mask;
1215
     struct frame *f;
1216 1217 1218 1219 1220 1221 1222
     GC gc;
     int src_x, src_y;
     unsigned int width, height;
     int dest_x, dest_y;
{
  Rect src_r, dest_r;