nsterm.m 228 KB
Newer Older
1
/* NeXT/Open/GNUstep / MacOSX communication module.
2

3 4
Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2014 Free Software
Foundation, Inc.
5 6 7

This file is part of GNU Emacs.

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

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

21
/*
22 23 24 25 26 27 28
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)
*/

29 30
/* This should be the first include, as it may set up #defines affecting
   interpretation of even the system includes. */
Dan Nicolaescu's avatar
Dan Nicolaescu committed
31
#include <config.h>
32

33
#include <fcntl.h>
34
#include <math.h>
35
#include <pthread.h>
36 37
#include <sys/types.h>
#include <time.h>
38
#include <signal.h>
39
#include <unistd.h>
40 41

#include <c-ctype.h>
42
#include <c-strcase.h>
43
#include <ftoastr.h>
44 45 46 47 48 49 50 51 52 53 54 55 56

#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 "termchar.h"
57
#include "menu.h"
58 59
#include "window.h"
#include "keyboard.h"
60
#include "buffer.h"
61 62
#include "font.h"

63 64 65 66
#ifdef NS_IMPL_GNUSTEP
#include "process.h"
#endif

67 68 69 70
#ifdef NS_IMPL_COCOA
#include "macfont.h"
#endif

71 72 73 74 75 76 77 78 79
/* 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

80
/* Detailed tracing. "S" means "size" and "LL" stands for "lower left". */
81
#if 0
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
int term_trace_num = 0;
#define NSTRACE_SIZE(str,size) fprintf (stderr,                         \
                                   "%s:%d: [%d]   " str                 \
                                   " (S:%.0f x %.0f)\n", \
                                   __FILE__, __LINE__, ++term_trace_num,\
                                   size.height,                       \
                                   size.width)
#define NSTRACE_RECT(s,r) fprintf (stderr,                              \
                                   "%s:%d: [%d]   " s                   \
                                   " (LL:%.0f x %.0f -> S:%.0f x %.0f)\n", \
                                   __FILE__, __LINE__, ++term_trace_num,\
                                   r.origin.x,                          \
                                   r.origin.y,                          \
                                   r.size.height,                       \
                                   r.size.width)
#else
#define NSTRACE_SIZE(str,size)
#define NSTRACE_RECT(s,r)
#endif

102
extern NSString *NSMenuDidBeginTrackingNotification;
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
/* ==========================================================================

   NSColor, EmacsColor category.

   ========================================================================== */
@implementation NSColor (EmacsColor)
+ (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
                         blue:(CGFloat)blue alpha:(CGFloat)alpha
{
#ifdef NS_IMPL_COCOA
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  if (ns_use_srgb_colorspace)
      return [NSColor colorWithSRGBRed: red
                                 green: green
                                  blue: blue
                                 alpha: alpha];
#endif
#endif
  return [NSColor colorWithCalibratedRed: red
                                   green: green
                                    blue: blue
                                   alpha: alpha];
}

- (NSColor *)colorUsingDefaultColorSpace
{
#ifdef NS_IMPL_COCOA
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  if (ns_use_srgb_colorspace)
    return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
#endif
#endif
  return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
}

@end

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
/* ==========================================================================

    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,
163
  NSClearLineFunctionKey,       0x0B,
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  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,
188 189 190 191 192 193 194 195 196
  NSF16FunctionKey,             0xCD,
  NSF17FunctionKey,             0xCE,
  NSF18FunctionKey,             0xCF,
  NSF19FunctionKey,             0xD0,
  NSF20FunctionKey,             0xD1,
  NSF21FunctionKey,             0xD2,
  NSF22FunctionKey,             0xD3,
  NSF23FunctionKey,             0xD4,
  NSF24FunctionKey,             0xD5,
197 198 199 200 201 202 203 204 205 206 207

  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,

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  0x41|NSNumericPadKeyMask,	0xAE,  /* KP_Decimal */
  0x43|NSNumericPadKeyMask,	0xAA,  /* KP_Multiply */
  0x45|NSNumericPadKeyMask,	0xAB,  /* KP_Add */
  0x4B|NSNumericPadKeyMask,	0xAF,  /* KP_Divide */
  0x4E|NSNumericPadKeyMask,	0xAD,  /* KP_Subtract */
  0x51|NSNumericPadKeyMask,	0xBD,  /* KP_Equal */
  0x52|NSNumericPadKeyMask,	0xB0,  /* KP_0 */
  0x53|NSNumericPadKeyMask,	0xB1,  /* KP_1 */
  0x54|NSNumericPadKeyMask,	0xB2,  /* KP_2 */
  0x55|NSNumericPadKeyMask,	0xB3,  /* KP_3 */
  0x56|NSNumericPadKeyMask,	0xB4,  /* KP_4 */
  0x57|NSNumericPadKeyMask,	0xB5,  /* KP_5 */
  0x58|NSNumericPadKeyMask,	0xB6,  /* KP_6 */
  0x59|NSNumericPadKeyMask,	0xB7,  /* KP_7 */
  0x5B|NSNumericPadKeyMask,	0xB8,  /* KP_8 */
  0x5C|NSNumericPadKeyMask,	0xB9,  /* KP_9 */
224

225 226 227 228
  0x1B,				0x1B   /* escape */
};

static Lisp_Object Qmodifier_value;
229
Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
230
extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
231

232
static Lisp_Object QUTF8_STRING;
Jan Djärv's avatar
Jan Djärv committed
233
static Lisp_Object Qcocoa, Qgnustep;
234
static Lisp_Object Qfile, Qurl;
235

236 237 238 239 240 241
/* 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;

NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
242
NSString *ns_app_name = @"Emacs";  /* default changed later */
243 244

/* Display variables */
245
struct ns_display_info *x_display_list; /* Chain of existing displays */
246 247 248 249 250
long context_menu_value = 0;

/* display update */
static struct frame *ns_updating_frame;
static NSView *focus_view = NULL;
251
static int ns_window_num = 0;
252
#ifdef NS_IMPL_GNUSTEP
253
static NSRect uRect;
254
#endif
255
static BOOL gsaved = NO;
256
static BOOL ns_fake_keydown = NO;
257
#ifdef NS_IMPL_COCOA
258
static BOOL ns_menu_bar_is_hidden = NO;
259
#endif
260 261 262 263
/*static int debug_lock = 0; */

/* event loop */
static BOOL send_appdefined = YES;
264 265
#define NO_APPDEFINED_DATA (-8)
static int last_appdefined_event_data = NO_APPDEFINED_DATA;
266 267
static NSTimer *timed_entry = 0;
static NSTimer *scroll_repeat_entry = nil;
268 269 270
static fd_set select_readfds, select_writefds;
enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
static int select_nfds = 0, select_valid = 0;
271
static struct timespec select_timeout = { 0, 0 };
272 273 274
static int selfds[2] = { -1, -1 };
static pthread_mutex_t select_mutex;
static int apploopnr = 0;
275 276 277 278 279 280
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;
281
static BOOL ns_do_open_file = NO;
282
static BOOL ns_last_use_native_fullscreen;
283

284 285 286 287 288
/* Non-zero means that a HELP_EVENT has been generated since Emacs
   start.  */

static BOOL any_help_event_p = NO;

289 290 291 292 293 294 295
static struct {
  struct input_event *q;
  int nr, cap;
} hold_event_q = {
  NULL, 0, 0
};

296
#ifdef NS_IMPL_COCOA
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
/*
 * State for pending menu activation:
 * MENU_NONE     Normal state
 * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
 *               run lisp to update the menu.
 * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
 *               will open.
 */
#define MENU_NONE 0
#define MENU_PENDING 1
#define MENU_OPENING 2
static int menu_will_open_state = MENU_NONE;

/* Saved position for menu click.  */
static CGPoint menu_mouse_point;
312
#endif
313

314
/* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
315
#define NS_FUNCTION_KEY_MASK 0x800000
316
#define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
317
#define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
318
#define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
319
#define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
320 321
#define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
#define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
322 323
#define EV_MODIFIERS2(flags)                          \
    (((flags & NSHelpKeyMask) ?           \
324
           hyper_modifier : 0)                        \
325
     | (!EQ (ns_right_alternate_modifier, Qleft) && \
326
        ((flags & NSRightAlternateKeyMask) \
327 328
         == NSRightAlternateKeyMask) ? \
           parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
329
     | ((flags & NSAlternateKeyMask) ?                 \
330
           parse_solitary_modifier (ns_alternate_modifier) : 0)   \
331
     | ((flags & NSShiftKeyMask) ?     \
332
           shift_modifier : 0)                        \
333
     | (!EQ (ns_right_control_modifier, Qleft) && \
334
        ((flags & NSRightControlKeyMask) \
335 336
         == NSRightControlKeyMask) ? \
           parse_solitary_modifier (ns_right_control_modifier) : 0) \
337
     | ((flags & NSControlKeyMask) ?      \
338
           parse_solitary_modifier (ns_control_modifier) : 0)     \
339
     | ((flags & NS_FUNCTION_KEY_MASK) ?  \
340
           parse_solitary_modifier (ns_function_modifier) : 0)    \
341
     | (!EQ (ns_right_command_modifier, Qleft) && \
342
        ((flags & NSRightCommandKeyMask) \
343 344
         == NSRightCommandKeyMask) ? \
           parse_solitary_modifier (ns_right_command_modifier) : 0) \
345
     | ((flags & NSCommandKeyMask) ?      \
346
           parse_solitary_modifier (ns_command_modifier):0))
347
#define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
348 349 350 351

#define EV_UDMODIFIERS(e)                                      \
    ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
     | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
352
     | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
353 354
     | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
     | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
355
     | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
356
     | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
357 358
     | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
     | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
359 360 361

#define EV_BUTTON(e)                                                         \
    ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
362 363
      (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
     [e buttonNumber] - 1)
364 365 366 367 368 369

/* 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.  */
370
#define EV_TRAILER(e)                                                   \
371 372 373 374 375 376 377
  {                                                                     \
    XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
    EV_TRAILER2 (e);                                                    \
  }

#define EV_TRAILER2(e)                                                  \
  {                                                                     \
378 379 380 381 382 383 384
      if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
      if (q_event_ptr)                                                  \
        {                                                               \
          n_emacs_events_pending++;                                     \
          kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
        }                                                               \
      else                                                              \
385
        hold_event (emacs_event);                                       \
386 387 388
      EVENT_INIT (*emacs_event);                                        \
      ns_send_appdefined (-1);                                          \
    }
389

390
/* TODO: get rid of need for these forward declarations */
391 392
static void ns_condemn_scroll_bars (struct frame *f);
static void ns_judge_scroll_bars (struct frame *f);
393
void x_set_frame_alpha (struct frame *f);
394 395 396 397 398 399 400 401


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

    Utilities

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

402 403 404 405 406 407 408 409 410 411 412 413 414
void
ns_init_events (struct input_event* ev)
{
  EVENT_INIT (*ev);
  emacs_event = ev;
}

void
ns_finish_events ()
{
  emacs_event = NULL;
}

415 416 417 418 419 420 421
static void
hold_event (struct input_event *event)
{
  if (hold_event_q.nr == hold_event_q.cap)
    {
      if (hold_event_q.cap == 0) hold_event_q.cap = 10;
      else hold_event_q.cap *= 2;
Paul Eggert's avatar
Paul Eggert committed
422 423
      hold_event_q.q =
        xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
424 425 426
    }

  hold_event_q.q[hold_event_q.nr++] = *event;
427
  /* Make sure ns_read_socket is called, i.e. we have input.  */
428
  raise (SIGIO);
429
  send_appdefined = YES;
430
}
431 432 433 434 435 436 437 438 439

static Lisp_Object
append2 (Lisp_Object list, Lisp_Object item)
/* --------------------------------------------------------------------------
   Utility to append to a list
   -------------------------------------------------------------------------- */
{
  Lisp_Object array[2];
  array[0] = list;
440
  array[1] = list1 (item);
441 442 443 444
  return Fnconc (2, &array[0]);
}


445
const char *
446 447 448
ns_etc_directory (void)
/* If running as a self-contained app bundle, return as a string the
   filename of the etc directory, if present; else nil.  */
449
{
450 451 452 453 454 455 456 457 458 459 460 461
  NSBundle *bundle = [NSBundle mainBundle];
  NSString *resourceDir = [bundle resourcePath];
  NSString *resourcePath;
  NSFileManager *fileManager = [NSFileManager defaultManager];
  BOOL isDir;

  resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
  if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
    {
      if (isDir) return [resourcePath UTF8String];
    }
  return NULL;
462 463
}

464 465 466 467 468 469 470 471 472 473 474 475 476 477

const char *
ns_exec_path (void)
/* If running as a self-contained app bundle, return as a path string
   the filenames of the libexec and bin directories, ie libexec:bin.
   Otherwise, return nil.
   Normally, Emacs does not add its own bin/ directory to the PATH.
   However, a self-contained NS build has a different layout, with
   bin/ and libexec/ subdirectories in the directory that contains
   Emacs.app itself.
   We put libexec first, because init_callproc_1 uses the first
   element to initialize exec-directory.  An alternative would be
   for init_callproc to check for invocation-directory/libexec.
*/
478 479
{
  NSBundle *bundle = [NSBundle mainBundle];
480 481
  NSString *resourceDir = [bundle resourcePath];
  NSString *binDir = [bundle bundlePath];
482 483
  NSString *resourcePath, *resourcePaths;
  NSRange range;
484
  NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
485
  NSFileManager *fileManager = [NSFileManager defaultManager];
486 487
  NSArray *paths;
  NSEnumerator *pathEnum;
488 489 490 491 492
  BOOL isDir;

  range = [resourceDir rangeOfString: @"Contents"];
  if (range.location != NSNotFound)
    {
493
      binDir = [binDir stringByAppendingPathComponent: @"Contents"];
494 495 496 497 498
#ifdef NS_IMPL_COCOA
      binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
#endif
    }

499 500 501 502 503
  paths = [binDir stringsByAppendingPaths:
                [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
  pathEnum = [paths objectEnumerator];
  resourcePaths = @"";

504
  while ((resourcePath = [pathEnum nextObject]))
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    {
      if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
        if (isDir)
          {
            if ([resourcePaths length] > 0)
              resourcePaths
                = [resourcePaths stringByAppendingString: pathSeparator];
            resourcePaths
              = [resourcePaths stringByAppendingString: resourcePath];
          }
    }
  if ([resourcePaths length] > 0) return [resourcePaths UTF8String];

  return NULL;
}


522 523 524
const char *
ns_load_path (void)
/* If running as a self-contained app bundle, return as a path string
525 526
   the filenames of the site-lisp and lisp directories.
   Ie, site-lisp:lisp.  Otherwise, return nil.  */
527 528 529 530
{
  NSBundle *bundle = [NSBundle mainBundle];
  NSString *resourceDir = [bundle resourcePath];
  NSString *resourcePath, *resourcePaths;
531
  NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
532 533
  NSFileManager *fileManager = [NSFileManager defaultManager];
  BOOL isDir;
534 535
  NSArray *paths = [resourceDir stringsByAppendingPaths:
                              [NSArray arrayWithObjects:
536
                                         @"site-lisp", @"lisp", nil]];
537 538
  NSEnumerator *pathEnum = [paths objectEnumerator];
  resourcePaths = @"";
539

540 541 542
  /* Hack to skip site-lisp.  */
  if (no_site_lisp) resourcePath = [pathEnum nextObject];

543
  while ((resourcePath = [pathEnum nextObject]))
544
    {
545 546 547 548 549 550 551 552 553
      if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
        if (isDir)
          {
            if ([resourcePaths length] > 0)
              resourcePaths
                = [resourcePaths stringByAppendingString: pathSeparator];
            resourcePaths
              = [resourcePaths stringByAppendingString: resourcePath];
          }
554
    }
555 556 557
  if ([resourcePaths length] > 0) return [resourcePaths UTF8String];

  return NULL;
558 559 560 561 562 563 564 565
}

static void
ns_timeout (int usecs)
/* --------------------------------------------------------------------------
     Blocking timer utility used by ns_ring_bell
   -------------------------------------------------------------------------- */
{
566 567
  struct timespec wakeup = timespec_add (current_timespec (),
					 make_timespec (0, usecs * 1000));
568 569 570 571

  /* Keep waiting until past the time wakeup.  */
  while (1)
    {
572 573
      struct timespec timeout, now = current_timespec ();
      if (timespec_cmp (wakeup, now) <= 0)
574
	break;
575
      timeout = timespec_sub (wakeup, now);
576 577

      /* Try to wait that long--but we might wake up sooner.  */
578
      pselect (0, NULL, NULL, NULL, &timeout, NULL);
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
    }
}


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 *
604
ns_alloc_autorelease_pool (void)
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
/* --------------------------------------------------------------------------
     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

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

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
//
// Window constraining
// -------------------
//
// To ensure that the windows are not placed under the menu bar, they
// are typically moved by the call-back constrainFrameRect. However,
// by overriding it, it's possible to inhibit this, leaving the window
// in it's original position.
//
// It's possible to hide the menu bar. However, technically, it's only
// possible to hide it when the application is active. To ensure that
// this work properly, the menu bar and window constraining are
// deferred until the application becomes active.
//
// Even though it's not possible to manually move a window above the
// top of the screen, it is allowed if it's done programmatically,
// when the menu is hidden. This allows the editable area to cover the
// full screen height.
//
// Test cases
// ----------
//
// Use the following extra files:
//
//    init.el:
//       ;; Hide menu and place frame slightly above the top of the screen.
//       (setq ns-auto-hide-menu-bar t)
//       (set-frame-position (selected-frame) 0 -20)
//
// Test 1:
//
//    emacs -Q -l init.el
//
//    Result: No menu bar, and the title bar should be above the screen.
//
// Test 2:
//
//    emacs -Q
//
//    Result: Menu bar visible, frame placed immediately below the menu.
//

static void
ns_constrain_all_frames (void)
{
  Lisp_Object tail, frame;

  FOR_EACH_FRAME (tail, frame)
    {
      struct frame *f = XFRAME (frame);
      if (FRAME_NS_P (f))
        {
          NSView *view = FRAME_NS_VIEW (f);
          /* This no-op will trigger the default window placing
Paul Eggert's avatar
Paul Eggert committed
684
           * constraint system. */
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
          [[view window] setFrameOrigin:[[view window] frame].origin];
        }
    }
}


/* True, if the menu bar should be hidden.  */

static BOOL
ns_menu_bar_should_be_hidden (void)
{
  return !NILP (ns_auto_hide_menu_bar)
    && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
}


/* Show or hide the menu bar, based on user setting.  */

static void
ns_update_auto_hide_menu_bar (void)
{
706
#ifdef NS_IMPL_COCOA
707
  block_input ();
708 709 710

  NSTRACE (ns_update_auto_hide_menu_bar);

711
  if (NSApp != nil && [NSApp isActive])
712 713 714 715 716 717 718 719
    {
      // Note, "setPresentationOptions" triggers an error unless the
      // application is active.
      BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();

      if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
        {
          NSApplicationPresentationOptions options
720
            = NSApplicationPresentationDefault;
721 722

          if (menu_bar_should_be_hidden)
723 724
            options |= NSApplicationPresentationAutoHideMenuBar
              | NSApplicationPresentationAutoHideDock;
725 726 727 728 729 730 731 732 733 734 735 736

          [NSApp setPresentationOptions: options];

          ns_menu_bar_is_hidden = menu_bar_should_be_hidden;

          if (!ns_menu_bar_is_hidden)
            {
              ns_constrain_all_frames ();
            }
        }
    }

737
  unblock_input ();
738
#endif
739 740 741
}


742 743 744 745
static void
ns_update_begin (struct frame *f)
/* --------------------------------------------------------------------------
   Prepare for a grouped sequence of drawing calls
746
   external (RIF) call; whole frame, called before update_window_begin
747 748
   -------------------------------------------------------------------------- */
{
749
  EmacsView *view = FRAME_NS_VIEW (f);
750 751
  NSTRACE (ns_update_begin);

752 753
  ns_update_auto_hide_menu_bar ();

754 755 756 757 758 759 760 761 762 763 764
#ifdef NS_IMPL_COCOA
  if ([view isFullscreen] && [view fsIsNative])
  {
    // Fix reappearing tool bar in fullscreen for OSX 10.7
    BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
    NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
    if (! tbar_visible != ! [toolbar isVisible])
      [toolbar setVisible: tbar_visible];
  }
#endif

765 766 767
  ns_updating_frame = f;
  [view lockFocus];

768 769 770 771
  /* drawRect may have been called for say the minibuffer, and then clip path
     is for the minibuffer.  But the display engine may draw more because
     we have set the frame as garbaged.  So reset clip path to the whole
     view.  */
772 773 774 775
#ifdef NS_IMPL_COCOA
  {
    NSBezierPath *bp;
    NSRect r = [view frame];
776 777 778 779 780 781 782 783 784 785 786 787
    NSRect cr = [[view window] frame];
    /* If a large frame size is set, r may be larger than the window frame
       before constrained.  In that case don't change the clip path, as we
       will clear in to the tool bar and title bar.  */
    if (r.size.height
        + FRAME_NS_TITLEBAR_HEIGHT (f)
        + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
      {
        bp = [[NSBezierPath bezierPathWithRect: r] retain];
        [bp setClip];
        [bp release];
      }
788 789
  }
#endif
790

791 792 793 794 795 796 797 798 799 800
#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
801
   external (RIF) call; for one window, called after update_begin
802 803 804
   -------------------------------------------------------------------------- */
{
  struct frame *f = XFRAME (WINDOW_FRAME (w));
805 806
  Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);

807
  NSTRACE (ns_update_window_begin);
808
  w->output_cursor = w->cursor;
809

810
  block_input ();
811

812
  if (f == hlinfo->mouse_face_mouse_frame)
813 814
    {
      /* Don't do highlighting for mouse motion during the update.  */
815
      hlinfo->mouse_face_defer = 1;
816 817 818 819

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

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

825
  unblock_input ();
826 827 828 829
}


static void
830 831
ns_update_window_end (struct window *w, bool cursor_on_p,
                      bool mouse_face_overwritten_p)
832 833
/* --------------------------------------------------------------------------
   Finished a grouped sequence of drawing calls
834
   external (RIF) call; for one window called before update_end
835 836 837 838 839
   -------------------------------------------------------------------------- */
{
  /* note: this fn is nearly identical in all terms */
  if (!w->pseudo_window_p)
    {
840
      block_input ();
841 842 843

      if (cursor_on_p)
	display_and_set_cursor (w, 1,
844 845
				w->output_cursor.hpos, w->output_cursor.vpos,
				w->output_cursor.x, w->output_cursor.y);
846 847

      if (draw_window_fringes (w, 1))
848 849 850 851 852 853
	{
	  if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
	    x_draw_right_divider (w);
	  else
	    x_draw_vertical_border (w);
	}
854

855
      unblock_input ();
856 857 858 859 860
    }

  /* If a row with mouse-face was overwritten, arrange for
     frame_up_to_date to redisplay the mouse highlight.  */
  if (mouse_face_overwritten_p)
861
    reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
862 863 864 865 866 867 868 869 870

  NSTRACE (update_window_end);
}


static void
ns_update_end (struct frame *f)
/* --------------------------------------------------------------------------
   Finished a grouped sequence of drawing calls
871
   external (RIF) call; for whole frame, called after update_window_end
872 873
   -------------------------------------------------------------------------- */
{
874
  EmacsView *view = FRAME_NS_VIEW (f);
875

876
/*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
877
  MOUSE_HL_INFO (f)->mouse_face_defer = 0;
878

879
  block_input ();
880 881 882 883

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

884
  unblock_input ();
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  ns_updating_frame = NULL;
  NSTRACE (ns_update_end);
}

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.
   -------------------------------------------------------------------------- */
{
900
//  NSTRACE (ns_focus);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
/* 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)
            [view lockFocus];
          focus_view = view;
/*if (view) debug_lock++; */
        }
    }

925
  /* clipping */
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
  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
   -------------------------------------------------------------------------- */
{
944
//  NSTRACE (ns_unfocus);
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

  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
966 967
ns_clip_to_row (struct window *w, struct glyph_row *row,
		enum glyph_row_area area, BOOL gc)
968
/* --------------------------------------------------------------------------
969
     Internal (but parallels other terms): Focus drawing on given row
970 971 972 973 974 975 976 977
   -------------------------------------------------------------------------- */
{
  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);

978
  clip_rect.origin.x = window_x;
979 980
  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);
981
  clip_rect.size.width = window_width;
982 983 984 985 986 987 988
  clip_rect.size.height = row->visible_height;

  ns_focus (f, &clip_rect, 1);
}


static void
989
ns_ring_bell (struct frame *f)
990 991 992 993 994 995 996 997 998 999 1000
/* --------------------------------------------------------------------------
     "Beep" routine
   -------------------------------------------------------------------------- */
{
  NSTRACE (ns_ring_bell);
  if (visible_bell)
    {
      NSAutoreleasePool *pool;
      struct frame *frame = SELECTED_FRAME ();
      NSView *view;

1001
      block_input ();
1002 1003 1004 1005 1006
      pool = [[NSAutoreleasePool alloc] init];

      view = FRAME_NS_VIEW (frame);
      if (view != nil)
        {
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
          NSRect r, surr;
          NSPoint dim = NSMakePoint (128, 128);

          r = [view bounds];
          r.origin.x += (r.size.width - dim.x) / 2;
          r.origin.y += (r.size.height - dim.y) / 2;
          r.size.width = dim.x;
          r.size.height = dim.y;
          surr = NSInsetRect (r, -2, -2);
          ns_focus (frame, &surr, 1);
          [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
          [ns_lookup_indexed_color (NS_FACE_FOREGROUND
                                      (FRAME_DEFAULT_FACE (frame)), frame) set];
          NSRectFill (r);
1021 1022
          [[view window] flushWindow];
          ns_timeout (150000);
1023
          [[view window] restoreCachedImage];
1024 1025 1026 1027
          [[view window] flushWindow];
          ns_unfocus (frame);
        }
      [pool release];
1028
      unblock_input ();
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    }
  else
    {
      NSBeep ();
    }
}

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

    Frame / window manager related functions

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


static void
ns_raise_frame (struct frame *f)
/* --------------------------------------------------------------------------
     Bring window to foreground and make it active
   -------------------------------------------------------------------------- */
{
1049 1050 1051
  NSView *view;
  check_window_system (f);
  view = FRAME_NS_VIEW (f);
1052
  block_input ();
1053
  if (FRAME_VISIBLE_P (f))
1054
    [[view window] makeKeyAndOrderFront: NSApp];
1055
  unblock_input ();
1056 1057 1058 1059 1060 1061 1062 1063 1064
}


static void
ns_lower_frame (struct frame *f)
/* --------------------------------------------------------------------------
     Send window to back
   -------------------------------------------------------------------------- */
{
1065 1066 1067
  NSView *view;
  check_window_system (f);
  view = FRAME_NS_VIEW (f);
1068
  block_input ();
1069
  [[view window] orderBack: NSApp];
1070
  unblock_input ();
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
}


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
   -------------------------------------------------------------------------- */
{
1095
  struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1096
  struct frame *old_highlight = dpyinfo->x_highlight_frame;
1097 1098

  NSTRACE (ns_frame_rehighlight);
1099
  if (dpyinfo->x_focus_frame)
1100
    {
1101 1102 1103 1104 1105
      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))
1106
        {
1107
          fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1108
          dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1109 1110 1111
        }
    }
  else
1112
      dpyinfo->x_highlight_frame = 0;
1113

1114 1115
  if (dpyinfo->x_highlight_frame &&
         dpyinfo->x_highlight_frame != old_highlight)
1116 1117
    {
      if (old_highlight)
1118
	{
1119
          x_update_cursor (old_highlight, 1);
1120 1121
	  x_set_frame_alpha (old_highlight);
	}
1122
      if (dpyinfo->x_highlight_frame)
1123
	{
1124
          x_update_cursor (dpyinfo->x_highlight_frame, 1);
1125 1126
          x_set_frame_alpha (dpyinfo->x_highlight_frame);
	}
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    }
}


void
x_make_frame_visible (struct frame *f)
/* --------------------------------------------------------------------------
     External: Show the window (X11 semantics)
   -------------------------------------------------------------------------- */
{
  NSTRACE (x_make_frame_visible);
1138
  /* XXX: at some points in past this was not needed, as the only place that
1139 1140 1141
     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))
1142
    {
1143
      EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1144 1145

      SET_FRAME_VISIBLE (f, 1);
1146
      ns_raise_frame (f);
1147 1148 1149

      /* Making a new frame from a fullscreen frame will make the new frame
         fullscreen also.  So skip handleFS as this will print an error.  */
1150 1151
      if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
          && [view isFullscreen])
1152
        return;
1153

1154 1155 1156 1157 1158 1159
      if (f->want_fullscreen != FULLSCREEN_NONE)
        {
          block_input ();
          [view handleFS];
          unblock_input ();
        }
1160
    }
1161 1162 1163 1164 1165 1166 1167 1168 1169
}


void
x_make_frame_invisible (struct frame *f)
/* --------------------------------------------------------------------------
     External: Hide the window (X11 semantics)
   -------------------------------------------------------------------------- */
{
1170
  NSView *view;
1171
  NSTRACE (x_make_frame_invisible);
1172 1173
  check_window_system (f);
  view = FRAME_NS_VIEW (f);
1174
  [[view window] orderOut: NSApp];
1175 1176
  SET_FRAME_VISIBLE (f, 0);
  SET_FRAME_ICONIFIED (f, 0);
1177 1178 1179 1180 1181 1182 1183 1184 1185
}


void
x_iconify_frame (struct frame *f)
/* --------------------------------------------------------------------------
     External: Iconify window
   -------------------------------------------------------------------------- */
{
1186 1187 1188
  NSView *view;
  struct ns_display_info *dpyinfo;

1189
  NSTRACE (x_iconify_frame);
1190 1191
  check_window_system (f);
  view = FRAME_NS_VIEW (f);
1192
  dpyinfo = FRAME_DISPLAY_INFO (f);
1193

1194 1195
  if (dpyinfo->x_highlight_frame == f)
    dpyinfo->x_highlight_frame = 0;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

  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];
}

1212
/* Free X resources of frame F.  */
1213 1214

void
1215
x_free_frame_resources (struct frame *f)
1216
{
1217 1218 1219 1220
  NSView *view;
  struct ns_display_info *dpyinfo;
  Mouse_HLInfo *hlinfo;

1221
  NSTRACE (x_free_frame_resources);
1222 1223
  check_window_system (f);
  view = FRAME_NS_VIEW (f);
1224
  dpyinfo = FRAME_DISPLAY_INFO (f);
1225
  hlinfo = MOUSE_HL_INFO (f);
1226 1227 1228

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

1229
  block_input ();
1230 1231

  free_frame_menubar (f);
1232
  free_frame_faces (f);
1233

1234 1235 1236 1237
  if (f == dpyinfo->x_focus_frame)
    dpyinfo->x_focus_frame = 0;
  if (f == dpyinfo->x_highlight_frame)
    dpyinfo->x_highlight_frame = 0;
1238
  if (f == hlinfo->mouse_face_mouse_frame)
1239
    reset_mouse_highlight (hlinfo);
1240

1241