CEDET (srecode-insert-fcn): Fix use of oref on a class
[emacs.git] / src / nsterm.m
blob187086cf8267014ff83e85bb431d53e227b4a8f2
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;
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;
2097 static void
2098 ns_scroll_run (struct window *w, struct run *run)
2099 /* --------------------------------------------------------------------------
2100     External (RIF):  Insert or delete n lines at line vpos
2101    -------------------------------------------------------------------------- */
2103   struct frame *f = XFRAME (w->frame);
2104   int x, y, width, height, from_y, to_y, bottom_y;
2106   NSTRACE (ns_scroll_run);
2108   /* begin copy from other terms */
2109   /* Get frame-relative bounding box of the text display area of W,
2110      without mode lines.  Include in this box the left and right
2111      fringe of W.  */
2112   window_box (w, ANY_AREA, &x, &y, &width, &height);
2114   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2115   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2116   bottom_y = y + height;
2118   if (to_y < from_y)
2119     {
2120       /* Scrolling up.  Make sure we don't copy part of the mode
2121          line at the bottom.  */
2122       if (from_y + run->height > bottom_y)
2123         height = bottom_y - from_y;
2124       else
2125         height = run->height;
2126     }
2127   else
2128     {
2129       /* Scrolling down.  Make sure we don't copy over the mode line.
2130          at the bottom.  */
2131       if (to_y + run->height > bottom_y)
2132         height = bottom_y - to_y;
2133       else
2134         height = run->height;
2135     }
2136   /* end copy from other terms */
2138   if (height == 0)
2139       return;
2141   block_input ();
2143   x_clear_cursor (w);
2145   {
2146     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2147     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2148     NSPoint dstOrigin = NSMakePoint (x, to_y);
2150     ns_focus (f, &dstRect, 1);
2151     NSCopyBits (0, srcRect , dstOrigin);
2152     ns_unfocus (f);
2153   }
2155   unblock_input ();
2159 static void
2160 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2161 /* --------------------------------------------------------------------------
2162     External (RIF): preparatory to fringe update after text was updated
2163    -------------------------------------------------------------------------- */
2165   struct frame *f;
2166   int width, height;
2168   NSTRACE (ns_after_update_window_line);
2170   /* begin copy from other terms */
2171   eassert (w);
2173   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2174     desired_row->redraw_fringe_bitmaps_p = 1;
2176   /* When a window has disappeared, make sure that no rest of
2177      full-width rows stays visible in the internal border.  */
2178   if (windows_or_buffers_changed
2179       && desired_row->full_width_p
2180       && (f = XFRAME (w->frame),
2181           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2182           width != 0)
2183       && (height = desired_row->visible_height,
2184           height > 0))
2185     {
2186       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2188       block_input ();
2189       ns_clear_frame_area (f, 0, y, width, height);
2190       ns_clear_frame_area (f,
2191                            FRAME_PIXEL_WIDTH (f) - width,
2192                            y, width, height);
2193       unblock_input ();
2194     }
2198 static void
2199 ns_shift_glyphs_for_insert (struct frame *f,
2200                            int x, int y, int width, int height,
2201                            int shift_by)
2202 /* --------------------------------------------------------------------------
2203     External (RIF): copy an area horizontally, don't worry about clearing src
2204    -------------------------------------------------------------------------- */
2206   NSRect srcRect = NSMakeRect (x, y, width, height);
2207   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2208   NSPoint dstOrigin = dstRect.origin;
2210   NSTRACE (ns_shift_glyphs_for_insert);
2212   ns_focus (f, &dstRect, 1);
2213   NSCopyBits (0, srcRect, dstOrigin);
2214   ns_unfocus (f);
2219 /* ==========================================================================
2221     Character encoding and metrics
2223    ========================================================================== */
2226 static void
2227 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2228 /* --------------------------------------------------------------------------
2229      External (RIF); compute left/right overhang of whole string and set in s
2230    -------------------------------------------------------------------------- */
2232   struct font *font = s->font;
2234   if (s->char2b)
2235     {
2236       struct font_metrics metrics;
2237       unsigned int codes[2];
2238       codes[0] = *(s->char2b);
2239       codes[1] = *(s->char2b + s->nchars - 1);
2241       font->driver->text_extents (font, codes, 2, &metrics);
2242       s->left_overhang = -metrics.lbearing;
2243       s->right_overhang
2244         = metrics.rbearing > metrics.width
2245         ? metrics.rbearing - metrics.width : 0;
2246     }
2247   else
2248     {
2249       s->left_overhang = 0;
2250       if (EQ (font->driver->type, Qns))
2251         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2252           FONT_HEIGHT (font) * 0.2 : 0;
2253       else
2254         s->right_overhang = 0;
2255     }
2260 /* ==========================================================================
2262     Fringe and cursor drawing
2264    ========================================================================== */
2267 extern int max_used_fringe_bitmap;
2268 static void
2269 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2270                       struct draw_fringe_bitmap_params *p)
2271 /* --------------------------------------------------------------------------
2272     External (RIF); fringe-related
2273    -------------------------------------------------------------------------- */
2275   struct frame *f = XFRAME (WINDOW_FRAME (w));
2276   struct face *face = p->face;
2277   static EmacsImage **bimgs = NULL;
2278   static int nBimgs = 0;
2280   /* grow bimgs if needed */
2281   if (nBimgs < max_used_fringe_bitmap)
2282     {
2283       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2284       memset (bimgs + nBimgs, 0,
2285               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2286       nBimgs = max_used_fringe_bitmap;
2287     }
2289   /* Must clip because of partially visible lines.  */
2290   ns_clip_to_row (w, row, ANY_AREA, YES);
2292   if (!p->overlay_p)
2293     {
2294       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2296       if (bx >= 0 && nx > 0)
2297         {
2298           NSRect r = NSMakeRect (bx, by, nx, ny);
2299           NSRectClip (r);
2300           [ns_lookup_indexed_color (face->background, f) set];
2301           NSRectFill (r);
2302         }
2303     }
2305   if (p->which)
2306     {
2307       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2308       EmacsImage *img = bimgs[p->which - 1];
2310       if (!img)
2311         {
2312           unsigned short *bits = p->bits + p->dh;
2313           int len = p->h;
2314           int i;
2315           unsigned char *cbits = xmalloc (len);
2317           for (i = 0; i < len; i++)
2318             cbits[i] = ~(bits[i] & 0xff);
2319           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2320                                            flip: NO];
2321           bimgs[p->which - 1] = img;
2322           xfree (cbits);
2323         }
2325       NSRectClip (r);
2326       /* Since we composite the bitmap instead of just blitting it, we need
2327          to erase the whole background. */
2328       [ns_lookup_indexed_color(face->background, f) set];
2329       NSRectFill (r);
2331       {
2332         NSColor *bm_color;
2333         if (!p->cursor_p)
2334           bm_color = ns_lookup_indexed_color(face->foreground, f);
2335         else if (p->overlay_p)
2336           bm_color = ns_lookup_indexed_color(face->background, f);
2337         else
2338           bm_color = f->output_data.ns->cursor_color;
2339         [img setXBMColor: bm_color];
2340       }
2342 #ifdef NS_IMPL_COCOA
2343       [img drawInRect: r
2344               fromRect: NSZeroRect
2345              operation: NSCompositeSourceOver
2346               fraction: 1.0
2347            respectFlipped: YES
2348                 hints: nil];
2349 #else
2350       {
2351         NSPoint pt = r.origin;
2352         pt.y += p->h;
2353         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2354       }
2355 #endif
2356     }
2357   ns_unfocus (f);
2361 static void
2362 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2363                        int x, int y, enum text_cursor_kinds cursor_type,
2364                        int cursor_width, bool on_p, bool active_p)
2365 /* --------------------------------------------------------------------------
2366      External call (RIF): draw cursor.
2367      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2368    -------------------------------------------------------------------------- */
2370   NSRect r, s;
2371   int fx, fy, h, cursor_height;
2372   struct frame *f = WINDOW_XFRAME (w);
2373   struct glyph *phys_cursor_glyph;
2374   struct glyph *cursor_glyph;
2375   struct face *face;
2376   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2378   /* If cursor is out of bounds, don't draw garbage.  This can happen
2379      in mini-buffer windows when switching between echo area glyphs
2380      and mini-buffer.  */
2382   NSTRACE (dumpcursor);
2384   if (!on_p)
2385     return;
2387   w->phys_cursor_type = cursor_type;
2388   w->phys_cursor_on_p = on_p;
2390   if (cursor_type == NO_CURSOR)
2391     {
2392       w->phys_cursor_width = 0;
2393       return;
2394     }
2396   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2397     {
2398       if (glyph_row->exact_window_width_line_p
2399           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2400         {
2401           glyph_row->cursor_in_fringe_p = 1;
2402           draw_fringe_bitmap (w, glyph_row, 0);
2403         }
2404       return;
2405     }
2407   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2408      (other terminals do it the other way round).  We must set
2409      w->phys_cursor_width to the cursor width.  For bar cursors, that
2410      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2411   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2413   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2414      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2415   if (cursor_type == BAR_CURSOR)
2416     {
2417       if (cursor_width < 1)
2418         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2419       w->phys_cursor_width = cursor_width;
2420     }
2421   /* If we have an HBAR, "cursor_width" MAY specify height. */
2422   else if (cursor_type == HBAR_CURSOR)
2423     {
2424       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2425       if (cursor_height > glyph_row->height)
2426         cursor_height = glyph_row->height;
2427       if (h > cursor_height) // Cursor smaller than line height, move down
2428         fy += h - cursor_height;
2429       h = cursor_height;
2430     }
2432   r.origin.x = fx, r.origin.y = fy;
2433   r.size.height = h;
2434   r.size.width = w->phys_cursor_width;
2436   /* TODO: only needed in rare cases with last-resort font in HELLO..
2437      should we do this more efficiently? */
2438   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2441   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2442   if (face && NS_FACE_BACKGROUND (face)
2443       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2444     {
2445       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2446       hollow_color = FRAME_CURSOR_COLOR (f);
2447     }
2448   else
2449     [FRAME_CURSOR_COLOR (f) set];
2451 #ifdef NS_IMPL_COCOA
2452   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2453            atomic.  Cleaner ways of doing this should be investigated.
2454            One way would be to set a global variable DRAWING_CURSOR
2455            when making the call to draw_phys..(), don't focus in that
2456            case, then move the ns_unfocus() here after that call. */
2457   NSDisableScreenUpdates ();
2458 #endif
2460   switch (cursor_type)
2461     {
2462     case NO_CURSOR:
2463       break;
2464     case FILLED_BOX_CURSOR:
2465       NSRectFill (r);
2466       break;
2467     case HOLLOW_BOX_CURSOR:
2468       NSRectFill (r);
2469       [hollow_color set];
2470       NSRectFill (NSInsetRect (r, 1, 1));
2471       [FRAME_CURSOR_COLOR (f) set];
2472       break;
2473     case HBAR_CURSOR:
2474       NSRectFill (r);
2475       break;
2476     case BAR_CURSOR:
2477       s = r;
2478       /* If the character under cursor is R2L, draw the bar cursor
2479          on the right of its glyph, rather than on the left.  */
2480       cursor_glyph = get_phys_cursor_glyph (w);
2481       if ((cursor_glyph->resolved_level & 1) != 0)
2482         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2484       NSRectFill (s);
2485       break;
2486     }
2487   ns_unfocus (f);
2489   /* draw the character under the cursor */
2490   if (cursor_type != NO_CURSOR)
2491     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2493 #ifdef NS_IMPL_COCOA
2494   NSEnableScreenUpdates ();
2495 #endif
2500 static void
2501 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2502 /* --------------------------------------------------------------------------
2503      External (RIF): Draw a vertical line.
2504    -------------------------------------------------------------------------- */
2506   struct frame *f = XFRAME (WINDOW_FRAME (w));
2507   struct face *face;
2508   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2510   NSTRACE (ns_draw_vertical_window_border);
2512   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2513   if (face)
2514       [ns_lookup_indexed_color(face->foreground, f) set];
2516   ns_focus (f, &r, 1);
2517   NSRectFill(r);
2518   ns_unfocus (f);
2522 static void
2523 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2524 /* --------------------------------------------------------------------------
2525      External (RIF): Draw a window divider.
2526    -------------------------------------------------------------------------- */
2528   struct frame *f = XFRAME (WINDOW_FRAME (w));
2529   struct face *face;
2530   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2532   NSTRACE (ns_draw_window_divider);
2534   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2535   if (face)
2536       [ns_lookup_indexed_color(face->foreground, f) set];
2538   ns_focus (f, &r, 1);
2539   NSRectFill(r);
2540   ns_unfocus (f);
2543 static void
2544 ns_show_hourglass (struct frame *f)
2546   /* TODO: add NSProgressIndicator to all frames.  */
2549 static void
2550 ns_hide_hourglass (struct frame *f)
2552   /* TODO: remove NSProgressIndicator from all frames.  */
2555 /* ==========================================================================
2557     Glyph drawing operations
2559    ========================================================================== */
2561 static int
2562 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2563 /* --------------------------------------------------------------------------
2564     Wrapper utility to account for internal border width on full-width lines,
2565     and allow top full-width rows to hit the frame top.  nr should be pointer
2566     to two successive NSRects.  Number of rects actually used is returned.
2567    -------------------------------------------------------------------------- */
2569   int n = get_glyph_string_clip_rects (s, nr, 2);
2570   return n;
2573 /* --------------------------------------------------------------------
2574    Draw a wavy line under glyph string s. The wave fills wave_height
2575    pixels from y.
2577                     x          wave_length = 2
2578                                  --
2579                 y    *   *   *   *   *
2580                      |* * * * * * * * *
2581     wave_height = 3  | *   *   *   *
2582   --------------------------------------------------------------------- */
2584 static void
2585 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2587   int wave_height = 3, wave_length = 2;
2588   int y, dx, dy, odd, xmax;
2589   NSPoint a, b;
2590   NSRect waveClip;
2592   dx = wave_length;
2593   dy = wave_height - 1;
2594   y =  s->ybase - wave_height + 3;
2595   xmax = x + width;
2597   /* Find and set clipping rectangle */
2598   waveClip = NSMakeRect (x, y, width, wave_height);
2599   [[NSGraphicsContext currentContext] saveGraphicsState];
2600   NSRectClip (waveClip);
2602   /* Draw the waves */
2603   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2604   b.x = a.x + dx;
2605   odd = (int)(a.x/dx) % 2;
2606   a.y = b.y = y + 0.5;
2608   if (odd)
2609     a.y += dy;
2610   else
2611     b.y += dy;
2613   while (a.x <= xmax)
2614     {
2615       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2616       a.x = b.x, a.y = b.y;
2617       b.x += dx, b.y = y + 0.5 + odd*dy;
2618       odd = !odd;
2619     }
2621   /* Restore previous clipping rectangle(s) */
2622   [[NSGraphicsContext currentContext] restoreGraphicsState];
2627 void
2628 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2629                          NSColor *defaultCol, CGFloat width, CGFloat x)
2630 /* --------------------------------------------------------------------------
2631    Draw underline, overline, and strike-through on glyph string s.
2632    -------------------------------------------------------------------------- */
2634   if (s->for_overlaps)
2635     return;
2637   /* Do underline. */
2638   if (face->underline_p)
2639     {
2640       if (s->face->underline_type == FACE_UNDER_WAVE)
2641         {
2642           if (face->underline_defaulted_p)
2643             [defaultCol set];
2644           else
2645             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2647           ns_draw_underwave (s, width, x);
2648         }
2649       else if (s->face->underline_type == FACE_UNDER_LINE)
2650         {
2652           NSRect r;
2653           unsigned long thickness, position;
2655           /* If the prev was underlined, match its appearance. */
2656           if (s->prev && s->prev->face->underline_p
2657               && s->prev->face->underline_type == FACE_UNDER_LINE
2658               && s->prev->underline_thickness > 0)
2659             {
2660               thickness = s->prev->underline_thickness;
2661               position = s->prev->underline_position;
2662             }
2663           else
2664             {
2665               struct font *font;
2666               unsigned long descent;
2668               font=s->font;
2669               descent = s->y + s->height - s->ybase;
2671               /* Use underline thickness of font, defaulting to 1. */
2672               thickness = (font && font->underline_thickness > 0)
2673                 ? font->underline_thickness : 1;
2675               /* Determine the offset of underlining from the baseline. */
2676               if (x_underline_at_descent_line)
2677                 position = descent - thickness;
2678               else if (x_use_underline_position_properties
2679                        && font && font->underline_position >= 0)
2680                 position = font->underline_position;
2681               else if (font)
2682                 position = lround (font->descent / 2);
2683               else
2684                 position = underline_minimum_offset;
2686               position = max (position, underline_minimum_offset);
2688               /* Ensure underlining is not cropped. */
2689               if (descent <= position)
2690                 {
2691                   position = descent - 1;
2692                   thickness = 1;
2693                 }
2694               else if (descent < position + thickness)
2695                 thickness = 1;
2696             }
2698           s->underline_thickness = thickness;
2699           s->underline_position = position;
2701           r = NSMakeRect (x, s->ybase + position, width, thickness);
2703           if (face->underline_defaulted_p)
2704             [defaultCol set];
2705           else
2706             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2707           NSRectFill (r);
2708         }
2709     }
2710   /* Do overline. We follow other terms in using a thickness of 1
2711      and ignoring overline_margin. */
2712   if (face->overline_p)
2713     {
2714       NSRect r;
2715       r = NSMakeRect (x, s->y, width, 1);
2717       if (face->overline_color_defaulted_p)
2718         [defaultCol set];
2719       else
2720         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2721       NSRectFill (r);
2722     }
2724   /* Do strike-through.  We follow other terms for thickness and
2725      vertical position.*/
2726   if (face->strike_through_p)
2727     {
2728       NSRect r;
2729       unsigned long dy;
2731       dy = lrint ((s->height - 1) / 2);
2732       r = NSMakeRect (x, s->y + dy, width, 1);
2734       if (face->strike_through_color_defaulted_p)
2735         [defaultCol set];
2736       else
2737         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2738       NSRectFill (r);
2739     }
2742 static void
2743 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2744              char left_p, char right_p)
2745 /* --------------------------------------------------------------------------
2746     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2747     Note we can't just use an NSDrawRect command, because of the possibility
2748     of some sides not being drawn, and because the rect will be filled.
2749    -------------------------------------------------------------------------- */
2751   NSRect s = r;
2752   [col set];
2754   /* top, bottom */
2755   s.size.height = thickness;
2756   NSRectFill (s);
2757   s.origin.y += r.size.height - thickness;
2758   NSRectFill (s);
2760   s.size.height = r.size.height;
2761   s.origin.y = r.origin.y;
2763   /* left, right (optional) */
2764   s.size.width = thickness;
2765   if (left_p)
2766     NSRectFill (s);
2767   if (right_p)
2768     {
2769       s.origin.x += r.size.width - thickness;
2770       NSRectFill (s);
2771     }
2775 static void
2776 ns_draw_relief (NSRect r, int thickness, char raised_p,
2777                char top_p, char bottom_p, char left_p, char right_p,
2778                struct glyph_string *s)
2779 /* --------------------------------------------------------------------------
2780     Draw a relief rect inside r, optionally leaving some sides open.
2781     Note we can't just use an NSDrawBezel command, because of the possibility
2782     of some sides not being drawn, and because the rect will be filled.
2783    -------------------------------------------------------------------------- */
2785   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2786   NSColor *newBaseCol = nil;
2787   NSRect sr = r;
2789   NSTRACE (ns_draw_relief);
2791   /* set up colors */
2793   if (s->face->use_box_color_for_shadows_p)
2794     {
2795       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2796     }
2797 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2798            && s->img->pixmap
2799            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2800        {
2801          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2802        } */
2803   else
2804     {
2805       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2806     }
2808   if (newBaseCol == nil)
2809     newBaseCol = [NSColor grayColor];
2811   if (newBaseCol != baseCol)  /* TODO: better check */
2812     {
2813       [baseCol release];
2814       baseCol = [newBaseCol retain];
2815       [lightCol release];
2816       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2817       [darkCol release];
2818       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2819     }
2821   [(raised_p ? lightCol : darkCol) set];
2823   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2825   /* top */
2826   sr.size.height = thickness;
2827   if (top_p) NSRectFill (sr);
2829   /* left */
2830   sr.size.height = r.size.height;
2831   sr.size.width = thickness;
2832   if (left_p) NSRectFill (sr);
2834   [(raised_p ? darkCol : lightCol) set];
2836   /* bottom */
2837   sr.size.width = r.size.width;
2838   sr.size.height = thickness;
2839   sr.origin.y += r.size.height - thickness;
2840   if (bottom_p) NSRectFill (sr);
2842   /* right */
2843   sr.size.height = r.size.height;
2844   sr.origin.y = r.origin.y;
2845   sr.size.width = thickness;
2846   sr.origin.x += r.size.width - thickness;
2847   if (right_p) NSRectFill (sr);
2851 static void
2852 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2853 /* --------------------------------------------------------------------------
2854       Function modeled after x_draw_glyph_string_box ().
2855       Sets up parameters for drawing.
2856    -------------------------------------------------------------------------- */
2858   int right_x, last_x;
2859   char left_p, right_p;
2860   struct glyph *last_glyph;
2861   NSRect r;
2862   int thickness;
2863   struct face *face;
2865   if (s->hl == DRAW_MOUSE_FACE)
2866     {
2867       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2868       if (!face)
2869         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2870     }
2871   else
2872     face = s->face;
2874   thickness = face->box_line_width;
2876   NSTRACE (ns_dumpglyphs_box_or_relief);
2878   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2879             ? WINDOW_RIGHT_EDGE_X (s->w)
2880             : window_box_right (s->w, s->area));
2881   last_glyph = (s->cmp || s->img
2882                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2884   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2885               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2887   left_p = (s->first_glyph->left_box_line_p
2888             || (s->hl == DRAW_MOUSE_FACE
2889                 && (s->prev == NULL || s->prev->hl != s->hl)));
2890   right_p = (last_glyph->right_box_line_p
2891              || (s->hl == DRAW_MOUSE_FACE
2892                  && (s->next == NULL || s->next->hl != s->hl)));
2894   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2896   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2897   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2898     {
2899       ns_draw_box (r, abs (thickness),
2900                    ns_lookup_indexed_color (face->box_color, s->f),
2901                   left_p, right_p);
2902     }
2903   else
2904     {
2905       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2906                      1, 1, left_p, right_p, s);
2907     }
2911 static void
2912 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2913 /* --------------------------------------------------------------------------
2914       Modeled after x_draw_glyph_string_background, which draws BG in
2915       certain cases.  Others are left to the text rendering routine.
2916    -------------------------------------------------------------------------- */
2918   NSTRACE (ns_maybe_dumpglyphs_background);
2920   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2921     {
2922       int box_line_width = max (s->face->box_line_width, 0);
2923       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2924           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2925         {
2926           struct face *face;
2927           if (s->hl == DRAW_MOUSE_FACE)
2928             {
2929               face = FACE_FROM_ID (s->f,
2930                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2931               if (!face)
2932                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2933             }
2934           else
2935             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2936           if (!face->stipple)
2937             [(NS_FACE_BACKGROUND (face) != 0
2938               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2939               : FRAME_BACKGROUND_COLOR (s->f)) set];
2940           else
2941             {
2942               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2943               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2944             }
2946           if (s->hl != DRAW_CURSOR)
2947             {
2948               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2949                                     s->background_width,
2950                                     s->height-2*box_line_width);
2951               NSRectFill (r);
2952             }
2954           s->background_filled_p = 1;
2955         }
2956     }
2960 static void
2961 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2962 /* --------------------------------------------------------------------------
2963       Renders an image and associated borders.
2964    -------------------------------------------------------------------------- */
2966   EmacsImage *img = s->img->pixmap;
2967   int box_line_vwidth = max (s->face->box_line_width, 0);
2968   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2969   int bg_x, bg_y, bg_height;
2970   int th;
2971   char raised_p;
2972   NSRect br;
2973   struct face *face;
2974   NSColor *tdCol;
2976   NSTRACE (ns_dumpglyphs_image);
2978   if (s->face->box != FACE_NO_BOX
2979       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2980     x += abs (s->face->box_line_width);
2982   bg_x = x;
2983   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2984   bg_height = s->height;
2985   /* other terms have this, but was causing problems w/tabbar mode */
2986   /* - 2 * box_line_vwidth; */
2988   if (s->slice.x == 0) x += s->img->hmargin;
2989   if (s->slice.y == 0) y += s->img->vmargin;
2991   /* Draw BG: if we need larger area than image itself cleared, do that,
2992      otherwise, since we composite the image under NS (instead of mucking
2993      with its background color), we must clear just the image area. */
2994   if (s->hl == DRAW_MOUSE_FACE)
2995     {
2996       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2997       if (!face)
2998        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2999     }
3000   else
3001     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3003   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3005   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3006       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3007     {
3008       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3009       s->background_filled_p = 1;
3010     }
3011   else
3012     {
3013       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3014     }
3016   NSRectFill (br);
3018   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3019   if (img != nil)
3020     {
3021 #ifdef NS_IMPL_COCOA
3022       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3023       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3024                               s->slice.width, s->slice.height);
3025       [img drawInRect: dr
3026              fromRect: ir
3027              operation: NSCompositeSourceOver
3028               fraction: 1.0
3029            respectFlipped: YES
3030                 hints: nil];
3031 #else
3032       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3033                   operation: NSCompositeSourceOver];
3034 #endif
3035     }
3037   if (s->hl == DRAW_CURSOR)
3038     {
3039     [FRAME_CURSOR_COLOR (s->f) set];
3040     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3041       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3042     else
3043       /* Currently on NS img->mask is always 0. Since
3044          get_window_cursor_type specifies a hollow box cursor when on
3045          a non-masked image we never reach this clause. But we put it
3046          in in anticipation of better support for image masks on
3047          NS. */
3048       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3049     }
3050   else
3051     {
3052       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3053     }
3055   /* Draw underline, overline, strike-through. */
3056   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3058   /* Draw relief, if requested */
3059   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3060     {
3061       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3062         {
3063           th = tool_bar_button_relief >= 0 ?
3064             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3065           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3066         }
3067       else
3068         {
3069           th = abs (s->img->relief);
3070           raised_p = (s->img->relief > 0);
3071         }
3073       r.origin.x = x - th;
3074       r.origin.y = y - th;
3075       r.size.width = s->slice.width + 2*th-1;
3076       r.size.height = s->slice.height + 2*th-1;
3077       ns_draw_relief (r, th, raised_p,
3078                       s->slice.y == 0,
3079                       s->slice.y + s->slice.height == s->img->height,
3080                       s->slice.x == 0,
3081                       s->slice.x + s->slice.width == s->img->width, s);
3082     }
3084   /* If there is no mask, the background won't be seen,
3085      so draw a rectangle on the image for the cursor.
3086      Do this for all images, getting transparency right is not reliable.  */
3087   if (s->hl == DRAW_CURSOR)
3088     {
3089       int thickness = abs (s->img->relief);
3090       if (thickness == 0) thickness = 1;
3091       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3092     }
3096 static void
3097 ns_dumpglyphs_stretch (struct glyph_string *s)
3099   NSRect r[2];
3100   int n, i;
3101   struct face *face;
3102   NSColor *fgCol, *bgCol;
3104   if (!s->background_filled_p)
3105     {
3106       n = ns_get_glyph_string_clip_rect (s, r);
3107       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3109       ns_focus (s->f, r, n);
3111       if (s->hl == DRAW_MOUSE_FACE)
3112        {
3113          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3114          if (!face)
3115            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3116        }
3117       else
3118        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3120       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3121       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3123       for (i = 0; i < n; ++i)
3124         {
3125           if (!s->row->full_width_p)
3126             {
3127               int overrun, leftoverrun;
3129               /* truncate to avoid overwriting fringe and/or scrollbar */
3130               overrun = max (0, (s->x + s->background_width)
3131                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3132                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3133               r[i].size.width -= overrun;
3135               /* truncate to avoid overwriting to left of the window box */
3136               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3137                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3139               if (leftoverrun > 0)
3140                 {
3141                   r[i].origin.x += leftoverrun;
3142                   r[i].size.width -= leftoverrun;
3143                 }
3145               /* XXX: Try to work between problem where a stretch glyph on
3146                  a partially-visible bottom row will clear part of the
3147                  modeline, and another where list-buffers headers and similar
3148                  rows erroneously have visible_height set to 0.  Not sure
3149                  where this is coming from as other terms seem not to show. */
3150               r[i].size.height = min (s->height, s->row->visible_height);
3151             }
3153           [bgCol set];
3155           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3156              overwriting cursor (usually when cursor on a tab) */
3157           if (s->hl == DRAW_CURSOR)
3158             {
3159               CGFloat x, width;
3161               x = r[i].origin.x;
3162               width = s->w->phys_cursor_width;
3163               r[i].size.width -= width;
3164               r[i].origin.x += width;
3166               NSRectFill (r[i]);
3168               /* Draw overlining, etc. on the cursor. */
3169               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3170                 ns_draw_text_decoration (s, face, bgCol, width, x);
3171               else
3172                 ns_draw_text_decoration (s, face, fgCol, width, x);
3173             }
3174           else
3175             {
3176               NSRectFill (r[i]);
3177             }
3179           /* Draw overlining, etc. on the stretch glyph (or the part
3180              of the stretch glyph after the cursor). */
3181           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3182                                    r[i].origin.x);
3183         }
3184       ns_unfocus (s->f);
3185       s->background_filled_p = 1;
3186     }
3190 static void
3191 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3193   int i, j, x;
3194   struct font *font = s->font;
3196   /* If first glyph of S has a left box line, start drawing the text
3197      of S to the right of that box line.  */
3198   if (s->face && s->face->box != FACE_NO_BOX
3199       && s->first_glyph->left_box_line_p)
3200     x = s->x + eabs (s->face->box_line_width);
3201   else
3202     x = s->x;
3204   /* S is a glyph string for a composition.  S->cmp_from is the index
3205      of the first character drawn for glyphs of this composition.
3206      S->cmp_from == 0 means we are drawing the very first character of
3207      this composition.  */
3209   /* Draw a rectangle for the composition if the font for the very
3210      first character of the composition could not be loaded.  */
3211   if (s->font_not_found_p)
3212     {
3213       if (s->cmp_from == 0)
3214         {
3215           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3216           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3217         }
3218     }
3219   else if (! s->first_glyph->u.cmp.automatic)
3220     {
3221       int y = s->ybase;
3223       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3224         /* TAB in a composition means display glyphs with padding
3225            space on the left or right.  */
3226         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3227           {
3228             int xx = x + s->cmp->offsets[j * 2];
3229             int yy = y - s->cmp->offsets[j * 2 + 1];
3231             font->driver->draw (s, j, j + 1, xx, yy, false);
3232             if (s->face->overstrike)
3233               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3234           }
3235     }
3236   else
3237     {
3238       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3239       Lisp_Object glyph;
3240       int y = s->ybase;
3241       int width = 0;
3243       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3244         {
3245           glyph = LGSTRING_GLYPH (gstring, i);
3246           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3247             width += LGLYPH_WIDTH (glyph);
3248           else
3249             {
3250               int xoff, yoff, wadjust;
3252               if (j < i)
3253                 {
3254                   font->driver->draw (s, j, i, x, y, false);
3255                   if (s->face->overstrike)
3256                     font->driver->draw (s, j, i, x + 1, y, false);
3257                   x += width;
3258                 }
3259               xoff = LGLYPH_XOFF (glyph);
3260               yoff = LGLYPH_YOFF (glyph);
3261               wadjust = LGLYPH_WADJUST (glyph);
3262               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3263               if (s->face->overstrike)
3264                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3265                                     false);
3266               x += wadjust;
3267               j = i + 1;
3268               width = 0;
3269             }
3270         }
3271       if (j < i)
3272         {
3273           font->driver->draw (s, j, i, x, y, false);
3274           if (s->face->overstrike)
3275             font->driver->draw (s, j, i, x + 1, y, false);
3276         }
3277     }
3280 static void
3281 ns_draw_glyph_string (struct glyph_string *s)
3282 /* --------------------------------------------------------------------------
3283       External (RIF): Main draw-text call.
3284    -------------------------------------------------------------------------- */
3286   /* TODO (optimize): focus for box and contents draw */
3287   NSRect r[2];
3288   int n, flags;
3289   char box_drawn_p = 0;
3290   struct font *font = s->face->font;
3291   if (! font) font = FRAME_FONT (s->f);
3293   NSTRACE (ns_draw_glyph_string);
3295   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3296     {
3297       int width;
3298       struct glyph_string *next;
3300       for (width = 0, next = s->next;
3301            next && width < s->right_overhang;
3302            width += next->width, next = next->next)
3303         if (next->first_glyph->type != IMAGE_GLYPH)
3304           {
3305             if (next->first_glyph->type != STRETCH_GLYPH)
3306               {
3307                 n = ns_get_glyph_string_clip_rect (s->next, r);
3308                 ns_focus (s->f, r, n);
3309                 ns_maybe_dumpglyphs_background (s->next, 1);
3310                 ns_unfocus (s->f);
3311               }
3312             else
3313               {
3314                 ns_dumpglyphs_stretch (s->next);
3315               }
3316             next->num_clips = 0;
3317           }
3318     }
3320   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3321         && (s->first_glyph->type == CHAR_GLYPH
3322             || s->first_glyph->type == COMPOSITE_GLYPH))
3323     {
3324       n = ns_get_glyph_string_clip_rect (s, r);
3325       ns_focus (s->f, r, n);
3326       ns_maybe_dumpglyphs_background (s, 1);
3327       ns_dumpglyphs_box_or_relief (s);
3328       ns_unfocus (s->f);
3329       box_drawn_p = 1;
3330     }
3332   switch (s->first_glyph->type)
3333     {
3335     case IMAGE_GLYPH:
3336       n = ns_get_glyph_string_clip_rect (s, r);
3337       ns_focus (s->f, r, n);
3338       ns_dumpglyphs_image (s, r[0]);
3339       ns_unfocus (s->f);
3340       break;
3342     case STRETCH_GLYPH:
3343       ns_dumpglyphs_stretch (s);
3344       break;
3346     case CHAR_GLYPH:
3347     case COMPOSITE_GLYPH:
3348       n = ns_get_glyph_string_clip_rect (s, r);
3349       ns_focus (s->f, r, n);
3351       if (s->for_overlaps || (s->cmp_from > 0
3352                               && ! s->first_glyph->u.cmp.automatic))
3353         s->background_filled_p = 1;
3354       else
3355         ns_maybe_dumpglyphs_background
3356           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3358       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3359         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3360          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3361           NS_DUMPGLYPH_NORMAL));
3363       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3364         {
3365           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3366           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3367           NS_FACE_FOREGROUND (s->face) = tmp;
3368         }
3370       {
3371         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3373         if (isComposite)
3374           ns_draw_composite_glyph_string_foreground (s);
3375         else
3376           font->driver->draw
3377             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3378              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3379              || flags == NS_DUMPGLYPH_MOUSEFACE);
3380       }
3382       {
3383         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3384                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3385                                                    s->f)
3386                         : FRAME_FOREGROUND_COLOR (s->f));
3387         [col set];
3389         /* Draw underline, overline, strike-through. */
3390         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3391       }
3393       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3394         {
3395           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3396           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3397           NS_FACE_FOREGROUND (s->face) = tmp;
3398         }
3400       ns_unfocus (s->f);
3401       break;
3403     case GLYPHLESS_GLYPH:
3404       n = ns_get_glyph_string_clip_rect (s, r);
3405       ns_focus (s->f, r, n);
3407       if (s->for_overlaps || (s->cmp_from > 0
3408                               && ! s->first_glyph->u.cmp.automatic))
3409         s->background_filled_p = 1;
3410       else
3411         ns_maybe_dumpglyphs_background
3412           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3413       /* ... */
3414       /* Not yet implemented.  */
3415       /* ... */
3416       ns_unfocus (s->f);
3417       break;
3419     default:
3420       emacs_abort ();
3421     }
3423   /* Draw box if not done already. */
3424   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3425     {
3426       n = ns_get_glyph_string_clip_rect (s, r);
3427       ns_focus (s->f, r, n);
3428       ns_dumpglyphs_box_or_relief (s);
3429       ns_unfocus (s->f);
3430     }
3432   s->num_clips = 0;
3437 /* ==========================================================================
3439     Event loop
3441    ========================================================================== */
3444 static void
3445 ns_send_appdefined (int value)
3446 /* --------------------------------------------------------------------------
3447     Internal: post an appdefined event which EmacsApp-sendEvent will
3448               recognize and take as a command to halt the event loop.
3449    -------------------------------------------------------------------------- */
3451   /*NSTRACE (ns_send_appdefined); */
3453 #ifdef NS_IMPL_GNUSTEP
3454   // GNUstep needs postEvent to happen on the main thread.
3455   if (! [[NSThread currentThread] isMainThread])
3456     {
3457       EmacsApp *app = (EmacsApp *)NSApp;
3458       app->nextappdefined = value;
3459       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3460                             withObject:nil
3461                          waitUntilDone:YES];
3462       return;
3463     }
3464 #endif
3466   /* Only post this event if we haven't already posted one.  This will end
3467        the [NXApp run] main loop after having processed all events queued at
3468        this moment.  */
3470 #ifdef NS_IMPL_COCOA
3471   if (! send_appdefined)
3472     {
3473       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3474          in certain situations (rapid incoming events).
3475          So check if we have one, if not add one.  */
3476       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3477                                           untilDate:[NSDate distantPast]
3478                                              inMode:NSDefaultRunLoopMode
3479                                             dequeue:NO];
3480       if (! appev) send_appdefined = YES;
3481     }
3482 #endif
3484   if (send_appdefined)
3485     {
3486       NSEvent *nxev;
3488       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3489       send_appdefined = NO;
3491       /* Don't need wakeup timer any more */
3492       if (timed_entry)
3493         {
3494           [timed_entry invalidate];
3495           [timed_entry release];
3496           timed_entry = nil;
3497         }
3499       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3500                                 location: NSMakePoint (0, 0)
3501                            modifierFlags: 0
3502                                timestamp: 0
3503                             windowNumber: [[NSApp mainWindow] windowNumber]
3504                                  context: [NSApp context]
3505                                  subtype: 0
3506                                    data1: value
3507                                    data2: 0];
3509       /* Post an application defined event on the event queue.  When this is
3510          received the [NXApp run] will return, thus having processed all
3511          events which are currently queued.  */
3512       [NSApp postEvent: nxev atStart: NO];
3513     }
3516 #ifdef HAVE_NATIVE_FS
3517 static void
3518 check_native_fs ()
3520   Lisp_Object frame, tail;
3522   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3523     return;
3525   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3527   FOR_EACH_FRAME (tail, frame)
3528     {
3529       struct frame *f = XFRAME (frame);
3530       if (FRAME_NS_P (f))
3531         {
3532           EmacsView *view = FRAME_NS_VIEW (f);
3533           [view updateCollectionBehavior];
3534         }
3535     }
3537 #endif
3539 /* GNUstep does not have cancelTracking.  */
3540 #ifdef NS_IMPL_COCOA
3541 /* Check if menu open should be canceled or continued as normal.  */
3542 void
3543 ns_check_menu_open (NSMenu *menu)
3545   /* Click in menu bar? */
3546   NSArray *a = [[NSApp mainMenu] itemArray];
3547   int i;
3548   BOOL found = NO;
3550   if (menu == nil) // Menu tracking ended.
3551     {
3552       if (menu_will_open_state == MENU_OPENING)
3553         menu_will_open_state = MENU_NONE;
3554       return;
3555     }
3557   for (i = 0; ! found && i < [a count]; i++)
3558     found = menu == [[a objectAtIndex:i] submenu];
3559   if (found)
3560     {
3561       if (menu_will_open_state == MENU_NONE && emacs_event)
3562         {
3563           NSEvent *theEvent = [NSApp currentEvent];
3564           struct frame *emacsframe = SELECTED_FRAME ();
3566           [menu cancelTracking];
3567           menu_will_open_state = MENU_PENDING;
3568           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3569           EV_TRAILER (theEvent);
3571           CGEventRef ourEvent = CGEventCreate (NULL);
3572           menu_mouse_point = CGEventGetLocation (ourEvent);
3573           CFRelease (ourEvent);
3574         }
3575       else if (menu_will_open_state == MENU_OPENING)
3576         {
3577           menu_will_open_state = MENU_NONE;
3578         }
3579     }
3582 /* Redo saved menu click if state is MENU_PENDING.  */
3583 void
3584 ns_check_pending_open_menu ()
3586   if (menu_will_open_state == MENU_PENDING)
3587     {
3588       CGEventSourceRef source
3589         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3591       CGEventRef event = CGEventCreateMouseEvent (source,
3592                                                   kCGEventLeftMouseDown,
3593                                                   menu_mouse_point,
3594                                                   kCGMouseButtonLeft);
3595       CGEventSetType (event, kCGEventLeftMouseDown);
3596       CGEventPost (kCGHIDEventTap, event);
3597       CFRelease (event);
3598       CFRelease (source);
3600       menu_will_open_state = MENU_OPENING;
3601     }
3603 #endif /* NS_IMPL_COCOA */
3605 static void
3606 unwind_apploopnr (Lisp_Object not_used)
3608   --apploopnr;
3609   n_emacs_events_pending = 0;
3610   ns_finish_events ();
3611   q_event_ptr = NULL;
3614 static int
3615 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3616 /* --------------------------------------------------------------------------
3617      External (hook): Post an event to ourself and keep reading events until
3618      we read it back again.  In effect process all events which were waiting.
3619      From 21+ we have to manage the event buffer ourselves.
3620    -------------------------------------------------------------------------- */
3622   struct input_event ev;
3623   int nevents;
3625 /* NSTRACE (ns_read_socket); */
3627 #ifdef HAVE_NATIVE_FS
3628   check_native_fs ();
3629 #endif
3631   if ([NSApp modalWindow] != nil)
3632     return -1;
3634   if (hold_event_q.nr > 0)
3635     {
3636       int i;
3637       for (i = 0; i < hold_event_q.nr; ++i)
3638         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3639       hold_event_q.nr = 0;
3640       return i;
3641     }
3643   block_input ();
3644   n_emacs_events_pending = 0;
3645   ns_init_events (&ev);
3646   q_event_ptr = hold_quit;
3648   /* we manage autorelease pools by allocate/reallocate each time around
3649      the loop; strict nesting is occasionally violated but seems not to
3650      matter.. earlier methods using full nesting caused major memory leaks */
3651   [outerpool release];
3652   outerpool = [[NSAutoreleasePool alloc] init];
3654   /* If have pending open-file requests, attend to the next one of those. */
3655   if (ns_pending_files && [ns_pending_files count] != 0
3656       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3657     {
3658       [ns_pending_files removeObjectAtIndex: 0];
3659     }
3660   /* Deal with pending service requests. */
3661   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3662     && [(EmacsApp *)
3663          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3664                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3665     {
3666       [ns_pending_service_names removeObjectAtIndex: 0];
3667       [ns_pending_service_args removeObjectAtIndex: 0];
3668     }
3669   else
3670     {
3671       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3672       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3673          to ourself, otherwise [NXApp run] will never exit.  */
3674       send_appdefined = YES;
3675       ns_send_appdefined (-1);
3677       if (++apploopnr != 1)
3678         {
3679           emacs_abort ();
3680         }
3681       record_unwind_protect (unwind_apploopnr, Qt);
3682       [NSApp run];
3683       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3684     }
3686   nevents = n_emacs_events_pending;
3687   n_emacs_events_pending = 0;
3688   ns_finish_events ();
3689   q_event_ptr = NULL;
3690   unblock_input ();
3692   return nevents;
3697 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3698            fd_set *exceptfds, struct timespec const *timeout,
3699            sigset_t const *sigmask)
3700 /* --------------------------------------------------------------------------
3701      Replacement for select, checking for events
3702    -------------------------------------------------------------------------- */
3704   int result;
3705   int t, k, nr = 0;
3706   struct input_event event;
3707   char c;
3709 /*  NSTRACE (ns_select); */
3711 #ifdef HAVE_NATIVE_FS
3712   check_native_fs ();
3713 #endif
3715   if (hold_event_q.nr > 0)
3716     {
3717       /* We already have events pending. */
3718       raise (SIGIO);
3719       errno = EINTR;
3720       return -1;
3721     }
3723   for (k = 0; k < nfds+1; k++)
3724     {
3725       if (readfds && FD_ISSET(k, readfds)) ++nr;
3726       if (writefds && FD_ISSET(k, writefds)) ++nr;
3727     }
3729   if (NSApp == nil
3730       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3731     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3733   [outerpool release];
3734   outerpool = [[NSAutoreleasePool alloc] init];
3737   send_appdefined = YES;
3738   if (nr > 0)
3739     {
3740       pthread_mutex_lock (&select_mutex);
3741       select_nfds = nfds;
3742       select_valid = 0;
3743       if (readfds)
3744         {
3745           select_readfds = *readfds;
3746           select_valid += SELECT_HAVE_READ;
3747         }
3748       if (writefds)
3749         {
3750           select_writefds = *writefds;
3751           select_valid += SELECT_HAVE_WRITE;
3752         }
3754       if (timeout)
3755         {
3756           select_timeout = *timeout;
3757           select_valid += SELECT_HAVE_TMO;
3758         }
3760       pthread_mutex_unlock (&select_mutex);
3762       /* Inform fd_handler that select should be called */
3763       c = 'g';
3764       emacs_write_sig (selfds[1], &c, 1);
3765     }
3766   else if (nr == 0 && timeout)
3767     {
3768       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3769       double time = timespectod (*timeout);
3770       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3771                                                       target: NSApp
3772                                                     selector:
3773                                   @selector (timeout_handler:)
3774                                                     userInfo: 0
3775                                                      repeats: NO]
3776                       retain];
3777     }
3778   else /* No timeout and no file descriptors, can this happen?  */
3779     {
3780       /* Send appdefined so we exit from the loop */
3781       ns_send_appdefined (-1);
3782     }
3784   block_input ();
3785   ns_init_events (&event);
3786   if (++apploopnr != 1)
3787     {
3788       emacs_abort ();
3789     }
3791   {
3792     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3793     record_unwind_protect (unwind_apploopnr, Qt);
3794     [NSApp run];
3795     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3796   }
3798   ns_finish_events ();
3799   if (nr > 0 && readfds)
3800     {
3801       c = 's';
3802       emacs_write_sig (selfds[1], &c, 1);
3803     }
3804   unblock_input ();
3806   t = last_appdefined_event_data;
3808   if (t != NO_APPDEFINED_DATA)
3809     {
3810       last_appdefined_event_data = NO_APPDEFINED_DATA;
3812       if (t == -2)
3813         {
3814           /* The NX_APPDEFINED event we received was a timeout. */
3815           result = 0;
3816         }
3817       else if (t == -1)
3818         {
3819           /* The NX_APPDEFINED event we received was the result of
3820              at least one real input event arriving.  */
3821           errno = EINTR;
3822           result = -1;
3823         }
3824       else
3825         {
3826           /* Received back from select () in fd_handler; copy the results */
3827           pthread_mutex_lock (&select_mutex);
3828           if (readfds) *readfds = select_readfds;
3829           if (writefds) *writefds = select_writefds;
3830           pthread_mutex_unlock (&select_mutex);
3831           result = t;
3832         }
3833     }
3834   else
3835     {
3836       errno = EINTR;
3837       result = -1;
3838     }
3840   return result;
3845 /* ==========================================================================
3847     Scrollbar handling
3849    ========================================================================== */
3852 static void
3853 ns_set_vertical_scroll_bar (struct window *window,
3854                            int portion, int whole, int position)
3855 /* --------------------------------------------------------------------------
3856       External (hook): Update or add scrollbar
3857    -------------------------------------------------------------------------- */
3859   Lisp_Object win;
3860   NSRect r, v;
3861   struct frame *f = XFRAME (WINDOW_FRAME (window));
3862   EmacsView *view = FRAME_NS_VIEW (f);
3863   EmacsScroller *bar;
3864   int window_y, window_height;
3865   int top, left, height, width;
3866   BOOL update_p = YES;
3868   /* optimization; display engine sends WAY too many of these.. */
3869   if (!NILP (window->vertical_scroll_bar))
3870     {
3871       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3872       if ([bar checkSamePosition: position portion: portion whole: whole])
3873         {
3874           if (view->scrollbarsNeedingUpdate == 0)
3875             {
3876               if (!windows_or_buffers_changed)
3877                   return;
3878             }
3879           else
3880             view->scrollbarsNeedingUpdate--;
3881           update_p = NO;
3882         }
3883     }
3885   NSTRACE (ns_set_vertical_scroll_bar);
3887   /* Get dimensions.  */
3888   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3889   top = window_y;
3890   height = window_height;
3891   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3892   left = WINDOW_SCROLL_BAR_AREA_X (window);
3894   r = NSMakeRect (left, top, width, height);
3895   /* the parent view is flipped, so we need to flip y value */
3896   v = [view frame];
3897   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3899   XSETWINDOW (win, window);
3900   block_input ();
3902   /* we want at least 5 lines to display a scrollbar */
3903   if (WINDOW_TOTAL_LINES (window) < 5)
3904     {
3905       if (!NILP (window->vertical_scroll_bar))
3906         {
3907           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3908           [bar removeFromSuperview];
3909           wset_vertical_scroll_bar (window, Qnil);
3910           [bar release];
3911         }
3912       ns_clear_frame_area (f, left, top, width, height);
3913       unblock_input ();
3914       return;
3915     }
3917   if (NILP (window->vertical_scroll_bar))
3918     {
3919       if (width > 0 && height > 0)
3920         ns_clear_frame_area (f, left, top, width, height);
3922       bar = [[EmacsScroller alloc] initFrame: r window: win];
3923       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3924       update_p = YES;
3925     }
3926   else
3927     {
3928       NSRect oldRect;
3929       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3930       oldRect = [bar frame];
3931       r.size.width = oldRect.size.width;
3932       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3933         {
3934           if (oldRect.origin.x != r.origin.x)
3935               ns_clear_frame_area (f, left, top, width, height);
3936           [bar setFrame: r];
3937         }
3938     }
3940   if (update_p)
3941     [bar setPosition: position portion: portion whole: whole];
3942   unblock_input ();
3946 static void
3947 ns_set_horizontal_scroll_bar (struct window *window,
3948                               int portion, int whole, int position)
3949 /* --------------------------------------------------------------------------
3950       External (hook): Update or add scrollbar
3951    -------------------------------------------------------------------------- */
3953   Lisp_Object win;
3954   NSRect r, v;
3955   struct frame *f = XFRAME (WINDOW_FRAME (window));
3956   EmacsView *view = FRAME_NS_VIEW (f);
3957   EmacsScroller *bar;
3958   int top, height, left, width;
3959   int window_x, window_width;
3960   int pixel_width = WINDOW_PIXEL_WIDTH (window);
3961   BOOL update_p = YES;
3963   /* optimization; display engine sends WAY too many of these.. */
3964   if (!NILP (window->horizontal_scroll_bar))
3965     {
3966       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3967       if ([bar checkSamePosition: position portion: portion whole: whole])
3968         {
3969           if (view->scrollbarsNeedingUpdate == 0)
3970             {
3971               if (!windows_or_buffers_changed)
3972                   return;
3973             }
3974           else
3975             view->scrollbarsNeedingUpdate--;
3976           update_p = NO;
3977         }
3978     }
3980   NSTRACE (ns_set_horizontal_scroll_bar);
3982   /* Get dimensions.  */
3983   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3984   left = window_x;
3985   width = window_width;
3986   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3987   top = WINDOW_SCROLL_BAR_AREA_Y (window);
3989   r = NSMakeRect (left, top, width, height);
3990   /* the parent view is flipped, so we need to flip y value */
3991   v = [view frame];
3992   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
3993   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3995   XSETWINDOW (win, window);
3996   block_input ();
3998   if (WINDOW_TOTAL_COLS (window) < 5)
3999     {
4000       if (!NILP (window->horizontal_scroll_bar))
4001         {
4002           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4003           [bar removeFromSuperview];
4004           wset_horizontal_scroll_bar (window, Qnil);
4005         }
4006       ns_clear_frame_area (f, left, top, width, height);
4007       unblock_input ();
4008       return;
4009     }
4011   if (NILP (window->horizontal_scroll_bar))
4012     {
4013       if (width > 0 && height > 0)
4014         ns_clear_frame_area (f, left, top, width, height);
4016       bar = [[EmacsScroller alloc] initFrame: r window: win];
4017       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4018       update_p = YES;
4019     }
4020   else
4021     {
4022       NSRect oldRect;
4023       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4024       oldRect = [bar frame];
4025       r.size.width = oldRect.size.width;
4026       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4027         {
4028           if (oldRect.origin.x != r.origin.x)
4029               ns_clear_frame_area (f, left, top, width, height);
4030           [bar setFrame: r];
4031           update_p = YES;
4032         }
4033     }
4035   if (update_p)
4036     [bar setPosition: position portion: portion whole: whole];
4037   unblock_input ();
4041 static void
4042 ns_condemn_scroll_bars (struct frame *f)
4043 /* --------------------------------------------------------------------------
4044      External (hook): arrange for all frame's scrollbars to be removed
4045      at next call to judge_scroll_bars, except for those redeemed.
4046    -------------------------------------------------------------------------- */
4048   int i;
4049   id view;
4050   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4052   NSTRACE (ns_condemn_scroll_bars);
4054   for (i =[subviews count]-1; i >= 0; i--)
4055     {
4056       view = [subviews objectAtIndex: i];
4057       if ([view isKindOfClass: [EmacsScroller class]])
4058         [view condemn];
4059     }
4063 static void
4064 ns_redeem_scroll_bar (struct window *window)
4065 /* --------------------------------------------------------------------------
4066      External (hook): arrange to spare this window's scrollbar
4067      at next call to judge_scroll_bars.
4068    -------------------------------------------------------------------------- */
4070   id bar;
4071   NSTRACE (ns_redeem_scroll_bar);
4072   if (!NILP (window->vertical_scroll_bar))
4073     {
4074       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4075       [bar reprieve];
4076     }
4078   if (!NILP (window->horizontal_scroll_bar))
4079     {
4080       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4081       [bar reprieve];
4082     }
4086 static void
4087 ns_judge_scroll_bars (struct frame *f)
4088 /* --------------------------------------------------------------------------
4089      External (hook): destroy all scrollbars on frame that weren't
4090      redeemed after call to condemn_scroll_bars.
4091    -------------------------------------------------------------------------- */
4093   int i;
4094   id view;
4095   EmacsView *eview = FRAME_NS_VIEW (f);
4096   NSArray *subviews = [[eview superview] subviews];
4097   BOOL removed = NO;
4099   NSTRACE (ns_judge_scroll_bars);
4100   for (i = [subviews count]-1; i >= 0; --i)
4101     {
4102       view = [subviews objectAtIndex: i];
4103       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4104       if ([view judge])
4105         removed = YES;
4106     }
4108   if (removed)
4109     [eview updateFrameSize: NO];
4112 /* ==========================================================================
4114     Initialization
4116    ========================================================================== */
4119 x_display_pixel_height (struct ns_display_info *dpyinfo)
4121   NSArray *screens = [NSScreen screens];
4122   NSEnumerator *enumerator = [screens objectEnumerator];
4123   NSScreen *screen;
4124   NSRect frame;
4126   frame = NSZeroRect;
4127   while ((screen = [enumerator nextObject]) != nil)
4128     frame = NSUnionRect (frame, [screen frame]);
4130   return NSHeight (frame);
4134 x_display_pixel_width (struct ns_display_info *dpyinfo)
4136   NSArray *screens = [NSScreen screens];
4137   NSEnumerator *enumerator = [screens objectEnumerator];
4138   NSScreen *screen;
4139   NSRect frame;
4141   frame = NSZeroRect;
4142   while ((screen = [enumerator nextObject]) != nil)
4143     frame = NSUnionRect (frame, [screen frame]);
4145   return NSWidth (frame);
4149 static Lisp_Object ns_string_to_lispmod (const char *s)
4150 /* --------------------------------------------------------------------------
4151      Convert modifier name to lisp symbol
4152    -------------------------------------------------------------------------- */
4154   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4155     return Qmeta;
4156   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4157     return Qsuper;
4158   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4159     return Qcontrol;
4160   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4161     return Qalt;
4162   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4163     return Qhyper;
4164   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4165     return Qnone;
4166   else
4167     return Qnil;
4171 static void
4172 ns_default (const char *parameter, Lisp_Object *result,
4173            Lisp_Object yesval, Lisp_Object noval,
4174            BOOL is_float, BOOL is_modstring)
4175 /* --------------------------------------------------------------------------
4176       Check a parameter value in user's preferences
4177    -------------------------------------------------------------------------- */
4179   const char *value = ns_get_defaults_value (parameter);
4181   if (value)
4182     {
4183       double f;
4184       char *pos;
4185       if (c_strcasecmp (value, "YES") == 0)
4186         *result = yesval;
4187       else if (c_strcasecmp (value, "NO") == 0)
4188         *result = noval;
4189       else if (is_float && (f = strtod (value, &pos), pos != value))
4190         *result = make_float (f);
4191       else if (is_modstring && value)
4192         *result = ns_string_to_lispmod (value);
4193       else fprintf (stderr,
4194                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4195     }
4199 static void
4200 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4201 /* --------------------------------------------------------------------------
4202       Initialize global info and storage for display.
4203    -------------------------------------------------------------------------- */
4205     NSScreen *screen = [NSScreen mainScreen];
4206     NSWindowDepth depth = [screen depth];
4208     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4209     dpyinfo->resy = 72.27;
4210     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4211                                                   NSColorSpaceFromDepth (depth)]
4212                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4213                                                  NSColorSpaceFromDepth (depth)];
4214     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4215     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4216     dpyinfo->color_table->colors = NULL;
4217     dpyinfo->root_window = 42; /* a placeholder.. */
4218     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4219     dpyinfo->n_fonts = 0;
4220     dpyinfo->smallest_font_height = 1;
4221     dpyinfo->smallest_char_width = 1;
4223     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4227 /* This and next define (many of the) public functions in this file. */
4228 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4229          with using despite presence in the "system dependent" redisplay
4230          interface.  In addition, many of the ns_ methods have code that is
4231          shared with all terms, indicating need for further refactoring. */
4232 extern frame_parm_handler ns_frame_parm_handlers[];
4233 static struct redisplay_interface ns_redisplay_interface =
4235   ns_frame_parm_handlers,
4236   x_produce_glyphs,
4237   x_write_glyphs,
4238   x_insert_glyphs,
4239   x_clear_end_of_line,
4240   ns_scroll_run,
4241   ns_after_update_window_line,
4242   ns_update_window_begin,
4243   ns_update_window_end,
4244   0, /* flush_display */
4245   x_clear_window_mouse_face,
4246   x_get_glyph_overhangs,
4247   x_fix_overlapping_area,
4248   ns_draw_fringe_bitmap,
4249   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4250   0, /* destroy_fringe_bitmap */
4251   ns_compute_glyph_string_overhangs,
4252   ns_draw_glyph_string,
4253   ns_define_frame_cursor,
4254   ns_clear_frame_area,
4255   ns_draw_window_cursor,
4256   ns_draw_vertical_window_border,
4257   ns_draw_window_divider,
4258   ns_shift_glyphs_for_insert,
4259   ns_show_hourglass,
4260   ns_hide_hourglass
4264 static void
4265 ns_delete_display (struct ns_display_info *dpyinfo)
4267   /* TODO... */
4271 /* This function is called when the last frame on a display is deleted. */
4272 static void
4273 ns_delete_terminal (struct terminal *terminal)
4275   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4277   /* Protect against recursive calls.  delete_frame in
4278      delete_terminal calls us back when it deletes our last frame.  */
4279   if (!terminal->name)
4280     return;
4282   block_input ();
4284   x_destroy_all_bitmaps (dpyinfo);
4285   ns_delete_display (dpyinfo);
4286   unblock_input ();
4290 static struct terminal *
4291 ns_create_terminal (struct ns_display_info *dpyinfo)
4292 /* --------------------------------------------------------------------------
4293       Set up use of NS before we make the first connection.
4294    -------------------------------------------------------------------------- */
4296   struct terminal *terminal;
4298   NSTRACE (ns_create_terminal);
4300   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4302   terminal->display_info.ns = dpyinfo;
4303   dpyinfo->terminal = terminal;
4305   terminal->clear_frame_hook = ns_clear_frame;
4306   terminal->ring_bell_hook = ns_ring_bell;
4307   terminal->update_begin_hook = ns_update_begin;
4308   terminal->update_end_hook = ns_update_end;
4309   terminal->read_socket_hook = ns_read_socket;
4310   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4311   terminal->mouse_position_hook = ns_mouse_position;
4312   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4313   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4314   terminal->fullscreen_hook = ns_fullscreen_hook;
4315   terminal->menu_show_hook = ns_menu_show;
4316   terminal->popup_dialog_hook = ns_popup_dialog;
4317   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4318   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4319   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4320   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4321   terminal->delete_frame_hook = x_destroy_window;
4322   terminal->delete_terminal_hook = ns_delete_terminal;
4323   /* Other hooks are NULL by default.  */
4325   return terminal;
4329 struct ns_display_info *
4330 ns_term_init (Lisp_Object display_name)
4331 /* --------------------------------------------------------------------------
4332      Start the Application and get things rolling.
4333    -------------------------------------------------------------------------- */
4335   struct terminal *terminal;
4336   struct ns_display_info *dpyinfo;
4337   static int ns_initialized = 0;
4338   Lisp_Object tmp;
4340   if (ns_initialized) return x_display_list;
4341   ns_initialized = 1;
4343   NSTRACE (ns_term_init);
4345   [outerpool release];
4346   outerpool = [[NSAutoreleasePool alloc] init];
4348   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4349   /*GSDebugAllocationActive (YES); */
4350   block_input ();
4352   baud_rate = 38400;
4353   Fset_input_interrupt_mode (Qnil);
4355   if (selfds[0] == -1)
4356     {
4357       if (emacs_pipe (selfds) != 0)
4358         {
4359           fprintf (stderr, "Failed to create pipe: %s\n",
4360                    emacs_strerror (errno));
4361           emacs_abort ();
4362         }
4364       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4365       FD_ZERO (&select_readfds);
4366       FD_ZERO (&select_writefds);
4367       pthread_mutex_init (&select_mutex, NULL);
4368     }
4370   ns_pending_files = [[NSMutableArray alloc] init];
4371   ns_pending_service_names = [[NSMutableArray alloc] init];
4372   ns_pending_service_args = [[NSMutableArray alloc] init];
4374 /* Start app and create the main menu, window, view.
4375      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4376      The view will then ask the NSApp to stop and return to Emacs. */
4377   [EmacsApp sharedApplication];
4378   if (NSApp == nil)
4379     return NULL;
4380   [NSApp setDelegate: NSApp];
4382   /* Start the select thread.  */
4383   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4384                            toTarget:NSApp
4385                          withObject:nil];
4387   /* debugging: log all notifications */
4388   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4389                                          selector: @selector (logNotification:)
4390                                              name: nil object: nil]; */
4392   dpyinfo = xzalloc (sizeof *dpyinfo);
4394   ns_initialize_display_info (dpyinfo);
4395   terminal = ns_create_terminal (dpyinfo);
4397   terminal->kboard = allocate_kboard (Qns);
4398   /* Don't let the initial kboard remain current longer than necessary.
4399      That would cause problems if a file loaded on startup tries to
4400      prompt in the mini-buffer.  */
4401   if (current_kboard == initial_kboard)
4402     current_kboard = terminal->kboard;
4403   terminal->kboard->reference_count++;
4405   dpyinfo->next = x_display_list;
4406   x_display_list = dpyinfo;
4408   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4410   terminal->name = xlispstrdup (display_name);
4412   unblock_input ();
4414   if (!inhibit_x_resources)
4415     {
4416       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4417                  Qt, Qnil, NO, NO);
4418       tmp = Qnil;
4419       /* this is a standard variable */
4420       ns_default ("AppleAntiAliasingThreshold", &tmp,
4421                  make_float (10.0), make_float (6.0), YES, NO);
4422       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4423     }
4425   {
4426     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4428     if ( cl == nil )
4429       {
4430         Lisp_Object color_file, color_map, color;
4431         unsigned long c;
4432         char *name;
4434         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4435                          Fsymbol_value (intern ("data-directory")));
4437         color_map = Fx_load_color_file (color_file);
4438         if (NILP (color_map))
4439           fatal ("Could not read %s.\n", SDATA (color_file));
4441         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4442         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4443           {
4444             color = XCAR (color_map);
4445             name = SSDATA (XCAR (color));
4446             c = XINT (XCDR (color));
4447             [cl setColor:
4448                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4449                                       green: GREEN_FROM_ULONG (c) / 255.0
4450                                        blue: BLUE_FROM_ULONG (c) / 255.0
4451                                       alpha: 1.0]
4452                   forKey: [NSString stringWithUTF8String: name]];
4453           }
4454         [cl writeToFile: nil];
4455       }
4456   }
4458   {
4459 #ifdef NS_IMPL_GNUSTEP
4460     Vwindow_system_version = build_string (gnustep_base_version);
4461 #else
4462     /*PSnextrelease (128, c); */
4463     char c[DBL_BUFSIZE_BOUND];
4464     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4465     Vwindow_system_version = make_unibyte_string (c, len);
4466 #endif
4467   }
4469   delete_keyboard_wait_descriptor (0);
4471   ns_app_name = [[NSProcessInfo processInfo] processName];
4473 /* Set up OS X app menu */
4474 #ifdef NS_IMPL_COCOA
4475   {
4476     NSMenu *appMenu;
4477     NSMenuItem *item;
4478     /* set up the application menu */
4479     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4480     [svcsMenu setAutoenablesItems: NO];
4481     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4482     [appMenu setAutoenablesItems: NO];
4483     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4484     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4486     [appMenu insertItemWithTitle: @"About Emacs"
4487                           action: @selector (orderFrontStandardAboutPanel:)
4488                    keyEquivalent: @""
4489                          atIndex: 0];
4490     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4491     [appMenu insertItemWithTitle: @"Preferences..."
4492                           action: @selector (showPreferencesWindow:)
4493                    keyEquivalent: @","
4494                          atIndex: 2];
4495     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4496     item = [appMenu insertItemWithTitle: @"Services"
4497                                  action: @selector (menuDown:)
4498                           keyEquivalent: @""
4499                                 atIndex: 4];
4500     [appMenu setSubmenu: svcsMenu forItem: item];
4501     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4502     [appMenu insertItemWithTitle: @"Hide Emacs"
4503                           action: @selector (hide:)
4504                    keyEquivalent: @"h"
4505                          atIndex: 6];
4506     item =  [appMenu insertItemWithTitle: @"Hide Others"
4507                           action: @selector (hideOtherApplications:)
4508                    keyEquivalent: @"h"
4509                          atIndex: 7];
4510     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4511     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4512     [appMenu insertItemWithTitle: @"Quit Emacs"
4513                           action: @selector (terminate:)
4514                    keyEquivalent: @"q"
4515                          atIndex: 9];
4517     item = [mainMenu insertItemWithTitle: ns_app_name
4518                                   action: @selector (menuDown:)
4519                            keyEquivalent: @""
4520                                  atIndex: 0];
4521     [mainMenu setSubmenu: appMenu forItem: item];
4522     [dockMenu insertItemWithTitle: @"New Frame"
4523                            action: @selector (newFrame:)
4524                     keyEquivalent: @""
4525                           atIndex: 0];
4527     [NSApp setMainMenu: mainMenu];
4528     [NSApp setAppleMenu: appMenu];
4529     [NSApp setServicesMenu: svcsMenu];
4530     /* Needed at least on Cocoa, to get dock menu to show windows */
4531     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4533     [[NSNotificationCenter defaultCenter]
4534       addObserver: mainMenu
4535          selector: @selector (trackingNotification:)
4536              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4537     [[NSNotificationCenter defaultCenter]
4538       addObserver: mainMenu
4539          selector: @selector (trackingNotification:)
4540              name: NSMenuDidEndTrackingNotification object: mainMenu];
4541   }
4542 #endif /* MAC OS X menu setup */
4544   /* Register our external input/output types, used for determining
4545      applicable services and also drag/drop eligibility. */
4546   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4547   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4548                       retain];
4549   ns_drag_types = [[NSArray arrayWithObjects:
4550                             NSStringPboardType,
4551                             NSTabularTextPboardType,
4552                             NSFilenamesPboardType,
4553                             NSURLPboardType, nil] retain];
4555   /* If fullscreen is in init/default-frame-alist, focus isn't set
4556      right for fullscreen windows, so set this.  */
4557   [NSApp activateIgnoringOtherApps:YES];
4559   [NSApp run];
4560   ns_do_open_file = YES;
4562 #ifdef NS_IMPL_GNUSTEP
4563   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4564      We must re-catch it so subprocess works.  */
4565   catch_child_signal ();
4566 #endif
4567   return dpyinfo;
4571 void
4572 ns_term_shutdown (int sig)
4574   [[NSUserDefaults standardUserDefaults] synchronize];
4576   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4577   if (STRINGP (Vauto_save_list_file_name))
4578     unlink (SSDATA (Vauto_save_list_file_name));
4580   if (sig == 0 || sig == SIGTERM)
4581     {
4582       [NSApp terminate: NSApp];
4583     }
4584   else // force a stack trace to happen
4585     {
4586       emacs_abort ();
4587     }
4591 /* ==========================================================================
4593     EmacsApp implementation
4595    ========================================================================== */
4598 @implementation EmacsApp
4600 - (id)init
4602   if (self = [super init])
4603     {
4604 #ifdef NS_IMPL_COCOA
4605       self->isFirst = YES;
4606 #endif
4607 #ifdef NS_IMPL_GNUSTEP
4608       self->applicationDidFinishLaunchingCalled = NO;
4609 #endif
4610     }
4612   return self;
4615 #ifdef NS_IMPL_COCOA
4616 - (void)run
4618 #ifndef NSAppKitVersionNumber10_9
4619 #define NSAppKitVersionNumber10_9 1265
4620 #endif
4622     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4623       {
4624         [super run];
4625         return;
4626       }
4628   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4630   if (isFirst) [self finishLaunching];
4631   isFirst = NO;
4633   shouldKeepRunning = YES;
4634   do
4635     {
4636       [pool release];
4637       pool = [[NSAutoreleasePool alloc] init];
4639       NSEvent *event =
4640         [self nextEventMatchingMask:NSAnyEventMask
4641                           untilDate:[NSDate distantFuture]
4642                              inMode:NSDefaultRunLoopMode
4643                             dequeue:YES];
4645       [self sendEvent:event];
4646       [self updateWindows];
4647     } while (shouldKeepRunning);
4649   [pool release];
4652 - (void)stop: (id)sender
4654     shouldKeepRunning = NO;
4655     // Stop possible dialog also.  Noop if no dialog present.
4656     // The file dialog still leaks 7k - 10k on 10.9 though.
4657     [super stop:sender];
4659 #endif /* NS_IMPL_COCOA */
4661 - (void)logNotification: (NSNotification *)notification
4663   const char *name = [[notification name] UTF8String];
4664   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4665       && !strstr (name, "WindowNumber"))
4666     NSLog (@"notification: '%@'", [notification name]);
4670 - (void)sendEvent: (NSEvent *)theEvent
4671 /* --------------------------------------------------------------------------
4672      Called when NSApp is running for each event received.  Used to stop
4673      the loop when we choose, since there's no way to just run one iteration.
4674    -------------------------------------------------------------------------- */
4676   int type = [theEvent type];
4677   NSWindow *window = [theEvent window];
4679 /*  NSTRACE (sendEvent); */
4680 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4682 #ifdef NS_IMPL_GNUSTEP
4683   // Keyboard events aren't propagated to file dialogs for some reason.
4684   if ([NSApp modalWindow] != nil &&
4685       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4686     {
4687       [[NSApp modalWindow] sendEvent: theEvent];
4688       return;
4689     }
4690 #endif
4692   if (represented_filename != nil && represented_frame)
4693     {
4694       NSString *fstr = represented_filename;
4695       NSView *view = FRAME_NS_VIEW (represented_frame);
4696 #ifdef NS_IMPL_COCOA
4697       /* work around a bug observed on 10.3 and later where
4698          setTitleWithRepresentedFilename does not clear out previous state
4699          if given filename does not exist */
4700       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4701         [[view window] setRepresentedFilename: @""];
4702 #endif
4703       [[view window] setRepresentedFilename: fstr];
4704       [represented_filename release];
4705       represented_filename = nil;
4706       represented_frame = NULL;
4707     }
4709   if (type == NSApplicationDefined)
4710     {
4711       switch ([theEvent data2])
4712         {
4713 #ifdef NS_IMPL_COCOA
4714         case NSAPP_DATA2_RUNASSCRIPT:
4715           ns_run_ascript ();
4716           [self stop: self];
4717           return;
4718 #endif
4719         case NSAPP_DATA2_RUNFILEDIALOG:
4720           ns_run_file_dialog ();
4721           [self stop: self];
4722           return;
4723         }
4724     }
4726   if (type == NSCursorUpdate && window == nil)
4727     {
4728       fprintf (stderr, "Dropping external cursor update event.\n");
4729       return;
4730     }
4732   if (type == NSApplicationDefined)
4733     {
4734       /* Events posted by ns_send_appdefined interrupt the run loop here.
4735          But, if a modal window is up, an appdefined can still come through,
4736          (e.g., from a makeKeyWindow event) but stopping self also stops the
4737          modal loop. Just defer it until later. */
4738       if ([NSApp modalWindow] == nil)
4739         {
4740           last_appdefined_event_data = [theEvent data1];
4741           [self stop: self];
4742         }
4743       else
4744         {
4745           send_appdefined = YES;
4746         }
4747     }
4750 #ifdef NS_IMPL_COCOA
4751   /* If no dialog and none of our frames have focus and it is a move, skip it.
4752      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4753      such as Wifi, sound, date or similar.
4754      This prevents "spooky" highlighting in the frame under the menu.  */
4755   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4756     {
4757       struct ns_display_info *di;
4758       BOOL has_focus = NO;
4759       for (di = x_display_list; ! has_focus && di; di = di->next)
4760         has_focus = di->x_focus_frame != 0;
4761       if (! has_focus)
4762         return;
4763     }
4764 #endif
4766   [super sendEvent: theEvent];
4770 - (void)showPreferencesWindow: (id)sender
4772   struct frame *emacsframe = SELECTED_FRAME ();
4773   NSEvent *theEvent = [NSApp currentEvent];
4775   if (!emacs_event)
4776     return;
4777   emacs_event->kind = NS_NONKEY_EVENT;
4778   emacs_event->code = KEY_NS_SHOW_PREFS;
4779   emacs_event->modifiers = 0;
4780   EV_TRAILER (theEvent);
4784 - (void)newFrame: (id)sender
4786   struct frame *emacsframe = SELECTED_FRAME ();
4787   NSEvent *theEvent = [NSApp currentEvent];
4789   if (!emacs_event)
4790     return;
4791   emacs_event->kind = NS_NONKEY_EVENT;
4792   emacs_event->code = KEY_NS_NEW_FRAME;
4793   emacs_event->modifiers = 0;
4794   EV_TRAILER (theEvent);
4798 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4799 - (BOOL) openFile: (NSString *)fileName
4801   struct frame *emacsframe = SELECTED_FRAME ();
4802   NSEvent *theEvent = [NSApp currentEvent];
4804   if (!emacs_event)
4805     return NO;
4807   emacs_event->kind = NS_NONKEY_EVENT;
4808   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4809   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4810   ns_input_line = Qnil; /* can be start or cons start,end */
4811   emacs_event->modifiers =0;
4812   EV_TRAILER (theEvent);
4814   return YES;
4818 /* **************************************************************************
4820       EmacsApp delegate implementation
4822    ************************************************************************** */
4824 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4825 /* --------------------------------------------------------------------------
4826      When application is loaded, terminate event loop in ns_term_init
4827    -------------------------------------------------------------------------- */
4829   NSTRACE (applicationDidFinishLaunching);
4830 #ifdef NS_IMPL_GNUSTEP
4831   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4832 #endif
4833   [NSApp setServicesProvider: NSApp];
4835   [self antialiasThresholdDidChange:nil];
4836 #ifdef NS_IMPL_COCOA
4837   [[NSNotificationCenter defaultCenter]
4838     addObserver:self
4839        selector:@selector(antialiasThresholdDidChange:)
4840            name:NSAntialiasThresholdChangedNotification
4841          object:nil];
4842 #endif
4844   ns_send_appdefined (-2);
4847 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4849 #ifdef NS_IMPL_COCOA
4850   macfont_update_antialias_threshold ();
4851 #endif
4855 /* Termination sequences:
4856     C-x C-c:
4857     Cmd-Q:
4858     MenuBar | File | Exit:
4859     Select Quit from App menubar:
4860         -terminate
4861         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4862         ns_term_shutdown()
4864     Select Quit from Dock menu:
4865     Logout attempt:
4866         -appShouldTerminate
4867           Cancel -> Nothing else
4868           Accept ->
4870           -terminate
4871           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4872           ns_term_shutdown()
4876 - (void) terminate: (id)sender
4878   struct frame *emacsframe = SELECTED_FRAME ();
4880   if (!emacs_event)
4881     return;
4883   emacs_event->kind = NS_NONKEY_EVENT;
4884   emacs_event->code = KEY_NS_POWER_OFF;
4885   emacs_event->arg = Qt; /* mark as non-key event */
4886   EV_TRAILER ((id)nil);
4890 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4892   int ret;
4894   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4895     return NSTerminateNow;
4897     ret = NSRunAlertPanel(ns_app_name,
4898                           @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4899                           @"Save Buffers and Exit", @"Cancel", nil);
4901     if (ret == NSAlertDefaultReturn)
4902         return NSTerminateNow;
4903     else if (ret == NSAlertAlternateReturn)
4904         return NSTerminateCancel;
4905     return NSTerminateNow;  /* just in case */
4908 static int
4909 not_in_argv (NSString *arg)
4911   int k;
4912   const char *a = [arg UTF8String];
4913   for (k = 1; k < initial_argc; ++k)
4914     if (strcmp (a, initial_argv[k]) == 0) return 0;
4915   return 1;
4918 /*   Notification from the Workspace to open a file */
4919 - (BOOL)application: sender openFile: (NSString *)file
4921   if (ns_do_open_file || not_in_argv (file))
4922     [ns_pending_files addObject: file];
4923   return YES;
4927 /*   Open a file as a temporary file */
4928 - (BOOL)application: sender openTempFile: (NSString *)file
4930   if (ns_do_open_file || not_in_argv (file))
4931     [ns_pending_files addObject: file];
4932   return YES;
4936 /*   Notification from the Workspace to open a file noninteractively (?) */
4937 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4939   if (ns_do_open_file || not_in_argv (file))
4940     [ns_pending_files addObject: file];
4941   return YES;
4944 /*   Notification from the Workspace to open multiple files */
4945 - (void)application: sender openFiles: (NSArray *)fileList
4947   NSEnumerator *files = [fileList objectEnumerator];
4948   NSString *file;
4949   /* Don't open files from the command line unconditionally,
4950      Cocoa parses the command line wrong, --option value tries to open value
4951      if --option is the last option.  */
4952   while ((file = [files nextObject]) != nil)
4953     if (ns_do_open_file || not_in_argv (file))
4954       [ns_pending_files addObject: file];
4956   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4961 /* Handle dock menu requests.  */
4962 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4964   return dockMenu;
4968 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4969 - (void)applicationWillBecomeActive: (NSNotification *)notification
4971   //ns_app_active=YES;
4973 - (void)applicationDidBecomeActive: (NSNotification *)notification
4975   NSTRACE (applicationDidBecomeActive);
4977 #ifdef NS_IMPL_GNUSTEP
4978   if (! applicationDidFinishLaunchingCalled)
4979     [self applicationDidFinishLaunching:notification];
4980 #endif
4981   //ns_app_active=YES;
4983   ns_update_auto_hide_menu_bar ();
4984   // No constraining takes place when the application is not active.
4985   ns_constrain_all_frames ();
4987 - (void)applicationDidResignActive: (NSNotification *)notification
4989   //ns_app_active=NO;
4990   ns_send_appdefined (-1);
4995 /* ==========================================================================
4997     EmacsApp aux handlers for managing event loop
4999    ========================================================================== */
5002 - (void)timeout_handler: (NSTimer *)timedEntry
5003 /* --------------------------------------------------------------------------
5004      The timeout specified to ns_select has passed.
5005    -------------------------------------------------------------------------- */
5007   /*NSTRACE (timeout_handler); */
5008   ns_send_appdefined (-2);
5011 #ifdef NS_IMPL_GNUSTEP
5012 - (void)sendFromMainThread:(id)unused
5014   ns_send_appdefined (nextappdefined);
5016 #endif
5018 - (void)fd_handler:(id)unused
5019 /* --------------------------------------------------------------------------
5020      Check data waiting on file descriptors and terminate if so
5021    -------------------------------------------------------------------------- */
5023   int result;
5024   int waiting = 1, nfds;
5025   char c;
5027   fd_set readfds, writefds, *wfds;
5028   struct timespec timeout, *tmo;
5029   NSAutoreleasePool *pool = nil;
5031   /* NSTRACE (fd_handler); */
5033   for (;;)
5034     {
5035       [pool release];
5036       pool = [[NSAutoreleasePool alloc] init];
5038       if (waiting)
5039         {
5040           fd_set fds;
5041           FD_ZERO (&fds);
5042           FD_SET (selfds[0], &fds);
5043           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5044           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5045             waiting = 0;
5046         }
5047       else
5048         {
5049           pthread_mutex_lock (&select_mutex);
5050           nfds = select_nfds;
5052           if (select_valid & SELECT_HAVE_READ)
5053             readfds = select_readfds;
5054           else
5055             FD_ZERO (&readfds);
5057           if (select_valid & SELECT_HAVE_WRITE)
5058             {
5059               writefds = select_writefds;
5060               wfds = &writefds;
5061             }
5062           else
5063             wfds = NULL;
5064           if (select_valid & SELECT_HAVE_TMO)
5065             {
5066               timeout = select_timeout;
5067               tmo = &timeout;
5068             }
5069           else
5070             tmo = NULL;
5072           pthread_mutex_unlock (&select_mutex);
5074           FD_SET (selfds[0], &readfds);
5075           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5077           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5079           if (result == 0)
5080             ns_send_appdefined (-2);
5081           else if (result > 0)
5082             {
5083               if (FD_ISSET (selfds[0], &readfds))
5084                 {
5085                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5086                     waiting = 1;
5087                 }
5088               else
5089                 {
5090                   pthread_mutex_lock (&select_mutex);
5091                   if (select_valid & SELECT_HAVE_READ)
5092                     select_readfds = readfds;
5093                   if (select_valid & SELECT_HAVE_WRITE)
5094                     select_writefds = writefds;
5095                   if (select_valid & SELECT_HAVE_TMO)
5096                     select_timeout = timeout;
5097                   pthread_mutex_unlock (&select_mutex);
5099                   ns_send_appdefined (result);
5100                 }
5101             }
5102           waiting = 1;
5103         }
5104     }
5109 /* ==========================================================================
5111     Service provision
5113    ========================================================================== */
5115 /* called from system: queue for next pass through event loop */
5116 - (void)requestService: (NSPasteboard *)pboard
5117               userData: (NSString *)userData
5118                  error: (NSString **)error
5120   [ns_pending_service_names addObject: userData];
5121   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5122       SSDATA (ns_string_from_pasteboard (pboard))]];
5126 /* called from ns_read_socket to clear queue */
5127 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5129   struct frame *emacsframe = SELECTED_FRAME ();
5130   NSEvent *theEvent = [NSApp currentEvent];
5132   if (!emacs_event)
5133     return NO;
5135   emacs_event->kind = NS_NONKEY_EVENT;
5136   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5137   ns_input_spi_name = build_string ([name UTF8String]);
5138   ns_input_spi_arg = build_string ([arg UTF8String]);
5139   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5140   EV_TRAILER (theEvent);
5142   return YES;
5146 @end  /* EmacsApp */
5150 /* ==========================================================================
5152     EmacsView implementation
5154    ========================================================================== */
5157 @implementation EmacsView
5159 /* needed to inform when window closed from LISP */
5160 - (void) setWindowClosing: (BOOL)closing
5162   windowClosing = closing;
5166 - (void)dealloc
5168   NSTRACE (EmacsView_dealloc);
5169   [toolbar release];
5170   if (fs_state == FULLSCREEN_BOTH)
5171     [nonfs_window release];
5172   [super dealloc];
5176 /* called on font panel selection */
5177 - (void)changeFont: (id)sender
5179   NSEvent *e = [[self window] currentEvent];
5180   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5181   struct font *font = face->font;
5182   id newFont;
5183   CGFloat size;
5184   NSFont *nsfont;
5186   NSTRACE (changeFont);
5188   if (!emacs_event)
5189     return;
5191 #ifdef NS_IMPL_GNUSTEP
5192   nsfont = ((struct nsfont_info *)font)->nsfont;
5193 #endif
5194 #ifdef NS_IMPL_COCOA
5195   nsfont = (NSFont *) macfont_get_nsctfont (font);
5196 #endif
5198   if ((newFont = [sender convertFont: nsfont]))
5199     {
5200       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5202       emacs_event->kind = NS_NONKEY_EVENT;
5203       emacs_event->modifiers = 0;
5204       emacs_event->code = KEY_NS_CHANGE_FONT;
5206       size = [newFont pointSize];
5207       ns_input_fontsize = make_number (lrint (size));
5208       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5209       EV_TRAILER (e);
5210     }
5214 - (BOOL)acceptsFirstResponder
5216   NSTRACE (acceptsFirstResponder);
5217   return YES;
5221 - (void)resetCursorRects
5223   NSRect visible = [self visibleRect];
5224   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5225   NSTRACE (resetCursorRects);
5227   if (currentCursor == nil)
5228     currentCursor = [NSCursor arrowCursor];
5230   if (!NSIsEmptyRect (visible))
5231     [self addCursorRect: visible cursor: currentCursor];
5232   [currentCursor setOnMouseEntered: YES];
5237 /*****************************************************************************/
5238 /* Keyboard handling. */
5239 #define NS_KEYLOG 0
5241 - (void)keyDown: (NSEvent *)theEvent
5243   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5244   int code;
5245   unsigned fnKeysym = 0;
5246   static NSMutableArray *nsEvArray;
5247 #ifdef NS_IMPL_GNUSTEP
5248   static BOOL firstTime = YES;
5249 #endif
5250   int left_is_none;
5251   unsigned int flags = [theEvent modifierFlags];
5253   NSTRACE (keyDown);
5255   /* Rhapsody and OS X give up and down events for the arrow keys */
5256   if (ns_fake_keydown == YES)
5257     ns_fake_keydown = NO;
5258   else if ([theEvent type] != NSKeyDown)
5259     return;
5261   if (!emacs_event)
5262     return;
5264  if (![[self window] isKeyWindow]
5265      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5266      /* we must avoid an infinite loop here. */
5267      && (EmacsView *)[[theEvent window] delegate] != self)
5268    {
5269      /* XXX: There is an occasional condition in which, when Emacs display
5270          updates a different frame from the current one, and temporarily
5271          selects it, then processes some interrupt-driven input
5272          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5273          for some reason that window has its first responder set to the NSView
5274          most recently updated (I guess), which is not the correct one. */
5275      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5276      return;
5277    }
5279   if (nsEvArray == nil)
5280     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5282   [NSCursor setHiddenUntilMouseMoves: YES];
5284   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5285     {
5286       clear_mouse_face (hlinfo);
5287       hlinfo->mouse_face_hidden = 1;
5288     }
5290   if (!processingCompose)
5291     {
5292       /* When using screen sharing, no left or right information is sent,
5293          so use Left key in those cases.  */
5294       int is_left_key, is_right_key;
5296       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5297         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5299       /* (Carbon way: [theEvent keyCode]) */
5301       /* is it a "function key"? */
5302       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5303          flag set (this is probably a bug in the OS).
5304       */
5305       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5306         {
5307           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5308         }
5309       if (fnKeysym == 0)
5310         {
5311           fnKeysym = ns_convert_key (code);
5312         }
5314       if (fnKeysym)
5315         {
5316           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5317              because Emacs treats Delete and KP-Delete same (in simple.el). */
5318           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5319 #ifdef NS_IMPL_GNUSTEP
5320               /*  GNUstep uses incompatible keycodes, even for those that are
5321                   supposed to be hardware independent.  Just check for delete.
5322                   Keypad delete does not have keysym 0xFFFF.
5323                   See http://savannah.gnu.org/bugs/?25395
5324               */
5325               || (fnKeysym == 0xFFFF && code == 127)
5326 #endif
5327             )
5328             code = 0xFF08; /* backspace */
5329           else
5330             code = fnKeysym;
5331         }
5333       /* are there modifiers? */
5334       emacs_event->modifiers = 0;
5336       if (flags & NSHelpKeyMask)
5337           emacs_event->modifiers |= hyper_modifier;
5339       if (flags & NSShiftKeyMask)
5340         emacs_event->modifiers |= shift_modifier;
5342       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5343       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5344         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5346       if (is_right_key)
5347         emacs_event->modifiers |= parse_solitary_modifier
5348           (EQ (ns_right_command_modifier, Qleft)
5349            ? ns_command_modifier
5350            : ns_right_command_modifier);
5352       if (is_left_key)
5353         {
5354           emacs_event->modifiers |= parse_solitary_modifier
5355             (ns_command_modifier);
5357           /* if super (default), take input manager's word so things like
5358              dvorak / qwerty layout work */
5359           if (EQ (ns_command_modifier, Qsuper)
5360               && !fnKeysym
5361               && [[theEvent characters] length] != 0)
5362             {
5363               /* XXX: the code we get will be unshifted, so if we have
5364                  a shift modifier, must convert ourselves */
5365               if (!(flags & NSShiftKeyMask))
5366                 code = [[theEvent characters] characterAtIndex: 0];
5367 #if 0
5368               /* this is ugly and also requires linking w/Carbon framework
5369                  (for LMGetKbdType) so for now leave this rare (?) case
5370                  undealt with.. in future look into CGEvent methods */
5371               else
5372                 {
5373                   long smv = GetScriptManagerVariable (smKeyScript);
5374                   Handle uchrHandle = GetResource
5375                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5376                   UInt32 dummy = 0;
5377                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5378                                  [[theEvent characters] characterAtIndex: 0],
5379                                  kUCKeyActionDisplay,
5380                                  (flags & ~NSCommandKeyMask) >> 8,
5381                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5382                                  &dummy, 1, &dummy, &code);
5383                   code &= 0xFF;
5384                 }
5385 #endif
5386             }
5387         }
5389       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5390       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5391         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5393       if (is_right_key)
5394           emacs_event->modifiers |= parse_solitary_modifier
5395               (EQ (ns_right_control_modifier, Qleft)
5396                ? ns_control_modifier
5397                : ns_right_control_modifier);
5399       if (is_left_key)
5400         emacs_event->modifiers |= parse_solitary_modifier
5401           (ns_control_modifier);
5403       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5404           emacs_event->modifiers |=
5405             parse_solitary_modifier (ns_function_modifier);
5407       left_is_none = NILP (ns_alternate_modifier)
5408         || EQ (ns_alternate_modifier, Qnone);
5410       is_right_key = (flags & NSRightAlternateKeyMask)
5411         == NSRightAlternateKeyMask;
5412       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5413         || (! is_right_key
5414             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5416       if (is_right_key)
5417         {
5418           if ((NILP (ns_right_alternate_modifier)
5419                || EQ (ns_right_alternate_modifier, Qnone)
5420                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5421               && !fnKeysym)
5422             {   /* accept pre-interp alt comb */
5423               if ([[theEvent characters] length] > 0)
5424                 code = [[theEvent characters] characterAtIndex: 0];
5425               /*HACK: clear lone shift modifier to stop next if from firing */
5426               if (emacs_event->modifiers == shift_modifier)
5427                 emacs_event->modifiers = 0;
5428             }
5429           else
5430             emacs_event->modifiers |= parse_solitary_modifier
5431               (EQ (ns_right_alternate_modifier, Qleft)
5432                ? ns_alternate_modifier
5433                : ns_right_alternate_modifier);
5434         }
5436       if (is_left_key) /* default = meta */
5437         {
5438           if (left_is_none && !fnKeysym)
5439             {   /* accept pre-interp alt comb */
5440               if ([[theEvent characters] length] > 0)
5441                 code = [[theEvent characters] characterAtIndex: 0];
5442               /*HACK: clear lone shift modifier to stop next if from firing */
5443               if (emacs_event->modifiers == shift_modifier)
5444                 emacs_event->modifiers = 0;
5445             }
5446           else
5447               emacs_event->modifiers |=
5448                 parse_solitary_modifier (ns_alternate_modifier);
5449         }
5451   if (NS_KEYLOG)
5452     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5453              code, fnKeysym, flags, emacs_event->modifiers);
5455       /* if it was a function key or had modifiers, pass it directly to emacs */
5456       if (fnKeysym || (emacs_event->modifiers
5457                        && (emacs_event->modifiers != shift_modifier)
5458                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5459 /*[[theEvent characters] length] */
5460         {
5461           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5462           if (code < 0x20)
5463             code |= (1<<28)|(3<<16);
5464           else if (code == 0x7f)
5465             code |= (1<<28)|(3<<16);
5466           else if (!fnKeysym)
5467             emacs_event->kind = code > 0xFF
5468               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5470           emacs_event->code = code;
5471           EV_TRAILER (theEvent);
5472           processingCompose = NO;
5473           return;
5474         }
5475     }
5478 #ifdef NS_IMPL_GNUSTEP
5479   /* if we get here we should send the key for input manager processing */
5480   /* Disable warning, there is nothing a user can do about it anyway, and
5481      it does not seem to matter.  */
5482 #if 0
5483   if (firstTime && [[NSInputManager currentInputManager]
5484                      wantsToDelayTextChangeNotifications] == NO)
5485     fprintf (stderr,
5486           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5487 #endif
5488   firstTime = NO;
5489 #endif
5490   if (NS_KEYLOG && !processingCompose)
5491     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5493   processingCompose = YES;
5494   [nsEvArray addObject: theEvent];
5495   [self interpretKeyEvents: nsEvArray];
5496   [nsEvArray removeObject: theEvent];
5500 #ifdef NS_IMPL_COCOA
5501 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5502    decided not to send key-down for.
5503    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5504    This only applies on Tiger and earlier.
5505    If it matches one of these, send it on to keyDown. */
5506 -(void)keyUp: (NSEvent *)theEvent
5508   int flags = [theEvent modifierFlags];
5509   int code = [theEvent keyCode];
5510   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5511       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5512     {
5513       if (NS_KEYLOG)
5514         fprintf (stderr, "keyUp: passed test");
5515       ns_fake_keydown = YES;
5516       [self keyDown: theEvent];
5517     }
5519 #endif
5522 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5525 /* <NSTextInput>: called when done composing;
5526    NOTE: also called when we delete over working text, followed immed.
5527          by doCommandBySelector: deleteBackward: */
5528 - (void)insertText: (id)aString
5530   int code;
5531   int len = [(NSString *)aString length];
5532   int i;
5534   if (NS_KEYLOG)
5535     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5536   processingCompose = NO;
5538   if (!emacs_event)
5539     return;
5541   /* first, clear any working text */
5542   if (workingText != nil)
5543     [self deleteWorkingText];
5545   /* now insert the string as keystrokes */
5546   for (i =0; i<len; i++)
5547     {
5548       code = [aString characterAtIndex: i];
5549       /* TODO: still need this? */
5550       if (code == 0x2DC)
5551         code = '~'; /* 0x7E */
5552       if (code != 32) /* Space */
5553         emacs_event->modifiers = 0;
5554       emacs_event->kind
5555         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5556       emacs_event->code = code;
5557       EV_TRAILER ((id)nil);
5558     }
5562 /* <NSTextInput>: inserts display of composing characters */
5563 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5565   NSString *str = [aString respondsToSelector: @selector (string)] ?
5566     [aString string] : aString;
5567   if (NS_KEYLOG)
5568     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5569            str, (unsigned long)[str length],
5570            (unsigned long)selRange.length,
5571            (unsigned long)selRange.location);
5573   if (workingText != nil)
5574     [self deleteWorkingText];
5575   if ([str length] == 0)
5576     return;
5578   if (!emacs_event)
5579     return;
5581   processingCompose = YES;
5582   workingText = [str copy];
5583   ns_working_text = build_string ([workingText UTF8String]);
5585   emacs_event->kind = NS_TEXT_EVENT;
5586   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5587   EV_TRAILER ((id)nil);
5591 /* delete display of composing characters [not in <NSTextInput>] */
5592 - (void)deleteWorkingText
5594   if (workingText == nil)
5595     return;
5596   if (NS_KEYLOG)
5597     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5598   [workingText release];
5599   workingText = nil;
5600   processingCompose = NO;
5602   if (!emacs_event)
5603     return;
5605   emacs_event->kind = NS_TEXT_EVENT;
5606   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5607   EV_TRAILER ((id)nil);
5611 - (BOOL)hasMarkedText
5613   return workingText != nil;
5617 - (NSRange)markedRange
5619   NSRange rng = workingText != nil
5620     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5621   if (NS_KEYLOG)
5622     NSLog (@"markedRange request");
5623   return rng;
5627 - (void)unmarkText
5629   if (NS_KEYLOG)
5630     NSLog (@"unmark (accept) text");
5631   [self deleteWorkingText];
5632   processingCompose = NO;
5636 /* used to position char selection windows, etc. */
5637 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5639   NSRect rect;
5640   NSPoint pt;
5641   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5642   if (NS_KEYLOG)
5643     NSLog (@"firstRectForCharRange request");
5645   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5646   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5647   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5648   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5649                                        +FRAME_LINE_HEIGHT (emacsframe));
5651   pt = [self convertPoint: pt toView: nil];
5652   pt = [[self window] convertBaseToScreen: pt];
5653   rect.origin = pt;
5654   return rect;
5658 - (NSInteger)conversationIdentifier
5660   return (NSInteger)self;
5664 - (void)doCommandBySelector: (SEL)aSelector
5666   if (NS_KEYLOG)
5667     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5669   processingCompose = NO;
5670   if (aSelector == @selector (deleteBackward:))
5671     {
5672       /* happens when user backspaces over an ongoing composition:
5673          throw a 'delete' into the event queue */
5674       if (!emacs_event)
5675         return;
5676       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5677       emacs_event->code = 0xFF08;
5678       EV_TRAILER ((id)nil);
5679     }
5682 - (NSArray *)validAttributesForMarkedText
5684   static NSArray *arr = nil;
5685   if (arr == nil) arr = [NSArray new];
5686  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5687   return arr;
5690 - (NSRange)selectedRange
5692   if (NS_KEYLOG)
5693     NSLog (@"selectedRange request");
5694   return NSMakeRange (NSNotFound, 0);
5697 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5698     GNUSTEP_GUI_MINOR_VERSION > 22
5699 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5700 #else
5701 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5702 #endif
5704   if (NS_KEYLOG)
5705     NSLog (@"characterIndexForPoint request");
5706   return 0;
5709 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5711   static NSAttributedString *str = nil;
5712   if (str == nil) str = [NSAttributedString new];
5713   if (NS_KEYLOG)
5714     NSLog (@"attributedSubstringFromRange request");
5715   return str;
5718 /* End <NSTextInput> impl. */
5719 /*****************************************************************************/
5722 /* This is what happens when the user presses a mouse button.  */
5723 - (void)mouseDown: (NSEvent *)theEvent
5725   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5726   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5728   NSTRACE (mouseDown);
5730   [self deleteWorkingText];
5732   if (!emacs_event)
5733     return;
5735   dpyinfo->last_mouse_frame = emacsframe;
5736   /* appears to be needed to prevent spurious movement events generated on
5737      button clicks */
5738   emacsframe->mouse_moved = 0;
5740   if ([theEvent type] == NSScrollWheel)
5741     {
5742       CGFloat delta = [theEvent deltaY];
5743       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5744       if (delta == 0)
5745         {
5746           delta = [theEvent deltaX];
5747           if (delta == 0)
5748             {
5749               NSTRACE (deltaIsZero);
5750               return;
5751             }
5752           emacs_event->kind = HORIZ_WHEEL_EVENT;
5753         }
5754       else
5755         emacs_event->kind = WHEEL_EVENT;
5757       emacs_event->code = 0;
5758       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5759         ((delta > 0) ? up_modifier : down_modifier);
5760     }
5761   else
5762     {
5763       emacs_event->kind = MOUSE_CLICK_EVENT;
5764       emacs_event->code = EV_BUTTON (theEvent);
5765       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5766                              | EV_UDMODIFIERS (theEvent);
5767     }
5768   XSETINT (emacs_event->x, lrint (p.x));
5769   XSETINT (emacs_event->y, lrint (p.y));
5770   EV_TRAILER (theEvent);
5774 - (void)rightMouseDown: (NSEvent *)theEvent
5776   NSTRACE (rightMouseDown);
5777   [self mouseDown: theEvent];
5781 - (void)otherMouseDown: (NSEvent *)theEvent
5783   NSTRACE (otherMouseDown);
5784   [self mouseDown: theEvent];
5788 - (void)mouseUp: (NSEvent *)theEvent
5790   NSTRACE (mouseUp);
5791   [self mouseDown: theEvent];
5795 - (void)rightMouseUp: (NSEvent *)theEvent
5797   NSTRACE (rightMouseUp);
5798   [self mouseDown: theEvent];
5802 - (void)otherMouseUp: (NSEvent *)theEvent
5804   NSTRACE (otherMouseUp);
5805   [self mouseDown: theEvent];
5809 - (void) scrollWheel: (NSEvent *)theEvent
5811   NSTRACE (scrollWheel);
5812   [self mouseDown: theEvent];
5816 /* Tell emacs the mouse has moved. */
5817 - (void)mouseMoved: (NSEvent *)e
5819   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5820   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5821   Lisp_Object frame;
5822   NSPoint pt;
5824 //  NSTRACE (mouseMoved);
5826   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5827   pt = [self convertPoint: [e locationInWindow] fromView: nil];
5828   dpyinfo->last_mouse_motion_x = pt.x;
5829   dpyinfo->last_mouse_motion_y = pt.y;
5831   /* update any mouse face */
5832   if (hlinfo->mouse_face_hidden)
5833     {
5834       hlinfo->mouse_face_hidden = 0;
5835       clear_mouse_face (hlinfo);
5836     }
5838   /* tooltip handling */
5839   previous_help_echo_string = help_echo_string;
5840   help_echo_string = Qnil;
5842   if (!NILP (Vmouse_autoselect_window))
5843     {
5844       NSTRACE (mouse_autoselect_window);
5845       static Lisp_Object last_mouse_window;
5846       Lisp_Object window
5847         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5849       if (WINDOWP (window)
5850           && !EQ (window, last_mouse_window)
5851           && !EQ (window, selected_window)
5852           && (focus_follows_mouse
5853               || (EQ (XWINDOW (window)->frame,
5854                       XWINDOW (selected_window)->frame))))
5855         {
5856           NSTRACE (in_window);
5857           emacs_event->kind = SELECT_WINDOW_EVENT;
5858           emacs_event->frame_or_window = window;
5859           EV_TRAILER2 (e);
5860         }
5861       /* Remember the last window where we saw the mouse.  */
5862       last_mouse_window = window;
5863     }
5865   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5866     help_echo_string = previous_help_echo_string;
5868   XSETFRAME (frame, emacsframe);
5869   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5870     {
5871       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5872          (note_mouse_highlight), which is called through the
5873          note_mouse_movement () call above */
5874       any_help_event_p = YES;
5875       gen_help_event (help_echo_string, frame, help_echo_window,
5876                       help_echo_object, help_echo_pos);
5877     }
5879   if (emacsframe->mouse_moved && send_appdefined)
5880     ns_send_appdefined (-1);
5884 - (void)mouseDragged: (NSEvent *)e
5886   NSTRACE (mouseDragged);
5887   [self mouseMoved: e];
5891 - (void)rightMouseDragged: (NSEvent *)e
5893   NSTRACE (rightMouseDragged);
5894   [self mouseMoved: e];
5898 - (void)otherMouseDragged: (NSEvent *)e
5900   NSTRACE (otherMouseDragged);
5901   [self mouseMoved: e];
5905 - (BOOL)windowShouldClose: (id)sender
5907   NSEvent *e =[[self window] currentEvent];
5909   NSTRACE (windowShouldClose);
5910   windowClosing = YES;
5911   if (!emacs_event)
5912     return NO;
5913   emacs_event->kind = DELETE_WINDOW_EVENT;
5914   emacs_event->modifiers = 0;
5915   emacs_event->code = 0;
5916   EV_TRAILER (e);
5917   /* Don't close this window, let this be done from lisp code.  */
5918   return NO;
5921 - (void) updateFrameSize: (BOOL) delay;
5923   NSWindow *window = [self window];
5924   NSRect wr = [window frame];
5925   int extra = 0;
5926   int oldc = cols, oldr = rows;
5927   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5928   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5929   int neww, newh;
5931   NSTRACE (updateFrameSize);
5932   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5934   if (! [self isFullscreen])
5935     {
5936 #ifdef NS_IMPL_GNUSTEP
5937       // GNUstep does not always update the tool bar height.  Force it.
5938       if (toolbar && [toolbar isVisible])
5939           update_frame_tool_bar (emacsframe);
5940 #endif
5942       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5943         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5944     }
5946   if (wait_for_tool_bar)
5947     {
5948       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5949         return;
5950       wait_for_tool_bar = NO;
5951     }
5953   neww = (int)wr.size.width - emacsframe->border_width;
5954   newh = (int)wr.size.height - extra;
5956   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5957   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5959   if (cols < MINWIDTH)
5960     cols = MINWIDTH;
5962   if (rows < MINHEIGHT)
5963     rows = MINHEIGHT;
5965   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5966     {
5967       NSView *view = FRAME_NS_VIEW (emacsframe);
5968       NSWindow *win = [view window];
5969       NSSize sz = [win resizeIncrements];
5971       change_frame_size (emacsframe,
5972                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5973                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5974                          0, delay, 0, 1);
5975       SET_FRAME_GARBAGED (emacsframe);
5976       cancel_mouse_face (emacsframe);
5978       // Did resize increments change because of a font change?
5979       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5980           sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5981           (frame_resize_pixelwise && sz.width != 1))
5982         {
5983           sz.width = frame_resize_pixelwise
5984             ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
5985           sz.height = frame_resize_pixelwise
5986             ? 1 : FRAME_LINE_HEIGHT (emacsframe);
5987           [win setResizeIncrements: sz];
5989           NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
5990         }
5992       [view setFrame: NSMakeRect (0, 0, neww, newh)];
5993       [self windowDidMove:nil];   // Update top/left.
5994     }
5997 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5998 /* normalize frame to gridded text size */
6000   int extra = 0;
6002   NSTRACE (windowWillResize);
6003   NSTRACE_SIZE ("Original size", frameSize);
6004 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
6006   if (fs_state == FULLSCREEN_MAXIMIZED
6007       && (maximized_width != (int)frameSize.width
6008           || maximized_height != (int)frameSize.height))
6009     [self setFSValue: FULLSCREEN_NONE];
6010   else if (fs_state == FULLSCREEN_WIDTH
6011            && maximized_width != (int)frameSize.width)
6012     [self setFSValue: FULLSCREEN_NONE];
6013   else if (fs_state == FULLSCREEN_HEIGHT
6014            && maximized_height != (int)frameSize.height)
6015     [self setFSValue: FULLSCREEN_NONE];
6016   if (fs_state == FULLSCREEN_NONE)
6017     maximized_width = maximized_height = -1;
6019   if (! [self isFullscreen])
6020     {
6021       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6022         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6023     }
6025   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6026   if (cols < MINWIDTH)
6027     cols = MINWIDTH;
6029   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6030                                            frameSize.height - extra);
6031   if (rows < MINHEIGHT)
6032     rows = MINHEIGHT;
6033 #ifdef NS_IMPL_COCOA
6034   {
6035     /* this sets window title to have size in it; the wm does this under GS */
6036     NSRect r = [[self window] frame];
6037     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6038       {
6039         if (old_title != 0)
6040           {
6041             xfree (old_title);
6042             old_title = 0;
6043           }
6044       }
6045     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6046       {
6047         char *size_title;
6048         NSWindow *window = [self window];
6049         if (old_title == 0)
6050           {
6051             char *t = strdup ([[[self window] title] UTF8String]);
6052             char *pos = strstr (t, "  â€”  ");
6053             if (pos)
6054               *pos = '\0';
6055             old_title = t;
6056           }
6057         size_title = xmalloc (strlen (old_title) + 40);
6058         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6059         [window setTitle: [NSString stringWithUTF8String: size_title]];
6060         [window display];
6061         xfree (size_title);
6062       }
6063   }
6064 #endif /* NS_IMPL_COCOA */
6065 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
6067   return frameSize;
6071 - (void)windowDidResize: (NSNotification *)notification
6073   if (! [self fsIsNative])
6074     {
6075       NSWindow *theWindow = [notification object];
6076       /* We can get notification on the non-FS window when in
6077          fullscreen mode.  */
6078       if ([self window] != theWindow) return;
6079     }
6081 #ifdef NS_IMPL_GNUSTEP
6082   NSWindow *theWindow = [notification object];
6084    /* In GNUstep, at least currently, it's possible to get a didResize
6085       without getting a willResize.. therefore we need to act as if we got
6086       the willResize now */
6087   NSSize sz = [theWindow frame].size;
6088   sz = [self windowWillResize: theWindow toSize: sz];
6089 #endif /* NS_IMPL_GNUSTEP */
6091   NSTRACE (windowDidResize);
6092 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6094 if (cols > 0 && rows > 0)
6095     {
6096       [self updateFrameSize: YES];
6097     }
6099   ns_send_appdefined (-1);
6102 #ifdef NS_IMPL_COCOA
6103 - (void)viewDidEndLiveResize
6105   [super viewDidEndLiveResize];
6106   if (old_title != 0)
6107     {
6108       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6109       xfree (old_title);
6110       old_title = 0;
6111     }
6112   maximizing_resize = NO;
6114 #endif /* NS_IMPL_COCOA */
6117 - (void)windowDidBecomeKey: (NSNotification *)notification
6118 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6120   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6121   struct frame *old_focus = dpyinfo->x_focus_frame;
6123   NSTRACE (windowDidBecomeKey);
6125   if (emacsframe != old_focus)
6126     dpyinfo->x_focus_frame = emacsframe;
6128   ns_frame_rehighlight (emacsframe);
6130   if (emacs_event)
6131     {
6132       emacs_event->kind = FOCUS_IN_EVENT;
6133       EV_TRAILER ((id)nil);
6134     }
6138 - (void)windowDidResignKey: (NSNotification *)notification
6139 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6141   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6142   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6143   NSTRACE (windowDidResignKey);
6145   if (is_focus_frame)
6146     dpyinfo->x_focus_frame = 0;
6148   emacsframe->mouse_moved = 0;
6149   ns_frame_rehighlight (emacsframe);
6151   /* FIXME: for some reason needed on second and subsequent clicks away
6152             from sole-frame Emacs to get hollow box to show */
6153   if (!windowClosing && [[self window] isVisible] == YES)
6154     {
6155       x_update_cursor (emacsframe, 1);
6156       x_set_frame_alpha (emacsframe);
6157     }
6159   if (any_help_event_p)
6160     {
6161       Lisp_Object frame;
6162       XSETFRAME (frame, emacsframe);
6163       help_echo_string = Qnil;
6164       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6165     }
6167   if (emacs_event && is_focus_frame)
6168     {
6169       [self deleteWorkingText];
6170       emacs_event->kind = FOCUS_OUT_EVENT;
6171       EV_TRAILER ((id)nil);
6172     }
6176 - (void)windowWillMiniaturize: sender
6178   NSTRACE (windowWillMiniaturize);
6182 - (BOOL)isFlipped
6184   return YES;
6188 - (BOOL)isOpaque
6190   return NO;
6194 - initFrameFromEmacs: (struct frame *)f
6196   NSRect r, wr;
6197   Lisp_Object tem;
6198   NSWindow *win;
6199   NSSize sz;
6200   NSColor *col;
6201   NSString *name;
6203   NSTRACE (initFrameFromEmacs);
6205   windowClosing = NO;
6206   processingCompose = NO;
6207   scrollbarsNeedingUpdate = 0;
6208   fs_state = FULLSCREEN_NONE;
6209   fs_before_fs = next_maximized = -1;
6210 #ifdef HAVE_NATIVE_FS
6211   fs_is_native = ns_use_native_fullscreen;
6212 #else
6213   fs_is_native = NO;
6214 #endif
6215   maximized_width = maximized_height = -1;
6216   nonfs_window = nil;
6218 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6220   ns_userRect = NSMakeRect (0, 0, 0, 0);
6221   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6222                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6223   [self initWithFrame: r];
6224   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6226   FRAME_NS_VIEW (f) = self;
6227   emacsframe = f;
6228 #ifdef NS_IMPL_COCOA
6229   old_title = 0;
6230   maximizing_resize = NO;
6231 #endif
6233   win = [[EmacsWindow alloc]
6234             initWithContentRect: r
6235                       styleMask: (NSResizableWindowMask |
6236 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6237                                   NSTitledWindowMask |
6238 #endif
6239                                   NSMiniaturizableWindowMask |
6240                                   NSClosableWindowMask)
6241                         backing: NSBackingStoreBuffered
6242                           defer: YES];
6244 #ifdef HAVE_NATIVE_FS
6245     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6246 #endif
6248   wr = [win frame];
6249   bwidth = f->border_width = wr.size.width - r.size.width;
6250   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6252   [win setAcceptsMouseMovedEvents: YES];
6253   [win setDelegate: self];
6254   [win useOptimizedDrawing: YES];
6256   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6257   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6258   [win setResizeIncrements: sz];
6260   [[win contentView] addSubview: self];
6262   if (ns_drag_types)
6263     [self registerForDraggedTypes: ns_drag_types];
6265   tem = f->name;
6266   name = [NSString stringWithUTF8String:
6267                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6268   [win setTitle: name];
6270   /* toolbar support */
6271   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6272                          [NSString stringWithFormat: @"Emacs Frame %d",
6273                                    ns_window_num]];
6274   [win setToolbar: toolbar];
6275   [toolbar setVisible: NO];
6277   /* Don't set frame garbaged until tool bar is up to date?
6278      This avoids an extra clear and redraw (flicker) at frame creation.  */
6279   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6280   else wait_for_tool_bar = NO;
6283 #ifdef NS_IMPL_COCOA
6284   {
6285     NSButton *toggleButton;
6286   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6287   [toggleButton setTarget: self];
6288   [toggleButton setAction: @selector (toggleToolbar: )];
6289   }
6290 #endif
6291   FRAME_TOOLBAR_HEIGHT (f) = 0;
6293   tem = f->icon_name;
6294   if (!NILP (tem))
6295     [win setMiniwindowTitle:
6296            [NSString stringWithUTF8String: SSDATA (tem)]];
6298   {
6299     NSScreen *screen = [win screen];
6301     if (screen != 0)
6302       [win setFrameTopLeftPoint: NSMakePoint
6303            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6304             IN_BOUND (-SCREENMAX,
6305                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6306   }
6308   [win makeFirstResponder: self];
6310   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6311                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6312   [win setBackgroundColor: col];
6313   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6314     [win setOpaque: NO];
6316   [self allocateGState];
6318   [NSApp registerServicesMenuSendTypes: ns_send_types
6319                            returnTypes: nil];
6321   ns_window_num++;
6322   return self;
6326 - (void)windowDidMove: sender
6328   NSWindow *win = [self window];
6329   NSRect r = [win frame];
6330   NSArray *screens = [NSScreen screens];
6331   NSScreen *screen = [screens objectAtIndex: 0];
6333   NSTRACE (windowDidMove);
6335   if (!emacsframe->output_data.ns)
6336     return;
6337   if (screen != nil)
6338     {
6339       emacsframe->left_pos = r.origin.x;
6340       emacsframe->top_pos =
6341         [screen frame].size.height - (r.origin.y + r.size.height);
6342     }
6346 /* Called AFTER method below, but before our windowWillResize call there leads
6347    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6348    location so set_window_size moves the frame. */
6349 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6351   emacsframe->output_data.ns->zooming = 1;
6352   return YES;
6356 /* Override to do something slightly nonstandard, but nice.  First click on
6357    zoom button will zoom vertically.  Second will zoom completely.  Third
6358    returns to original. */
6359 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6360                         defaultFrame:(NSRect)defaultFrame
6362   NSRect result = [sender frame];
6364   NSTRACE (windowWillUseStandardFrame);
6366   if (fs_before_fs != -1) /* Entering fullscreen */
6367       {
6368         result = defaultFrame;
6369       }
6370   else if (next_maximized == FULLSCREEN_HEIGHT
6371       || (next_maximized == -1
6372           && abs (defaultFrame.size.height - result.size.height)
6373           > FRAME_LINE_HEIGHT (emacsframe)))
6374     {
6375       /* first click */
6376       ns_userRect = result;
6377       maximized_height = result.size.height = defaultFrame.size.height;
6378       maximized_width = -1;
6379       result.origin.y = defaultFrame.origin.y;
6380       [self setFSValue: FULLSCREEN_HEIGHT];
6381 #ifdef NS_IMPL_COCOA
6382       maximizing_resize = YES;
6383 #endif
6384     }
6385   else if (next_maximized == FULLSCREEN_WIDTH)
6386     {
6387       ns_userRect = result;
6388       maximized_width = result.size.width = defaultFrame.size.width;
6389       maximized_height = -1;
6390       result.origin.x = defaultFrame.origin.x;
6391       [self setFSValue: FULLSCREEN_WIDTH];
6392     }
6393   else if (next_maximized == FULLSCREEN_MAXIMIZED
6394            || (next_maximized == -1
6395                && abs (defaultFrame.size.width - result.size.width)
6396                > FRAME_COLUMN_WIDTH (emacsframe)))
6397     {
6398       result = defaultFrame;  /* second click */
6399       maximized_width = result.size.width;
6400       maximized_height = result.size.height;
6401       [self setFSValue: FULLSCREEN_MAXIMIZED];
6402 #ifdef NS_IMPL_COCOA
6403       maximizing_resize = YES;
6404 #endif
6405     }
6406   else
6407     {
6408       /* restore */
6409       result = ns_userRect.size.height ? ns_userRect : result;
6410       ns_userRect = NSMakeRect (0, 0, 0, 0);
6411 #ifdef NS_IMPL_COCOA
6412       maximizing_resize = fs_state != FULLSCREEN_NONE;
6413 #endif
6414       [self setFSValue: FULLSCREEN_NONE];
6415       maximized_width = maximized_height = -1;
6416     }
6418   if (fs_before_fs == -1) next_maximized = -1;
6419   [self windowWillResize: sender toSize: result.size];
6420   return result;
6424 - (void)windowDidDeminiaturize: sender
6426   NSTRACE (windowDidDeminiaturize);
6427   if (!emacsframe->output_data.ns)
6428     return;
6430   SET_FRAME_ICONIFIED (emacsframe, 0);
6431   SET_FRAME_VISIBLE (emacsframe, 1);
6432   windows_or_buffers_changed = 63;
6434   if (emacs_event)
6435     {
6436       emacs_event->kind = DEICONIFY_EVENT;
6437       EV_TRAILER ((id)nil);
6438     }
6442 - (void)windowDidExpose: sender
6444   NSTRACE (windowDidExpose);
6445   if (!emacsframe->output_data.ns)
6446     return;
6448   SET_FRAME_VISIBLE (emacsframe, 1);
6449   SET_FRAME_GARBAGED (emacsframe);
6451   if (send_appdefined)
6452     ns_send_appdefined (-1);
6456 - (void)windowDidMiniaturize: sender
6458   NSTRACE (windowDidMiniaturize);
6459   if (!emacsframe->output_data.ns)
6460     return;
6462   SET_FRAME_ICONIFIED (emacsframe, 1);
6463   SET_FRAME_VISIBLE (emacsframe, 0);
6465   if (emacs_event)
6466     {
6467       emacs_event->kind = ICONIFY_EVENT;
6468       EV_TRAILER ((id)nil);
6469     }
6472 #ifdef HAVE_NATIVE_FS
6473 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6474       willUseFullScreenPresentationOptions:
6475   (NSApplicationPresentationOptions)proposedOptions
6477   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6479 #endif
6481 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6483   fs_before_fs = fs_state;
6486 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6488   [self setFSValue: FULLSCREEN_BOTH];
6489   if (! [self fsIsNative])
6490     {
6491       [self windowDidBecomeKey:notification];
6492       [nonfs_window orderOut:self];
6493     }
6494   else
6495     {
6496       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6497 #ifdef NS_IMPL_COCOA
6498 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6499       unsigned val = (unsigned)[NSApp presentationOptions];
6501       // OSX 10.7 bug fix, the menu won't appear without this.
6502       // val is non-zero on other OSX versions.
6503       if (val == 0)
6504         {
6505           NSApplicationPresentationOptions options
6506             = NSApplicationPresentationAutoHideDock
6507             | NSApplicationPresentationAutoHideMenuBar
6508             | NSApplicationPresentationFullScreen
6509             | NSApplicationPresentationAutoHideToolbar;
6511           [NSApp setPresentationOptions: options];
6512         }
6513 #endif
6514 #endif
6515       [toolbar setVisible:tbar_visible];
6516     }
6519 - (void)windowWillExitFullScreen:(NSNotification *)notification
6521   if (next_maximized != -1)
6522     fs_before_fs = next_maximized;
6525 - (void)windowDidExitFullScreen:(NSNotification *)notification
6527   [self setFSValue: fs_before_fs];
6528   fs_before_fs = -1;
6529 #ifdef HAVE_NATIVE_FS
6530   [self updateCollectionBehavior];
6531 #endif
6532   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6533     {
6534       [toolbar setVisible:YES];
6535       update_frame_tool_bar (emacsframe);
6536       [self updateFrameSize:YES];
6537       [[self window] display];
6538     }
6539   else
6540     [toolbar setVisible:NO];
6542   if (next_maximized != -1)
6543     [[self window] performZoom:self];
6546 - (BOOL)fsIsNative
6548   return fs_is_native;
6551 - (BOOL)isFullscreen
6553   if (! fs_is_native) return nonfs_window != nil;
6554 #ifdef HAVE_NATIVE_FS
6555   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6556 #else
6557   return NO;
6558 #endif
6561 #ifdef HAVE_NATIVE_FS
6562 - (void)updateCollectionBehavior
6564   if (! [self isFullscreen])
6565     {
6566       NSWindow *win = [self window];
6567       NSWindowCollectionBehavior b = [win collectionBehavior];
6568       if (ns_use_native_fullscreen)
6569         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6570       else
6571         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6573       [win setCollectionBehavior: b];
6574       fs_is_native = ns_use_native_fullscreen;
6575     }
6577 #endif
6579 - (void)toggleFullScreen: (id)sender
6581   NSWindow *w, *fw;
6582   BOOL onFirstScreen;
6583   struct frame *f;
6584   NSSize sz;
6585   NSRect r, wr;
6586   NSColor *col;
6588   if (fs_is_native)
6589     {
6590 #ifdef HAVE_NATIVE_FS
6591       [[self window] toggleFullScreen:sender];
6592 #endif
6593       return;
6594     }
6596   w = [self window];
6597   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6598   f = emacsframe;
6599   wr = [w frame];
6600   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6601                                  (FRAME_DEFAULT_FACE (f)),
6602                                  f);
6604   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6605   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6607   if (fs_state != FULLSCREEN_BOTH)
6608     {
6609       NSScreen *screen = [w screen];
6611 #if defined (NS_IMPL_COCOA) && \
6612   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6613       /* Hide ghost menu bar on secondary monitor? */
6614       if (! onFirstScreen)
6615         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6616 #endif
6617       /* Hide dock and menubar if we are on the primary screen.  */
6618       if (onFirstScreen)
6619         {
6620 #ifdef NS_IMPL_COCOA
6621           NSApplicationPresentationOptions options
6622             = NSApplicationPresentationAutoHideDock
6623             | NSApplicationPresentationAutoHideMenuBar;
6625           [NSApp setPresentationOptions: options];
6626 #else
6627           [NSMenu setMenuBarVisible:NO];
6628 #endif
6629         }
6631       fw = [[EmacsFSWindow alloc]
6632                        initWithContentRect:[w contentRectForFrameRect:wr]
6633                                  styleMask:NSBorderlessWindowMask
6634                                    backing:NSBackingStoreBuffered
6635                                      defer:YES
6636                                     screen:screen];
6638       [fw setContentView:[w contentView]];
6639       [fw setTitle:[w title]];
6640       [fw setDelegate:self];
6641       [fw setAcceptsMouseMovedEvents: YES];
6642       [fw useOptimizedDrawing: YES];
6643       [fw setResizeIncrements: sz];
6644       [fw setBackgroundColor: col];
6645       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6646         [fw setOpaque: NO];
6648       f->border_width = 0;
6649       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6650       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6651       FRAME_TOOLBAR_HEIGHT (f) = 0;
6653       nonfs_window = w;
6655       [self windowWillEnterFullScreen:nil];
6656       [fw makeKeyAndOrderFront:NSApp];
6657       [fw makeFirstResponder:self];
6658       [w orderOut:self];
6659       r = [fw frameRectForContentRect:[screen frame]];
6660       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6661       [self windowDidEnterFullScreen:nil];
6662       [fw display];
6663     }
6664   else
6665     {
6666       fw = w;
6667       w = nonfs_window;
6668       nonfs_window = nil;
6670       if (onFirstScreen)
6671         {
6672 #ifdef NS_IMPL_COCOA
6673           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6674 #else
6675           [NSMenu setMenuBarVisible:YES];
6676 #endif
6677         }
6679       [w setContentView:[fw contentView]];
6680       [w setResizeIncrements: sz];
6681       [w setBackgroundColor: col];
6682       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6683         [w setOpaque: NO];
6685       f->border_width = bwidth;
6686       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6687       if (FRAME_EXTERNAL_TOOL_BAR (f))
6688         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6690       [self windowWillExitFullScreen:nil];
6691       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6692       [fw close];
6693       [w makeKeyAndOrderFront:NSApp];
6694       [self windowDidExitFullScreen:nil];
6695       [self updateFrameSize:YES];
6696     }
6699 - (void)handleFS
6701   if (fs_state != emacsframe->want_fullscreen)
6702     {
6703       if (fs_state == FULLSCREEN_BOTH)
6704         {
6705           [self toggleFullScreen:self];
6706         }
6708       switch (emacsframe->want_fullscreen)
6709         {
6710         case FULLSCREEN_BOTH:
6711           [self toggleFullScreen:self];
6712           break;
6713         case FULLSCREEN_WIDTH:
6714           next_maximized = FULLSCREEN_WIDTH;
6715           if (fs_state != FULLSCREEN_BOTH)
6716             [[self window] performZoom:self];
6717           break;
6718         case FULLSCREEN_HEIGHT:
6719           next_maximized = FULLSCREEN_HEIGHT;
6720           if (fs_state != FULLSCREEN_BOTH)
6721             [[self window] performZoom:self];
6722           break;
6723         case FULLSCREEN_MAXIMIZED:
6724           next_maximized = FULLSCREEN_MAXIMIZED;
6725           if (fs_state != FULLSCREEN_BOTH)
6726             [[self window] performZoom:self];
6727           break;
6728         case FULLSCREEN_NONE:
6729           if (fs_state != FULLSCREEN_BOTH)
6730             {
6731               next_maximized = FULLSCREEN_NONE;
6732               [[self window] performZoom:self];
6733             }
6734           break;
6735         }
6737       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6738     }
6742 - (void) setFSValue: (int)value
6744   Lisp_Object lval = Qnil;
6745   switch (value)
6746     {
6747     case FULLSCREEN_BOTH:
6748       lval = Qfullboth;
6749       break;
6750     case FULLSCREEN_WIDTH:
6751       lval = Qfullwidth;
6752       break;
6753     case FULLSCREEN_HEIGHT:
6754       lval = Qfullheight;
6755       break;
6756     case FULLSCREEN_MAXIMIZED:
6757       lval = Qmaximized;
6758       break;
6759     }
6760   store_frame_param (emacsframe, Qfullscreen, lval);
6761   fs_state = value;
6764 - (void)mouseEntered: (NSEvent *)theEvent
6766   NSTRACE (mouseEntered);
6767   if (emacsframe)
6768     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6769       = EV_TIMESTAMP (theEvent);
6773 - (void)mouseExited: (NSEvent *)theEvent
6775   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6777   NSTRACE (mouseExited);
6779   if (!hlinfo)
6780     return;
6782   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6783     = EV_TIMESTAMP (theEvent);
6785   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6786     {
6787       clear_mouse_face (hlinfo);
6788       hlinfo->mouse_face_mouse_frame = 0;
6789     }
6793 - menuDown: sender
6795   NSTRACE (menuDown);
6796   if (context_menu_value == -1)
6797     context_menu_value = [sender tag];
6798   else
6799     {
6800       NSInteger tag = [sender tag];
6801       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6802                                     emacsframe->menu_bar_vector,
6803                                     (void *)tag);
6804     }
6806   ns_send_appdefined (-1);
6807   return self;
6811 - (EmacsToolbar *)toolbar
6813   return toolbar;
6817 /* this gets called on toolbar button click */
6818 - toolbarClicked: (id)item
6820   NSEvent *theEvent;
6821   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6823   NSTRACE (toolbarClicked);
6825   if (!emacs_event)
6826     return self;
6828   /* send first event (for some reason two needed) */
6829   theEvent = [[self window] currentEvent];
6830   emacs_event->kind = TOOL_BAR_EVENT;
6831   XSETFRAME (emacs_event->arg, emacsframe);
6832   EV_TRAILER (theEvent);
6834   emacs_event->kind = TOOL_BAR_EVENT;
6835 /*   XSETINT (emacs_event->code, 0); */
6836   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6837                            idx + TOOL_BAR_ITEM_KEY);
6838   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6839   EV_TRAILER (theEvent);
6840   return self;
6844 - toggleToolbar: (id)sender
6846   if (!emacs_event)
6847     return self;
6849   emacs_event->kind = NS_NONKEY_EVENT;
6850   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6851   EV_TRAILER ((id)nil);
6852   return self;
6856 - (void)drawRect: (NSRect)rect
6858   int x = NSMinX (rect), y = NSMinY (rect);
6859   int width = NSWidth (rect), height = NSHeight (rect);
6861   NSTRACE (drawRect);
6863   if (!emacsframe || !emacsframe->output_data.ns)
6864     return;
6866   ns_clear_frame_area (emacsframe, x, y, width, height);
6867   block_input ();
6868   expose_frame (emacsframe, x, y, width, height);
6869   unblock_input ();
6871   /*
6872     drawRect: may be called (at least in OS X 10.5) for invisible
6873     views as well for some reason.  Thus, do not infer visibility
6874     here.
6876     emacsframe->async_visible = 1;
6877     emacsframe->async_iconified = 0;
6878   */
6882 /* NSDraggingDestination protocol methods.  Actually this is not really a
6883    protocol, but a category of Object.  O well...  */
6885 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6887   NSTRACE (draggingEntered);
6888   return NSDragOperationGeneric;
6892 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6894   return YES;
6898 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6900   id pb;
6901   int x, y;
6902   NSString *type;
6903   NSEvent *theEvent = [[self window] currentEvent];
6904   NSPoint position;
6905   NSDragOperation op = [sender draggingSourceOperationMask];
6906   int modifiers = 0;
6908   NSTRACE (performDragOperation);
6910   if (!emacs_event)
6911     return NO;
6913   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6914   x = lrint (position.x);  y = lrint (position.y);
6916   pb = [sender draggingPasteboard];
6917   type = [pb availableTypeFromArray: ns_drag_types];
6919   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6920       // URL drags contain all operations (0xf), don't allow all to be set.
6921       (op & 0xf) != 0xf)
6922     {
6923       if (op & NSDragOperationLink)
6924         modifiers |= NSControlKeyMask;
6925       if (op & NSDragOperationCopy)
6926         modifiers |= NSAlternateKeyMask;
6927       if (op & NSDragOperationGeneric)
6928         modifiers |= NSCommandKeyMask;
6929     }
6931   modifiers = EV_MODIFIERS2 (modifiers);
6932   if (type == 0)
6933     {
6934       return NO;
6935     }
6936   else if ([type isEqualToString: NSFilenamesPboardType])
6937     {
6938       NSArray *files;
6939       NSEnumerator *fenum;
6940       NSString *file;
6942       if (!(files = [pb propertyListForType: type]))
6943         return NO;
6945       fenum = [files objectEnumerator];
6946       while ( (file = [fenum nextObject]) )
6947         {
6948           emacs_event->kind = DRAG_N_DROP_EVENT;
6949           XSETINT (emacs_event->x, x);
6950           XSETINT (emacs_event->y, y);
6951           ns_input_file = append2 (ns_input_file,
6952                                    build_string ([file UTF8String]));
6953           emacs_event->modifiers = modifiers;
6954           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
6955           EV_TRAILER (theEvent);
6956         }
6957       return YES;
6958     }
6959   else if ([type isEqualToString: NSURLPboardType])
6960     {
6961       NSURL *url = [NSURL URLFromPasteboard: pb];
6962       if (url == nil) return NO;
6964       emacs_event->kind = DRAG_N_DROP_EVENT;
6965       XSETINT (emacs_event->x, x);
6966       XSETINT (emacs_event->y, y);
6967       emacs_event->modifiers = modifiers;
6968       emacs_event->arg =  list2 (Qurl,
6969                                  build_string ([[url absoluteString]
6970                                                  UTF8String]));
6971       EV_TRAILER (theEvent);
6973       if ([url isFileURL] != NO)
6974         {
6975           NSString *file = [url path];
6976           ns_input_file = append2 (ns_input_file,
6977                                    build_string ([file UTF8String]));
6978         }
6979       return YES;
6980     }
6981   else if ([type isEqualToString: NSStringPboardType]
6982            || [type isEqualToString: NSTabularTextPboardType])
6983     {
6984       NSString *data;
6986       if (! (data = [pb stringForType: type]))
6987         return NO;
6989       emacs_event->kind = DRAG_N_DROP_EVENT;
6990       XSETINT (emacs_event->x, x);
6991       XSETINT (emacs_event->y, y);
6992       emacs_event->modifiers = modifiers;
6993       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
6994       EV_TRAILER (theEvent);
6995       return YES;
6996     }
6997   else
6998     {
6999       fprintf (stderr, "Invalid data type in dragging pasteboard");
7000       return NO;
7001     }
7005 - (id) validRequestorForSendType: (NSString *)typeSent
7006                       returnType: (NSString *)typeReturned
7008   NSTRACE (validRequestorForSendType);
7009   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7010       && typeReturned == nil)
7011     {
7012       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7013         return self;
7014     }
7016   return [super validRequestorForSendType: typeSent
7017                                returnType: typeReturned];
7021 /* The next two methods are part of NSServicesRequests informal protocol,
7022    supposedly called when a services menu item is chosen from this app.
7023    But this should not happen because we override the services menu with our
7024    own entries which call ns-perform-service.
7025    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7026    So let's at least stub them out until further investigation can be done. */
7028 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7030   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7031      be written into the buffer in place of the existing selection..
7032      ordinary service calls go through functions defined in ns-win.el */
7033   return NO;
7036 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7038   NSArray *typesDeclared;
7039   Lisp_Object val;
7041   /* We only support NSStringPboardType */
7042   if ([types containsObject:NSStringPboardType] == NO) {
7043     return NO;
7044   }
7046   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7047   if (CONSP (val) && SYMBOLP (XCAR (val)))
7048     {
7049       val = XCDR (val);
7050       if (CONSP (val) && NILP (XCDR (val)))
7051         val = XCAR (val);
7052     }
7053   if (! STRINGP (val))
7054     return NO;
7056   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7057   [pb declareTypes:typesDeclared owner:nil];
7058   ns_string_to_pasteboard (pb, val);
7059   return YES;
7063 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7064    (gives a miniaturized version of the window); currently we use the latter for
7065    frames whose active buffer doesn't correspond to any file
7066    (e.g., '*scratch*') */
7067 - setMiniwindowImage: (BOOL) setMini
7069   id image = [[self window] miniwindowImage];
7070   NSTRACE (setMiniwindowImage);
7072   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7073      about "AppleDockIconEnabled" notwithstanding, however the set message
7074      below has its effect nonetheless. */
7075   if (image != emacsframe->output_data.ns->miniimage)
7076     {
7077       if (image && [image isKindOfClass: [EmacsImage class]])
7078         [image release];
7079       [[self window] setMiniwindowImage:
7080                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7081     }
7083   return self;
7087 - (void) setRows: (int) r andColumns: (int) c
7089   rows = r;
7090   cols = c;
7093 @end  /* EmacsView */
7097 /* ==========================================================================
7099     EmacsWindow implementation
7101    ========================================================================== */
7103 @implementation EmacsWindow
7105 #ifdef NS_IMPL_COCOA
7106 - (id)accessibilityAttributeValue:(NSString *)attribute
7108   Lisp_Object str = Qnil;
7109   struct frame *f = SELECTED_FRAME ();
7110   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7112   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7113     return NSAccessibilityTextFieldRole;
7115   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7116       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7117     {
7118       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7119     }
7120   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7121     {
7122       if (! NILP (BVAR (curbuf, mark_active)))
7123           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7125       if (NILP (str))
7126         {
7127           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7128           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7129           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7131           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7132             str = make_uninit_multibyte_string (range, byte_range);
7133           else
7134             str = make_uninit_string (range);
7135           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7136              Is this a problem?  */
7137           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7138         }
7139     }
7142   if (! NILP (str))
7143     {
7144       if (CONSP (str) && SYMBOLP (XCAR (str)))
7145         {
7146           str = XCDR (str);
7147           if (CONSP (str) && NILP (XCDR (str)))
7148             str = XCAR (str);
7149         }
7150       if (STRINGP (str))
7151         {
7152           const char *utfStr = SSDATA (str);
7153           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7154           return nsStr;
7155         }
7156     }
7158   return [super accessibilityAttributeValue:attribute];
7160 #endif /* NS_IMPL_COCOA */
7162 /* If we have multiple monitors, one above the other, we don't want to
7163    restrict the height to just one monitor.  So we override this.  */
7164 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7166   /* When making the frame visible for the first time or if there is just
7167      one screen, we want to constrain.  Other times not.  */
7168   NSArray *screens = [NSScreen screens];
7169   NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7170   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
7171   NSTRACE (constrainFrameRect);
7172   NSTRACE_RECT ("input", frameRect);
7174   if (ns_menu_bar_should_be_hidden ())
7175     return frameRect;
7177   if (nr_screens == 1)
7178     return [super constrainFrameRect:frameRect toScreen:screen];
7180 #ifdef NS_IMPL_COCOA
7181 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7182   // If separate spaces is on, it is like each screen is independent.  There is
7183   // no spanning of frames across screens.
7184   if ([NSScreen screensHaveSeparateSpaces])
7185     return [super constrainFrameRect:frameRect toScreen:screen];
7186 #endif
7187 #endif
7189   for (i = 0; i < nr_screens; ++i)
7190     {
7191       NSScreen *s = [screens objectAtIndex: i];
7192       NSRect scrrect = [s frame];
7193       NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7195       if (intersect.size.width > 0 || intersect.size.height > 0)
7196         ++nr_eff_screens;
7197     }
7199   if (nr_eff_screens == 1)
7200     return [super constrainFrameRect:frameRect toScreen:screen];
7202   /* The default implementation does two things 1) ensure that the top
7203      of the rectangle is below the menu bar (or below the top of the
7204      screen) and 2) resizes windows larger than the screen. As we
7205      don't want the latter, a smaller rectangle is used. */
7206 #define FAKE_HEIGHT 64
7207   float old_top = frameRect.origin.y + frameRect.size.height;
7208   NSRect r;
7209   r.size.height = FAKE_HEIGHT;
7210   r.size.width = frameRect.size.width;
7211   r.origin.x = frameRect.origin.x;
7212   r.origin.y = old_top - FAKE_HEIGHT;
7214   NSTRACE_RECT ("input to super", r);
7216   r = [super constrainFrameRect:r toScreen:screen];
7218   NSTRACE_RECT ("output from super", r);
7220   float new_top = r.origin.y + FAKE_HEIGHT;
7221   if (new_top < old_top)
7222   {
7223     frameRect.origin.y = new_top - frameRect.size.height;
7224   }
7226   NSTRACE_RECT ("output", frameRect);
7228   return frameRect;
7229 #undef FAKE_HEIGHT
7232 @end /* EmacsWindow */
7235 @implementation EmacsFSWindow
7237 - (BOOL)canBecomeKeyWindow
7239   return YES;
7242 - (BOOL)canBecomeMainWindow
7244   return YES;
7247 @end
7249 /* ==========================================================================
7251     EmacsScroller implementation
7253    ========================================================================== */
7256 @implementation EmacsScroller
7258 /* for repeat button push */
7259 #define SCROLL_BAR_FIRST_DELAY 0.5
7260 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7262 + (CGFloat) scrollerWidth
7264   /* TODO: if we want to allow variable widths, this is the place to do it,
7265            however neither GNUstep nor Cocoa support it very well */
7266   return [NSScroller scrollerWidth];
7270 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7272   NSTRACE (EmacsScroller_initFrame);
7274   r.size.width = [EmacsScroller scrollerWidth];
7275   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7276   [self setContinuous: YES];
7277   [self setEnabled: YES];
7279   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7280      locked against the top and bottom edges, and right edge on OS X, where
7281      scrollers are on right. */
7282 #ifdef NS_IMPL_GNUSTEP
7283   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7284 #else
7285   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7286 #endif
7288   window = XWINDOW (nwin);
7289   condemned = NO;
7290   pixel_height = NSHeight (r);
7291   if (pixel_height == 0) pixel_height = 1;
7292   min_portion = 20 / pixel_height;
7294   frame = XFRAME (window->frame);
7295   if (FRAME_LIVE_P (frame))
7296     {
7297       int i;
7298       EmacsView *view = FRAME_NS_VIEW (frame);
7299       NSView *sview = [[view window] contentView];
7300       NSArray *subs = [sview subviews];
7302       /* disable optimization stopping redraw of other scrollbars */
7303       view->scrollbarsNeedingUpdate = 0;
7304       for (i =[subs count]-1; i >= 0; i--)
7305         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7306           view->scrollbarsNeedingUpdate++;
7307       [sview addSubview: self];
7308     }
7310 /*  [self setFrame: r]; */
7312   return self;
7316 - (void)setFrame: (NSRect)newRect
7318   NSTRACE (EmacsScroller_setFrame);
7319 /*  block_input (); */
7320   pixel_height = NSHeight (newRect);
7321   if (pixel_height == 0) pixel_height = 1;
7322   min_portion = 20 / pixel_height;
7323   [super setFrame: newRect];
7324 /*  unblock_input (); */
7328 - (void)dealloc
7330   NSTRACE (EmacsScroller_dealloc);
7331   if (window)
7332     wset_vertical_scroll_bar (window, Qnil);
7333   window = 0;
7334   [super dealloc];
7338 - condemn
7340   NSTRACE (condemn);
7341   condemned =YES;
7342   return self;
7346 - reprieve
7348   NSTRACE (reprieve);
7349   condemned =NO;
7350   return self;
7354 -(bool)judge
7356   NSTRACE (judge);
7357   bool ret = condemned;
7358   if (condemned)
7359     {
7360       EmacsView *view;
7361       block_input ();
7362       /* ensure other scrollbar updates after deletion */
7363       view = (EmacsView *)FRAME_NS_VIEW (frame);
7364       if (view != nil)
7365         view->scrollbarsNeedingUpdate++;
7366       if (window)
7367         wset_vertical_scroll_bar (window, Qnil);
7368       window = 0;
7369       [self removeFromSuperview];
7370       [self release];
7371       unblock_input ();
7372     }
7373   return ret;
7377 - (void)resetCursorRects
7379   NSRect visible = [self visibleRect];
7380   NSTRACE (resetCursorRects);
7382   if (!NSIsEmptyRect (visible))
7383     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7384   [[NSCursor arrowCursor] setOnMouseEntered: YES];
7388 - (int) checkSamePosition: (int) position portion: (int) portion
7389                     whole: (int) whole
7391   return em_position ==position && em_portion ==portion && em_whole ==whole
7392     && portion != whole; /* needed for resize empty buf */
7396 - setPosition: (int)position portion: (int)portion whole: (int)whole
7398   NSTRACE (setPosition);
7400   em_position = position;
7401   em_portion = portion;
7402   em_whole = whole;
7404   if (portion >= whole)
7405     {
7406 #ifdef NS_IMPL_COCOA
7407       [self setKnobProportion: 1.0];
7408       [self setDoubleValue: 1.0];
7409 #else
7410       [self setFloatValue: 0.0 knobProportion: 1.0];
7411 #endif
7412     }
7413   else
7414     {
7415       float pos;
7416       CGFloat por;
7417       portion = max ((float)whole*min_portion/pixel_height, portion);
7418       pos = (float)position / (whole - portion);
7419       por = (CGFloat)portion/whole;
7420 #ifdef NS_IMPL_COCOA
7421       [self setKnobProportion: por];
7422       [self setDoubleValue: pos];
7423 #else
7424       [self setFloatValue: pos knobProportion: por];
7425 #endif
7426     }
7428   return self;
7431 /* set up emacs_event */
7432 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7434   Lisp_Object win;
7435   if (!emacs_event)
7436     return;
7438   emacs_event->part = last_hit_part;
7439   emacs_event->code = 0;
7440   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7441   XSETWINDOW (win, window);
7442   emacs_event->frame_or_window = win;
7443   emacs_event->timestamp = EV_TIMESTAMP (e);
7444   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7445   emacs_event->arg = Qnil;
7446   XSETINT (emacs_event->x, loc * pixel_height);
7447   XSETINT (emacs_event->y, pixel_height-20);
7449   if (q_event_ptr)
7450     {
7451       n_emacs_events_pending++;
7452       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7453     }
7454   else
7455     hold_event (emacs_event);
7456   EVENT_INIT (*emacs_event);
7457   ns_send_appdefined (-1);
7461 /* called manually thru timer to implement repeated button action w/hold-down */
7462 - repeatScroll: (NSTimer *)scrollEntry
7464   NSEvent *e = [[self window] currentEvent];
7465   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7466   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7468   /* clear timer if need be */
7469   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7470     {
7471         [scroll_repeat_entry invalidate];
7472         [scroll_repeat_entry release];
7473         scroll_repeat_entry = nil;
7475         if (inKnob)
7476           return self;
7478         scroll_repeat_entry
7479           = [[NSTimer scheduledTimerWithTimeInterval:
7480                         SCROLL_BAR_CONTINUOUS_DELAY
7481                                             target: self
7482                                           selector: @selector (repeatScroll:)
7483                                           userInfo: 0
7484                                            repeats: YES]
7485               retain];
7486     }
7488   [self sendScrollEventAtLoc: 0 fromEvent: e];
7489   return self;
7493 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7494    mouseDragged events without going into a modal loop. */
7495 - (void)mouseDown: (NSEvent *)e
7497   NSRect sr, kr;
7498   /* hitPart is only updated AFTER event is passed on */
7499   NSScrollerPart part = [self testPart: [e locationInWindow]];
7500   CGFloat inc = 0.0, loc, kloc, pos;
7501   int edge = 0;
7503   NSTRACE (EmacsScroller_mouseDown);
7505   switch (part)
7506     {
7507     case NSScrollerDecrementPage:
7508         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7509     case NSScrollerIncrementPage:
7510         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7511     case NSScrollerDecrementLine:
7512       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7513     case NSScrollerIncrementLine:
7514       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7515     case NSScrollerKnob:
7516       last_hit_part = scroll_bar_handle; break;
7517     case NSScrollerKnobSlot:  /* GNUstep-only */
7518       last_hit_part = scroll_bar_move_ratio; break;
7519     default:  /* NSScrollerNoPart? */
7520       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7521                (long) part);
7522       return;
7523     }
7525   if (inc != 0.0)
7526     {
7527       pos = 0;      /* ignored */
7529       /* set a timer to repeat, as we can't let superclass do this modally */
7530       scroll_repeat_entry
7531         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7532                                             target: self
7533                                           selector: @selector (repeatScroll:)
7534                                           userInfo: 0
7535                                            repeats: YES]
7536             retain];
7537     }
7538   else
7539     {
7540       /* handle, or on GNUstep possibly slot */
7541       NSEvent *fake_event;
7543       /* compute float loc in slot and mouse offset on knob */
7544       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7545                       toView: nil];
7546       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7547       if (loc <= 0.0)
7548         {
7549           loc = 0.0;
7550           edge = -1;
7551         }
7552       else if (loc >= NSHeight (sr))
7553         {
7554           loc = NSHeight (sr);
7555           edge = 1;
7556         }
7558       if (edge)
7559         kloc = 0.5 * edge;
7560       else
7561         {
7562           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7563                           toView: nil];
7564           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7565         }
7566       last_mouse_offset = kloc;
7568       /* if knob, tell emacs a location offset by knob pos
7569          (to indicate top of handle) */
7570       if (part == NSScrollerKnob)
7571           pos = (loc - last_mouse_offset) / NSHeight (sr);
7572       else
7573         /* else this is a slot click on GNUstep: go straight there */
7574         pos = loc / NSHeight (sr);
7576       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7577       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7578                                       location: [e locationInWindow]
7579                                  modifierFlags: [e modifierFlags]
7580                                      timestamp: [e timestamp]
7581                                   windowNumber: [e windowNumber]
7582                                        context: [e context]
7583                                    eventNumber: [e eventNumber]
7584                                     clickCount: [e clickCount]
7585                                       pressure: [e pressure]];
7586       [super mouseUp: fake_event];
7587     }
7589   if (part != NSScrollerKnob)
7590     [self sendScrollEventAtLoc: pos fromEvent: e];
7594 /* Called as we manually track scroller drags, rather than superclass. */
7595 - (void)mouseDragged: (NSEvent *)e
7597     NSRect sr;
7598     double loc, pos;
7600     NSTRACE (EmacsScroller_mouseDragged);
7602       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7603                       toView: nil];
7604       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7606       if (loc <= 0.0)
7607         {
7608           loc = 0.0;
7609         }
7610       else if (loc >= NSHeight (sr) + last_mouse_offset)
7611         {
7612           loc = NSHeight (sr) + last_mouse_offset;
7613         }
7615       pos = (loc - last_mouse_offset) / NSHeight (sr);
7616       [self sendScrollEventAtLoc: pos fromEvent: e];
7620 - (void)mouseUp: (NSEvent *)e
7622   if (scroll_repeat_entry)
7623     {
7624       [scroll_repeat_entry invalidate];
7625       [scroll_repeat_entry release];
7626       scroll_repeat_entry = nil;
7627     }
7628   last_hit_part = scroll_bar_above_handle;
7632 /* treat scrollwheel events in the bar as though they were in the main window */
7633 - (void) scrollWheel: (NSEvent *)theEvent
7635   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7636   [view mouseDown: theEvent];
7639 @end  /* EmacsScroller */
7642 #ifdef NS_IMPL_GNUSTEP
7643 /* Dummy class to get rid of startup warnings.  */
7644 @implementation EmacsDocument
7646 @end
7647 #endif
7650 /* ==========================================================================
7652    Font-related functions; these used to be in nsfaces.m
7654    ========================================================================== */
7657 Lisp_Object
7658 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7660   struct font *font = XFONT_OBJECT (font_object);
7661   EmacsView *view = FRAME_NS_VIEW (f);
7663   if (fontset < 0)
7664     fontset = fontset_from_font (font_object);
7665   FRAME_FONTSET (f) = fontset;
7667   if (FRAME_FONT (f) == font)
7668     /* This font is already set in frame F.  There's nothing more to
7669        do.  */
7670     return font_object;
7672   FRAME_FONT (f) = font;
7674   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7675   FRAME_COLUMN_WIDTH (f) = font->average_width;
7676   FRAME_LINE_HEIGHT (f) = font->height;
7678   /* Compute the scroll bar width in character columns.  */
7679   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7680     {
7681       int wid = FRAME_COLUMN_WIDTH (f);
7682       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7683         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7684     }
7685   else
7686     {
7687       int wid = FRAME_COLUMN_WIDTH (f);
7688       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7689     }
7691   /* Compute the scroll bar height in character lines.  */
7692   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7693     {
7694       int height = FRAME_LINE_HEIGHT (f);
7695       FRAME_CONFIG_SCROLL_BAR_LINES (f)
7696         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7697     }
7698   else
7699     {
7700       int height = FRAME_LINE_HEIGHT (f);
7701       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7702     }
7704   /* Now make the frame display the given font.  */
7705   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7706     x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7707                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7709   return font_object;
7713 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7714 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7715          in 1.43. */
7717 const char *
7718 ns_xlfd_to_fontname (const char *xlfd)
7719 /* --------------------------------------------------------------------------
7720     Convert an X font name (XLFD) to an NS font name.
7721     Only family is used.
7722     The string returned is temporarily allocated.
7723    -------------------------------------------------------------------------- */
7725   char *name = xmalloc (180);
7726   int i, len;
7727   const char *ret;
7729   if (!strncmp (xlfd, "--", 2))
7730     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7731   else
7732     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7734   /* stopgap for malformed XLFD input */
7735   if (strlen (name) == 0)
7736     strcpy (name, "Monaco");
7738   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7739      also uppercase after '-' or ' ' */
7740   name[0] = c_toupper (name[0]);
7741   for (len =strlen (name), i =0; i<len; i++)
7742     {
7743       if (name[i] == '$')
7744         {
7745           name[i] = '-';
7746           if (i+1<len)
7747             name[i+1] = c_toupper (name[i+1]);
7748         }
7749       else if (name[i] == '_')
7750         {
7751           name[i] = ' ';
7752           if (i+1<len)
7753             name[i+1] = c_toupper (name[i+1]);
7754         }
7755     }
7756 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7757   ret = [[NSString stringWithUTF8String: name] UTF8String];
7758   xfree (name);
7759   return ret;
7763 void
7764 syms_of_nsterm (void)
7766   NSTRACE (syms_of_nsterm);
7768   ns_antialias_threshold = 10.0;
7770   /* from 23+ we need to tell emacs what modifiers there are.. */
7771   DEFSYM (Qmodifier_value, "modifier-value");
7772   DEFSYM (Qalt, "alt");
7773   DEFSYM (Qhyper, "hyper");
7774   DEFSYM (Qmeta, "meta");
7775   DEFSYM (Qsuper, "super");
7776   DEFSYM (Qcontrol, "control");
7777   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7779   DEFSYM (Qfile, "file");
7780   DEFSYM (Qurl, "url");
7782   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7783   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7784   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7785   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7786   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7788   DEFVAR_LISP ("ns-input-file", ns_input_file,
7789               "The file specified in the last NS event.");
7790   ns_input_file =Qnil;
7792   DEFVAR_LISP ("ns-working-text", ns_working_text,
7793               "String for visualizing working composition sequence.");
7794   ns_working_text =Qnil;
7796   DEFVAR_LISP ("ns-input-font", ns_input_font,
7797               "The font specified in the last NS event.");
7798   ns_input_font =Qnil;
7800   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7801               "The fontsize specified in the last NS event.");
7802   ns_input_fontsize =Qnil;
7804   DEFVAR_LISP ("ns-input-line", ns_input_line,
7805                "The line specified in the last NS event.");
7806   ns_input_line =Qnil;
7808   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7809                "The service name specified in the last NS event.");
7810   ns_input_spi_name =Qnil;
7812   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7813                "The service argument specified in the last NS event.");
7814   ns_input_spi_arg =Qnil;
7816   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7817                "This variable describes the behavior of the alternate or option key.\n\
7818 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7819 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7820 at all, allowing it to be used at a lower level for accented character entry.");
7821   ns_alternate_modifier = Qmeta;
7823   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7824                "This variable describes the behavior of the right alternate or option key.\n\
7825 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7826 Set to left means be the same key as `ns-alternate-modifier'.\n\
7827 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7828 at all, allowing it to be used at a lower level for accented character entry.");
7829   ns_right_alternate_modifier = Qleft;
7831   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7832                "This variable describes the behavior of the command key.\n\
7833 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7834   ns_command_modifier = Qsuper;
7836   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7837                "This variable describes the behavior of the right command key.\n\
7838 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7839 Set to left means be the same key as `ns-command-modifier'.\n\
7840 Set to none means that the command / option key is not interpreted by Emacs\n\
7841 at all, allowing it to be used at a lower level for accented character entry.");
7842   ns_right_command_modifier = Qleft;
7844   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7845                "This variable describes the behavior of the control key.\n\
7846 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7847   ns_control_modifier = Qcontrol;
7849   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7850                "This variable describes the behavior of the right control key.\n\
7851 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7852 Set to left means be the same key as `ns-control-modifier'.\n\
7853 Set to none means that the control / option key is not interpreted by Emacs\n\
7854 at all, allowing it to be used at a lower level for accented character entry.");
7855   ns_right_control_modifier = Qleft;
7857   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7858                "This variable describes the behavior of the function key (on laptops).\n\
7859 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7860 Set to none means that the function key is not interpreted by Emacs at all,\n\
7861 allowing it to be used at a lower level for accented character entry.");
7862   ns_function_modifier = Qnone;
7864   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7865                "Non-nil (the default) means to render text antialiased.");
7866   ns_antialias_text = Qt;
7868   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7869                "Whether to confirm application quit using dialog.");
7870   ns_confirm_quit = Qnil;
7872   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7873                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7874 Only works on OSX 10.6 or later.  */);
7875   ns_auto_hide_menu_bar = Qnil;
7877   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7878      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7879 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7880 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7881 Default is t for OSX >= 10.7, nil otherwise.  */);
7882 #ifdef HAVE_NATIVE_FS
7883   ns_use_native_fullscreen = YES;
7884 #else
7885   ns_use_native_fullscreen = NO;
7886 #endif
7887   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7889   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7890      doc: /*Non-nil means use animation on non-native fullscreen.
7891 For native fullscreen, this does nothing.
7892 Default is nil.  */);
7893   ns_use_fullscreen_animation = NO;
7895   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7896      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7897 Note that this does not apply to images.
7898 This variable is ignored on OSX < 10.7 and GNUstep.  */);
7899   ns_use_srgb_colorspace = YES;
7901   /* TODO: move to common code */
7902   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7903                doc: /* Which toolkit scroll bars Emacs uses, if any.
7904 A value of nil means Emacs doesn't use toolkit scroll bars.
7905 With the X Window system, the value is a symbol describing the
7906 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7907 With MS Windows or Nextstep, the value is t.  */);
7908   Vx_toolkit_scroll_bars = Qt;
7910   DEFVAR_BOOL ("x-use-underline-position-properties",
7911                x_use_underline_position_properties,
7912      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7913 A value of nil means ignore them.  If you encounter fonts with bogus
7914 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7915 to 4.1, set this to nil. */);
7916   x_use_underline_position_properties = 0;
7918   DEFVAR_BOOL ("x-underline-at-descent-line",
7919                x_underline_at_descent_line,
7920      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7921 A value of nil means to draw the underline according to the value of the
7922 variable `x-use-underline-position-properties', which is usually at the
7923 baseline level.  The default value is nil.  */);
7924   x_underline_at_descent_line = 0;
7926   /* Tell Emacs about this window system.  */
7927   Fprovide (Qns, Qnil);
7929   DEFSYM (Qcocoa, "cocoa");
7930   DEFSYM (Qgnustep, "gnustep");
7932 #ifdef NS_IMPL_COCOA
7933   Fprovide (Qcocoa, Qnil);
7934   syms_of_macfont ();
7935 #else
7936   Fprovide (Qgnustep, Qnil);
7937   syms_of_nsfont ();
7938 #endif