macterm.c 323 KB
Newer Older
1
/* Implementation of GUI terminal on the Mac OS.
2
   Copyright (C) 2000, 2001, 2002, 2003, 2004,
Glenn Morris's avatar
Glenn Morris committed
3
                 2005, 2006, 2007 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
#include <Displays.h>
56
#if defined (__MRC__) || (__MSL__ >= 0x6000)
57 58 59 60 61 62
#include <ControlDefinitions.h>
#endif

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

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

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

73 74
#include "charset.h"
#include "coding.h"
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 "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
/* Non-zero means to draw the underline at the same place as the descent line.  */

int x_underline_at_descent_line;

116 117 118 119 120 121
/* 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
122 123 124 125 126 127
   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. */
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 164 165 166 167

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;
168
static FRAME_PTR last_mouse_glyph_frame;
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 198 199 200 201

/* 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

202
extern Lisp_Object Vsystem_name;
203

YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
204 205
extern Lisp_Object Qeql;

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

208
extern EMACS_INT extra_keyboard_modifiers;
209

210 211
/* The keysyms to use for the various modifiers.  */

212
static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
213

214
extern int inhibit_window_system;
215

216
#if __MRC__ && !TARGET_API_MAC_CARBON
217 218 219
QDGlobals qd;  /* QuickDraw global information structure.  */
#endif

220
#define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
221 222 223 224 225 226 227 228 229 230 231 232 233

struct mac_display_info *mac_display_info_for_display (Display *);
static void x_update_window_end P_ ((struct window *, int, int));
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));
234
void mac_initialize P_ ((void));
235 236 237 238 239 240 241 242 243 244
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 *));
245 246 247
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 *,
248 249
				       const EventRecord *,
				       struct input_event *));
250 251 252
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 *));
253 254 255
static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
				   enum text_cursor_kinds));

256
static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
257 258 259 260
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 *));
261 262 263 264
static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
					    enum scroll_bar_part *,
					    Lisp_Object *, Lisp_Object *,
					    unsigned long *));
265

266
static int is_emacs_window P_ ((WindowPtr));
267
static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
268
static void XSetFont P_ ((Display *, GC, XFontStruct *));
269

270 271 272
#define GC_FORE_COLOR(gc)	(&(gc)->fore_color)
#define GC_BACK_COLOR(gc)	(&(gc)->back_color)
#define GC_FONT(gc)		((gc)->xgcv.font)
273
#define FRAME_NORMAL_GC(f)	((f)->output_data.mac->normal_gc)
274 275

#define CG_SET_FILL_COLOR(context, color)				\
276 277 278 279
  CGContextSetRGBFillColor (context,					\
			    RED_FROM_ULONG (color) / 255.0f,		\
			    GREEN_FROM_ULONG (color) / 255.0f,		\
			    BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
#if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
#if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
#define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
  do {								       \
    if (CGColorGetTypeID != NULL)				       \
      CGContextSetFillColorWithColor (context, cg_color);	       \
    else							       \
      CG_SET_FILL_COLOR (context, color);			       \
  } while (0)
#else
#define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color)	\
  CGContextSetFillColorWithColor (context, cg_color)
#endif
#else
#define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color)	\
  CG_SET_FILL_COLOR (context, color)
#endif
#define CG_SET_FILL_COLOR_WITH_GC_FOREGROUND(context, gc)		\
  CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.foreground,	\
					(gc)->cg_fore_color)
#define CG_SET_FILL_COLOR_WITH_GC_BACKGROUND(context, gc)		\
  CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.background,	\
					(gc)->cg_back_color)


#define CG_SET_STROKE_COLOR(context, color)				\
306 307 308 309
  CGContextSetRGBStrokeColor (context,					\
			      RED_FROM_ULONG (color) / 255.0f,		\
			      GREEN_FROM_ULONG (color) / 255.0f,	\
			      BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
#if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
#if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
#define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
  do {								       \
    if (CGColorGetTypeID != NULL)				       \
      CGContextSetStrokeColorWithColor (context, cg_color);	       \
    else							       \
      CG_SET_STROKE_COLOR (context, color);			       \
  } while (0)
#else
#define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
  CGContextSetStrokeColorWithColor (context, cg_color)
#endif
#else
#define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
  CG_SET_STROKE_COLOR (context, color)
#endif
#define CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND(context, gc) \
  CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.foreground, \
					  (gc)->cg_fore_color)

331 332 333
#if USE_CG_DRAWING
#define FRAME_CG_CONTEXT(f)	((f)->output_data.mac->cg_context)

334 335 336 337 338
/* Fringe bitmaps.  */

static int max_fringe_bmp = 0;
static CGImageRef *fringe_bmp = 0;

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
static CGColorSpaceRef mac_cg_color_space_rgb;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
static CGColorRef mac_cg_color_black;
#endif

static void
init_cg_color ()
{
  mac_cg_color_space_rgb = CGColorSpaceCreateDeviceRGB ();
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
#if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
  /* Don't check the availability of CGColorCreate; this symbol is
     defined even in Mac OS X 10.1.  */
  if (CGColorGetTypeID != NULL)
#endif
    {
      float rgba[] = {0.0f, 0.0f, 0.0f, 1.0f};

      mac_cg_color_black = CGColorCreate (mac_cg_color_space_rgb, rgba);
    }
#endif
}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
static CGContextRef
mac_begin_cg_clip (f, gc)
     struct frame *f;
     GC gc;
{
  CGContextRef context = FRAME_CG_CONTEXT (f);

  if (!context)
    {
      QDBeginCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)), &context);
      FRAME_CG_CONTEXT (f) = context;
    }

  CGContextSaveGState (context);
  CGContextTranslateCTM (context, 0, FRAME_PIXEL_HEIGHT (f));
  CGContextScaleCTM (context, 1, -1);
  if (gc && gc->n_clip_rects)
    CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);

  return context;
}

static void
mac_end_cg_clip (f)
     struct frame *f;
{
  CGContextRestoreGState (FRAME_CG_CONTEXT (f));
}

void
mac_prepare_for_quickdraw (f)
     struct frame *f;
{
  if (f == NULL)
    {
      Lisp_Object rest, frame;
      FOR_EACH_FRAME (rest, frame)
	if (FRAME_MAC_P (XFRAME (frame)))
	  mac_prepare_for_quickdraw (XFRAME (frame));
    }
  else
    {
      CGContextRef context = FRAME_CG_CONTEXT (f);

      if (context)
	{
	  CGContextSynchronize (context);
	  QDEndCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)),
			  &FRAME_CG_CONTEXT (f));
	}
    }
}
#endif
415

416 417 418
static RgnHandle saved_port_clip_region = NULL;

static void
419 420
mac_begin_clip (gc)
     GC gc;
421 422 423 424 425 426 427 428
{
  static RgnHandle new_region = NULL;

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

429
  if (gc->n_clip_rects)
430 431
    {
      GetClip (saved_port_clip_region);
432
      SectRgn (saved_port_clip_region, gc->clip_region, new_region);
433 434 435 436 437
      SetClip (new_region);
    }
}

static void
438 439
mac_end_clip (gc)
     GC gc;
440
{
441
  if (gc->n_clip_rects)
442 443 444
    SetClip (saved_port_clip_region);
}

445

446 447
/* X display function emulation */

448
void
449
XFreePixmap (display, pixmap)
450
     Display *display;		/* not used */
451 452
     Pixmap pixmap;
{
453
  DisposeGWorld (pixmap);
454 455 456 457 458 459
}


/* Mac version of XDrawLine.  */

static void
460 461
mac_draw_line (f, gc, x1, y1, x2, y2)
     struct frame *f;
462 463 464
     GC gc;
     int x1, y1, x2, y2;
{
465 466
#if USE_CG_DRAWING
  CGContextRef context;
467 468 469 470 471 472
  float gx1 = x1, gy1 = y1, gx2 = x2, gy2 = y2;

  if (y1 != y2)
    gx1 += 0.5f, gx2 += 0.5f;
  if (x1 != x2)
    gy1 += 0.5f, gy2 += 0.5f;
473 474

  context = mac_begin_cg_clip (f, gc);
475
  CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND (context, gc);
476
  CGContextBeginPath (context);
477 478
  CGContextMoveToPoint (context, gx1, gy1);
  CGContextAddLineToPoint (context, gx2, gy2);
479 480 481 482
  CGContextClosePath (context);
  CGContextStrokePath (context);
  mac_end_cg_clip (f);
#else
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  if (x1 == x2)
    {
      if (y1 > y2)
	y1--;
      else if (y2 > y1)
	y2--;
    }
  else if (y1 == y2)
    {
      if (x1 > x2)
	x1--;
      else
	x2--;
    }

498
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
499

500
  RGBForeColor (GC_FORE_COLOR (gc));
501

502
  mac_begin_clip (gc);
503 504
  MoveTo (x1, y1);
  LineTo (x2, y2);
505
  mac_end_clip (gc);
506
#endif
507 508
}

509 510
/* Mac version of XDrawLine (to Pixmap).  */

511
void
512
XDrawLine (display, p, gc, x1, y1, x2, y2)
513 514 515 516 517
     Display *display;
     Pixmap p;
     GC gc;
     int x1, y1, x2, y2;
{
518 519 520
  CGrafPtr old_port;
  GDHandle old_gdh;

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  if (x1 == x2)
    {
      if (y1 > y2)
	y1--;
      else if (y2 > y1)
	y2--;
    }
  else if (y1 == y2)
    {
      if (x1 > x2)
	x1--;
      else
	x2--;
    }

536
  GetGWorld (&old_port, &old_gdh);
537 538
  SetGWorld (p, NULL);

539
  RGBForeColor (GC_FORE_COLOR (gc));
540 541 542 543 544

  LockPixels (GetGWorldPixMap (p));
  MoveTo (x1, y1);
  LineTo (x2, y2);
  UnlockPixels (GetGWorldPixMap (p));
545 546

  SetGWorld (old_port, old_gdh);
547 548
}

549

550
static void
551 552
mac_erase_rectangle (f, gc, x, y, width, height)
     struct frame *f;
553
     GC gc;
554 555 556
     int x, y;
     unsigned int width, height;
{
557 558 559 560
#if USE_CG_DRAWING
  CGContextRef context;

  context = mac_begin_cg_clip (f, gc);
561
  CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
562 563 564
  CGContextFillRect (context, CGRectMake (x, y, width, height));
  mac_end_cg_clip (f);
#else
565 566
  Rect r;

567
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
568

569
  RGBBackColor (GC_BACK_COLOR (gc));
570 571
  SetRect (&r, x, y, x + width, y + height);

572
  mac_begin_clip (gc);
573
  EraseRect (&r);
574
  mac_end_clip (gc);
575

576
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
577
#endif
578 579 580 581 582 583
}


/* Mac version of XClearArea.  */

void
584 585
mac_clear_area (f, x, y, width, height)
     struct frame *f;
586 587 588
     int x, y;
     unsigned int width, height;
{
589
  mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
590 591 592 593 594
}

/* Mac version of XClearWindow.  */

static void
595 596
mac_clear_window (f)
     struct frame *f;
597
{
598 599 600 601 602
#if USE_CG_DRAWING
  CGContextRef context;
  GC gc = FRAME_NORMAL_GC (f);

  context = mac_begin_cg_clip (f, NULL);
603
  CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
604 605 606 607
  CGContextFillRect (context, CGRectMake (0, 0, FRAME_PIXEL_WIDTH (f),
					  FRAME_PIXEL_HEIGHT (f)));
  mac_end_cg_clip (f);
#else
608
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
609

610
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
611

612 613 614
#if TARGET_API_MAC_CARBON
  {
    Rect r;
615

616
    GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
617 618 619
    EraseRect (&r);
  }
#else /* not TARGET_API_MAC_CARBON */
620
  EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
621
#endif /* not TARGET_API_MAC_CARBON */
622
#endif
623 624 625 626 627
}


/* Mac replacement for XCopyArea.  */

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
#if USE_CG_DRAWING
static void
mac_draw_cg_image (image, f, gc, src_x, src_y, width, height,
		   dest_x, dest_y, overlay_p)
     CGImageRef image;
     struct frame *f;
     GC gc;
     int src_x, src_y;
     unsigned int width, height;
     int dest_x, dest_y, overlay_p;
{
  CGContextRef context;
  float port_height = FRAME_PIXEL_HEIGHT (f);
  CGRect dest_rect = CGRectMake (dest_x, dest_y, width, height);

  context = mac_begin_cg_clip (f, gc);
  if (!overlay_p)
    {
646
      CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
647 648 649 650 651 652
      CGContextFillRect (context, dest_rect);
    }
  CGContextClipToRect (context, dest_rect);
  CGContextScaleCTM (context, 1, -1);
  CGContextTranslateCTM (context, 0, -port_height);
  if (CGImageIsMask (image))
653
    CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
654 655 656 657 658 659 660 661 662 663 664 665
  CGContextDrawImage (context,
		      CGRectMake (dest_x - src_x,
				  port_height - (dest_y - src_y
						 + CGImageGetHeight (image)),
				  CGImageGetWidth (image),
				  CGImageGetHeight (image)),
		      image);
  mac_end_cg_clip (f);
}

#else  /* !USE_CG_DRAWING */

666
static void
667 668
mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
     struct frame *f;
669
     GC gc;
670 671
     int x, y, width, height;
     unsigned short *bits;
672
     int overlay_p;
673
{
674
  BitMap bitmap;
675 676
  Rect r;

677
  bitmap.rowBytes = sizeof(unsigned short);
678
  bitmap.baseAddr = (char *)bits;
679 680
  SetRect (&(bitmap.bounds), 0, 0, width, height);

681
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
682

683 684
  RGBForeColor (GC_FORE_COLOR (gc));
  RGBBackColor (GC_BACK_COLOR (gc));
685
  SetRect (&r, x, y, x + width, y + height);
686

687
  mac_begin_clip (gc);
688
#if TARGET_API_MAC_CARBON
689 690 691 692 693 694 695 696 697
  {
    CGrafPtr port;

    GetPort (&port);
    LockPortBits (port);
    CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
	      &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
    UnlockPortBits (port);
  }
698
#else /* not TARGET_API_MAC_CARBON */
699
  CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
700
	    overlay_p ? srcOr : srcCopy, 0);
701
#endif /* not TARGET_API_MAC_CARBON */
702
  mac_end_clip (gc);
703

704
  RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
705
}
706
#endif	/* !USE_CG_DRAWING */
707 708 709 710 711 712 713 714 715 716


/* Mac replacement for XCreateBitmapFromBitmapData.  */

static void
mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
     BitMap *bitmap;
     char *bits;
     int w, h;
{
717
  static const unsigned char swap_nibble[16]
718 719 720 721
    = { 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 */
722 723
  int i, j, w1;
  char *p;
724

725 726
  w1 = (w + 7) / 8;         /* nb of 8bits elt in X bitmap */
  bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
727 728 729
  bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
  bzero (bitmap->baseAddr, bitmap->rowBytes * h);
  for (i = 0; i < h; i++)
730 731 732
    {
      p = bitmap->baseAddr + i * bitmap->rowBytes;
      for (j = 0; j < w1; j++)
733 734 735 736
	{
	  /* Bitswap XBM bytes to match how Mac does things.  */
	  unsigned char c = *bits++;
	  *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
737
				 | (swap_nibble[(c>>4) & 0xf]));
738
	}
739
    }
740 741 742 743 744 745 746 747 748 749 750 751

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


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

752 753 754 755 756 757

Pixmap
XCreatePixmap (display, w, width, height, depth)
     Display *display;		/* not used */
     WindowPtr w;
     unsigned int width, height;
Steven Tamm's avatar
Steven Tamm committed
758
     unsigned int depth;
759 760 761 762 763
{
  Pixmap pixmap;
  Rect r;
  QDErr err;

764
  SetPortWindowPort (w);
765 766

  SetRect (&r, 0, 0, width, height);
767 768 769 770 771 772 773 774 775
#if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
  if (depth == 1)
#endif
    err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
#if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
  else
    /* CreateCGImageFromPixMaps requires ARGB format.  */
    err = QTNewGWorld (&pixmap, k32ARGBPixelFormat, &r, NULL, NULL, 0);
#endif
776 777 778 779 780 781 782 783 784 785 786 787 788
  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;
789
     unsigned int depth;
790 791 792
{
  Pixmap pixmap;
  BitMap bitmap;
793 794
  CGrafPtr old_port;
  GDHandle old_gdh;
795 796 797 798
  static GC gc = NULL;		/* not reentrant */

  if (gc == NULL)
    gc = XCreateGC (display, w, 0, NULL);
799 800 801 802 803

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

804
  GetGWorld (&old_port, &old_gdh);
805 806
  SetGWorld (pixmap, NULL);
  mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
807 808 809 810
  XSetForeground (display, gc, fg);
  XSetBackground (display, gc, bg);
  RGBForeColor (GC_FORE_COLOR (gc));
  RGBBackColor (GC_BACK_COLOR (gc));
811 812 813 814 815 816 817 818 819
  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));
820
  SetGWorld (old_port, old_gdh);
821 822 823 824 825 826
  mac_free_bitmap (&bitmap);

  return pixmap;
}


827 828 829
/* Mac replacement for XFillRectangle.  */

static void
830 831
mac_fill_rectangle (f, gc, x, y, width, height)
     struct frame *f;
832 833 834 835
     GC gc;
     int x, y;
     unsigned int width, height;
{
836 837 838 839
#if USE_CG_DRAWING
  CGContextRef context;

  context = mac_begin_cg_clip (f, gc);
840
  CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
841 842 843
  CGContextFillRect (context, CGRectMake (x, y, width, height));
  mac_end_cg_clip (f);
#else
844 845
  Rect r;

846
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
847

848
  RGBForeColor (GC_FORE_COLOR (gc));
849 850
  SetRect (&r, x, y, x + width, y + height);

851
  mac_begin_clip (gc);
852
  PaintRect (&r); /* using foreground color of gc */
853
  mac_end_clip (gc);
854
#endif
855 856 857 858 859 860
}


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

static void
861 862
mac_draw_rectangle (f, gc, x, y, width, height)
     struct frame *f;
863 864 865 866
     GC gc;
     int x, y;
     unsigned int width, height;
{
867 868 869 870
#if USE_CG_DRAWING
  CGContextRef context;

  context = mac_begin_cg_clip (f, gc);
871
  CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND (context, gc);
872 873 874 875
  CGContextStrokeRect (context,
		       CGRectMake (x + 0.5f, y + 0.5f, width, height));
  mac_end_cg_clip (f);
#else
876 877
  Rect r;

878
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
879

880
  RGBForeColor (GC_FORE_COLOR (gc));
881
  SetRect (&r, x, y, x + width + 1, y + height + 1);
882

883
  mac_begin_clip (gc);
884
  FrameRect (&r); /* using foreground color of gc */
885
  mac_end_clip (gc);
886
#endif
887 888 889
}


890 891 892 893 894 895 896 897 898 899 900 901 902
#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)
    {
903 904 905
      static const UniCharCount lengths[] = {kATSUToTextEnd};
      static const ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
      static const ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
906 907
      static ATSLineLayoutOptions line_layout =
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
908
	kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
909
	| kATSLineUseQDRendering
910
#else
911
	kATSLineIsDisplayOnly | kATSLineFractDisable
912 913
#endif
	;
914
      static const ATSUAttributeValuePtr values[] = {&line_layout};
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

      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

947

948
static void
949 950
mac_invert_rectangle (f, x, y, width, height)
     struct frame *f;
951 952 953 954 955
     int x, y;
     unsigned int width, height;
{
  Rect r;

956 957 958
#if USE_CG_DRAWING
  mac_prepare_for_quickdraw (f);
#endif
959
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
960 961 962 963 964 965 966

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

  InvertRect (&r);
}


967
static void
968 969
mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width,
			overstrike_p, bytes_per_char)
970
     struct frame *f;
971 972 973
     GC gc;
     int x, y;
     char *buf;
974
     int nchars, bg_width, overstrike_p, bytes_per_char;
975
{
976
  SetPortWindowPort (FRAME_MAC_WINDOW (f));
977

978 979 980
#if USE_ATSUI
  if (GC_FONT (gc)->mac_style)
    {
981
      OSStatus err;
982 983 984 985 986 987 988
      ATSUTextLayout text_layout;

      xassert (bytes_per_char == 2);

#ifndef WORDS_BIG_ENDIAN
      {
	int i;
989
	UniChar *text = (UniChar *)buf;
990 991

	for (i = 0; i < nchars; i++)
992
	  text[i] = EndianU16_BtoN (text[i]);
993 994 995 996 997 998
      }
#endif
      err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
						nchars,
						GC_FONT (gc)->mac_style,
						&text_layout);
999 1000
      if (err != noErr)
	return;
1001
#ifdef MAC_OSX
1002 1003
      if (!mac_use_core_graphics)
	{
1004 1005 1006
#endif
#if USE_CG_DRAWING
	  mac_prepare_for_quickdraw (f);
1007
#endif
1008
	  mac_begin_clip (gc);
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
	  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)));
1019
	    }
1020 1021 1022 1023
	  MoveTo (x, y);
	  ATSUDrawText (text_layout,
			kATSUFromTextBeginning, kATSUToTextEnd,
			kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
1024 1025 1026 1027 1028 1029 1030
	  if (overstrike_p)
	    {
	      MoveTo (x + 1, y);
	      ATSUDrawText (text_layout,
			    kATSUFromTextBeginning, kATSUToTextEnd,
			    kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
	    }
1031
	  mac_end_clip (gc);
1032 1033 1034 1035 1036
#ifdef MAC_OSX
	}
      else
	{
	  CGrafPtr port;
1037
	  static CGContextRef context;
1038
	  float port_height = FRAME_PIXEL_HEIGHT (f);
1039 1040 1041
	  static const ATSUAttributeTag tags[] = {kATSUCGContextTag};
	  static const ByteCount sizes[] = {sizeof (CGContextRef)};
	  static const ATSUAttributeValuePtr values[] = {&context};
1042

1043 1044 1045
#if USE_CG_DRAWING
	  context = mac_begin_cg_clip (f, gc);
#else
1046 1047 1048
	  GetPort (&port);
	  QDBeginCGContext (port, &context);
	  if (gc->n_clip_rects || bg_width)
1049
	    {
1050 1051
	      CGContextTranslateCTM (context, 0, port_height);
	      CGContextScaleCTM (context, 1, -1);
1052
	      if (gc->n_clip_rects)
1053 1054
		CGContextClipToRects (context, gc->clip_rects,
				      gc->n_clip_rects);
1055
#endif
1056
	      if (bg_width)
1057
		{
1058
		  CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
1059 1060 1061 1062
		  CGContextFillRect
		    (context,
		     CGRectMake (x, y - FONT_BASE (GC_FONT (gc)),
				 bg_width, FONT_HEIGHT (GC_FONT (gc))));
1063
		}
1064 1065
	      CGContextScaleCTM (context, 1, -1);
	      CGContextTranslateCTM (context, 0, -port_height);
1066
#if !USE_CG_DRAWING
1067
	    }
1068
#endif
1069
	  CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
1070
	  err = ATSUSetLayoutControls (text_layout,
1071
				       sizeof (tags) / sizeof (tags[0]),
1072 1073
				       tags, sizes, values);
	  if (err == noErr)
1074 1075 1076 1077 1078 1079 1080 1081 1082
	    {
	      ATSUDrawText (text_layout,
			    kATSUFromTextBeginning, kATSUToTextEnd,
			    Long2Fix (x), Long2Fix (port_height - y));
	      if (overstrike_p)
		ATSUDrawText (text_layout,
			      kATSUFromTextBeginning, kATSUToTextEnd,
			      Long2Fix (x + 1), Long2Fix (port_height - y));
	    }
1083 1084 1085 1086
#if USE_CG_DRAWING
	  mac_end_cg_clip (f);
	  context = NULL;
#else
1087 1088
	  CGContextSynchronize (context);
	  QDEndCGContext (port, &context);
1089
#endif
1090 1091 1092 1093
#if 0
	  /* This doesn't work on Mac OS X 10.1.  */
	  ATSUClearLayoutControls (text_layout,
				   sizeof (tags) / sizeof (tags[0]), tags);
1094
#else
1095 1096 1097
	  ATSUSetLayoutControls (text_layout,
				 sizeof (tags) / sizeof (tags[0]),
				 tags, sizes, values);
1098 1099
#endif
	}
1100
#endif	/* MAC_OSX */
1101 1102
    }
  else
1103
#endif	/* USE_ATSUI */
1104
    {
1105 1106 1107 1108 1109
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
      UInt32 savedFlags;

      if (mac_use_core_graphics)
	savedFlags = SwapQDTextFlags (kQDUseCGTextRendering);
1110 1111 1112
#endif
#if USE_CG_DRAWING
      mac_prepare_for_quickdraw (f);
1113
#endif
1114
      mac_begin_clip (gc);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
      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;
1135

1136 1137 1138 1139 1140 1141
	  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);
1142
#endif
1143 1144 1145 1146 1147
      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);
1148 1149 1150 1151 1152 1153
      if (overstrike_p)
	{
	  TextMode (srcOr);
	  MoveTo (x + 1, y);
	  DrawText (buf, 0, nchars * bytes_per_char);
	}
1154 1155
      if (bg_width)
	RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1156
      mac_end_clip (gc);
1157

1158
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1159 1160
      if (mac_use_core_graphics)
	SwapQDTextFlags(savedFlags);
1161
#endif
1162
    }
1163 1164