* admin/make-tarball.txt: Copyedits.
[emacs.git] / src / nsterm.m
blob08b8e3a90760fb8cc57d18845b74d1c2b167fdb6
1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2015 Free Software
4 Foundation, Inc.
6 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 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 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/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <signal.h>
39 #include <unistd.h>
41 #include <c-ctype.h>
42 #include <c-strcase.h>
43 #include <ftoastr.h>
45 #include "lisp.h"
46 #include "blockinput.h"
47 #include "sysselect.h"
48 #include "nsterm.h"
49 #include "systime.h"
50 #include "character.h"
51 #include "fontset.h"
52 #include "composite.h"
53 #include "ccl.h"
55 #include "termhooks.h"
56 #include "termchar.h"
58 #include "window.h"
59 #include "keyboard.h"
60 #include "buffer.h"
61 #include "font.h"
63 #ifdef NS_IMPL_GNUSTEP
64 #include "process.h"
65 #endif
67 #ifdef NS_IMPL_COCOA
68 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
69 #include "macfont.h"
70 #endif
71 #endif
73 /* call tracing */
74 #if 0
75 int term_trace_num = 0;
76 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
77                                 __FILE__, __LINE__, ++term_trace_num)
78 #else
79 #define NSTRACE(x)
80 #endif
82 /* Detailed tracing. "S" means "size" and "LL" stands for "lower left". */
83 #if 0
84 int term_trace_num = 0;
85 #define NSTRACE_SIZE(str,size) fprintf (stderr,                         \
86                                    "%s:%d: [%d]   " str                 \
87                                    " (S:%.0f x %.0f)\n", \
88                                    __FILE__, __LINE__, ++term_trace_num,\
89                                    size.height,                       \
90                                    size.width)
91 #define NSTRACE_RECT(s,r) fprintf (stderr,                              \
92                                    "%s:%d: [%d]   " s                   \
93                                    " (LL:%.0f x %.0f -> S:%.0f x %.0f)\n", \
94                                    __FILE__, __LINE__, ++term_trace_num,\
95                                    r.origin.x,                          \
96                                    r.origin.y,                          \
97                                    r.size.height,                       \
98                                    r.size.width)
99 #else
100 #define NSTRACE_SIZE(str,size)
101 #define NSTRACE_RECT(s,r)
102 #endif
104 extern NSString *NSMenuDidBeginTrackingNotification;
106 /* ==========================================================================
108    NSColor, EmacsColor category.
110    ========================================================================== */
111 @implementation NSColor (EmacsColor)
112 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
113                          blue:(CGFloat)blue alpha:(CGFloat)alpha
115 #ifdef NS_IMPL_COCOA
116 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
117   if (ns_use_srgb_colorspace)
118       return [NSColor colorWithSRGBRed: red
119                                  green: green
120                                   blue: blue
121                                  alpha: alpha];
122 #endif
123 #endif
124   return [NSColor colorWithCalibratedRed: red
125                                    green: green
126                                     blue: blue
127                                    alpha: alpha];
130 - (NSColor *)colorUsingDefaultColorSpace
132 #ifdef NS_IMPL_COCOA
133 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
134   if (ns_use_srgb_colorspace)
135     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
136 #endif
137 #endif
138   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
141 @end
143 /* ==========================================================================
145     Local declarations
147    ========================================================================== */
149 /* Convert a symbol indexed with an NSxxx value to a value as defined
150    in keyboard.c (lispy_function_key). I hope this is a correct way
151    of doing things... */
152 static unsigned convert_ns_to_X_keysym[] =
154   NSHomeFunctionKey,            0x50,
155   NSLeftArrowFunctionKey,       0x51,
156   NSUpArrowFunctionKey,         0x52,
157   NSRightArrowFunctionKey,      0x53,
158   NSDownArrowFunctionKey,       0x54,
159   NSPageUpFunctionKey,          0x55,
160   NSPageDownFunctionKey,        0x56,
161   NSEndFunctionKey,             0x57,
162   NSBeginFunctionKey,           0x58,
163   NSSelectFunctionKey,          0x60,
164   NSPrintFunctionKey,           0x61,
165   NSClearLineFunctionKey,       0x0B,
166   NSExecuteFunctionKey,         0x62,
167   NSInsertFunctionKey,          0x63,
168   NSUndoFunctionKey,            0x65,
169   NSRedoFunctionKey,            0x66,
170   NSMenuFunctionKey,            0x67,
171   NSFindFunctionKey,            0x68,
172   NSHelpFunctionKey,            0x6A,
173   NSBreakFunctionKey,           0x6B,
175   NSF1FunctionKey,              0xBE,
176   NSF2FunctionKey,              0xBF,
177   NSF3FunctionKey,              0xC0,
178   NSF4FunctionKey,              0xC1,
179   NSF5FunctionKey,              0xC2,
180   NSF6FunctionKey,              0xC3,
181   NSF7FunctionKey,              0xC4,
182   NSF8FunctionKey,              0xC5,
183   NSF9FunctionKey,              0xC6,
184   NSF10FunctionKey,             0xC7,
185   NSF11FunctionKey,             0xC8,
186   NSF12FunctionKey,             0xC9,
187   NSF13FunctionKey,             0xCA,
188   NSF14FunctionKey,             0xCB,
189   NSF15FunctionKey,             0xCC,
190   NSF16FunctionKey,             0xCD,
191   NSF17FunctionKey,             0xCE,
192   NSF18FunctionKey,             0xCF,
193   NSF19FunctionKey,             0xD0,
194   NSF20FunctionKey,             0xD1,
195   NSF21FunctionKey,             0xD2,
196   NSF22FunctionKey,             0xD3,
197   NSF23FunctionKey,             0xD4,
198   NSF24FunctionKey,             0xD5,
200   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
201   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
202   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
204   NSTabCharacter,               0x09,
205   0x19,                         0x09,  /* left tab->regular since pass shift */
206   NSCarriageReturnCharacter,    0x0D,
207   NSNewlineCharacter,           0x0D,
208   NSEnterCharacter,             0x8D,
210   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
211   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
212   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
213   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
214   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
215   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
216   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
217   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
218   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
219   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
220   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
221   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
222   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
223   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
224   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
225   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
227   0x1B,                         0x1B   /* escape */
230 static Lisp_Object Qmodifier_value;
231 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
232 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
234 static Lisp_Object QUTF8_STRING;
235 static Lisp_Object Qcocoa, Qgnustep;
236 static Lisp_Object Qfile, Qurl;
238 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
239    the maximum font size to NOT antialias.  On GNUstep there is currently
240    no way to control this behavior. */
241 float ns_antialias_threshold;
243 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
244 NSString *ns_app_name = @"Emacs";  /* default changed later */
246 /* Display variables */
247 struct ns_display_info *x_display_list; /* Chain of existing displays */
248 long context_menu_value = 0;
250 /* display update */
251 static struct frame *ns_updating_frame;
252 static NSView *focus_view = NULL;
253 static int ns_window_num = 0;
254 #ifdef NS_IMPL_GNUSTEP
255 static NSRect uRect;
256 #endif
257 static BOOL gsaved = NO;
258 static BOOL ns_fake_keydown = NO;
259 #ifdef NS_IMPL_COCOA
260 static BOOL ns_menu_bar_is_hidden = NO;
261 #endif
262 /*static int debug_lock = 0; */
264 /* event loop */
265 static BOOL send_appdefined = YES;
266 #define NO_APPDEFINED_DATA (-8)
267 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
268 static NSTimer *timed_entry = 0;
269 static NSTimer *scroll_repeat_entry = nil;
270 static fd_set select_readfds, select_writefds;
271 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
272 static int select_nfds = 0, select_valid = 0;
273 static struct timespec select_timeout = { 0, 0 };
274 static int selfds[2] = { -1, -1 };
275 static pthread_mutex_t select_mutex;
276 static int apploopnr = 0;
277 static NSAutoreleasePool *outerpool;
278 static struct input_event *emacs_event = NULL;
279 static struct input_event *q_event_ptr = NULL;
280 static int n_emacs_events_pending = 0;
281 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
282   *ns_pending_service_args;
283 static BOOL ns_do_open_file = NO;
284 static BOOL ns_last_use_native_fullscreen;
286 static struct {
287   struct input_event *q;
288   int nr, cap;
289 } hold_event_q = {
290   NULL, 0, 0
293 static NSString *represented_filename = nil;
294 static struct frame *represented_frame = 0;
296 #ifdef NS_IMPL_COCOA
298  * State for pending menu activation:
299  * MENU_NONE     Normal state
300  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
301  *               run lisp to update the menu.
302  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
303  *               will open.
304  */
305 #define MENU_NONE 0
306 #define MENU_PENDING 1
307 #define MENU_OPENING 2
308 static int menu_will_open_state = MENU_NONE;
310 /* Saved position for menu click.  */
311 static CGPoint menu_mouse_point;
312 #endif
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 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
321 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
322 #define EV_MODIFIERS2(flags)                          \
323     (((flags & NSHelpKeyMask) ?           \
324            hyper_modifier : 0)                        \
325      | (!EQ (ns_right_alternate_modifier, Qleft) && \
326         ((flags & NSRightAlternateKeyMask) \
327          == NSRightAlternateKeyMask) ? \
328            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          == NSRightControlKeyMask) ? \
336            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          == NSRightCommandKeyMask) ? \
344            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])
349 #define EV_UDMODIFIERS(e)                                      \
350     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
351      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
352      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
353      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
354      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
355      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
356      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
357      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
358      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
360 #define EV_BUTTON(e)                                                         \
361     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
362       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
363      [e buttonNumber] - 1)
365 /* Convert the time field to a timestamp in milliseconds. */
366 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
368 /* This is a piece of code which is common to all the event handling
369    methods.  Maybe it should even be a function.  */
370 #define EV_TRAILER(e)                                                   \
371   {                                                                     \
372     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
373     EV_TRAILER2 (e);                                                    \
374   }
376 #define EV_TRAILER2(e)                                                  \
377   {                                                                     \
378       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
379       if (q_event_ptr)                                                  \
380         {                                                               \
381           Lisp_Object tem = Vinhibit_quit;                              \
382           Vinhibit_quit = Qt;                                           \
383           n_emacs_events_pending++;                                     \
384           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
385           Vinhibit_quit = tem;                                          \
386         }                                                               \
387       else                                                              \
388         hold_event (emacs_event);                                       \
389       EVENT_INIT (*emacs_event);                                        \
390       ns_send_appdefined (-1);                                          \
391     }
393 /* TODO: get rid of need for these forward declarations */
394 static void ns_condemn_scroll_bars (struct frame *f);
395 static void ns_judge_scroll_bars (struct frame *f);
396 void x_set_frame_alpha (struct frame *f);
399 /* ==========================================================================
401     Utilities
403    ========================================================================== */
405 void
406 ns_set_represented_filename (NSString* fstr, struct frame *f)
408   represented_filename = [fstr retain];
409   represented_frame = f;
413 static void
414 hold_event (struct input_event *event)
416   if (hold_event_q.nr == hold_event_q.cap)
417     {
418       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
419       else hold_event_q.cap *= 2;
420       hold_event_q.q =
421         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
422     }
424   hold_event_q.q[hold_event_q.nr++] = *event;
425   /* Make sure ns_read_socket is called, i.e. we have input.  */
426   raise (SIGIO);
427   send_appdefined = YES;
430 static Lisp_Object
431 append2 (Lisp_Object list, Lisp_Object item)
432 /* --------------------------------------------------------------------------
433    Utility to append to a list
434    -------------------------------------------------------------------------- */
436   Lisp_Object array[2];
437   array[0] = list;
438   array[1] = list1 (item);
439   return Fnconc (2, &array[0]);
443 const char *
444 ns_etc_directory (void)
445 /* If running as a self-contained app bundle, return as a string the
446    filename of the etc directory, if present; else nil.  */
448   NSBundle *bundle = [NSBundle mainBundle];
449   NSString *resourceDir = [bundle resourcePath];
450   NSString *resourcePath;
451   NSFileManager *fileManager = [NSFileManager defaultManager];
452   BOOL isDir;
454   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
455   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
456     {
457       if (isDir) return [resourcePath UTF8String];
458     }
459   return NULL;
463 const char *
464 ns_exec_path (void)
465 /* If running as a self-contained app bundle, return as a path string
466    the filenames of the libexec and bin directories, ie libexec:bin.
467    Otherwise, return nil.
468    Normally, Emacs does not add its own bin/ directory to the PATH.
469    However, a self-contained NS build has a different layout, with
470    bin/ and libexec/ subdirectories in the directory that contains
471    Emacs.app itself.
472    We put libexec first, because init_callproc_1 uses the first
473    element to initialize exec-directory.  An alternative would be
474    for init_callproc to check for invocation-directory/libexec.
477   NSBundle *bundle = [NSBundle mainBundle];
478   NSString *resourceDir = [bundle resourcePath];
479   NSString *binDir = [bundle bundlePath];
480   NSString *resourcePath, *resourcePaths;
481   NSRange range;
482   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
483   NSFileManager *fileManager = [NSFileManager defaultManager];
484   NSArray *paths;
485   NSEnumerator *pathEnum;
486   BOOL isDir;
488   range = [resourceDir rangeOfString: @"Contents"];
489   if (range.location != NSNotFound)
490     {
491       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
492 #ifdef NS_IMPL_COCOA
493       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
494 #endif
495     }
497   paths = [binDir stringsByAppendingPaths:
498                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
499   pathEnum = [paths objectEnumerator];
500   resourcePaths = @"";
502   while ((resourcePath = [pathEnum nextObject]))
503     {
504       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
505         if (isDir)
506           {
507             if ([resourcePaths length] > 0)
508               resourcePaths
509                 = [resourcePaths stringByAppendingString: pathSeparator];
510             resourcePaths
511               = [resourcePaths stringByAppendingString: resourcePath];
512           }
513     }
514   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
516   return NULL;
520 const char *
521 ns_load_path (void)
522 /* If running as a self-contained app bundle, return as a path string
523    the filenames of the site-lisp and lisp directories.
524    Ie, site-lisp:lisp.  Otherwise, return nil.  */
526   NSBundle *bundle = [NSBundle mainBundle];
527   NSString *resourceDir = [bundle resourcePath];
528   NSString *resourcePath, *resourcePaths;
529   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
530   NSFileManager *fileManager = [NSFileManager defaultManager];
531   BOOL isDir;
532   NSArray *paths = [resourceDir stringsByAppendingPaths:
533                               [NSArray arrayWithObjects:
534                                          @"site-lisp", @"lisp", nil]];
535   NSEnumerator *pathEnum = [paths objectEnumerator];
536   resourcePaths = @"";
538   /* Hack to skip site-lisp.  */
539   if (no_site_lisp) resourcePath = [pathEnum nextObject];
541   while ((resourcePath = [pathEnum nextObject]))
542     {
543       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
544         if (isDir)
545           {
546             if ([resourcePaths length] > 0)
547               resourcePaths
548                 = [resourcePaths stringByAppendingString: pathSeparator];
549             resourcePaths
550               = [resourcePaths stringByAppendingString: resourcePath];
551           }
552     }
553   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
555   return NULL;
558 static void
559 ns_timeout (int usecs)
560 /* --------------------------------------------------------------------------
561      Blocking timer utility used by ns_ring_bell
562    -------------------------------------------------------------------------- */
564   struct timespec wakeup = timespec_add (current_timespec (),
565                                          make_timespec (0, usecs * 1000));
567   /* Keep waiting until past the time wakeup.  */
568   while (1)
569     {
570       struct timespec timeout, now = current_timespec ();
571       if (timespec_cmp (wakeup, now) <= 0)
572         break;
573       timeout = timespec_sub (wakeup, now);
575       /* Try to wait that long--but we might wake up sooner.  */
576       pselect (0, NULL, NULL, NULL, &timeout, NULL);
577     }
581 void
582 ns_release_object (void *obj)
583 /* --------------------------------------------------------------------------
584     Release an object (callable from C)
585    -------------------------------------------------------------------------- */
587     [(id)obj release];
591 void
592 ns_retain_object (void *obj)
593 /* --------------------------------------------------------------------------
594     Retain an object (callable from C)
595    -------------------------------------------------------------------------- */
597     [(id)obj retain];
601 void *
602 ns_alloc_autorelease_pool (void)
603 /* --------------------------------------------------------------------------
604      Allocate a pool for temporary objects (callable from C)
605    -------------------------------------------------------------------------- */
607   return [[NSAutoreleasePool alloc] init];
611 void
612 ns_release_autorelease_pool (void *pool)
613 /* --------------------------------------------------------------------------
614      Free a pool and temporary objects it refers to (callable from C)
615    -------------------------------------------------------------------------- */
617   ns_release_object (pool);
622 /* ==========================================================================
624     Focus (clipping) and screen update
626    ========================================================================== */
629 // Window constraining
630 // -------------------
632 // To ensure that the windows are not placed under the menu bar, they
633 // are typically moved by the call-back constrainFrameRect. However,
634 // by overriding it, it's possible to inhibit this, leaving the window
635 // in it's original position.
637 // It's possible to hide the menu bar. However, technically, it's only
638 // possible to hide it when the application is active. To ensure that
639 // this work properly, the menu bar and window constraining are
640 // deferred until the application becomes active.
642 // Even though it's not possible to manually move a window above the
643 // top of the screen, it is allowed if it's done programmatically,
644 // when the menu is hidden. This allows the editable area to cover the
645 // full screen height.
647 // Test cases
648 // ----------
650 // Use the following extra files:
652 //    init.el:
653 //       ;; Hide menu and place frame slightly above the top of the screen.
654 //       (setq ns-auto-hide-menu-bar t)
655 //       (set-frame-position (selected-frame) 0 -20)
657 // Test 1:
659 //    emacs -Q -l init.el
661 //    Result: No menu bar, and the title bar should be above the screen.
663 // Test 2:
665 //    emacs -Q
667 //    Result: Menu bar visible, frame placed immediately below the menu.
670 static void
671 ns_constrain_all_frames (void)
673   Lisp_Object tail, frame;
675   FOR_EACH_FRAME (tail, frame)
676     {
677       struct frame *f = XFRAME (frame);
678       if (FRAME_NS_P (f))
679         {
680           NSView *view = FRAME_NS_VIEW (f);
681           /* This no-op will trigger the default window placing
682            * constraint system. */
683           [[view window] setFrameOrigin:[[view window] frame].origin];
684         }
685     }
689 /* True, if the menu bar should be hidden.  */
691 static BOOL
692 ns_menu_bar_should_be_hidden (void)
694   return !NILP (ns_auto_hide_menu_bar)
695     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
699 /* Show or hide the menu bar, based on user setting.  */
701 static void
702 ns_update_auto_hide_menu_bar (void)
704 #ifdef NS_IMPL_COCOA
705 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
706   block_input ();
708   NSTRACE (ns_update_auto_hide_menu_bar);
710   if (NSApp != nil && [NSApp isActive])
711     {
712       // Note, "setPresentationOptions" triggers an error unless the
713       // application is active.
714       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
716       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
717         {
718           NSApplicationPresentationOptions options
719             = NSApplicationPresentationDefault;
721           if (menu_bar_should_be_hidden)
722             options |= NSApplicationPresentationAutoHideMenuBar
723               | NSApplicationPresentationAutoHideDock;
725           [NSApp setPresentationOptions: options];
727           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
729           if (!ns_menu_bar_is_hidden)
730             {
731               ns_constrain_all_frames ();
732             }
733         }
734     }
736   unblock_input ();
737 #endif
738 #endif
742 static void
743 ns_update_begin (struct frame *f)
744 /* --------------------------------------------------------------------------
745    Prepare for a grouped sequence of drawing calls
746    external (RIF) call; whole frame, called before update_window_begin
747    -------------------------------------------------------------------------- */
749   EmacsView *view = FRAME_NS_VIEW (f);
750   NSTRACE (ns_update_begin);
752   ns_update_auto_hide_menu_bar ();
754 #ifdef NS_IMPL_COCOA
755   if ([view isFullscreen] && [view fsIsNative])
756   {
757     // Fix reappearing tool bar in fullscreen for OSX 10.7
758     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
759     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
760     if (! tbar_visible != ! [toolbar isVisible])
761       [toolbar setVisible: tbar_visible];
762   }
763 #endif
765   ns_updating_frame = f;
766   [view lockFocus];
768   /* drawRect may have been called for say the minibuffer, and then clip path
769      is for the minibuffer.  But the display engine may draw more because
770      we have set the frame as garbaged.  So reset clip path to the whole
771      view.  */
772 #ifdef NS_IMPL_COCOA
773   {
774     NSBezierPath *bp;
775     NSRect r = [view frame];
776     NSRect cr = [[view window] frame];
777     /* If a large frame size is set, r may be larger than the window frame
778        before constrained.  In that case don't change the clip path, as we
779        will clear in to the tool bar and title bar.  */
780     if (r.size.height
781         + FRAME_NS_TITLEBAR_HEIGHT (f)
782         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
783       {
784         bp = [[NSBezierPath bezierPathWithRect: r] retain];
785         [bp setClip];
786         [bp release];
787       }
788   }
789 #endif
791 #ifdef NS_IMPL_GNUSTEP
792   uRect = NSMakeRect (0, 0, 0, 0);
793 #endif
797 static void
798 ns_update_window_begin (struct window *w)
799 /* --------------------------------------------------------------------------
800    Prepare for a grouped sequence of drawing calls
801    external (RIF) call; for one window, called after update_begin
802    -------------------------------------------------------------------------- */
804   struct frame *f = XFRAME (WINDOW_FRAME (w));
805   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
807   NSTRACE (ns_update_window_begin);
808   w->output_cursor = w->cursor;
810   block_input ();
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;
817         /* If the frame needs to be redrawn,
818            simply forget about any prior mouse highlighting.  */
819       if (FRAME_GARBAGED_P (f))
820         hlinfo->mouse_face_window = Qnil;
822       /* (further code for mouse faces ifdef'd out in other terms elided) */
823     }
825   unblock_input ();
829 static void
830 ns_update_window_end (struct window *w, bool cursor_on_p,
831                       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    -------------------------------------------------------------------------- */
837   /* note: this fn is nearly identical in all terms */
838   if (!w->pseudo_window_p)
839     {
840       block_input ();
842       if (cursor_on_p)
843         display_and_set_cursor (w, 1,
844                                 w->output_cursor.hpos, w->output_cursor.vpos,
845                                 w->output_cursor.x, w->output_cursor.y);
847       if (draw_window_fringes (w, 1))
848         {
849           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
850             x_draw_right_divider (w);
851           else
852             x_draw_vertical_border (w);
853         }
855       unblock_input ();
856     }
858   /* If a row with mouse-face was overwritten, arrange for
859      frame_up_to_date to redisplay the mouse highlight.  */
860   if (mouse_face_overwritten_p)
861     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
863   NSTRACE (update_window_end);
867 static void
868 ns_update_end (struct frame *f)
869 /* --------------------------------------------------------------------------
870    Finished a grouped sequence of drawing calls
871    external (RIF) call; for whole frame, called after update_window_end
872    -------------------------------------------------------------------------- */
874   EmacsView *view = FRAME_NS_VIEW (f);
876 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
877   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
879   block_input ();
881   [view unlockFocus];
882   [[view window] flushWindow];
884   unblock_input ();
885   ns_updating_frame = NULL;
886   NSTRACE (ns_update_end);
889 static void
890 ns_focus (struct frame *f, NSRect *r, int n)
891 /* --------------------------------------------------------------------------
892    Internal: Focus on given frame.  During small local updates this is used to
893      draw, however during large updates, ns_update_begin and ns_update_end are
894      called to wrap the whole thing, in which case these calls are stubbed out.
895      Except, on GNUstep, we accumulate the rectangle being drawn into, because
896      the back end won't do this automatically, and will just end up flushing
897      the entire window.
898    -------------------------------------------------------------------------- */
900 //  NSTRACE (ns_focus);
901 /* static int c =0;
902    fprintf (stderr, "focus: %d", c++);
903    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
904    fprintf (stderr, "\n"); */
906   if (f != ns_updating_frame)
907     {
908       NSView *view = FRAME_NS_VIEW (f);
909       if (view != focus_view)
910         {
911           if (focus_view != NULL)
912             {
913               [focus_view unlockFocus];
914               [[focus_view window] flushWindow];
915 /*debug_lock--; */
916             }
918           if (view)
919             [view lockFocus];
920           focus_view = view;
921 /*if (view) debug_lock++; */
922         }
923     }
925   /* clipping */
926   if (r)
927     {
928       [[NSGraphicsContext currentContext] saveGraphicsState];
929       if (n == 2)
930         NSRectClipList (r, 2);
931       else
932         NSRectClip (*r);
933       gsaved = YES;
934     }
938 static void
939 ns_unfocus (struct frame *f)
940 /* --------------------------------------------------------------------------
941      Internal: Remove focus on given frame
942    -------------------------------------------------------------------------- */
944 //  NSTRACE (ns_unfocus);
946   if (gsaved)
947     {
948       [[NSGraphicsContext currentContext] restoreGraphicsState];
949       gsaved = NO;
950     }
952   if (f != ns_updating_frame)
953     {
954       if (focus_view != NULL)
955         {
956           [focus_view unlockFocus];
957           [[focus_view window] flushWindow];
958           focus_view = NULL;
959 /*debug_lock--; */
960         }
961     }
965 static void
966 ns_clip_to_row (struct window *w, struct glyph_row *row,
967                 enum glyph_row_area area, BOOL gc)
968 /* --------------------------------------------------------------------------
969      Internal (but parallels other terms): Focus drawing on given row
970    -------------------------------------------------------------------------- */
972   struct frame *f = XFRAME (WINDOW_FRAME (w));
973   NSRect clip_rect;
974   int window_x, window_y, window_width;
976   window_box (w, area, &window_x, &window_y, &window_width, 0);
978   clip_rect.origin.x = window_x;
979   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
980   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
981   clip_rect.size.width = window_width;
982   clip_rect.size.height = row->visible_height;
984   ns_focus (f, &clip_rect, 1);
988 static void
989 ns_ring_bell (struct frame *f)
990 /* --------------------------------------------------------------------------
991      "Beep" routine
992    -------------------------------------------------------------------------- */
994   NSTRACE (ns_ring_bell);
995   if (visible_bell)
996     {
997       NSAutoreleasePool *pool;
998       struct frame *frame = SELECTED_FRAME ();
999       NSView *view;
1001       block_input ();
1002       pool = [[NSAutoreleasePool alloc] init];
1004       view = FRAME_NS_VIEW (frame);
1005       if (view != nil)
1006         {
1007           NSRect r, surr;
1008           NSPoint dim = NSMakePoint (128, 128);
1010           r = [view bounds];
1011           r.origin.x += (r.size.width - dim.x) / 2;
1012           r.origin.y += (r.size.height - dim.y) / 2;
1013           r.size.width = dim.x;
1014           r.size.height = dim.y;
1015           surr = NSInsetRect (r, -2, -2);
1016           ns_focus (frame, &surr, 1);
1017           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1018           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1019                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
1020           NSRectFill (r);
1021           [[view window] flushWindow];
1022           ns_timeout (150000);
1023           [[view window] restoreCachedImage];
1024           [[view window] flushWindow];
1025           ns_unfocus (frame);
1026         }
1027       [pool release];
1028       unblock_input ();
1029     }
1030   else
1031     {
1032       NSBeep ();
1033     }
1036 /* ==========================================================================
1038     Frame / window manager related functions
1040    ========================================================================== */
1043 static void
1044 ns_raise_frame (struct frame *f)
1045 /* --------------------------------------------------------------------------
1046      Bring window to foreground and make it active
1047    -------------------------------------------------------------------------- */
1049   NSView *view;
1050   check_window_system (f);
1051   view = FRAME_NS_VIEW (f);
1052   block_input ();
1053   if (FRAME_VISIBLE_P (f))
1054     [[view window] makeKeyAndOrderFront: NSApp];
1055   unblock_input ();
1059 static void
1060 ns_lower_frame (struct frame *f)
1061 /* --------------------------------------------------------------------------
1062      Send window to back
1063    -------------------------------------------------------------------------- */
1065   NSView *view;
1066   check_window_system (f);
1067   view = FRAME_NS_VIEW (f);
1068   block_input ();
1069   [[view window] orderBack: NSApp];
1070   unblock_input ();
1074 static void
1075 ns_frame_raise_lower (struct frame *f, int raise)
1076 /* --------------------------------------------------------------------------
1077      External (hook)
1078    -------------------------------------------------------------------------- */
1080   NSTRACE (ns_frame_raise_lower);
1082   if (raise)
1083     ns_raise_frame (f);
1084   else
1085     ns_lower_frame (f);
1089 static void
1090 ns_frame_rehighlight (struct frame *frame)
1091 /* --------------------------------------------------------------------------
1092      External (hook): called on things like window switching within frame
1093    -------------------------------------------------------------------------- */
1095   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1096   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1098   NSTRACE (ns_frame_rehighlight);
1099   if (dpyinfo->x_focus_frame)
1100     {
1101       dpyinfo->x_highlight_frame
1102         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1103            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1104            : dpyinfo->x_focus_frame);
1105       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;
1114   if (dpyinfo->x_highlight_frame &&
1115          dpyinfo->x_highlight_frame != old_highlight)
1116     {
1117       if (old_highlight)
1118         {
1119           x_update_cursor (old_highlight, 1);
1120           x_set_frame_alpha (old_highlight);
1121         }
1122       if (dpyinfo->x_highlight_frame)
1123         {
1124           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1125           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1126         }
1127     }
1131 void
1132 x_make_frame_visible (struct frame *f)
1133 /* --------------------------------------------------------------------------
1134      External: Show the window (X11 semantics)
1135    -------------------------------------------------------------------------- */
1137   NSTRACE (x_make_frame_visible);
1138   /* XXX: at some points in past this was not needed, as the only place that
1139      called this (frame.c:Fraise_frame ()) also called raise_lower;
1140      if this ends up the case again, comment this out again. */
1141   if (!FRAME_VISIBLE_P (f))
1142     {
1143       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1145       SET_FRAME_VISIBLE (f, 1);
1146       ns_raise_frame (f);
1148       /* Making a new frame from a fullscreen frame will make the new frame
1149          fullscreen also.  So skip handleFS as this will print an error.  */
1150       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1151           && [view isFullscreen])
1152         return;
1154       if (f->want_fullscreen != FULLSCREEN_NONE)
1155         {
1156           block_input ();
1157           [view handleFS];
1158           unblock_input ();
1159         }
1160     }
1164 void
1165 x_make_frame_invisible (struct frame *f)
1166 /* --------------------------------------------------------------------------
1167      External: Hide the window (X11 semantics)
1168    -------------------------------------------------------------------------- */
1170   NSView *view;
1171   NSTRACE (x_make_frame_invisible);
1172   check_window_system (f);
1173   view = FRAME_NS_VIEW (f);
1174   [[view window] orderOut: NSApp];
1175   SET_FRAME_VISIBLE (f, 0);
1176   SET_FRAME_ICONIFIED (f, 0);
1180 void
1181 x_iconify_frame (struct frame *f)
1182 /* --------------------------------------------------------------------------
1183      External: Iconify window
1184    -------------------------------------------------------------------------- */
1186   NSView *view;
1187   struct ns_display_info *dpyinfo;
1189   NSTRACE (x_iconify_frame);
1190   check_window_system (f);
1191   view = FRAME_NS_VIEW (f);
1192   dpyinfo = FRAME_DISPLAY_INFO (f);
1194   if (dpyinfo->x_highlight_frame == f)
1195     dpyinfo->x_highlight_frame = 0;
1197   if ([[view window] windowNumber] <= 0)
1198     {
1199       /* the window is still deferred.  Make it very small, bring it
1200          on screen and order it out. */
1201       NSRect s = { { 100, 100}, {0, 0} };
1202       NSRect t;
1203       t = [[view window] frame];
1204       [[view window] setFrame: s display: NO];
1205       [[view window] orderBack: NSApp];
1206       [[view window] orderOut: NSApp];
1207       [[view window] setFrame: t display: NO];
1208     }
1209   [[view window] miniaturize: NSApp];
1212 /* Free X resources of frame F.  */
1214 void
1215 x_free_frame_resources (struct frame *f)
1217   NSView *view;
1218   struct ns_display_info *dpyinfo;
1219   Mouse_HLInfo *hlinfo;
1221   NSTRACE (x_free_frame_resources);
1222   check_window_system (f);
1223   view = FRAME_NS_VIEW (f);
1224   dpyinfo = FRAME_DISPLAY_INFO (f);
1225   hlinfo = MOUSE_HL_INFO (f);
1227   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1229   block_input ();
1231   free_frame_menubar (f);
1232   free_frame_faces (f);
1234   if (f == dpyinfo->x_focus_frame)
1235     dpyinfo->x_focus_frame = 0;
1236   if (f == dpyinfo->x_highlight_frame)
1237     dpyinfo->x_highlight_frame = 0;
1238   if (f == hlinfo->mouse_face_mouse_frame)
1239     reset_mouse_highlight (hlinfo);
1241   if (f->output_data.ns->miniimage != nil)
1242     [f->output_data.ns->miniimage release];
1244   [[view window] close];
1245   [view release];
1247   xfree (f->output_data.ns);
1249   unblock_input ();
1252 void
1253 x_destroy_window (struct frame *f)
1254 /* --------------------------------------------------------------------------
1255      External: Delete the window
1256    -------------------------------------------------------------------------- */
1258   NSTRACE (x_destroy_window);
1259   check_window_system (f);
1260   x_free_frame_resources (f);
1261   ns_window_num--;
1265 void
1266 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1267 /* --------------------------------------------------------------------------
1268      External: Position the window
1269    -------------------------------------------------------------------------- */
1271   NSView *view = FRAME_NS_VIEW (f);
1272   NSArray *screens = [NSScreen screens];
1273   NSScreen *fscreen = [screens objectAtIndex: 0];
1274   NSScreen *screen = [[view window] screen];
1276   NSTRACE (x_set_offset);
1278   block_input ();
1280   f->left_pos = xoff;
1281   f->top_pos = yoff;
1283   if (view != nil && screen && fscreen)
1284     {
1285       f->left_pos = f->size_hint_flags & XNegative
1286         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1287         : f->left_pos;
1288       /* We use visibleFrame here to take menu bar into account.
1289          Ideally we should also adjust left/top with visibleFrame.origin.  */
1291       f->top_pos = f->size_hint_flags & YNegative
1292         ? ([screen visibleFrame].size.height + f->top_pos
1293            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1294            - FRAME_TOOLBAR_HEIGHT (f))
1295         : f->top_pos;
1296 #ifdef NS_IMPL_GNUSTEP
1297       if (f->left_pos < 100)
1298         f->left_pos = 100;  /* don't overlap menu */
1299 #endif
1300       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1301          menu bar.  */
1302       [[view window] setFrameTopLeftPoint:
1303                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1304                                     SCREENMAXBOUND ([fscreen frame].size.height
1305                                                     - NS_TOP_POS (f)))];
1306       f->size_hint_flags &= ~(XNegative|YNegative);
1307     }
1309   unblock_input ();
1313 void
1314 x_set_window_size (struct frame *f,
1315                    int change_grav,
1316                    int width,
1317                    int height,
1318                    bool pixelwise)
1319 /* --------------------------------------------------------------------------
1320      Adjust window pixel size based on given character grid size
1321      Impl is a bit more complex than other terms, need to do some
1322      internal clipping.
1323    -------------------------------------------------------------------------- */
1325   EmacsView *view = FRAME_NS_VIEW (f);
1326   NSWindow *window = [view window];
1327   NSRect wr = [window frame];
1328   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1329   int pixelwidth, pixelheight;
1330   int rows, cols;
1332   NSTRACE (x_set_window_size);
1334   if (view == nil)
1335     return;
1337 /*fprintf (stderr, "\tsetWindowSize: %d x %d, pixelwise %d, font size %d x %d\n", width, height, pixelwise, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));*/
1339   block_input ();
1341   check_frame_size (f, &width, &height, pixelwise);
1343   compute_fringe_widths (f, 0);
1345   if (pixelwise)
1346     {
1347       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1348       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1349       cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1350       rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1351     }
1352   else
1353     {
1354       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1355       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1356       cols = width;
1357       rows = height;
1358     }
1360   /* If we have a toolbar, take its height into account. */
1361   if (tb && ! [view isFullscreen])
1362     {
1363     /* NOTE: previously this would generate wrong result if toolbar not
1364              yet displayed and fixing toolbar_height=32 helped, but
1365              now (200903) seems no longer needed */
1366     FRAME_TOOLBAR_HEIGHT (f) =
1367       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1368         - FRAME_NS_TITLEBAR_HEIGHT (f);
1369 #ifdef NS_IMPL_GNUSTEP
1370       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1371 #endif
1372     }
1373   else
1374     FRAME_TOOLBAR_HEIGHT (f) = 0;
1376   wr.size.width = pixelwidth + f->border_width;
1377   wr.size.height = pixelheight;
1378   if (! [view isFullscreen])
1379     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1380       + FRAME_TOOLBAR_HEIGHT (f);
1382   /* Do not try to constrain to this screen.  We may have multiple
1383      screens, and want Emacs to span those.  Constraining to screen
1384      prevents that, and that is not nice to the user.  */
1385  if (f->output_data.ns->zooming)
1386    f->output_data.ns->zooming = 0;
1387  else
1388    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1390   [view setRows: rows andColumns: cols];
1391   [window setFrame: wr display: YES];
1393   /* This is a trick to compensate for Emacs' managing the scrollbar area
1394      as a fixed number of standard character columns.  Instead of leaving
1395      blank space for the extra, we chopped it off above.  Now for
1396      left-hand scrollbars, we shift all rendering to the left by the
1397      difference between the real width and Emacs' imagined one.  For
1398      right-hand bars, don't worry about it since the extra is never used.
1399      (Obviously doesn't work for vertically split windows tho..) */
1400   {
1401     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1402       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1403                      - NS_SCROLL_BAR_WIDTH (f), 0)
1404       : NSMakePoint (0, 0);
1405     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1406     [view setBoundsOrigin: origin];
1407   }
1409   change_frame_size (f, width, height, 0, 1, 0, pixelwise);
1410 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1412   mark_window_cursors_off (XWINDOW (f->root_window));
1413   cancel_mouse_face (f);
1415   unblock_input ();
1419 static void
1420 ns_fullscreen_hook (struct frame *f)
1422   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1424   if (!FRAME_VISIBLE_P (f))
1425     return;
1427    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1428     {
1429       /* Old style fs don't initiate correctly if created from
1430          init/default-frame alist, so use a timer (not nice...).
1431       */
1432       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1433                                      selector: @selector (handleFS)
1434                                      userInfo: nil repeats: NO];
1435       return;
1436     }
1438   block_input ();
1439   [view handleFS];
1440   unblock_input ();
1443 /* ==========================================================================
1445     Color management
1447    ========================================================================== */
1450 NSColor *
1451 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1453   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1454   if (idx < 1 || idx >= color_table->avail)
1455     return nil;
1456   return color_table->colors[idx];
1460 unsigned long
1461 ns_index_color (NSColor *color, struct frame *f)
1463   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1464   ptrdiff_t idx;
1465   ptrdiff_t i;
1467   if (!color_table->colors)
1468     {
1469       color_table->size = NS_COLOR_CAPACITY;
1470       color_table->avail = 1; /* skip idx=0 as marker */
1471       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1472       color_table->colors[0] = nil;
1473       color_table->empty_indices = [[NSMutableSet alloc] init];
1474     }
1476   /* Do we already have this color?  */
1477   for (i = 1; i < color_table->avail; i++)
1478     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1479       return i;
1481   if ([color_table->empty_indices count] > 0)
1482     {
1483       NSNumber *index = [color_table->empty_indices anyObject];
1484       [color_table->empty_indices removeObject: index];
1485       idx = [index unsignedLongValue];
1486     }
1487   else
1488     {
1489       if (color_table->avail == color_table->size)
1490         color_table->colors =
1491           xpalloc (color_table->colors, &color_table->size, 1,
1492                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1493       idx = color_table->avail++;
1494     }
1496   color_table->colors[idx] = color;
1497   [color retain];
1498 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1499   return idx;
1503 void
1504 ns_free_indexed_color (unsigned long idx, struct frame *f)
1506   struct ns_color_table *color_table;
1507   NSColor *color;
1508   NSNumber *index;
1510   if (!f)
1511     return;
1513   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1515   if (idx <= 0 || idx >= color_table->size) {
1516     message1 ("ns_free_indexed_color: Color index out of range.\n");
1517     return;
1518   }
1520   index = [NSNumber numberWithUnsignedInt: idx];
1521   if ([color_table->empty_indices containsObject: index]) {
1522     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1523     return;
1524   }
1526   color = color_table->colors[idx];
1527   [color release];
1528   color_table->colors[idx] = nil;
1529   [color_table->empty_indices addObject: index];
1530 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1534 static int
1535 ns_get_color (const char *name, NSColor **col)
1536 /* --------------------------------------------------------------------------
1537      Parse a color name
1538    -------------------------------------------------------------------------- */
1539 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1540    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1541    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1543   NSColor *new = nil;
1544   static char hex[20];
1545   int scaling;
1546   float r = -1.0, g, b;
1547   NSString *nsname = [NSString stringWithUTF8String: name];
1549 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1550   block_input ();
1552   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1553     {
1554 #ifdef NS_IMPL_COCOA
1555       NSString *defname = [[NSUserDefaults standardUserDefaults]
1556                             stringForKey: @"AppleHighlightColor"];
1557       if (defname != nil)
1558         nsname = defname;
1559       else
1560 #endif
1561       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1562         {
1563           *col = [new colorUsingDefaultColorSpace];
1564           unblock_input ();
1565           return 0;
1566         }
1567       else
1568         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1570       name = [nsname UTF8String];
1571     }
1572   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1573     {
1574       /* NOTE: OSX applications normally don't set foreground selection, but
1575          text may be unreadable if we don't.
1576       */
1577       if ((new = [NSColor selectedTextColor]) != nil)
1578         {
1579           *col = [new colorUsingDefaultColorSpace];
1580           unblock_input ();
1581           return 0;
1582         }
1584       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1585       name = [nsname UTF8String];
1586     }
1588   /* First, check for some sort of numeric specification. */
1589   hex[0] = '\0';
1591   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1592     {
1593       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1594       [scanner scanFloat: &r];
1595       [scanner scanFloat: &g];
1596       [scanner scanFloat: &b];
1597     }
1598   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1599     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1600   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1601     {
1602       int len = (strlen(name) - 1);
1603       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1604       int i;
1605       scaling = strlen(name+start) / 3;
1606       for (i = 0; i < 3; i++)
1607         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1608                  name + start + i * scaling);
1609       hex[3 * (scaling + 1) - 1] = '\0';
1610     }
1612   if (hex[0])
1613     {
1614       int rr, gg, bb;
1615       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1616       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1617         {
1618           r = rr / fscale;
1619           g = gg / fscale;
1620           b = bb / fscale;
1621         }
1622     }
1624   if (r >= 0.0F)
1625     {
1626       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1627       unblock_input ();
1628       return 0;
1629     }
1631   /* Otherwise, color is expected to be from a list */
1632   {
1633     NSEnumerator *lenum, *cenum;
1634     NSString *name;
1635     NSColorList *clist;
1637 #ifdef NS_IMPL_GNUSTEP
1638     /* XXX: who is wrong, the requestor or the implementation? */
1639     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1640         == NSOrderedSame)
1641       nsname = @"highlightColor";
1642 #endif
1644     lenum = [[NSColorList availableColorLists] objectEnumerator];
1645     while ( (clist = [lenum nextObject]) && new == nil)
1646       {
1647         cenum = [[clist allKeys] objectEnumerator];
1648         while ( (name = [cenum nextObject]) && new == nil )
1649           {
1650             if ([name compare: nsname
1651                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1652               new = [clist colorWithKey: name];
1653           }
1654       }
1655   }
1657   if (new)
1658     *col = [new colorUsingDefaultColorSpace];
1659   unblock_input ();
1660   return new ? 0 : 1;
1665 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1666 /* --------------------------------------------------------------------------
1667      Convert a Lisp string object to a NS color
1668    -------------------------------------------------------------------------- */
1670   NSTRACE (ns_lisp_to_color);
1671   if (STRINGP (color))
1672     return ns_get_color (SSDATA (color), col);
1673   else if (SYMBOLP (color))
1674     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1675   return 1;
1679 Lisp_Object
1680 ns_color_to_lisp (NSColor *col)
1681 /* --------------------------------------------------------------------------
1682      Convert a color to a lisp string with the RGB equivalent
1683    -------------------------------------------------------------------------- */
1685   EmacsCGFloat red, green, blue, alpha, gray;
1686   char buf[1024];
1687   const char *str;
1688   NSTRACE (ns_color_to_lisp);
1690   block_input ();
1691   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1693       if ((str =[[col colorNameComponent] UTF8String]))
1694         {
1695           unblock_input ();
1696           return build_string ((char *)str);
1697         }
1699     [[col colorUsingDefaultColorSpace]
1700         getRed: &red green: &green blue: &blue alpha: &alpha];
1701   if (red == green && red == blue)
1702     {
1703       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1704             getWhite: &gray alpha: &alpha];
1705       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1706                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1707       unblock_input ();
1708       return build_string (buf);
1709     }
1711   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1712             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1714   unblock_input ();
1715   return build_string (buf);
1719 void
1720 ns_query_color(void *col, XColor *color_def, int setPixel)
1721 /* --------------------------------------------------------------------------
1722          Get ARGB values out of NSColor col and put them into color_def.
1723          If setPixel, set the pixel to a concatenated version.
1724          and set color_def pixel to the resulting index.
1725    -------------------------------------------------------------------------- */
1727   EmacsCGFloat r, g, b, a;
1729   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1730   color_def->red   = r * 65535;
1731   color_def->green = g * 65535;
1732   color_def->blue  = b * 65535;
1734   if (setPixel == YES)
1735     color_def->pixel
1736       = ARGB_TO_ULONG((int)(a*255),
1737                       (int)(r*255), (int)(g*255), (int)(b*255));
1741 bool
1742 ns_defined_color (struct frame *f,
1743                   const char *name,
1744                   XColor *color_def,
1745                   bool alloc,
1746                   bool makeIndex)
1747 /* --------------------------------------------------------------------------
1748          Return true if named color found, and set color_def rgb accordingly.
1749          If makeIndex and alloc are nonzero put the color in the color_table,
1750          and set color_def pixel to the resulting index.
1751          If makeIndex is zero, set color_def pixel to ARGB.
1752          Return false if not found
1753    -------------------------------------------------------------------------- */
1755   NSColor *col;
1756   NSTRACE (ns_defined_color);
1758   block_input ();
1759   if (ns_get_color (name, &col) != 0) /* Color not found  */
1760     {
1761       unblock_input ();
1762       return 0;
1763     }
1764   if (makeIndex && alloc)
1765     color_def->pixel = ns_index_color (col, f);
1766   ns_query_color (col, color_def, !makeIndex);
1767   unblock_input ();
1768   return 1;
1772 void
1773 x_set_frame_alpha (struct frame *f)
1774 /* --------------------------------------------------------------------------
1775      change the entire-frame transparency
1776    -------------------------------------------------------------------------- */
1778   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1779   double alpha = 1.0;
1780   double alpha_min = 1.0;
1782   if (dpyinfo->x_highlight_frame == f)
1783     alpha = f->alpha[0];
1784   else
1785     alpha = f->alpha[1];
1787   if (FLOATP (Vframe_alpha_lower_limit))
1788     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1789   else if (INTEGERP (Vframe_alpha_lower_limit))
1790     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1792   if (alpha < 0.0)
1793     return;
1794   else if (1.0 < alpha)
1795     alpha = 1.0;
1796   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1797     alpha = alpha_min;
1799 #ifdef NS_IMPL_COCOA
1800   {
1801     EmacsView *view = FRAME_NS_VIEW (f);
1802   [[view window] setAlphaValue: alpha];
1803   }
1804 #endif
1808 /* ==========================================================================
1810     Mouse handling
1812    ========================================================================== */
1815 void
1816 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1817 /* --------------------------------------------------------------------------
1818      Programmatically reposition mouse pointer in pixel coordinates
1819    -------------------------------------------------------------------------- */
1821   NSTRACE (x_set_mouse_pixel_position);
1822   ns_raise_frame (f);
1823 #if 0
1824   /* FIXME: this does not work, and what about GNUstep? */
1825 #ifdef NS_IMPL_COCOA
1826   [FRAME_NS_VIEW (f) lockFocus];
1827   PSsetmouse ((float)pix_x, (float)pix_y);
1828   [FRAME_NS_VIEW (f) unlockFocus];
1829 #endif
1830 #endif
1834 void
1835 x_set_mouse_position (struct frame *f, int h, int v)
1836 /* --------------------------------------------------------------------------
1837      Programmatically reposition mouse pointer in character coordinates
1838    -------------------------------------------------------------------------- */
1840   int pix_x, pix_y;
1842   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1843   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1845   if (pix_x < 0) pix_x = 0;
1846   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1848   if (pix_y < 0) pix_y = 0;
1849   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1851   x_set_mouse_pixel_position (f, pix_x, pix_y);
1855 static int
1856 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1857 /*   ------------------------------------------------------------------------
1858      Called by EmacsView on mouseMovement events.  Passes on
1859      to emacs mainstream code if we moved off of a rect of interest
1860      known as last_mouse_glyph.
1861      ------------------------------------------------------------------------ */
1863   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1864   NSRect *r;
1866 //  NSTRACE (note_mouse_movement);
1868   dpyinfo->last_mouse_motion_frame = frame;
1869   r = &dpyinfo->last_mouse_glyph;
1871   /* Note, this doesn't get called for enter/leave, since we don't have a
1872      position.  Those are taken care of in the corresponding NSView methods. */
1874   /* has movement gone beyond last rect we were tracking? */
1875   if (x < r->origin.x || x >= r->origin.x + r->size.width
1876       || y < r->origin.y || y >= r->origin.y + r->size.height)
1877     {
1878       ns_update_begin (frame);
1879       frame->mouse_moved = 1;
1880       note_mouse_highlight (frame, x, y);
1881       remember_mouse_glyph (frame, x, y, r);
1882       ns_update_end (frame);
1883       return 1;
1884     }
1886   return 0;
1890 static void
1891 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1892                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1893                    Time *time)
1894 /* --------------------------------------------------------------------------
1895     External (hook): inform emacs about mouse position and hit parts.
1896     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1897     x & y should be position in the scrollbar (the whole bar, not the handle)
1898     and length of scrollbar respectively
1899    -------------------------------------------------------------------------- */
1901   id view;
1902   NSPoint position;
1903   Lisp_Object frame, tail;
1904   struct frame *f;
1905   struct ns_display_info *dpyinfo;
1907   NSTRACE (ns_mouse_position);
1909   if (*fp == NULL)
1910     {
1911       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1912       return;
1913     }
1915   dpyinfo = FRAME_DISPLAY_INFO (*fp);
1917   block_input ();
1919   /* Clear the mouse-moved flag for every frame on this display.  */
1920   FOR_EACH_FRAME (tail, frame)
1921     if (FRAME_NS_P (XFRAME (frame))
1922         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1923       XFRAME (frame)->mouse_moved = 0;
1925   dpyinfo->last_mouse_scroll_bar = nil;
1926   if (dpyinfo->last_mouse_frame
1927       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1928     f = dpyinfo->last_mouse_frame;
1929   else
1930     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
1932   if (f && FRAME_NS_P (f))
1933     {
1934       view = FRAME_NS_VIEW (*fp);
1936       position = [[view window] mouseLocationOutsideOfEventStream];
1937       position = [view convertPoint: position fromView: nil];
1938       remember_mouse_glyph (f, position.x, position.y,
1939                             &dpyinfo->last_mouse_glyph);
1940 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1942       if (bar_window) *bar_window = Qnil;
1943       if (part) *part = 0; /*scroll_bar_handle; */
1945       if (x) XSETINT (*x, lrint (position.x));
1946       if (y) XSETINT (*y, lrint (position.y));
1947       if (time)
1948         *time = dpyinfo->last_mouse_movement_time;
1949       *fp = f;
1950     }
1952   unblock_input ();
1956 static void
1957 ns_frame_up_to_date (struct frame *f)
1958 /* --------------------------------------------------------------------------
1959     External (hook): Fix up mouse highlighting right after a full update.
1960     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1961    -------------------------------------------------------------------------- */
1963   NSTRACE (ns_frame_up_to_date);
1965   if (FRAME_NS_P (f))
1966     {
1967       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1968       if (f == hlinfo->mouse_face_mouse_frame)
1969         {
1970           block_input ();
1971           ns_update_begin(f);
1972           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1973                                 hlinfo->mouse_face_mouse_x,
1974                                 hlinfo->mouse_face_mouse_y);
1975           ns_update_end(f);
1976           unblock_input ();
1977         }
1978     }
1982 static void
1983 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1984 /* --------------------------------------------------------------------------
1985     External (RIF): set frame mouse pointer type.
1986    -------------------------------------------------------------------------- */
1988   NSTRACE (ns_define_frame_cursor);
1989   if (FRAME_POINTER_TYPE (f) != cursor)
1990     {
1991       EmacsView *view = FRAME_NS_VIEW (f);
1992       FRAME_POINTER_TYPE (f) = cursor;
1993       [[view window] invalidateCursorRectsForView: view];
1994       /* Redisplay assumes this function also draws the changed frame
1995          cursor, but this function doesn't, so do it explicitly.  */
1996       x_update_cursor (f, 1);
1997     }
2002 /* ==========================================================================
2004     Keyboard handling
2006    ========================================================================== */
2009 static unsigned
2010 ns_convert_key (unsigned code)
2011 /* --------------------------------------------------------------------------
2012     Internal call used by NSView-keyDown.
2013    -------------------------------------------------------------------------- */
2015   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
2016                                 / sizeof (convert_ns_to_X_keysym[0]));
2017   unsigned keysym;
2018   /* An array would be faster, but less easy to read. */
2019   for (keysym = 0; keysym < last_keysym; keysym += 2)
2020     if (code == convert_ns_to_X_keysym[keysym])
2021       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2022   return 0;
2023 /* if decide to use keyCode and Carbon table, use this line:
2024      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2028 char *
2029 x_get_keysym_name (int keysym)
2030 /* --------------------------------------------------------------------------
2031     Called by keyboard.c.  Not sure if the return val is important, except
2032     that it be unique.
2033    -------------------------------------------------------------------------- */
2035   static char value[16];
2036   NSTRACE (x_get_keysym_name);
2037   sprintf (value, "%d", keysym);
2038   return value;
2043 /* ==========================================================================
2045     Block drawing operations
2047    ========================================================================== */
2050 static void
2051 ns_redraw_scroll_bars (struct frame *f)
2053   int i;
2054   id view;
2055   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2056   NSTRACE (ns_redraw_scroll_bars);
2057   for (i =[subviews count]-1; i >= 0; i--)
2058     {
2059       view = [subviews objectAtIndex: i];
2060       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2061       [view display];
2062     }
2066 void
2067 ns_clear_frame (struct frame *f)
2068 /* --------------------------------------------------------------------------
2069       External (hook): Erase the entire frame
2070    -------------------------------------------------------------------------- */
2072   NSView *view = FRAME_NS_VIEW (f);
2073   NSRect r;
2075   NSTRACE (ns_clear_frame);
2077  /* comes on initial frame because we have
2078     after-make-frame-functions = select-frame */
2079  if (!FRAME_DEFAULT_FACE (f))
2080    return;
2082   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2084   r = [view bounds];
2086   block_input ();
2087   ns_focus (f, &r, 1);
2088   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2089   NSRectFill (r);
2090   ns_unfocus (f);
2092   /* as of 2006/11 or so this is now needed */
2093   ns_redraw_scroll_bars (f);
2094   unblock_input ();
2098 static void
2099 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2100 /* --------------------------------------------------------------------------
2101     External (RIF):  Clear section of frame
2102    -------------------------------------------------------------------------- */
2104   NSRect r = NSMakeRect (x, y, width, height);
2105   NSView *view = FRAME_NS_VIEW (f);
2106   struct face *face = FRAME_DEFAULT_FACE (f);
2108   if (!view || !face)
2109     return;
2111   NSTRACE (ns_clear_frame_area);
2113   r = NSIntersectionRect (r, [view frame]);
2114   ns_focus (f, &r, 1);
2115   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2117   NSRectFill (r);
2119   ns_unfocus (f);
2120   return;
2124 static void
2125 ns_scroll_run (struct window *w, struct run *run)
2126 /* --------------------------------------------------------------------------
2127     External (RIF):  Insert or delete n lines at line vpos
2128    -------------------------------------------------------------------------- */
2130   struct frame *f = XFRAME (w->frame);
2131   int x, y, width, height, from_y, to_y, bottom_y;
2133   NSTRACE (ns_scroll_run);
2135   /* begin copy from other terms */
2136   /* Get frame-relative bounding box of the text display area of W,
2137      without mode lines.  Include in this box the left and right
2138      fringe of W.  */
2139   window_box (w, ANY_AREA, &x, &y, &width, &height);
2141   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2142   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2143   bottom_y = y + height;
2145   if (to_y < from_y)
2146     {
2147       /* Scrolling up.  Make sure we don't copy part of the mode
2148          line at the bottom.  */
2149       if (from_y + run->height > bottom_y)
2150         height = bottom_y - from_y;
2151       else
2152         height = run->height;
2153     }
2154   else
2155     {
2156       /* Scrolling down.  Make sure we don't copy over the mode line.
2157          at the bottom.  */
2158       if (to_y + run->height > bottom_y)
2159         height = bottom_y - to_y;
2160       else
2161         height = run->height;
2162     }
2163   /* end copy from other terms */
2165   if (height == 0)
2166       return;
2168   block_input ();
2170   x_clear_cursor (w);
2172   {
2173     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2174     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2175     NSPoint dstOrigin = NSMakePoint (x, to_y);
2177     ns_focus (f, &dstRect, 1);
2178     NSCopyBits (0, srcRect , dstOrigin);
2179     ns_unfocus (f);
2180   }
2182   unblock_input ();
2186 static void
2187 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2188 /* --------------------------------------------------------------------------
2189     External (RIF): preparatory to fringe update after text was updated
2190    -------------------------------------------------------------------------- */
2192   struct frame *f;
2193   int width, height;
2195   NSTRACE (ns_after_update_window_line);
2197   /* begin copy from other terms */
2198   eassert (w);
2200   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2201     desired_row->redraw_fringe_bitmaps_p = 1;
2203   /* When a window has disappeared, make sure that no rest of
2204      full-width rows stays visible in the internal border.  */
2205   if (windows_or_buffers_changed
2206       && desired_row->full_width_p
2207       && (f = XFRAME (w->frame),
2208           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2209           width != 0)
2210       && (height = desired_row->visible_height,
2211           height > 0))
2212     {
2213       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2215       block_input ();
2216       ns_clear_frame_area (f, 0, y, width, height);
2217       ns_clear_frame_area (f,
2218                            FRAME_PIXEL_WIDTH (f) - width,
2219                            y, width, height);
2220       unblock_input ();
2221     }
2225 static void
2226 ns_shift_glyphs_for_insert (struct frame *f,
2227                            int x, int y, int width, int height,
2228                            int shift_by)
2229 /* --------------------------------------------------------------------------
2230     External (RIF): copy an area horizontally, don't worry about clearing src
2231    -------------------------------------------------------------------------- */
2233   NSRect srcRect = NSMakeRect (x, y, width, height);
2234   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2235   NSPoint dstOrigin = dstRect.origin;
2237   NSTRACE (ns_shift_glyphs_for_insert);
2239   ns_focus (f, &dstRect, 1);
2240   NSCopyBits (0, srcRect, dstOrigin);
2241   ns_unfocus (f);
2246 /* ==========================================================================
2248     Character encoding and metrics
2250    ========================================================================== */
2253 static void
2254 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2255 /* --------------------------------------------------------------------------
2256      External (RIF); compute left/right overhang of whole string and set in s
2257    -------------------------------------------------------------------------- */
2259   struct font *font = s->font;
2261   if (s->char2b)
2262     {
2263       struct font_metrics metrics;
2264       unsigned int codes[2];
2265       codes[0] = *(s->char2b);
2266       codes[1] = *(s->char2b + s->nchars - 1);
2268       font->driver->text_extents (font, codes, 2, &metrics);
2269       s->left_overhang = -metrics.lbearing;
2270       s->right_overhang
2271         = metrics.rbearing > metrics.width
2272         ? metrics.rbearing - metrics.width : 0;
2273     }
2274   else
2275     {
2276       s->left_overhang = 0;
2277       if (EQ (font->driver->type, Qns))
2278         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2279           FONT_HEIGHT (font) * 0.2 : 0;
2280       else
2281         s->right_overhang = 0;
2282     }
2287 /* ==========================================================================
2289     Fringe and cursor drawing
2291    ========================================================================== */
2294 extern int max_used_fringe_bitmap;
2295 static void
2296 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2297                       struct draw_fringe_bitmap_params *p)
2298 /* --------------------------------------------------------------------------
2299     External (RIF); fringe-related
2300    -------------------------------------------------------------------------- */
2302   struct frame *f = XFRAME (WINDOW_FRAME (w));
2303   struct face *face = p->face;
2304   static EmacsImage **bimgs = NULL;
2305   static int nBimgs = 0;
2307   /* grow bimgs if needed */
2308   if (nBimgs < max_used_fringe_bitmap)
2309     {
2310       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2311       memset (bimgs + nBimgs, 0,
2312               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2313       nBimgs = max_used_fringe_bitmap;
2314     }
2316   /* Must clip because of partially visible lines.  */
2317   ns_clip_to_row (w, row, ANY_AREA, YES);
2319   if (!p->overlay_p)
2320     {
2321       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2323       /* If the fringe is adjacent to the left (right) scroll bar of a
2324          leftmost (rightmost, respectively) window, then extend its
2325          background to the gap between the fringe and the bar.  */
2326       if ((WINDOW_LEFTMOST_P (w)
2327            && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2328           || (WINDOW_RIGHTMOST_P (w)
2329               && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2330         {
2331           int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2333           if (sb_width > 0)
2334             {
2335               int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2336               int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2337                                     * FRAME_COLUMN_WIDTH (f));
2339               if (bx < 0)
2340                 {
2341                   /* Bitmap fills the fringe.  */
2342                   if (bar_area_x + bar_area_width == p->x)
2343                     bx = bar_area_x + sb_width;
2344                   else if (p->x + p->wd == bar_area_x)
2345                     bx = bar_area_x;
2346                   if (bx >= 0)
2347                     {
2348                       int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2350                       nx = bar_area_width - sb_width;
2351                       by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2352                                                             row->y));
2353                       ny = row->visible_height;
2354                     }
2355                 }
2356               else
2357                 {
2358                   if (bar_area_x + bar_area_width == bx)
2359                     {
2360                       bx = bar_area_x + sb_width;
2361                       nx += bar_area_width - sb_width;
2362                     }
2363                   else if (bx + nx == bar_area_x)
2364                     nx += bar_area_width - sb_width;
2365                 }
2366             }
2367         }
2369       if (bx >= 0 && nx > 0)
2370         {
2371           NSRect r = NSMakeRect (bx, by, nx, ny);
2372           NSRectClip (r);
2373           [ns_lookup_indexed_color (face->background, f) set];
2374           NSRectFill (r);
2375         }
2376     }
2378   if (p->which)
2379     {
2380       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2381       EmacsImage *img = bimgs[p->which - 1];
2383       if (!img)
2384         {
2385           unsigned short *bits = p->bits + p->dh;
2386           int len = p->h;
2387           int i;
2388           unsigned char *cbits = xmalloc (len);
2390           for (i = 0; i < len; i++)
2391             cbits[i] = ~(bits[i] & 0xff);
2392           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2393                                            flip: NO];
2394           bimgs[p->which - 1] = img;
2395           xfree (cbits);
2396         }
2398       NSRectClip (r);
2399       /* Since we composite the bitmap instead of just blitting it, we need
2400          to erase the whole background. */
2401       [ns_lookup_indexed_color(face->background, f) set];
2402       NSRectFill (r);
2403       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2404 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2405       [img drawInRect: r
2406               fromRect: NSZeroRect
2407              operation: NSCompositeSourceOver
2408               fraction: 1.0
2409            respectFlipped: YES
2410                 hints: nil];
2411 #else
2412       {
2413         NSPoint pt = r.origin;
2414         pt.y += p->h;
2415         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2416       }
2417 #endif
2418     }
2419   ns_unfocus (f);
2423 static void
2424 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2425                        int x, int y, enum text_cursor_kinds cursor_type,
2426                        int cursor_width, bool on_p, bool active_p)
2427 /* --------------------------------------------------------------------------
2428      External call (RIF): draw cursor.
2429      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2430    -------------------------------------------------------------------------- */
2432   NSRect r, s;
2433   int fx, fy, h, cursor_height;
2434   struct frame *f = WINDOW_XFRAME (w);
2435   struct glyph *phys_cursor_glyph;
2436   struct glyph *cursor_glyph;
2437   struct face *face;
2438   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2440   /* If cursor is out of bounds, don't draw garbage.  This can happen
2441      in mini-buffer windows when switching between echo area glyphs
2442      and mini-buffer.  */
2444   NSTRACE (dumpcursor);
2446   if (!on_p)
2447     return;
2449   w->phys_cursor_type = cursor_type;
2450   w->phys_cursor_on_p = on_p;
2452   if (cursor_type == NO_CURSOR)
2453     {
2454       w->phys_cursor_width = 0;
2455       return;
2456     }
2458   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2459     {
2460       if (glyph_row->exact_window_width_line_p
2461           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2462         {
2463           glyph_row->cursor_in_fringe_p = 1;
2464           draw_fringe_bitmap (w, glyph_row, 0);
2465         }
2466       return;
2467     }
2469   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2470      (other terminals do it the other way round).  We must set
2471      w->phys_cursor_width to the cursor width.  For bar cursors, that
2472      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2473   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2475   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2476      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2477   if (cursor_type == BAR_CURSOR)
2478     {
2479       if (cursor_width < 1)
2480         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2481       w->phys_cursor_width = cursor_width;
2482     }
2483   /* If we have an HBAR, "cursor_width" MAY specify height. */
2484   else if (cursor_type == HBAR_CURSOR)
2485     {
2486       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2487       fy += h - cursor_height;
2488       h = cursor_height;
2489     }
2491   r.origin.x = fx, r.origin.y = fy;
2492   r.size.height = h;
2493   r.size.width = w->phys_cursor_width;
2495   /* TODO: only needed in rare cases with last-resort font in HELLO..
2496      should we do this more efficiently? */
2497   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2500   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2501   if (face && NS_FACE_BACKGROUND (face)
2502       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2503     {
2504       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2505       hollow_color = FRAME_CURSOR_COLOR (f);
2506     }
2507   else
2508     [FRAME_CURSOR_COLOR (f) set];
2510 #ifdef NS_IMPL_COCOA
2511   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2512            atomic.  Cleaner ways of doing this should be investigated.
2513            One way would be to set a global variable DRAWING_CURSOR
2514            when making the call to draw_phys..(), don't focus in that
2515            case, then move the ns_unfocus() here after that call. */
2516   NSDisableScreenUpdates ();
2517 #endif
2519   switch (cursor_type)
2520     {
2521     case NO_CURSOR:
2522       break;
2523     case FILLED_BOX_CURSOR:
2524       NSRectFill (r);
2525       break;
2526     case HOLLOW_BOX_CURSOR:
2527       NSRectFill (r);
2528       [hollow_color set];
2529       NSRectFill (NSInsetRect (r, 1, 1));
2530       [FRAME_CURSOR_COLOR (f) set];
2531       break;
2532     case HBAR_CURSOR:
2533       NSRectFill (r);
2534       break;
2535     case BAR_CURSOR:
2536       s = r;
2537       /* If the character under cursor is R2L, draw the bar cursor
2538          on the right of its glyph, rather than on the left.  */
2539       cursor_glyph = get_phys_cursor_glyph (w);
2540       if ((cursor_glyph->resolved_level & 1) != 0)
2541         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2543       NSRectFill (s);
2544       break;
2545     }
2546   ns_unfocus (f);
2548   /* draw the character under the cursor */
2549   if (cursor_type != NO_CURSOR)
2550     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2552 #ifdef NS_IMPL_COCOA
2553   NSEnableScreenUpdates ();
2554 #endif
2559 static void
2560 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2561 /* --------------------------------------------------------------------------
2562      External (RIF): Draw a vertical line.
2563    -------------------------------------------------------------------------- */
2565   struct frame *f = XFRAME (WINDOW_FRAME (w));
2566   struct face *face;
2567   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2569   NSTRACE (ns_draw_vertical_window_border);
2571   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2572   if (face)
2573       [ns_lookup_indexed_color(face->foreground, f) set];
2575   ns_focus (f, &r, 1);
2576   NSRectFill(r);
2577   ns_unfocus (f);
2581 static void
2582 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2583 /* --------------------------------------------------------------------------
2584      External (RIF): Draw a window divider.
2585    -------------------------------------------------------------------------- */
2587   struct frame *f = XFRAME (WINDOW_FRAME (w));
2588   struct face *face;
2589   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2591   NSTRACE (ns_draw_window_divider);
2593   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2594   if (face)
2595       [ns_lookup_indexed_color(face->foreground, f) set];
2597   ns_focus (f, &r, 1);
2598   NSRectFill(r);
2599   ns_unfocus (f);
2603 void
2604 show_hourglass (struct atimer *timer)
2606   if (hourglass_shown_p)
2607     return;
2609   block_input ();
2611   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2613   hourglass_shown_p = 1;
2614   unblock_input ();
2618 void
2619 hide_hourglass (void)
2621   if (!hourglass_shown_p)
2622     return;
2624   block_input ();
2626   /* TODO: remove NSProgressIndicator from all frames */
2628   hourglass_shown_p = 0;
2629   unblock_input ();
2634 /* ==========================================================================
2636     Glyph drawing operations
2638    ========================================================================== */
2640 static int
2641 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2642 /* --------------------------------------------------------------------------
2643     Wrapper utility to account for internal border width on full-width lines,
2644     and allow top full-width rows to hit the frame top.  nr should be pointer
2645     to two successive NSRects.  Number of rects actually used is returned.
2646    -------------------------------------------------------------------------- */
2648   int n = get_glyph_string_clip_rects (s, nr, 2);
2649   return n;
2652 /* --------------------------------------------------------------------
2653    Draw a wavy line under glyph string s. The wave fills wave_height
2654    pixels from y.
2656                     x          wave_length = 2
2657                                  --
2658                 y    *   *   *   *   *
2659                      |* * * * * * * * *
2660     wave_height = 3  | *   *   *   *
2661   --------------------------------------------------------------------- */
2663 static void
2664 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2666   int wave_height = 3, wave_length = 2;
2667   int y, dx, dy, odd, xmax;
2668   NSPoint a, b;
2669   NSRect waveClip;
2671   dx = wave_length;
2672   dy = wave_height - 1;
2673   y =  s->ybase - wave_height + 3;
2674   xmax = x + width;
2676   /* Find and set clipping rectangle */
2677   waveClip = NSMakeRect (x, y, width, wave_height);
2678   [[NSGraphicsContext currentContext] saveGraphicsState];
2679   NSRectClip (waveClip);
2681   /* Draw the waves */
2682   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2683   b.x = a.x + dx;
2684   odd = (int)(a.x/dx) % 2;
2685   a.y = b.y = y + 0.5;
2687   if (odd)
2688     a.y += dy;
2689   else
2690     b.y += dy;
2692   while (a.x <= xmax)
2693     {
2694       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2695       a.x = b.x, a.y = b.y;
2696       b.x += dx, b.y = y + 0.5 + odd*dy;
2697       odd = !odd;
2698     }
2700   /* Restore previous clipping rectangle(s) */
2701   [[NSGraphicsContext currentContext] restoreGraphicsState];
2706 void
2707 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2708                          NSColor *defaultCol, CGFloat width, CGFloat x)
2709 /* --------------------------------------------------------------------------
2710    Draw underline, overline, and strike-through on glyph string s.
2711    -------------------------------------------------------------------------- */
2713   if (s->for_overlaps)
2714     return;
2716   /* Do underline. */
2717   if (face->underline_p)
2718     {
2719       if (s->face->underline_type == FACE_UNDER_WAVE)
2720         {
2721           if (face->underline_defaulted_p)
2722             [defaultCol set];
2723           else
2724             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2726           ns_draw_underwave (s, width, x);
2727         }
2728       else if (s->face->underline_type == FACE_UNDER_LINE)
2729         {
2731           NSRect r;
2732           unsigned long thickness, position;
2734           /* If the prev was underlined, match its appearance. */
2735           if (s->prev && s->prev->face->underline_p
2736               && s->prev->face->underline_type == FACE_UNDER_LINE
2737               && s->prev->underline_thickness > 0)
2738             {
2739               thickness = s->prev->underline_thickness;
2740               position = s->prev->underline_position;
2741             }
2742           else
2743             {
2744               struct font *font;
2745               unsigned long descent;
2747               font=s->font;
2748               descent = s->y + s->height - s->ybase;
2750               /* Use underline thickness of font, defaulting to 1. */
2751               thickness = (font && font->underline_thickness > 0)
2752                 ? font->underline_thickness : 1;
2754               /* Determine the offset of underlining from the baseline. */
2755               if (x_underline_at_descent_line)
2756                 position = descent - thickness;
2757               else if (x_use_underline_position_properties
2758                        && font && font->underline_position >= 0)
2759                 position = font->underline_position;
2760               else if (font)
2761                 position = lround (font->descent / 2);
2762               else
2763                 position = underline_minimum_offset;
2765               position = max (position, underline_minimum_offset);
2767               /* Ensure underlining is not cropped. */
2768               if (descent <= position)
2769                 {
2770                   position = descent - 1;
2771                   thickness = 1;
2772                 }
2773               else if (descent < position + thickness)
2774                 thickness = 1;
2775             }
2777           s->underline_thickness = thickness;
2778           s->underline_position = position;
2780           r = NSMakeRect (x, s->ybase + position, width, thickness);
2782           if (face->underline_defaulted_p)
2783             [defaultCol set];
2784           else
2785             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2786           NSRectFill (r);
2787         }
2788     }
2789   /* Do overline. We follow other terms in using a thickness of 1
2790      and ignoring overline_margin. */
2791   if (face->overline_p)
2792     {
2793       NSRect r;
2794       r = NSMakeRect (x, s->y, width, 1);
2796       if (face->overline_color_defaulted_p)
2797         [defaultCol set];
2798       else
2799         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2800       NSRectFill (r);
2801     }
2803   /* Do strike-through.  We follow other terms for thickness and
2804      vertical position.*/
2805   if (face->strike_through_p)
2806     {
2807       NSRect r;
2808       unsigned long dy;
2810       dy = lrint ((s->height - 1) / 2);
2811       r = NSMakeRect (x, s->y + dy, width, 1);
2813       if (face->strike_through_color_defaulted_p)
2814         [defaultCol set];
2815       else
2816         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2817       NSRectFill (r);
2818     }
2821 static void
2822 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2823              char left_p, char right_p)
2824 /* --------------------------------------------------------------------------
2825     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2826     Note we can't just use an NSDrawRect command, because of the possibility
2827     of some sides not being drawn, and because the rect will be filled.
2828    -------------------------------------------------------------------------- */
2830   NSRect s = r;
2831   [col set];
2833   /* top, bottom */
2834   s.size.height = thickness;
2835   NSRectFill (s);
2836   s.origin.y += r.size.height - thickness;
2837   NSRectFill (s);
2839   s.size.height = r.size.height;
2840   s.origin.y = r.origin.y;
2842   /* left, right (optional) */
2843   s.size.width = thickness;
2844   if (left_p)
2845     NSRectFill (s);
2846   if (right_p)
2847     {
2848       s.origin.x += r.size.width - thickness;
2849       NSRectFill (s);
2850     }
2854 static void
2855 ns_draw_relief (NSRect r, int thickness, char raised_p,
2856                char top_p, char bottom_p, char left_p, char right_p,
2857                struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859     Draw a relief rect inside r, optionally leaving some sides open.
2860     Note we can't just use an NSDrawBezel command, because of the possibility
2861     of some sides not being drawn, and because the rect will be filled.
2862    -------------------------------------------------------------------------- */
2864   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2865   NSColor *newBaseCol = nil;
2866   NSRect sr = r;
2868   NSTRACE (ns_draw_relief);
2870   /* set up colors */
2872   if (s->face->use_box_color_for_shadows_p)
2873     {
2874       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2875     }
2876 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2877            && s->img->pixmap
2878            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2879        {
2880          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2881        } */
2882   else
2883     {
2884       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2885     }
2887   if (newBaseCol == nil)
2888     newBaseCol = [NSColor grayColor];
2890   if (newBaseCol != baseCol)  /* TODO: better check */
2891     {
2892       [baseCol release];
2893       baseCol = [newBaseCol retain];
2894       [lightCol release];
2895       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2896       [darkCol release];
2897       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2898     }
2900   [(raised_p ? lightCol : darkCol) set];
2902   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2904   /* top */
2905   sr.size.height = thickness;
2906   if (top_p) NSRectFill (sr);
2908   /* left */
2909   sr.size.height = r.size.height;
2910   sr.size.width = thickness;
2911   if (left_p) NSRectFill (sr);
2913   [(raised_p ? darkCol : lightCol) set];
2915   /* bottom */
2916   sr.size.width = r.size.width;
2917   sr.size.height = thickness;
2918   sr.origin.y += r.size.height - thickness;
2919   if (bottom_p) NSRectFill (sr);
2921   /* right */
2922   sr.size.height = r.size.height;
2923   sr.origin.y = r.origin.y;
2924   sr.size.width = thickness;
2925   sr.origin.x += r.size.width - thickness;
2926   if (right_p) NSRectFill (sr);
2930 static void
2931 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2932 /* --------------------------------------------------------------------------
2933       Function modeled after x_draw_glyph_string_box ().
2934       Sets up parameters for drawing.
2935    -------------------------------------------------------------------------- */
2937   int right_x, last_x;
2938   char left_p, right_p;
2939   struct glyph *last_glyph;
2940   NSRect r;
2941   int thickness;
2942   struct face *face;
2944   if (s->hl == DRAW_MOUSE_FACE)
2945     {
2946       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2947       if (!face)
2948         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2949     }
2950   else
2951     face = s->face;
2953   thickness = face->box_line_width;
2955   NSTRACE (ns_dumpglyphs_box_or_relief);
2957   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2958             ? WINDOW_RIGHT_EDGE_X (s->w)
2959             : window_box_right (s->w, s->area));
2960   last_glyph = (s->cmp || s->img
2961                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2963   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2964               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2966   left_p = (s->first_glyph->left_box_line_p
2967             || (s->hl == DRAW_MOUSE_FACE
2968                 && (s->prev == NULL || s->prev->hl != s->hl)));
2969   right_p = (last_glyph->right_box_line_p
2970              || (s->hl == DRAW_MOUSE_FACE
2971                  && (s->next == NULL || s->next->hl != s->hl)));
2973   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2975   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2976   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2977     {
2978       ns_draw_box (r, abs (thickness),
2979                    ns_lookup_indexed_color (face->box_color, s->f),
2980                   left_p, right_p);
2981     }
2982   else
2983     {
2984       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2985                      1, 1, left_p, right_p, s);
2986     }
2990 static void
2991 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2992 /* --------------------------------------------------------------------------
2993       Modeled after x_draw_glyph_string_background, which draws BG in
2994       certain cases.  Others are left to the text rendering routine.
2995    -------------------------------------------------------------------------- */
2997   NSTRACE (ns_maybe_dumpglyphs_background);
2999   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3000     {
3001       int box_line_width = max (s->face->box_line_width, 0);
3002       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3003           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3004         {
3005           struct face *face;
3006           if (s->hl == DRAW_MOUSE_FACE)
3007             {
3008               face = FACE_FROM_ID (s->f,
3009                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3010               if (!face)
3011                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3012             }
3013           else
3014             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3015           if (!face->stipple)
3016             [(NS_FACE_BACKGROUND (face) != 0
3017               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3018               : FRAME_BACKGROUND_COLOR (s->f)) set];
3019           else
3020             {
3021               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3022               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3023             }
3025           if (s->hl != DRAW_CURSOR)
3026             {
3027               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3028                                     s->background_width,
3029                                     s->height-2*box_line_width);
3030               NSRectFill (r);
3031             }
3033           s->background_filled_p = 1;
3034         }
3035     }
3039 static void
3040 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3041 /* --------------------------------------------------------------------------
3042       Renders an image and associated borders.
3043    -------------------------------------------------------------------------- */
3045   EmacsImage *img = s->img->pixmap;
3046   int box_line_vwidth = max (s->face->box_line_width, 0);
3047   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3048   int bg_x, bg_y, bg_height;
3049   int th;
3050   char raised_p;
3051   NSRect br;
3052   struct face *face;
3053   NSColor *tdCol;
3055   NSTRACE (ns_dumpglyphs_image);
3057   if (s->face->box != FACE_NO_BOX
3058       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3059     x += abs (s->face->box_line_width);
3061   bg_x = x;
3062   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3063   bg_height = s->height;
3064   /* other terms have this, but was causing problems w/tabbar mode */
3065   /* - 2 * box_line_vwidth; */
3067   if (s->slice.x == 0) x += s->img->hmargin;
3068   if (s->slice.y == 0) y += s->img->vmargin;
3070   /* Draw BG: if we need larger area than image itself cleared, do that,
3071      otherwise, since we composite the image under NS (instead of mucking
3072      with its background color), we must clear just the image area. */
3073   if (s->hl == DRAW_MOUSE_FACE)
3074     {
3075       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3076       if (!face)
3077        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3078     }
3079   else
3080     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3082   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3084   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3085       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3086     {
3087       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3088       s->background_filled_p = 1;
3089     }
3090   else
3091     {
3092       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3093     }
3095   NSRectFill (br);
3097   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3098   if (img != nil)
3099     {
3100 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
3101       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3102       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3103                               s->slice.width, s->slice.height);
3104       [img drawInRect: dr
3105              fromRect: ir
3106              operation: NSCompositeSourceOver
3107               fraction: 1.0
3108            respectFlipped: YES
3109                 hints: nil];
3110 #else
3111       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3112                   operation: NSCompositeSourceOver];
3113 #endif
3114     }
3116   if (s->hl == DRAW_CURSOR)
3117     {
3118     [FRAME_CURSOR_COLOR (s->f) set];
3119     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3120       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3121     else
3122       /* Currently on NS img->mask is always 0. Since
3123          get_window_cursor_type specifies a hollow box cursor when on
3124          a non-masked image we never reach this clause. But we put it
3125          in in anticipation of better support for image masks on
3126          NS. */
3127       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3128     }
3129   else
3130     {
3131       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3132     }
3134   /* Draw underline, overline, strike-through. */
3135   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3137   /* Draw relief, if requested */
3138   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3139     {
3140       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3141         {
3142           th = tool_bar_button_relief >= 0 ?
3143             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3144           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3145         }
3146       else
3147         {
3148           th = abs (s->img->relief);
3149           raised_p = (s->img->relief > 0);
3150         }
3152       r.origin.x = x - th;
3153       r.origin.y = y - th;
3154       r.size.width = s->slice.width + 2*th-1;
3155       r.size.height = s->slice.height + 2*th-1;
3156       ns_draw_relief (r, th, raised_p,
3157                       s->slice.y == 0,
3158                       s->slice.y + s->slice.height == s->img->height,
3159                       s->slice.x == 0,
3160                       s->slice.x + s->slice.width == s->img->width, s);
3161     }
3163   /* If there is no mask, the background won't be seen,
3164      so draw a rectangle on the image for the cursor.
3165      Do this for all images, getting transparency right is not reliable.  */
3166   if (s->hl == DRAW_CURSOR)
3167     {
3168       int thickness = abs (s->img->relief);
3169       if (thickness == 0) thickness = 1;
3170       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3171     }
3175 static void
3176 ns_dumpglyphs_stretch (struct glyph_string *s)
3178   NSRect r[2];
3179   int n, i;
3180   struct face *face;
3181   NSColor *fgCol, *bgCol;
3183   if (!s->background_filled_p)
3184     {
3185       n = ns_get_glyph_string_clip_rect (s, r);
3186       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3188       ns_focus (s->f, r, n);
3190       if (s->hl == DRAW_MOUSE_FACE)
3191        {
3192          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3193          if (!face)
3194            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3195        }
3196       else
3197        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3199       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3200       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3202       for (i = 0; i < n; ++i)
3203         {
3204           if (!s->row->full_width_p)
3205             {
3206               int overrun, leftoverrun;
3208               /* truncate to avoid overwriting fringe and/or scrollbar */
3209               overrun = max (0, (s->x + s->background_width)
3210                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3211                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3212               r[i].size.width -= overrun;
3214               /* truncate to avoid overwriting to left of the window box */
3215               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3216                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3218               if (leftoverrun > 0)
3219                 {
3220                   r[i].origin.x += leftoverrun;
3221                   r[i].size.width -= leftoverrun;
3222                 }
3224               /* XXX: Try to work between problem where a stretch glyph on
3225                  a partially-visible bottom row will clear part of the
3226                  modeline, and another where list-buffers headers and similar
3227                  rows erroneously have visible_height set to 0.  Not sure
3228                  where this is coming from as other terms seem not to show. */
3229               r[i].size.height = min (s->height, s->row->visible_height);
3230             }
3232           [bgCol set];
3234           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3235              overwriting cursor (usually when cursor on a tab) */
3236           if (s->hl == DRAW_CURSOR)
3237             {
3238               CGFloat x, width;
3240               x = r[i].origin.x;
3241               width = s->w->phys_cursor_width;
3242               r[i].size.width -= width;
3243               r[i].origin.x += width;
3245               NSRectFill (r[i]);
3247               /* Draw overlining, etc. on the cursor. */
3248               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3249                 ns_draw_text_decoration (s, face, bgCol, width, x);
3250               else
3251                 ns_draw_text_decoration (s, face, fgCol, width, x);
3252             }
3253           else
3254             {
3255               NSRectFill (r[i]);
3256             }
3258           /* Draw overlining, etc. on the stretch glyph (or the part
3259              of the stretch glyph after the cursor). */
3260           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3261                                    r[i].origin.x);
3262         }
3263       ns_unfocus (s->f);
3264       s->background_filled_p = 1;
3265     }
3269 static void
3270 ns_draw_glyph_string (struct glyph_string *s)
3271 /* --------------------------------------------------------------------------
3272       External (RIF): Main draw-text call.
3273    -------------------------------------------------------------------------- */
3275   /* TODO (optimize): focus for box and contents draw */
3276   NSRect r[2];
3277   int n, flags;
3278   char box_drawn_p = 0;
3279   struct font *font = s->face->font;
3280   if (! font) font = FRAME_FONT (s->f);
3282   NSTRACE (ns_draw_glyph_string);
3284   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3285     {
3286       int width;
3287       struct glyph_string *next;
3289       for (width = 0, next = s->next;
3290            next && width < s->right_overhang;
3291            width += next->width, next = next->next)
3292         if (next->first_glyph->type != IMAGE_GLYPH)
3293           {
3294             if (next->first_glyph->type != STRETCH_GLYPH)
3295               {
3296                 n = ns_get_glyph_string_clip_rect (s->next, r);
3297                 ns_focus (s->f, r, n);
3298                 ns_maybe_dumpglyphs_background (s->next, 1);
3299                 ns_unfocus (s->f);
3300               }
3301             else
3302               {
3303                 ns_dumpglyphs_stretch (s->next);
3304               }
3305             next->num_clips = 0;
3306           }
3307     }
3309   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3310         && (s->first_glyph->type == CHAR_GLYPH
3311             || s->first_glyph->type == COMPOSITE_GLYPH))
3312     {
3313       n = ns_get_glyph_string_clip_rect (s, r);
3314       ns_focus (s->f, r, n);
3315       ns_maybe_dumpglyphs_background (s, 1);
3316       ns_dumpglyphs_box_or_relief (s);
3317       ns_unfocus (s->f);
3318       box_drawn_p = 1;
3319     }
3321   switch (s->first_glyph->type)
3322     {
3324     case IMAGE_GLYPH:
3325       n = ns_get_glyph_string_clip_rect (s, r);
3326       ns_focus (s->f, r, n);
3327       ns_dumpglyphs_image (s, r[0]);
3328       ns_unfocus (s->f);
3329       break;
3331     case STRETCH_GLYPH:
3332       ns_dumpglyphs_stretch (s);
3333       break;
3335     case CHAR_GLYPH:
3336     case COMPOSITE_GLYPH:
3337       n = ns_get_glyph_string_clip_rect (s, r);
3338       ns_focus (s->f, r, n);
3340       if (s->for_overlaps || (s->cmp_from > 0
3341                               && ! s->first_glyph->u.cmp.automatic))
3342         s->background_filled_p = 1;
3343       else
3344         ns_maybe_dumpglyphs_background
3345           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3347       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3348         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3349          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3350           NS_DUMPGLYPH_NORMAL));
3352       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3353         {
3354           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3355           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3356           NS_FACE_FOREGROUND (s->face) = tmp;
3357         }
3359       font->driver->draw
3360         (s, 0, s->nchars, s->x, s->y,
3361          (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3362          || flags == NS_DUMPGLYPH_MOUSEFACE);
3364       {
3365         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3366                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3367                                                    s->f)
3368                         : FRAME_FOREGROUND_COLOR (s->f));
3369         [col set];
3371         /* Draw underline, overline, strike-through. */
3372         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3373       }
3375       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3376         {
3377           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3378           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3379           NS_FACE_FOREGROUND (s->face) = tmp;
3380         }
3382       ns_unfocus (s->f);
3383       break;
3385     case GLYPHLESS_GLYPH:
3386       n = ns_get_glyph_string_clip_rect (s, r);
3387       ns_focus (s->f, r, n);
3389       if (s->for_overlaps || (s->cmp_from > 0
3390                               && ! s->first_glyph->u.cmp.automatic))
3391         s->background_filled_p = 1;
3392       else
3393         ns_maybe_dumpglyphs_background
3394           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3395       /* ... */
3396       /* Not yet implemented.  */
3397       /* ... */
3398       ns_unfocus (s->f);
3399       break;
3401     default:
3402       emacs_abort ();
3403     }
3405   /* Draw box if not done already. */
3406   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3407     {
3408       n = ns_get_glyph_string_clip_rect (s, r);
3409       ns_focus (s->f, r, n);
3410       ns_dumpglyphs_box_or_relief (s);
3411       ns_unfocus (s->f);
3412     }
3414   s->num_clips = 0;
3419 /* ==========================================================================
3421     Event loop
3423    ========================================================================== */
3426 static void
3427 ns_send_appdefined (int value)
3428 /* --------------------------------------------------------------------------
3429     Internal: post an appdefined event which EmacsApp-sendEvent will
3430               recognize and take as a command to halt the event loop.
3431    -------------------------------------------------------------------------- */
3433   /*NSTRACE (ns_send_appdefined); */
3435 #ifdef NS_IMPL_GNUSTEP
3436   // GNUstep needs postEvent to happen on the main thread.
3437   if (! [[NSThread currentThread] isMainThread])
3438     {
3439       EmacsApp *app = (EmacsApp *)NSApp;
3440       app->nextappdefined = value;
3441       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3442                             withObject:nil
3443                          waitUntilDone:YES];
3444       return;
3445     }
3446 #endif
3448   /* Only post this event if we haven't already posted one.  This will end
3449        the [NXApp run] main loop after having processed all events queued at
3450        this moment.  */
3452 #ifdef NS_IMPL_COCOA
3453   if (! send_appdefined)
3454     {
3455       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3456          in certain situations (rapid incoming events).
3457          So check if we have one, if not add one.  */
3458       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3459                                           untilDate:[NSDate distantPast]
3460                                              inMode:NSDefaultRunLoopMode
3461                                             dequeue:NO];
3462       if (! appev) send_appdefined = YES;
3463     }
3464 #endif
3466   if (send_appdefined)
3467     {
3468       NSEvent *nxev;
3470       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3471       send_appdefined = NO;
3473       /* Don't need wakeup timer any more */
3474       if (timed_entry)
3475         {
3476           [timed_entry invalidate];
3477           [timed_entry release];
3478           timed_entry = nil;
3479         }
3481       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3482                                 location: NSMakePoint (0, 0)
3483                            modifierFlags: 0
3484                                timestamp: 0
3485                             windowNumber: [[NSApp mainWindow] windowNumber]
3486                                  context: [NSApp context]
3487                                  subtype: 0
3488                                    data1: value
3489                                    data2: 0];
3491       /* Post an application defined event on the event queue.  When this is
3492          received the [NXApp run] will return, thus having processed all
3493          events which are currently queued.  */
3494       [NSApp postEvent: nxev atStart: NO];
3495     }
3498 #ifdef HAVE_NATIVE_FS
3499 static void
3500 check_native_fs ()
3502   Lisp_Object frame, tail;
3504   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3505     return;
3507   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3509   FOR_EACH_FRAME (tail, frame)
3510     {
3511       struct frame *f = XFRAME (frame);
3512       if (FRAME_NS_P (f))
3513         {
3514           EmacsView *view = FRAME_NS_VIEW (f);
3515           [view updateCollectionBehavior];
3516         }
3517     }
3519 #endif
3521 /* GNUstep and OSX <= 10.4 does not have cancelTracking.  */
3522 #if defined (NS_IMPL_COCOA) && \
3523   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
3524 /* Check if menu open should be canceled or continued as normal.  */
3525 void
3526 ns_check_menu_open (NSMenu *menu)
3528   /* Click in menu bar? */
3529   NSArray *a = [[NSApp mainMenu] itemArray];
3530   int i;
3531   BOOL found = NO;
3533   if (menu == nil) // Menu tracking ended.
3534     {
3535       if (menu_will_open_state == MENU_OPENING)
3536         menu_will_open_state = MENU_NONE;
3537       return;
3538     }
3540   for (i = 0; ! found && i < [a count]; i++)
3541     found = menu == [[a objectAtIndex:i] submenu];
3542   if (found)
3543     {
3544       if (menu_will_open_state == MENU_NONE && emacs_event)
3545         {
3546           NSEvent *theEvent = [NSApp currentEvent];
3547           struct frame *emacsframe = SELECTED_FRAME ();
3549           [menu cancelTracking];
3550           menu_will_open_state = MENU_PENDING;
3551           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3552           EV_TRAILER (theEvent);
3554           CGEventRef ourEvent = CGEventCreate (NULL);
3555           menu_mouse_point = CGEventGetLocation (ourEvent);
3556           CFRelease (ourEvent);
3557         }
3558       else if (menu_will_open_state == MENU_OPENING)
3559         {
3560           menu_will_open_state = MENU_NONE;
3561         }
3562     }
3565 /* Redo saved menu click if state is MENU_PENDING.  */
3566 void
3567 ns_check_pending_open_menu ()
3569   if (menu_will_open_state == MENU_PENDING)
3570     {
3571       CGEventSourceRef source
3572         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3574       CGEventRef event = CGEventCreateMouseEvent (source,
3575                                                   kCGEventLeftMouseDown,
3576                                                   menu_mouse_point,
3577                                                   kCGMouseButtonLeft);
3578       CGEventSetType (event, kCGEventLeftMouseDown);
3579       CGEventPost (kCGHIDEventTap, event);
3580       CFRelease (event);
3581       CFRelease (source);
3583       menu_will_open_state = MENU_OPENING;
3584     }
3586 #endif /* NS_IMPL_COCOA) && >= MAC_OS_X_VERSION_10_5 */
3588 static int
3589 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3590 /* --------------------------------------------------------------------------
3591      External (hook): Post an event to ourself and keep reading events until
3592      we read it back again.  In effect process all events which were waiting.
3593      From 21+ we have to manage the event buffer ourselves.
3594    -------------------------------------------------------------------------- */
3596   struct input_event ev;
3597   int nevents;
3599 /* NSTRACE (ns_read_socket); */
3601 #ifdef HAVE_NATIVE_FS
3602   check_native_fs ();
3603 #endif
3605   if ([NSApp modalWindow] != nil)
3606     return -1;
3608   if (hold_event_q.nr > 0)
3609     {
3610       int i;
3611       for (i = 0; i < hold_event_q.nr; ++i)
3612         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3613       hold_event_q.nr = 0;
3614       return i;
3615     }
3617   block_input ();
3618   n_emacs_events_pending = 0;
3619   EVENT_INIT (ev);
3620   emacs_event = &ev;
3621   q_event_ptr = hold_quit;
3623   /* we manage autorelease pools by allocate/reallocate each time around
3624      the loop; strict nesting is occasionally violated but seems not to
3625      matter.. earlier methods using full nesting caused major memory leaks */
3626   [outerpool release];
3627   outerpool = [[NSAutoreleasePool alloc] init];
3629   /* If have pending open-file requests, attend to the next one of those. */
3630   if (ns_pending_files && [ns_pending_files count] != 0
3631       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3632     {
3633       [ns_pending_files removeObjectAtIndex: 0];
3634     }
3635   /* Deal with pending service requests. */
3636   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3637     && [(EmacsApp *)
3638          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3639                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3640     {
3641       [ns_pending_service_names removeObjectAtIndex: 0];
3642       [ns_pending_service_args removeObjectAtIndex: 0];
3643     }
3644   else
3645     {
3646       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3647          to ourself, otherwise [NXApp run] will never exit.  */
3648       send_appdefined = YES;
3649       ns_send_appdefined (-1);
3651       if (++apploopnr != 1)
3652         {
3653           emacs_abort ();
3654         }
3655       [NSApp run];
3656       --apploopnr;
3657     }
3659   nevents = n_emacs_events_pending;
3660   n_emacs_events_pending = 0;
3661   emacs_event = q_event_ptr = NULL;
3662   unblock_input ();
3664   return nevents;
3669 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3670            fd_set *exceptfds, struct timespec const *timeout,
3671            sigset_t const *sigmask)
3672 /* --------------------------------------------------------------------------
3673      Replacement for select, checking for events
3674    -------------------------------------------------------------------------- */
3676   int result;
3677   int t, k, nr = 0;
3678   struct input_event event;
3679   char c;
3681 /*  NSTRACE (ns_select); */
3683 #ifdef HAVE_NATIVE_FS
3684   check_native_fs ();
3685 #endif
3687   if (hold_event_q.nr > 0)
3688     {
3689       /* We already have events pending. */
3690       raise (SIGIO);
3691       errno = EINTR;
3692       return -1;
3693     }
3695   for (k = 0; k < nfds+1; k++)
3696     {
3697       if (readfds && FD_ISSET(k, readfds)) ++nr;
3698       if (writefds && FD_ISSET(k, writefds)) ++nr;
3699     }
3701   if (NSApp == nil
3702       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3703     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3705   [outerpool release];
3706   outerpool = [[NSAutoreleasePool alloc] init];
3709   send_appdefined = YES;
3710   if (nr > 0)
3711     {
3712       pthread_mutex_lock (&select_mutex);
3713       select_nfds = nfds;
3714       select_valid = 0;
3715       if (readfds)
3716         {
3717           select_readfds = *readfds;
3718           select_valid += SELECT_HAVE_READ;
3719         }
3720       if (writefds)
3721         {
3722           select_writefds = *writefds;
3723           select_valid += SELECT_HAVE_WRITE;
3724         }
3726       if (timeout)
3727         {
3728           select_timeout = *timeout;
3729           select_valid += SELECT_HAVE_TMO;
3730         }
3732       pthread_mutex_unlock (&select_mutex);
3734       /* Inform fd_handler that select should be called */
3735       c = 'g';
3736       emacs_write_sig (selfds[1], &c, 1);
3737     }
3738   else if (nr == 0 && timeout)
3739     {
3740       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3741       double time = timespectod (*timeout);
3742       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3743                                                       target: NSApp
3744                                                     selector:
3745                                   @selector (timeout_handler:)
3746                                                     userInfo: 0
3747                                                      repeats: NO]
3748                       retain];
3749     }
3750   else /* No timeout and no file descriptors, can this happen?  */
3751     {
3752       /* Send appdefined so we exit from the loop */
3753       ns_send_appdefined (-1);
3754     }
3756   EVENT_INIT (event);
3757   block_input ();
3758   emacs_event = &event;
3759   if (++apploopnr != 1)
3760     {
3761       emacs_abort ();
3762     }
3763   [NSApp run];
3764   --apploopnr;
3765   emacs_event = NULL;
3766   if (nr > 0 && readfds)
3767     {
3768       c = 's';
3769       emacs_write_sig (selfds[1], &c, 1);
3770     }
3771   unblock_input ();
3773   t = last_appdefined_event_data;
3775   if (t != NO_APPDEFINED_DATA)
3776     {
3777       last_appdefined_event_data = NO_APPDEFINED_DATA;
3779       if (t == -2)
3780         {
3781           /* The NX_APPDEFINED event we received was a timeout. */
3782           result = 0;
3783         }
3784       else if (t == -1)
3785         {
3786           /* The NX_APPDEFINED event we received was the result of
3787              at least one real input event arriving.  */
3788           errno = EINTR;
3789           result = -1;
3790         }
3791       else
3792         {
3793           /* Received back from select () in fd_handler; copy the results */
3794           pthread_mutex_lock (&select_mutex);
3795           if (readfds) *readfds = select_readfds;
3796           if (writefds) *writefds = select_writefds;
3797           pthread_mutex_unlock (&select_mutex);
3798           result = t;
3799         }
3800     }
3801   else
3802     {
3803       errno = EINTR;
3804       result = -1;
3805     }
3807   return result;
3812 /* ==========================================================================
3814     Scrollbar handling
3816    ========================================================================== */
3819 static void
3820 ns_set_vertical_scroll_bar (struct window *window,
3821                            int portion, int whole, int position)
3822 /* --------------------------------------------------------------------------
3823       External (hook): Update or add scrollbar
3824    -------------------------------------------------------------------------- */
3826   Lisp_Object win;
3827   NSRect r, v;
3828   struct frame *f = XFRAME (WINDOW_FRAME (window));
3829   EmacsView *view = FRAME_NS_VIEW (f);
3830   int window_y, window_height;
3831   int top, left, height, width, sb_width, sb_left;
3832   EmacsScroller *bar;
3833   BOOL fringe_extended_p;
3834   BOOL update_p = YES;
3836   /* optimization; display engine sends WAY too many of these.. */
3837   if (!NILP (window->vertical_scroll_bar))
3838     {
3839       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3840       if ([bar checkSamePosition: position portion: portion whole: whole])
3841         {
3842           if (view->scrollbarsNeedingUpdate == 0)
3843             {
3844               if (!windows_or_buffers_changed)
3845                   return;
3846             }
3847           else
3848             view->scrollbarsNeedingUpdate--;
3849           update_p = NO;
3850         }
3851     }
3853   NSTRACE (ns_set_vertical_scroll_bar);
3855   /* Get dimensions.  */
3856   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3857   top = window_y;
3858   height = window_height;
3859   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3860   left = WINDOW_SCROLL_BAR_AREA_X (window);
3862   /* allow for displaying a skinnier scrollbar than char area allotted */
3863   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3864     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3865   sb_left = left;
3867   r = NSMakeRect (sb_left, top, sb_width, height);
3868   /* the parent view is flipped, so we need to flip y value */
3869   v = [view frame];
3870   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3872   fringe_extended_p = WINDOW_FRINGE_EXTENDED_P (window);
3874   XSETWINDOW (win, window);
3875   block_input ();
3877   /* we want at least 5 lines to display a scrollbar */
3878   if (WINDOW_TOTAL_LINES (window) < 5)
3879     {
3880       if (!NILP (window->vertical_scroll_bar))
3881         {
3882           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3883           [bar removeFromSuperview];
3884           wset_vertical_scroll_bar (window, Qnil);
3885           [bar release];
3886         }
3887       ns_clear_frame_area (f, sb_left, top, width, height);
3888       unblock_input ();
3889       return;
3890     }
3892   if (NILP (window->vertical_scroll_bar))
3893     {
3894       if (width > 0 && height > 0)
3895         {
3896           if (fringe_extended_p)
3897             ns_clear_frame_area (f, sb_left, top, sb_width, height);
3898           else
3899             ns_clear_frame_area (f, left, top, width, height);
3900         }
3902       bar = [[EmacsScroller alloc] initFrame: r window: win];
3903       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3904       update_p = YES;
3905     }
3906   else
3907     {
3908       NSRect oldRect;
3909       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3910       oldRect = [bar frame];
3911       r.size.width = oldRect.size.width;
3912       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3913         {
3914           if (oldRect.origin.x != r.origin.x)
3915               ns_clear_frame_area (f, sb_left, top, width, height);
3916           [bar setFrame: r];
3917           update_p = YES;
3918         }
3919     }
3921   if (update_p)
3922     [bar setPosition: position portion: portion whole: whole];
3923   unblock_input ();
3927 static void
3928 ns_condemn_scroll_bars (struct frame *f)
3929 /* --------------------------------------------------------------------------
3930      External (hook): arrange for all frame's scrollbars to be removed
3931      at next call to judge_scroll_bars, except for those redeemed.
3932    -------------------------------------------------------------------------- */
3934   int i;
3935   id view;
3936   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3938   NSTRACE (ns_condemn_scroll_bars);
3940   for (i =[subviews count]-1; i >= 0; i--)
3941     {
3942       view = [subviews objectAtIndex: i];
3943       if ([view isKindOfClass: [EmacsScroller class]])
3944         [view condemn];
3945     }
3949 static void
3950 ns_redeem_scroll_bar (struct window *window)
3951 /* --------------------------------------------------------------------------
3952      External (hook): arrange to spare this window's scrollbar
3953      at next call to judge_scroll_bars.
3954    -------------------------------------------------------------------------- */
3956   id bar;
3957   NSTRACE (ns_redeem_scroll_bar);
3958   if (!NILP (window->vertical_scroll_bar))
3959     {
3960       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3961       [bar reprieve];
3962     }
3966 static void
3967 ns_judge_scroll_bars (struct frame *f)
3968 /* --------------------------------------------------------------------------
3969      External (hook): destroy all scrollbars on frame that weren't
3970      redeemed after call to condemn_scroll_bars.
3971    -------------------------------------------------------------------------- */
3973   int i;
3974   id view;
3975   EmacsView *eview = FRAME_NS_VIEW (f);
3976   NSArray *subviews = [[eview superview] subviews];
3977   BOOL removed = NO;
3979   NSTRACE (ns_judge_scroll_bars);
3980   for (i = [subviews count]-1; i >= 0; --i)
3981     {
3982       view = [subviews objectAtIndex: i];
3983       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3984       if ([view judge])
3985         removed = YES;
3986     }
3988   if (removed)
3989     [eview updateFrameSize: NO];
3992 /* ==========================================================================
3994     Initialization
3996    ========================================================================== */
3999 x_display_pixel_height (struct ns_display_info *dpyinfo)
4001   NSArray *screens = [NSScreen screens];
4002   NSEnumerator *enumerator = [screens objectEnumerator];
4003   NSScreen *screen;
4004   NSRect frame;
4006   frame = NSZeroRect;
4007   while ((screen = [enumerator nextObject]) != nil)
4008     frame = NSUnionRect (frame, [screen frame]);
4010   return NSHeight (frame);
4014 x_display_pixel_width (struct ns_display_info *dpyinfo)
4016   NSArray *screens = [NSScreen screens];
4017   NSEnumerator *enumerator = [screens objectEnumerator];
4018   NSScreen *screen;
4019   NSRect frame;
4021   frame = NSZeroRect;
4022   while ((screen = [enumerator nextObject]) != nil)
4023     frame = NSUnionRect (frame, [screen frame]);
4025   return NSWidth (frame);
4029 static Lisp_Object ns_string_to_lispmod (const char *s)
4030 /* --------------------------------------------------------------------------
4031      Convert modifier name to lisp symbol
4032    -------------------------------------------------------------------------- */
4034   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4035     return Qmeta;
4036   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4037     return Qsuper;
4038   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4039     return Qcontrol;
4040   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4041     return Qalt;
4042   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4043     return Qhyper;
4044   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4045     return Qnone;
4046   else
4047     return Qnil;
4051 static void
4052 ns_default (const char *parameter, Lisp_Object *result,
4053            Lisp_Object yesval, Lisp_Object noval,
4054            BOOL is_float, BOOL is_modstring)
4055 /* --------------------------------------------------------------------------
4056       Check a parameter value in user's preferences
4057    -------------------------------------------------------------------------- */
4059   const char *value = ns_get_defaults_value (parameter);
4061   if (value)
4062     {
4063       double f;
4064       char *pos;
4065       if (c_strcasecmp (value, "YES") == 0)
4066         *result = yesval;
4067       else if (c_strcasecmp (value, "NO") == 0)
4068         *result = noval;
4069       else if (is_float && (f = strtod (value, &pos), pos != value))
4070         *result = make_float (f);
4071       else if (is_modstring && value)
4072         *result = ns_string_to_lispmod (value);
4073       else fprintf (stderr,
4074                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4075     }
4079 static void
4080 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4081 /* --------------------------------------------------------------------------
4082       Initialize global info and storage for display.
4083    -------------------------------------------------------------------------- */
4085     NSScreen *screen = [NSScreen mainScreen];
4086     NSWindowDepth depth = [screen depth];
4088     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4089     dpyinfo->resy = 72.27;
4090     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4091                                                   NSColorSpaceFromDepth (depth)]
4092                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4093                                                  NSColorSpaceFromDepth (depth)];
4094     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4095     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4096     dpyinfo->color_table->colors = NULL;
4097     dpyinfo->root_window = 42; /* a placeholder.. */
4098     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4099     dpyinfo->n_fonts = 0;
4100     dpyinfo->smallest_font_height = 1;
4101     dpyinfo->smallest_char_width = 1;
4103     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4107 /* This and next define (many of the) public functions in this file. */
4108 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4109          with using despite presence in the "system dependent" redisplay
4110          interface.  In addition, many of the ns_ methods have code that is
4111          shared with all terms, indicating need for further refactoring. */
4112 extern frame_parm_handler ns_frame_parm_handlers[];
4113 static struct redisplay_interface ns_redisplay_interface =
4115   ns_frame_parm_handlers,
4116   x_produce_glyphs,
4117   x_write_glyphs,
4118   x_insert_glyphs,
4119   x_clear_end_of_line,
4120   ns_scroll_run,
4121   ns_after_update_window_line,
4122   ns_update_window_begin,
4123   ns_update_window_end,
4124   0, /* flush_display */
4125   x_clear_window_mouse_face,
4126   x_get_glyph_overhangs,
4127   x_fix_overlapping_area,
4128   ns_draw_fringe_bitmap,
4129   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4130   0, /* destroy_fringe_bitmap */
4131   ns_compute_glyph_string_overhangs,
4132   ns_draw_glyph_string,
4133   ns_define_frame_cursor,
4134   ns_clear_frame_area,
4135   ns_draw_window_cursor,
4136   ns_draw_vertical_window_border,
4137   ns_draw_window_divider,
4138   ns_shift_glyphs_for_insert
4142 static void
4143 ns_delete_display (struct ns_display_info *dpyinfo)
4145   /* TODO... */
4149 /* This function is called when the last frame on a display is deleted. */
4150 static void
4151 ns_delete_terminal (struct terminal *terminal)
4153   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4155   /* Protect against recursive calls.  delete_frame in
4156      delete_terminal calls us back when it deletes our last frame.  */
4157   if (!terminal->name)
4158     return;
4160   block_input ();
4162   x_destroy_all_bitmaps (dpyinfo);
4163   ns_delete_display (dpyinfo);
4164   unblock_input ();
4168 static struct terminal *
4169 ns_create_terminal (struct ns_display_info *dpyinfo)
4170 /* --------------------------------------------------------------------------
4171       Set up use of NS before we make the first connection.
4172    -------------------------------------------------------------------------- */
4174   struct terminal *terminal;
4176   NSTRACE (ns_create_terminal);
4178   terminal = create_terminal ();
4180   terminal->type = output_ns;
4181   terminal->display_info.ns = dpyinfo;
4182   dpyinfo->terminal = terminal;
4184   terminal->rif = &ns_redisplay_interface;
4186   terminal->clear_frame_hook = ns_clear_frame;
4187   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
4188   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
4189   terminal->ring_bell_hook = ns_ring_bell;
4190   terminal->reset_terminal_modes_hook = NULL;
4191   terminal->set_terminal_modes_hook = NULL;
4192   terminal->update_begin_hook = ns_update_begin;
4193   terminal->update_end_hook = ns_update_end;
4194   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
4195   terminal->read_socket_hook = ns_read_socket;
4196   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4197   terminal->mouse_position_hook = ns_mouse_position;
4198   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4199   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4201   terminal->fullscreen_hook = ns_fullscreen_hook;
4203   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4204   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4205   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4206   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4208   terminal->delete_frame_hook = x_destroy_window;
4209   terminal->delete_terminal_hook = ns_delete_terminal;
4211   return terminal;
4215 struct ns_display_info *
4216 ns_term_init (Lisp_Object display_name)
4217 /* --------------------------------------------------------------------------
4218      Start the Application and get things rolling.
4219    -------------------------------------------------------------------------- */
4221   struct terminal *terminal;
4222   struct ns_display_info *dpyinfo;
4223   static int ns_initialized = 0;
4224   Lisp_Object tmp;
4226   if (ns_initialized) return x_display_list;
4227   ns_initialized = 1;
4229   NSTRACE (ns_term_init);
4231   [outerpool release];
4232   outerpool = [[NSAutoreleasePool alloc] init];
4234   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4235   /*GSDebugAllocationActive (YES); */
4236   block_input ();
4238   baud_rate = 38400;
4239   Fset_input_interrupt_mode (Qnil);
4241   if (selfds[0] == -1)
4242     {
4243       if (emacs_pipe (selfds) != 0)
4244         {
4245           fprintf (stderr, "Failed to create pipe: %s\n",
4246                    emacs_strerror (errno));
4247           emacs_abort ();
4248         }
4250       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4251       FD_ZERO (&select_readfds);
4252       FD_ZERO (&select_writefds);
4253       pthread_mutex_init (&select_mutex, NULL);
4254     }
4256   ns_pending_files = [[NSMutableArray alloc] init];
4257   ns_pending_service_names = [[NSMutableArray alloc] init];
4258   ns_pending_service_args = [[NSMutableArray alloc] init];
4260 /* Start app and create the main menu, window, view.
4261      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4262      The view will then ask the NSApp to stop and return to Emacs. */
4263   [EmacsApp sharedApplication];
4264   if (NSApp == nil)
4265     return NULL;
4266   [NSApp setDelegate: NSApp];
4268   /* Start the select thread.  */
4269   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4270                            toTarget:NSApp
4271                          withObject:nil];
4273   /* debugging: log all notifications */
4274   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4275                                          selector: @selector (logNotification:)
4276                                              name: nil object: nil]; */
4278   dpyinfo = xzalloc (sizeof *dpyinfo);
4280   ns_initialize_display_info (dpyinfo);
4281   terminal = ns_create_terminal (dpyinfo);
4283   terminal->kboard = allocate_kboard (Qns);
4284   /* Don't let the initial kboard remain current longer than necessary.
4285      That would cause problems if a file loaded on startup tries to
4286      prompt in the mini-buffer.  */
4287   if (current_kboard == initial_kboard)
4288     current_kboard = terminal->kboard;
4289   terminal->kboard->reference_count++;
4291   dpyinfo->next = x_display_list;
4292   x_display_list = dpyinfo;
4294   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4296   terminal->name = xstrdup (SSDATA (display_name));
4298   unblock_input ();
4300   if (!inhibit_x_resources)
4301     {
4302       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4303                  Qt, Qnil, NO, NO);
4304       tmp = Qnil;
4305       /* this is a standard variable */
4306       ns_default ("AppleAntiAliasingThreshold", &tmp,
4307                  make_float (10.0), make_float (6.0), YES, NO);
4308       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4309     }
4311   {
4312     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4314     if ( cl == nil )
4315       {
4316         Lisp_Object color_file, color_map, color;
4317         unsigned long c;
4318         char *name;
4320         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4321                          Fsymbol_value (intern ("data-directory")));
4323         color_map = Fx_load_color_file (color_file);
4324         if (NILP (color_map))
4325           fatal ("Could not read %s.\n", SDATA (color_file));
4327         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4328         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4329           {
4330             color = XCAR (color_map);
4331             name = SSDATA (XCAR (color));
4332             c = XINT (XCDR (color));
4333             [cl setColor:
4334                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4335                                       green: GREEN_FROM_ULONG (c) / 255.0
4336                                        blue: BLUE_FROM_ULONG (c) / 255.0
4337                                       alpha: 1.0]
4338                   forKey: [NSString stringWithUTF8String: name]];
4339           }
4340         [cl writeToFile: nil];
4341       }
4342   }
4344   {
4345 #ifdef NS_IMPL_GNUSTEP
4346     Vwindow_system_version = build_string (gnustep_base_version);
4347 #else
4348     /*PSnextrelease (128, c); */
4349     char c[DBL_BUFSIZE_BOUND];
4350     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4351     Vwindow_system_version = make_unibyte_string (c, len);
4352 #endif
4353   }
4355   delete_keyboard_wait_descriptor (0);
4357   ns_app_name = [[NSProcessInfo processInfo] processName];
4359 /* Set up OS X app menu */
4360 #ifdef NS_IMPL_COCOA
4361   {
4362     NSMenu *appMenu;
4363     NSMenuItem *item;
4364     /* set up the application menu */
4365     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4366     [svcsMenu setAutoenablesItems: NO];
4367     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4368     [appMenu setAutoenablesItems: NO];
4369     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4370     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4372     [appMenu insertItemWithTitle: @"About Emacs"
4373                           action: @selector (orderFrontStandardAboutPanel:)
4374                    keyEquivalent: @""
4375                          atIndex: 0];
4376     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4377     [appMenu insertItemWithTitle: @"Preferences..."
4378                           action: @selector (showPreferencesWindow:)
4379                    keyEquivalent: @","
4380                          atIndex: 2];
4381     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4382     item = [appMenu insertItemWithTitle: @"Services"
4383                                  action: @selector (menuDown:)
4384                           keyEquivalent: @""
4385                                 atIndex: 4];
4386     [appMenu setSubmenu: svcsMenu forItem: item];
4387     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4388     [appMenu insertItemWithTitle: @"Hide Emacs"
4389                           action: @selector (hide:)
4390                    keyEquivalent: @"h"
4391                          atIndex: 6];
4392     item =  [appMenu insertItemWithTitle: @"Hide Others"
4393                           action: @selector (hideOtherApplications:)
4394                    keyEquivalent: @"h"
4395                          atIndex: 7];
4396     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4397     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4398     [appMenu insertItemWithTitle: @"Quit Emacs"
4399                           action: @selector (terminate:)
4400                    keyEquivalent: @"q"
4401                          atIndex: 9];
4403     item = [mainMenu insertItemWithTitle: ns_app_name
4404                                   action: @selector (menuDown:)
4405                            keyEquivalent: @""
4406                                  atIndex: 0];
4407     [mainMenu setSubmenu: appMenu forItem: item];
4408     [dockMenu insertItemWithTitle: @"New Frame"
4409                            action: @selector (newFrame:)
4410                     keyEquivalent: @""
4411                           atIndex: 0];
4413     [NSApp setMainMenu: mainMenu];
4414     [NSApp setAppleMenu: appMenu];
4415     [NSApp setServicesMenu: svcsMenu];
4416     /* Needed at least on Cocoa, to get dock menu to show windows */
4417     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4419     [[NSNotificationCenter defaultCenter]
4420       addObserver: mainMenu
4421          selector: @selector (trackingNotification:)
4422              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4423     [[NSNotificationCenter defaultCenter]
4424       addObserver: mainMenu
4425          selector: @selector (trackingNotification:)
4426              name: NSMenuDidEndTrackingNotification object: mainMenu];
4427   }
4428 #endif /* MAC OS X menu setup */
4430   /* Register our external input/output types, used for determining
4431      applicable services and also drag/drop eligibility. */
4432   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4433   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4434                       retain];
4435   ns_drag_types = [[NSArray arrayWithObjects:
4436                             NSStringPboardType,
4437                             NSTabularTextPboardType,
4438                             NSFilenamesPboardType,
4439                             NSURLPboardType, nil] retain];
4441   /* If fullscreen is in init/default-frame-alist, focus isn't set
4442      right for fullscreen windows, so set this.  */
4443   [NSApp activateIgnoringOtherApps:YES];
4445   [NSApp run];
4446   ns_do_open_file = YES;
4448 #ifdef NS_IMPL_GNUSTEP
4449   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4450      We must re-catch it so subprocess works.  */
4451   catch_child_signal ();
4452 #endif
4453   return dpyinfo;
4457 void
4458 ns_term_shutdown (int sig)
4460   [[NSUserDefaults standardUserDefaults] synchronize];
4462   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4463   if (STRINGP (Vauto_save_list_file_name))
4464     unlink (SSDATA (Vauto_save_list_file_name));
4466   if (sig == 0 || sig == SIGTERM)
4467     {
4468       [NSApp terminate: NSApp];
4469     }
4470   else // force a stack trace to happen
4471     {
4472       emacs_abort ();
4473     }
4477 /* ==========================================================================
4479     EmacsApp implementation
4481    ========================================================================== */
4484 @implementation EmacsApp
4486 - (id)init
4488   if (self = [super init])
4489     {
4490 #ifdef NS_IMPL_COCOA
4491       self->isFirst = YES;
4492 #endif
4493 #ifdef NS_IMPL_GNUSTEP
4494       self->applicationDidFinishLaunchingCalled = NO;
4495 #endif
4496     }
4498   return self;
4501 #ifdef NS_IMPL_COCOA
4502 - (void)run
4504 #ifndef NSAppKitVersionNumber10_9
4505 #define NSAppKitVersionNumber10_9 1265
4506 #endif
4508     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4509       {
4510         [super run];
4511         return;
4512       }
4514     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4516     if (isFirst) [self finishLaunching];
4517     isFirst = NO;
4519     shouldKeepRunning = YES;
4520     do
4521       {
4522         [pool release];
4523         pool = [[NSAutoreleasePool alloc] init];
4525         NSEvent *event =
4526           [self nextEventMatchingMask:NSAnyEventMask
4527                             untilDate:[NSDate distantFuture]
4528                                inMode:NSDefaultRunLoopMode
4529                               dequeue:YES];
4530         [self sendEvent:event];
4531         [self updateWindows];
4532     } while (shouldKeepRunning);
4534     [pool release];
4537 - (void)stop: (id)sender
4539     shouldKeepRunning = NO;
4540     // Stop possible dialog also.  Noop if no dialog present.
4541     // The file dialog still leaks 7k - 10k on 10.9 though.
4542     [super stop:sender];
4544 #endif /* NS_IMPL_COCOA */
4546 - (void)logNotification: (NSNotification *)notification
4548   const char *name = [[notification name] UTF8String];
4549   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4550       && !strstr (name, "WindowNumber"))
4551     NSLog (@"notification: '%@'", [notification name]);
4555 - (void)sendEvent: (NSEvent *)theEvent
4556 /* --------------------------------------------------------------------------
4557      Called when NSApp is running for each event received.  Used to stop
4558      the loop when we choose, since there's no way to just run one iteration.
4559    -------------------------------------------------------------------------- */
4561   int type = [theEvent type];
4562   NSWindow *window = [theEvent window];
4564 /*  NSTRACE (sendEvent); */
4565 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4567 #ifdef NS_IMPL_GNUSTEP
4568   // Keyboard events aren't propagated to file dialogs for some reason.
4569   if ([NSApp modalWindow] != nil &&
4570       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4571     {
4572       [[NSApp modalWindow] sendEvent: theEvent];
4573       return;
4574     }
4575 #endif
4577   if (represented_filename != nil && represented_frame)
4578     {
4579       NSString *fstr = represented_filename;
4580       NSView *view = FRAME_NS_VIEW (represented_frame);
4581 #ifdef NS_IMPL_COCOA
4582       /* work around a bug observed on 10.3 and later where
4583          setTitleWithRepresentedFilename does not clear out previous state
4584          if given filename does not exist */
4585       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4586         [[view window] setRepresentedFilename: @""];
4587 #endif
4588       [[view window] setRepresentedFilename: fstr];
4589       [represented_filename release];
4590       represented_filename = nil;
4591       represented_frame = NULL;
4592     }
4594   if (type == NSApplicationDefined)
4595     {
4596       switch ([theEvent data2])
4597         {
4598 #ifdef NS_IMPL_COCOA
4599         case NSAPP_DATA2_RUNASSCRIPT:
4600           ns_run_ascript ();
4601           [self stop: self];
4602           return;
4603 #endif
4604         case NSAPP_DATA2_RUNFILEDIALOG:
4605           ns_run_file_dialog ();
4606           [self stop: self];
4607           return;
4608         }
4609     }
4611   if (type == NSCursorUpdate && window == nil)
4612     {
4613       fprintf (stderr, "Dropping external cursor update event.\n");
4614       return;
4615     }
4617   if (type == NSApplicationDefined)
4618     {
4619       /* Events posted by ns_send_appdefined interrupt the run loop here.
4620          But, if a modal window is up, an appdefined can still come through,
4621          (e.g., from a makeKeyWindow event) but stopping self also stops the
4622          modal loop. Just defer it until later. */
4623       if ([NSApp modalWindow] == nil)
4624         {
4625           last_appdefined_event_data = [theEvent data1];
4626           [self stop: self];
4627         }
4628       else
4629         {
4630           send_appdefined = YES;
4631         }
4632     }
4635 #ifdef NS_IMPL_COCOA
4636   /* If no dialog and none of our frames have focus and it is a move, skip it.
4637      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4638      such as Wifi, sound, date or similar.
4639      This prevents "spooky" highlighting in the frame under the menu.  */
4640   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4641     {
4642       struct ns_display_info *di;
4643       BOOL has_focus = NO;
4644       for (di = x_display_list; ! has_focus && di; di = di->next)
4645         has_focus = di->x_focus_frame != 0;
4646       if (! has_focus)
4647         return;
4648     }
4649 #endif
4651   [super sendEvent: theEvent];
4655 - (void)showPreferencesWindow: (id)sender
4657   struct frame *emacsframe = SELECTED_FRAME ();
4658   NSEvent *theEvent = [NSApp currentEvent];
4660   if (!emacs_event)
4661     return;
4662   emacs_event->kind = NS_NONKEY_EVENT;
4663   emacs_event->code = KEY_NS_SHOW_PREFS;
4664   emacs_event->modifiers = 0;
4665   EV_TRAILER (theEvent);
4669 - (void)newFrame: (id)sender
4671   struct frame *emacsframe = SELECTED_FRAME ();
4672   NSEvent *theEvent = [NSApp currentEvent];
4674   if (!emacs_event)
4675     return;
4676   emacs_event->kind = NS_NONKEY_EVENT;
4677   emacs_event->code = KEY_NS_NEW_FRAME;
4678   emacs_event->modifiers = 0;
4679   EV_TRAILER (theEvent);
4683 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4684 - (BOOL) openFile: (NSString *)fileName
4686   struct frame *emacsframe = SELECTED_FRAME ();
4687   NSEvent *theEvent = [NSApp currentEvent];
4689   if (!emacs_event)
4690     return NO;
4692   emacs_event->kind = NS_NONKEY_EVENT;
4693   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4694   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4695   ns_input_line = Qnil; /* can be start or cons start,end */
4696   emacs_event->modifiers =0;
4697   EV_TRAILER (theEvent);
4699   return YES;
4703 /* **************************************************************************
4705       EmacsApp delegate implementation
4707    ************************************************************************** */
4709 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4710 /* --------------------------------------------------------------------------
4711      When application is loaded, terminate event loop in ns_term_init
4712    -------------------------------------------------------------------------- */
4714   NSTRACE (applicationDidFinishLaunching);
4715 #ifdef NS_IMPL_GNUSTEP
4716   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4717 #endif
4718   [NSApp setServicesProvider: NSApp];
4720   [self antialiasThresholdDidChange:nil];
4721 #ifdef NS_IMPL_COCOA
4722 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
4723   [[NSNotificationCenter defaultCenter]
4724     addObserver:self
4725        selector:@selector(antialiasThresholdDidChange:)
4726            name:NSAntialiasThresholdChangedNotification
4727          object:nil];
4728 #endif
4729 #endif
4731   ns_send_appdefined (-2);
4734 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4736 #ifdef NS_IMPL_COCOA
4737 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
4738   macfont_update_antialias_threshold ();
4739 #endif
4740 #endif
4744 /* Termination sequences:
4745     C-x C-c:
4746     Cmd-Q:
4747     MenuBar | File | Exit:
4748     Select Quit from App menubar:
4749         -terminate
4750         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4751         ns_term_shutdown()
4753     Select Quit from Dock menu:
4754     Logout attempt:
4755         -appShouldTerminate
4756           Cancel -> Nothing else
4757           Accept ->
4759           -terminate
4760           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4761           ns_term_shutdown()
4765 - (void) terminate: (id)sender
4767   struct frame *emacsframe = SELECTED_FRAME ();
4769   if (!emacs_event)
4770     return;
4772   emacs_event->kind = NS_NONKEY_EVENT;
4773   emacs_event->code = KEY_NS_POWER_OFF;
4774   emacs_event->arg = Qt; /* mark as non-key event */
4775   EV_TRAILER ((id)nil);
4779 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4781   int ret;
4783   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4784     return NSTerminateNow;
4786     ret = NSRunAlertPanel(ns_app_name,
4787                           @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4788                           @"Save Buffers and Exit", @"Cancel", nil);
4790     if (ret == NSAlertDefaultReturn)
4791         return NSTerminateNow;
4792     else if (ret == NSAlertAlternateReturn)
4793         return NSTerminateCancel;
4794     return NSTerminateNow;  /* just in case */
4797 static int
4798 not_in_argv (NSString *arg)
4800   int k;
4801   const char *a = [arg UTF8String];
4802   for (k = 1; k < initial_argc; ++k)
4803     if (strcmp (a, initial_argv[k]) == 0) return 0;
4804   return 1;
4807 /*   Notification from the Workspace to open a file */
4808 - (BOOL)application: sender openFile: (NSString *)file
4810   if (ns_do_open_file || not_in_argv (file))
4811     [ns_pending_files addObject: file];
4812   return YES;
4816 /*   Open a file as a temporary file */
4817 - (BOOL)application: sender openTempFile: (NSString *)file
4819   if (ns_do_open_file || not_in_argv (file))
4820     [ns_pending_files addObject: file];
4821   return YES;
4825 /*   Notification from the Workspace to open a file noninteractively (?) */
4826 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4828   if (ns_do_open_file || not_in_argv (file))
4829     [ns_pending_files addObject: file];
4830   return YES;
4833 /*   Notification from the Workspace to open multiple files */
4834 - (void)application: sender openFiles: (NSArray *)fileList
4836   NSEnumerator *files = [fileList objectEnumerator];
4837   NSString *file;
4838   /* Don't open files from the command line unconditionally,
4839      Cocoa parses the command line wrong, --option value tries to open value
4840      if --option is the last option.  */
4841   while ((file = [files nextObject]) != nil)
4842     if (ns_do_open_file || not_in_argv (file))
4843       [ns_pending_files addObject: file];
4845   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4850 /* Handle dock menu requests.  */
4851 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4853   return dockMenu;
4857 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4858 - (void)applicationWillBecomeActive: (NSNotification *)notification
4860   //ns_app_active=YES;
4862 - (void)applicationDidBecomeActive: (NSNotification *)notification
4864   NSTRACE (applicationDidBecomeActive);
4866 #ifdef NS_IMPL_GNUSTEP
4867   if (! applicationDidFinishLaunchingCalled)
4868     [self applicationDidFinishLaunching:notification];
4869 #endif
4870   //ns_app_active=YES;
4872   ns_update_auto_hide_menu_bar ();
4873   // No constraining takes place when the application is not active.
4874   ns_constrain_all_frames ();
4876 - (void)applicationDidResignActive: (NSNotification *)notification
4878   //ns_app_active=NO;
4879   ns_send_appdefined (-1);
4884 /* ==========================================================================
4886     EmacsApp aux handlers for managing event loop
4888    ========================================================================== */
4891 - (void)timeout_handler: (NSTimer *)timedEntry
4892 /* --------------------------------------------------------------------------
4893      The timeout specified to ns_select has passed.
4894    -------------------------------------------------------------------------- */
4896   /*NSTRACE (timeout_handler); */
4897   ns_send_appdefined (-2);
4900 #ifdef NS_IMPL_GNUSTEP
4901 - (void)sendFromMainThread:(id)unused
4903   ns_send_appdefined (nextappdefined);
4905 #endif
4907 - (void)fd_handler:(id)unused
4908 /* --------------------------------------------------------------------------
4909      Check data waiting on file descriptors and terminate if so
4910    -------------------------------------------------------------------------- */
4912   int result;
4913   int waiting = 1, nfds;
4914   char c;
4916   fd_set readfds, writefds, *wfds;
4917   struct timespec timeout, *tmo;
4918   NSAutoreleasePool *pool = nil;
4920   /* NSTRACE (fd_handler); */
4922   for (;;)
4923     {
4924       [pool release];
4925       pool = [[NSAutoreleasePool alloc] init];
4927       if (waiting)
4928         {
4929           fd_set fds;
4930           FD_ZERO (&fds);
4931           FD_SET (selfds[0], &fds);
4932           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4933           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4934             waiting = 0;
4935         }
4936       else
4937         {
4938           pthread_mutex_lock (&select_mutex);
4939           nfds = select_nfds;
4941           if (select_valid & SELECT_HAVE_READ)
4942             readfds = select_readfds;
4943           else
4944             FD_ZERO (&readfds);
4946           if (select_valid & SELECT_HAVE_WRITE)
4947             {
4948               writefds = select_writefds;
4949               wfds = &writefds;
4950             }
4951           else
4952             wfds = NULL;
4953           if (select_valid & SELECT_HAVE_TMO)
4954             {
4955               timeout = select_timeout;
4956               tmo = &timeout;
4957             }
4958           else
4959             tmo = NULL;
4961           pthread_mutex_unlock (&select_mutex);
4963           FD_SET (selfds[0], &readfds);
4964           if (selfds[0] >= nfds) nfds = selfds[0]+1;
4966           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4968           if (result == 0)
4969             ns_send_appdefined (-2);
4970           else if (result > 0)
4971             {
4972               if (FD_ISSET (selfds[0], &readfds))
4973                 {
4974                   if (read (selfds[0], &c, 1) == 1 && c == 's')
4975                     waiting = 1;
4976                 }
4977               else
4978                 {
4979                   pthread_mutex_lock (&select_mutex);
4980                   if (select_valid & SELECT_HAVE_READ)
4981                     select_readfds = readfds;
4982                   if (select_valid & SELECT_HAVE_WRITE)
4983                     select_writefds = writefds;
4984                   if (select_valid & SELECT_HAVE_TMO)
4985                     select_timeout = timeout;
4986                   pthread_mutex_unlock (&select_mutex);
4988                   ns_send_appdefined (result);
4989                 }
4990             }
4991           waiting = 1;
4992         }
4993     }
4998 /* ==========================================================================
5000     Service provision
5002    ========================================================================== */
5004 /* called from system: queue for next pass through event loop */
5005 - (void)requestService: (NSPasteboard *)pboard
5006               userData: (NSString *)userData
5007                  error: (NSString **)error
5009   [ns_pending_service_names addObject: userData];
5010   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5011       SSDATA (ns_string_from_pasteboard (pboard))]];
5015 /* called from ns_read_socket to clear queue */
5016 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5018   struct frame *emacsframe = SELECTED_FRAME ();
5019   NSEvent *theEvent = [NSApp currentEvent];
5021   if (!emacs_event)
5022     return NO;
5024   emacs_event->kind = NS_NONKEY_EVENT;
5025   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5026   ns_input_spi_name = build_string ([name UTF8String]);
5027   ns_input_spi_arg = build_string ([arg UTF8String]);
5028   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5029   EV_TRAILER (theEvent);
5031   return YES;
5035 @end  /* EmacsApp */
5039 /* ==========================================================================
5041     EmacsView implementation
5043    ========================================================================== */
5046 @implementation EmacsView
5048 /* needed to inform when window closed from LISP */
5049 - (void) setWindowClosing: (BOOL)closing
5051   windowClosing = closing;
5055 - (void)dealloc
5057   NSTRACE (EmacsView_dealloc);
5058   [toolbar release];
5059   if (fs_state == FULLSCREEN_BOTH)
5060     [nonfs_window release];
5061   [super dealloc];
5065 /* called on font panel selection */
5066 - (void)changeFont: (id)sender
5068   NSEvent *e = [[self window] currentEvent];
5069   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5070   struct font *font = face->font;
5071   id newFont;
5072   CGFloat size;
5073   NSFont *nsfont;
5075   NSTRACE (changeFont);
5077   if (!emacs_event)
5078     return;
5080   if (EQ (font->driver->type, Qns))
5081     nsfont = ((struct nsfont_info *)font)->nsfont;
5082 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
5083   else
5084     nsfont = (NSFont *) macfont_get_nsctfont (font);
5085 #endif
5087   if ((newFont = [sender convertFont: nsfont]))
5088     {
5089       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5091       emacs_event->kind = NS_NONKEY_EVENT;
5092       emacs_event->modifiers = 0;
5093       emacs_event->code = KEY_NS_CHANGE_FONT;
5095       size = [newFont pointSize];
5096       ns_input_fontsize = make_number (lrint (size));
5097       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5098       EV_TRAILER (e);
5099     }
5103 - (BOOL)acceptsFirstResponder
5105   NSTRACE (acceptsFirstResponder);
5106   return YES;
5110 - (void)resetCursorRects
5112   NSRect visible = [self visibleRect];
5113   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5114   NSTRACE (resetCursorRects);
5116   if (currentCursor == nil)
5117     currentCursor = [NSCursor arrowCursor];
5119   if (!NSIsEmptyRect (visible))
5120     [self addCursorRect: visible cursor: currentCursor];
5121   [currentCursor setOnMouseEntered: YES];
5126 /*****************************************************************************/
5127 /* Keyboard handling. */
5128 #define NS_KEYLOG 0
5130 - (void)keyDown: (NSEvent *)theEvent
5132   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5133   int code;
5134   unsigned fnKeysym = 0;
5135   static NSMutableArray *nsEvArray;
5136 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5137   static BOOL firstTime = YES;
5138 #endif
5139   int left_is_none;
5140   unsigned int flags = [theEvent modifierFlags];
5142   NSTRACE (keyDown);
5144   /* Rhapsody and OS X give up and down events for the arrow keys */
5145   if (ns_fake_keydown == YES)
5146     ns_fake_keydown = NO;
5147   else if ([theEvent type] != NSKeyDown)
5148     return;
5150   if (!emacs_event)
5151     return;
5153  if (![[self window] isKeyWindow]
5154      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5155      /* we must avoid an infinite loop here. */
5156      && (EmacsView *)[[theEvent window] delegate] != self)
5157    {
5158      /* XXX: There is an occasional condition in which, when Emacs display
5159          updates a different frame from the current one, and temporarily
5160          selects it, then processes some interrupt-driven input
5161          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5162          for some reason that window has its first responder set to the NSView
5163          most recently updated (I guess), which is not the correct one. */
5164      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5165      return;
5166    }
5168   if (nsEvArray == nil)
5169     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5171   [NSCursor setHiddenUntilMouseMoves: YES];
5173   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5174     {
5175       clear_mouse_face (hlinfo);
5176       hlinfo->mouse_face_hidden = 1;
5177     }
5179   if (!processingCompose)
5180     {
5181       /* When using screen sharing, no left or right information is sent,
5182          so use Left key in those cases.  */
5183       int is_left_key, is_right_key;
5185       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5186         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5188       /* (Carbon way: [theEvent keyCode]) */
5190       /* is it a "function key"? */
5191       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5192          flag set (this is probably a bug in the OS).
5193       */
5194       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5195         {
5196           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5197         }
5198       if (fnKeysym == 0)
5199         {
5200           fnKeysym = ns_convert_key (code);
5201         }
5203       if (fnKeysym)
5204         {
5205           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5206              because Emacs treats Delete and KP-Delete same (in simple.el). */
5207           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5208 #ifdef NS_IMPL_GNUSTEP
5209               /*  GNUstep uses incompatible keycodes, even for those that are
5210                   supposed to be hardware independent.  Just check for delete.
5211                   Keypad delete does not have keysym 0xFFFF.
5212                   See http://savannah.gnu.org/bugs/?25395
5213               */
5214               || (fnKeysym == 0xFFFF && code == 127)
5215 #endif
5216             )
5217             code = 0xFF08; /* backspace */
5218           else
5219             code = fnKeysym;
5220         }
5222       /* are there modifiers? */
5223       emacs_event->modifiers = 0;
5225       if (flags & NSHelpKeyMask)
5226           emacs_event->modifiers |= hyper_modifier;
5228       if (flags & NSShiftKeyMask)
5229         emacs_event->modifiers |= shift_modifier;
5231       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5232       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5233         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5235       if (is_right_key)
5236         emacs_event->modifiers |= parse_solitary_modifier
5237           (EQ (ns_right_command_modifier, Qleft)
5238            ? ns_command_modifier
5239            : ns_right_command_modifier);
5241       if (is_left_key)
5242         {
5243           emacs_event->modifiers |= parse_solitary_modifier
5244             (ns_command_modifier);
5246           /* if super (default), take input manager's word so things like
5247              dvorak / qwerty layout work */
5248           if (EQ (ns_command_modifier, Qsuper)
5249               && !fnKeysym
5250               && [[theEvent characters] length] != 0)
5251             {
5252               /* XXX: the code we get will be unshifted, so if we have
5253                  a shift modifier, must convert ourselves */
5254               if (!(flags & NSShiftKeyMask))
5255                 code = [[theEvent characters] characterAtIndex: 0];
5256 #if 0
5257               /* this is ugly and also requires linking w/Carbon framework
5258                  (for LMGetKbdType) so for now leave this rare (?) case
5259                  undealt with.. in future look into CGEvent methods */
5260               else
5261                 {
5262                   long smv = GetScriptManagerVariable (smKeyScript);
5263                   Handle uchrHandle = GetResource
5264                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5265                   UInt32 dummy = 0;
5266                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5267                                  [[theEvent characters] characterAtIndex: 0],
5268                                  kUCKeyActionDisplay,
5269                                  (flags & ~NSCommandKeyMask) >> 8,
5270                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5271                                  &dummy, 1, &dummy, &code);
5272                   code &= 0xFF;
5273                 }
5274 #endif
5275             }
5276         }
5278       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5279       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5280         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5282       if (is_right_key)
5283           emacs_event->modifiers |= parse_solitary_modifier
5284               (EQ (ns_right_control_modifier, Qleft)
5285                ? ns_control_modifier
5286                : ns_right_control_modifier);
5288       if (is_left_key)
5289         emacs_event->modifiers |= parse_solitary_modifier
5290           (ns_control_modifier);
5292       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5293           emacs_event->modifiers |=
5294             parse_solitary_modifier (ns_function_modifier);
5296       left_is_none = NILP (ns_alternate_modifier)
5297         || EQ (ns_alternate_modifier, Qnone);
5299       is_right_key = (flags & NSRightAlternateKeyMask)
5300         == NSRightAlternateKeyMask;
5301       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5302         || (! is_right_key
5303             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5305       if (is_right_key)
5306         {
5307           if ((NILP (ns_right_alternate_modifier)
5308                || EQ (ns_right_alternate_modifier, Qnone)
5309                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5310               && !fnKeysym)
5311             {   /* accept pre-interp alt comb */
5312               if ([[theEvent characters] length] > 0)
5313                 code = [[theEvent characters] characterAtIndex: 0];
5314               /*HACK: clear lone shift modifier to stop next if from firing */
5315               if (emacs_event->modifiers == shift_modifier)
5316                 emacs_event->modifiers = 0;
5317             }
5318           else
5319             emacs_event->modifiers |= parse_solitary_modifier
5320               (EQ (ns_right_alternate_modifier, Qleft)
5321                ? ns_alternate_modifier
5322                : ns_right_alternate_modifier);
5323         }
5325       if (is_left_key) /* default = meta */
5326         {
5327           if (left_is_none && !fnKeysym)
5328             {   /* accept pre-interp alt comb */
5329               if ([[theEvent characters] length] > 0)
5330                 code = [[theEvent characters] characterAtIndex: 0];
5331               /*HACK: clear lone shift modifier to stop next if from firing */
5332               if (emacs_event->modifiers == shift_modifier)
5333                 emacs_event->modifiers = 0;
5334             }
5335           else
5336               emacs_event->modifiers |=
5337                 parse_solitary_modifier (ns_alternate_modifier);
5338         }
5340   if (NS_KEYLOG)
5341     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5342              code, fnKeysym, flags, emacs_event->modifiers);
5344       /* if it was a function key or had modifiers, pass it directly to emacs */
5345       if (fnKeysym || (emacs_event->modifiers
5346                        && (emacs_event->modifiers != shift_modifier)
5347                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5348 /*[[theEvent characters] length] */
5349         {
5350           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5351           if (code < 0x20)
5352             code |= (1<<28)|(3<<16);
5353           else if (code == 0x7f)
5354             code |= (1<<28)|(3<<16);
5355           else if (!fnKeysym)
5356             emacs_event->kind = code > 0xFF
5357               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5359           emacs_event->code = code;
5360           EV_TRAILER (theEvent);
5361           processingCompose = NO;
5362           return;
5363         }
5364     }
5367 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5368   /* if we get here we should send the key for input manager processing */
5369   /* Disable warning, there is nothing a user can do about it anyway, and
5370      it does not seem to matter.  */
5371 #if 0
5372   if (firstTime && [[NSInputManager currentInputManager]
5373                      wantsToDelayTextChangeNotifications] == NO)
5374     fprintf (stderr,
5375           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5376 #endif
5377   firstTime = NO;
5378 #endif
5379   if (NS_KEYLOG && !processingCompose)
5380     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5382   processingCompose = YES;
5383   [nsEvArray addObject: theEvent];
5384   [self interpretKeyEvents: nsEvArray];
5385   [nsEvArray removeObject: theEvent];
5389 #ifdef NS_IMPL_COCOA
5390 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5391    decided not to send key-down for.
5392    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5393    This only applies on Tiger and earlier.
5394    If it matches one of these, send it on to keyDown. */
5395 -(void)keyUp: (NSEvent *)theEvent
5397   int flags = [theEvent modifierFlags];
5398   int code = [theEvent keyCode];
5399   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5400       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5401     {
5402       if (NS_KEYLOG)
5403         fprintf (stderr, "keyUp: passed test");
5404       ns_fake_keydown = YES;
5405       [self keyDown: theEvent];
5406     }
5408 #endif
5411 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5414 /* <NSTextInput>: called when done composing;
5415    NOTE: also called when we delete over working text, followed immed.
5416          by doCommandBySelector: deleteBackward: */
5417 - (void)insertText: (id)aString
5419   int code;
5420   int len = [(NSString *)aString length];
5421   int i;
5423   if (NS_KEYLOG)
5424     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5425   processingCompose = NO;
5427   if (!emacs_event)
5428     return;
5430   /* first, clear any working text */
5431   if (workingText != nil)
5432     [self deleteWorkingText];
5434   /* now insert the string as keystrokes */
5435   for (i =0; i<len; i++)
5436     {
5437       code = [aString characterAtIndex: i];
5438       /* TODO: still need this? */
5439       if (code == 0x2DC)
5440         code = '~'; /* 0x7E */
5441       if (code != 32) /* Space */
5442         emacs_event->modifiers = 0;
5443       emacs_event->kind
5444         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5445       emacs_event->code = code;
5446       EV_TRAILER ((id)nil);
5447     }
5451 /* <NSTextInput>: inserts display of composing characters */
5452 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5454   NSString *str = [aString respondsToSelector: @selector (string)] ?
5455     [aString string] : aString;
5456   if (NS_KEYLOG)
5457     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5458            str, (unsigned long)[str length],
5459            (unsigned long)selRange.length,
5460            (unsigned long)selRange.location);
5462   if (workingText != nil)
5463     [self deleteWorkingText];
5464   if ([str length] == 0)
5465     return;
5467   if (!emacs_event)
5468     return;
5470   processingCompose = YES;
5471   workingText = [str copy];
5472   ns_working_text = build_string ([workingText UTF8String]);
5474   emacs_event->kind = NS_TEXT_EVENT;
5475   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5476   EV_TRAILER ((id)nil);
5480 /* delete display of composing characters [not in <NSTextInput>] */
5481 - (void)deleteWorkingText
5483   if (workingText == nil)
5484     return;
5485   if (NS_KEYLOG)
5486     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5487   [workingText release];
5488   workingText = nil;
5489   processingCompose = NO;
5491   if (!emacs_event)
5492     return;
5494   emacs_event->kind = NS_TEXT_EVENT;
5495   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5496   EV_TRAILER ((id)nil);
5500 - (BOOL)hasMarkedText
5502   return workingText != nil;
5506 - (NSRange)markedRange
5508   NSRange rng = workingText != nil
5509     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5510   if (NS_KEYLOG)
5511     NSLog (@"markedRange request");
5512   return rng;
5516 - (void)unmarkText
5518   if (NS_KEYLOG)
5519     NSLog (@"unmark (accept) text");
5520   [self deleteWorkingText];
5521   processingCompose = NO;
5525 /* used to position char selection windows, etc. */
5526 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5528   NSRect rect;
5529   NSPoint pt;
5530   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5531   if (NS_KEYLOG)
5532     NSLog (@"firstRectForCharRange request");
5534   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5535   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5536   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5537   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5538                                        +FRAME_LINE_HEIGHT (emacsframe));
5540   pt = [self convertPoint: pt toView: nil];
5541   pt = [[self window] convertBaseToScreen: pt];
5542   rect.origin = pt;
5543   return rect;
5547 - (NSInteger)conversationIdentifier
5549   return (NSInteger)self;
5553 - (void)doCommandBySelector: (SEL)aSelector
5555   if (NS_KEYLOG)
5556     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5558   processingCompose = NO;
5559   if (aSelector == @selector (deleteBackward:))
5560     {
5561       /* happens when user backspaces over an ongoing composition:
5562          throw a 'delete' into the event queue */
5563       if (!emacs_event)
5564         return;
5565       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5566       emacs_event->code = 0xFF08;
5567       EV_TRAILER ((id)nil);
5568     }
5571 - (NSArray *)validAttributesForMarkedText
5573   static NSArray *arr = nil;
5574   if (arr == nil) arr = [NSArray new];
5575  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5576   return arr;
5579 - (NSRange)selectedRange
5581   if (NS_KEYLOG)
5582     NSLog (@"selectedRange request");
5583   return NSMakeRange (NSNotFound, 0);
5586 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5587     GNUSTEP_GUI_MINOR_VERSION > 22
5588 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5589 #else
5590 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5591 #endif
5593   if (NS_KEYLOG)
5594     NSLog (@"characterIndexForPoint request");
5595   return 0;
5598 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5600   static NSAttributedString *str = nil;
5601   if (str == nil) str = [NSAttributedString new];
5602   if (NS_KEYLOG)
5603     NSLog (@"attributedSubstringFromRange request");
5604   return str;
5607 /* End <NSTextInput> impl. */
5608 /*****************************************************************************/
5611 /* This is what happens when the user presses a mouse button.  */
5612 - (void)mouseDown: (NSEvent *)theEvent
5614   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5615   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5617   NSTRACE (mouseDown);
5619   [self deleteWorkingText];
5621   if (!emacs_event)
5622     return;
5624   dpyinfo->last_mouse_frame = emacsframe;
5625   /* appears to be needed to prevent spurious movement events generated on
5626      button clicks */
5627   emacsframe->mouse_moved = 0;
5629   if ([theEvent type] == NSScrollWheel)
5630     {
5631       CGFloat delta = [theEvent deltaY];
5632       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5633       if (delta == 0)
5634         {
5635           delta = [theEvent deltaX];
5636           if (delta == 0)
5637             {
5638               NSTRACE (deltaIsZero);
5639               return;
5640             }
5641           emacs_event->kind = HORIZ_WHEEL_EVENT;
5642         }
5643       else
5644         emacs_event->kind = WHEEL_EVENT;
5646       emacs_event->code = 0;
5647       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5648         ((delta > 0) ? up_modifier : down_modifier);
5649     }
5650   else
5651     {
5652       emacs_event->kind = MOUSE_CLICK_EVENT;
5653       emacs_event->code = EV_BUTTON (theEvent);
5654       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5655                              | EV_UDMODIFIERS (theEvent);
5656     }
5657   XSETINT (emacs_event->x, lrint (p.x));
5658   XSETINT (emacs_event->y, lrint (p.y));
5659   EV_TRAILER (theEvent);
5663 - (void)rightMouseDown: (NSEvent *)theEvent
5665   NSTRACE (rightMouseDown);
5666   [self mouseDown: theEvent];
5670 - (void)otherMouseDown: (NSEvent *)theEvent
5672   NSTRACE (otherMouseDown);
5673   [self mouseDown: theEvent];
5677 - (void)mouseUp: (NSEvent *)theEvent
5679   NSTRACE (mouseUp);
5680   [self mouseDown: theEvent];
5684 - (void)rightMouseUp: (NSEvent *)theEvent
5686   NSTRACE (rightMouseUp);
5687   [self mouseDown: theEvent];
5691 - (void)otherMouseUp: (NSEvent *)theEvent
5693   NSTRACE (otherMouseUp);
5694   [self mouseDown: theEvent];
5698 - (void) scrollWheel: (NSEvent *)theEvent
5700   NSTRACE (scrollWheel);
5701   [self mouseDown: theEvent];
5705 /* Tell emacs the mouse has moved. */
5706 - (void)mouseMoved: (NSEvent *)e
5708   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5709   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5710   Lisp_Object frame;
5711   NSPoint pt;
5713 //  NSTRACE (mouseMoved);
5715   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5716   pt = [self convertPoint: [e locationInWindow] fromView: nil];
5717   dpyinfo->last_mouse_motion_x = pt.x;
5718   dpyinfo->last_mouse_motion_y = pt.y;
5720   /* update any mouse face */
5721   if (hlinfo->mouse_face_hidden)
5722     {
5723       hlinfo->mouse_face_hidden = 0;
5724       clear_mouse_face (hlinfo);
5725     }
5727   /* tooltip handling */
5728   previous_help_echo_string = help_echo_string;
5729   help_echo_string = Qnil;
5731   if (!NILP (Vmouse_autoselect_window))
5732     {
5733       NSTRACE (mouse_autoselect_window);
5734       static Lisp_Object last_mouse_window;
5735       Lisp_Object window
5736         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5738       if (WINDOWP (window)
5739           && !EQ (window, last_mouse_window)
5740           && !EQ (window, selected_window)
5741           && (focus_follows_mouse
5742               || (EQ (XWINDOW (window)->frame,
5743                       XWINDOW (selected_window)->frame))))
5744         {
5745           NSTRACE (in_window);
5746           emacs_event->kind = SELECT_WINDOW_EVENT;
5747           emacs_event->frame_or_window = window;
5748           EV_TRAILER2 (e);
5749         }
5750       /* Remember the last window where we saw the mouse.  */
5751       last_mouse_window = window;
5752     }
5754   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5755     help_echo_string = previous_help_echo_string;
5757   XSETFRAME (frame, emacsframe);
5758   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5759     {
5760       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5761          (note_mouse_highlight), which is called through the
5762          note_mouse_movement () call above */
5763       gen_help_event (help_echo_string, frame, help_echo_window,
5764                       help_echo_object, help_echo_pos);
5765     }
5766   else
5767     {
5768       help_echo_string = Qnil;
5769       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5770     }
5772   if (emacsframe->mouse_moved && send_appdefined)
5773     ns_send_appdefined (-1);
5777 - (void)mouseDragged: (NSEvent *)e
5779   NSTRACE (mouseDragged);
5780   [self mouseMoved: e];
5784 - (void)rightMouseDragged: (NSEvent *)e
5786   NSTRACE (rightMouseDragged);
5787   [self mouseMoved: e];
5791 - (void)otherMouseDragged: (NSEvent *)e
5793   NSTRACE (otherMouseDragged);
5794   [self mouseMoved: e];
5798 - (BOOL)windowShouldClose: (id)sender
5800   NSEvent *e =[[self window] currentEvent];
5802   NSTRACE (windowShouldClose);
5803   windowClosing = YES;
5804   if (!emacs_event)
5805     return NO;
5806   emacs_event->kind = DELETE_WINDOW_EVENT;
5807   emacs_event->modifiers = 0;
5808   emacs_event->code = 0;
5809   EV_TRAILER (e);
5810   /* Don't close this window, let this be done from lisp code.  */
5811   return NO;
5814 - (void) updateFrameSize: (BOOL) delay;
5816   NSWindow *window = [self window];
5817   NSRect wr = [window frame];
5818   int extra = 0;
5819   int oldc = cols, oldr = rows;
5820   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5821   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5822   int neww, newh;
5824   NSTRACE (updateFrameSize);
5825   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5827   if (! [self isFullscreen])
5828     {
5829 #ifdef NS_IMPL_GNUSTEP
5830       // GNUstep does not always update the tool bar height.  Force it.
5831       if (toolbar) update_frame_tool_bar (emacsframe);
5832 #endif
5834       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5835         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5836     }
5838   if (wait_for_tool_bar)
5839     {
5840       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5841         return;
5842       wait_for_tool_bar = NO;
5843     }
5845   neww = (int)wr.size.width - emacsframe->border_width;
5846   newh = (int)wr.size.height - extra;
5848   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5849   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5851   if (cols < MINWIDTH)
5852     cols = MINWIDTH;
5854   if (rows < MINHEIGHT)
5855     rows = MINHEIGHT;
5857   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5858     {
5859       NSView *view = FRAME_NS_VIEW (emacsframe);
5860       NSWindow *win = [view window];
5861       NSSize sz = [win resizeIncrements];
5863       change_frame_size (emacsframe,
5864                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5865                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5866                          0, delay, 0, 1);
5867       SET_FRAME_GARBAGED (emacsframe);
5868       cancel_mouse_face (emacsframe);
5870       // Did resize increments change because of a font change?
5871       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5872           sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5873           (frame_resize_pixelwise && sz.width != 1))
5874         {
5875           sz.width = frame_resize_pixelwise
5876             ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
5877           sz.height = frame_resize_pixelwise
5878             ? 1 : FRAME_LINE_HEIGHT (emacsframe);
5879           [win setResizeIncrements: sz];
5881           NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
5882         }
5884       [view setFrame: NSMakeRect (0, 0, neww, newh)];
5885       [self windowDidMove:nil];   // Update top/left.
5886     }
5889 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5890 /* normalize frame to gridded text size */
5892   int extra = 0;
5894   NSTRACE (windowWillResize);
5895   NSTRACE_SIZE ("Original size", frameSize);
5896 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5898   if (fs_state == FULLSCREEN_MAXIMIZED
5899       && (maximized_width != (int)frameSize.width
5900           || maximized_height != (int)frameSize.height))
5901     [self setFSValue: FULLSCREEN_NONE];
5902   else if (fs_state == FULLSCREEN_WIDTH
5903            && maximized_width != (int)frameSize.width)
5904     [self setFSValue: FULLSCREEN_NONE];
5905   else if (fs_state == FULLSCREEN_HEIGHT
5906            && maximized_height != (int)frameSize.height)
5907     [self setFSValue: FULLSCREEN_NONE];
5908   if (fs_state == FULLSCREEN_NONE)
5909     maximized_width = maximized_height = -1;
5911   if (! [self isFullscreen])
5912     {
5913       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5914         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5915     }
5917   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
5918   if (cols < MINWIDTH)
5919     cols = MINWIDTH;
5921   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5922                                            frameSize.height - extra);
5923   if (rows < MINHEIGHT)
5924     rows = MINHEIGHT;
5925 #ifdef NS_IMPL_COCOA
5926   {
5927     /* this sets window title to have size in it; the wm does this under GS */
5928     NSRect r = [[self window] frame];
5929     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5930       {
5931         if (old_title != 0)
5932           {
5933             xfree (old_title);
5934             old_title = 0;
5935           }
5936       }
5937     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
5938       {
5939         char *size_title;
5940         NSWindow *window = [self window];
5941         if (old_title == 0)
5942           {
5943             char *t = strdup ([[[self window] title] UTF8String]);
5944             char *pos = strstr (t, "  â€”  ");
5945             if (pos)
5946               *pos = '\0';
5947             old_title = t;
5948           }
5949         size_title = xmalloc (strlen (old_title) + 40);
5950         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5951         [window setTitle: [NSString stringWithUTF8String: size_title]];
5952         [window display];
5953         xfree (size_title);
5954       }
5955   }
5956 #endif /* NS_IMPL_COCOA */
5957 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5959   return frameSize;
5963 - (void)windowDidResize: (NSNotification *)notification
5965   if (! [self fsIsNative])
5966     {
5967       NSWindow *theWindow = [notification object];
5968       /* We can get notification on the non-FS window when in
5969          fullscreen mode.  */
5970       if ([self window] != theWindow) return;
5971     }
5973 #ifdef NS_IMPL_GNUSTEP
5974   NSWindow *theWindow = [notification object];
5976    /* In GNUstep, at least currently, it's possible to get a didResize
5977       without getting a willResize.. therefore we need to act as if we got
5978       the willResize now */
5979   NSSize sz = [theWindow frame].size;
5980   sz = [self windowWillResize: theWindow toSize: sz];
5981 #endif /* NS_IMPL_GNUSTEP */
5983   NSTRACE (windowDidResize);
5984 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5986 if (cols > 0 && rows > 0)
5987     {
5988       [self updateFrameSize: YES];
5989     }
5991   ns_send_appdefined (-1);
5994 #ifdef NS_IMPL_COCOA
5995 - (void)viewDidEndLiveResize
5997   [super viewDidEndLiveResize];
5998   if (old_title != 0)
5999     {
6000       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6001       xfree (old_title);
6002       old_title = 0;
6003     }
6004   maximizing_resize = NO;
6006 #endif /* NS_IMPL_COCOA */
6009 - (void)windowDidBecomeKey: (NSNotification *)notification
6010 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6012   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6013   struct frame *old_focus = dpyinfo->x_focus_frame;
6015   NSTRACE (windowDidBecomeKey);
6017   if (emacsframe != old_focus)
6018     dpyinfo->x_focus_frame = emacsframe;
6020   ns_frame_rehighlight (emacsframe);
6022   if (emacs_event)
6023     {
6024       emacs_event->kind = FOCUS_IN_EVENT;
6025       EV_TRAILER ((id)nil);
6026     }
6030 - (void)windowDidResignKey: (NSNotification *)notification
6031 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6033   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6034   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6035   NSTRACE (windowDidResignKey);
6037   if (is_focus_frame)
6038     dpyinfo->x_focus_frame = 0;
6040   emacsframe->mouse_moved = 0;
6041   ns_frame_rehighlight (emacsframe);
6043   /* FIXME: for some reason needed on second and subsequent clicks away
6044             from sole-frame Emacs to get hollow box to show */
6045   if (!windowClosing && [[self window] isVisible] == YES)
6046     {
6047       x_update_cursor (emacsframe, 1);
6048       x_set_frame_alpha (emacsframe);
6049     }
6051   if (emacs_event && is_focus_frame)
6052     {
6053       [self deleteWorkingText];
6054       emacs_event->kind = FOCUS_OUT_EVENT;
6055       EV_TRAILER ((id)nil);
6056     }
6060 - (void)windowWillMiniaturize: sender
6062   NSTRACE (windowWillMiniaturize);
6066 - (BOOL)isFlipped
6068   return YES;
6072 - (BOOL)isOpaque
6074   return NO;
6078 - initFrameFromEmacs: (struct frame *)f
6080   NSRect r, wr;
6081   Lisp_Object tem;
6082   NSWindow *win;
6083   NSSize sz;
6084   NSColor *col;
6085   NSString *name;
6087   NSTRACE (initFrameFromEmacs);
6089   windowClosing = NO;
6090   processingCompose = NO;
6091   scrollbarsNeedingUpdate = 0;
6092   fs_state = FULLSCREEN_NONE;
6093   fs_before_fs = next_maximized = -1;
6094 #ifdef HAVE_NATIVE_FS
6095   fs_is_native = ns_use_native_fullscreen;
6096 #else
6097   fs_is_native = NO;
6098 #endif
6099   maximized_width = maximized_height = -1;
6100   nonfs_window = nil;
6102 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6104   ns_userRect = NSMakeRect (0, 0, 0, 0);
6105   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6106                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6107   [self initWithFrame: r];
6108   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6110   FRAME_NS_VIEW (f) = self;
6111   emacsframe = f;
6112 #ifdef NS_IMPL_COCOA
6113   old_title = 0;
6114   maximizing_resize = NO;
6115 #endif
6117   win = [[EmacsWindow alloc]
6118             initWithContentRect: r
6119                       styleMask: (NSResizableWindowMask |
6120 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6121                                   NSTitledWindowMask |
6122 #endif
6123                                   NSMiniaturizableWindowMask |
6124                                   NSClosableWindowMask)
6125                         backing: NSBackingStoreBuffered
6126                           defer: YES];
6128 #ifdef HAVE_NATIVE_FS
6129     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6130 #endif
6132   wr = [win frame];
6133   bwidth = f->border_width = wr.size.width - r.size.width;
6134   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6136   [win setAcceptsMouseMovedEvents: YES];
6137   [win setDelegate: self];
6138   [win useOptimizedDrawing: YES];
6140   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6141   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6142   [win setResizeIncrements: sz];
6144   [[win contentView] addSubview: self];
6146   if (ns_drag_types)
6147     [self registerForDraggedTypes: ns_drag_types];
6149   tem = f->name;
6150   name = [NSString stringWithUTF8String:
6151                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6152   [win setTitle: name];
6154   /* toolbar support */
6155   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6156                          [NSString stringWithFormat: @"Emacs Frame %d",
6157                                    ns_window_num]];
6158   [win setToolbar: toolbar];
6159   [toolbar setVisible: NO];
6161   /* Don't set frame garbaged until tool bar is up to date?
6162      This avoids an extra clear and redraw (flicker) at frame creation.  */
6163   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6164   else wait_for_tool_bar = NO;
6167 #ifdef NS_IMPL_COCOA
6168   {
6169     NSButton *toggleButton;
6170   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6171   [toggleButton setTarget: self];
6172   [toggleButton setAction: @selector (toggleToolbar: )];
6173   }
6174 #endif
6175   FRAME_TOOLBAR_HEIGHT (f) = 0;
6177   tem = f->icon_name;
6178   if (!NILP (tem))
6179     [win setMiniwindowTitle:
6180            [NSString stringWithUTF8String: SSDATA (tem)]];
6182   {
6183     NSScreen *screen = [win screen];
6185     if (screen != 0)
6186       [win setFrameTopLeftPoint: NSMakePoint
6187            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6188             IN_BOUND (-SCREENMAX,
6189                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6190   }
6192   [win makeFirstResponder: self];
6194   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6195                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6196   [win setBackgroundColor: col];
6197   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6198     [win setOpaque: NO];
6200   [self allocateGState];
6202   [NSApp registerServicesMenuSendTypes: ns_send_types
6203                            returnTypes: nil];
6205   ns_window_num++;
6206   return self;
6210 - (void)windowDidMove: sender
6212   NSWindow *win = [self window];
6213   NSRect r = [win frame];
6214   NSArray *screens = [NSScreen screens];
6215   NSScreen *screen = [screens objectAtIndex: 0];
6217   NSTRACE (windowDidMove);
6219   if (!emacsframe->output_data.ns)
6220     return;
6221   if (screen != nil)
6222     {
6223       emacsframe->left_pos = r.origin.x;
6224       emacsframe->top_pos =
6225         [screen frame].size.height - (r.origin.y + r.size.height);
6226     }
6230 /* Called AFTER method below, but before our windowWillResize call there leads
6231    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6232    location so set_window_size moves the frame. */
6233 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6235   emacsframe->output_data.ns->zooming = 1;
6236   return YES;
6240 /* Override to do something slightly nonstandard, but nice.  First click on
6241    zoom button will zoom vertically.  Second will zoom completely.  Third
6242    returns to original. */
6243 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6244                         defaultFrame:(NSRect)defaultFrame
6246   NSRect result = [sender frame];
6248   NSTRACE (windowWillUseStandardFrame);
6250   if (fs_before_fs != -1) /* Entering fullscreen */
6251       {
6252         result = defaultFrame;
6253       }
6254   else if (next_maximized == FULLSCREEN_HEIGHT
6255       || (next_maximized == -1
6256           && abs (defaultFrame.size.height - result.size.height)
6257           > FRAME_LINE_HEIGHT (emacsframe)))
6258     {
6259       /* first click */
6260       ns_userRect = result;
6261       maximized_height = result.size.height = defaultFrame.size.height;
6262       maximized_width = -1;
6263       result.origin.y = defaultFrame.origin.y;
6264       [self setFSValue: FULLSCREEN_HEIGHT];
6265 #ifdef NS_IMPL_COCOA
6266       maximizing_resize = YES;
6267 #endif
6268     }
6269   else if (next_maximized == FULLSCREEN_WIDTH)
6270     {
6271       ns_userRect = result;
6272       maximized_width = result.size.width = defaultFrame.size.width;
6273       maximized_height = -1;
6274       result.origin.x = defaultFrame.origin.x;
6275       [self setFSValue: FULLSCREEN_WIDTH];
6276     }
6277   else if (next_maximized == FULLSCREEN_MAXIMIZED
6278            || (next_maximized == -1
6279                && abs (defaultFrame.size.width - result.size.width)
6280                > FRAME_COLUMN_WIDTH (emacsframe)))
6281     {
6282       result = defaultFrame;  /* second click */
6283       maximized_width = result.size.width;
6284       maximized_height = result.size.height;
6285       [self setFSValue: FULLSCREEN_MAXIMIZED];
6286 #ifdef NS_IMPL_COCOA
6287       maximizing_resize = YES;
6288 #endif
6289     }
6290   else
6291     {
6292       /* restore */
6293       result = ns_userRect.size.height ? ns_userRect : result;
6294       ns_userRect = NSMakeRect (0, 0, 0, 0);
6295 #ifdef NS_IMPL_COCOA
6296       maximizing_resize = fs_state != FULLSCREEN_NONE;
6297 #endif
6298       [self setFSValue: FULLSCREEN_NONE];
6299       maximized_width = maximized_height = -1;
6300     }
6302   if (fs_before_fs == -1) next_maximized = -1;
6303   [self windowWillResize: sender toSize: result.size];
6304   return result;
6308 - (void)windowDidDeminiaturize: sender
6310   NSTRACE (windowDidDeminiaturize);
6311   if (!emacsframe->output_data.ns)
6312     return;
6314   SET_FRAME_ICONIFIED (emacsframe, 0);
6315   SET_FRAME_VISIBLE (emacsframe, 1);
6316   windows_or_buffers_changed = 63;
6318   if (emacs_event)
6319     {
6320       emacs_event->kind = DEICONIFY_EVENT;
6321       EV_TRAILER ((id)nil);
6322     }
6326 - (void)windowDidExpose: sender
6328   NSTRACE (windowDidExpose);
6329   if (!emacsframe->output_data.ns)
6330     return;
6332   SET_FRAME_VISIBLE (emacsframe, 1);
6333   SET_FRAME_GARBAGED (emacsframe);
6335   if (send_appdefined)
6336     ns_send_appdefined (-1);
6340 - (void)windowDidMiniaturize: sender
6342   NSTRACE (windowDidMiniaturize);
6343   if (!emacsframe->output_data.ns)
6344     return;
6346   SET_FRAME_ICONIFIED (emacsframe, 1);
6347   SET_FRAME_VISIBLE (emacsframe, 0);
6349   if (emacs_event)
6350     {
6351       emacs_event->kind = ICONIFY_EVENT;
6352       EV_TRAILER ((id)nil);
6353     }
6356 #ifdef HAVE_NATIVE_FS
6357 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6358       willUseFullScreenPresentationOptions:
6359   (NSApplicationPresentationOptions)proposedOptions
6361   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6363 #endif
6365 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6367   fs_before_fs = fs_state;
6370 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6372   [self setFSValue: FULLSCREEN_BOTH];
6373   if (! [self fsIsNative])
6374     {
6375       [self windowDidBecomeKey:notification];
6376       [nonfs_window orderOut:self];
6377     }
6378   else
6379     {
6380       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6381 #ifdef NS_IMPL_COCOA
6382 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6383       unsigned val = (unsigned)[NSApp presentationOptions];
6385       // OSX 10.7 bug fix, the menu won't appear without this.
6386       // val is non-zero on other OSX versions.
6387       if (val == 0)
6388         {
6389           NSApplicationPresentationOptions options
6390             = NSApplicationPresentationAutoHideDock
6391             | NSApplicationPresentationAutoHideMenuBar
6392             | NSApplicationPresentationFullScreen
6393             | NSApplicationPresentationAutoHideToolbar;
6395           [NSApp setPresentationOptions: options];
6396         }
6397 #endif
6398 #endif
6399       [toolbar setVisible:tbar_visible];
6400     }
6403 - (void)windowWillExitFullScreen:(NSNotification *)notification
6405   if (next_maximized != -1)
6406     fs_before_fs = next_maximized;
6409 - (void)windowDidExitFullScreen:(NSNotification *)notification
6411   [self setFSValue: fs_before_fs];
6412   fs_before_fs = -1;
6413 #ifdef HAVE_NATIVE_FS
6414   [self updateCollectionBehavior];
6415 #endif
6416   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6417     {
6418       [toolbar setVisible:YES];
6419       update_frame_tool_bar (emacsframe);
6420       [self updateFrameSize:YES];
6421       [[self window] display];
6422     }
6423   else
6424     [toolbar setVisible:NO];
6426   if (next_maximized != -1)
6427     [[self window] performZoom:self];
6430 - (BOOL)fsIsNative
6432   return fs_is_native;
6435 - (BOOL)isFullscreen
6437   if (! fs_is_native) return nonfs_window != nil;
6438 #ifdef HAVE_NATIVE_FS
6439   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6440 #else
6441   return NO;
6442 #endif
6445 #ifdef HAVE_NATIVE_FS
6446 - (void)updateCollectionBehavior
6448   if (! [self isFullscreen])
6449     {
6450       NSWindow *win = [self window];
6451       NSWindowCollectionBehavior b = [win collectionBehavior];
6452       if (ns_use_native_fullscreen)
6453         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6454       else
6455         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6457       [win setCollectionBehavior: b];
6458       fs_is_native = ns_use_native_fullscreen;
6459     }
6461 #endif
6463 - (void)toggleFullScreen: (id)sender
6465   NSWindow *w, *fw;
6466   BOOL onFirstScreen;
6467   struct frame *f;
6468   NSSize sz;
6469   NSRect r, wr;
6470   NSColor *col;
6472   if (fs_is_native)
6473     {
6474 #ifdef HAVE_NATIVE_FS
6475       [[self window] toggleFullScreen:sender];
6476 #endif
6477       return;
6478     }
6480   w = [self window];
6481   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6482   f = emacsframe;
6483   wr = [w frame];
6484   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6485                                  (FRAME_DEFAULT_FACE (f)),
6486                                  f);
6488   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6489   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6491   if (fs_state != FULLSCREEN_BOTH)
6492     {
6493       NSScreen *screen = [w screen];
6495 #if defined (NS_IMPL_COCOA) && \
6496   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6497       /* Hide ghost menu bar on secondary monitor? */
6498       if (! onFirstScreen)
6499         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6500 #endif
6501       /* Hide dock and menubar if we are on the primary screen.  */
6502       if (onFirstScreen)
6503         {
6504 #if defined (NS_IMPL_COCOA) && \
6505   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6506           NSApplicationPresentationOptions options
6507             = NSApplicationPresentationAutoHideDock
6508             | NSApplicationPresentationAutoHideMenuBar;
6510           [NSApp setPresentationOptions: options];
6511 #else
6512           [NSMenu setMenuBarVisible:NO];
6513 #endif
6514         }
6516       fw = [[EmacsFSWindow alloc]
6517                        initWithContentRect:[w contentRectForFrameRect:wr]
6518                                  styleMask:NSBorderlessWindowMask
6519                                    backing:NSBackingStoreBuffered
6520                                      defer:YES
6521                                     screen:screen];
6523       [fw setContentView:[w contentView]];
6524       [fw setTitle:[w title]];
6525       [fw setDelegate:self];
6526       [fw setAcceptsMouseMovedEvents: YES];
6527       [fw useOptimizedDrawing: YES];
6528       [fw setResizeIncrements: sz];
6529       [fw setBackgroundColor: col];
6530       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6531         [fw setOpaque: NO];
6533       f->border_width = 0;
6534       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6535       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6536       FRAME_TOOLBAR_HEIGHT (f) = 0;
6538       nonfs_window = w;
6540       [self windowWillEnterFullScreen:nil];
6541       [fw makeKeyAndOrderFront:NSApp];
6542       [fw makeFirstResponder:self];
6543       [w orderOut:self];
6544       r = [fw frameRectForContentRect:[screen frame]];
6545       [fw setFrame: r display:YES animate:YES];
6546       [self windowDidEnterFullScreen:nil];
6547       [fw display];
6548     }
6549   else
6550     {
6551       fw = w;
6552       w = nonfs_window;
6553       nonfs_window = nil;
6555       if (onFirstScreen)
6556         {
6557 #if defined (NS_IMPL_COCOA) && \
6558   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6559           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6560 #else
6561           [NSMenu setMenuBarVisible:YES];
6562 #endif
6563         }
6565       [w setContentView:[fw contentView]];
6566       [w setResizeIncrements: sz];
6567       [w setBackgroundColor: col];
6568       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6569         [w setOpaque: NO];
6571       f->border_width = bwidth;
6572       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6573       if (FRAME_EXTERNAL_TOOL_BAR (f))
6574         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6576       [self windowWillExitFullScreen:nil];
6577       [fw setFrame: [w frame] display:YES animate:YES];
6578       [fw close];
6579       [w makeKeyAndOrderFront:NSApp];
6580       [self windowDidExitFullScreen:nil];
6581       [self updateFrameSize:YES];
6582     }
6585 - (void)handleFS
6587   if (fs_state != emacsframe->want_fullscreen)
6588     {
6589       if (fs_state == FULLSCREEN_BOTH)
6590         {
6591           [self toggleFullScreen:self];
6592         }
6594       switch (emacsframe->want_fullscreen)
6595         {
6596         case FULLSCREEN_BOTH:
6597           [self toggleFullScreen:self];
6598           break;
6599         case FULLSCREEN_WIDTH:
6600           next_maximized = FULLSCREEN_WIDTH;
6601           if (fs_state != FULLSCREEN_BOTH)
6602             [[self window] performZoom:self];
6603           break;
6604         case FULLSCREEN_HEIGHT:
6605           next_maximized = FULLSCREEN_HEIGHT;
6606           if (fs_state != FULLSCREEN_BOTH)
6607             [[self window] performZoom:self];
6608           break;
6609         case FULLSCREEN_MAXIMIZED:
6610           next_maximized = FULLSCREEN_MAXIMIZED;
6611           if (fs_state != FULLSCREEN_BOTH)
6612             [[self window] performZoom:self];
6613           break;
6614         case FULLSCREEN_NONE:
6615           if (fs_state != FULLSCREEN_BOTH)
6616             {
6617               next_maximized = FULLSCREEN_NONE;
6618               [[self window] performZoom:self];
6619             }
6620           break;
6621         }
6623       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6624     }
6628 - (void) setFSValue: (int)value
6630   Lisp_Object lval = Qnil;
6631   switch (value)
6632     {
6633     case FULLSCREEN_BOTH:
6634       lval = Qfullboth;
6635       break;
6636     case FULLSCREEN_WIDTH:
6637       lval = Qfullwidth;
6638       break;
6639     case FULLSCREEN_HEIGHT:
6640       lval = Qfullheight;
6641       break;
6642     case FULLSCREEN_MAXIMIZED:
6643       lval = Qmaximized;
6644       break;
6645     }
6646   store_frame_param (emacsframe, Qfullscreen, lval);
6647   fs_state = value;
6650 - (void)mouseEntered: (NSEvent *)theEvent
6652   NSTRACE (mouseEntered);
6653   if (emacsframe)
6654     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6655       = EV_TIMESTAMP (theEvent);
6659 - (void)mouseExited: (NSEvent *)theEvent
6661   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6663   NSTRACE (mouseExited);
6665   if (!hlinfo)
6666     return;
6668   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6669     = EV_TIMESTAMP (theEvent);
6671   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6672     {
6673       clear_mouse_face (hlinfo);
6674       hlinfo->mouse_face_mouse_frame = 0;
6675     }
6679 - menuDown: sender
6681   NSTRACE (menuDown);
6682   if (context_menu_value == -1)
6683     context_menu_value = [sender tag];
6684   else
6685     {
6686       NSInteger tag = [sender tag];
6687       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6688                                     emacsframe->menu_bar_vector,
6689                                     (void *)tag);
6690     }
6692   ns_send_appdefined (-1);
6693   return self;
6697 - (EmacsToolbar *)toolbar
6699   return toolbar;
6703 /* this gets called on toolbar button click */
6704 - toolbarClicked: (id)item
6706   NSEvent *theEvent;
6707   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6709   NSTRACE (toolbarClicked);
6711   if (!emacs_event)
6712     return self;
6714   /* send first event (for some reason two needed) */
6715   theEvent = [[self window] currentEvent];
6716   emacs_event->kind = TOOL_BAR_EVENT;
6717   XSETFRAME (emacs_event->arg, emacsframe);
6718   EV_TRAILER (theEvent);
6720   emacs_event->kind = TOOL_BAR_EVENT;
6721 /*   XSETINT (emacs_event->code, 0); */
6722   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6723                            idx + TOOL_BAR_ITEM_KEY);
6724   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6725   EV_TRAILER (theEvent);
6726   return self;
6730 - toggleToolbar: (id)sender
6732   if (!emacs_event)
6733     return self;
6735   emacs_event->kind = NS_NONKEY_EVENT;
6736   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6737   EV_TRAILER ((id)nil);
6738   return self;
6742 - (void)drawRect: (NSRect)rect
6744   int x = NSMinX (rect), y = NSMinY (rect);
6745   int width = NSWidth (rect), height = NSHeight (rect);
6747   NSTRACE (drawRect);
6749   if (!emacsframe || !emacsframe->output_data.ns)
6750     return;
6752   ns_clear_frame_area (emacsframe, x, y, width, height);
6753   block_input ();
6754   expose_frame (emacsframe, x, y, width, height);
6755   unblock_input ();
6757   /*
6758     drawRect: may be called (at least in OS X 10.5) for invisible
6759     views as well for some reason.  Thus, do not infer visibility
6760     here.
6762     emacsframe->async_visible = 1;
6763     emacsframe->async_iconified = 0;
6764   */
6768 /* NSDraggingDestination protocol methods.  Actually this is not really a
6769    protocol, but a category of Object.  O well...  */
6771 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6773   NSTRACE (draggingEntered);
6774   return NSDragOperationGeneric;
6778 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6780   return YES;
6784 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6786   id pb;
6787   int x, y;
6788   NSString *type;
6789   NSEvent *theEvent = [[self window] currentEvent];
6790   NSPoint position;
6791   NSDragOperation op = [sender draggingSourceOperationMask];
6792   int modifiers = 0;
6794   NSTRACE (performDragOperation);
6796   if (!emacs_event)
6797     return NO;
6799   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6800   x = lrint (position.x);  y = lrint (position.y);
6802   pb = [sender draggingPasteboard];
6803   type = [pb availableTypeFromArray: ns_drag_types];
6805   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6806       // URL drags contain all operations (0xf), don't allow all to be set.
6807       (op & 0xf) != 0xf)
6808     {
6809       if (op & NSDragOperationLink)
6810         modifiers |= NSControlKeyMask;
6811       if (op & NSDragOperationCopy)
6812         modifiers |= NSAlternateKeyMask;
6813       if (op & NSDragOperationGeneric)
6814         modifiers |= NSCommandKeyMask;
6815     }
6817   modifiers = EV_MODIFIERS2 (modifiers);
6818   if (type == 0)
6819     {
6820       return NO;
6821     }
6822   else if ([type isEqualToString: NSFilenamesPboardType])
6823     {
6824       NSArray *files;
6825       NSEnumerator *fenum;
6826       NSString *file;
6828       if (!(files = [pb propertyListForType: type]))
6829         return NO;
6831       fenum = [files objectEnumerator];
6832       while ( (file = [fenum nextObject]) )
6833         {
6834           emacs_event->kind = DRAG_N_DROP_EVENT;
6835           XSETINT (emacs_event->x, x);
6836           XSETINT (emacs_event->y, y);
6837           ns_input_file = append2 (ns_input_file,
6838                                    build_string ([file UTF8String]));
6839           emacs_event->modifiers = modifiers;
6840           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
6841           EV_TRAILER (theEvent);
6842         }
6843       return YES;
6844     }
6845   else if ([type isEqualToString: NSURLPboardType])
6846     {
6847       NSURL *url = [NSURL URLFromPasteboard: pb];
6848       if (url == nil) return NO;
6850       emacs_event->kind = DRAG_N_DROP_EVENT;
6851       XSETINT (emacs_event->x, x);
6852       XSETINT (emacs_event->y, y);
6853       emacs_event->modifiers = modifiers;
6854       emacs_event->arg =  list2 (Qurl,
6855                                  build_string ([[url absoluteString]
6856                                                  UTF8String]));
6857       EV_TRAILER (theEvent);
6859       if ([url isFileURL] != NO)
6860         {
6861           NSString *file = [url path];
6862           ns_input_file = append2 (ns_input_file,
6863                                    build_string ([file UTF8String]));
6864         }
6865       return YES;
6866     }
6867   else if ([type isEqualToString: NSStringPboardType]
6868            || [type isEqualToString: NSTabularTextPboardType])
6869     {
6870       NSString *data;
6872       if (! (data = [pb stringForType: type]))
6873         return NO;
6875       emacs_event->kind = DRAG_N_DROP_EVENT;
6876       XSETINT (emacs_event->x, x);
6877       XSETINT (emacs_event->y, y);
6878       emacs_event->modifiers = modifiers;
6879       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
6880       EV_TRAILER (theEvent);
6881       return YES;
6882     }
6883   else
6884     {
6885       error ("Invalid data type in dragging pasteboard");
6886       return NO;
6887     }
6891 - (id) validRequestorForSendType: (NSString *)typeSent
6892                       returnType: (NSString *)typeReturned
6894   NSTRACE (validRequestorForSendType);
6895   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6896       && typeReturned == nil)
6897     {
6898       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6899         return self;
6900     }
6902   return [super validRequestorForSendType: typeSent
6903                                returnType: typeReturned];
6907 /* The next two methods are part of NSServicesRequests informal protocol,
6908    supposedly called when a services menu item is chosen from this app.
6909    But this should not happen because we override the services menu with our
6910    own entries which call ns-perform-service.
6911    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6912    So let's at least stub them out until further investigation can be done. */
6914 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6916   /* we could call ns_string_from_pasteboard(pboard) here but then it should
6917      be written into the buffer in place of the existing selection..
6918      ordinary service calls go through functions defined in ns-win.el */
6919   return NO;
6922 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6924   NSArray *typesDeclared;
6925   Lisp_Object val;
6927   /* We only support NSStringPboardType */
6928   if ([types containsObject:NSStringPboardType] == NO) {
6929     return NO;
6930   }
6932   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6933   if (CONSP (val) && SYMBOLP (XCAR (val)))
6934     {
6935       val = XCDR (val);
6936       if (CONSP (val) && NILP (XCDR (val)))
6937         val = XCAR (val);
6938     }
6939   if (! STRINGP (val))
6940     return NO;
6942   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6943   [pb declareTypes:typesDeclared owner:nil];
6944   ns_string_to_pasteboard (pb, val);
6945   return YES;
6949 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6950    (gives a miniaturized version of the window); currently we use the latter for
6951    frames whose active buffer doesn't correspond to any file
6952    (e.g., '*scratch*') */
6953 - setMiniwindowImage: (BOOL) setMini
6955   id image = [[self window] miniwindowImage];
6956   NSTRACE (setMiniwindowImage);
6958   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6959      about "AppleDockIconEnabled" notwithstanding, however the set message
6960      below has its effect nonetheless. */
6961   if (image != emacsframe->output_data.ns->miniimage)
6962     {
6963       if (image && [image isKindOfClass: [EmacsImage class]])
6964         [image release];
6965       [[self window] setMiniwindowImage:
6966                        setMini ? emacsframe->output_data.ns->miniimage : nil];
6967     }
6969   return self;
6973 - (void) setRows: (int) r andColumns: (int) c
6975   rows = r;
6976   cols = c;
6979 @end  /* EmacsView */
6983 /* ==========================================================================
6985     EmacsWindow implementation
6987    ========================================================================== */
6989 @implementation EmacsWindow
6991 #ifdef NS_IMPL_COCOA
6992 - (id)accessibilityAttributeValue:(NSString *)attribute
6994   Lisp_Object str = Qnil;
6995   struct frame *f = SELECTED_FRAME ();
6996   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
6998   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6999     return NSAccessibilityTextFieldRole;
7001   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7002       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7003     {
7004       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7005     }
7006   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7007     {
7008       if (! NILP (BVAR (curbuf, mark_active)))
7009           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7011       if (NILP (str))
7012         {
7013           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7014           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7015           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7017           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7018             str = make_uninit_multibyte_string (range, byte_range);
7019           else
7020             str = make_uninit_string (range);
7021           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7022              Is this a problem?  */
7023           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7024         }
7025     }
7028   if (! NILP (str))
7029     {
7030       if (CONSP (str) && SYMBOLP (XCAR (str)))
7031         {
7032           str = XCDR (str);
7033           if (CONSP (str) && NILP (XCDR (str)))
7034             str = XCAR (str);
7035         }
7036       if (STRINGP (str))
7037         {
7038           const char *utfStr = SSDATA (str);
7039           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7040           return nsStr;
7041         }
7042     }
7044   return [super accessibilityAttributeValue:attribute];
7046 #endif /* NS_IMPL_COCOA */
7048 /* If we have multiple monitors, one above the other, we don't want to
7049    restrict the height to just one monitor.  So we override this.  */
7050 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7052   /* When making the frame visible for the first time or if there is just
7053      one screen, we want to constrain.  Other times not.  */
7054   NSArray *screens = [NSScreen screens];
7055   NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7056   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
7057   NSTRACE (constrainFrameRect);
7058   NSTRACE_RECT ("input", frameRect);
7060   if (ns_menu_bar_should_be_hidden ())
7061     return frameRect;
7063   if (nr_screens == 1)
7064     return [super constrainFrameRect:frameRect toScreen:screen];
7066 #ifdef NS_IMPL_COCOA
7067 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7068   // If separate spaces is on, it is like each screen is independent.  There is
7069   // no spanning of frames across screens.
7070   if ([NSScreen screensHaveSeparateSpaces])
7071     return [super constrainFrameRect:frameRect toScreen:screen];
7072 #endif
7073 #endif
7075   for (i = 0; i < nr_screens; ++i) 
7076     {
7077       NSScreen *s = [screens objectAtIndex: i];
7078       NSRect scrrect = [s frame];
7079       NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7081       if (intersect.size.width > 0 || intersect.size.height > 0)
7082         ++nr_eff_screens;
7083     }
7085   if (nr_eff_screens == 1)
7086     return [super constrainFrameRect:frameRect toScreen:screen];
7087   
7088   /* The default implementation does two things 1) ensure that the top
7089      of the rectangle is below the menu bar (or below the top of the
7090      screen) and 2) resizes windows larger than the screen. As we
7091      don't want the latter, a smaller rectangle is used. */
7092 #define FAKE_HEIGHT 64
7093   float old_top = frameRect.origin.y + frameRect.size.height;
7094   NSRect r;
7095   r.size.height = FAKE_HEIGHT;
7096   r.size.width = frameRect.size.width;
7097   r.origin.x = frameRect.origin.x;
7098   r.origin.y = old_top - FAKE_HEIGHT;
7100   NSTRACE_RECT ("input to super", r);
7102   r = [super constrainFrameRect:r toScreen:screen];
7104   NSTRACE_RECT ("output from super", r);
7106   float new_top = r.origin.y + FAKE_HEIGHT;
7107   if (new_top < old_top)
7108   {
7109     frameRect.origin.y = new_top - frameRect.size.height;
7110   }
7112   NSTRACE_RECT ("output", frameRect);
7114   return frameRect;
7115 #undef FAKE_HEIGHT
7118 @end /* EmacsWindow */
7121 @implementation EmacsFSWindow
7123 - (BOOL)canBecomeKeyWindow
7125   return YES;
7128 - (BOOL)canBecomeMainWindow
7130   return YES;
7133 @end
7135 /* ==========================================================================
7137     EmacsScroller implementation
7139    ========================================================================== */
7142 @implementation EmacsScroller
7144 /* for repeat button push */
7145 #define SCROLL_BAR_FIRST_DELAY 0.5
7146 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7148 + (CGFloat) scrollerWidth
7150   /* TODO: if we want to allow variable widths, this is the place to do it,
7151            however neither GNUstep nor Cocoa support it very well */
7152   return [NSScroller scrollerWidth];
7156 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7158   NSTRACE (EmacsScroller_initFrame);
7160   r.size.width = [EmacsScroller scrollerWidth];
7161   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7162   [self setContinuous: YES];
7163   [self setEnabled: YES];
7165   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7166      locked against the top and bottom edges, and right edge on OS X, where
7167      scrollers are on right. */
7168 #ifdef NS_IMPL_GNUSTEP
7169   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7170 #else
7171   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7172 #endif
7174   window = XWINDOW (nwin);
7175   condemned = NO;
7176   pixel_height = NSHeight (r);
7177   if (pixel_height == 0) pixel_height = 1;
7178   min_portion = 20 / pixel_height;
7180   frame = XFRAME (window->frame);
7181   if (FRAME_LIVE_P (frame))
7182     {
7183       int i;
7184       EmacsView *view = FRAME_NS_VIEW (frame);
7185       NSView *sview = [[view window] contentView];
7186       NSArray *subs = [sview subviews];
7188       /* disable optimization stopping redraw of other scrollbars */
7189       view->scrollbarsNeedingUpdate = 0;
7190       for (i =[subs count]-1; i >= 0; i--)
7191         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7192           view->scrollbarsNeedingUpdate++;
7193       [sview addSubview: self];
7194     }
7196 /*  [self setFrame: r]; */
7198   return self;
7202 - (void)setFrame: (NSRect)newRect
7204   NSTRACE (EmacsScroller_setFrame);
7205 /*  block_input (); */
7206   pixel_height = NSHeight (newRect);
7207   if (pixel_height == 0) pixel_height = 1;
7208   min_portion = 20 / pixel_height;
7209   [super setFrame: newRect];
7210 /*  unblock_input (); */
7214 - (void)dealloc
7216   NSTRACE (EmacsScroller_dealloc);
7217   if (window)
7218     wset_vertical_scroll_bar (window, Qnil);
7219   window = 0;
7220   [super dealloc];
7224 - condemn
7226   NSTRACE (condemn);
7227   condemned =YES;
7228   return self;
7232 - reprieve
7234   NSTRACE (reprieve);
7235   condemned =NO;
7236   return self;
7240 -(bool)judge
7242   NSTRACE (judge);
7243   bool ret = condemned;
7244   if (condemned)
7245     {
7246       EmacsView *view;
7247       block_input ();
7248       /* ensure other scrollbar updates after deletion */
7249       view = (EmacsView *)FRAME_NS_VIEW (frame);
7250       if (view != nil)
7251         view->scrollbarsNeedingUpdate++;
7252       if (window)
7253         wset_vertical_scroll_bar (window, Qnil);
7254       window = 0;
7255       [self removeFromSuperview];
7256       [self release];
7257       unblock_input ();
7258     }
7259   return ret;
7263 - (void)resetCursorRects
7265   NSRect visible = [self visibleRect];
7266   NSTRACE (resetCursorRects);
7268   if (!NSIsEmptyRect (visible))
7269     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7270   [[NSCursor arrowCursor] setOnMouseEntered: YES];
7274 - (int) checkSamePosition: (int) position portion: (int) portion
7275                     whole: (int) whole
7277   return em_position ==position && em_portion ==portion && em_whole ==whole
7278     && portion != whole; /* needed for resize empty buf */
7282 - setPosition: (int)position portion: (int)portion whole: (int)whole
7284   NSTRACE (setPosition);
7286   em_position = position;
7287   em_portion = portion;
7288   em_whole = whole;
7290   if (portion >= whole)
7291     {
7292 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
7293       [self setKnobProportion: 1.0];
7294       [self setDoubleValue: 1.0];
7295 #else
7296       [self setFloatValue: 0.0 knobProportion: 1.0];
7297 #endif
7298     }
7299   else
7300     {
7301       float pos;
7302       CGFloat por;
7303       portion = max ((float)whole*min_portion/pixel_height, portion);
7304       pos = (float)position / (whole - portion);
7305       por = (CGFloat)portion/whole;
7306 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
7307       [self setKnobProportion: por];
7308       [self setDoubleValue: pos];
7309 #else
7310       [self setFloatValue: pos knobProportion: por];
7311 #endif
7312     }
7314   return self;
7317 /* set up emacs_event */
7318 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7320   Lisp_Object win;
7321   if (!emacs_event)
7322     return;
7324   emacs_event->part = last_hit_part;
7325   emacs_event->code = 0;
7326   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7327   XSETWINDOW (win, window);
7328   emacs_event->frame_or_window = win;
7329   emacs_event->timestamp = EV_TIMESTAMP (e);
7330   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7331   emacs_event->arg = Qnil;
7332   XSETINT (emacs_event->x, loc * pixel_height);
7333   XSETINT (emacs_event->y, pixel_height-20);
7335   if (q_event_ptr)
7336     {
7337       n_emacs_events_pending++;
7338       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7339     }
7340   else
7341     hold_event (emacs_event);
7342   EVENT_INIT (*emacs_event);
7343   ns_send_appdefined (-1);
7347 /* called manually thru timer to implement repeated button action w/hold-down */
7348 - repeatScroll: (NSTimer *)scrollEntry
7350   NSEvent *e = [[self window] currentEvent];
7351   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7352   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7354   /* clear timer if need be */
7355   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7356     {
7357         [scroll_repeat_entry invalidate];
7358         [scroll_repeat_entry release];
7359         scroll_repeat_entry = nil;
7361         if (inKnob)
7362           return self;
7364         scroll_repeat_entry
7365           = [[NSTimer scheduledTimerWithTimeInterval:
7366                         SCROLL_BAR_CONTINUOUS_DELAY
7367                                             target: self
7368                                           selector: @selector (repeatScroll:)
7369                                           userInfo: 0
7370                                            repeats: YES]
7371               retain];
7372     }
7374   [self sendScrollEventAtLoc: 0 fromEvent: e];
7375   return self;
7379 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7380    mouseDragged events without going into a modal loop. */
7381 - (void)mouseDown: (NSEvent *)e
7383   NSRect sr, kr;
7384   /* hitPart is only updated AFTER event is passed on */
7385   NSScrollerPart part = [self testPart: [e locationInWindow]];
7386   CGFloat inc = 0.0, loc, kloc, pos;
7387   int edge = 0;
7389   NSTRACE (EmacsScroller_mouseDown);
7391   switch (part)
7392     {
7393     case NSScrollerDecrementPage:
7394         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7395     case NSScrollerIncrementPage:
7396         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7397     case NSScrollerDecrementLine:
7398       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7399     case NSScrollerIncrementLine:
7400       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7401     case NSScrollerKnob:
7402       last_hit_part = scroll_bar_handle; break;
7403     case NSScrollerKnobSlot:  /* GNUstep-only */
7404       last_hit_part = scroll_bar_move_ratio; break;
7405     default:  /* NSScrollerNoPart? */
7406       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7407                (long) part);
7408       return;
7409     }
7411   if (inc != 0.0)
7412     {
7413       pos = 0;      /* ignored */
7415       /* set a timer to repeat, as we can't let superclass do this modally */
7416       scroll_repeat_entry
7417         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7418                                             target: self
7419                                           selector: @selector (repeatScroll:)
7420                                           userInfo: 0
7421                                            repeats: YES]
7422             retain];
7423     }
7424   else
7425     {
7426       /* handle, or on GNUstep possibly slot */
7427       NSEvent *fake_event;
7429       /* compute float loc in slot and mouse offset on knob */
7430       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7431                       toView: nil];
7432       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7433       if (loc <= 0.0)
7434         {
7435           loc = 0.0;
7436           edge = -1;
7437         }
7438       else if (loc >= NSHeight (sr))
7439         {
7440           loc = NSHeight (sr);
7441           edge = 1;
7442         }
7444       if (edge)
7445         kloc = 0.5 * edge;
7446       else
7447         {
7448           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7449                           toView: nil];
7450           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7451         }
7452       last_mouse_offset = kloc;
7454       /* if knob, tell emacs a location offset by knob pos
7455          (to indicate top of handle) */
7456       if (part == NSScrollerKnob)
7457           pos = (loc - last_mouse_offset) / NSHeight (sr);
7458       else
7459         /* else this is a slot click on GNUstep: go straight there */
7460         pos = loc / NSHeight (sr);
7462       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7463       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7464                                       location: [e locationInWindow]
7465                                  modifierFlags: [e modifierFlags]
7466                                      timestamp: [e timestamp]
7467                                   windowNumber: [e windowNumber]
7468                                        context: [e context]
7469                                    eventNumber: [e eventNumber]
7470                                     clickCount: [e clickCount]
7471                                       pressure: [e pressure]];
7472       [super mouseUp: fake_event];
7473     }
7475   if (part != NSScrollerKnob)
7476     [self sendScrollEventAtLoc: pos fromEvent: e];
7480 /* Called as we manually track scroller drags, rather than superclass. */
7481 - (void)mouseDragged: (NSEvent *)e
7483     NSRect sr;
7484     double loc, pos;
7486     NSTRACE (EmacsScroller_mouseDragged);
7488       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7489                       toView: nil];
7490       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7492       if (loc <= 0.0)
7493         {
7494           loc = 0.0;
7495         }
7496       else if (loc >= NSHeight (sr) + last_mouse_offset)
7497         {
7498           loc = NSHeight (sr) + last_mouse_offset;
7499         }
7501       pos = (loc - last_mouse_offset) / NSHeight (sr);
7502       [self sendScrollEventAtLoc: pos fromEvent: e];
7506 - (void)mouseUp: (NSEvent *)e
7508   if (scroll_repeat_entry)
7509     {
7510       [scroll_repeat_entry invalidate];
7511       [scroll_repeat_entry release];
7512       scroll_repeat_entry = nil;
7513     }
7514   last_hit_part = 0;
7518 /* treat scrollwheel events in the bar as though they were in the main window */
7519 - (void) scrollWheel: (NSEvent *)theEvent
7521   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7522   [view mouseDown: theEvent];
7525 @end  /* EmacsScroller */
7528 #ifdef NS_IMPL_GNUSTEP
7529 /* Dummy class to get rid of startup warnings.  */
7530 @implementation EmacsDocument
7532 @end
7533 #endif
7536 /* ==========================================================================
7538    Font-related functions; these used to be in nsfaces.m
7540    ========================================================================== */
7543 Lisp_Object
7544 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7546   struct font *font = XFONT_OBJECT (font_object);
7547   EmacsView *view = FRAME_NS_VIEW (f);
7549   if (fontset < 0)
7550     fontset = fontset_from_font (font_object);
7551   FRAME_FONTSET (f) = fontset;
7553   if (FRAME_FONT (f) == font)
7554     /* This font is already set in frame F.  There's nothing more to
7555        do.  */
7556     return font_object;
7558   FRAME_FONT (f) = font;
7560   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7561   FRAME_COLUMN_WIDTH (f) = font->average_width;
7562   FRAME_LINE_HEIGHT (f) = font->height;
7564   compute_fringe_widths (f, 1);
7566   /* Compute the scroll bar width in character columns.  */
7567   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7568     {
7569       int wid = FRAME_COLUMN_WIDTH (f);
7570       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7571         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7572     }
7573   else
7574     {
7575       int wid = FRAME_COLUMN_WIDTH (f);
7576       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7577     }
7579   /* Now make the frame display the given font.  */
7580   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7581     x_set_window_size (f, 0, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7582                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 1);
7584   return font_object;
7588 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7589 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7590          in 1.43. */
7592 const char *
7593 ns_xlfd_to_fontname (const char *xlfd)
7594 /* --------------------------------------------------------------------------
7595     Convert an X font name (XLFD) to an NS font name.
7596     Only family is used.
7597     The string returned is temporarily allocated.
7598    -------------------------------------------------------------------------- */
7600   char *name = xmalloc (180);
7601   int i, len;
7602   const char *ret;
7604   if (!strncmp (xlfd, "--", 2))
7605     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7606   else
7607     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7609   /* stopgap for malformed XLFD input */
7610   if (strlen (name) == 0)
7611     strcpy (name, "Monaco");
7613   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7614      also uppercase after '-' or ' ' */
7615   name[0] = c_toupper (name[0]);
7616   for (len =strlen (name), i =0; i<len; i++)
7617     {
7618       if (name[i] == '$')
7619         {
7620           name[i] = '-';
7621           if (i+1<len)
7622             name[i+1] = c_toupper (name[i+1]);
7623         }
7624       else if (name[i] == '_')
7625         {
7626           name[i] = ' ';
7627           if (i+1<len)
7628             name[i+1] = c_toupper (name[i+1]);
7629         }
7630     }
7631 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7632   ret = [[NSString stringWithUTF8String: name] UTF8String];
7633   xfree (name);
7634   return ret;
7638 void
7639 syms_of_nsterm (void)
7641   NSTRACE (syms_of_nsterm);
7643   ns_antialias_threshold = 10.0;
7645   /* from 23+ we need to tell emacs what modifiers there are.. */
7646   DEFSYM (Qmodifier_value, "modifier-value");
7647   DEFSYM (Qalt, "alt");
7648   DEFSYM (Qhyper, "hyper");
7649   DEFSYM (Qmeta, "meta");
7650   DEFSYM (Qsuper, "super");
7651   DEFSYM (Qcontrol, "control");
7652   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7654   DEFSYM (Qfile, "file");
7655   DEFSYM (Qurl, "url");
7657   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7658   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7659   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7660   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7661   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7663   DEFVAR_LISP ("ns-input-file", ns_input_file,
7664               "The file specified in the last NS event.");
7665   ns_input_file =Qnil;
7667   DEFVAR_LISP ("ns-working-text", ns_working_text,
7668               "String for visualizing working composition sequence.");
7669   ns_working_text =Qnil;
7671   DEFVAR_LISP ("ns-input-font", ns_input_font,
7672               "The font specified in the last NS event.");
7673   ns_input_font =Qnil;
7675   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7676               "The fontsize specified in the last NS event.");
7677   ns_input_fontsize =Qnil;
7679   DEFVAR_LISP ("ns-input-line", ns_input_line,
7680                "The line specified in the last NS event.");
7681   ns_input_line =Qnil;
7683   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7684                "The service name specified in the last NS event.");
7685   ns_input_spi_name =Qnil;
7687   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7688                "The service argument specified in the last NS event.");
7689   ns_input_spi_arg =Qnil;
7691   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7692                "This variable describes the behavior of the alternate or option key.\n\
7693 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7694 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7695 at all, allowing it to be used at a lower level for accented character entry.");
7696   ns_alternate_modifier = Qmeta;
7698   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7699                "This variable describes the behavior of the right alternate or option key.\n\
7700 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7701 Set to left means be the same key as `ns-alternate-modifier'.\n\
7702 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7703 at all, allowing it to be used at a lower level for accented character entry.");
7704   ns_right_alternate_modifier = Qleft;
7706   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7707                "This variable describes the behavior of the command key.\n\
7708 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7709   ns_command_modifier = Qsuper;
7711   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7712                "This variable describes the behavior of the right command key.\n\
7713 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7714 Set to left means be the same key as `ns-command-modifier'.\n\
7715 Set to none means that the command / option key is not interpreted by Emacs\n\
7716 at all, allowing it to be used at a lower level for accented character entry.");
7717   ns_right_command_modifier = Qleft;
7719   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7720                "This variable describes the behavior of the control key.\n\
7721 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7722   ns_control_modifier = Qcontrol;
7724   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7725                "This variable describes the behavior of the right control key.\n\
7726 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7727 Set to left means be the same key as `ns-control-modifier'.\n\
7728 Set to none means that the control / option key is not interpreted by Emacs\n\
7729 at all, allowing it to be used at a lower level for accented character entry.");
7730   ns_right_control_modifier = Qleft;
7732   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7733                "This variable describes the behavior of the function key (on laptops).\n\
7734 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7735 Set to none means that the function key is not interpreted by Emacs at all,\n\
7736 allowing it to be used at a lower level for accented character entry.");
7737   ns_function_modifier = Qnone;
7739   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7740                "Non-nil (the default) means to render text antialiased.");
7741   ns_antialias_text = Qt;
7743   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7744                "Whether to confirm application quit using dialog.");
7745   ns_confirm_quit = Qnil;
7747   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7748                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7749 Only works on OSX 10.6 or later.  */);
7750   ns_auto_hide_menu_bar = Qnil;
7752   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7753      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7754 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7755 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7756 Default is t for OSX >= 10.7, nil otherwise.  */);
7757 #ifdef HAVE_NATIVE_FS
7758   ns_use_native_fullscreen = YES;
7759 #else
7760   ns_use_native_fullscreen = NO;
7761 #endif
7762   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7764   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7765      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7766 Note that this does not apply to images.
7767 This variable is ignored on OSX < 10.7 and GNUstep.  */);
7768   ns_use_srgb_colorspace = YES;
7770   /* TODO: move to common code */
7771   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7772                doc: /* Which toolkit scroll bars Emacs uses, if any.
7773 A value of nil means Emacs doesn't use toolkit scroll bars.
7774 With the X Window system, the value is a symbol describing the
7775 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7776 With MS Windows or Nextstep, the value is t.  */);
7777   Vx_toolkit_scroll_bars = Qt;
7779   DEFVAR_BOOL ("x-use-underline-position-properties",
7780                x_use_underline_position_properties,
7781      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7782 A value of nil means ignore them.  If you encounter fonts with bogus
7783 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7784 to 4.1, set this to nil. */);
7785   x_use_underline_position_properties = 0;
7787   DEFVAR_BOOL ("x-underline-at-descent-line",
7788                x_underline_at_descent_line,
7789      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7790 A value of nil means to draw the underline according to the value of the
7791 variable `x-use-underline-position-properties', which is usually at the
7792 baseline level.  The default value is nil.  */);
7793   x_underline_at_descent_line = 0;
7795   /* Tell Emacs about this window system.  */
7796   Fprovide (Qns, Qnil);
7798   DEFSYM (Qcocoa, "cocoa");
7799   DEFSYM (Qgnustep, "gnustep");
7801   syms_of_nsfont ();
7802 #ifdef NS_IMPL_COCOA
7803   Fprovide (Qcocoa, Qnil);
7804 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
7805   syms_of_macfont ();
7806 #endif
7807 #else
7808   Fprovide (Qgnustep, Qnil);
7809 #endif