Quoting fixes in lisp/progmodes
[emacs.git] / src / nsterm.m
blob2806f31155df94c0be99a5c1f639d8a9293ea713
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"
57 #include "menu.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 #include "macfont.h"
69 #endif
71 /* call tracing */
72 #if 0
73 int term_trace_num = 0;
74 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
75                                 __FILE__, __LINE__, ++term_trace_num)
76 #else
77 #define NSTRACE(x)
78 #endif
80 /* Detailed tracing. "S" means "size" and "LL" stands for "lower left". */
81 #if 0
82 int term_trace_num = 0;
83 #define NSTRACE_SIZE(str,size) fprintf (stderr,                         \
84                                    "%s:%d: [%d]   " str                 \
85                                    " (S:%.0f x %.0f)\n", \
86                                    __FILE__, __LINE__, ++term_trace_num,\
87                                    size.height,                       \
88                                    size.width)
89 #define NSTRACE_RECT(s,r) fprintf (stderr,                              \
90                                    "%s:%d: [%d]   " s                   \
91                                    " (LL:%.0f x %.0f -> S:%.0f x %.0f)\n", \
92                                    __FILE__, __LINE__, ++term_trace_num,\
93                                    r.origin.x,                          \
94                                    r.origin.y,                          \
95                                    r.size.height,                       \
96                                    r.size.width)
97 #else
98 #define NSTRACE_SIZE(str,size)
99 #define NSTRACE_RECT(s,r)
100 #endif
102 extern NSString *NSMenuDidBeginTrackingNotification;
104 /* ==========================================================================
106    NSColor, EmacsColor category.
108    ========================================================================== */
109 @implementation NSColor (EmacsColor)
110 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
111                          blue:(CGFloat)blue alpha:(CGFloat)alpha
113 #ifdef NS_IMPL_COCOA
114 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
115   if (ns_use_srgb_colorspace)
116       return [NSColor colorWithSRGBRed: red
117                                  green: green
118                                   blue: blue
119                                  alpha: alpha];
120 #endif
121 #endif
122   return [NSColor colorWithCalibratedRed: red
123                                    green: green
124                                     blue: blue
125                                    alpha: alpha];
128 - (NSColor *)colorUsingDefaultColorSpace
130 #ifdef NS_IMPL_COCOA
131 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
132   if (ns_use_srgb_colorspace)
133     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
134 #endif
135 #endif
136   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
139 @end
141 /* ==========================================================================
143     Local declarations
145    ========================================================================== */
147 /* Convert a symbol indexed with an NSxxx value to a value as defined
148    in keyboard.c (lispy_function_key). I hope this is a correct way
149    of doing things... */
150 static unsigned convert_ns_to_X_keysym[] =
152   NSHomeFunctionKey,            0x50,
153   NSLeftArrowFunctionKey,       0x51,
154   NSUpArrowFunctionKey,         0x52,
155   NSRightArrowFunctionKey,      0x53,
156   NSDownArrowFunctionKey,       0x54,
157   NSPageUpFunctionKey,          0x55,
158   NSPageDownFunctionKey,        0x56,
159   NSEndFunctionKey,             0x57,
160   NSBeginFunctionKey,           0x58,
161   NSSelectFunctionKey,          0x60,
162   NSPrintFunctionKey,           0x61,
163   NSClearLineFunctionKey,       0x0B,
164   NSExecuteFunctionKey,         0x62,
165   NSInsertFunctionKey,          0x63,
166   NSUndoFunctionKey,            0x65,
167   NSRedoFunctionKey,            0x66,
168   NSMenuFunctionKey,            0x67,
169   NSFindFunctionKey,            0x68,
170   NSHelpFunctionKey,            0x6A,
171   NSBreakFunctionKey,           0x6B,
173   NSF1FunctionKey,              0xBE,
174   NSF2FunctionKey,              0xBF,
175   NSF3FunctionKey,              0xC0,
176   NSF4FunctionKey,              0xC1,
177   NSF5FunctionKey,              0xC2,
178   NSF6FunctionKey,              0xC3,
179   NSF7FunctionKey,              0xC4,
180   NSF8FunctionKey,              0xC5,
181   NSF9FunctionKey,              0xC6,
182   NSF10FunctionKey,             0xC7,
183   NSF11FunctionKey,             0xC8,
184   NSF12FunctionKey,             0xC9,
185   NSF13FunctionKey,             0xCA,
186   NSF14FunctionKey,             0xCB,
187   NSF15FunctionKey,             0xCC,
188   NSF16FunctionKey,             0xCD,
189   NSF17FunctionKey,             0xCE,
190   NSF18FunctionKey,             0xCF,
191   NSF19FunctionKey,             0xD0,
192   NSF20FunctionKey,             0xD1,
193   NSF21FunctionKey,             0xD2,
194   NSF22FunctionKey,             0xD3,
195   NSF23FunctionKey,             0xD4,
196   NSF24FunctionKey,             0xD5,
198   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
199   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
200   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
202   NSTabCharacter,               0x09,
203   0x19,                         0x09,  /* left tab->regular since pass shift */
204   NSCarriageReturnCharacter,    0x0D,
205   NSNewlineCharacter,           0x0D,
206   NSEnterCharacter,             0x8D,
208   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
209   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
210   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
211   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
212   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
213   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
214   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
215   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
216   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
217   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
218   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
219   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
220   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
221   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
222   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
223   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
225   0x1B,                         0x1B   /* escape */
228 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
229    the maximum font size to NOT antialias.  On GNUstep there is currently
230    no way to control this behavior. */
231 float ns_antialias_threshold;
233 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
234 NSString *ns_app_name = @"Emacs";  /* default changed later */
236 /* Display variables */
237 struct ns_display_info *x_display_list; /* Chain of existing displays */
238 long context_menu_value = 0;
240 /* display update */
241 static struct frame *ns_updating_frame;
242 static NSView *focus_view = NULL;
243 static int ns_window_num = 0;
244 #ifdef NS_IMPL_GNUSTEP
245 static NSRect uRect;
246 #endif
247 static BOOL gsaved = NO;
248 static BOOL ns_fake_keydown = NO;
249 #ifdef NS_IMPL_COCOA
250 static BOOL ns_menu_bar_is_hidden = NO;
251 #endif
252 /*static int debug_lock = 0; */
254 /* event loop */
255 static BOOL send_appdefined = YES;
256 #define NO_APPDEFINED_DATA (-8)
257 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
258 static NSTimer *timed_entry = 0;
259 static NSTimer *scroll_repeat_entry = nil;
260 static fd_set select_readfds, select_writefds;
261 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
262 static int select_nfds = 0, select_valid = 0;
263 static struct timespec select_timeout = { 0, 0 };
264 static int selfds[2] = { -1, -1 };
265 static pthread_mutex_t select_mutex;
266 static int apploopnr = 0;
267 static NSAutoreleasePool *outerpool;
268 static struct input_event *emacs_event = NULL;
269 static struct input_event *q_event_ptr = NULL;
270 static int n_emacs_events_pending = 0;
271 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
272   *ns_pending_service_args;
273 static BOOL ns_do_open_file = NO;
274 static BOOL ns_last_use_native_fullscreen;
276 /* Non-zero means that a HELP_EVENT has been generated since Emacs
277    start.  */
279 static BOOL any_help_event_p = NO;
281 static struct {
282   struct input_event *q;
283   int nr, cap;
284 } hold_event_q = {
285   NULL, 0, 0
288 static NSString *represented_filename = nil;
289 static struct frame *represented_frame = 0;
291 #ifdef NS_IMPL_COCOA
293  * State for pending menu activation:
294  * MENU_NONE     Normal state
295  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
296  *               run lisp to update the menu.
297  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
298  *               will open.
299  */
300 #define MENU_NONE 0
301 #define MENU_PENDING 1
302 #define MENU_OPENING 2
303 static int menu_will_open_state = MENU_NONE;
305 /* Saved position for menu click.  */
306 static CGPoint menu_mouse_point;
307 #endif
309 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
310 #define NS_FUNCTION_KEY_MASK 0x800000
311 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
312 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
313 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
314 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
315 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
316 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
317 #define EV_MODIFIERS2(flags)                          \
318     (((flags & NSHelpKeyMask) ?           \
319            hyper_modifier : 0)                        \
320      | (!EQ (ns_right_alternate_modifier, Qleft) && \
321         ((flags & NSRightAlternateKeyMask) \
322          == NSRightAlternateKeyMask) ? \
323            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
324      | ((flags & NSAlternateKeyMask) ?                 \
325            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
326      | ((flags & NSShiftKeyMask) ?     \
327            shift_modifier : 0)                        \
328      | (!EQ (ns_right_control_modifier, Qleft) && \
329         ((flags & NSRightControlKeyMask) \
330          == NSRightControlKeyMask) ? \
331            parse_solitary_modifier (ns_right_control_modifier) : 0) \
332      | ((flags & NSControlKeyMask) ?      \
333            parse_solitary_modifier (ns_control_modifier) : 0)     \
334      | ((flags & NS_FUNCTION_KEY_MASK) ?  \
335            parse_solitary_modifier (ns_function_modifier) : 0)    \
336      | (!EQ (ns_right_command_modifier, Qleft) && \
337         ((flags & NSRightCommandKeyMask) \
338          == NSRightCommandKeyMask) ? \
339            parse_solitary_modifier (ns_right_command_modifier) : 0) \
340      | ((flags & NSCommandKeyMask) ?      \
341            parse_solitary_modifier (ns_command_modifier):0))
342 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
344 #define EV_UDMODIFIERS(e)                                      \
345     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
346      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
347      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
348      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
349      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
350      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
351      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
352      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
353      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
355 #define EV_BUTTON(e)                                                         \
356     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
357       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
358      [e buttonNumber] - 1)
360 /* Convert the time field to a timestamp in milliseconds. */
361 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
363 /* This is a piece of code which is common to all the event handling
364    methods.  Maybe it should even be a function.  */
365 #define EV_TRAILER(e)                                                   \
366   {                                                                     \
367     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
368     EV_TRAILER2 (e);                                                    \
369   }
371 #define EV_TRAILER2(e)                                                  \
372   {                                                                     \
373       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
374       if (q_event_ptr)                                                  \
375         {                                                               \
376           Lisp_Object tem = Vinhibit_quit;                              \
377           Vinhibit_quit = Qt;                                           \
378           n_emacs_events_pending++;                                     \
379           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
380           Vinhibit_quit = tem;                                          \
381         }                                                               \
382       else                                                              \
383         hold_event (emacs_event);                                       \
384       EVENT_INIT (*emacs_event);                                        \
385       ns_send_appdefined (-1);                                          \
386     }
388 /* TODO: get rid of need for these forward declarations */
389 static void ns_condemn_scroll_bars (struct frame *f);
390 static void ns_judge_scroll_bars (struct frame *f);
391 void x_set_frame_alpha (struct frame *f);
394 /* ==========================================================================
396     Utilities
398    ========================================================================== */
400 void
401 ns_set_represented_filename (NSString* fstr, struct frame *f)
403   represented_filename = [fstr retain];
404   represented_frame = f;
407 void
408 ns_init_events (struct input_event* ev)
410   EVENT_INIT (*ev);
411   emacs_event = ev;
414 void
415 ns_finish_events ()
417   emacs_event = NULL;
420 static void
421 hold_event (struct input_event *event)
423   if (hold_event_q.nr == hold_event_q.cap)
424     {
425       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
426       else hold_event_q.cap *= 2;
427       hold_event_q.q =
428         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
429     }
431   hold_event_q.q[hold_event_q.nr++] = *event;
432   /* Make sure ns_read_socket is called, i.e. we have input.  */
433   raise (SIGIO);
434   send_appdefined = YES;
437 static Lisp_Object
438 append2 (Lisp_Object list, Lisp_Object item)
439 /* --------------------------------------------------------------------------
440    Utility to append to a list
441    -------------------------------------------------------------------------- */
443   Lisp_Object array[2];
444   array[0] = list;
445   array[1] = list1 (item);
446   return Fnconc (2, &array[0]);
450 const char *
451 ns_etc_directory (void)
452 /* If running as a self-contained app bundle, return as a string the
453    filename of the etc directory, if present; else nil.  */
455   NSBundle *bundle = [NSBundle mainBundle];
456   NSString *resourceDir = [bundle resourcePath];
457   NSString *resourcePath;
458   NSFileManager *fileManager = [NSFileManager defaultManager];
459   BOOL isDir;
461   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
462   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
463     {
464       if (isDir) return [resourcePath UTF8String];
465     }
466   return NULL;
470 const char *
471 ns_exec_path (void)
472 /* If running as a self-contained app bundle, return as a path string
473    the filenames of the libexec and bin directories, ie libexec:bin.
474    Otherwise, return nil.
475    Normally, Emacs does not add its own bin/ directory to the PATH.
476    However, a self-contained NS build has a different layout, with
477    bin/ and libexec/ subdirectories in the directory that contains
478    Emacs.app itself.
479    We put libexec first, because init_callproc_1 uses the first
480    element to initialize exec-directory.  An alternative would be
481    for init_callproc to check for invocation-directory/libexec.
484   NSBundle *bundle = [NSBundle mainBundle];
485   NSString *resourceDir = [bundle resourcePath];
486   NSString *binDir = [bundle bundlePath];
487   NSString *resourcePath, *resourcePaths;
488   NSRange range;
489   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
490   NSFileManager *fileManager = [NSFileManager defaultManager];
491   NSArray *paths;
492   NSEnumerator *pathEnum;
493   BOOL isDir;
495   range = [resourceDir rangeOfString: @"Contents"];
496   if (range.location != NSNotFound)
497     {
498       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
499 #ifdef NS_IMPL_COCOA
500       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
501 #endif
502     }
504   paths = [binDir stringsByAppendingPaths:
505                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
506   pathEnum = [paths objectEnumerator];
507   resourcePaths = @"";
509   while ((resourcePath = [pathEnum nextObject]))
510     {
511       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
512         if (isDir)
513           {
514             if ([resourcePaths length] > 0)
515               resourcePaths
516                 = [resourcePaths stringByAppendingString: pathSeparator];
517             resourcePaths
518               = [resourcePaths stringByAppendingString: resourcePath];
519           }
520     }
521   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
523   return NULL;
527 const char *
528 ns_load_path (void)
529 /* If running as a self-contained app bundle, return as a path string
530    the filenames of the site-lisp and lisp directories.
531    Ie, site-lisp:lisp.  Otherwise, return nil.  */
533   NSBundle *bundle = [NSBundle mainBundle];
534   NSString *resourceDir = [bundle resourcePath];
535   NSString *resourcePath, *resourcePaths;
536   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
537   NSFileManager *fileManager = [NSFileManager defaultManager];
538   BOOL isDir;
539   NSArray *paths = [resourceDir stringsByAppendingPaths:
540                               [NSArray arrayWithObjects:
541                                          @"site-lisp", @"lisp", nil]];
542   NSEnumerator *pathEnum = [paths objectEnumerator];
543   resourcePaths = @"";
545   /* Hack to skip site-lisp.  */
546   if (no_site_lisp) resourcePath = [pathEnum nextObject];
548   while ((resourcePath = [pathEnum nextObject]))
549     {
550       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
551         if (isDir)
552           {
553             if ([resourcePaths length] > 0)
554               resourcePaths
555                 = [resourcePaths stringByAppendingString: pathSeparator];
556             resourcePaths
557               = [resourcePaths stringByAppendingString: resourcePath];
558           }
559     }
560   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
562   return NULL;
565 static void
566 ns_timeout (int usecs)
567 /* --------------------------------------------------------------------------
568      Blocking timer utility used by ns_ring_bell
569    -------------------------------------------------------------------------- */
571   struct timespec wakeup = timespec_add (current_timespec (),
572                                          make_timespec (0, usecs * 1000));
574   /* Keep waiting until past the time wakeup.  */
575   while (1)
576     {
577       struct timespec timeout, now = current_timespec ();
578       if (timespec_cmp (wakeup, now) <= 0)
579         break;
580       timeout = timespec_sub (wakeup, now);
582       /* Try to wait that long--but we might wake up sooner.  */
583       pselect (0, NULL, NULL, NULL, &timeout, NULL);
584     }
588 void
589 ns_release_object (void *obj)
590 /* --------------------------------------------------------------------------
591     Release an object (callable from C)
592    -------------------------------------------------------------------------- */
594     [(id)obj release];
598 void
599 ns_retain_object (void *obj)
600 /* --------------------------------------------------------------------------
601     Retain an object (callable from C)
602    -------------------------------------------------------------------------- */
604     [(id)obj retain];
608 void *
609 ns_alloc_autorelease_pool (void)
610 /* --------------------------------------------------------------------------
611      Allocate a pool for temporary objects (callable from C)
612    -------------------------------------------------------------------------- */
614   return [[NSAutoreleasePool alloc] init];
618 void
619 ns_release_autorelease_pool (void *pool)
620 /* --------------------------------------------------------------------------
621      Free a pool and temporary objects it refers to (callable from C)
622    -------------------------------------------------------------------------- */
624   ns_release_object (pool);
629 /* ==========================================================================
631     Focus (clipping) and screen update
633    ========================================================================== */
636 // Window constraining
637 // -------------------
639 // To ensure that the windows are not placed under the menu bar, they
640 // are typically moved by the call-back constrainFrameRect. However,
641 // by overriding it, it's possible to inhibit this, leaving the window
642 // in it's original position.
644 // It's possible to hide the menu bar. However, technically, it's only
645 // possible to hide it when the application is active. To ensure that
646 // this work properly, the menu bar and window constraining are
647 // deferred until the application becomes active.
649 // Even though it's not possible to manually move a window above the
650 // top of the screen, it is allowed if it's done programmatically,
651 // when the menu is hidden. This allows the editable area to cover the
652 // full screen height.
654 // Test cases
655 // ----------
657 // Use the following extra files:
659 //    init.el:
660 //       ;; Hide menu and place frame slightly above the top of the screen.
661 //       (setq ns-auto-hide-menu-bar t)
662 //       (set-frame-position (selected-frame) 0 -20)
664 // Test 1:
666 //    emacs -Q -l init.el
668 //    Result: No menu bar, and the title bar should be above the screen.
670 // Test 2:
672 //    emacs -Q
674 //    Result: Menu bar visible, frame placed immediately below the menu.
677 static void
678 ns_constrain_all_frames (void)
680   Lisp_Object tail, frame;
682   FOR_EACH_FRAME (tail, frame)
683     {
684       struct frame *f = XFRAME (frame);
685       if (FRAME_NS_P (f))
686         {
687           NSView *view = FRAME_NS_VIEW (f);
688           /* This no-op will trigger the default window placing
689            * constraint system. */
690           [[view window] setFrameOrigin:[[view window] frame].origin];
691         }
692     }
696 /* True, if the menu bar should be hidden.  */
698 static BOOL
699 ns_menu_bar_should_be_hidden (void)
701   return !NILP (ns_auto_hide_menu_bar)
702     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
706 /* Show or hide the menu bar, based on user setting.  */
708 static void
709 ns_update_auto_hide_menu_bar (void)
711 #ifdef NS_IMPL_COCOA
712   block_input ();
714   NSTRACE (ns_update_auto_hide_menu_bar);
716   if (NSApp != nil && [NSApp isActive])
717     {
718       // Note, "setPresentationOptions" triggers an error unless the
719       // application is active.
720       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
722       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
723         {
724           NSApplicationPresentationOptions options
725             = NSApplicationPresentationDefault;
727           if (menu_bar_should_be_hidden)
728             options |= NSApplicationPresentationAutoHideMenuBar
729               | NSApplicationPresentationAutoHideDock;
731           [NSApp setPresentationOptions: options];
733           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
735           if (!ns_menu_bar_is_hidden)
736             {
737               ns_constrain_all_frames ();
738             }
739         }
740     }
742   unblock_input ();
743 #endif
747 static void
748 ns_update_begin (struct frame *f)
749 /* --------------------------------------------------------------------------
750    Prepare for a grouped sequence of drawing calls
751    external (RIF) call; whole frame, called before update_window_begin
752    -------------------------------------------------------------------------- */
754   EmacsView *view = FRAME_NS_VIEW (f);
755   NSTRACE (ns_update_begin);
757   ns_update_auto_hide_menu_bar ();
759 #ifdef NS_IMPL_COCOA
760   if ([view isFullscreen] && [view fsIsNative])
761   {
762     // Fix reappearing tool bar in fullscreen for OSX 10.7
763     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
764     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
765     if (! tbar_visible != ! [toolbar isVisible])
766       [toolbar setVisible: tbar_visible];
767   }
768 #endif
770   ns_updating_frame = f;
771   [view lockFocus];
773   /* drawRect may have been called for say the minibuffer, and then clip path
774      is for the minibuffer.  But the display engine may draw more because
775      we have set the frame as garbaged.  So reset clip path to the whole
776      view.  */
777 #ifdef NS_IMPL_COCOA
778   {
779     NSBezierPath *bp;
780     NSRect r = [view frame];
781     NSRect cr = [[view window] frame];
782     /* If a large frame size is set, r may be larger than the window frame
783        before constrained.  In that case don't change the clip path, as we
784        will clear in to the tool bar and title bar.  */
785     if (r.size.height
786         + FRAME_NS_TITLEBAR_HEIGHT (f)
787         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
788       {
789         bp = [[NSBezierPath bezierPathWithRect: r] retain];
790         [bp setClip];
791         [bp release];
792       }
793   }
794 #endif
796 #ifdef NS_IMPL_GNUSTEP
797   uRect = NSMakeRect (0, 0, 0, 0);
798 #endif
802 static void
803 ns_update_window_begin (struct window *w)
804 /* --------------------------------------------------------------------------
805    Prepare for a grouped sequence of drawing calls
806    external (RIF) call; for one window, called after update_begin
807    -------------------------------------------------------------------------- */
809   struct frame *f = XFRAME (WINDOW_FRAME (w));
810   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
812   NSTRACE (ns_update_window_begin);
813   w->output_cursor = w->cursor;
815   block_input ();
817   if (f == hlinfo->mouse_face_mouse_frame)
818     {
819       /* Don't do highlighting for mouse motion during the update.  */
820       hlinfo->mouse_face_defer = 1;
822         /* If the frame needs to be redrawn,
823            simply forget about any prior mouse highlighting.  */
824       if (FRAME_GARBAGED_P (f))
825         hlinfo->mouse_face_window = Qnil;
827       /* (further code for mouse faces ifdef'd out in other terms elided) */
828     }
830   unblock_input ();
834 static void
835 ns_update_window_end (struct window *w, bool cursor_on_p,
836                       bool mouse_face_overwritten_p)
837 /* --------------------------------------------------------------------------
838    Finished a grouped sequence of drawing calls
839    external (RIF) call; for one window called before update_end
840    -------------------------------------------------------------------------- */
842   /* note: this fn is nearly identical in all terms */
843   if (!w->pseudo_window_p)
844     {
845       block_input ();
847       if (cursor_on_p)
848         display_and_set_cursor (w, 1,
849                                 w->output_cursor.hpos, w->output_cursor.vpos,
850                                 w->output_cursor.x, w->output_cursor.y);
852       if (draw_window_fringes (w, 1))
853         {
854           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
855             x_draw_right_divider (w);
856           else
857             x_draw_vertical_border (w);
858         }
860       unblock_input ();
861     }
863   /* If a row with mouse-face was overwritten, arrange for
864      frame_up_to_date to redisplay the mouse highlight.  */
865   if (mouse_face_overwritten_p)
866     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
868   NSTRACE (update_window_end);
872 static void
873 ns_update_end (struct frame *f)
874 /* --------------------------------------------------------------------------
875    Finished a grouped sequence of drawing calls
876    external (RIF) call; for whole frame, called after update_window_end
877    -------------------------------------------------------------------------- */
879   EmacsView *view = FRAME_NS_VIEW (f);
881 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
882   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
884   block_input ();
886   [view unlockFocus];
887   [[view window] flushWindow];
889   unblock_input ();
890   ns_updating_frame = NULL;
891   NSTRACE (ns_update_end);
894 static void
895 ns_focus (struct frame *f, NSRect *r, int n)
896 /* --------------------------------------------------------------------------
897    Internal: Focus on given frame.  During small local updates this is used to
898      draw, however during large updates, ns_update_begin and ns_update_end are
899      called to wrap the whole thing, in which case these calls are stubbed out.
900      Except, on GNUstep, we accumulate the rectangle being drawn into, because
901      the back end won't do this automatically, and will just end up flushing
902      the entire window.
903    -------------------------------------------------------------------------- */
905 //  NSTRACE (ns_focus);
906 /* static int c =0;
907    fprintf (stderr, "focus: %d", c++);
908    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
909    fprintf (stderr, "\n"); */
911   if (f != ns_updating_frame)
912     {
913       NSView *view = FRAME_NS_VIEW (f);
914       if (view != focus_view)
915         {
916           if (focus_view != NULL)
917             {
918               [focus_view unlockFocus];
919               [[focus_view window] flushWindow];
920 /*debug_lock--; */
921             }
923           if (view)
924             [view lockFocus];
925           focus_view = view;
926 /*if (view) debug_lock++; */
927         }
928     }
930   /* clipping */
931   if (r)
932     {
933       [[NSGraphicsContext currentContext] saveGraphicsState];
934       if (n == 2)
935         NSRectClipList (r, 2);
936       else
937         NSRectClip (*r);
938       gsaved = YES;
939     }
943 static void
944 ns_unfocus (struct frame *f)
945 /* --------------------------------------------------------------------------
946      Internal: Remove focus on given frame
947    -------------------------------------------------------------------------- */
949 //  NSTRACE (ns_unfocus);
951   if (gsaved)
952     {
953       [[NSGraphicsContext currentContext] restoreGraphicsState];
954       gsaved = NO;
955     }
957   if (f != ns_updating_frame)
958     {
959       if (focus_view != NULL)
960         {
961           [focus_view unlockFocus];
962           [[focus_view window] flushWindow];
963           focus_view = NULL;
964 /*debug_lock--; */
965         }
966     }
970 static void
971 ns_clip_to_row (struct window *w, struct glyph_row *row,
972                 enum glyph_row_area area, BOOL gc)
973 /* --------------------------------------------------------------------------
974      Internal (but parallels other terms): Focus drawing on given row
975    -------------------------------------------------------------------------- */
977   struct frame *f = XFRAME (WINDOW_FRAME (w));
978   NSRect clip_rect;
979   int window_x, window_y, window_width;
981   window_box (w, area, &window_x, &window_y, &window_width, 0);
983   clip_rect.origin.x = window_x;
984   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
985   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
986   clip_rect.size.width = window_width;
987   clip_rect.size.height = row->visible_height;
989   ns_focus (f, &clip_rect, 1);
993 static void
994 ns_ring_bell (struct frame *f)
995 /* --------------------------------------------------------------------------
996      "Beep" routine
997    -------------------------------------------------------------------------- */
999   NSTRACE (ns_ring_bell);
1000   if (visible_bell)
1001     {
1002       NSAutoreleasePool *pool;
1003       struct frame *frame = SELECTED_FRAME ();
1004       NSView *view;
1006       block_input ();
1007       pool = [[NSAutoreleasePool alloc] init];
1009       view = FRAME_NS_VIEW (frame);
1010       if (view != nil)
1011         {
1012           NSRect r, surr;
1013           NSPoint dim = NSMakePoint (128, 128);
1015           r = [view bounds];
1016           r.origin.x += (r.size.width - dim.x) / 2;
1017           r.origin.y += (r.size.height - dim.y) / 2;
1018           r.size.width = dim.x;
1019           r.size.height = dim.y;
1020           surr = NSInsetRect (r, -2, -2);
1021           ns_focus (frame, &surr, 1);
1022           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1023           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1024                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
1025           NSRectFill (r);
1026           [[view window] flushWindow];
1027           ns_timeout (150000);
1028           [[view window] restoreCachedImage];
1029           [[view window] flushWindow];
1030           ns_unfocus (frame);
1031         }
1032       [pool release];
1033       unblock_input ();
1034     }
1035   else
1036     {
1037       NSBeep ();
1038     }
1041 /* ==========================================================================
1043     Frame / window manager related functions
1045    ========================================================================== */
1048 static void
1049 ns_raise_frame (struct frame *f)
1050 /* --------------------------------------------------------------------------
1051      Bring window to foreground and make it active
1052    -------------------------------------------------------------------------- */
1054   NSView *view;
1055   check_window_system (f);
1056   view = FRAME_NS_VIEW (f);
1057   block_input ();
1058   if (FRAME_VISIBLE_P (f))
1059     [[view window] makeKeyAndOrderFront: NSApp];
1060   unblock_input ();
1064 static void
1065 ns_lower_frame (struct frame *f)
1066 /* --------------------------------------------------------------------------
1067      Send window to back
1068    -------------------------------------------------------------------------- */
1070   NSView *view;
1071   check_window_system (f);
1072   view = FRAME_NS_VIEW (f);
1073   block_input ();
1074   [[view window] orderBack: NSApp];
1075   unblock_input ();
1079 static void
1080 ns_frame_raise_lower (struct frame *f, bool raise)
1081 /* --------------------------------------------------------------------------
1082      External (hook)
1083    -------------------------------------------------------------------------- */
1085   NSTRACE (ns_frame_raise_lower);
1087   if (raise)
1088     ns_raise_frame (f);
1089   else
1090     ns_lower_frame (f);
1094 static void
1095 ns_frame_rehighlight (struct frame *frame)
1096 /* --------------------------------------------------------------------------
1097      External (hook): called on things like window switching within frame
1098    -------------------------------------------------------------------------- */
1100   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1101   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1103   NSTRACE (ns_frame_rehighlight);
1104   if (dpyinfo->x_focus_frame)
1105     {
1106       dpyinfo->x_highlight_frame
1107         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1108            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1109            : dpyinfo->x_focus_frame);
1110       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1111         {
1112           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1113           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1114         }
1115     }
1116   else
1117       dpyinfo->x_highlight_frame = 0;
1119   if (dpyinfo->x_highlight_frame &&
1120          dpyinfo->x_highlight_frame != old_highlight)
1121     {
1122       if (old_highlight)
1123         {
1124           x_update_cursor (old_highlight, 1);
1125           x_set_frame_alpha (old_highlight);
1126         }
1127       if (dpyinfo->x_highlight_frame)
1128         {
1129           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1130           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1131         }
1132     }
1136 void
1137 x_make_frame_visible (struct frame *f)
1138 /* --------------------------------------------------------------------------
1139      External: Show the window (X11 semantics)
1140    -------------------------------------------------------------------------- */
1142   NSTRACE (x_make_frame_visible);
1143   /* XXX: at some points in past this was not needed, as the only place that
1144      called this (frame.c:Fraise_frame ()) also called raise_lower;
1145      if this ends up the case again, comment this out again. */
1146   if (!FRAME_VISIBLE_P (f))
1147     {
1148       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1150       SET_FRAME_VISIBLE (f, 1);
1151       ns_raise_frame (f);
1153       /* Making a new frame from a fullscreen frame will make the new frame
1154          fullscreen also.  So skip handleFS as this will print an error.  */
1155       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1156           && [view isFullscreen])
1157         return;
1159       if (f->want_fullscreen != FULLSCREEN_NONE)
1160         {
1161           block_input ();
1162           [view handleFS];
1163           unblock_input ();
1164         }
1165     }
1169 void
1170 x_make_frame_invisible (struct frame *f)
1171 /* --------------------------------------------------------------------------
1172      External: Hide the window (X11 semantics)
1173    -------------------------------------------------------------------------- */
1175   NSView *view;
1176   NSTRACE (x_make_frame_invisible);
1177   check_window_system (f);
1178   view = FRAME_NS_VIEW (f);
1179   [[view window] orderOut: NSApp];
1180   SET_FRAME_VISIBLE (f, 0);
1181   SET_FRAME_ICONIFIED (f, 0);
1185 void
1186 x_iconify_frame (struct frame *f)
1187 /* --------------------------------------------------------------------------
1188      External: Iconify window
1189    -------------------------------------------------------------------------- */
1191   NSView *view;
1192   struct ns_display_info *dpyinfo;
1194   NSTRACE (x_iconify_frame);
1195   check_window_system (f);
1196   view = FRAME_NS_VIEW (f);
1197   dpyinfo = FRAME_DISPLAY_INFO (f);
1199   if (dpyinfo->x_highlight_frame == f)
1200     dpyinfo->x_highlight_frame = 0;
1202   if ([[view window] windowNumber] <= 0)
1203     {
1204       /* the window is still deferred.  Make it very small, bring it
1205          on screen and order it out. */
1206       NSRect s = { { 100, 100}, {0, 0} };
1207       NSRect t;
1208       t = [[view window] frame];
1209       [[view window] setFrame: s display: NO];
1210       [[view window] orderBack: NSApp];
1211       [[view window] orderOut: NSApp];
1212       [[view window] setFrame: t display: NO];
1213     }
1214   [[view window] miniaturize: NSApp];
1217 /* Free X resources of frame F.  */
1219 void
1220 x_free_frame_resources (struct frame *f)
1222   NSView *view;
1223   struct ns_display_info *dpyinfo;
1224   Mouse_HLInfo *hlinfo;
1226   NSTRACE (x_free_frame_resources);
1227   check_window_system (f);
1228   view = FRAME_NS_VIEW (f);
1229   dpyinfo = FRAME_DISPLAY_INFO (f);
1230   hlinfo = MOUSE_HL_INFO (f);
1232   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1234   block_input ();
1236   free_frame_menubar (f);
1237   free_frame_faces (f);
1239   if (f == dpyinfo->x_focus_frame)
1240     dpyinfo->x_focus_frame = 0;
1241   if (f == dpyinfo->x_highlight_frame)
1242     dpyinfo->x_highlight_frame = 0;
1243   if (f == hlinfo->mouse_face_mouse_frame)
1244     reset_mouse_highlight (hlinfo);
1246   if (f->output_data.ns->miniimage != nil)
1247     [f->output_data.ns->miniimage release];
1249   [[view window] close];
1250   [view release];
1252   xfree (f->output_data.ns);
1254   unblock_input ();
1257 void
1258 x_destroy_window (struct frame *f)
1259 /* --------------------------------------------------------------------------
1260      External: Delete the window
1261    -------------------------------------------------------------------------- */
1263   NSTRACE (x_destroy_window);
1264   check_window_system (f);
1265   x_free_frame_resources (f);
1266   ns_window_num--;
1270 void
1271 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1272 /* --------------------------------------------------------------------------
1273      External: Position the window
1274    -------------------------------------------------------------------------- */
1276   NSView *view = FRAME_NS_VIEW (f);
1277   NSArray *screens = [NSScreen screens];
1278   NSScreen *fscreen = [screens objectAtIndex: 0];
1279   NSScreen *screen = [[view window] screen];
1281   NSTRACE (x_set_offset);
1283   block_input ();
1285   f->left_pos = xoff;
1286   f->top_pos = yoff;
1288   if (view != nil && screen && fscreen)
1289     {
1290       f->left_pos = f->size_hint_flags & XNegative
1291         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1292         : f->left_pos;
1293       /* We use visibleFrame here to take menu bar into account.
1294          Ideally we should also adjust left/top with visibleFrame.origin.  */
1296       f->top_pos = f->size_hint_flags & YNegative
1297         ? ([screen visibleFrame].size.height + f->top_pos
1298            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1299            - FRAME_TOOLBAR_HEIGHT (f))
1300         : f->top_pos;
1301 #ifdef NS_IMPL_GNUSTEP
1302       if (f->left_pos < 100)
1303         f->left_pos = 100;  /* don't overlap menu */
1304 #endif
1305       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1306          menu bar.  */
1307       [[view window] setFrameTopLeftPoint:
1308                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1309                                     SCREENMAXBOUND ([fscreen frame].size.height
1310                                                     - NS_TOP_POS (f)))];
1311       f->size_hint_flags &= ~(XNegative|YNegative);
1312     }
1314   unblock_input ();
1318 void
1319 x_set_window_size (struct frame *f,
1320                    bool change_gravity,
1321                    int width,
1322                    int height,
1323                    bool pixelwise)
1324 /* --------------------------------------------------------------------------
1325      Adjust window pixel size based on given character grid size
1326      Impl is a bit more complex than other terms, need to do some
1327      internal clipping.
1328    -------------------------------------------------------------------------- */
1330   EmacsView *view = FRAME_NS_VIEW (f);
1331   NSWindow *window = [view window];
1332   NSRect wr = [window frame];
1333   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1334   int pixelwidth, pixelheight;
1335   int rows, cols;
1337   NSTRACE (x_set_window_size);
1339   if (view == nil)
1340     return;
1342 /*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));*/
1344   block_input ();
1346   if (pixelwise)
1347     {
1348       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1349       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1350       cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1351       rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1352     }
1353   else
1354     {
1355       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1356       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1357       cols = width;
1358       rows = height;
1359     }
1361   /* If we have a toolbar, take its height into account. */
1362   if (tb && ! [view isFullscreen])
1363     {
1364     /* NOTE: previously this would generate wrong result if toolbar not
1365              yet displayed and fixing toolbar_height=32 helped, but
1366              now (200903) seems no longer needed */
1367     FRAME_TOOLBAR_HEIGHT (f) =
1368       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1369         - FRAME_NS_TITLEBAR_HEIGHT (f);
1370 #ifdef NS_IMPL_GNUSTEP
1371       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1372 #endif
1373     }
1374   else
1375     FRAME_TOOLBAR_HEIGHT (f) = 0;
1377   wr.size.width = pixelwidth + f->border_width;
1378   wr.size.height = pixelheight;
1379   if (! [view isFullscreen])
1380     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1381       + FRAME_TOOLBAR_HEIGHT (f);
1383   /* Do not try to constrain to this screen.  We may have multiple
1384      screens, and want Emacs to span those.  Constraining to screen
1385      prevents that, and that is not nice to the user.  */
1386  if (f->output_data.ns->zooming)
1387    f->output_data.ns->zooming = 0;
1388  else
1389    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1391   [view setRows: rows andColumns: cols];
1392   [window setFrame: wr display: YES];
1394   /* This is a trick to compensate for Emacs' managing the scrollbar area
1395      as a fixed number of standard character columns.  Instead of leaving
1396      blank space for the extra, we chopped it off above.  Now for
1397      left-hand scrollbars, we shift all rendering to the left by the
1398      difference between the real width and Emacs' imagined one.  For
1399      right-hand bars, don't worry about it since the extra is never used.
1400      (Obviously doesn't work for vertically split windows tho..) */
1401   {
1402     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1403       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1404                      - NS_SCROLL_BAR_WIDTH (f), 0)
1405       : NSMakePoint (0, 0);
1406     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1407     [view setBoundsOrigin: origin];
1408   }
1410   [view updateFrameSize: NO];
1411   unblock_input ();
1415 static void
1416 ns_fullscreen_hook (struct frame *f)
1418   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1420   if (!FRAME_VISIBLE_P (f))
1421     return;
1423    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1424     {
1425       /* Old style fs don't initiate correctly if created from
1426          init/default-frame alist, so use a timer (not nice...).
1427       */
1428       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1429                                      selector: @selector (handleFS)
1430                                      userInfo: nil repeats: NO];
1431       return;
1432     }
1434   block_input ();
1435   [view handleFS];
1436   unblock_input ();
1439 /* ==========================================================================
1441     Color management
1443    ========================================================================== */
1446 NSColor *
1447 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1449   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1450   if (idx < 1 || idx >= color_table->avail)
1451     return nil;
1452   return color_table->colors[idx];
1456 unsigned long
1457 ns_index_color (NSColor *color, struct frame *f)
1459   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1460   ptrdiff_t idx;
1461   ptrdiff_t i;
1463   if (!color_table->colors)
1464     {
1465       color_table->size = NS_COLOR_CAPACITY;
1466       color_table->avail = 1; /* skip idx=0 as marker */
1467       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1468       color_table->colors[0] = nil;
1469       color_table->empty_indices = [[NSMutableSet alloc] init];
1470     }
1472   /* Do we already have this color?  */
1473   for (i = 1; i < color_table->avail; i++)
1474     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1475       return i;
1477   if ([color_table->empty_indices count] > 0)
1478     {
1479       NSNumber *index = [color_table->empty_indices anyObject];
1480       [color_table->empty_indices removeObject: index];
1481       idx = [index unsignedLongValue];
1482     }
1483   else
1484     {
1485       if (color_table->avail == color_table->size)
1486         color_table->colors =
1487           xpalloc (color_table->colors, &color_table->size, 1,
1488                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1489       idx = color_table->avail++;
1490     }
1492   color_table->colors[idx] = color;
1493   [color retain];
1494 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1495   return idx;
1499 void
1500 ns_free_indexed_color (unsigned long idx, struct frame *f)
1502   struct ns_color_table *color_table;
1503   NSColor *color;
1504   NSNumber *index;
1506   if (!f)
1507     return;
1509   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1511   if (idx <= 0 || idx >= color_table->size) {
1512     message1 ("ns_free_indexed_color: Color index out of range.\n");
1513     return;
1514   }
1516   index = [NSNumber numberWithUnsignedInt: idx];
1517   if ([color_table->empty_indices containsObject: index]) {
1518     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1519     return;
1520   }
1522   color = color_table->colors[idx];
1523   [color release];
1524   color_table->colors[idx] = nil;
1525   [color_table->empty_indices addObject: index];
1526 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1530 static int
1531 ns_get_color (const char *name, NSColor **col)
1532 /* --------------------------------------------------------------------------
1533      Parse a color name
1534    -------------------------------------------------------------------------- */
1535 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1536    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1537    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1539   NSColor *new = nil;
1540   static char hex[20];
1541   int scaling = 0;
1542   float r = -1.0, g, b;
1543   NSString *nsname = [NSString stringWithUTF8String: name];
1545 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1546   block_input ();
1548   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1549     {
1550 #ifdef NS_IMPL_COCOA
1551       NSString *defname = [[NSUserDefaults standardUserDefaults]
1552                             stringForKey: @"AppleHighlightColor"];
1553       if (defname != nil)
1554         nsname = defname;
1555       else
1556 #endif
1557       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1558         {
1559           *col = [new colorUsingDefaultColorSpace];
1560           unblock_input ();
1561           return 0;
1562         }
1563       else
1564         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1566       name = [nsname UTF8String];
1567     }
1568   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1569     {
1570       /* NOTE: OSX applications normally don't set foreground selection, but
1571          text may be unreadable if we don't.
1572       */
1573       if ((new = [NSColor selectedTextColor]) != nil)
1574         {
1575           *col = [new colorUsingDefaultColorSpace];
1576           unblock_input ();
1577           return 0;
1578         }
1580       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1581       name = [nsname UTF8String];
1582     }
1584   /* First, check for some sort of numeric specification. */
1585   hex[0] = '\0';
1587   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1588     {
1589       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1590       [scanner scanFloat: &r];
1591       [scanner scanFloat: &g];
1592       [scanner scanFloat: &b];
1593     }
1594   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1595     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1596   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1597     {
1598       int len = (strlen(name) - 1);
1599       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1600       int i;
1601       scaling = strlen(name+start) / 3;
1602       for (i = 0; i < 3; i++)
1603         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1604                  name + start + i * scaling);
1605       hex[3 * (scaling + 1) - 1] = '\0';
1606     }
1608   if (hex[0])
1609     {
1610       int rr, gg, bb;
1611       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1612       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1613         {
1614           r = rr / fscale;
1615           g = gg / fscale;
1616           b = bb / fscale;
1617         }
1618     }
1620   if (r >= 0.0F)
1621     {
1622       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1623       unblock_input ();
1624       return 0;
1625     }
1627   /* Otherwise, color is expected to be from a list */
1628   {
1629     NSEnumerator *lenum, *cenum;
1630     NSString *name;
1631     NSColorList *clist;
1633 #ifdef NS_IMPL_GNUSTEP
1634     /* XXX: who is wrong, the requestor or the implementation? */
1635     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1636         == NSOrderedSame)
1637       nsname = @"highlightColor";
1638 #endif
1640     lenum = [[NSColorList availableColorLists] objectEnumerator];
1641     while ( (clist = [lenum nextObject]) && new == nil)
1642       {
1643         cenum = [[clist allKeys] objectEnumerator];
1644         while ( (name = [cenum nextObject]) && new == nil )
1645           {
1646             if ([name compare: nsname
1647                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1648               new = [clist colorWithKey: name];
1649           }
1650       }
1651   }
1653   if (new)
1654     *col = [new colorUsingDefaultColorSpace];
1655   unblock_input ();
1656   return new ? 0 : 1;
1661 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1662 /* --------------------------------------------------------------------------
1663      Convert a Lisp string object to a NS color
1664    -------------------------------------------------------------------------- */
1666   NSTRACE (ns_lisp_to_color);
1667   if (STRINGP (color))
1668     return ns_get_color (SSDATA (color), col);
1669   else if (SYMBOLP (color))
1670     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1671   return 1;
1675 Lisp_Object
1676 ns_color_to_lisp (NSColor *col)
1677 /* --------------------------------------------------------------------------
1678      Convert a color to a lisp string with the RGB equivalent
1679    -------------------------------------------------------------------------- */
1681   EmacsCGFloat red, green, blue, alpha, gray;
1682   char buf[1024];
1683   const char *str;
1684   NSTRACE (ns_color_to_lisp);
1686   block_input ();
1687   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1689       if ((str =[[col colorNameComponent] UTF8String]))
1690         {
1691           unblock_input ();
1692           return build_string ((char *)str);
1693         }
1695     [[col colorUsingDefaultColorSpace]
1696         getRed: &red green: &green blue: &blue alpha: &alpha];
1697   if (red == green && red == blue)
1698     {
1699       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1700             getWhite: &gray alpha: &alpha];
1701       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1702                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1703       unblock_input ();
1704       return build_string (buf);
1705     }
1707   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1708             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1710   unblock_input ();
1711   return build_string (buf);
1715 void
1716 ns_query_color(void *col, XColor *color_def, int setPixel)
1717 /* --------------------------------------------------------------------------
1718          Get ARGB values out of NSColor col and put them into color_def.
1719          If setPixel, set the pixel to a concatenated version.
1720          and set color_def pixel to the resulting index.
1721    -------------------------------------------------------------------------- */
1723   EmacsCGFloat r, g, b, a;
1725   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1726   color_def->red   = r * 65535;
1727   color_def->green = g * 65535;
1728   color_def->blue  = b * 65535;
1730   if (setPixel == YES)
1731     color_def->pixel
1732       = ARGB_TO_ULONG((int)(a*255),
1733                       (int)(r*255), (int)(g*255), (int)(b*255));
1737 bool
1738 ns_defined_color (struct frame *f,
1739                   const char *name,
1740                   XColor *color_def,
1741                   bool alloc,
1742                   bool makeIndex)
1743 /* --------------------------------------------------------------------------
1744          Return true if named color found, and set color_def rgb accordingly.
1745          If makeIndex and alloc are nonzero put the color in the color_table,
1746          and set color_def pixel to the resulting index.
1747          If makeIndex is zero, set color_def pixel to ARGB.
1748          Return false if not found
1749    -------------------------------------------------------------------------- */
1751   NSColor *col;
1752   NSTRACE (ns_defined_color);
1754   block_input ();
1755   if (ns_get_color (name, &col) != 0) /* Color not found  */
1756     {
1757       unblock_input ();
1758       return 0;
1759     }
1760   if (makeIndex && alloc)
1761     color_def->pixel = ns_index_color (col, f);
1762   ns_query_color (col, color_def, !makeIndex);
1763   unblock_input ();
1764   return 1;
1768 void
1769 x_set_frame_alpha (struct frame *f)
1770 /* --------------------------------------------------------------------------
1771      change the entire-frame transparency
1772    -------------------------------------------------------------------------- */
1774   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1775   double alpha = 1.0;
1776   double alpha_min = 1.0;
1778   if (dpyinfo->x_highlight_frame == f)
1779     alpha = f->alpha[0];
1780   else
1781     alpha = f->alpha[1];
1783   if (FLOATP (Vframe_alpha_lower_limit))
1784     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1785   else if (INTEGERP (Vframe_alpha_lower_limit))
1786     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1788   if (alpha < 0.0)
1789     return;
1790   else if (1.0 < alpha)
1791     alpha = 1.0;
1792   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1793     alpha = alpha_min;
1795 #ifdef NS_IMPL_COCOA
1796   {
1797     EmacsView *view = FRAME_NS_VIEW (f);
1798   [[view window] setAlphaValue: alpha];
1799   }
1800 #endif
1804 /* ==========================================================================
1806     Mouse handling
1808    ========================================================================== */
1811 void
1812 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1813 /* --------------------------------------------------------------------------
1814      Programmatically reposition mouse pointer in pixel coordinates
1815    -------------------------------------------------------------------------- */
1817   NSTRACE (frame_set_mouse_pixel_position);
1818   ns_raise_frame (f);
1819 #if 0
1820   /* FIXME: this does not work, and what about GNUstep? */
1821 #ifdef NS_IMPL_COCOA
1822   [FRAME_NS_VIEW (f) lockFocus];
1823   PSsetmouse ((float)pix_x, (float)pix_y);
1824   [FRAME_NS_VIEW (f) unlockFocus];
1825 #endif
1826 #endif
1829 static int
1830 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1831 /*   ------------------------------------------------------------------------
1832      Called by EmacsView on mouseMovement events.  Passes on
1833      to emacs mainstream code if we moved off of a rect of interest
1834      known as last_mouse_glyph.
1835      ------------------------------------------------------------------------ */
1837   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1838   NSRect *r;
1840 //  NSTRACE (note_mouse_movement);
1842   dpyinfo->last_mouse_motion_frame = frame;
1843   r = &dpyinfo->last_mouse_glyph;
1845   /* Note, this doesn't get called for enter/leave, since we don't have a
1846      position.  Those are taken care of in the corresponding NSView methods. */
1848   /* has movement gone beyond last rect we were tracking? */
1849   if (x < r->origin.x || x >= r->origin.x + r->size.width
1850       || y < r->origin.y || y >= r->origin.y + r->size.height)
1851     {
1852       ns_update_begin (frame);
1853       frame->mouse_moved = 1;
1854       note_mouse_highlight (frame, x, y);
1855       remember_mouse_glyph (frame, x, y, r);
1856       ns_update_end (frame);
1857       return 1;
1858     }
1860   return 0;
1864 static void
1865 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1866                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1867                    Time *time)
1868 /* --------------------------------------------------------------------------
1869     External (hook): inform emacs about mouse position and hit parts.
1870     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1871     x & y should be position in the scrollbar (the whole bar, not the handle)
1872     and length of scrollbar respectively
1873    -------------------------------------------------------------------------- */
1875   id view;
1876   NSPoint position;
1877   Lisp_Object frame, tail;
1878   struct frame *f;
1879   struct ns_display_info *dpyinfo;
1881   NSTRACE (ns_mouse_position);
1883   if (*fp == NULL)
1884     {
1885       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1886       return;
1887     }
1889   dpyinfo = FRAME_DISPLAY_INFO (*fp);
1891   block_input ();
1893   /* Clear the mouse-moved flag for every frame on this display.  */
1894   FOR_EACH_FRAME (tail, frame)
1895     if (FRAME_NS_P (XFRAME (frame))
1896         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1897       XFRAME (frame)->mouse_moved = 0;
1899   dpyinfo->last_mouse_scroll_bar = nil;
1900   if (dpyinfo->last_mouse_frame
1901       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1902     f = dpyinfo->last_mouse_frame;
1903   else
1904     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
1906   if (f && FRAME_NS_P (f))
1907     {
1908       view = FRAME_NS_VIEW (*fp);
1910       position = [[view window] mouseLocationOutsideOfEventStream];
1911       position = [view convertPoint: position fromView: nil];
1912       remember_mouse_glyph (f, position.x, position.y,
1913                             &dpyinfo->last_mouse_glyph);
1914 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1916       if (bar_window) *bar_window = Qnil;
1917       if (part) *part = scroll_bar_above_handle;
1919       if (x) XSETINT (*x, lrint (position.x));
1920       if (y) XSETINT (*y, lrint (position.y));
1921       if (time)
1922         *time = dpyinfo->last_mouse_movement_time;
1923       *fp = f;
1924     }
1926   unblock_input ();
1930 static void
1931 ns_frame_up_to_date (struct frame *f)
1932 /* --------------------------------------------------------------------------
1933     External (hook): Fix up mouse highlighting right after a full update.
1934     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1935    -------------------------------------------------------------------------- */
1937   NSTRACE (ns_frame_up_to_date);
1939   if (FRAME_NS_P (f))
1940     {
1941       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1942       if (f == hlinfo->mouse_face_mouse_frame)
1943         {
1944           block_input ();
1945           ns_update_begin(f);
1946           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1947                                 hlinfo->mouse_face_mouse_x,
1948                                 hlinfo->mouse_face_mouse_y);
1949           ns_update_end(f);
1950           unblock_input ();
1951         }
1952     }
1956 static void
1957 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1958 /* --------------------------------------------------------------------------
1959     External (RIF): set frame mouse pointer type.
1960    -------------------------------------------------------------------------- */
1962   NSTRACE (ns_define_frame_cursor);
1963   if (FRAME_POINTER_TYPE (f) != cursor)
1964     {
1965       EmacsView *view = FRAME_NS_VIEW (f);
1966       FRAME_POINTER_TYPE (f) = cursor;
1967       [[view window] invalidateCursorRectsForView: view];
1968       /* Redisplay assumes this function also draws the changed frame
1969          cursor, but this function doesn't, so do it explicitly.  */
1970       x_update_cursor (f, 1);
1971     }
1976 /* ==========================================================================
1978     Keyboard handling
1980    ========================================================================== */
1983 static unsigned
1984 ns_convert_key (unsigned code)
1985 /* --------------------------------------------------------------------------
1986     Internal call used by NSView-keyDown.
1987    -------------------------------------------------------------------------- */
1989   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
1990   unsigned keysym;
1991   /* An array would be faster, but less easy to read. */
1992   for (keysym = 0; keysym < last_keysym; keysym += 2)
1993     if (code == convert_ns_to_X_keysym[keysym])
1994       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1995   return 0;
1996 /* if decide to use keyCode and Carbon table, use this line:
1997      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2001 char *
2002 x_get_keysym_name (int keysym)
2003 /* --------------------------------------------------------------------------
2004     Called by keyboard.c.  Not sure if the return val is important, except
2005     that it be unique.
2006    -------------------------------------------------------------------------- */
2008   static char value[16];
2009   NSTRACE (x_get_keysym_name);
2010   sprintf (value, "%d", keysym);
2011   return value;
2016 /* ==========================================================================
2018     Block drawing operations
2020    ========================================================================== */
2023 static void
2024 ns_redraw_scroll_bars (struct frame *f)
2026   int i;
2027   id view;
2028   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2029   NSTRACE (ns_redraw_scroll_bars);
2030   for (i =[subviews count]-1; i >= 0; i--)
2031     {
2032       view = [subviews objectAtIndex: i];
2033       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2034       [view display];
2035     }
2039 void
2040 ns_clear_frame (struct frame *f)
2041 /* --------------------------------------------------------------------------
2042       External (hook): Erase the entire frame
2043    -------------------------------------------------------------------------- */
2045   NSView *view = FRAME_NS_VIEW (f);
2046   NSRect r;
2048   NSTRACE (ns_clear_frame);
2050  /* comes on initial frame because we have
2051     after-make-frame-functions = select-frame */
2052  if (!FRAME_DEFAULT_FACE (f))
2053    return;
2055   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2057   r = [view bounds];
2059   block_input ();
2060   ns_focus (f, &r, 1);
2061   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2062   NSRectFill (r);
2063   ns_unfocus (f);
2065   /* as of 2006/11 or so this is now needed */
2066   ns_redraw_scroll_bars (f);
2067   unblock_input ();
2071 static void
2072 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2073 /* --------------------------------------------------------------------------
2074     External (RIF):  Clear section of frame
2075    -------------------------------------------------------------------------- */
2077   NSRect r = NSMakeRect (x, y, width, height);
2078   NSView *view = FRAME_NS_VIEW (f);
2079   struct face *face = FRAME_DEFAULT_FACE (f);
2081   if (!view || !face)
2082     return;
2084   NSTRACE (ns_clear_frame_area);
2086   r = NSIntersectionRect (r, [view frame]);
2087   ns_focus (f, &r, 1);
2088   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2090   NSRectFill (r);
2092   ns_unfocus (f);
2093   return;
2096 static void
2097 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2099   if (FRAME_NS_VIEW (f))
2100     {
2101       ns_focus (f, &dest, 1);
2102       [FRAME_NS_VIEW (f) scrollRect: src
2103                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2104                                                  dest.origin.y - src.origin.y)];
2105       ns_unfocus (f);
2106     }
2109 static void
2110 ns_scroll_run (struct window *w, struct run *run)
2111 /* --------------------------------------------------------------------------
2112     External (RIF):  Insert or delete n lines at line vpos
2113    -------------------------------------------------------------------------- */
2115   struct frame *f = XFRAME (w->frame);
2116   int x, y, width, height, from_y, to_y, bottom_y;
2118   NSTRACE (ns_scroll_run);
2120   /* begin copy from other terms */
2121   /* Get frame-relative bounding box of the text display area of W,
2122      without mode lines.  Include in this box the left and right
2123      fringe of W.  */
2124   window_box (w, ANY_AREA, &x, &y, &width, &height);
2126   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2127   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2128   bottom_y = y + height;
2130   if (to_y < from_y)
2131     {
2132       /* Scrolling up.  Make sure we don't copy part of the mode
2133          line at the bottom.  */
2134       if (from_y + run->height > bottom_y)
2135         height = bottom_y - from_y;
2136       else
2137         height = run->height;
2138     }
2139   else
2140     {
2141       /* Scrolling down.  Make sure we don't copy over the mode line.
2142          at the bottom.  */
2143       if (to_y + run->height > bottom_y)
2144         height = bottom_y - to_y;
2145       else
2146         height = run->height;
2147     }
2148   /* end copy from other terms */
2150   if (height == 0)
2151       return;
2153   block_input ();
2155   x_clear_cursor (w);
2157   {
2158     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2159     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2161     ns_copy_bits (f, srcRect , dstRect);
2162   }
2164   unblock_input ();
2168 static void
2169 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2170 /* --------------------------------------------------------------------------
2171     External (RIF): preparatory to fringe update after text was updated
2172    -------------------------------------------------------------------------- */
2174   struct frame *f;
2175   int width, height;
2177   NSTRACE (ns_after_update_window_line);
2179   /* begin copy from other terms */
2180   eassert (w);
2182   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2183     desired_row->redraw_fringe_bitmaps_p = 1;
2185   /* When a window has disappeared, make sure that no rest of
2186      full-width rows stays visible in the internal border.  */
2187   if (windows_or_buffers_changed
2188       && desired_row->full_width_p
2189       && (f = XFRAME (w->frame),
2190           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2191           width != 0)
2192       && (height = desired_row->visible_height,
2193           height > 0))
2194     {
2195       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2197       block_input ();
2198       ns_clear_frame_area (f, 0, y, width, height);
2199       ns_clear_frame_area (f,
2200                            FRAME_PIXEL_WIDTH (f) - width,
2201                            y, width, height);
2202       unblock_input ();
2203     }
2207 static void
2208 ns_shift_glyphs_for_insert (struct frame *f,
2209                            int x, int y, int width, int height,
2210                            int shift_by)
2211 /* --------------------------------------------------------------------------
2212     External (RIF): copy an area horizontally, don't worry about clearing src
2213    -------------------------------------------------------------------------- */
2215   NSRect srcRect = NSMakeRect (x, y, width, height);
2216   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2218   NSTRACE (ns_shift_glyphs_for_insert);
2220   ns_copy_bits (f, srcRect, dstRect);
2225 /* ==========================================================================
2227     Character encoding and metrics
2229    ========================================================================== */
2232 static void
2233 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2234 /* --------------------------------------------------------------------------
2235      External (RIF); compute left/right overhang of whole string and set in s
2236    -------------------------------------------------------------------------- */
2238   struct font *font = s->font;
2240   if (s->char2b)
2241     {
2242       struct font_metrics metrics;
2243       unsigned int codes[2];
2244       codes[0] = *(s->char2b);
2245       codes[1] = *(s->char2b + s->nchars - 1);
2247       font->driver->text_extents (font, codes, 2, &metrics);
2248       s->left_overhang = -metrics.lbearing;
2249       s->right_overhang
2250         = metrics.rbearing > metrics.width
2251         ? metrics.rbearing - metrics.width : 0;
2252     }
2253   else
2254     {
2255       s->left_overhang = 0;
2256       if (EQ (font->driver->type, Qns))
2257         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2258           FONT_HEIGHT (font) * 0.2 : 0;
2259       else
2260         s->right_overhang = 0;
2261     }
2266 /* ==========================================================================
2268     Fringe and cursor drawing
2270    ========================================================================== */
2273 extern int max_used_fringe_bitmap;
2274 static void
2275 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2276                       struct draw_fringe_bitmap_params *p)
2277 /* --------------------------------------------------------------------------
2278     External (RIF); fringe-related
2279    -------------------------------------------------------------------------- */
2281   struct frame *f = XFRAME (WINDOW_FRAME (w));
2282   struct face *face = p->face;
2283   static EmacsImage **bimgs = NULL;
2284   static int nBimgs = 0;
2286   /* grow bimgs if needed */
2287   if (nBimgs < max_used_fringe_bitmap)
2288     {
2289       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2290       memset (bimgs + nBimgs, 0,
2291               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2292       nBimgs = max_used_fringe_bitmap;
2293     }
2295   /* Must clip because of partially visible lines.  */
2296   ns_clip_to_row (w, row, ANY_AREA, YES);
2298   if (!p->overlay_p)
2299     {
2300       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2302       if (bx >= 0 && nx > 0)
2303         {
2304           NSRect r = NSMakeRect (bx, by, nx, ny);
2305           NSRectClip (r);
2306           [ns_lookup_indexed_color (face->background, f) set];
2307           NSRectFill (r);
2308         }
2309     }
2311   if (p->which)
2312     {
2313       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2314       EmacsImage *img = bimgs[p->which - 1];
2316       if (!img)
2317         {
2318           unsigned short *bits = p->bits + p->dh;
2319           int len = p->h;
2320           int i;
2321           unsigned char *cbits = xmalloc (len);
2323           for (i = 0; i < len; i++)
2324             cbits[i] = ~(bits[i] & 0xff);
2325           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2326                                              fg: 0 bg: 0];
2327           bimgs[p->which - 1] = img;
2328           xfree (cbits);
2329         }
2331       NSRectClip (r);
2332       /* Since we composite the bitmap instead of just blitting it, we need
2333          to erase the whole background. */
2334       [ns_lookup_indexed_color(face->background, f) set];
2335       NSRectFill (r);
2337       {
2338         NSColor *bm_color;
2339         if (!p->cursor_p)
2340           bm_color = ns_lookup_indexed_color(face->foreground, f);
2341         else if (p->overlay_p)
2342           bm_color = ns_lookup_indexed_color(face->background, f);
2343         else
2344           bm_color = f->output_data.ns->cursor_color;
2345         [img setXBMColor: bm_color];
2346       }
2348 #ifdef NS_IMPL_COCOA
2349       [img drawInRect: r
2350               fromRect: NSZeroRect
2351              operation: NSCompositeSourceOver
2352               fraction: 1.0
2353            respectFlipped: YES
2354                 hints: nil];
2355 #else
2356       {
2357         NSPoint pt = r.origin;
2358         pt.y += p->h;
2359         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2360       }
2361 #endif
2362     }
2363   ns_unfocus (f);
2367 static void
2368 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2369                        int x, int y, enum text_cursor_kinds cursor_type,
2370                        int cursor_width, bool on_p, bool active_p)
2371 /* --------------------------------------------------------------------------
2372      External call (RIF): draw cursor.
2373      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2374    -------------------------------------------------------------------------- */
2376   NSRect r, s;
2377   int fx, fy, h, cursor_height;
2378   struct frame *f = WINDOW_XFRAME (w);
2379   struct glyph *phys_cursor_glyph;
2380   struct glyph *cursor_glyph;
2381   struct face *face;
2382   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2384   /* If cursor is out of bounds, don't draw garbage.  This can happen
2385      in mini-buffer windows when switching between echo area glyphs
2386      and mini-buffer.  */
2388   NSTRACE (dumpcursor);
2390   if (!on_p)
2391     return;
2393   w->phys_cursor_type = cursor_type;
2394   w->phys_cursor_on_p = on_p;
2396   if (cursor_type == NO_CURSOR)
2397     {
2398       w->phys_cursor_width = 0;
2399       return;
2400     }
2402   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2403     {
2404       if (glyph_row->exact_window_width_line_p
2405           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2406         {
2407           glyph_row->cursor_in_fringe_p = 1;
2408           draw_fringe_bitmap (w, glyph_row, 0);
2409         }
2410       return;
2411     }
2413   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2414      (other terminals do it the other way round).  We must set
2415      w->phys_cursor_width to the cursor width.  For bar cursors, that
2416      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2417   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2419   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2420      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2421   if (cursor_type == BAR_CURSOR)
2422     {
2423       if (cursor_width < 1)
2424         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2425       w->phys_cursor_width = cursor_width;
2426     }
2427   /* If we have an HBAR, "cursor_width" MAY specify height. */
2428   else if (cursor_type == HBAR_CURSOR)
2429     {
2430       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2431       if (cursor_height > glyph_row->height)
2432         cursor_height = glyph_row->height;
2433       if (h > cursor_height) // Cursor smaller than line height, move down
2434         fy += h - cursor_height;
2435       h = cursor_height;
2436     }
2438   r.origin.x = fx, r.origin.y = fy;
2439   r.size.height = h;
2440   r.size.width = w->phys_cursor_width;
2442   /* TODO: only needed in rare cases with last-resort font in HELLO..
2443      should we do this more efficiently? */
2444   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2447   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2448   if (face && NS_FACE_BACKGROUND (face)
2449       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2450     {
2451       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2452       hollow_color = FRAME_CURSOR_COLOR (f);
2453     }
2454   else
2455     [FRAME_CURSOR_COLOR (f) set];
2457 #ifdef NS_IMPL_COCOA
2458   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2459            atomic.  Cleaner ways of doing this should be investigated.
2460            One way would be to set a global variable DRAWING_CURSOR
2461            when making the call to draw_phys..(), don't focus in that
2462            case, then move the ns_unfocus() here after that call. */
2463   NSDisableScreenUpdates ();
2464 #endif
2466   switch (cursor_type)
2467     {
2468     case DEFAULT_CURSOR:
2469     case NO_CURSOR:
2470       break;
2471     case FILLED_BOX_CURSOR:
2472       NSRectFill (r);
2473       break;
2474     case HOLLOW_BOX_CURSOR:
2475       NSRectFill (r);
2476       [hollow_color set];
2477       NSRectFill (NSInsetRect (r, 1, 1));
2478       [FRAME_CURSOR_COLOR (f) set];
2479       break;
2480     case HBAR_CURSOR:
2481       NSRectFill (r);
2482       break;
2483     case BAR_CURSOR:
2484       s = r;
2485       /* If the character under cursor is R2L, draw the bar cursor
2486          on the right of its glyph, rather than on the left.  */
2487       cursor_glyph = get_phys_cursor_glyph (w);
2488       if ((cursor_glyph->resolved_level & 1) != 0)
2489         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2491       NSRectFill (s);
2492       break;
2493     }
2494   ns_unfocus (f);
2496   /* draw the character under the cursor */
2497   if (cursor_type != NO_CURSOR)
2498     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2500 #ifdef NS_IMPL_COCOA
2501   NSEnableScreenUpdates ();
2502 #endif
2507 static void
2508 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2509 /* --------------------------------------------------------------------------
2510      External (RIF): Draw a vertical line.
2511    -------------------------------------------------------------------------- */
2513   struct frame *f = XFRAME (WINDOW_FRAME (w));
2514   struct face *face;
2515   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2517   NSTRACE (ns_draw_vertical_window_border);
2519   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2520   if (face)
2521       [ns_lookup_indexed_color(face->foreground, f) set];
2523   ns_focus (f, &r, 1);
2524   NSRectFill(r);
2525   ns_unfocus (f);
2529 static void
2530 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2531 /* --------------------------------------------------------------------------
2532      External (RIF): Draw a window divider.
2533    -------------------------------------------------------------------------- */
2535   struct frame *f = XFRAME (WINDOW_FRAME (w));
2536   struct face *face;
2537   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2539   NSTRACE (ns_draw_window_divider);
2541   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2542   if (face)
2543       [ns_lookup_indexed_color(face->foreground, f) set];
2545   ns_focus (f, &r, 1);
2546   NSRectFill(r);
2547   ns_unfocus (f);
2550 static void
2551 ns_show_hourglass (struct frame *f)
2553   /* TODO: add NSProgressIndicator to all frames.  */
2556 static void
2557 ns_hide_hourglass (struct frame *f)
2559   /* TODO: remove NSProgressIndicator from all frames.  */
2562 /* ==========================================================================
2564     Glyph drawing operations
2566    ========================================================================== */
2568 static int
2569 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2570 /* --------------------------------------------------------------------------
2571     Wrapper utility to account for internal border width on full-width lines,
2572     and allow top full-width rows to hit the frame top.  nr should be pointer
2573     to two successive NSRects.  Number of rects actually used is returned.
2574    -------------------------------------------------------------------------- */
2576   int n = get_glyph_string_clip_rects (s, nr, 2);
2577   return n;
2580 /* --------------------------------------------------------------------
2581    Draw a wavy line under glyph string s. The wave fills wave_height
2582    pixels from y.
2584                     x          wave_length = 2
2585                                  --
2586                 y    *   *   *   *   *
2587                      |* * * * * * * * *
2588     wave_height = 3  | *   *   *   *
2589   --------------------------------------------------------------------- */
2591 static void
2592 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2594   int wave_height = 3, wave_length = 2;
2595   int y, dx, dy, odd, xmax;
2596   NSPoint a, b;
2597   NSRect waveClip;
2599   dx = wave_length;
2600   dy = wave_height - 1;
2601   y =  s->ybase - wave_height + 3;
2602   xmax = x + width;
2604   /* Find and set clipping rectangle */
2605   waveClip = NSMakeRect (x, y, width, wave_height);
2606   [[NSGraphicsContext currentContext] saveGraphicsState];
2607   NSRectClip (waveClip);
2609   /* Draw the waves */
2610   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2611   b.x = a.x + dx;
2612   odd = (int)(a.x/dx) % 2;
2613   a.y = b.y = y + 0.5;
2615   if (odd)
2616     a.y += dy;
2617   else
2618     b.y += dy;
2620   while (a.x <= xmax)
2621     {
2622       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2623       a.x = b.x, a.y = b.y;
2624       b.x += dx, b.y = y + 0.5 + odd*dy;
2625       odd = !odd;
2626     }
2628   /* Restore previous clipping rectangle(s) */
2629   [[NSGraphicsContext currentContext] restoreGraphicsState];
2634 void
2635 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2636                          NSColor *defaultCol, CGFloat width, CGFloat x)
2637 /* --------------------------------------------------------------------------
2638    Draw underline, overline, and strike-through on glyph string s.
2639    -------------------------------------------------------------------------- */
2641   if (s->for_overlaps)
2642     return;
2644   /* Do underline. */
2645   if (face->underline_p)
2646     {
2647       if (s->face->underline_type == FACE_UNDER_WAVE)
2648         {
2649           if (face->underline_defaulted_p)
2650             [defaultCol set];
2651           else
2652             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2654           ns_draw_underwave (s, width, x);
2655         }
2656       else if (s->face->underline_type == FACE_UNDER_LINE)
2657         {
2659           NSRect r;
2660           unsigned long thickness, position;
2662           /* If the prev was underlined, match its appearance. */
2663           if (s->prev && s->prev->face->underline_p
2664               && s->prev->face->underline_type == FACE_UNDER_LINE
2665               && s->prev->underline_thickness > 0)
2666             {
2667               thickness = s->prev->underline_thickness;
2668               position = s->prev->underline_position;
2669             }
2670           else
2671             {
2672               struct font *font;
2673               unsigned long descent;
2675               font=s->font;
2676               descent = s->y + s->height - s->ybase;
2678               /* Use underline thickness of font, defaulting to 1. */
2679               thickness = (font && font->underline_thickness > 0)
2680                 ? font->underline_thickness : 1;
2682               /* Determine the offset of underlining from the baseline. */
2683               if (x_underline_at_descent_line)
2684                 position = descent - thickness;
2685               else if (x_use_underline_position_properties
2686                        && font && font->underline_position >= 0)
2687                 position = font->underline_position;
2688               else if (font)
2689                 position = lround (font->descent / 2);
2690               else
2691                 position = underline_minimum_offset;
2693               position = max (position, underline_minimum_offset);
2695               /* Ensure underlining is not cropped. */
2696               if (descent <= position)
2697                 {
2698                   position = descent - 1;
2699                   thickness = 1;
2700                 }
2701               else if (descent < position + thickness)
2702                 thickness = 1;
2703             }
2705           s->underline_thickness = thickness;
2706           s->underline_position = position;
2708           r = NSMakeRect (x, s->ybase + position, width, thickness);
2710           if (face->underline_defaulted_p)
2711             [defaultCol set];
2712           else
2713             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2714           NSRectFill (r);
2715         }
2716     }
2717   /* Do overline. We follow other terms in using a thickness of 1
2718      and ignoring overline_margin. */
2719   if (face->overline_p)
2720     {
2721       NSRect r;
2722       r = NSMakeRect (x, s->y, width, 1);
2724       if (face->overline_color_defaulted_p)
2725         [defaultCol set];
2726       else
2727         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2728       NSRectFill (r);
2729     }
2731   /* Do strike-through.  We follow other terms for thickness and
2732      vertical position.*/
2733   if (face->strike_through_p)
2734     {
2735       NSRect r;
2736       unsigned long dy;
2738       dy = lrint ((s->height - 1) / 2);
2739       r = NSMakeRect (x, s->y + dy, width, 1);
2741       if (face->strike_through_color_defaulted_p)
2742         [defaultCol set];
2743       else
2744         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2745       NSRectFill (r);
2746     }
2749 static void
2750 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2751              char left_p, char right_p)
2752 /* --------------------------------------------------------------------------
2753     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2754     Note we can't just use an NSDrawRect command, because of the possibility
2755     of some sides not being drawn, and because the rect will be filled.
2756    -------------------------------------------------------------------------- */
2758   NSRect s = r;
2759   [col set];
2761   /* top, bottom */
2762   s.size.height = thickness;
2763   NSRectFill (s);
2764   s.origin.y += r.size.height - thickness;
2765   NSRectFill (s);
2767   s.size.height = r.size.height;
2768   s.origin.y = r.origin.y;
2770   /* left, right (optional) */
2771   s.size.width = thickness;
2772   if (left_p)
2773     NSRectFill (s);
2774   if (right_p)
2775     {
2776       s.origin.x += r.size.width - thickness;
2777       NSRectFill (s);
2778     }
2782 static void
2783 ns_draw_relief (NSRect r, int thickness, char raised_p,
2784                char top_p, char bottom_p, char left_p, char right_p,
2785                struct glyph_string *s)
2786 /* --------------------------------------------------------------------------
2787     Draw a relief rect inside r, optionally leaving some sides open.
2788     Note we can't just use an NSDrawBezel command, because of the possibility
2789     of some sides not being drawn, and because the rect will be filled.
2790    -------------------------------------------------------------------------- */
2792   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2793   NSColor *newBaseCol = nil;
2794   NSRect sr = r;
2796   NSTRACE (ns_draw_relief);
2798   /* set up colors */
2800   if (s->face->use_box_color_for_shadows_p)
2801     {
2802       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2803     }
2804 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2805            && s->img->pixmap
2806            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2807        {
2808          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2809        } */
2810   else
2811     {
2812       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2813     }
2815   if (newBaseCol == nil)
2816     newBaseCol = [NSColor grayColor];
2818   if (newBaseCol != baseCol)  /* TODO: better check */
2819     {
2820       [baseCol release];
2821       baseCol = [newBaseCol retain];
2822       [lightCol release];
2823       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2824       [darkCol release];
2825       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2826     }
2828   [(raised_p ? lightCol : darkCol) set];
2830   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2832   /* top */
2833   sr.size.height = thickness;
2834   if (top_p) NSRectFill (sr);
2836   /* left */
2837   sr.size.height = r.size.height;
2838   sr.size.width = thickness;
2839   if (left_p) NSRectFill (sr);
2841   [(raised_p ? darkCol : lightCol) set];
2843   /* bottom */
2844   sr.size.width = r.size.width;
2845   sr.size.height = thickness;
2846   sr.origin.y += r.size.height - thickness;
2847   if (bottom_p) NSRectFill (sr);
2849   /* right */
2850   sr.size.height = r.size.height;
2851   sr.origin.y = r.origin.y;
2852   sr.size.width = thickness;
2853   sr.origin.x += r.size.width - thickness;
2854   if (right_p) NSRectFill (sr);
2858 static void
2859 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2860 /* --------------------------------------------------------------------------
2861       Function modeled after x_draw_glyph_string_box ().
2862       Sets up parameters for drawing.
2863    -------------------------------------------------------------------------- */
2865   int right_x, last_x;
2866   char left_p, right_p;
2867   struct glyph *last_glyph;
2868   NSRect r;
2869   int thickness;
2870   struct face *face;
2872   if (s->hl == DRAW_MOUSE_FACE)
2873     {
2874       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2875       if (!face)
2876         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2877     }
2878   else
2879     face = s->face;
2881   thickness = face->box_line_width;
2883   NSTRACE (ns_dumpglyphs_box_or_relief);
2885   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2886             ? WINDOW_RIGHT_EDGE_X (s->w)
2887             : window_box_right (s->w, s->area));
2888   last_glyph = (s->cmp || s->img
2889                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2891   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2892               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2894   left_p = (s->first_glyph->left_box_line_p
2895             || (s->hl == DRAW_MOUSE_FACE
2896                 && (s->prev == NULL || s->prev->hl != s->hl)));
2897   right_p = (last_glyph->right_box_line_p
2898              || (s->hl == DRAW_MOUSE_FACE
2899                  && (s->next == NULL || s->next->hl != s->hl)));
2901   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2903   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2904   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2905     {
2906       ns_draw_box (r, abs (thickness),
2907                    ns_lookup_indexed_color (face->box_color, s->f),
2908                   left_p, right_p);
2909     }
2910   else
2911     {
2912       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2913                      1, 1, left_p, right_p, s);
2914     }
2918 static void
2919 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2920 /* --------------------------------------------------------------------------
2921       Modeled after x_draw_glyph_string_background, which draws BG in
2922       certain cases.  Others are left to the text rendering routine.
2923    -------------------------------------------------------------------------- */
2925   NSTRACE (ns_maybe_dumpglyphs_background);
2927   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2928     {
2929       int box_line_width = max (s->face->box_line_width, 0);
2930       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2931           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
2932              dimensions, since the actual glyphs might be much
2933              smaller.  So in that case we always clear the rectangle
2934              with background color.  */
2935           || FONT_TOO_HIGH (s->font)
2936           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2937         {
2938           struct face *face;
2939           if (s->hl == DRAW_MOUSE_FACE)
2940             {
2941               face = FACE_FROM_ID (s->f,
2942                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2943               if (!face)
2944                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2945             }
2946           else
2947             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2948           if (!face->stipple)
2949             [(NS_FACE_BACKGROUND (face) != 0
2950               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2951               : FRAME_BACKGROUND_COLOR (s->f)) set];
2952           else
2953             {
2954               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2955               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2956             }
2958           if (s->hl != DRAW_CURSOR)
2959             {
2960               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2961                                     s->background_width,
2962                                     s->height-2*box_line_width);
2963               NSRectFill (r);
2964             }
2966           s->background_filled_p = 1;
2967         }
2968     }
2972 static void
2973 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2974 /* --------------------------------------------------------------------------
2975       Renders an image and associated borders.
2976    -------------------------------------------------------------------------- */
2978   EmacsImage *img = s->img->pixmap;
2979   int box_line_vwidth = max (s->face->box_line_width, 0);
2980   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2981   int bg_x, bg_y, bg_height;
2982   int th;
2983   char raised_p;
2984   NSRect br;
2985   struct face *face;
2986   NSColor *tdCol;
2988   NSTRACE (ns_dumpglyphs_image);
2990   if (s->face->box != FACE_NO_BOX
2991       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2992     x += abs (s->face->box_line_width);
2994   bg_x = x;
2995   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2996   bg_height = s->height;
2997   /* other terms have this, but was causing problems w/tabbar mode */
2998   /* - 2 * box_line_vwidth; */
3000   if (s->slice.x == 0) x += s->img->hmargin;
3001   if (s->slice.y == 0) y += s->img->vmargin;
3003   /* Draw BG: if we need larger area than image itself cleared, do that,
3004      otherwise, since we composite the image under NS (instead of mucking
3005      with its background color), we must clear just the image area. */
3006   if (s->hl == DRAW_MOUSE_FACE)
3007     {
3008       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3009       if (!face)
3010        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3011     }
3012   else
3013     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3015   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3017   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3018       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3019     {
3020       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3021       s->background_filled_p = 1;
3022     }
3023   else
3024     {
3025       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3026     }
3028   NSRectFill (br);
3030   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3031   if (img != nil)
3032     {
3033 #ifdef NS_IMPL_COCOA
3034       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3035       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3036                               s->slice.width, s->slice.height);
3037       [img drawInRect: dr
3038              fromRect: ir
3039              operation: NSCompositeSourceOver
3040               fraction: 1.0
3041            respectFlipped: YES
3042                 hints: nil];
3043 #else
3044       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3045                   operation: NSCompositeSourceOver];
3046 #endif
3047     }
3049   if (s->hl == DRAW_CURSOR)
3050     {
3051     [FRAME_CURSOR_COLOR (s->f) set];
3052     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3053       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3054     else
3055       /* Currently on NS img->mask is always 0. Since
3056          get_window_cursor_type specifies a hollow box cursor when on
3057          a non-masked image we never reach this clause. But we put it
3058          in in anticipation of better support for image masks on
3059          NS. */
3060       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3061     }
3062   else
3063     {
3064       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3065     }
3067   /* Draw underline, overline, strike-through. */
3068   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3070   /* Draw relief, if requested */
3071   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3072     {
3073       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3074         {
3075           th = tool_bar_button_relief >= 0 ?
3076             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3077           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3078         }
3079       else
3080         {
3081           th = abs (s->img->relief);
3082           raised_p = (s->img->relief > 0);
3083         }
3085       r.origin.x = x - th;
3086       r.origin.y = y - th;
3087       r.size.width = s->slice.width + 2*th-1;
3088       r.size.height = s->slice.height + 2*th-1;
3089       ns_draw_relief (r, th, raised_p,
3090                       s->slice.y == 0,
3091                       s->slice.y + s->slice.height == s->img->height,
3092                       s->slice.x == 0,
3093                       s->slice.x + s->slice.width == s->img->width, s);
3094     }
3096   /* If there is no mask, the background won't be seen,
3097      so draw a rectangle on the image for the cursor.
3098      Do this for all images, getting transparency right is not reliable.  */
3099   if (s->hl == DRAW_CURSOR)
3100     {
3101       int thickness = abs (s->img->relief);
3102       if (thickness == 0) thickness = 1;
3103       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3104     }
3108 static void
3109 ns_dumpglyphs_stretch (struct glyph_string *s)
3111   NSRect r[2];
3112   int n, i;
3113   struct face *face;
3114   NSColor *fgCol, *bgCol;
3116   if (!s->background_filled_p)
3117     {
3118       n = ns_get_glyph_string_clip_rect (s, r);
3119       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3121       ns_focus (s->f, r, n);
3123       if (s->hl == DRAW_MOUSE_FACE)
3124        {
3125          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3126          if (!face)
3127            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3128        }
3129       else
3130        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3132       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3133       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3135       for (i = 0; i < n; ++i)
3136         {
3137           if (!s->row->full_width_p)
3138             {
3139               int overrun, leftoverrun;
3141               /* truncate to avoid overwriting fringe and/or scrollbar */
3142               overrun = max (0, (s->x + s->background_width)
3143                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3144                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3145               r[i].size.width -= overrun;
3147               /* truncate to avoid overwriting to left of the window box */
3148               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3149                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3151               if (leftoverrun > 0)
3152                 {
3153                   r[i].origin.x += leftoverrun;
3154                   r[i].size.width -= leftoverrun;
3155                 }
3157               /* XXX: Try to work between problem where a stretch glyph on
3158                  a partially-visible bottom row will clear part of the
3159                  modeline, and another where list-buffers headers and similar
3160                  rows erroneously have visible_height set to 0.  Not sure
3161                  where this is coming from as other terms seem not to show. */
3162               r[i].size.height = min (s->height, s->row->visible_height);
3163             }
3165           [bgCol set];
3167           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3168              overwriting cursor (usually when cursor on a tab) */
3169           if (s->hl == DRAW_CURSOR)
3170             {
3171               CGFloat x, width;
3173               x = r[i].origin.x;
3174               width = s->w->phys_cursor_width;
3175               r[i].size.width -= width;
3176               r[i].origin.x += width;
3178               NSRectFill (r[i]);
3180               /* Draw overlining, etc. on the cursor. */
3181               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3182                 ns_draw_text_decoration (s, face, bgCol, width, x);
3183               else
3184                 ns_draw_text_decoration (s, face, fgCol, width, x);
3185             }
3186           else
3187             {
3188               NSRectFill (r[i]);
3189             }
3191           /* Draw overlining, etc. on the stretch glyph (or the part
3192              of the stretch glyph after the cursor). */
3193           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3194                                    r[i].origin.x);
3195         }
3196       ns_unfocus (s->f);
3197       s->background_filled_p = 1;
3198     }
3202 static void
3203 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3205   int i, j, x;
3206   struct font *font = s->font;
3208   /* If first glyph of S has a left box line, start drawing the text
3209      of S to the right of that box line.  */
3210   if (s->face && s->face->box != FACE_NO_BOX
3211       && s->first_glyph->left_box_line_p)
3212     x = s->x + eabs (s->face->box_line_width);
3213   else
3214     x = s->x;
3216   /* S is a glyph string for a composition.  S->cmp_from is the index
3217      of the first character drawn for glyphs of this composition.
3218      S->cmp_from == 0 means we are drawing the very first character of
3219      this composition.  */
3221   /* Draw a rectangle for the composition if the font for the very
3222      first character of the composition could not be loaded.  */
3223   if (s->font_not_found_p)
3224     {
3225       if (s->cmp_from == 0)
3226         {
3227           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3228           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3229         }
3230     }
3231   else if (! s->first_glyph->u.cmp.automatic)
3232     {
3233       int y = s->ybase;
3235       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3236         /* TAB in a composition means display glyphs with padding
3237            space on the left or right.  */
3238         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3239           {
3240             int xx = x + s->cmp->offsets[j * 2];
3241             int yy = y - s->cmp->offsets[j * 2 + 1];
3243             font->driver->draw (s, j, j + 1, xx, yy, false);
3244             if (s->face->overstrike)
3245               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3246           }
3247     }
3248   else
3249     {
3250       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3251       Lisp_Object glyph;
3252       int y = s->ybase;
3253       int width = 0;
3255       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3256         {
3257           glyph = LGSTRING_GLYPH (gstring, i);
3258           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3259             width += LGLYPH_WIDTH (glyph);
3260           else
3261             {
3262               int xoff, yoff, wadjust;
3264               if (j < i)
3265                 {
3266                   font->driver->draw (s, j, i, x, y, false);
3267                   if (s->face->overstrike)
3268                     font->driver->draw (s, j, i, x + 1, y, false);
3269                   x += width;
3270                 }
3271               xoff = LGLYPH_XOFF (glyph);
3272               yoff = LGLYPH_YOFF (glyph);
3273               wadjust = LGLYPH_WADJUST (glyph);
3274               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3275               if (s->face->overstrike)
3276                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3277                                     false);
3278               x += wadjust;
3279               j = i + 1;
3280               width = 0;
3281             }
3282         }
3283       if (j < i)
3284         {
3285           font->driver->draw (s, j, i, x, y, false);
3286           if (s->face->overstrike)
3287             font->driver->draw (s, j, i, x + 1, y, false);
3288         }
3289     }
3292 static void
3293 ns_draw_glyph_string (struct glyph_string *s)
3294 /* --------------------------------------------------------------------------
3295       External (RIF): Main draw-text call.
3296    -------------------------------------------------------------------------- */
3298   /* TODO (optimize): focus for box and contents draw */
3299   NSRect r[2];
3300   int n, flags;
3301   char box_drawn_p = 0;
3302   struct font *font = s->face->font;
3303   if (! font) font = FRAME_FONT (s->f);
3305   NSTRACE (ns_draw_glyph_string);
3307   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3308     {
3309       int width;
3310       struct glyph_string *next;
3312       for (width = 0, next = s->next;
3313            next && width < s->right_overhang;
3314            width += next->width, next = next->next)
3315         if (next->first_glyph->type != IMAGE_GLYPH)
3316           {
3317             if (next->first_glyph->type != STRETCH_GLYPH)
3318               {
3319                 n = ns_get_glyph_string_clip_rect (s->next, r);
3320                 ns_focus (s->f, r, n);
3321                 ns_maybe_dumpglyphs_background (s->next, 1);
3322                 ns_unfocus (s->f);
3323               }
3324             else
3325               {
3326                 ns_dumpglyphs_stretch (s->next);
3327               }
3328             next->num_clips = 0;
3329           }
3330     }
3332   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3333         && (s->first_glyph->type == CHAR_GLYPH
3334             || s->first_glyph->type == COMPOSITE_GLYPH))
3335     {
3336       n = ns_get_glyph_string_clip_rect (s, r);
3337       ns_focus (s->f, r, n);
3338       ns_maybe_dumpglyphs_background (s, 1);
3339       ns_dumpglyphs_box_or_relief (s);
3340       ns_unfocus (s->f);
3341       box_drawn_p = 1;
3342     }
3344   switch (s->first_glyph->type)
3345     {
3347     case IMAGE_GLYPH:
3348       n = ns_get_glyph_string_clip_rect (s, r);
3349       ns_focus (s->f, r, n);
3350       ns_dumpglyphs_image (s, r[0]);
3351       ns_unfocus (s->f);
3352       break;
3354     case STRETCH_GLYPH:
3355       ns_dumpglyphs_stretch (s);
3356       break;
3358     case CHAR_GLYPH:
3359     case COMPOSITE_GLYPH:
3360       n = ns_get_glyph_string_clip_rect (s, r);
3361       ns_focus (s->f, r, n);
3363       if (s->for_overlaps || (s->cmp_from > 0
3364                               && ! s->first_glyph->u.cmp.automatic))
3365         s->background_filled_p = 1;
3366       else
3367         ns_maybe_dumpglyphs_background
3368           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3370       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3371         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3372          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3373           NS_DUMPGLYPH_NORMAL));
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       {
3383         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3385         if (isComposite)
3386           ns_draw_composite_glyph_string_foreground (s);
3387         else
3388           font->driver->draw
3389             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3390              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3391              || flags == NS_DUMPGLYPH_MOUSEFACE);
3392       }
3394       {
3395         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3396                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3397                                                    s->f)
3398                         : FRAME_FOREGROUND_COLOR (s->f));
3399         [col set];
3401         /* Draw underline, overline, strike-through. */
3402         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3403       }
3405       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3406         {
3407           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3408           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3409           NS_FACE_FOREGROUND (s->face) = tmp;
3410         }
3412       ns_unfocus (s->f);
3413       break;
3415     case GLYPHLESS_GLYPH:
3416       n = ns_get_glyph_string_clip_rect (s, r);
3417       ns_focus (s->f, r, n);
3419       if (s->for_overlaps || (s->cmp_from > 0
3420                               && ! s->first_glyph->u.cmp.automatic))
3421         s->background_filled_p = 1;
3422       else
3423         ns_maybe_dumpglyphs_background
3424           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3425       /* ... */
3426       /* Not yet implemented.  */
3427       /* ... */
3428       ns_unfocus (s->f);
3429       break;
3431     default:
3432       emacs_abort ();
3433     }
3435   /* Draw box if not done already. */
3436   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3437     {
3438       n = ns_get_glyph_string_clip_rect (s, r);
3439       ns_focus (s->f, r, n);
3440       ns_dumpglyphs_box_or_relief (s);
3441       ns_unfocus (s->f);
3442     }
3444   s->num_clips = 0;
3449 /* ==========================================================================
3451     Event loop
3453    ========================================================================== */
3456 static void
3457 ns_send_appdefined (int value)
3458 /* --------------------------------------------------------------------------
3459     Internal: post an appdefined event which EmacsApp-sendEvent will
3460               recognize and take as a command to halt the event loop.
3461    -------------------------------------------------------------------------- */
3463   /*NSTRACE (ns_send_appdefined); */
3465 #ifdef NS_IMPL_GNUSTEP
3466   // GNUstep needs postEvent to happen on the main thread.
3467   if (! [[NSThread currentThread] isMainThread])
3468     {
3469       EmacsApp *app = (EmacsApp *)NSApp;
3470       app->nextappdefined = value;
3471       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3472                             withObject:nil
3473                          waitUntilDone:YES];
3474       return;
3475     }
3476 #endif
3478   /* Only post this event if we haven't already posted one.  This will end
3479        the [NXApp run] main loop after having processed all events queued at
3480        this moment.  */
3482 #ifdef NS_IMPL_COCOA
3483   if (! send_appdefined)
3484     {
3485       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3486          in certain situations (rapid incoming events).
3487          So check if we have one, if not add one.  */
3488       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3489                                           untilDate:[NSDate distantPast]
3490                                              inMode:NSDefaultRunLoopMode
3491                                             dequeue:NO];
3492       if (! appev) send_appdefined = YES;
3493     }
3494 #endif
3496   if (send_appdefined)
3497     {
3498       NSEvent *nxev;
3500       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3501       send_appdefined = NO;
3503       /* Don't need wakeup timer any more */
3504       if (timed_entry)
3505         {
3506           [timed_entry invalidate];
3507           [timed_entry release];
3508           timed_entry = nil;
3509         }
3511       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3512                                 location: NSMakePoint (0, 0)
3513                            modifierFlags: 0
3514                                timestamp: 0
3515                             windowNumber: [[NSApp mainWindow] windowNumber]
3516                                  context: [NSApp context]
3517                                  subtype: 0
3518                                    data1: value
3519                                    data2: 0];
3521       /* Post an application defined event on the event queue.  When this is
3522          received the [NXApp run] will return, thus having processed all
3523          events which are currently queued.  */
3524       [NSApp postEvent: nxev atStart: NO];
3525     }
3528 #ifdef HAVE_NATIVE_FS
3529 static void
3530 check_native_fs ()
3532   Lisp_Object frame, tail;
3534   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3535     return;
3537   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3539   FOR_EACH_FRAME (tail, frame)
3540     {
3541       struct frame *f = XFRAME (frame);
3542       if (FRAME_NS_P (f))
3543         {
3544           EmacsView *view = FRAME_NS_VIEW (f);
3545           [view updateCollectionBehavior];
3546         }
3547     }
3549 #endif
3551 /* GNUstep does not have cancelTracking.  */
3552 #ifdef NS_IMPL_COCOA
3553 /* Check if menu open should be canceled or continued as normal.  */
3554 void
3555 ns_check_menu_open (NSMenu *menu)
3557   /* Click in menu bar? */
3558   NSArray *a = [[NSApp mainMenu] itemArray];
3559   int i;
3560   BOOL found = NO;
3562   if (menu == nil) // Menu tracking ended.
3563     {
3564       if (menu_will_open_state == MENU_OPENING)
3565         menu_will_open_state = MENU_NONE;
3566       return;
3567     }
3569   for (i = 0; ! found && i < [a count]; i++)
3570     found = menu == [[a objectAtIndex:i] submenu];
3571   if (found)
3572     {
3573       if (menu_will_open_state == MENU_NONE && emacs_event)
3574         {
3575           NSEvent *theEvent = [NSApp currentEvent];
3576           struct frame *emacsframe = SELECTED_FRAME ();
3578           [menu cancelTracking];
3579           menu_will_open_state = MENU_PENDING;
3580           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3581           EV_TRAILER (theEvent);
3583           CGEventRef ourEvent = CGEventCreate (NULL);
3584           menu_mouse_point = CGEventGetLocation (ourEvent);
3585           CFRelease (ourEvent);
3586         }
3587       else if (menu_will_open_state == MENU_OPENING)
3588         {
3589           menu_will_open_state = MENU_NONE;
3590         }
3591     }
3594 /* Redo saved menu click if state is MENU_PENDING.  */
3595 void
3596 ns_check_pending_open_menu ()
3598   if (menu_will_open_state == MENU_PENDING)
3599     {
3600       CGEventSourceRef source
3601         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3603       CGEventRef event = CGEventCreateMouseEvent (source,
3604                                                   kCGEventLeftMouseDown,
3605                                                   menu_mouse_point,
3606                                                   kCGMouseButtonLeft);
3607       CGEventSetType (event, kCGEventLeftMouseDown);
3608       CGEventPost (kCGHIDEventTap, event);
3609       CFRelease (event);
3610       CFRelease (source);
3612       menu_will_open_state = MENU_OPENING;
3613     }
3615 #endif /* NS_IMPL_COCOA */
3617 static void
3618 unwind_apploopnr (Lisp_Object not_used)
3620   --apploopnr;
3621   n_emacs_events_pending = 0;
3622   ns_finish_events ();
3623   q_event_ptr = NULL;
3626 static int
3627 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3628 /* --------------------------------------------------------------------------
3629      External (hook): Post an event to ourself and keep reading events until
3630      we read it back again.  In effect process all events which were waiting.
3631      From 21+ we have to manage the event buffer ourselves.
3632    -------------------------------------------------------------------------- */
3634   struct input_event ev;
3635   int nevents;
3637 /* NSTRACE (ns_read_socket); */
3639 #ifdef HAVE_NATIVE_FS
3640   check_native_fs ();
3641 #endif
3643   if ([NSApp modalWindow] != nil)
3644     return -1;
3646   if (hold_event_q.nr > 0)
3647     {
3648       int i;
3649       for (i = 0; i < hold_event_q.nr; ++i)
3650         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3651       hold_event_q.nr = 0;
3652       return i;
3653     }
3655   block_input ();
3656   n_emacs_events_pending = 0;
3657   ns_init_events (&ev);
3658   q_event_ptr = hold_quit;
3660   /* we manage autorelease pools by allocate/reallocate each time around
3661      the loop; strict nesting is occasionally violated but seems not to
3662      matter.. earlier methods using full nesting caused major memory leaks */
3663   [outerpool release];
3664   outerpool = [[NSAutoreleasePool alloc] init];
3666   /* If have pending open-file requests, attend to the next one of those. */
3667   if (ns_pending_files && [ns_pending_files count] != 0
3668       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3669     {
3670       [ns_pending_files removeObjectAtIndex: 0];
3671     }
3672   /* Deal with pending service requests. */
3673   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3674     && [(EmacsApp *)
3675          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3676                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3677     {
3678       [ns_pending_service_names removeObjectAtIndex: 0];
3679       [ns_pending_service_args removeObjectAtIndex: 0];
3680     }
3681   else
3682     {
3683       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3684       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3685          to ourself, otherwise [NXApp run] will never exit.  */
3686       send_appdefined = YES;
3687       ns_send_appdefined (-1);
3689       if (++apploopnr != 1)
3690         {
3691           emacs_abort ();
3692         }
3693       record_unwind_protect (unwind_apploopnr, Qt);
3694       [NSApp run];
3695       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3696     }
3698   nevents = n_emacs_events_pending;
3699   n_emacs_events_pending = 0;
3700   ns_finish_events ();
3701   q_event_ptr = NULL;
3702   unblock_input ();
3704   return nevents;
3709 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3710            fd_set *exceptfds, struct timespec const *timeout,
3711            sigset_t const *sigmask)
3712 /* --------------------------------------------------------------------------
3713      Replacement for select, checking for events
3714    -------------------------------------------------------------------------- */
3716   int result;
3717   int t, k, nr = 0;
3718   struct input_event event;
3719   char c;
3721 /*  NSTRACE (ns_select); */
3723 #ifdef HAVE_NATIVE_FS
3724   check_native_fs ();
3725 #endif
3727   if (hold_event_q.nr > 0)
3728     {
3729       /* We already have events pending. */
3730       raise (SIGIO);
3731       errno = EINTR;
3732       return -1;
3733     }
3735   for (k = 0; k < nfds+1; k++)
3736     {
3737       if (readfds && FD_ISSET(k, readfds)) ++nr;
3738       if (writefds && FD_ISSET(k, writefds)) ++nr;
3739     }
3741   if (NSApp == nil
3742       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3743     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3745   [outerpool release];
3746   outerpool = [[NSAutoreleasePool alloc] init];
3749   send_appdefined = YES;
3750   if (nr > 0)
3751     {
3752       pthread_mutex_lock (&select_mutex);
3753       select_nfds = nfds;
3754       select_valid = 0;
3755       if (readfds)
3756         {
3757           select_readfds = *readfds;
3758           select_valid += SELECT_HAVE_READ;
3759         }
3760       if (writefds)
3761         {
3762           select_writefds = *writefds;
3763           select_valid += SELECT_HAVE_WRITE;
3764         }
3766       if (timeout)
3767         {
3768           select_timeout = *timeout;
3769           select_valid += SELECT_HAVE_TMO;
3770         }
3772       pthread_mutex_unlock (&select_mutex);
3774       /* Inform fd_handler that select should be called */
3775       c = 'g';
3776       emacs_write_sig (selfds[1], &c, 1);
3777     }
3778   else if (nr == 0 && timeout)
3779     {
3780       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3781       double time = timespectod (*timeout);
3782       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3783                                                       target: NSApp
3784                                                     selector:
3785                                   @selector (timeout_handler:)
3786                                                     userInfo: 0
3787                                                      repeats: NO]
3788                       retain];
3789     }
3790   else /* No timeout and no file descriptors, can this happen?  */
3791     {
3792       /* Send appdefined so we exit from the loop */
3793       ns_send_appdefined (-1);
3794     }
3796   block_input ();
3797   ns_init_events (&event);
3798   if (++apploopnr != 1)
3799     {
3800       emacs_abort ();
3801     }
3803   {
3804     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3805     record_unwind_protect (unwind_apploopnr, Qt);
3806     [NSApp run];
3807     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3808   }
3810   ns_finish_events ();
3811   if (nr > 0 && readfds)
3812     {
3813       c = 's';
3814       emacs_write_sig (selfds[1], &c, 1);
3815     }
3816   unblock_input ();
3818   t = last_appdefined_event_data;
3820   if (t != NO_APPDEFINED_DATA)
3821     {
3822       last_appdefined_event_data = NO_APPDEFINED_DATA;
3824       if (t == -2)
3825         {
3826           /* The NX_APPDEFINED event we received was a timeout. */
3827           result = 0;
3828         }
3829       else if (t == -1)
3830         {
3831           /* The NX_APPDEFINED event we received was the result of
3832              at least one real input event arriving.  */
3833           errno = EINTR;
3834           result = -1;
3835         }
3836       else
3837         {
3838           /* Received back from select () in fd_handler; copy the results */
3839           pthread_mutex_lock (&select_mutex);
3840           if (readfds) *readfds = select_readfds;
3841           if (writefds) *writefds = select_writefds;
3842           pthread_mutex_unlock (&select_mutex);
3843           result = t;
3844         }
3845     }
3846   else
3847     {
3848       errno = EINTR;
3849       result = -1;
3850     }
3852   return result;
3857 /* ==========================================================================
3859     Scrollbar handling
3861    ========================================================================== */
3864 static void
3865 ns_set_vertical_scroll_bar (struct window *window,
3866                            int portion, int whole, int position)
3867 /* --------------------------------------------------------------------------
3868       External (hook): Update or add scrollbar
3869    -------------------------------------------------------------------------- */
3871   Lisp_Object win;
3872   NSRect r, v;
3873   struct frame *f = XFRAME (WINDOW_FRAME (window));
3874   EmacsView *view = FRAME_NS_VIEW (f);
3875   EmacsScroller *bar;
3876   int window_y, window_height;
3877   int top, left, height, width;
3878   BOOL update_p = YES;
3880   /* optimization; display engine sends WAY too many of these.. */
3881   if (!NILP (window->vertical_scroll_bar))
3882     {
3883       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3884       if ([bar checkSamePosition: position portion: portion whole: whole])
3885         {
3886           if (view->scrollbarsNeedingUpdate == 0)
3887             {
3888               if (!windows_or_buffers_changed)
3889                   return;
3890             }
3891           else
3892             view->scrollbarsNeedingUpdate--;
3893           update_p = NO;
3894         }
3895     }
3897   NSTRACE (ns_set_vertical_scroll_bar);
3899   /* Get dimensions.  */
3900   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3901   top = window_y;
3902   height = window_height;
3903   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3904   left = WINDOW_SCROLL_BAR_AREA_X (window);
3906   r = NSMakeRect (left, top, width, height);
3907   /* the parent view is flipped, so we need to flip y value */
3908   v = [view frame];
3909   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3911   XSETWINDOW (win, window);
3912   block_input ();
3914   /* we want at least 5 lines to display a scrollbar */
3915   if (WINDOW_TOTAL_LINES (window) < 5)
3916     {
3917       if (!NILP (window->vertical_scroll_bar))
3918         {
3919           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3920           [bar removeFromSuperview];
3921           wset_vertical_scroll_bar (window, Qnil);
3922           [bar release];
3923         }
3924       ns_clear_frame_area (f, left, top, width, height);
3925       unblock_input ();
3926       return;
3927     }
3929   if (NILP (window->vertical_scroll_bar))
3930     {
3931       if (width > 0 && height > 0)
3932         ns_clear_frame_area (f, left, top, width, height);
3934       bar = [[EmacsScroller alloc] initFrame: r window: win];
3935       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3936       update_p = YES;
3937     }
3938   else
3939     {
3940       NSRect oldRect;
3941       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3942       oldRect = [bar frame];
3943       r.size.width = oldRect.size.width;
3944       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3945         {
3946           if (oldRect.origin.x != r.origin.x)
3947               ns_clear_frame_area (f, left, top, width, height);
3948           [bar setFrame: r];
3949         }
3950     }
3952   if (update_p)
3953     [bar setPosition: position portion: portion whole: whole];
3954   unblock_input ();
3958 static void
3959 ns_set_horizontal_scroll_bar (struct window *window,
3960                               int portion, int whole, int position)
3961 /* --------------------------------------------------------------------------
3962       External (hook): Update or add scrollbar
3963    -------------------------------------------------------------------------- */
3965   Lisp_Object win;
3966   NSRect r, v;
3967   struct frame *f = XFRAME (WINDOW_FRAME (window));
3968   EmacsView *view = FRAME_NS_VIEW (f);
3969   EmacsScroller *bar;
3970   int top, height, left, width;
3971   int window_x, window_width;
3972   BOOL update_p = YES;
3974   /* optimization; display engine sends WAY too many of these.. */
3975   if (!NILP (window->horizontal_scroll_bar))
3976     {
3977       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3978       if ([bar checkSamePosition: position portion: portion whole: whole])
3979         {
3980           if (view->scrollbarsNeedingUpdate == 0)
3981             {
3982               if (!windows_or_buffers_changed)
3983                   return;
3984             }
3985           else
3986             view->scrollbarsNeedingUpdate--;
3987           update_p = NO;
3988         }
3989     }
3991   NSTRACE (ns_set_horizontal_scroll_bar);
3993   /* Get dimensions.  */
3994   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3995   left = window_x;
3996   width = window_width;
3997   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3998   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4000   r = NSMakeRect (left, top, width, height);
4001   /* the parent view is flipped, so we need to flip y value */
4002   v = [view frame];
4003   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4004   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4006   XSETWINDOW (win, window);
4007   block_input ();
4009   if (WINDOW_TOTAL_COLS (window) < 5)
4010     {
4011       if (!NILP (window->horizontal_scroll_bar))
4012         {
4013           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4014           [bar removeFromSuperview];
4015           wset_horizontal_scroll_bar (window, Qnil);
4016         }
4017       ns_clear_frame_area (f, left, top, width, height);
4018       unblock_input ();
4019       return;
4020     }
4022   if (NILP (window->horizontal_scroll_bar))
4023     {
4024       if (width > 0 && height > 0)
4025         ns_clear_frame_area (f, left, top, width, height);
4027       bar = [[EmacsScroller alloc] initFrame: r window: win];
4028       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4029       update_p = YES;
4030     }
4031   else
4032     {
4033       NSRect oldRect;
4034       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4035       oldRect = [bar frame];
4036       r.size.width = oldRect.size.width;
4037       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4038         {
4039           if (oldRect.origin.x != r.origin.x)
4040               ns_clear_frame_area (f, left, top, width, height);
4041           [bar setFrame: r];
4042           update_p = YES;
4043         }
4044     }
4046   if (update_p)
4047     [bar setPosition: position portion: portion whole: whole];
4048   unblock_input ();
4052 static void
4053 ns_condemn_scroll_bars (struct frame *f)
4054 /* --------------------------------------------------------------------------
4055      External (hook): arrange for all frame's scrollbars to be removed
4056      at next call to judge_scroll_bars, except for those redeemed.
4057    -------------------------------------------------------------------------- */
4059   int i;
4060   id view;
4061   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4063   NSTRACE (ns_condemn_scroll_bars);
4065   for (i =[subviews count]-1; i >= 0; i--)
4066     {
4067       view = [subviews objectAtIndex: i];
4068       if ([view isKindOfClass: [EmacsScroller class]])
4069         [view condemn];
4070     }
4074 static void
4075 ns_redeem_scroll_bar (struct window *window)
4076 /* --------------------------------------------------------------------------
4077      External (hook): arrange to spare this window's scrollbar
4078      at next call to judge_scroll_bars.
4079    -------------------------------------------------------------------------- */
4081   id bar;
4082   NSTRACE (ns_redeem_scroll_bar);
4083   if (!NILP (window->vertical_scroll_bar))
4084     {
4085       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4086       [bar reprieve];
4087     }
4089   if (!NILP (window->horizontal_scroll_bar))
4090     {
4091       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4092       [bar reprieve];
4093     }
4097 static void
4098 ns_judge_scroll_bars (struct frame *f)
4099 /* --------------------------------------------------------------------------
4100      External (hook): destroy all scrollbars on frame that weren't
4101      redeemed after call to condemn_scroll_bars.
4102    -------------------------------------------------------------------------- */
4104   int i;
4105   id view;
4106   EmacsView *eview = FRAME_NS_VIEW (f);
4107   NSArray *subviews = [[eview superview] subviews];
4108   BOOL removed = NO;
4110   NSTRACE (ns_judge_scroll_bars);
4111   for (i = [subviews count]-1; i >= 0; --i)
4112     {
4113       view = [subviews objectAtIndex: i];
4114       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4115       if ([view judge])
4116         removed = YES;
4117     }
4119   if (removed)
4120     [eview updateFrameSize: NO];
4123 /* ==========================================================================
4125     Initialization
4127    ========================================================================== */
4130 x_display_pixel_height (struct ns_display_info *dpyinfo)
4132   NSArray *screens = [NSScreen screens];
4133   NSEnumerator *enumerator = [screens objectEnumerator];
4134   NSScreen *screen;
4135   NSRect frame;
4137   frame = NSZeroRect;
4138   while ((screen = [enumerator nextObject]) != nil)
4139     frame = NSUnionRect (frame, [screen frame]);
4141   return NSHeight (frame);
4145 x_display_pixel_width (struct ns_display_info *dpyinfo)
4147   NSArray *screens = [NSScreen screens];
4148   NSEnumerator *enumerator = [screens objectEnumerator];
4149   NSScreen *screen;
4150   NSRect frame;
4152   frame = NSZeroRect;
4153   while ((screen = [enumerator nextObject]) != nil)
4154     frame = NSUnionRect (frame, [screen frame]);
4156   return NSWidth (frame);
4160 static Lisp_Object ns_string_to_lispmod (const char *s)
4161 /* --------------------------------------------------------------------------
4162      Convert modifier name to lisp symbol
4163    -------------------------------------------------------------------------- */
4165   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4166     return Qmeta;
4167   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4168     return Qsuper;
4169   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4170     return Qcontrol;
4171   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4172     return Qalt;
4173   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4174     return Qhyper;
4175   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4176     return Qnone;
4177   else
4178     return Qnil;
4182 static void
4183 ns_default (const char *parameter, Lisp_Object *result,
4184            Lisp_Object yesval, Lisp_Object noval,
4185            BOOL is_float, BOOL is_modstring)
4186 /* --------------------------------------------------------------------------
4187       Check a parameter value in user's preferences
4188    -------------------------------------------------------------------------- */
4190   const char *value = ns_get_defaults_value (parameter);
4192   if (value)
4193     {
4194       double f;
4195       char *pos;
4196       if (c_strcasecmp (value, "YES") == 0)
4197         *result = yesval;
4198       else if (c_strcasecmp (value, "NO") == 0)
4199         *result = noval;
4200       else if (is_float && (f = strtod (value, &pos), pos != value))
4201         *result = make_float (f);
4202       else if (is_modstring && value)
4203         *result = ns_string_to_lispmod (value);
4204       else fprintf (stderr,
4205                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4206     }
4210 static void
4211 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4212 /* --------------------------------------------------------------------------
4213       Initialize global info and storage for display.
4214    -------------------------------------------------------------------------- */
4216     NSScreen *screen = [NSScreen mainScreen];
4217     NSWindowDepth depth = [screen depth];
4219     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4220     dpyinfo->resy = 72.27;
4221     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4222                                                   NSColorSpaceFromDepth (depth)]
4223                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4224                                                  NSColorSpaceFromDepth (depth)];
4225     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4226     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4227     dpyinfo->color_table->colors = NULL;
4228     dpyinfo->root_window = 42; /* a placeholder.. */
4229     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4230     dpyinfo->n_fonts = 0;
4231     dpyinfo->smallest_font_height = 1;
4232     dpyinfo->smallest_char_width = 1;
4234     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4238 /* This and next define (many of the) public functions in this file. */
4239 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4240          with using despite presence in the "system dependent" redisplay
4241          interface.  In addition, many of the ns_ methods have code that is
4242          shared with all terms, indicating need for further refactoring. */
4243 extern frame_parm_handler ns_frame_parm_handlers[];
4244 static struct redisplay_interface ns_redisplay_interface =
4246   ns_frame_parm_handlers,
4247   x_produce_glyphs,
4248   x_write_glyphs,
4249   x_insert_glyphs,
4250   x_clear_end_of_line,
4251   ns_scroll_run,
4252   ns_after_update_window_line,
4253   ns_update_window_begin,
4254   ns_update_window_end,
4255   0, /* flush_display */
4256   x_clear_window_mouse_face,
4257   x_get_glyph_overhangs,
4258   x_fix_overlapping_area,
4259   ns_draw_fringe_bitmap,
4260   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4261   0, /* destroy_fringe_bitmap */
4262   ns_compute_glyph_string_overhangs,
4263   ns_draw_glyph_string,
4264   ns_define_frame_cursor,
4265   ns_clear_frame_area,
4266   ns_draw_window_cursor,
4267   ns_draw_vertical_window_border,
4268   ns_draw_window_divider,
4269   ns_shift_glyphs_for_insert,
4270   ns_show_hourglass,
4271   ns_hide_hourglass
4275 static void
4276 ns_delete_display (struct ns_display_info *dpyinfo)
4278   /* TODO... */
4282 /* This function is called when the last frame on a display is deleted. */
4283 static void
4284 ns_delete_terminal (struct terminal *terminal)
4286   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4288   /* Protect against recursive calls.  delete_frame in
4289      delete_terminal calls us back when it deletes our last frame.  */
4290   if (!terminal->name)
4291     return;
4293   block_input ();
4295   x_destroy_all_bitmaps (dpyinfo);
4296   ns_delete_display (dpyinfo);
4297   unblock_input ();
4301 static struct terminal *
4302 ns_create_terminal (struct ns_display_info *dpyinfo)
4303 /* --------------------------------------------------------------------------
4304       Set up use of NS before we make the first connection.
4305    -------------------------------------------------------------------------- */
4307   struct terminal *terminal;
4309   NSTRACE (ns_create_terminal);
4311   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4313   terminal->display_info.ns = dpyinfo;
4314   dpyinfo->terminal = terminal;
4316   terminal->clear_frame_hook = ns_clear_frame;
4317   terminal->ring_bell_hook = ns_ring_bell;
4318   terminal->update_begin_hook = ns_update_begin;
4319   terminal->update_end_hook = ns_update_end;
4320   terminal->read_socket_hook = ns_read_socket;
4321   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4322   terminal->mouse_position_hook = ns_mouse_position;
4323   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4324   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4325   terminal->fullscreen_hook = ns_fullscreen_hook;
4326   terminal->menu_show_hook = ns_menu_show;
4327   terminal->popup_dialog_hook = ns_popup_dialog;
4328   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4329   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4330   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4331   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4332   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4333   terminal->delete_frame_hook = x_destroy_window;
4334   terminal->delete_terminal_hook = ns_delete_terminal;
4335   /* Other hooks are NULL by default.  */
4337   return terminal;
4341 struct ns_display_info *
4342 ns_term_init (Lisp_Object display_name)
4343 /* --------------------------------------------------------------------------
4344      Start the Application and get things rolling.
4345    -------------------------------------------------------------------------- */
4347   struct terminal *terminal;
4348   struct ns_display_info *dpyinfo;
4349   static int ns_initialized = 0;
4350   Lisp_Object tmp;
4352   if (ns_initialized) return x_display_list;
4353   ns_initialized = 1;
4355   NSTRACE (ns_term_init);
4357   [outerpool release];
4358   outerpool = [[NSAutoreleasePool alloc] init];
4360   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4361   /*GSDebugAllocationActive (YES); */
4362   block_input ();
4364   baud_rate = 38400;
4365   Fset_input_interrupt_mode (Qnil);
4367   if (selfds[0] == -1)
4368     {
4369       if (emacs_pipe (selfds) != 0)
4370         {
4371           fprintf (stderr, "Failed to create pipe: %s\n",
4372                    emacs_strerror (errno));
4373           emacs_abort ();
4374         }
4376       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4377       FD_ZERO (&select_readfds);
4378       FD_ZERO (&select_writefds);
4379       pthread_mutex_init (&select_mutex, NULL);
4380     }
4382   ns_pending_files = [[NSMutableArray alloc] init];
4383   ns_pending_service_names = [[NSMutableArray alloc] init];
4384   ns_pending_service_args = [[NSMutableArray alloc] init];
4386 /* Start app and create the main menu, window, view.
4387      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4388      The view will then ask the NSApp to stop and return to Emacs. */
4389   [EmacsApp sharedApplication];
4390   if (NSApp == nil)
4391     return NULL;
4392   [NSApp setDelegate: NSApp];
4394   /* Start the select thread.  */
4395   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4396                            toTarget:NSApp
4397                          withObject:nil];
4399   /* debugging: log all notifications */
4400   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4401                                          selector: @selector (logNotification:)
4402                                              name: nil object: nil]; */
4404   dpyinfo = xzalloc (sizeof *dpyinfo);
4406   ns_initialize_display_info (dpyinfo);
4407   terminal = ns_create_terminal (dpyinfo);
4409   terminal->kboard = allocate_kboard (Qns);
4410   /* Don't let the initial kboard remain current longer than necessary.
4411      That would cause problems if a file loaded on startup tries to
4412      prompt in the mini-buffer.  */
4413   if (current_kboard == initial_kboard)
4414     current_kboard = terminal->kboard;
4415   terminal->kboard->reference_count++;
4417   dpyinfo->next = x_display_list;
4418   x_display_list = dpyinfo;
4420   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4422   terminal->name = xlispstrdup (display_name);
4424   unblock_input ();
4426   if (!inhibit_x_resources)
4427     {
4428       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4429                  Qt, Qnil, NO, NO);
4430       tmp = Qnil;
4431       /* this is a standard variable */
4432       ns_default ("AppleAntiAliasingThreshold", &tmp,
4433                  make_float (10.0), make_float (6.0), YES, NO);
4434       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4435     }
4437   {
4438     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4440     if ( cl == nil )
4441       {
4442         Lisp_Object color_file, color_map, color;
4443         unsigned long c;
4444         char *name;
4446         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4447                          Fsymbol_value (intern ("data-directory")));
4449         color_map = Fx_load_color_file (color_file);
4450         if (NILP (color_map))
4451           fatal ("Could not read %s.\n", SDATA (color_file));
4453         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4454         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4455           {
4456             color = XCAR (color_map);
4457             name = SSDATA (XCAR (color));
4458             c = XINT (XCDR (color));
4459             [cl setColor:
4460                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4461                                       green: GREEN_FROM_ULONG (c) / 255.0
4462                                        blue: BLUE_FROM_ULONG (c) / 255.0
4463                                       alpha: 1.0]
4464                   forKey: [NSString stringWithUTF8String: name]];
4465           }
4466         [cl writeToFile: nil];
4467       }
4468   }
4470   {
4471 #ifdef NS_IMPL_GNUSTEP
4472     Vwindow_system_version = build_string (gnustep_base_version);
4473 #else
4474     /*PSnextrelease (128, c); */
4475     char c[DBL_BUFSIZE_BOUND];
4476     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4477     Vwindow_system_version = make_unibyte_string (c, len);
4478 #endif
4479   }
4481   delete_keyboard_wait_descriptor (0);
4483   ns_app_name = [[NSProcessInfo processInfo] processName];
4485 /* Set up OS X app menu */
4486 #ifdef NS_IMPL_COCOA
4487   {
4488     NSMenu *appMenu;
4489     NSMenuItem *item;
4490     /* set up the application menu */
4491     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4492     [svcsMenu setAutoenablesItems: NO];
4493     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4494     [appMenu setAutoenablesItems: NO];
4495     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4496     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4498     [appMenu insertItemWithTitle: @"About Emacs"
4499                           action: @selector (orderFrontStandardAboutPanel:)
4500                    keyEquivalent: @""
4501                          atIndex: 0];
4502     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4503     [appMenu insertItemWithTitle: @"Preferences..."
4504                           action: @selector (showPreferencesWindow:)
4505                    keyEquivalent: @","
4506                          atIndex: 2];
4507     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4508     item = [appMenu insertItemWithTitle: @"Services"
4509                                  action: @selector (menuDown:)
4510                           keyEquivalent: @""
4511                                 atIndex: 4];
4512     [appMenu setSubmenu: svcsMenu forItem: item];
4513     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4514     [appMenu insertItemWithTitle: @"Hide Emacs"
4515                           action: @selector (hide:)
4516                    keyEquivalent: @"h"
4517                          atIndex: 6];
4518     item =  [appMenu insertItemWithTitle: @"Hide Others"
4519                           action: @selector (hideOtherApplications:)
4520                    keyEquivalent: @"h"
4521                          atIndex: 7];
4522     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4523     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4524     [appMenu insertItemWithTitle: @"Quit Emacs"
4525                           action: @selector (terminate:)
4526                    keyEquivalent: @"q"
4527                          atIndex: 9];
4529     item = [mainMenu insertItemWithTitle: ns_app_name
4530                                   action: @selector (menuDown:)
4531                            keyEquivalent: @""
4532                                  atIndex: 0];
4533     [mainMenu setSubmenu: appMenu forItem: item];
4534     [dockMenu insertItemWithTitle: @"New Frame"
4535                            action: @selector (newFrame:)
4536                     keyEquivalent: @""
4537                           atIndex: 0];
4539     [NSApp setMainMenu: mainMenu];
4540     [NSApp setAppleMenu: appMenu];
4541     [NSApp setServicesMenu: svcsMenu];
4542     /* Needed at least on Cocoa, to get dock menu to show windows */
4543     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4545     [[NSNotificationCenter defaultCenter]
4546       addObserver: mainMenu
4547          selector: @selector (trackingNotification:)
4548              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4549     [[NSNotificationCenter defaultCenter]
4550       addObserver: mainMenu
4551          selector: @selector (trackingNotification:)
4552              name: NSMenuDidEndTrackingNotification object: mainMenu];
4553   }
4554 #endif /* MAC OS X menu setup */
4556   /* Register our external input/output types, used for determining
4557      applicable services and also drag/drop eligibility. */
4558   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4559   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4560                       retain];
4561   ns_drag_types = [[NSArray arrayWithObjects:
4562                             NSStringPboardType,
4563                             NSTabularTextPboardType,
4564                             NSFilenamesPboardType,
4565                             NSURLPboardType, nil] retain];
4567   /* If fullscreen is in init/default-frame-alist, focus isn't set
4568      right for fullscreen windows, so set this.  */
4569   [NSApp activateIgnoringOtherApps:YES];
4571   [NSApp run];
4572   ns_do_open_file = YES;
4574 #ifdef NS_IMPL_GNUSTEP
4575   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4576      We must re-catch it so subprocess works.  */
4577   catch_child_signal ();
4578 #endif
4579   return dpyinfo;
4583 void
4584 ns_term_shutdown (int sig)
4586   [[NSUserDefaults standardUserDefaults] synchronize];
4588   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4589   if (STRINGP (Vauto_save_list_file_name))
4590     unlink (SSDATA (Vauto_save_list_file_name));
4592   if (sig == 0 || sig == SIGTERM)
4593     {
4594       [NSApp terminate: NSApp];
4595     }
4596   else // force a stack trace to happen
4597     {
4598       emacs_abort ();
4599     }
4603 /* ==========================================================================
4605     EmacsApp implementation
4607    ========================================================================== */
4610 @implementation EmacsApp
4612 - (id)init
4614   if ((self = [super init]))
4615     {
4616 #ifdef NS_IMPL_COCOA
4617       self->isFirst = YES;
4618 #endif
4619 #ifdef NS_IMPL_GNUSTEP
4620       self->applicationDidFinishLaunchingCalled = NO;
4621 #endif
4622     }
4624   return self;
4627 #ifdef NS_IMPL_COCOA
4628 - (void)run
4630 #ifndef NSAppKitVersionNumber10_9
4631 #define NSAppKitVersionNumber10_9 1265
4632 #endif
4634     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4635       {
4636         [super run];
4637         return;
4638       }
4640   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4642   if (isFirst) [self finishLaunching];
4643   isFirst = NO;
4645   shouldKeepRunning = YES;
4646   do
4647     {
4648       [pool release];
4649       pool = [[NSAutoreleasePool alloc] init];
4651       NSEvent *event =
4652         [self nextEventMatchingMask:NSAnyEventMask
4653                           untilDate:[NSDate distantFuture]
4654                              inMode:NSDefaultRunLoopMode
4655                             dequeue:YES];
4657       [self sendEvent:event];
4658       [self updateWindows];
4659     } while (shouldKeepRunning);
4661   [pool release];
4664 - (void)stop: (id)sender
4666     shouldKeepRunning = NO;
4667     // Stop possible dialog also.  Noop if no dialog present.
4668     // The file dialog still leaks 7k - 10k on 10.9 though.
4669     [super stop:sender];
4671 #endif /* NS_IMPL_COCOA */
4673 - (void)logNotification: (NSNotification *)notification
4675   const char *name = [[notification name] UTF8String];
4676   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4677       && !strstr (name, "WindowNumber"))
4678     NSLog (@"notification: '%@'", [notification name]);
4682 - (void)sendEvent: (NSEvent *)theEvent
4683 /* --------------------------------------------------------------------------
4684      Called when NSApp is running for each event received.  Used to stop
4685      the loop when we choose, since there's no way to just run one iteration.
4686    -------------------------------------------------------------------------- */
4688   int type = [theEvent type];
4689   NSWindow *window = [theEvent window];
4691 /*  NSTRACE (sendEvent); */
4692 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4694 #ifdef NS_IMPL_GNUSTEP
4695   // Keyboard events aren't propagated to file dialogs for some reason.
4696   if ([NSApp modalWindow] != nil &&
4697       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4698     {
4699       [[NSApp modalWindow] sendEvent: theEvent];
4700       return;
4701     }
4702 #endif
4704   if (represented_filename != nil && represented_frame)
4705     {
4706       NSString *fstr = represented_filename;
4707       NSView *view = FRAME_NS_VIEW (represented_frame);
4708 #ifdef NS_IMPL_COCOA
4709       /* work around a bug observed on 10.3 and later where
4710          setTitleWithRepresentedFilename does not clear out previous state
4711          if given filename does not exist */
4712       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4713         [[view window] setRepresentedFilename: @""];
4714 #endif
4715       [[view window] setRepresentedFilename: fstr];
4716       [represented_filename release];
4717       represented_filename = nil;
4718       represented_frame = NULL;
4719     }
4721   if (type == NSApplicationDefined)
4722     {
4723       switch ([theEvent data2])
4724         {
4725 #ifdef NS_IMPL_COCOA
4726         case NSAPP_DATA2_RUNASSCRIPT:
4727           ns_run_ascript ();
4728           [self stop: self];
4729           return;
4730 #endif
4731         case NSAPP_DATA2_RUNFILEDIALOG:
4732           ns_run_file_dialog ();
4733           [self stop: self];
4734           return;
4735         }
4736     }
4738   if (type == NSCursorUpdate && window == nil)
4739     {
4740       fprintf (stderr, "Dropping external cursor update event.\n");
4741       return;
4742     }
4744   if (type == NSApplicationDefined)
4745     {
4746       /* Events posted by ns_send_appdefined interrupt the run loop here.
4747          But, if a modal window is up, an appdefined can still come through,
4748          (e.g., from a makeKeyWindow event) but stopping self also stops the
4749          modal loop. Just defer it until later. */
4750       if ([NSApp modalWindow] == nil)
4751         {
4752           last_appdefined_event_data = [theEvent data1];
4753           [self stop: self];
4754         }
4755       else
4756         {
4757           send_appdefined = YES;
4758         }
4759     }
4762 #ifdef NS_IMPL_COCOA
4763   /* If no dialog and none of our frames have focus and it is a move, skip it.
4764      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4765      such as Wifi, sound, date or similar.
4766      This prevents "spooky" highlighting in the frame under the menu.  */
4767   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4768     {
4769       struct ns_display_info *di;
4770       BOOL has_focus = NO;
4771       for (di = x_display_list; ! has_focus && di; di = di->next)
4772         has_focus = di->x_focus_frame != 0;
4773       if (! has_focus)
4774         return;
4775     }
4776 #endif
4778   [super sendEvent: theEvent];
4782 - (void)showPreferencesWindow: (id)sender
4784   struct frame *emacsframe = SELECTED_FRAME ();
4785   NSEvent *theEvent = [NSApp currentEvent];
4787   if (!emacs_event)
4788     return;
4789   emacs_event->kind = NS_NONKEY_EVENT;
4790   emacs_event->code = KEY_NS_SHOW_PREFS;
4791   emacs_event->modifiers = 0;
4792   EV_TRAILER (theEvent);
4796 - (void)newFrame: (id)sender
4798   struct frame *emacsframe = SELECTED_FRAME ();
4799   NSEvent *theEvent = [NSApp currentEvent];
4801   if (!emacs_event)
4802     return;
4803   emacs_event->kind = NS_NONKEY_EVENT;
4804   emacs_event->code = KEY_NS_NEW_FRAME;
4805   emacs_event->modifiers = 0;
4806   EV_TRAILER (theEvent);
4810 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4811 - (BOOL) openFile: (NSString *)fileName
4813   struct frame *emacsframe = SELECTED_FRAME ();
4814   NSEvent *theEvent = [NSApp currentEvent];
4816   if (!emacs_event)
4817     return NO;
4819   emacs_event->kind = NS_NONKEY_EVENT;
4820   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4821   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4822   ns_input_line = Qnil; /* can be start or cons start,end */
4823   emacs_event->modifiers =0;
4824   EV_TRAILER (theEvent);
4826   return YES;
4830 /* **************************************************************************
4832       EmacsApp delegate implementation
4834    ************************************************************************** */
4836 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4837 /* --------------------------------------------------------------------------
4838      When application is loaded, terminate event loop in ns_term_init
4839    -------------------------------------------------------------------------- */
4841   NSTRACE (applicationDidFinishLaunching);
4842 #ifdef NS_IMPL_GNUSTEP
4843   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4844 #endif
4845   [NSApp setServicesProvider: NSApp];
4847   [self antialiasThresholdDidChange:nil];
4848 #ifdef NS_IMPL_COCOA
4849   [[NSNotificationCenter defaultCenter]
4850     addObserver:self
4851        selector:@selector(antialiasThresholdDidChange:)
4852            name:NSAntialiasThresholdChangedNotification
4853          object:nil];
4854 #endif
4856   ns_send_appdefined (-2);
4859 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4861 #ifdef NS_IMPL_COCOA
4862   macfont_update_antialias_threshold ();
4863 #endif
4867 /* Termination sequences:
4868     C-x C-c:
4869     Cmd-Q:
4870     MenuBar | File | Exit:
4871     Select Quit from App menubar:
4872         -terminate
4873         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4874         ns_term_shutdown()
4876     Select Quit from Dock menu:
4877     Logout attempt:
4878         -appShouldTerminate
4879           Cancel -> Nothing else
4880           Accept ->
4882           -terminate
4883           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4884           ns_term_shutdown()
4888 - (void) terminate: (id)sender
4890   struct frame *emacsframe = SELECTED_FRAME ();
4892   if (!emacs_event)
4893     return;
4895   emacs_event->kind = NS_NONKEY_EVENT;
4896   emacs_event->code = KEY_NS_POWER_OFF;
4897   emacs_event->arg = Qt; /* mark as non-key event */
4898   EV_TRAILER ((id)nil);
4901 static bool
4902 runAlertPanel(NSString *title,
4903               NSString *msgFormat,
4904               NSString *defaultButton,
4905               NSString *alternateButton)
4907 #if !defined (NS_IMPL_COCOA) || \
4908   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
4909   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
4910     == NSAlertDefaultReturn;
4911 #else
4912   NSAlert *alert = [[NSAlert alloc] init];
4913   [alert setAlertStyle: NSCriticalAlertStyle];
4914   [alert setMessageText: msgFormat];
4915   [alert addButtonWithTitle: defaultButton];
4916   [alert addButtonWithTitle: alternateButton];
4917   NSInteger ret = [alert runModal];
4918   [alert release];
4919   return ret == NSAlertFirstButtonReturn;
4920 #endif
4924 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4926   bool ret;
4928   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4929     return NSTerminateNow;
4931     ret = runAlertPanel(ns_app_name,
4932                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4933                         @"Save Buffers and Exit", @"Cancel");
4935     if (ret)
4936         return NSTerminateNow;
4937     else
4938         return NSTerminateCancel;
4939     return NSTerminateNow;  /* just in case */
4942 static int
4943 not_in_argv (NSString *arg)
4945   int k;
4946   const char *a = [arg UTF8String];
4947   for (k = 1; k < initial_argc; ++k)
4948     if (strcmp (a, initial_argv[k]) == 0) return 0;
4949   return 1;
4952 /*   Notification from the Workspace to open a file */
4953 - (BOOL)application: sender openFile: (NSString *)file
4955   if (ns_do_open_file || not_in_argv (file))
4956     [ns_pending_files addObject: file];
4957   return YES;
4961 /*   Open a file as a temporary file */
4962 - (BOOL)application: sender openTempFile: (NSString *)file
4964   if (ns_do_open_file || not_in_argv (file))
4965     [ns_pending_files addObject: file];
4966   return YES;
4970 /*   Notification from the Workspace to open a file noninteractively (?) */
4971 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4973   if (ns_do_open_file || not_in_argv (file))
4974     [ns_pending_files addObject: file];
4975   return YES;
4978 /*   Notification from the Workspace to open multiple files */
4979 - (void)application: sender openFiles: (NSArray *)fileList
4981   NSEnumerator *files = [fileList objectEnumerator];
4982   NSString *file;
4983   /* Don't open files from the command line unconditionally,
4984      Cocoa parses the command line wrong, --option value tries to open value
4985      if --option is the last option.  */
4986   while ((file = [files nextObject]) != nil)
4987     if (ns_do_open_file || not_in_argv (file))
4988       [ns_pending_files addObject: file];
4990   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4995 /* Handle dock menu requests.  */
4996 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4998   return dockMenu;
5002 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5003 - (void)applicationWillBecomeActive: (NSNotification *)notification
5005   //ns_app_active=YES;
5007 - (void)applicationDidBecomeActive: (NSNotification *)notification
5009   NSTRACE (applicationDidBecomeActive);
5011 #ifdef NS_IMPL_GNUSTEP
5012   if (! applicationDidFinishLaunchingCalled)
5013     [self applicationDidFinishLaunching:notification];
5014 #endif
5015   //ns_app_active=YES;
5017   ns_update_auto_hide_menu_bar ();
5018   // No constraining takes place when the application is not active.
5019   ns_constrain_all_frames ();
5021 - (void)applicationDidResignActive: (NSNotification *)notification
5023   //ns_app_active=NO;
5024   ns_send_appdefined (-1);
5029 /* ==========================================================================
5031     EmacsApp aux handlers for managing event loop
5033    ========================================================================== */
5036 - (void)timeout_handler: (NSTimer *)timedEntry
5037 /* --------------------------------------------------------------------------
5038      The timeout specified to ns_select has passed.
5039    -------------------------------------------------------------------------- */
5041   /*NSTRACE (timeout_handler); */
5042   ns_send_appdefined (-2);
5045 #ifdef NS_IMPL_GNUSTEP
5046 - (void)sendFromMainThread:(id)unused
5048   ns_send_appdefined (nextappdefined);
5050 #endif
5052 - (void)fd_handler:(id)unused
5053 /* --------------------------------------------------------------------------
5054      Check data waiting on file descriptors and terminate if so
5055    -------------------------------------------------------------------------- */
5057   int result;
5058   int waiting = 1, nfds;
5059   char c;
5061   fd_set readfds, writefds, *wfds;
5062   struct timespec timeout, *tmo;
5063   NSAutoreleasePool *pool = nil;
5065   /* NSTRACE (fd_handler); */
5067   for (;;)
5068     {
5069       [pool release];
5070       pool = [[NSAutoreleasePool alloc] init];
5072       if (waiting)
5073         {
5074           fd_set fds;
5075           FD_ZERO (&fds);
5076           FD_SET (selfds[0], &fds);
5077           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5078           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5079             waiting = 0;
5080         }
5081       else
5082         {
5083           pthread_mutex_lock (&select_mutex);
5084           nfds = select_nfds;
5086           if (select_valid & SELECT_HAVE_READ)
5087             readfds = select_readfds;
5088           else
5089             FD_ZERO (&readfds);
5091           if (select_valid & SELECT_HAVE_WRITE)
5092             {
5093               writefds = select_writefds;
5094               wfds = &writefds;
5095             }
5096           else
5097             wfds = NULL;
5098           if (select_valid & SELECT_HAVE_TMO)
5099             {
5100               timeout = select_timeout;
5101               tmo = &timeout;
5102             }
5103           else
5104             tmo = NULL;
5106           pthread_mutex_unlock (&select_mutex);
5108           FD_SET (selfds[0], &readfds);
5109           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5111           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5113           if (result == 0)
5114             ns_send_appdefined (-2);
5115           else if (result > 0)
5116             {
5117               if (FD_ISSET (selfds[0], &readfds))
5118                 {
5119                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5120                     waiting = 1;
5121                 }
5122               else
5123                 {
5124                   pthread_mutex_lock (&select_mutex);
5125                   if (select_valid & SELECT_HAVE_READ)
5126                     select_readfds = readfds;
5127                   if (select_valid & SELECT_HAVE_WRITE)
5128                     select_writefds = writefds;
5129                   if (select_valid & SELECT_HAVE_TMO)
5130                     select_timeout = timeout;
5131                   pthread_mutex_unlock (&select_mutex);
5133                   ns_send_appdefined (result);
5134                 }
5135             }
5136           waiting = 1;
5137         }
5138     }
5143 /* ==========================================================================
5145     Service provision
5147    ========================================================================== */
5149 /* called from system: queue for next pass through event loop */
5150 - (void)requestService: (NSPasteboard *)pboard
5151               userData: (NSString *)userData
5152                  error: (NSString **)error
5154   [ns_pending_service_names addObject: userData];
5155   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5156       SSDATA (ns_string_from_pasteboard (pboard))]];
5160 /* called from ns_read_socket to clear queue */
5161 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5163   struct frame *emacsframe = SELECTED_FRAME ();
5164   NSEvent *theEvent = [NSApp currentEvent];
5166   if (!emacs_event)
5167     return NO;
5169   emacs_event->kind = NS_NONKEY_EVENT;
5170   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5171   ns_input_spi_name = build_string ([name UTF8String]);
5172   ns_input_spi_arg = build_string ([arg UTF8String]);
5173   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5174   EV_TRAILER (theEvent);
5176   return YES;
5180 @end  /* EmacsApp */
5184 /* ==========================================================================
5186     EmacsView implementation
5188    ========================================================================== */
5191 @implementation EmacsView
5193 /* needed to inform when window closed from LISP */
5194 - (void) setWindowClosing: (BOOL)closing
5196   windowClosing = closing;
5200 - (void)dealloc
5202   NSTRACE (EmacsView_dealloc);
5203   [toolbar release];
5204   if (fs_state == FULLSCREEN_BOTH)
5205     [nonfs_window release];
5206   [super dealloc];
5210 /* called on font panel selection */
5211 - (void)changeFont: (id)sender
5213   NSEvent *e = [[self window] currentEvent];
5214   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5215   struct font *font = face->font;
5216   id newFont;
5217   CGFloat size;
5218   NSFont *nsfont;
5220   NSTRACE (changeFont);
5222   if (!emacs_event)
5223     return;
5225 #ifdef NS_IMPL_GNUSTEP
5226   nsfont = ((struct nsfont_info *)font)->nsfont;
5227 #endif
5228 #ifdef NS_IMPL_COCOA
5229   nsfont = (NSFont *) macfont_get_nsctfont (font);
5230 #endif
5232   if ((newFont = [sender convertFont: nsfont]))
5233     {
5234       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5236       emacs_event->kind = NS_NONKEY_EVENT;
5237       emacs_event->modifiers = 0;
5238       emacs_event->code = KEY_NS_CHANGE_FONT;
5240       size = [newFont pointSize];
5241       ns_input_fontsize = make_number (lrint (size));
5242       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5243       EV_TRAILER (e);
5244     }
5248 - (BOOL)acceptsFirstResponder
5250   NSTRACE (acceptsFirstResponder);
5251   return YES;
5255 - (void)resetCursorRects
5257   NSRect visible = [self visibleRect];
5258   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5259   NSTRACE (resetCursorRects);
5261   if (currentCursor == nil)
5262     currentCursor = [NSCursor arrowCursor];
5264   if (!NSIsEmptyRect (visible))
5265     [self addCursorRect: visible cursor: currentCursor];
5266   [currentCursor setOnMouseEntered: YES];
5271 /*****************************************************************************/
5272 /* Keyboard handling. */
5273 #define NS_KEYLOG 0
5275 - (void)keyDown: (NSEvent *)theEvent
5277   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5278   int code;
5279   unsigned fnKeysym = 0;
5280   static NSMutableArray *nsEvArray;
5281   int left_is_none;
5282   unsigned int flags = [theEvent modifierFlags];
5284   NSTRACE (keyDown);
5286   /* Rhapsody and OS X give up and down events for the arrow keys */
5287   if (ns_fake_keydown == YES)
5288     ns_fake_keydown = NO;
5289   else if ([theEvent type] != NSKeyDown)
5290     return;
5292   if (!emacs_event)
5293     return;
5295  if (![[self window] isKeyWindow]
5296      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5297      /* we must avoid an infinite loop here. */
5298      && (EmacsView *)[[theEvent window] delegate] != self)
5299    {
5300      /* XXX: There is an occasional condition in which, when Emacs display
5301          updates a different frame from the current one, and temporarily
5302          selects it, then processes some interrupt-driven input
5303          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5304          for some reason that window has its first responder set to the NSView
5305          most recently updated (I guess), which is not the correct one. */
5306      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5307      return;
5308    }
5310   if (nsEvArray == nil)
5311     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5313   [NSCursor setHiddenUntilMouseMoves: YES];
5315   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5316     {
5317       clear_mouse_face (hlinfo);
5318       hlinfo->mouse_face_hidden = 1;
5319     }
5321   if (!processingCompose)
5322     {
5323       /* When using screen sharing, no left or right information is sent,
5324          so use Left key in those cases.  */
5325       int is_left_key, is_right_key;
5327       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5328         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5330       /* (Carbon way: [theEvent keyCode]) */
5332       /* is it a "function key"? */
5333       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5334          flag set (this is probably a bug in the OS).
5335       */
5336       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5337         {
5338           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5339         }
5340       if (fnKeysym == 0)
5341         {
5342           fnKeysym = ns_convert_key (code);
5343         }
5345       if (fnKeysym)
5346         {
5347           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5348              because Emacs treats Delete and KP-Delete same (in simple.el). */
5349           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5350 #ifdef NS_IMPL_GNUSTEP
5351               /*  GNUstep uses incompatible keycodes, even for those that are
5352                   supposed to be hardware independent.  Just check for delete.
5353                   Keypad delete does not have keysym 0xFFFF.
5354                   See http://savannah.gnu.org/bugs/?25395
5355               */
5356               || (fnKeysym == 0xFFFF && code == 127)
5357 #endif
5358             )
5359             code = 0xFF08; /* backspace */
5360           else
5361             code = fnKeysym;
5362         }
5364       /* are there modifiers? */
5365       emacs_event->modifiers = 0;
5367       if (flags & NSHelpKeyMask)
5368           emacs_event->modifiers |= hyper_modifier;
5370       if (flags & NSShiftKeyMask)
5371         emacs_event->modifiers |= shift_modifier;
5373       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5374       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5375         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5377       if (is_right_key)
5378         emacs_event->modifiers |= parse_solitary_modifier
5379           (EQ (ns_right_command_modifier, Qleft)
5380            ? ns_command_modifier
5381            : ns_right_command_modifier);
5383       if (is_left_key)
5384         {
5385           emacs_event->modifiers |= parse_solitary_modifier
5386             (ns_command_modifier);
5388           /* if super (default), take input manager's word so things like
5389              dvorak / qwerty layout work */
5390           if (EQ (ns_command_modifier, Qsuper)
5391               && !fnKeysym
5392               && [[theEvent characters] length] != 0)
5393             {
5394               /* XXX: the code we get will be unshifted, so if we have
5395                  a shift modifier, must convert ourselves */
5396               if (!(flags & NSShiftKeyMask))
5397                 code = [[theEvent characters] characterAtIndex: 0];
5398 #if 0
5399               /* this is ugly and also requires linking w/Carbon framework
5400                  (for LMGetKbdType) so for now leave this rare (?) case
5401                  undealt with.. in future look into CGEvent methods */
5402               else
5403                 {
5404                   long smv = GetScriptManagerVariable (smKeyScript);
5405                   Handle uchrHandle = GetResource
5406                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5407                   UInt32 dummy = 0;
5408                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5409                                  [[theEvent characters] characterAtIndex: 0],
5410                                  kUCKeyActionDisplay,
5411                                  (flags & ~NSCommandKeyMask) >> 8,
5412                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5413                                  &dummy, 1, &dummy, &code);
5414                   code &= 0xFF;
5415                 }
5416 #endif
5417             }
5418         }
5420       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5421       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5422         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5424       if (is_right_key)
5425           emacs_event->modifiers |= parse_solitary_modifier
5426               (EQ (ns_right_control_modifier, Qleft)
5427                ? ns_control_modifier
5428                : ns_right_control_modifier);
5430       if (is_left_key)
5431         emacs_event->modifiers |= parse_solitary_modifier
5432           (ns_control_modifier);
5434       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5435           emacs_event->modifiers |=
5436             parse_solitary_modifier (ns_function_modifier);
5438       left_is_none = NILP (ns_alternate_modifier)
5439         || EQ (ns_alternate_modifier, Qnone);
5441       is_right_key = (flags & NSRightAlternateKeyMask)
5442         == NSRightAlternateKeyMask;
5443       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5444         || (! is_right_key
5445             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5447       if (is_right_key)
5448         {
5449           if ((NILP (ns_right_alternate_modifier)
5450                || EQ (ns_right_alternate_modifier, Qnone)
5451                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5452               && !fnKeysym)
5453             {   /* accept pre-interp alt comb */
5454               if ([[theEvent characters] length] > 0)
5455                 code = [[theEvent characters] characterAtIndex: 0];
5456               /*HACK: clear lone shift modifier to stop next if from firing */
5457               if (emacs_event->modifiers == shift_modifier)
5458                 emacs_event->modifiers = 0;
5459             }
5460           else
5461             emacs_event->modifiers |= parse_solitary_modifier
5462               (EQ (ns_right_alternate_modifier, Qleft)
5463                ? ns_alternate_modifier
5464                : ns_right_alternate_modifier);
5465         }
5467       if (is_left_key) /* default = meta */
5468         {
5469           if (left_is_none && !fnKeysym)
5470             {   /* accept pre-interp alt comb */
5471               if ([[theEvent characters] length] > 0)
5472                 code = [[theEvent characters] characterAtIndex: 0];
5473               /*HACK: clear lone shift modifier to stop next if from firing */
5474               if (emacs_event->modifiers == shift_modifier)
5475                 emacs_event->modifiers = 0;
5476             }
5477           else
5478               emacs_event->modifiers |=
5479                 parse_solitary_modifier (ns_alternate_modifier);
5480         }
5482   if (NS_KEYLOG)
5483     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5484              code, fnKeysym, flags, emacs_event->modifiers);
5486       /* if it was a function key or had modifiers, pass it directly to emacs */
5487       if (fnKeysym || (emacs_event->modifiers
5488                        && (emacs_event->modifiers != shift_modifier)
5489                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5490 /*[[theEvent characters] length] */
5491         {
5492           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5493           if (code < 0x20)
5494             code |= (1<<28)|(3<<16);
5495           else if (code == 0x7f)
5496             code |= (1<<28)|(3<<16);
5497           else if (!fnKeysym)
5498             emacs_event->kind = code > 0xFF
5499               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5501           emacs_event->code = code;
5502           EV_TRAILER (theEvent);
5503           processingCompose = NO;
5504           return;
5505         }
5506     }
5509   if (NS_KEYLOG && !processingCompose)
5510     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5512   processingCompose = YES;
5513   [nsEvArray addObject: theEvent];
5514   [self interpretKeyEvents: nsEvArray];
5515   [nsEvArray removeObject: theEvent];
5519 #ifdef NS_IMPL_COCOA
5520 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5521    decided not to send key-down for.
5522    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5523    This only applies on Tiger and earlier.
5524    If it matches one of these, send it on to keyDown. */
5525 -(void)keyUp: (NSEvent *)theEvent
5527   int flags = [theEvent modifierFlags];
5528   int code = [theEvent keyCode];
5529   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5530       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5531     {
5532       if (NS_KEYLOG)
5533         fprintf (stderr, "keyUp: passed test");
5534       ns_fake_keydown = YES;
5535       [self keyDown: theEvent];
5536     }
5538 #endif
5541 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5544 /* <NSTextInput>: called when done composing;
5545    NOTE: also called when we delete over working text, followed immed.
5546          by doCommandBySelector: deleteBackward: */
5547 - (void)insertText: (id)aString
5549   int code;
5550   int len = [(NSString *)aString length];
5551   int i;
5553   if (NS_KEYLOG)
5554     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5555   processingCompose = NO;
5557   if (!emacs_event)
5558     return;
5560   /* first, clear any working text */
5561   if (workingText != nil)
5562     [self deleteWorkingText];
5564   /* now insert the string as keystrokes */
5565   for (i =0; i<len; i++)
5566     {
5567       code = [aString characterAtIndex: i];
5568       /* TODO: still need this? */
5569       if (code == 0x2DC)
5570         code = '~'; /* 0x7E */
5571       if (code != 32) /* Space */
5572         emacs_event->modifiers = 0;
5573       emacs_event->kind
5574         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5575       emacs_event->code = code;
5576       EV_TRAILER ((id)nil);
5577     }
5581 /* <NSTextInput>: inserts display of composing characters */
5582 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5584   NSString *str = [aString respondsToSelector: @selector (string)] ?
5585     [aString string] : aString;
5586   if (NS_KEYLOG)
5587     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5588            str, (unsigned long)[str length],
5589            (unsigned long)selRange.length,
5590            (unsigned long)selRange.location);
5592   if (workingText != nil)
5593     [self deleteWorkingText];
5594   if ([str length] == 0)
5595     return;
5597   if (!emacs_event)
5598     return;
5600   processingCompose = YES;
5601   workingText = [str copy];
5602   ns_working_text = build_string ([workingText UTF8String]);
5604   emacs_event->kind = NS_TEXT_EVENT;
5605   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5606   EV_TRAILER ((id)nil);
5610 /* delete display of composing characters [not in <NSTextInput>] */
5611 - (void)deleteWorkingText
5613   if (workingText == nil)
5614     return;
5615   if (NS_KEYLOG)
5616     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5617   [workingText release];
5618   workingText = nil;
5619   processingCompose = NO;
5621   if (!emacs_event)
5622     return;
5624   emacs_event->kind = NS_TEXT_EVENT;
5625   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5626   EV_TRAILER ((id)nil);
5630 - (BOOL)hasMarkedText
5632   return workingText != nil;
5636 - (NSRange)markedRange
5638   NSRange rng = workingText != nil
5639     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5640   if (NS_KEYLOG)
5641     NSLog (@"markedRange request");
5642   return rng;
5646 - (void)unmarkText
5648   if (NS_KEYLOG)
5649     NSLog (@"unmark (accept) text");
5650   [self deleteWorkingText];
5651   processingCompose = NO;
5655 /* used to position char selection windows, etc. */
5656 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5658   NSRect rect;
5659   NSPoint pt;
5660   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5661   if (NS_KEYLOG)
5662     NSLog (@"firstRectForCharRange request");
5664   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5665   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5666   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5667   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5668                                        +FRAME_LINE_HEIGHT (emacsframe));
5670   pt = [self convertPoint: pt toView: nil];
5671   pt = [[self window] convertBaseToScreen: pt];
5672   rect.origin = pt;
5673   return rect;
5677 - (NSInteger)conversationIdentifier
5679   return (NSInteger)self;
5683 - (void)doCommandBySelector: (SEL)aSelector
5685   if (NS_KEYLOG)
5686     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5688   processingCompose = NO;
5689   if (aSelector == @selector (deleteBackward:))
5690     {
5691       /* happens when user backspaces over an ongoing composition:
5692          throw a 'delete' into the event queue */
5693       if (!emacs_event)
5694         return;
5695       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5696       emacs_event->code = 0xFF08;
5697       EV_TRAILER ((id)nil);
5698     }
5701 - (NSArray *)validAttributesForMarkedText
5703   static NSArray *arr = nil;
5704   if (arr == nil) arr = [NSArray new];
5705  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5706   return arr;
5709 - (NSRange)selectedRange
5711   if (NS_KEYLOG)
5712     NSLog (@"selectedRange request");
5713   return NSMakeRange (NSNotFound, 0);
5716 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5717     GNUSTEP_GUI_MINOR_VERSION > 22
5718 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5719 #else
5720 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5721 #endif
5723   if (NS_KEYLOG)
5724     NSLog (@"characterIndexForPoint request");
5725   return 0;
5728 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5730   static NSAttributedString *str = nil;
5731   if (str == nil) str = [NSAttributedString new];
5732   if (NS_KEYLOG)
5733     NSLog (@"attributedSubstringFromRange request");
5734   return str;
5737 /* End <NSTextInput> impl. */
5738 /*****************************************************************************/
5741 /* This is what happens when the user presses a mouse button.  */
5742 - (void)mouseDown: (NSEvent *)theEvent
5744   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5745   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5747   NSTRACE (mouseDown);
5749   [self deleteWorkingText];
5751   if (!emacs_event)
5752     return;
5754   dpyinfo->last_mouse_frame = emacsframe;
5755   /* appears to be needed to prevent spurious movement events generated on
5756      button clicks */
5757   emacsframe->mouse_moved = 0;
5759   if ([theEvent type] == NSScrollWheel)
5760     {
5761       CGFloat delta = [theEvent deltaY];
5762       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5763       if (delta == 0)
5764         {
5765           delta = [theEvent deltaX];
5766           if (delta == 0)
5767             {
5768               NSTRACE (deltaIsZero);
5769               return;
5770             }
5771           emacs_event->kind = HORIZ_WHEEL_EVENT;
5772         }
5773       else
5774         emacs_event->kind = WHEEL_EVENT;
5776       emacs_event->code = 0;
5777       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5778         ((delta > 0) ? up_modifier : down_modifier);
5779     }
5780   else
5781     {
5782       emacs_event->kind = MOUSE_CLICK_EVENT;
5783       emacs_event->code = EV_BUTTON (theEvent);
5784       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5785                              | EV_UDMODIFIERS (theEvent);
5786     }
5787   XSETINT (emacs_event->x, lrint (p.x));
5788   XSETINT (emacs_event->y, lrint (p.y));
5789   EV_TRAILER (theEvent);
5793 - (void)rightMouseDown: (NSEvent *)theEvent
5795   NSTRACE (rightMouseDown);
5796   [self mouseDown: theEvent];
5800 - (void)otherMouseDown: (NSEvent *)theEvent
5802   NSTRACE (otherMouseDown);
5803   [self mouseDown: theEvent];
5807 - (void)mouseUp: (NSEvent *)theEvent
5809   NSTRACE (mouseUp);
5810   [self mouseDown: theEvent];
5814 - (void)rightMouseUp: (NSEvent *)theEvent
5816   NSTRACE (rightMouseUp);
5817   [self mouseDown: theEvent];
5821 - (void)otherMouseUp: (NSEvent *)theEvent
5823   NSTRACE (otherMouseUp);
5824   [self mouseDown: theEvent];
5828 - (void) scrollWheel: (NSEvent *)theEvent
5830   NSTRACE (scrollWheel);
5831   [self mouseDown: theEvent];
5835 /* Tell emacs the mouse has moved. */
5836 - (void)mouseMoved: (NSEvent *)e
5838   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5839   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5840   Lisp_Object frame;
5841   NSPoint pt;
5843 //  NSTRACE (mouseMoved);
5845   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5846   pt = [self convertPoint: [e locationInWindow] fromView: nil];
5847   dpyinfo->last_mouse_motion_x = pt.x;
5848   dpyinfo->last_mouse_motion_y = pt.y;
5850   /* update any mouse face */
5851   if (hlinfo->mouse_face_hidden)
5852     {
5853       hlinfo->mouse_face_hidden = 0;
5854       clear_mouse_face (hlinfo);
5855     }
5857   /* tooltip handling */
5858   previous_help_echo_string = help_echo_string;
5859   help_echo_string = Qnil;
5861   if (!NILP (Vmouse_autoselect_window))
5862     {
5863       NSTRACE (mouse_autoselect_window);
5864       static Lisp_Object last_mouse_window;
5865       Lisp_Object window
5866         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5868       if (WINDOWP (window)
5869           && !EQ (window, last_mouse_window)
5870           && !EQ (window, selected_window)
5871           && (focus_follows_mouse
5872               || (EQ (XWINDOW (window)->frame,
5873                       XWINDOW (selected_window)->frame))))
5874         {
5875           NSTRACE (in_window);
5876           emacs_event->kind = SELECT_WINDOW_EVENT;
5877           emacs_event->frame_or_window = window;
5878           EV_TRAILER2 (e);
5879         }
5880       /* Remember the last window where we saw the mouse.  */
5881       last_mouse_window = window;
5882     }
5884   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5885     help_echo_string = previous_help_echo_string;
5887   XSETFRAME (frame, emacsframe);
5888   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5889     {
5890       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5891          (note_mouse_highlight), which is called through the
5892          note_mouse_movement () call above */
5893       any_help_event_p = YES;
5894       gen_help_event (help_echo_string, frame, help_echo_window,
5895                       help_echo_object, help_echo_pos);
5896     }
5898   if (emacsframe->mouse_moved && send_appdefined)
5899     ns_send_appdefined (-1);
5903 - (void)mouseDragged: (NSEvent *)e
5905   NSTRACE (mouseDragged);
5906   [self mouseMoved: e];
5910 - (void)rightMouseDragged: (NSEvent *)e
5912   NSTRACE (rightMouseDragged);
5913   [self mouseMoved: e];
5917 - (void)otherMouseDragged: (NSEvent *)e
5919   NSTRACE (otherMouseDragged);
5920   [self mouseMoved: e];
5924 - (BOOL)windowShouldClose: (id)sender
5926   NSEvent *e =[[self window] currentEvent];
5928   NSTRACE (windowShouldClose);
5929   windowClosing = YES;
5930   if (!emacs_event)
5931     return NO;
5932   emacs_event->kind = DELETE_WINDOW_EVENT;
5933   emacs_event->modifiers = 0;
5934   emacs_event->code = 0;
5935   EV_TRAILER (e);
5936   /* Don't close this window, let this be done from lisp code.  */
5937   return NO;
5940 - (void) updateFrameSize: (BOOL) delay;
5942   NSWindow *window = [self window];
5943   NSRect wr = [window frame];
5944   int extra = 0;
5945   int oldc = cols, oldr = rows;
5946   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5947   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5948   int neww, newh;
5950   NSTRACE (updateFrameSize);
5951   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5953   if (! [self isFullscreen])
5954     {
5955 #ifdef NS_IMPL_GNUSTEP
5956       // GNUstep does not always update the tool bar height.  Force it.
5957       if (toolbar && [toolbar isVisible])
5958           update_frame_tool_bar (emacsframe);
5959 #endif
5961       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5962         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5963     }
5965   if (wait_for_tool_bar)
5966     {
5967       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5968         return;
5969       wait_for_tool_bar = NO;
5970     }
5972   neww = (int)wr.size.width - emacsframe->border_width;
5973   newh = (int)wr.size.height - extra;
5975   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5976   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5978   if (cols < MINWIDTH)
5979     cols = MINWIDTH;
5981   if (rows < MINHEIGHT)
5982     rows = MINHEIGHT;
5984   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5985     {
5986       NSView *view = FRAME_NS_VIEW (emacsframe);
5987       NSWindow *win = [view window];
5988       NSSize sz = [win resizeIncrements];
5990       change_frame_size (emacsframe,
5991                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5992                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5993                          0, delay, 0, 1);
5994       SET_FRAME_GARBAGED (emacsframe);
5995       cancel_mouse_face (emacsframe);
5997       // Did resize increments change because of a font change?
5998       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5999           sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
6000           (frame_resize_pixelwise && sz.width != 1))
6001         {
6002           sz.width = frame_resize_pixelwise
6003             ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
6004           sz.height = frame_resize_pixelwise
6005             ? 1 : FRAME_LINE_HEIGHT (emacsframe);
6006           [win setResizeIncrements: sz];
6008           NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6009         }
6011       [view setFrame: NSMakeRect (0, 0, neww, newh)];
6012       [self windowDidMove:nil];   // Update top/left.
6013     }
6016 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6017 /* normalize frame to gridded text size */
6019   int extra = 0;
6021   NSTRACE (windowWillResize);
6022   NSTRACE_SIZE ("Original size", frameSize);
6023 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
6025   if (fs_state == FULLSCREEN_MAXIMIZED
6026       && (maximized_width != (int)frameSize.width
6027           || maximized_height != (int)frameSize.height))
6028     [self setFSValue: FULLSCREEN_NONE];
6029   else if (fs_state == FULLSCREEN_WIDTH
6030            && maximized_width != (int)frameSize.width)
6031     [self setFSValue: FULLSCREEN_NONE];
6032   else if (fs_state == FULLSCREEN_HEIGHT
6033            && maximized_height != (int)frameSize.height)
6034     [self setFSValue: FULLSCREEN_NONE];
6035   if (fs_state == FULLSCREEN_NONE)
6036     maximized_width = maximized_height = -1;
6038   if (! [self isFullscreen])
6039     {
6040       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6041         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6042     }
6044   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6045   if (cols < MINWIDTH)
6046     cols = MINWIDTH;
6048   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6049                                            frameSize.height - extra);
6050   if (rows < MINHEIGHT)
6051     rows = MINHEIGHT;
6052 #ifdef NS_IMPL_COCOA
6053   {
6054     /* this sets window title to have size in it; the wm does this under GS */
6055     NSRect r = [[self window] frame];
6056     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6057       {
6058         if (old_title != 0)
6059           {
6060             xfree (old_title);
6061             old_title = 0;
6062           }
6063       }
6064     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6065       {
6066         char *size_title;
6067         NSWindow *window = [self window];
6068         if (old_title == 0)
6069           {
6070             char *t = strdup ([[[self window] title] UTF8String]);
6071             char *pos = strstr (t, "  â€”  ");
6072             if (pos)
6073               *pos = '\0';
6074             old_title = t;
6075           }
6076         size_title = xmalloc (strlen (old_title) + 40);
6077         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6078         [window setTitle: [NSString stringWithUTF8String: size_title]];
6079         [window display];
6080         xfree (size_title);
6081       }
6082   }
6083 #endif /* NS_IMPL_COCOA */
6084 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
6086   return frameSize;
6090 - (void)windowDidResize: (NSNotification *)notification
6092   if (! [self fsIsNative])
6093     {
6094       NSWindow *theWindow = [notification object];
6095       /* We can get notification on the non-FS window when in
6096          fullscreen mode.  */
6097       if ([self window] != theWindow) return;
6098     }
6100 #ifdef NS_IMPL_GNUSTEP
6101   NSWindow *theWindow = [notification object];
6103    /* In GNUstep, at least currently, it's possible to get a didResize
6104       without getting a willResize.. therefore we need to act as if we got
6105       the willResize now */
6106   NSSize sz = [theWindow frame].size;
6107   sz = [self windowWillResize: theWindow toSize: sz];
6108 #endif /* NS_IMPL_GNUSTEP */
6110   NSTRACE (windowDidResize);
6111 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6113 if (cols > 0 && rows > 0)
6114     {
6115       [self updateFrameSize: YES];
6116     }
6118   ns_send_appdefined (-1);
6121 #ifdef NS_IMPL_COCOA
6122 - (void)viewDidEndLiveResize
6124   [super viewDidEndLiveResize];
6125   if (old_title != 0)
6126     {
6127       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6128       xfree (old_title);
6129       old_title = 0;
6130     }
6131   maximizing_resize = NO;
6133 #endif /* NS_IMPL_COCOA */
6136 - (void)windowDidBecomeKey: (NSNotification *)notification
6137 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6139   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6140   struct frame *old_focus = dpyinfo->x_focus_frame;
6142   NSTRACE (windowDidBecomeKey);
6144   if (emacsframe != old_focus)
6145     dpyinfo->x_focus_frame = emacsframe;
6147   ns_frame_rehighlight (emacsframe);
6149   if (emacs_event)
6150     {
6151       emacs_event->kind = FOCUS_IN_EVENT;
6152       EV_TRAILER ((id)nil);
6153     }
6157 - (void)windowDidResignKey: (NSNotification *)notification
6158 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6160   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6161   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6162   NSTRACE (windowDidResignKey);
6164   if (is_focus_frame)
6165     dpyinfo->x_focus_frame = 0;
6167   emacsframe->mouse_moved = 0;
6168   ns_frame_rehighlight (emacsframe);
6170   /* FIXME: for some reason needed on second and subsequent clicks away
6171             from sole-frame Emacs to get hollow box to show */
6172   if (!windowClosing && [[self window] isVisible] == YES)
6173     {
6174       x_update_cursor (emacsframe, 1);
6175       x_set_frame_alpha (emacsframe);
6176     }
6178   if (any_help_event_p)
6179     {
6180       Lisp_Object frame;
6181       XSETFRAME (frame, emacsframe);
6182       help_echo_string = Qnil;
6183       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6184     }
6186   if (emacs_event && is_focus_frame)
6187     {
6188       [self deleteWorkingText];
6189       emacs_event->kind = FOCUS_OUT_EVENT;
6190       EV_TRAILER ((id)nil);
6191     }
6195 - (void)windowWillMiniaturize: sender
6197   NSTRACE (windowWillMiniaturize);
6201 - (BOOL)isFlipped
6203   return YES;
6207 - (BOOL)isOpaque
6209   return NO;
6213 - initFrameFromEmacs: (struct frame *)f
6215   NSRect r, wr;
6216   Lisp_Object tem;
6217   NSWindow *win;
6218   NSSize sz;
6219   NSColor *col;
6220   NSString *name;
6222   NSTRACE (initFrameFromEmacs);
6224   windowClosing = NO;
6225   processingCompose = NO;
6226   scrollbarsNeedingUpdate = 0;
6227   fs_state = FULLSCREEN_NONE;
6228   fs_before_fs = next_maximized = -1;
6229 #ifdef HAVE_NATIVE_FS
6230   fs_is_native = ns_use_native_fullscreen;
6231 #else
6232   fs_is_native = NO;
6233 #endif
6234   maximized_width = maximized_height = -1;
6235   nonfs_window = nil;
6237 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6239   ns_userRect = NSMakeRect (0, 0, 0, 0);
6240   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6241                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6242   [self initWithFrame: r];
6243   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6245   FRAME_NS_VIEW (f) = self;
6246   emacsframe = f;
6247 #ifdef NS_IMPL_COCOA
6248   old_title = 0;
6249   maximizing_resize = NO;
6250 #endif
6252   win = [[EmacsWindow alloc]
6253             initWithContentRect: r
6254                       styleMask: (NSResizableWindowMask |
6255 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6256                                   NSTitledWindowMask |
6257 #endif
6258                                   NSMiniaturizableWindowMask |
6259                                   NSClosableWindowMask)
6260                         backing: NSBackingStoreBuffered
6261                           defer: YES];
6263 #ifdef HAVE_NATIVE_FS
6264     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6265 #endif
6267   wr = [win frame];
6268   bwidth = f->border_width = wr.size.width - r.size.width;
6269   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6271   [win setAcceptsMouseMovedEvents: YES];
6272   [win setDelegate: self];
6273 #if !defined (NS_IMPL_COCOA) || \
6274   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6275   [win useOptimizedDrawing: YES];
6276 #endif
6277   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6278   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6279   [win setResizeIncrements: sz];
6281   [[win contentView] addSubview: self];
6283   if (ns_drag_types)
6284     [self registerForDraggedTypes: ns_drag_types];
6286   tem = f->name;
6287   name = [NSString stringWithUTF8String:
6288                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6289   [win setTitle: name];
6291   /* toolbar support */
6292   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6293                          [NSString stringWithFormat: @"Emacs Frame %d",
6294                                    ns_window_num]];
6295   [win setToolbar: toolbar];
6296   [toolbar setVisible: NO];
6298   /* Don't set frame garbaged until tool bar is up to date?
6299      This avoids an extra clear and redraw (flicker) at frame creation.  */
6300   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6301   else wait_for_tool_bar = NO;
6304 #ifdef NS_IMPL_COCOA
6305   {
6306     NSButton *toggleButton;
6307   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6308   [toggleButton setTarget: self];
6309   [toggleButton setAction: @selector (toggleToolbar: )];
6310   }
6311 #endif
6312   FRAME_TOOLBAR_HEIGHT (f) = 0;
6314   tem = f->icon_name;
6315   if (!NILP (tem))
6316     [win setMiniwindowTitle:
6317            [NSString stringWithUTF8String: SSDATA (tem)]];
6319   {
6320     NSScreen *screen = [win screen];
6322     if (screen != 0)
6323       [win setFrameTopLeftPoint: NSMakePoint
6324            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6325             IN_BOUND (-SCREENMAX,
6326                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6327   }
6329   [win makeFirstResponder: self];
6331   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6332                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6333   [win setBackgroundColor: col];
6334   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6335     [win setOpaque: NO];
6337 #if !defined (NS_IMPL_COCOA) || \
6338   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6339   [self allocateGState];
6340 #endif
6341   [NSApp registerServicesMenuSendTypes: ns_send_types
6342                            returnTypes: nil];
6344   ns_window_num++;
6345   return self;
6349 - (void)windowDidMove: sender
6351   NSWindow *win = [self window];
6352   NSRect r = [win frame];
6353   NSArray *screens = [NSScreen screens];
6354   NSScreen *screen = [screens objectAtIndex: 0];
6356   NSTRACE (windowDidMove);
6358   if (!emacsframe->output_data.ns)
6359     return;
6360   if (screen != nil)
6361     {
6362       emacsframe->left_pos = r.origin.x;
6363       emacsframe->top_pos =
6364         [screen frame].size.height - (r.origin.y + r.size.height);
6365     }
6369 /* Called AFTER method below, but before our windowWillResize call there leads
6370    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6371    location so set_window_size moves the frame. */
6372 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6374   emacsframe->output_data.ns->zooming = 1;
6375   return YES;
6379 /* Override to do something slightly nonstandard, but nice.  First click on
6380    zoom button will zoom vertically.  Second will zoom completely.  Third
6381    returns to original. */
6382 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6383                         defaultFrame:(NSRect)defaultFrame
6385   NSRect result = [sender frame];
6387   NSTRACE (windowWillUseStandardFrame);
6389   if (fs_before_fs != -1) /* Entering fullscreen */
6390       {
6391         result = defaultFrame;
6392       }
6393   else if (next_maximized == FULLSCREEN_HEIGHT
6394       || (next_maximized == -1
6395           && abs ((int)(defaultFrame.size.height - result.size.height))
6396           > FRAME_LINE_HEIGHT (emacsframe)))
6397     {
6398       /* first click */
6399       ns_userRect = result;
6400       maximized_height = result.size.height = defaultFrame.size.height;
6401       maximized_width = -1;
6402       result.origin.y = defaultFrame.origin.y;
6403       [self setFSValue: FULLSCREEN_HEIGHT];
6404 #ifdef NS_IMPL_COCOA
6405       maximizing_resize = YES;
6406 #endif
6407     }
6408   else if (next_maximized == FULLSCREEN_WIDTH)
6409     {
6410       ns_userRect = result;
6411       maximized_width = result.size.width = defaultFrame.size.width;
6412       maximized_height = -1;
6413       result.origin.x = defaultFrame.origin.x;
6414       [self setFSValue: FULLSCREEN_WIDTH];
6415     }
6416   else if (next_maximized == FULLSCREEN_MAXIMIZED
6417            || (next_maximized == -1
6418                && abs ((int)(defaultFrame.size.width - result.size.width))
6419                > FRAME_COLUMN_WIDTH (emacsframe)))
6420     {
6421       result = defaultFrame;  /* second click */
6422       maximized_width = result.size.width;
6423       maximized_height = result.size.height;
6424       [self setFSValue: FULLSCREEN_MAXIMIZED];
6425 #ifdef NS_IMPL_COCOA
6426       maximizing_resize = YES;
6427 #endif
6428     }
6429   else
6430     {
6431       /* restore */
6432       result = ns_userRect.size.height ? ns_userRect : result;
6433       ns_userRect = NSMakeRect (0, 0, 0, 0);
6434 #ifdef NS_IMPL_COCOA
6435       maximizing_resize = fs_state != FULLSCREEN_NONE;
6436 #endif
6437       [self setFSValue: FULLSCREEN_NONE];
6438       maximized_width = maximized_height = -1;
6439     }
6441   if (fs_before_fs == -1) next_maximized = -1;
6442   [self windowWillResize: sender toSize: result.size];
6443   return result;
6447 - (void)windowDidDeminiaturize: sender
6449   NSTRACE (windowDidDeminiaturize);
6450   if (!emacsframe->output_data.ns)
6451     return;
6453   SET_FRAME_ICONIFIED (emacsframe, 0);
6454   SET_FRAME_VISIBLE (emacsframe, 1);
6455   windows_or_buffers_changed = 63;
6457   if (emacs_event)
6458     {
6459       emacs_event->kind = DEICONIFY_EVENT;
6460       EV_TRAILER ((id)nil);
6461     }
6465 - (void)windowDidExpose: sender
6467   NSTRACE (windowDidExpose);
6468   if (!emacsframe->output_data.ns)
6469     return;
6471   SET_FRAME_VISIBLE (emacsframe, 1);
6472   SET_FRAME_GARBAGED (emacsframe);
6474   if (send_appdefined)
6475     ns_send_appdefined (-1);
6479 - (void)windowDidMiniaturize: sender
6481   NSTRACE (windowDidMiniaturize);
6482   if (!emacsframe->output_data.ns)
6483     return;
6485   SET_FRAME_ICONIFIED (emacsframe, 1);
6486   SET_FRAME_VISIBLE (emacsframe, 0);
6488   if (emacs_event)
6489     {
6490       emacs_event->kind = ICONIFY_EVENT;
6491       EV_TRAILER ((id)nil);
6492     }
6495 #ifdef HAVE_NATIVE_FS
6496 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6497       willUseFullScreenPresentationOptions:
6498   (NSApplicationPresentationOptions)proposedOptions
6500   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6502 #endif
6504 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6506   fs_before_fs = fs_state;
6509 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6511   [self setFSValue: FULLSCREEN_BOTH];
6512   if (! [self fsIsNative])
6513     {
6514       [self windowDidBecomeKey:notification];
6515       [nonfs_window orderOut:self];
6516     }
6517   else
6518     {
6519       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6520 #ifdef NS_IMPL_COCOA
6521 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6522       unsigned val = (unsigned)[NSApp presentationOptions];
6524       // OSX 10.7 bug fix, the menu won't appear without this.
6525       // val is non-zero on other OSX versions.
6526       if (val == 0)
6527         {
6528           NSApplicationPresentationOptions options
6529             = NSApplicationPresentationAutoHideDock
6530             | NSApplicationPresentationAutoHideMenuBar
6531             | NSApplicationPresentationFullScreen
6532             | NSApplicationPresentationAutoHideToolbar;
6534           [NSApp setPresentationOptions: options];
6535         }
6536 #endif
6537 #endif
6538       [toolbar setVisible:tbar_visible];
6539     }
6542 - (void)windowWillExitFullScreen:(NSNotification *)notification
6544   if (next_maximized != -1)
6545     fs_before_fs = next_maximized;
6548 - (void)windowDidExitFullScreen:(NSNotification *)notification
6550   [self setFSValue: fs_before_fs];
6551   fs_before_fs = -1;
6552 #ifdef HAVE_NATIVE_FS
6553   [self updateCollectionBehavior];
6554 #endif
6555   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6556     {
6557       [toolbar setVisible:YES];
6558       update_frame_tool_bar (emacsframe);
6559       [self updateFrameSize:YES];
6560       [[self window] display];
6561     }
6562   else
6563     [toolbar setVisible:NO];
6565   if (next_maximized != -1)
6566     [[self window] performZoom:self];
6569 - (BOOL)fsIsNative
6571   return fs_is_native;
6574 - (BOOL)isFullscreen
6576   if (! fs_is_native) return nonfs_window != nil;
6577 #ifdef HAVE_NATIVE_FS
6578   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6579 #else
6580   return NO;
6581 #endif
6584 #ifdef HAVE_NATIVE_FS
6585 - (void)updateCollectionBehavior
6587   if (! [self isFullscreen])
6588     {
6589       NSWindow *win = [self window];
6590       NSWindowCollectionBehavior b = [win collectionBehavior];
6591       if (ns_use_native_fullscreen)
6592         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6593       else
6594         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6596       [win setCollectionBehavior: b];
6597       fs_is_native = ns_use_native_fullscreen;
6598     }
6600 #endif
6602 - (void)toggleFullScreen: (id)sender
6604   NSWindow *w, *fw;
6605   BOOL onFirstScreen;
6606   struct frame *f;
6607   NSSize sz;
6608   NSRect r, wr;
6609   NSColor *col;
6611   if (fs_is_native)
6612     {
6613 #ifdef HAVE_NATIVE_FS
6614       [[self window] toggleFullScreen:sender];
6615 #endif
6616       return;
6617     }
6619   w = [self window];
6620   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6621   f = emacsframe;
6622   wr = [w frame];
6623   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6624                                  (FRAME_DEFAULT_FACE (f)),
6625                                  f);
6627   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6628   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6630   if (fs_state != FULLSCREEN_BOTH)
6631     {
6632       NSScreen *screen = [w screen];
6634 #if defined (NS_IMPL_COCOA) && \
6635   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6636       /* Hide ghost menu bar on secondary monitor? */
6637       if (! onFirstScreen)
6638         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6639 #endif
6640       /* Hide dock and menubar if we are on the primary screen.  */
6641       if (onFirstScreen)
6642         {
6643 #ifdef NS_IMPL_COCOA
6644           NSApplicationPresentationOptions options
6645             = NSApplicationPresentationAutoHideDock
6646             | NSApplicationPresentationAutoHideMenuBar;
6648           [NSApp setPresentationOptions: options];
6649 #else
6650           [NSMenu setMenuBarVisible:NO];
6651 #endif
6652         }
6654       fw = [[EmacsFSWindow alloc]
6655                        initWithContentRect:[w contentRectForFrameRect:wr]
6656                                  styleMask:NSBorderlessWindowMask
6657                                    backing:NSBackingStoreBuffered
6658                                      defer:YES
6659                                     screen:screen];
6661       [fw setContentView:[w contentView]];
6662       [fw setTitle:[w title]];
6663       [fw setDelegate:self];
6664       [fw setAcceptsMouseMovedEvents: YES];
6665 #if !defined (NS_IMPL_COCOA) || \
6666   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6667       [fw useOptimizedDrawing: YES];
6668 #endif
6669       [fw setResizeIncrements: sz];
6670       [fw setBackgroundColor: col];
6671       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6672         [fw setOpaque: NO];
6674       f->border_width = 0;
6675       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6676       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6677       FRAME_TOOLBAR_HEIGHT (f) = 0;
6679       nonfs_window = w;
6681       [self windowWillEnterFullScreen:nil];
6682       [fw makeKeyAndOrderFront:NSApp];
6683       [fw makeFirstResponder:self];
6684       [w orderOut:self];
6685       r = [fw frameRectForContentRect:[screen frame]];
6686       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6687       [self windowDidEnterFullScreen:nil];
6688       [fw display];
6689     }
6690   else
6691     {
6692       fw = w;
6693       w = nonfs_window;
6694       nonfs_window = nil;
6696       if (onFirstScreen)
6697         {
6698 #ifdef NS_IMPL_COCOA
6699           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6700 #else
6701           [NSMenu setMenuBarVisible:YES];
6702 #endif
6703         }
6705       [w setContentView:[fw contentView]];
6706       [w setResizeIncrements: sz];
6707       [w setBackgroundColor: col];
6708       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6709         [w setOpaque: NO];
6711       f->border_width = bwidth;
6712       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6713       if (FRAME_EXTERNAL_TOOL_BAR (f))
6714         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6716       [self windowWillExitFullScreen:nil];
6717       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6718       [fw close];
6719       [w makeKeyAndOrderFront:NSApp];
6720       [self windowDidExitFullScreen:nil];
6721       [self updateFrameSize:YES];
6722     }
6725 - (void)handleFS
6727   if (fs_state != emacsframe->want_fullscreen)
6728     {
6729       if (fs_state == FULLSCREEN_BOTH)
6730         {
6731           [self toggleFullScreen:self];
6732         }
6734       switch (emacsframe->want_fullscreen)
6735         {
6736         case FULLSCREEN_BOTH:
6737           [self toggleFullScreen:self];
6738           break;
6739         case FULLSCREEN_WIDTH:
6740           next_maximized = FULLSCREEN_WIDTH;
6741           if (fs_state != FULLSCREEN_BOTH)
6742             [[self window] performZoom:self];
6743           break;
6744         case FULLSCREEN_HEIGHT:
6745           next_maximized = FULLSCREEN_HEIGHT;
6746           if (fs_state != FULLSCREEN_BOTH)
6747             [[self window] performZoom:self];
6748           break;
6749         case FULLSCREEN_MAXIMIZED:
6750           next_maximized = FULLSCREEN_MAXIMIZED;
6751           if (fs_state != FULLSCREEN_BOTH)
6752             [[self window] performZoom:self];
6753           break;
6754         case FULLSCREEN_NONE:
6755           if (fs_state != FULLSCREEN_BOTH)
6756             {
6757               next_maximized = FULLSCREEN_NONE;
6758               [[self window] performZoom:self];
6759             }
6760           break;
6761         }
6763       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6764     }
6768 - (void) setFSValue: (int)value
6770   Lisp_Object lval = Qnil;
6771   switch (value)
6772     {
6773     case FULLSCREEN_BOTH:
6774       lval = Qfullboth;
6775       break;
6776     case FULLSCREEN_WIDTH:
6777       lval = Qfullwidth;
6778       break;
6779     case FULLSCREEN_HEIGHT:
6780       lval = Qfullheight;
6781       break;
6782     case FULLSCREEN_MAXIMIZED:
6783       lval = Qmaximized;
6784       break;
6785     }
6786   store_frame_param (emacsframe, Qfullscreen, lval);
6787   fs_state = value;
6790 - (void)mouseEntered: (NSEvent *)theEvent
6792   NSTRACE (mouseEntered);
6793   if (emacsframe)
6794     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6795       = EV_TIMESTAMP (theEvent);
6799 - (void)mouseExited: (NSEvent *)theEvent
6801   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6803   NSTRACE (mouseExited);
6805   if (!hlinfo)
6806     return;
6808   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6809     = EV_TIMESTAMP (theEvent);
6811   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6812     {
6813       clear_mouse_face (hlinfo);
6814       hlinfo->mouse_face_mouse_frame = 0;
6815     }
6819 - menuDown: sender
6821   NSTRACE (menuDown);
6822   if (context_menu_value == -1)
6823     context_menu_value = [sender tag];
6824   else
6825     {
6826       NSInteger tag = [sender tag];
6827       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6828                                     emacsframe->menu_bar_vector,
6829                                     (void *)tag);
6830     }
6832   ns_send_appdefined (-1);
6833   return self;
6837 - (EmacsToolbar *)toolbar
6839   return toolbar;
6843 /* this gets called on toolbar button click */
6844 - toolbarClicked: (id)item
6846   NSEvent *theEvent;
6847   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6849   NSTRACE (toolbarClicked);
6851   if (!emacs_event)
6852     return self;
6854   /* send first event (for some reason two needed) */
6855   theEvent = [[self window] currentEvent];
6856   emacs_event->kind = TOOL_BAR_EVENT;
6857   XSETFRAME (emacs_event->arg, emacsframe);
6858   EV_TRAILER (theEvent);
6860   emacs_event->kind = TOOL_BAR_EVENT;
6861 /*   XSETINT (emacs_event->code, 0); */
6862   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6863                            idx + TOOL_BAR_ITEM_KEY);
6864   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6865   EV_TRAILER (theEvent);
6866   return self;
6870 - toggleToolbar: (id)sender
6872   if (!emacs_event)
6873     return self;
6875   emacs_event->kind = NS_NONKEY_EVENT;
6876   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6877   EV_TRAILER ((id)nil);
6878   return self;
6882 - (void)drawRect: (NSRect)rect
6884   int x = NSMinX (rect), y = NSMinY (rect);
6885   int width = NSWidth (rect), height = NSHeight (rect);
6887   NSTRACE (drawRect);
6889   if (!emacsframe || !emacsframe->output_data.ns)
6890     return;
6892   ns_clear_frame_area (emacsframe, x, y, width, height);
6893   block_input ();
6894   expose_frame (emacsframe, x, y, width, height);
6895   unblock_input ();
6897   /*
6898     drawRect: may be called (at least in OS X 10.5) for invisible
6899     views as well for some reason.  Thus, do not infer visibility
6900     here.
6902     emacsframe->async_visible = 1;
6903     emacsframe->async_iconified = 0;
6904   */
6908 /* NSDraggingDestination protocol methods.  Actually this is not really a
6909    protocol, but a category of Object.  O well...  */
6911 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
6913   NSTRACE (draggingEntered);
6914   return NSDragOperationGeneric;
6918 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6920   return YES;
6924 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6926   id pb;
6927   int x, y;
6928   NSString *type;
6929   NSEvent *theEvent = [[self window] currentEvent];
6930   NSPoint position;
6931   NSDragOperation op = [sender draggingSourceOperationMask];
6932   int modifiers = 0;
6934   NSTRACE (performDragOperation);
6936   if (!emacs_event)
6937     return NO;
6939   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6940   x = lrint (position.x);  y = lrint (position.y);
6942   pb = [sender draggingPasteboard];
6943   type = [pb availableTypeFromArray: ns_drag_types];
6945   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6946       // URL drags contain all operations (0xf), don't allow all to be set.
6947       (op & 0xf) != 0xf)
6948     {
6949       if (op & NSDragOperationLink)
6950         modifiers |= NSControlKeyMask;
6951       if (op & NSDragOperationCopy)
6952         modifiers |= NSAlternateKeyMask;
6953       if (op & NSDragOperationGeneric)
6954         modifiers |= NSCommandKeyMask;
6955     }
6957   modifiers = EV_MODIFIERS2 (modifiers);
6958   if (type == 0)
6959     {
6960       return NO;
6961     }
6962   else if ([type isEqualToString: NSFilenamesPboardType])
6963     {
6964       NSArray *files;
6965       NSEnumerator *fenum;
6966       NSString *file;
6968       if (!(files = [pb propertyListForType: type]))
6969         return NO;
6971       fenum = [files objectEnumerator];
6972       while ( (file = [fenum nextObject]) )
6973         {
6974           emacs_event->kind = DRAG_N_DROP_EVENT;
6975           XSETINT (emacs_event->x, x);
6976           XSETINT (emacs_event->y, y);
6977           ns_input_file = append2 (ns_input_file,
6978                                    build_string ([file UTF8String]));
6979           emacs_event->modifiers = modifiers;
6980           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
6981           EV_TRAILER (theEvent);
6982         }
6983       return YES;
6984     }
6985   else if ([type isEqualToString: NSURLPboardType])
6986     {
6987       NSURL *url = [NSURL URLFromPasteboard: pb];
6988       if (url == nil) return NO;
6990       emacs_event->kind = DRAG_N_DROP_EVENT;
6991       XSETINT (emacs_event->x, x);
6992       XSETINT (emacs_event->y, y);
6993       emacs_event->modifiers = modifiers;
6994       emacs_event->arg =  list2 (Qurl,
6995                                  build_string ([[url absoluteString]
6996                                                  UTF8String]));
6997       EV_TRAILER (theEvent);
6999       if ([url isFileURL] != NO)
7000         {
7001           NSString *file = [url path];
7002           ns_input_file = append2 (ns_input_file,
7003                                    build_string ([file UTF8String]));
7004         }
7005       return YES;
7006     }
7007   else if ([type isEqualToString: NSStringPboardType]
7008            || [type isEqualToString: NSTabularTextPboardType])
7009     {
7010       NSString *data;
7012       if (! (data = [pb stringForType: type]))
7013         return NO;
7015       emacs_event->kind = DRAG_N_DROP_EVENT;
7016       XSETINT (emacs_event->x, x);
7017       XSETINT (emacs_event->y, y);
7018       emacs_event->modifiers = modifiers;
7019       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7020       EV_TRAILER (theEvent);
7021       return YES;
7022     }
7023   else
7024     {
7025       fprintf (stderr, "Invalid data type in dragging pasteboard");
7026       return NO;
7027     }
7031 - (id) validRequestorForSendType: (NSString *)typeSent
7032                       returnType: (NSString *)typeReturned
7034   NSTRACE (validRequestorForSendType);
7035   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7036       && typeReturned == nil)
7037     {
7038       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7039         return self;
7040     }
7042   return [super validRequestorForSendType: typeSent
7043                                returnType: typeReturned];
7047 /* The next two methods are part of NSServicesRequests informal protocol,
7048    supposedly called when a services menu item is chosen from this app.
7049    But this should not happen because we override the services menu with our
7050    own entries which call ns-perform-service.
7051    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7052    So let's at least stub them out until further investigation can be done. */
7054 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7056   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7057      be written into the buffer in place of the existing selection..
7058      ordinary service calls go through functions defined in ns-win.el */
7059   return NO;
7062 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7064   NSArray *typesDeclared;
7065   Lisp_Object val;
7067   /* We only support NSStringPboardType */
7068   if ([types containsObject:NSStringPboardType] == NO) {
7069     return NO;
7070   }
7072   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7073   if (CONSP (val) && SYMBOLP (XCAR (val)))
7074     {
7075       val = XCDR (val);
7076       if (CONSP (val) && NILP (XCDR (val)))
7077         val = XCAR (val);
7078     }
7079   if (! STRINGP (val))
7080     return NO;
7082   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7083   [pb declareTypes:typesDeclared owner:nil];
7084   ns_string_to_pasteboard (pb, val);
7085   return YES;
7089 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7090    (gives a miniaturized version of the window); currently we use the latter for
7091    frames whose active buffer doesn't correspond to any file
7092    (e.g., '*scratch*') */
7093 - setMiniwindowImage: (BOOL) setMini
7095   id image = [[self window] miniwindowImage];
7096   NSTRACE (setMiniwindowImage);
7098   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7099      about "AppleDockIconEnabled" notwithstanding, however the set message
7100      below has its effect nonetheless. */
7101   if (image != emacsframe->output_data.ns->miniimage)
7102     {
7103       if (image && [image isKindOfClass: [EmacsImage class]])
7104         [image release];
7105       [[self window] setMiniwindowImage:
7106                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7107     }
7109   return self;
7113 - (void) setRows: (int) r andColumns: (int) c
7115   rows = r;
7116   cols = c;
7119 @end  /* EmacsView */
7123 /* ==========================================================================
7125     EmacsWindow implementation
7127    ========================================================================== */
7129 @implementation EmacsWindow
7131 #ifdef NS_IMPL_COCOA
7132 - (id)accessibilityAttributeValue:(NSString *)attribute
7134   Lisp_Object str = Qnil;
7135   struct frame *f = SELECTED_FRAME ();
7136   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7138   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7139     return NSAccessibilityTextFieldRole;
7141   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7142       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7143     {
7144       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7145     }
7146   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7147     {
7148       if (! NILP (BVAR (curbuf, mark_active)))
7149           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7151       if (NILP (str))
7152         {
7153           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7154           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7155           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7157           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7158             str = make_uninit_multibyte_string (range, byte_range);
7159           else
7160             str = make_uninit_string (range);
7161           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7162              Is this a problem?  */
7163           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7164         }
7165     }
7168   if (! NILP (str))
7169     {
7170       if (CONSP (str) && SYMBOLP (XCAR (str)))
7171         {
7172           str = XCDR (str);
7173           if (CONSP (str) && NILP (XCDR (str)))
7174             str = XCAR (str);
7175         }
7176       if (STRINGP (str))
7177         {
7178           const char *utfStr = SSDATA (str);
7179           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7180           return nsStr;
7181         }
7182     }
7184   return [super accessibilityAttributeValue:attribute];
7186 #endif /* NS_IMPL_COCOA */
7188 /* If we have multiple monitors, one above the other, we don't want to
7189    restrict the height to just one monitor.  So we override this.  */
7190 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7192   /* When making the frame visible for the first time or if there is just
7193      one screen, we want to constrain.  Other times not.  */
7194   NSArray *screens = [NSScreen screens];
7195   NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7196   NSTRACE (constrainFrameRect);
7197   NSTRACE_RECT ("input", frameRect);
7199   if (ns_menu_bar_should_be_hidden ())
7200     return frameRect;
7202   if (nr_screens == 1)
7203     return [super constrainFrameRect:frameRect toScreen:screen];
7205 #ifdef NS_IMPL_COCOA
7206 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7207   // If separate spaces is on, it is like each screen is independent.  There is
7208   // no spanning of frames across screens.
7209   if ([NSScreen screensHaveSeparateSpaces])
7210     return [super constrainFrameRect:frameRect toScreen:screen];
7211 #endif
7212 #endif
7214   for (i = 0; i < nr_screens; ++i)
7215     {
7216       NSScreen *s = [screens objectAtIndex: i];
7217       NSRect scrrect = [s frame];
7218       NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7220       if (intersect.size.width > 0 || intersect.size.height > 0)
7221         ++nr_eff_screens;
7222     }
7224   if (nr_eff_screens == 1)
7225     return [super constrainFrameRect:frameRect toScreen:screen];
7227   /* The default implementation does two things 1) ensure that the top
7228      of the rectangle is below the menu bar (or below the top of the
7229      screen) and 2) resizes windows larger than the screen. As we
7230      don't want the latter, a smaller rectangle is used. */
7231 #define FAKE_HEIGHT 64
7232   float old_top = frameRect.origin.y + frameRect.size.height;
7233   NSRect r;
7234   r.size.height = FAKE_HEIGHT;
7235   r.size.width = frameRect.size.width;
7236   r.origin.x = frameRect.origin.x;
7237   r.origin.y = old_top - FAKE_HEIGHT;
7239   NSTRACE_RECT ("input to super", r);
7241   r = [super constrainFrameRect:r toScreen:screen];
7243   NSTRACE_RECT ("output from super", r);
7245   float new_top = r.origin.y + FAKE_HEIGHT;
7246   if (new_top < old_top)
7247   {
7248     frameRect.origin.y = new_top - frameRect.size.height;
7249   }
7251   NSTRACE_RECT ("output", frameRect);
7253   return frameRect;
7254 #undef FAKE_HEIGHT
7257 @end /* EmacsWindow */
7260 @implementation EmacsFSWindow
7262 - (BOOL)canBecomeKeyWindow
7264   return YES;
7267 - (BOOL)canBecomeMainWindow
7269   return YES;
7272 @end
7274 /* ==========================================================================
7276     EmacsScroller implementation
7278    ========================================================================== */
7281 @implementation EmacsScroller
7283 /* for repeat button push */
7284 #define SCROLL_BAR_FIRST_DELAY 0.5
7285 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7287 + (CGFloat) scrollerWidth
7289   /* TODO: if we want to allow variable widths, this is the place to do it,
7290            however neither GNUstep nor Cocoa support it very well */
7291   CGFloat r;
7292 #if !defined (NS_IMPL_COCOA) || \
7293   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7294   r = [NSScroller scrollerWidth];
7295 #else
7296   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7297                                 scrollerStyle: NSScrollerStyleLegacy];
7298 #endif
7299   return r;
7303 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7305   NSTRACE (EmacsScroller_initFrame);
7307   r.size.width = [EmacsScroller scrollerWidth];
7308   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7309   [self setContinuous: YES];
7310   [self setEnabled: YES];
7312   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7313      locked against the top and bottom edges, and right edge on OS X, where
7314      scrollers are on right. */
7315 #ifdef NS_IMPL_GNUSTEP
7316   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7317 #else
7318   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7319 #endif
7321   window = XWINDOW (nwin);
7322   condemned = NO;
7323   pixel_height = NSHeight (r);
7324   if (pixel_height == 0) pixel_height = 1;
7325   min_portion = 20 / pixel_height;
7327   frame = XFRAME (window->frame);
7328   if (FRAME_LIVE_P (frame))
7329     {
7330       int i;
7331       EmacsView *view = FRAME_NS_VIEW (frame);
7332       NSView *sview = [[view window] contentView];
7333       NSArray *subs = [sview subviews];
7335       /* disable optimization stopping redraw of other scrollbars */
7336       view->scrollbarsNeedingUpdate = 0;
7337       for (i =[subs count]-1; i >= 0; i--)
7338         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7339           view->scrollbarsNeedingUpdate++;
7340       [sview addSubview: self];
7341     }
7343 /*  [self setFrame: r]; */
7345   return self;
7349 - (void)setFrame: (NSRect)newRect
7351   NSTRACE (EmacsScroller_setFrame);
7352 /*  block_input (); */
7353   pixel_height = NSHeight (newRect);
7354   if (pixel_height == 0) pixel_height = 1;
7355   min_portion = 20 / pixel_height;
7356   [super setFrame: newRect];
7357 /*  unblock_input (); */
7361 - (void)dealloc
7363   NSTRACE (EmacsScroller_dealloc);
7364   if (window)
7365     wset_vertical_scroll_bar (window, Qnil);
7366   window = 0;
7367   [super dealloc];
7371 - condemn
7373   NSTRACE (condemn);
7374   condemned =YES;
7375   return self;
7379 - reprieve
7381   NSTRACE (reprieve);
7382   condemned =NO;
7383   return self;
7387 -(bool)judge
7389   NSTRACE (judge);
7390   bool ret = condemned;
7391   if (condemned)
7392     {
7393       EmacsView *view;
7394       block_input ();
7395       /* ensure other scrollbar updates after deletion */
7396       view = (EmacsView *)FRAME_NS_VIEW (frame);
7397       if (view != nil)
7398         view->scrollbarsNeedingUpdate++;
7399       if (window)
7400         wset_vertical_scroll_bar (window, Qnil);
7401       window = 0;
7402       [self removeFromSuperview];
7403       [self release];
7404       unblock_input ();
7405     }
7406   return ret;
7410 - (void)resetCursorRects
7412   NSRect visible = [self visibleRect];
7413   NSTRACE (resetCursorRects);
7415   if (!NSIsEmptyRect (visible))
7416     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7417   [[NSCursor arrowCursor] setOnMouseEntered: YES];
7421 - (int) checkSamePosition: (int) position portion: (int) portion
7422                     whole: (int) whole
7424   return em_position ==position && em_portion ==portion && em_whole ==whole
7425     && portion != whole; /* needed for resize empty buf */
7429 - setPosition: (int)position portion: (int)portion whole: (int)whole
7431   NSTRACE (setPosition);
7433   em_position = position;
7434   em_portion = portion;
7435   em_whole = whole;
7437   if (portion >= whole)
7438     {
7439 #ifdef NS_IMPL_COCOA
7440       [self setKnobProportion: 1.0];
7441       [self setDoubleValue: 1.0];
7442 #else
7443       [self setFloatValue: 0.0 knobProportion: 1.0];
7444 #endif
7445     }
7446   else
7447     {
7448       float pos;
7449       CGFloat por;
7450       portion = max ((float)whole*min_portion/pixel_height, portion);
7451       pos = (float)position / (whole - portion);
7452       por = (CGFloat)portion/whole;
7453 #ifdef NS_IMPL_COCOA
7454       [self setKnobProportion: por];
7455       [self setDoubleValue: pos];
7456 #else
7457       [self setFloatValue: pos knobProportion: por];
7458 #endif
7459     }
7461   return self;
7464 /* set up emacs_event */
7465 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7467   Lisp_Object win;
7468   if (!emacs_event)
7469     return;
7471   emacs_event->part = last_hit_part;
7472   emacs_event->code = 0;
7473   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7474   XSETWINDOW (win, window);
7475   emacs_event->frame_or_window = win;
7476   emacs_event->timestamp = EV_TIMESTAMP (e);
7477   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7478   emacs_event->arg = Qnil;
7479   XSETINT (emacs_event->x, loc * pixel_height);
7480   XSETINT (emacs_event->y, pixel_height-20);
7482   if (q_event_ptr)
7483     {
7484       n_emacs_events_pending++;
7485       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7486     }
7487   else
7488     hold_event (emacs_event);
7489   EVENT_INIT (*emacs_event);
7490   ns_send_appdefined (-1);
7494 /* called manually thru timer to implement repeated button action w/hold-down */
7495 - repeatScroll: (NSTimer *)scrollEntry
7497   NSEvent *e = [[self window] currentEvent];
7498   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7499   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7501   /* clear timer if need be */
7502   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7503     {
7504         [scroll_repeat_entry invalidate];
7505         [scroll_repeat_entry release];
7506         scroll_repeat_entry = nil;
7508         if (inKnob)
7509           return self;
7511         scroll_repeat_entry
7512           = [[NSTimer scheduledTimerWithTimeInterval:
7513                         SCROLL_BAR_CONTINUOUS_DELAY
7514                                             target: self
7515                                           selector: @selector (repeatScroll:)
7516                                           userInfo: 0
7517                                            repeats: YES]
7518               retain];
7519     }
7521   [self sendScrollEventAtLoc: 0 fromEvent: e];
7522   return self;
7526 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7527    mouseDragged events without going into a modal loop. */
7528 - (void)mouseDown: (NSEvent *)e
7530   NSRect sr, kr;
7531   /* hitPart is only updated AFTER event is passed on */
7532   NSScrollerPart part = [self testPart: [e locationInWindow]];
7533   CGFloat inc = 0.0, loc, kloc, pos;
7534   int edge = 0;
7536   NSTRACE (EmacsScroller_mouseDown);
7538   switch (part)
7539     {
7540     case NSScrollerDecrementPage:
7541         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7542     case NSScrollerIncrementPage:
7543         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7544     case NSScrollerDecrementLine:
7545       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7546     case NSScrollerIncrementLine:
7547       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7548     case NSScrollerKnob:
7549       last_hit_part = scroll_bar_handle; break;
7550     case NSScrollerKnobSlot:  /* GNUstep-only */
7551       last_hit_part = scroll_bar_move_ratio; break;
7552     default:  /* NSScrollerNoPart? */
7553       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7554                (long) part);
7555       return;
7556     }
7558   if (inc != 0.0)
7559     {
7560       pos = 0;      /* ignored */
7562       /* set a timer to repeat, as we can't let superclass do this modally */
7563       scroll_repeat_entry
7564         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7565                                             target: self
7566                                           selector: @selector (repeatScroll:)
7567                                           userInfo: 0
7568                                            repeats: YES]
7569             retain];
7570     }
7571   else
7572     {
7573       /* handle, or on GNUstep possibly slot */
7574       NSEvent *fake_event;
7576       /* compute float loc in slot and mouse offset on knob */
7577       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7578                       toView: nil];
7579       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7580       if (loc <= 0.0)
7581         {
7582           loc = 0.0;
7583           edge = -1;
7584         }
7585       else if (loc >= NSHeight (sr))
7586         {
7587           loc = NSHeight (sr);
7588           edge = 1;
7589         }
7591       if (edge)
7592         kloc = 0.5 * edge;
7593       else
7594         {
7595           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7596                           toView: nil];
7597           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7598         }
7599       last_mouse_offset = kloc;
7601       /* if knob, tell emacs a location offset by knob pos
7602          (to indicate top of handle) */
7603       if (part == NSScrollerKnob)
7604           pos = (loc - last_mouse_offset) / NSHeight (sr);
7605       else
7606         /* else this is a slot click on GNUstep: go straight there */
7607         pos = loc / NSHeight (sr);
7609       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7610       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7611                                       location: [e locationInWindow]
7612                                  modifierFlags: [e modifierFlags]
7613                                      timestamp: [e timestamp]
7614                                   windowNumber: [e windowNumber]
7615                                        context: [e context]
7616                                    eventNumber: [e eventNumber]
7617                                     clickCount: [e clickCount]
7618                                       pressure: [e pressure]];
7619       [super mouseUp: fake_event];
7620     }
7622   if (part != NSScrollerKnob)
7623     [self sendScrollEventAtLoc: pos fromEvent: e];
7627 /* Called as we manually track scroller drags, rather than superclass. */
7628 - (void)mouseDragged: (NSEvent *)e
7630     NSRect sr;
7631     double loc, pos;
7633     NSTRACE (EmacsScroller_mouseDragged);
7635       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7636                       toView: nil];
7637       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7639       if (loc <= 0.0)
7640         {
7641           loc = 0.0;
7642         }
7643       else if (loc >= NSHeight (sr) + last_mouse_offset)
7644         {
7645           loc = NSHeight (sr) + last_mouse_offset;
7646         }
7648       pos = (loc - last_mouse_offset) / NSHeight (sr);
7649       [self sendScrollEventAtLoc: pos fromEvent: e];
7653 - (void)mouseUp: (NSEvent *)e
7655   if (scroll_repeat_entry)
7656     {
7657       [scroll_repeat_entry invalidate];
7658       [scroll_repeat_entry release];
7659       scroll_repeat_entry = nil;
7660     }
7661   last_hit_part = scroll_bar_above_handle;
7665 /* treat scrollwheel events in the bar as though they were in the main window */
7666 - (void) scrollWheel: (NSEvent *)theEvent
7668   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7669   [view mouseDown: theEvent];
7672 @end  /* EmacsScroller */
7675 #ifdef NS_IMPL_GNUSTEP
7676 /* Dummy class to get rid of startup warnings.  */
7677 @implementation EmacsDocument
7679 @end
7680 #endif
7683 /* ==========================================================================
7685    Font-related functions; these used to be in nsfaces.m
7687    ========================================================================== */
7690 Lisp_Object
7691 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7693   struct font *font = XFONT_OBJECT (font_object);
7694   EmacsView *view = FRAME_NS_VIEW (f);
7695   int font_ascent, font_descent;
7697   if (fontset < 0)
7698     fontset = fontset_from_font (font_object);
7699   FRAME_FONTSET (f) = fontset;
7701   if (FRAME_FONT (f) == font)
7702     /* This font is already set in frame F.  There's nothing more to
7703        do.  */
7704     return font_object;
7706   FRAME_FONT (f) = font;
7708   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7709   FRAME_COLUMN_WIDTH (f) = font->average_width;
7710   get_font_ascent_descent (font, &font_ascent, &font_descent);
7711   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
7713   /* Compute the scroll bar width in character columns.  */
7714   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7715     {
7716       int wid = FRAME_COLUMN_WIDTH (f);
7717       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7718         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7719     }
7720   else
7721     {
7722       int wid = FRAME_COLUMN_WIDTH (f);
7723       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7724     }
7726   /* Compute the scroll bar height in character lines.  */
7727   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7728     {
7729       int height = FRAME_LINE_HEIGHT (f);
7730       FRAME_CONFIG_SCROLL_BAR_LINES (f)
7731         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7732     }
7733   else
7734     {
7735       int height = FRAME_LINE_HEIGHT (f);
7736       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7737     }
7739   /* Now make the frame display the given font.  */
7740   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7741     x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7742                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7744   return font_object;
7748 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7749 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7750          in 1.43. */
7752 const char *
7753 ns_xlfd_to_fontname (const char *xlfd)
7754 /* --------------------------------------------------------------------------
7755     Convert an X font name (XLFD) to an NS font name.
7756     Only family is used.
7757     The string returned is temporarily allocated.
7758    -------------------------------------------------------------------------- */
7760   char *name = xmalloc (180);
7761   int i, len;
7762   const char *ret;
7764   if (!strncmp (xlfd, "--", 2))
7765     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7766   else
7767     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7769   /* stopgap for malformed XLFD input */
7770   if (strlen (name) == 0)
7771     strcpy (name, "Monaco");
7773   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7774      also uppercase after '-' or ' ' */
7775   name[0] = c_toupper (name[0]);
7776   for (len =strlen (name), i =0; i<len; i++)
7777     {
7778       if (name[i] == '$')
7779         {
7780           name[i] = '-';
7781           if (i+1<len)
7782             name[i+1] = c_toupper (name[i+1]);
7783         }
7784       else if (name[i] == '_')
7785         {
7786           name[i] = ' ';
7787           if (i+1<len)
7788             name[i+1] = c_toupper (name[i+1]);
7789         }
7790     }
7791 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7792   ret = [[NSString stringWithUTF8String: name] UTF8String];
7793   xfree (name);
7794   return ret;
7798 void
7799 syms_of_nsterm (void)
7801   NSTRACE (syms_of_nsterm);
7803   ns_antialias_threshold = 10.0;
7805   /* from 23+ we need to tell emacs what modifiers there are.. */
7806   DEFSYM (Qmodifier_value, "modifier-value");
7807   DEFSYM (Qalt, "alt");
7808   DEFSYM (Qhyper, "hyper");
7809   DEFSYM (Qmeta, "meta");
7810   DEFSYM (Qsuper, "super");
7811   DEFSYM (Qcontrol, "control");
7812   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7814   DEFSYM (Qfile, "file");
7815   DEFSYM (Qurl, "url");
7817   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7818   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7819   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7820   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7821   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7823   DEFVAR_LISP ("ns-input-file", ns_input_file,
7824               "The file specified in the last NS event.");
7825   ns_input_file =Qnil;
7827   DEFVAR_LISP ("ns-working-text", ns_working_text,
7828               "String for visualizing working composition sequence.");
7829   ns_working_text =Qnil;
7831   DEFVAR_LISP ("ns-input-font", ns_input_font,
7832               "The font specified in the last NS event.");
7833   ns_input_font =Qnil;
7835   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7836               "The fontsize specified in the last NS event.");
7837   ns_input_fontsize =Qnil;
7839   DEFVAR_LISP ("ns-input-line", ns_input_line,
7840                "The line specified in the last NS event.");
7841   ns_input_line =Qnil;
7843   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7844                "The service name specified in the last NS event.");
7845   ns_input_spi_name =Qnil;
7847   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7848                "The service argument specified in the last NS event.");
7849   ns_input_spi_arg =Qnil;
7851   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7852                "This variable describes the behavior of the alternate or option key.\n\
7853 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7854 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7855 at all, allowing it to be used at a lower level for accented character entry.");
7856   ns_alternate_modifier = Qmeta;
7858   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7859                "This variable describes the behavior of the right alternate or option key.\n\
7860 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7861 Set to left means be the same key as `ns-alternate-modifier'.\n\
7862 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7863 at all, allowing it to be used at a lower level for accented character entry.");
7864   ns_right_alternate_modifier = Qleft;
7866   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7867                "This variable describes the behavior of the command key.\n\
7868 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7869   ns_command_modifier = Qsuper;
7871   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7872                "This variable describes the behavior of the right command key.\n\
7873 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7874 Set to left means be the same key as `ns-command-modifier'.\n\
7875 Set to none means that the command / option key is not interpreted by Emacs\n\
7876 at all, allowing it to be used at a lower level for accented character entry.");
7877   ns_right_command_modifier = Qleft;
7879   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7880                "This variable describes the behavior of the control key.\n\
7881 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7882   ns_control_modifier = Qcontrol;
7884   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7885                "This variable describes the behavior of the right control key.\n\
7886 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7887 Set to left means be the same key as `ns-control-modifier'.\n\
7888 Set to none means that the control / option key is not interpreted by Emacs\n\
7889 at all, allowing it to be used at a lower level for accented character entry.");
7890   ns_right_control_modifier = Qleft;
7892   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7893                "This variable describes the behavior of the function key (on laptops).\n\
7894 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7895 Set to none means that the function key is not interpreted by Emacs at all,\n\
7896 allowing it to be used at a lower level for accented character entry.");
7897   ns_function_modifier = Qnone;
7899   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7900                "Non-nil (the default) means to render text antialiased.");
7901   ns_antialias_text = Qt;
7903   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7904                "Whether to confirm application quit using dialog.");
7905   ns_confirm_quit = Qnil;
7907   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7908                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7909 Only works on OSX 10.6 or later.  */);
7910   ns_auto_hide_menu_bar = Qnil;
7912   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7913      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7914 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7915 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7916 Default is t for OSX >= 10.7, nil otherwise.  */);
7917 #ifdef HAVE_NATIVE_FS
7918   ns_use_native_fullscreen = YES;
7919 #else
7920   ns_use_native_fullscreen = NO;
7921 #endif
7922   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7924   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7925      doc: /*Non-nil means use animation on non-native fullscreen.
7926 For native fullscreen, this does nothing.
7927 Default is nil.  */);
7928   ns_use_fullscreen_animation = NO;
7930   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7931      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7932 Note that this does not apply to images.
7933 This variable is ignored on OSX < 10.7 and GNUstep.  */);
7934   ns_use_srgb_colorspace = YES;
7936   /* TODO: move to common code */
7937   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7938                doc: /* Which toolkit scroll bars Emacs uses, if any.
7939 A value of nil means Emacs doesn't use toolkit scroll bars.
7940 With the X Window system, the value is a symbol describing the
7941 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7942 With MS Windows or Nextstep, the value is t.  */);
7943   Vx_toolkit_scroll_bars = Qt;
7945   DEFVAR_BOOL ("x-use-underline-position-properties",
7946                x_use_underline_position_properties,
7947      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7948 A value of nil means ignore them.  If you encounter fonts with bogus
7949 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7950 to 4.1, set this to nil. */);
7951   x_use_underline_position_properties = 0;
7953   DEFVAR_BOOL ("x-underline-at-descent-line",
7954                x_underline_at_descent_line,
7955      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7956 A value of nil means to draw the underline according to the value of the
7957 variable `x-use-underline-position-properties', which is usually at the
7958 baseline level.  The default value is nil.  */);
7959   x_underline_at_descent_line = 0;
7961   /* Tell Emacs about this window system.  */
7962   Fprovide (Qns, Qnil);
7964   DEFSYM (Qcocoa, "cocoa");
7965   DEFSYM (Qgnustep, "gnustep");
7967 #ifdef NS_IMPL_COCOA
7968   Fprovide (Qcocoa, Qnil);
7969   syms_of_macfont ();
7970 #else
7971   Fprovide (Qgnustep, Qnil);
7972   syms_of_nsfont ();
7973 #endif