nsterm.m 186 KB
Newer Older
1
/* NeXT/Open/GNUstep / MacOSX communication module.
Glenn Morris's avatar
Glenn Morris committed
2
   Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009, 2010
3
     Free Software Foundation, Inc.
4 5 6

This file is part of GNU Emacs.

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

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

You should have received a copy of the GNU General Public License
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
19

20
/*
21 22 23 24 25 26 27
Originally by Carl Edman
Updated by Christian Limpach (chris@nice.ch)
OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
*/

28 29 30 31
/* This should be the first include, as it may set up #defines affecting
   interpretation of even the system includes. */
#include "config.h"

32 33 34
#include <math.h>
#include <sys/types.h>
#include <time.h>
35
#include <signal.h>
36
#include <unistd.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
37
#include <setjmp.h>
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

#include "lisp.h"
#include "blockinput.h"
#include "sysselect.h"
#include "nsterm.h"
#include "systime.h"
#include "character.h"
#include "fontset.h"
#include "composite.h"
#include "ccl.h"

#include "termhooks.h"
#include "termopts.h"
#include "termchar.h"

#include "window.h"
#include "keyboard.h"

#include "font.h"

/* call tracing */
#if 0
int term_trace_num = 0;
#define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
                                __FILE__, __LINE__, ++term_trace_num)
#else
#define NSTRACE(x)
#endif


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

    Local declarations

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

/* Convert a symbol indexed with an NSxxx value to a value as defined
   in keyboard.c (lispy_function_key). I hope this is a correct way
   of doing things... */
static unsigned convert_ns_to_X_keysym[] =
{
  NSHomeFunctionKey,            0x50,
  NSLeftArrowFunctionKey,       0x51,
  NSUpArrowFunctionKey,         0x52,
  NSRightArrowFunctionKey,      0x53,
  NSDownArrowFunctionKey,       0x54,
  NSPageUpFunctionKey,          0x55,
  NSPageDownFunctionKey,        0x56,
  NSEndFunctionKey,             0x57,
  NSBeginFunctionKey,           0x58,
  NSSelectFunctionKey,          0x60,
  NSPrintFunctionKey,           0x61,
  NSExecuteFunctionKey,         0x62,
  NSInsertFunctionKey,          0x63,
  NSUndoFunctionKey,            0x65,
  NSRedoFunctionKey,            0x66,
  NSMenuFunctionKey,            0x67,
  NSFindFunctionKey,            0x68,
  NSHelpFunctionKey,            0x6A,
  NSBreakFunctionKey,           0x6B,

  NSF1FunctionKey,              0xBE,
  NSF2FunctionKey,              0xBF,
  NSF3FunctionKey,              0xC0,
  NSF4FunctionKey,              0xC1,
  NSF5FunctionKey,              0xC2,
  NSF6FunctionKey,              0xC3,
  NSF7FunctionKey,              0xC4,
  NSF8FunctionKey,              0xC5,
  NSF9FunctionKey,              0xC6,
  NSF10FunctionKey,             0xC7,
  NSF11FunctionKey,             0xC8,
  NSF12FunctionKey,             0xC9,
  NSF13FunctionKey,             0xCA,
  NSF14FunctionKey,             0xCB,
  NSF15FunctionKey,             0xCC,
114 115 116 117 118 119 120 121 122
  NSF16FunctionKey,             0xCD,
  NSF17FunctionKey,             0xCE,
  NSF18FunctionKey,             0xCF,
  NSF19FunctionKey,             0xD0,
  NSF20FunctionKey,             0xD1,
  NSF21FunctionKey,             0xD2,
  NSF22FunctionKey,             0xD3,
  NSF23FunctionKey,             0xD4,
  NSF24FunctionKey,             0xD5,
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

  NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
  NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
  NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */

  NSTabCharacter,		0x09,
  0x19,				0x09,  /* left tab->regular since pass shift */
  NSCarriageReturnCharacter,	0x0D,
  NSNewlineCharacter,		0x0D,
  NSEnterCharacter,		0x8D,

  0x1B,				0x1B   /* escape */
};


/* Lisp communications */
Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
Lisp_Object ns_input_color, ns_input_text, ns_working_text;
Lisp_Object ns_input_spi_name, ns_input_spi_arg;
Lisp_Object Vx_toolkit_scroll_bars;
static Lisp_Object Qmodifier_value;
144
Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
extern Lisp_Object Qcursor_color, Qcursor_type, Qns;

/* Specifies which emacs modifier should be generated when NS receives
   the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
Lisp_Object ns_alternate_modifier;

/* Specifies which emacs modifier should be generated when NS receives
   the Command modifer.  May be any of the modifier lisp symbols. */
Lisp_Object ns_command_modifier;

/* Specifies which emacs modifier should be generated when NS receives
   the Control modifer.  May be any of the modifier lisp symbols. */
Lisp_Object ns_control_modifier;

/* Specifies which emacs modifier should be generated when NS receives
   the Function modifer (laptops).  May be any of the modifier lisp symbols. */
Lisp_Object ns_function_modifier;

/* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
164
Lisp_Object ns_antialias_text;
165 166 167 168 169 170 171 172 173

/* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
   the maximum font size to NOT antialias.  On GNUstep there is currently
   no way to control this behavior. */
float ns_antialias_threshold;

/* Used to pick up AppleHighlightColor on OS X */
NSString *ns_selection_color;

174 175
/* Confirm on exit. */
Lisp_Object ns_confirm_quit;
176 177

NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
178
NSString *ns_app_name = @"Emacs";  /* default changed later */
179 180

/* Display variables */
181
struct ns_display_info *x_display_list; /* Chain of existing displays */
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
Lisp_Object ns_display_name_list;
long context_menu_value = 0;

/* display update */
NSPoint last_mouse_motion_position;
static NSRect last_mouse_glyph;
static unsigned long last_mouse_movement_time = 0;
static Lisp_Object last_mouse_motion_frame;
static EmacsScroller *last_mouse_scroll_bar = nil;
static struct frame *ns_updating_frame;
static NSView *focus_view = NULL;
static int ns_window_num =0;
static NSRect uRect;
static BOOL gsaved = NO;
BOOL ns_in_resize = NO;
197
static BOOL ns_fake_keydown = NO;
198 199
int ns_tmp_flags; /* FIXME */
struct nsfont_info *ns_tmp_font; /* FIXME */
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
/*static int debug_lock = 0; */

/* event loop */
static BOOL send_appdefined = YES;
static NSEvent *last_appdefined_event = 0;
static NSTimer *timed_entry = 0;
static NSTimer *fd_entry = nil;
static NSTimer *scroll_repeat_entry = nil;
static fd_set select_readfds, t_readfds;
static struct timeval select_timeout;
static int select_nfds;
static NSAutoreleasePool *outerpool;
static struct input_event *emacs_event = NULL;
static struct input_event *q_event_ptr = NULL;
static int n_emacs_events_pending = 0;
static NSMutableArray *ns_pending_files, *ns_pending_service_names,
  *ns_pending_service_args;
static BOOL inNsSelect = 0;

/* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
#define NS_FUNCTION_KEY_MASK 0x800000
#define EV_MODIFIERS(e)                               \
    ((([e modifierFlags] & NSHelpKeyMask) ?           \
           hyper_modifier : 0)                        \
     | (([e modifierFlags] & NSAlternateKeyMask) ?    \
225
           parse_solitary_modifier (ns_alternate_modifier) : 0)   \
226 227 228
     | (([e modifierFlags] & NSShiftKeyMask) ?        \
           shift_modifier : 0)                        \
     | (([e modifierFlags] & NSControlKeyMask) ?      \
229
           parse_solitary_modifier (ns_control_modifier) : 0)     \
230
     | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
231
           parse_solitary_modifier (ns_function_modifier) : 0)    \
232
     | (([e modifierFlags] & NSCommandKeyMask) ?      \
233
           parse_solitary_modifier (ns_command_modifier):0))
234 235 236 237

#define EV_UDMODIFIERS(e)                                      \
    ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
     | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
238
     | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
239 240
     | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
     | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
241
     | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
242
     | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
243 244
     | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
     | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
245 246 247

#define EV_BUTTON(e)                                                         \
    ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
248 249
      (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
     [e buttonNumber] - 1)
250 251 252 253 254 255 256 257

/* Convert the time field to a timestamp in milliseconds. */
#define EV_TIMESTAMP(e) ([e timestamp] * 1000)

/* This is a piece of code which is common to all the event handling
   methods.  Maybe it should even be a function.  */
#define EV_TRAILER(e)                                         \
  {                                                           \
258
  XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
259 260 261 262 263 264 265
  if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
  n_emacs_events_pending++;                                   \
  kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
  EVENT_INIT (*emacs_event);                                  \
  ns_send_appdefined (-1);                                    \
  }

266 267
void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);

268
/* TODO: get rid of need for these forward declarations */
269 270
static void ns_condemn_scroll_bars (struct frame *f);
static void ns_judge_scroll_bars (struct frame *f);
271
void x_set_frame_alpha (struct frame *f);
272 273 274

/* unused variables needed for compatibility reasons */
int x_use_underline_position_properties, x_underline_at_descent_line;
275
/* FIXME: figure out what to do with underline_minimum_offset. */
276 277 278 279 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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338


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

    Utilities

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


static Lisp_Object
append2 (Lisp_Object list, Lisp_Object item)
/* --------------------------------------------------------------------------
   Utility to append to a list
   -------------------------------------------------------------------------- */
{
  Lisp_Object array[2];
  array[0] = list;
  array[1] = Fcons (item, Qnil);
  return Fnconc (2, &array[0]);
}


void
ns_init_paths ()
/* --------------------------------------------------------------------------
   Used to allow emacs to find its resources under Emacs.app
   Called from emacs.c at startup.
   -------------------------------------------------------------------------- */
{
  NSBundle *bundle = [NSBundle mainBundle];
  NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
  NSString *resourcePath, *resourcePaths;
  NSRange range;
  BOOL onWindows = NO; /* how do I determine this? */
  NSString *pathSeparator = onWindows ? @";" : @":";
  NSFileManager *fileManager = [NSFileManager defaultManager];
  BOOL isDir;
/*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */

  /* get bindir from base */
  range = [resourceDir rangeOfString: @"Contents"];
  if (range.location != NSNotFound)
    {
      binDir = [binDir stringByAppendingPathComponent: @"Contents"];
#ifdef NS_IMPL_COCOA
      binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
#endif
    }

  /* the following based on Andrew Choi's init_mac_osx_environment () */
  if (!getenv ("EMACSLOADPATH"))
    {
      NSArray *paths = [resourceDir stringsByAppendingPaths:
                                  [NSArray arrayWithObjects:
                                         @"site-lisp", @"lisp", @"leim", nil]];
      NSEnumerator *pathEnum = [paths objectEnumerator];
      resourcePaths = @"";
      while (resourcePath = [pathEnum nextObject])
        {
          if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
            if (isDir)
              {
                if ([resourcePaths length] > 0)
339 340 341 342
                  resourcePaths
		    = [resourcePaths stringByAppendingString: pathSeparator];
                resourcePaths
		  = [resourcePaths stringByAppendingString: resourcePath];
343 344 345 346
              }
        }
      if ([resourcePaths length] > 0)
        setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
347
/*NSLog (@"loadPath: '%@'\n", resourcePaths); */
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    }

  if (!getenv ("EMACSPATH"))
    {
      NSArray *paths = [binDir stringsByAppendingPaths:
                                  [NSArray arrayWithObjects: @"bin",
                                                             @"lib-exec", nil]];
      NSEnumerator *pathEnum = [paths objectEnumerator];
      resourcePaths = @"";
      while (resourcePath = [pathEnum nextObject])
        {
          if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
            if (isDir)
              {
                if ([resourcePaths length] > 0)
363 364 365 366
                  resourcePaths
		    = [resourcePaths stringByAppendingString: pathSeparator];
                resourcePaths
		  = [resourcePaths stringByAppendingString: resourcePath];
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
              }
        }
      if ([resourcePaths length] > 0)
        setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
    }

  resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
  if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
    {
      if (isDir)
        {
          if (!getenv ("EMACSDATA"))
            setenv ("EMACSDATA", [resourcePath UTF8String], 1);
          if (!getenv ("EMACSDOC"))
            setenv ("EMACSDOC", [resourcePath UTF8String], 1);
        }
    }

  if (!getenv ("INFOPATH"))
    {
      resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
      if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
        if (isDir)
390 391 392
          setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
                                             UTF8String], 1);
      /* Note, extra colon needed to cause merge w/later user additions. */
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    }
}


static int
timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
/* --------------------------------------------------------------------------
   Subtract the `struct timeval' values X and Y, storing the result in RESULT.
   Return 1 if the difference is negative, otherwise 0.
   -------------------------------------------------------------------------- */
{
  /* Perform the carry for the later subtraction by updating y.
     This is safer because on some systems
     the tv_sec member is unsigned.  */
  if (x.tv_usec < y.tv_usec)
    {
      int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
      y.tv_usec -= 1000000 * nsec;
      y.tv_sec += nsec;
    }
  if (x.tv_usec - y.tv_usec > 1000000)
    {
      int nsec = (y.tv_usec - x.tv_usec) / 1000000;
      y.tv_usec += 1000000 * nsec;
      y.tv_sec -= nsec;
    }

  /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
  result->tv_sec = x.tv_sec - y.tv_sec;
  result->tv_usec = x.tv_usec - y.tv_usec;

  /* Return indication of whether the result should be considered negative.  */
  return x.tv_sec < y.tv_sec;
}

static void
ns_timeout (int usecs)
/* --------------------------------------------------------------------------
     Blocking timer utility used by ns_ring_bell
   -------------------------------------------------------------------------- */
{
  struct timeval wakeup;

  EMACS_GET_TIME (wakeup);

  /* Compute time to wait until, propagating carry from usecs.  */
  wakeup.tv_usec += usecs;
  wakeup.tv_sec += (wakeup.tv_usec / 1000000);
  wakeup.tv_usec %= 1000000;

  /* Keep waiting until past the time wakeup.  */
  while (1)
    {
      struct timeval timeout;

      EMACS_GET_TIME (timeout);

      /* In effect, timeout = wakeup - timeout.
	 Break if result would be negative.  */
      if (timeval_subtract (&timeout, wakeup, timeout))
	break;

      /* Try to wait that long--but we might wake up sooner.  */
      select (0, NULL, NULL, NULL, &timeout);
    }
}


void
ns_release_object (void *obj)
/* --------------------------------------------------------------------------
    Release an object (callable from C)
   -------------------------------------------------------------------------- */
{
    [(id)obj release];
}


void
ns_retain_object (void *obj)
/* --------------------------------------------------------------------------
    Retain an object (callable from C)
   -------------------------------------------------------------------------- */
{
    [(id)obj retain];
}


void *
ns_alloc_autorelease_pool ()
/* --------------------------------------------------------------------------
     Allocate a pool for temporary objects (callable from C)
   -------------------------------------------------------------------------- */
{
  return [[NSAutoreleasePool alloc] init];
}


void
ns_release_autorelease_pool (void *pool)
/* --------------------------------------------------------------------------
     Free a pool and temporary objects it refers to (callable from C)
   -------------------------------------------------------------------------- */
{
  ns_release_object (pool);
}



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

    Focus (clipping) and screen update

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

static NSRect
ns_resize_handle_rect (NSWindow *window)
{
  NSRect r = [window frame];
  r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
  r.origin.y = 0;
  r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
  return r;
}


static void
ns_update_begin (struct frame *f)
/* --------------------------------------------------------------------------
   Prepare for a grouped sequence of drawing calls
523
   external (RIF) call; whole frame, called before update_window_begin
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
   -------------------------------------------------------------------------- */
{
  NSView *view = FRAME_NS_VIEW (f);
  NSTRACE (ns_update_begin);

  ns_updating_frame = f;
  [view lockFocus];

#ifdef NS_IMPL_GNUSTEP
  uRect = NSMakeRect (0, 0, 0, 0);
#endif
}


static void
ns_update_window_begin (struct window *w)
/* --------------------------------------------------------------------------
   Prepare for a grouped sequence of drawing calls
542
   external (RIF) call; for one window, called after update_begin
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
   -------------------------------------------------------------------------- */
{
  struct frame *f = XFRAME (WINDOW_FRAME (w));
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
  NSTRACE (ns_update_window_begin);

  updated_window = w;
  set_output_cursor (&w->cursor);

  BLOCK_INPUT;

  if (f == dpyinfo->mouse_face_mouse_frame)
    {
      /* Don't do highlighting for mouse motion during the update.  */
      dpyinfo->mouse_face_defer = 1;

        /* If the frame needs to be redrawn,
           simply forget about any prior mouse highlighting.  */
      if (FRAME_GARBAGED_P (f))
        dpyinfo->mouse_face_window = Qnil;

      /* (further code for mouse faces ifdef'd out in other terms elided) */
    }

  UNBLOCK_INPUT;
}


static void
ns_update_window_end (struct window *w, int cursor_on_p,
                      int mouse_face_overwritten_p)
/* --------------------------------------------------------------------------
   Finished a grouped sequence of drawing calls
576
   external (RIF) call; for one window called before update_end
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
   -------------------------------------------------------------------------- */
{
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));

  /* note: this fn is nearly identical in all terms */
  if (!w->pseudo_window_p)
    {
      BLOCK_INPUT;

      if (cursor_on_p)
	display_and_set_cursor (w, 1,
                                output_cursor.hpos, output_cursor.vpos,
				output_cursor.x, output_cursor.y);

      if (draw_window_fringes (w, 1))
	x_draw_vertical_border (w);

      UNBLOCK_INPUT;
    }

  /* If a row with mouse-face was overwritten, arrange for
     frame_up_to_date to redisplay the mouse highlight.  */
  if (mouse_face_overwritten_p)
    {
      dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
      dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
      dpyinfo->mouse_face_window = Qnil;
    }

  updated_window = NULL;
  NSTRACE (update_window_end);
}


static void
ns_update_end (struct frame *f)
/* --------------------------------------------------------------------------
   Finished a grouped sequence of drawing calls
615
   external (RIF) call; for whole frame, called after update_window_end
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
   -------------------------------------------------------------------------- */
{
  NSView *view = FRAME_NS_VIEW (f);

/*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
    FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;

  BLOCK_INPUT;

#ifdef NS_IMPL_GNUSTEP
  /* trigger flush only in the rectangle we tracked as being drawn */
  [view unlockFocusNeedsFlush: NO];
/*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
  [view lockFocusInRect: uRect];
#endif

  [view unlockFocus];
  [[view window] flushWindow];

  UNBLOCK_INPUT;
  ns_updating_frame = NULL;
  NSTRACE (ns_update_end);
}


static void
ns_flush (struct frame *f)
/* --------------------------------------------------------------------------
644
   external (RIF) call
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
   NS impl is no-op since currently we flush in ns_update_end and elsewhere
   -------------------------------------------------------------------------- */
{
    NSTRACE (ns_flush);
}


static void
ns_focus (struct frame *f, NSRect *r, int n)
/* --------------------------------------------------------------------------
   Internal: Focus on given frame.  During small local updates this is used to
     draw, however during large updates, ns_update_begin and ns_update_end are
     called to wrap the whole thing, in which case these calls are stubbed out.
     Except, on GNUstep, we accumulate the rectangle being drawn into, because
     the back end won't do this automatically, and will just end up flushing
     the entire window.
   -------------------------------------------------------------------------- */
{
663
//  NSTRACE (ns_focus);
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
#ifdef NS_IMPL_GNUSTEP
  NSRect u;
    if (n == 2)
      u = NSUnionRect (r[0], r[1]);
    else if (r)
      u = *r;
#endif
/* static int c =0;
   fprintf (stderr, "focus: %d", c++);
   if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
   fprintf (stderr, "\n"); */

  if (f != ns_updating_frame)
    {
      NSView *view = FRAME_NS_VIEW (f);
      if (view != focus_view)
        {
          if (focus_view != NULL)
            {
              [focus_view unlockFocus];
              [[focus_view window] flushWindow];
/*debug_lock--; */
            }

          if (view)
#ifdef NS_IMPL_GNUSTEP
            r ? [view lockFocusInRect: u] : [view lockFocus];
#else
            [view lockFocus];
#endif
          focus_view = view;
/*if (view) debug_lock++; */
        }
#ifdef NS_IMPL_GNUSTEP
      else
        {
          /* more than one rect being drawn into */
          if (view && r)
            {
              [view unlockFocus]; /* add prev rect to redraw list */
              [view lockFocusInRect: u]; /* focus for draw in new rect */
            }
        }
#endif
    }
#ifdef NS_IMPL_GNUSTEP
  else
    {
      /* in batch mode, but in GNUstep must still track rectangles explicitly */
      uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
    }
#endif

717
  /* clipping */
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  if (r)
    {
      [[NSGraphicsContext currentContext] saveGraphicsState];
      if (n == 2)
        NSRectClipList (r, 2);
      else
        NSRectClip (*r);
      gsaved = YES;
    }
}


static void
ns_unfocus (struct frame *f)
/* --------------------------------------------------------------------------
     Internal: Remove focus on given frame
   -------------------------------------------------------------------------- */
{
736
//  NSTRACE (ns_unfocus);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

  if (gsaved)
    {
      [[NSGraphicsContext currentContext] restoreGraphicsState];
      gsaved = NO;
    }

  if (f != ns_updating_frame)
    {
      if (focus_view != NULL)
        {
          [focus_view unlockFocus];
          [[focus_view window] flushWindow];
          focus_view = NULL;
/*debug_lock--; */
        }
    }
}


static void
758
ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
759
/* --------------------------------------------------------------------------
760
     Internal (but parallels other terms): Focus drawing on given row
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
   -------------------------------------------------------------------------- */
{
  struct frame *f = XFRAME (WINDOW_FRAME (w));
  NSRect clip_rect;
  int window_x, window_y, window_width;

  window_box (w, area, &window_x, &window_y, &window_width, 0);

  clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
  clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
  clip_rect.origin.y = max (clip_rect.origin.y, window_y);
  clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
  clip_rect.size.height = row->visible_height;

  /* allow a full-height row at the top when requested
     (used to draw fringe all the way through internal border area) */
  if (gc && clip_rect.origin.y < 5)
    {
      clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
      clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
    }

  /* likewise at bottom */
  if (gc &&
      FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
    clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);

  ns_focus (f, &clip_rect, 1);
}


static void
ns_ring_bell ()
/* --------------------------------------------------------------------------
     "Beep" routine
   -------------------------------------------------------------------------- */
{
  NSTRACE (ns_ring_bell);
  if (visible_bell)
    {
      NSAutoreleasePool *pool;
      struct frame *frame = SELECTED_FRAME ();
      NSView *view;

      BLOCK_INPUT;
      pool = [[NSAutoreleasePool alloc] init];

      view = FRAME_NS_VIEW (frame);
      if (view != nil)
        {
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
          /* Get the bounds of our NSView */
          NSRect viewBounds = [view bounds];

          /* Height of each line to flash.  */
          int flash_height = FRAME_LINE_HEIGHT (frame);
          int width = FRAME_PIXEL_WIDTH (frame)
                    - NS_SCROLL_BAR_WIDTH (frame);

          /* Get the GraphicsContext */
          CGContextRef ctxt = [[NSGraphicsContext currentContext] graphicsPort];
          CGRect lowerLine, upperLine;
          lowerLine =
          CGRectMake(viewBounds.origin.x, viewBounds.origin.y,
                     width + NS_SCROLL_BAR_WIDTH(frame),
                     flash_height + FRAME_INTERNAL_BORDER_WIDTH (frame));
          upperLine =
          CGRectMake(viewBounds.origin.x,
                     viewBounds.origin.y + viewBounds.size.height
                     - (flash_height + FRAME_INTERNAL_BORDER_WIDTH (frame)),
                     width,
                     flash_height + FRAME_INTERNAL_BORDER_WIDTH (frame));

          /* Invert the colors using a difference blend.  */
          CGContextSetBlendMode(ctxt, kCGBlendModeDifference);
          CGContextSetGrayFillColor(ctxt, 1, 1);

          /* If window is tall, flash top and bottom line.  */
          if (viewBounds.size.height > 3 * FRAME_LINE_HEIGHT (frame))
            {
              CGContextFillRect(ctxt, upperLine);
              CGContextFillRect(ctxt, lowerLine);
            }
          else
            /* If it is short, flash it all.  */
            CGContextFillRect(ctxt, NSRectToCGRect([view bounds]));

          /* Bounce Dock icon. Maybe we can allow some configuration here.  */
          [NSApp requestUserAttention: NSInformationalRequest];

850 851
          [[view window] flushWindow];
          ns_timeout (150000);
852 853 854 855 856 857 858 859 860 861 862

          /* If window is tall, flash top and bottom line.  */
          if (viewBounds.size.height > 3 * FRAME_LINE_HEIGHT (frame))
            {
              CGContextFillRect(ctxt, upperLine);
              CGContextFillRect(ctxt, lowerLine);
            }
          else
            /* If it is short, flash it all.  */
            CGContextFillRect(ctxt, NSRectToCGRect([view bounds]));

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
          [[view window] flushWindow];
          ns_unfocus (frame);
        }
      [pool release];
      UNBLOCK_INPUT;
    }
  else
    {
      NSBeep ();
    }
}


static void
ns_reset_terminal_modes (struct terminal *terminal)
/*  Externally called as hook */
{
  NSTRACE (ns_reset_terminal_modes);
}

883

884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
static void
ns_set_terminal_modes (struct terminal *terminal)
/*  Externally called as hook */
{
  NSTRACE (ns_set_terminal_modes);
}



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

    Frame / window manager related functions

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


static void
ns_raise_frame (struct frame *f)
/* --------------------------------------------------------------------------
     Bring window to foreground and make it active
   -------------------------------------------------------------------------- */
{
  NSView *view = FRAME_NS_VIEW (f);
  check_ns ();
  BLOCK_INPUT;
909 910 911 912 913
  FRAME_SAMPLE_VISIBILITY (f);
  if (FRAME_VISIBLE_P (f))
    {
      [[view window] makeKeyAndOrderFront: NSApp];
    }
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
  UNBLOCK_INPUT;
}


static void
ns_lower_frame (struct frame *f)
/* --------------------------------------------------------------------------
     Send window to back
   -------------------------------------------------------------------------- */
{
  NSView *view = FRAME_NS_VIEW (f);
  check_ns ();
  BLOCK_INPUT;
  [[view window] orderBack: NSApp];
  UNBLOCK_INPUT;
}


static void
ns_frame_raise_lower (struct frame *f, int raise)
/* --------------------------------------------------------------------------
     External (hook)
   -------------------------------------------------------------------------- */
{
  NSTRACE (ns_frame_raise_lower);

  if (raise)
    ns_raise_frame (f);
  else
    ns_lower_frame (f);
}


static void
ns_frame_rehighlight (struct frame *frame)
/* --------------------------------------------------------------------------
     External (hook): called on things like window switching within frame
   -------------------------------------------------------------------------- */
{
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
954
  struct frame *old_highlight = dpyinfo->x_highlight_frame;
955 956

  NSTRACE (ns_frame_rehighlight);
957
  if (dpyinfo->x_focus_frame)
958
    {
959 960 961 962 963
      dpyinfo->x_highlight_frame
	= (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
           ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
           : dpyinfo->x_focus_frame);
      if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
964
        {
965 966
          FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
          dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
967 968 969
        }
    }
  else
970
      dpyinfo->x_highlight_frame = 0;
971

972 973
  if (dpyinfo->x_highlight_frame &&
         dpyinfo->x_highlight_frame != old_highlight)
974 975
    {
      if (old_highlight)
976
	{
977
          x_update_cursor (old_highlight, 1);
978 979
	  x_set_frame_alpha (old_highlight);
	}
980
      if (dpyinfo->x_highlight_frame)
981
	{
982
          x_update_cursor (dpyinfo->x_highlight_frame, 1);
983 984
          x_set_frame_alpha (dpyinfo->x_highlight_frame);
	}
985 986 987 988 989 990 991 992 993 994 995
    }
}


void
x_make_frame_visible (struct frame *f)
/* --------------------------------------------------------------------------
     External: Show the window (X11 semantics)
   -------------------------------------------------------------------------- */
{
  NSTRACE (x_make_frame_visible);
996
  /* XXX: at some points in past this was not needed, as the only place that
997 998 999
     called this (frame.c:Fraise_frame ()) also called raise_lower;
     if this ends up the case again, comment this out again. */
  if (!FRAME_VISIBLE_P (f))
1000 1001 1002 1003
    {
      f->async_visible = 1;
      ns_raise_frame (f);
    }
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
}


void
x_make_frame_invisible (struct frame *f)
/* --------------------------------------------------------------------------
     External: Hide the window (X11 semantics)
   -------------------------------------------------------------------------- */
{
  NSView * view = FRAME_NS_VIEW (f);
  NSTRACE (x_make_frame_invisible);
  check_ns ();
  [[view window] orderOut: NSApp];
1017 1018
  f->async_visible = 0;
  f->async_iconified = 0;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
}


void
x_iconify_frame (struct frame *f)
/* --------------------------------------------------------------------------
     External: Iconify window
   -------------------------------------------------------------------------- */
{
  NSView * view = FRAME_NS_VIEW (f);
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
  NSTRACE (x_iconify_frame);
  check_ns ();

1033 1034
  if (dpyinfo->x_highlight_frame == f)
    dpyinfo->x_highlight_frame = 0;
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

  if ([[view window] windowNumber] <= 0)
    {
      /* the window is still deferred.  Make it very small, bring it
         on screen and order it out. */
      NSRect s = { { 100, 100}, {0, 0} };
      NSRect t;
      t = [[view window] frame];
      [[view window] setFrame: s display: NO];
      [[view window] orderBack: NSApp];
      [[view window] orderOut: NSApp];
      [[view window] setFrame: t display: NO];
    }
  [[view window] miniaturize: NSApp];
}


void
x_destroy_window (struct frame *f)
/* --------------------------------------------------------------------------
     External: Delete the window
   -------------------------------------------------------------------------- */
{
  NSView *view = FRAME_NS_VIEW (f);
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
  NSTRACE (x_destroy_window);
  check_ns ();

  [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */

  BLOCK_INPUT;

  free_frame_menubar (f);

  if (FRAME_FACE_CACHE (f))
    free_frame_faces (f);

1072 1073 1074 1075
  if (f == dpyinfo->x_focus_frame)
    dpyinfo->x_focus_frame = 0;
  if (f == dpyinfo->x_highlight_frame)
    dpyinfo->x_highlight_frame = 0;
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  if (f == dpyinfo->mouse_face_mouse_frame)
    {
      dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
      dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
      dpyinfo->mouse_face_window = Qnil;
      dpyinfo->mouse_face_deferred_gc = 0;
      dpyinfo->mouse_face_mouse_frame = 0;
    }

  xfree (f->output_data.ns);

  [[view window] close];
  [view release];

  ns_window_num--;
  UNBLOCK_INPUT;
}


void
x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
/* --------------------------------------------------------------------------
     External: Position the window
   -------------------------------------------------------------------------- */
{
  NSScreen *screen;
  NSView *view = FRAME_NS_VIEW (f);

  NSTRACE (x_set_offset);

  BLOCK_INPUT;

  f->left_pos = xoff;
  f->top_pos = yoff;
#ifdef NS_IMPL_GNUSTEP
  if (xoff < 100)
    f->left_pos = 100;  /* don't overlap menu */
#endif
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  if (view != nil && (screen = [[view window] screen]))
    [[view window] setFrameTopLeftPoint:
        NSMakePoint (SCREENMAXBOUND (f->left_pos),
                     SCREENMAXBOUND ([screen frame].size.height
                                     - NS_TOP_POS (f)))];
  UNBLOCK_INPUT;
}


void
x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
/* --------------------------------------------------------------------------
     Adjust window pixel size based on given character grid size
     Impl is a bit more complex than other terms, need to do some
     internal clipping and also pay attention to screen constraints.
   -------------------------------------------------------------------------- */
{
  EmacsView *view = FRAME_NS_VIEW (f);
  EmacsToolbar *toolbar = [view toolbar];
  NSWindow *window = [view window];
  NSScreen *screen = [window screen];
  NSRect wr = [window frame];
  int tb = FRAME_EXTERNAL_TOOL_BAR (f);
  int pixelwidth, pixelheight;
  static int oldRows, oldCols, oldFontWidth, oldFontHeight;
  static int oldTB;
  static struct frame *oldF;

  NSTRACE (x_set_window_size);

  if (view == nil ||
      (f == oldF
       && rows == oldRows && cols == oldCols
       && oldFontWidth == FRAME_COLUMN_WIDTH (f)
       && oldFontHeight == FRAME_LINE_HEIGHT (f)
       && oldTB == tb))
    return;

/*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */

  BLOCK_INPUT;

  check_frame_size (f, &rows, &cols);
  oldF = f;
  oldRows = rows;
  oldCols = cols;
  oldFontWidth = FRAME_COLUMN_WIDTH (f);
  oldFontHeight = FRAME_LINE_HEIGHT (f);
  oldTB = tb;

  f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
  compute_fringe_widths (f, 0);

  pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
  pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1170

1171
  /* If we have a toolbar, take its height into account. */
1172
  if (tb)
1173 1174 1175
    /* NOTE: previously this would generate wrong result if toolbar not
             yet displayed and fixing toolbar_height=32 helped, but
             now (200903) seems no longer needed */
1176 1177
    FRAME_NS_TOOLBAR_HEIGHT (f) =
      NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1178
        - FRAME_NS_TITLEBAR_HEIGHT (f);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  else
    FRAME_NS_TOOLBAR_HEIGHT (f) = 0;

  wr.size.width = pixelwidth + f->border_width;
  wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
                  + FRAME_NS_TOOLBAR_HEIGHT (f);

  /* constrain to screen if we can */
  if (screen)
    {
      NSSize sz = [screen visibleFrame].size;
      NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
      if (ez.width > 0)
        {
          int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
          cols -= cr;
          oldCols = cols;
          wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
          pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
        }
      if (ez.height > 0)
        {
          int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
          rows -= rr;
          oldRows = rows;
          wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
          pixelheight -= rr * FRAME_LINE_HEIGHT (f);
        }
      wr.origin.x = f->left_pos;
      wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
        - wr.size.height;
    }

  [view setRows: rows andColumns: cols];
  [window setFrame: wr display: YES];

/*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */

  /* This is a trick to compensate for Emacs' managing the scrollbar area
     as a fixed number of standard character columns.  Instead of leaving
     blank space for the extra, we chopped it off above.  Now for
     left-hand scrollbars, we shift all rendering to the left by the
     difference between the real width and Emacs' imagined one.  For
     right-hand bars, don't worry about it since the extra is never used.
     (Obviously doesn't work for vertically split windows tho..) */
  NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
    ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
                  - NS_SCROLL_BAR_WIDTH (f), 0)
    : NSMakePoint (0, 0);
  [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
  [view setBoundsOrigin: origin];

  change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
  FRAME_PIXEL_WIDTH (f) = pixelwidth;
  FRAME_PIXEL_HEIGHT (f) = pixelheight;
/*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */

  mark_window_cursors_off (XWINDOW (f->root_window));
  cancel_mouse_face (f);

  UNBLOCK_INPUT;
}


1243

1244 1245 1246 1247 1248 1249
/* ==========================================================================

    Color management

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

1250

1251 1252 1253 1254
NSColor *
ns_lookup_indexed_color (unsigned long idx, struct frame *f)
{
  struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1255 1256
  if (idx < 1 || idx >= color_table->avail)
    return nil;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  return color_table->colors[idx];
}


unsigned long
ns_index_color (NSColor *color, struct frame *f)
{
  struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
  int idx;
  NSNumber *index;

  if (!color_table->colors)
    {
      color_table->size = NS_COLOR_CAPACITY;
      color_table->avail = 1; /* skip idx=0 as marker */
1272 1273
      color_table->colors
	= (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1274
      color_table->colors[0] = nil;
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
      color_table->empty_indices = [[NSMutableSet alloc] init];
    }

  /* do we already have this color ? */
  {
    int i;
    for (i = 1; i < color_table->avail; i++)
      {
        if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
          {
            [color_table->colors[i] retain];
            return i;
          }
      }
  }

  if ([color_table->empty_indices count] > 0)
    {
      index = [color_table->empty_indices anyObject];
      [color_table->empty_indices removeObject: index];
      idx = [index unsignedIntValue];
    }
  else
    {
      if (color_table->avail == color_table->size)
        {
          color_table->size += NS_COLOR_CAPACITY;
1302 1303 1304
          color_table->colors
	    = (NSColor **)xrealloc (color_table->colors,
				    color_table->size * sizeof (NSColor *));
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
        }
      idx = color_table->avail++;
    }

  color_table->colors[idx] = color;
  [color retain];
/*fprintf(stderr, "color_table: allocated %d\n",idx);*/
  return idx;
}


void
ns_free_indexed_color (unsigned long idx, struct frame *f)
{
1319
  struct ns_color_table *color_table;
1320
  NSColor *color;
1321 1322 1323 1324 1325 1326 1327 1328 1329
  NSNumber *index;

  if (!f)
    return;

  color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;

  if (idx <= 0 || idx >= color_table->size) {
    message1("ns_free_indexed_color: Color index out of range.\n");
1330
    return;
1331 1332 1333 1334 1335 1336 1337 1338
  }

  index = [NSNumber numberWithUnsignedInt: idx];
  if ([color_table->empty_indices containsObject: index]) {
    message1("ns_free_indexed_color: attempt to free already freed color.\n");
    return;
  }

1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
  color = color_table->colors[idx];
  [color release];
  color_table->colors[idx] = nil;
  [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
/*fprintf(stderr, "color_table: FREED %d\n",idx);*/
}


static int
ns_get_color (const char *name, NSColor **col)
/* --------------------------------------------------------------------------
     Parse a color name
1351
   -------------------------------------------------------------------------- */
1352 1353 1354
/* On *Step, we attempt to mimic the X11 platform here, down to installing an
   X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
   See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1355
{
1356 1357 1358 1359
  NSColor *new = nil;
  static char hex[20];
  int scaling;
  float r = -1.0, g, b;
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
  NSString *nsname = [NSString stringWithUTF8String: name];

/*fprintf (stderr, "ns_get_color: '%s'\n", name); */
  BLOCK_INPUT;

  if ([nsname isEqualToString: @"ns_selection_color"])
    {
      nsname = ns_selection_color;
      name = [ns_selection_color UTF8String];
    }

1371 1372 1373 1374
  /* First, check for some sort of numeric specification. */
  hex[0] = '\0';

  if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1375 1376 1377 1378 1379 1380
    {
      NSScanner *scanner = [NSScanner scannerWithString: nsname];
      [scanner scanFloat: &r];
      [scanner scanFloat: &g];
      [scanner scanFloat: &b];
    }
1381
  else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1382
    {
1383 1384
      strncpy (hex, name + 4, 19);
      hex[19] = '\0';
1385
      scaling = (strlen(hex) - 2) / 3;
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    }
  else if (name[0] == '#')        /* An old X11 format; convert to newer */
    {
      int len = (strlen(name) - 1);
      int start = (len % 3 == 0) ? 1 : len / 4 + 1;
      int i;
      scaling = strlen(name+start) / 3;
      for (i=0; i<3; i++) {
        strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
        hex[(i+1) * (scaling + 1) - 1] = '/';
      }
      hex[3 * (scaling + 1) - 1] = '\0';
1398 1399
    }

1400
  if (hex[0])
1401
    {
1402 1403 1404
      int rr, gg, bb;
      float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
      if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1405
        {
1406 1407 1408
          r = rr / fscale;
          g = gg / fscale;
          b = bb / fscale;
1409 1410 1411
        }
    }

1412 1413 1414 1415 1416 1417 1418
  if (r >= 0.0)
    {
      *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
      UNBLOCK_INPUT;
      return 0;
    }

1419 1420 1421 1422 1423
  /* Otherwise, color is expected to be from a list */
  {
    NSEnumerator *lenum, *cenum;
    NSString *name;
    NSColorList *clist;
1424

1425
#ifdef NS_IMPL_GNUSTEP
1426
    /* XXX: who is wrong, the requestor or the implementation? */
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
        == NSOrderedSame)
      nsname = @"highlightColor";
#endif

    lenum = [[NSColorList availableColorLists] objectEnumerator];
    while ( (clist = [lenum nextObject]) && new == nil)
      {
        cenum = [[clist allKeys] objectEnumerator];
        while ( (name = [cenum nextObject]) && new == nil )
          {
            if ([name compare: nsname
                      options: NSCaseInsensitiveSearch] == NSOrderedSame )
              new = [clist colorWithKey: name];
          }
      }
  }

1445
  if (new)
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
  UNBLOCK_INPUT;
  return new ? 0 : 1;
}


static NSColor *
ns_get_color_default (const char *name, NSColor *dflt)
/* --------------------------------------------------------------------------
     Parse a color or use a default value
   -------------------------------------------------------------------------- */
{
  NSColor * col;

  if (ns_get_color (name, &col))
    return dflt;
  else
    return col;
}


int
ns_lisp_to_color (Lisp_Object color, NSColor **col)
/* --------------------------------------------------------------------------
     Convert a Lisp string object to a NS color
   -------------------------------------------------------------------------- */
{
  NSTRACE (ns_lisp_to_color);
1474 1475 1476 1477
  if (STRINGP (color))
    return ns_get_color (SDATA (color), col);
  else if (SYMBOLP (color))
    return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
  return 1;
}


Lisp_Object
ns_color_to_lisp (NSColor *col)
/* --------------------------------------------------------------------------
     Convert a color to a lisp string with the RGB equivalent
   -------------------------------------------------------------------------- */
{
1488
  CGFloat red, green, blue, alpha, gray;
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
  char buf[1024];
  const char *str;
  NSTRACE (ns_color_to_lisp);

  BLOCK_INPUT;
  if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])

      if ((str =[[col colorNameComponent] UTF8String]))
        {
          UNBLOCK_INPUT;
          return build_string ((char *)str);
        }

    [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
        getRed: &red green: &green blue: &blue alpha: &alpha];
  if (red ==green && red ==blue)
    {
      [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
            getWhite: &gray alpha: &alpha];
1508
      snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1509
		lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1510 1511 1512 1513
      UNBLOCK_INPUT;
      return build_string (buf);
    }

1514
  snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1515 1516 1517 1518 1519 1520 1521
            lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));

  UNBLOCK_INPUT;
  return build_string (buf);
}


1522 1523 1524 1525 1526 1527 1528 1529
void
ns_query_color(void *col, XColor *color_def, int setPixel)
/* --------------------------------------------------------------------------
         Get ARGB values out of NSColor col and put them into color_def.
         If setPixel, set the pixel to a concatenated version.
         and set color_def pixel to the resulting index.
   -------------------------------------------------------------------------- */
{
1530
  CGFloat r, g, b, a;
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

  [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
  color_def->red   = r * 65535;
  color_def->green = g * 65535;
  color_def->blue  = b * 65535;

  if (setPixel == YES)
    color_def->pixel
      = ARGB_TO_ULONG((int)(a*255),
		      (int)(r*255), (int)(g*255), (int)(b*255));
}


1544 1545 1546 1547
int
ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
                  char makeIndex)
/* --------------------------------------------------------------------------
1548
         Return 1 if named color found, and set color_def rgb accordingly.
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
         If makeIndex and alloc are nonzero put the color in the color_table,
         and set color_def pixel to the resulting index.
         If makeIndex is zero, set color_def pixel to ARGB.
         Return 0 if not found
   -------------------------------------------------------------------------- */
{
  NSColor *temp;
  int notFound = ns_get_color (name, &temp);

  NSTRACE (ns_defined_color);

  if (notFound)
    return 0;

  if (makeIndex && alloc)
1564
      color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1565

1566
  ns_query_color (temp, color_def, !makeIndex);
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

  return 1;
}


unsigned long
ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
/* --------------------------------------------------------------------------
    return an autoreleased RGB color
   -------------------------------------------------------------------------- */
{
/*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
  if (r < 0.0) r = 0.0;
  else if (r > 1.0) r = 1.0;
  if (g < 0.0) g = 0.0;
  else if (g > 1.0) g = 1.0;
  if (b < 0.0) b = 0.0;
  else if (b > 1.0) b = 1.0;
  if (a < 0.0) a = 0.0;
  else if (a > 1.0) a = 1.0;
  return (unsigned long) ns_index_color(
    [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
}


1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
void
x_set_frame_alpha (struct frame *f)
/* --------------------------------------------------------------------------
     change the entire-frame transparency
   -------------------------------------------------------------------------- */
{
  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
  EmacsView *view = FRAME_NS_VIEW (f);
  double alpha = 1.0;
  double alpha_min = 1.0;

  if (dpyinfo->x_highlight_frame == f)
    alpha = f->alpha[0];
  else
    alpha = f->alpha[1];

  if (FLOATP (Vframe_alpha_lower_limit))
    alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
  else if (INTEGERP (Vframe_alpha_lower_limit))
    alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;

  if (alpha < 0.0)
    return;
  else if (1.0 < alpha)
    alpha = 1.0;
  else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
    alpha = alpha_min;
1619

1620 1621 1622 1623 1624
#ifdef NS_IMPL_COCOA
  [[view window] setAlphaValue: alpha];
#endif
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641

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

    Mouse handling

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


void
x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
/* --------------------------------------------------------------------------
     Programmatically reposition mouse pointer in pixel coordinates
   -------------------------------------------------------------------------- */
{
  NSTRACE (x_set_mouse_pixel_position);
  ns_raise_frame (f);
#if 0
1642
  /* FIXME: this does not work, and what about GNUstep? */
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
#ifdef NS_IMPL_COCOA
  [FRAME_NS_VIEW (f) lockFocus];
  PSsetmouse ((float)pix_x, (float)pix_y);
  [FRAME_NS_VIEW (f) unlockFocus];
#endif
#endif
}


void
x_set_mouse_position (struct frame *f, int h, int v)
/* --------------------------------------------------------------------------
     Programmatically reposition mouse pointer in character coordinates
   -------------------------------------------------------------------------- */
{
  int pix_x, pix_y;

  pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
  pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;

  if (pix_x < 0) pix_x = 0;
  if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);

  if (pix_y < 0) pix_y = 0;
  if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);

  x_set_mouse_pixel_position (f, pix_x, pix_y);
}


static int
note_mouse_movement (struct frame *frame, float x, float y)
/*   ------------------------------------------------------------------------
     Called by EmacsView on mouseMovement events.  Passes on
     to emacs mainstream code if we moved off of a rect of interest
     known as last_mouse_glyph.
     ------------------------------------------------------------------------ */
{
1681
//  NSTRACE (note_mouse_movement);
1682 1683

  XSETFRAME (last_mouse_motion_frame, frame);
1684

1685 1686 1687 1688 1689 1690 1691 1692 1693
  /* Note, this doesn't get called for enter/leave, since we don't have a
     position.  Those are taken care of in the corresponding NSView methods. */

  /* has movement gone beyond last rect we were tracking? */
  if (x < last_mouse_glyph.origin.x ||
      x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
      y < last_mouse_glyph.origin.y ||
      y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
    {
1694
      ns_update_begin(frame);
1695 1696 1697
      frame->mouse_moved = 1;
      note_mouse_highlight (frame, x, y);
      remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1698
      ns_update_end(frame);
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
      return 1;
    }

  return 0;
}


static void
ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
                   enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
                   unsigned long *time)
/* --------------------------------------------------------------------------
    External (hook): inform emacs about mouse position and hit parts.
    If a scrollbar is being dragged, set bar_window, part, x, y, time.
    x & y should be position in the scrollbar (the whole bar, not the handle)
    and length of scrollbar respectively
   -------------------------------------------------------------------------- */
{
  id view;
  NSPoint position;
  int xchar, ychar;
  Lisp_Object frame, tail;
  struct frame *f;
  struct ns_display_info *dpyinfo;

  NSTRACE (ns_mouse_position);

  if (*fp == NULL)
    {
      fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
      return;
    }

  dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);

  BLOCK_INPUT;

  if (last_mouse_scroll_bar != nil && insist == 0)
    {
1738 1739
      /* TODO: we do not use this path at the moment because drag events will
           go directly to the EmacsScroller.  Leaving code in for now. */
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
      [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
                                              x: x y: y];
      if (time) *time = last_mouse_movement_time;
      last_mouse_scroll_bar = nil;
    }
  else
    {
      /* Clear the mouse-moved flag for every frame on this display.  */
      FOR_EACH_FRAME (tail, frame)
        if (FRAME_NS_P (XFRAME (frame))
            && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
          XFRAME (frame)->mouse_moved = 0;

      last_mouse_scroll_bar = nil;
      if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
        f = last_mouse_frame;
      else
1757
        f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1758 1759
                                    : SELECTED_FRAME ();

1760
      if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
        {
          view = FRAME_NS_VIEW (*fp);

          position = [[view window] mouseLocationOutsideOfEventStream];
          position = [view convertPoint: position fromView: nil];
          remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
/*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */

          if (bar_window) *bar_window = Qnil;
          if (part) *part = 0; /*scroll_bar_handle; */

          if (x) XSETINT (*x, lrint (position.x));
          if (y) XSETINT (*y, lrint (position.y));
          if (time) *time = last_mouse_movement_time;
          *fp = f;
        }
    }

  UNBLOCK_INPUT;
}


static void
ns_frame_up_to_date (struct frame *f)
/* --------------------------------------------------------------------------
    External (hook): Fix up mouse highlighting right after a full update.
    Some highlighting was deferred if GC was happening during
    note_mouse_highlight (), while other highlighting was deferred for update.
   -------------------------------------------------------------------------- */
{
  NSTRACE (ns_frame_up_to_date);

  if (FRAME_NS_P (f))
    {
      struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
      if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
      /*&& dpyinfo->mouse_face_mouse_frame*/)
        {
          BLOCK_INPUT;
1800
         ns_update_begin(f);
1801 1802 1803 1804