Fix problems caught with --enable-gcc-warnings
[emacs.git] / src / nsterm.m
blob65d07b2f1e46a8622fcca4ddabda3fb05162996a
1 /* NeXT/Open/GNUstep / MacOSX communication module.      -*- coding: utf-8 -*-
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   return CALLN (Fnconc, list, list1 (item));
447 const char *
448 ns_etc_directory (void)
449 /* If running as a self-contained app bundle, return as a string the
450    filename of the etc directory, if present; else nil.  */
452   NSBundle *bundle = [NSBundle mainBundle];
453   NSString *resourceDir = [bundle resourcePath];
454   NSString *resourcePath;
455   NSFileManager *fileManager = [NSFileManager defaultManager];
456   BOOL isDir;
458   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
459   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
460     {
461       if (isDir) return [resourcePath UTF8String];
462     }
463   return NULL;
467 const char *
468 ns_exec_path (void)
469 /* If running as a self-contained app bundle, return as a path string
470    the filenames of the libexec and bin directories, ie libexec:bin.
471    Otherwise, return nil.
472    Normally, Emacs does not add its own bin/ directory to the PATH.
473    However, a self-contained NS build has a different layout, with
474    bin/ and libexec/ subdirectories in the directory that contains
475    Emacs.app itself.
476    We put libexec first, because init_callproc_1 uses the first
477    element to initialize exec-directory.  An alternative would be
478    for init_callproc to check for invocation-directory/libexec.
481   NSBundle *bundle = [NSBundle mainBundle];
482   NSString *resourceDir = [bundle resourcePath];
483   NSString *binDir = [bundle bundlePath];
484   NSString *resourcePath, *resourcePaths;
485   NSRange range;
486   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
487   NSFileManager *fileManager = [NSFileManager defaultManager];
488   NSArray *paths;
489   NSEnumerator *pathEnum;
490   BOOL isDir;
492   range = [resourceDir rangeOfString: @"Contents"];
493   if (range.location != NSNotFound)
494     {
495       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
496 #ifdef NS_IMPL_COCOA
497       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
498 #endif
499     }
501   paths = [binDir stringsByAppendingPaths:
502                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
503   pathEnum = [paths objectEnumerator];
504   resourcePaths = @"";
506   while ((resourcePath = [pathEnum nextObject]))
507     {
508       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
509         if (isDir)
510           {
511             if ([resourcePaths length] > 0)
512               resourcePaths
513                 = [resourcePaths stringByAppendingString: pathSeparator];
514             resourcePaths
515               = [resourcePaths stringByAppendingString: resourcePath];
516           }
517     }
518   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
520   return NULL;
524 const char *
525 ns_load_path (void)
526 /* If running as a self-contained app bundle, return as a path string
527    the filenames of the site-lisp and lisp directories.
528    Ie, site-lisp:lisp.  Otherwise, return nil.  */
530   NSBundle *bundle = [NSBundle mainBundle];
531   NSString *resourceDir = [bundle resourcePath];
532   NSString *resourcePath, *resourcePaths;
533   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
534   NSFileManager *fileManager = [NSFileManager defaultManager];
535   BOOL isDir;
536   NSArray *paths = [resourceDir stringsByAppendingPaths:
537                               [NSArray arrayWithObjects:
538                                          @"site-lisp", @"lisp", nil]];
539   NSEnumerator *pathEnum = [paths objectEnumerator];
540   resourcePaths = @"";
542   /* Hack to skip site-lisp.  */
543   if (no_site_lisp) resourcePath = [pathEnum nextObject];
545   while ((resourcePath = [pathEnum nextObject]))
546     {
547       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
548         if (isDir)
549           {
550             if ([resourcePaths length] > 0)
551               resourcePaths
552                 = [resourcePaths stringByAppendingString: pathSeparator];
553             resourcePaths
554               = [resourcePaths stringByAppendingString: resourcePath];
555           }
556     }
557   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
559   return NULL;
562 static void
563 ns_timeout (int usecs)
564 /* --------------------------------------------------------------------------
565      Blocking timer utility used by ns_ring_bell
566    -------------------------------------------------------------------------- */
568   struct timespec wakeup = timespec_add (current_timespec (),
569                                          make_timespec (0, usecs * 1000));
571   /* Keep waiting until past the time wakeup.  */
572   while (1)
573     {
574       struct timespec timeout, now = current_timespec ();
575       if (timespec_cmp (wakeup, now) <= 0)
576         break;
577       timeout = timespec_sub (wakeup, now);
579       /* Try to wait that long--but we might wake up sooner.  */
580       pselect (0, NULL, NULL, NULL, &timeout, NULL);
581     }
585 void
586 ns_release_object (void *obj)
587 /* --------------------------------------------------------------------------
588     Release an object (callable from C)
589    -------------------------------------------------------------------------- */
591     [(id)obj release];
595 void
596 ns_retain_object (void *obj)
597 /* --------------------------------------------------------------------------
598     Retain an object (callable from C)
599    -------------------------------------------------------------------------- */
601     [(id)obj retain];
605 void *
606 ns_alloc_autorelease_pool (void)
607 /* --------------------------------------------------------------------------
608      Allocate a pool for temporary objects (callable from C)
609    -------------------------------------------------------------------------- */
611   return [[NSAutoreleasePool alloc] init];
615 void
616 ns_release_autorelease_pool (void *pool)
617 /* --------------------------------------------------------------------------
618      Free a pool and temporary objects it refers to (callable from C)
619    -------------------------------------------------------------------------- */
621   ns_release_object (pool);
626 /* ==========================================================================
628     Focus (clipping) and screen update
630    ========================================================================== */
633 // Window constraining
634 // -------------------
636 // To ensure that the windows are not placed under the menu bar, they
637 // are typically moved by the call-back constrainFrameRect. However,
638 // by overriding it, it's possible to inhibit this, leaving the window
639 // in it's original position.
641 // It's possible to hide the menu bar. However, technically, it's only
642 // possible to hide it when the application is active. To ensure that
643 // this work properly, the menu bar and window constraining are
644 // deferred until the application becomes active.
646 // Even though it's not possible to manually move a window above the
647 // top of the screen, it is allowed if it's done programmatically,
648 // when the menu is hidden. This allows the editable area to cover the
649 // full screen height.
651 // Test cases
652 // ----------
654 // Use the following extra files:
656 //    init.el:
657 //       ;; Hide menu and place frame slightly above the top of the screen.
658 //       (setq ns-auto-hide-menu-bar t)
659 //       (set-frame-position (selected-frame) 0 -20)
661 // Test 1:
663 //    emacs -Q -l init.el
665 //    Result: No menu bar, and the title bar should be above the screen.
667 // Test 2:
669 //    emacs -Q
671 //    Result: Menu bar visible, frame placed immediately below the menu.
674 static void
675 ns_constrain_all_frames (void)
677   Lisp_Object tail, frame;
679   FOR_EACH_FRAME (tail, frame)
680     {
681       struct frame *f = XFRAME (frame);
682       if (FRAME_NS_P (f))
683         {
684           NSView *view = FRAME_NS_VIEW (f);
685           /* This no-op will trigger the default window placing
686            * constraint system. */
687           [[view window] setFrameOrigin:[[view window] frame].origin];
688         }
689     }
693 /* True, if the menu bar should be hidden.  */
695 static BOOL
696 ns_menu_bar_should_be_hidden (void)
698   return !NILP (ns_auto_hide_menu_bar)
699     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
703 /* Show or hide the menu bar, based on user setting.  */
705 static void
706 ns_update_auto_hide_menu_bar (void)
708 #ifdef NS_IMPL_COCOA
709   block_input ();
711   NSTRACE (ns_update_auto_hide_menu_bar);
713   if (NSApp != nil && [NSApp isActive])
714     {
715       // Note, "setPresentationOptions" triggers an error unless the
716       // application is active.
717       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
719       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
720         {
721           NSApplicationPresentationOptions options
722             = NSApplicationPresentationDefault;
724           if (menu_bar_should_be_hidden)
725             options |= NSApplicationPresentationAutoHideMenuBar
726               | NSApplicationPresentationAutoHideDock;
728           [NSApp setPresentationOptions: options];
730           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
732           if (!ns_menu_bar_is_hidden)
733             {
734               ns_constrain_all_frames ();
735             }
736         }
737     }
739   unblock_input ();
740 #endif
744 static void
745 ns_update_begin (struct frame *f)
746 /* --------------------------------------------------------------------------
747    Prepare for a grouped sequence of drawing calls
748    external (RIF) call; whole frame, called before update_window_begin
749    -------------------------------------------------------------------------- */
751   EmacsView *view = FRAME_NS_VIEW (f);
752   NSTRACE (ns_update_begin);
754   ns_update_auto_hide_menu_bar ();
756 #ifdef NS_IMPL_COCOA
757   if ([view isFullscreen] && [view fsIsNative])
758   {
759     // Fix reappearing tool bar in fullscreen for OSX 10.7
760     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
761     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
762     if (! tbar_visible != ! [toolbar isVisible])
763       [toolbar setVisible: tbar_visible];
764   }
765 #endif
767   ns_updating_frame = f;
768   [view lockFocus];
770   /* drawRect may have been called for say the minibuffer, and then clip path
771      is for the minibuffer.  But the display engine may draw more because
772      we have set the frame as garbaged.  So reset clip path to the whole
773      view.  */
774 #ifdef NS_IMPL_COCOA
775   {
776     NSBezierPath *bp;
777     NSRect r = [view frame];
778     NSRect cr = [[view window] frame];
779     /* If a large frame size is set, r may be larger than the window frame
780        before constrained.  In that case don't change the clip path, as we
781        will clear in to the tool bar and title bar.  */
782     if (r.size.height
783         + FRAME_NS_TITLEBAR_HEIGHT (f)
784         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
785       {
786         bp = [[NSBezierPath bezierPathWithRect: r] retain];
787         [bp setClip];
788         [bp release];
789       }
790   }
791 #endif
793 #ifdef NS_IMPL_GNUSTEP
794   uRect = NSMakeRect (0, 0, 0, 0);
795 #endif
799 static void
800 ns_update_window_begin (struct window *w)
801 /* --------------------------------------------------------------------------
802    Prepare for a grouped sequence of drawing calls
803    external (RIF) call; for one window, called after update_begin
804    -------------------------------------------------------------------------- */
806   struct frame *f = XFRAME (WINDOW_FRAME (w));
807   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
809   NSTRACE (ns_update_window_begin);
810   w->output_cursor = w->cursor;
812   block_input ();
814   if (f == hlinfo->mouse_face_mouse_frame)
815     {
816       /* Don't do highlighting for mouse motion during the update.  */
817       hlinfo->mouse_face_defer = 1;
819         /* If the frame needs to be redrawn,
820            simply forget about any prior mouse highlighting.  */
821       if (FRAME_GARBAGED_P (f))
822         hlinfo->mouse_face_window = Qnil;
824       /* (further code for mouse faces ifdef'd out in other terms elided) */
825     }
827   unblock_input ();
831 static void
832 ns_update_window_end (struct window *w, bool cursor_on_p,
833                       bool mouse_face_overwritten_p)
834 /* --------------------------------------------------------------------------
835    Finished a grouped sequence of drawing calls
836    external (RIF) call; for one window called before update_end
837    -------------------------------------------------------------------------- */
839   /* note: this fn is nearly identical in all terms */
840   if (!w->pseudo_window_p)
841     {
842       block_input ();
844       if (cursor_on_p)
845         display_and_set_cursor (w, 1,
846                                 w->output_cursor.hpos, w->output_cursor.vpos,
847                                 w->output_cursor.x, w->output_cursor.y);
849       if (draw_window_fringes (w, 1))
850         {
851           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
852             x_draw_right_divider (w);
853           else
854             x_draw_vertical_border (w);
855         }
857       unblock_input ();
858     }
860   /* If a row with mouse-face was overwritten, arrange for
861      frame_up_to_date to redisplay the mouse highlight.  */
862   if (mouse_face_overwritten_p)
863     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
865   NSTRACE (update_window_end);
869 static void
870 ns_update_end (struct frame *f)
871 /* --------------------------------------------------------------------------
872    Finished a grouped sequence of drawing calls
873    external (RIF) call; for whole frame, called after update_window_end
874    -------------------------------------------------------------------------- */
876   EmacsView *view = FRAME_NS_VIEW (f);
878 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
879   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
881   block_input ();
883   [view unlockFocus];
884   [[view window] flushWindow];
886   unblock_input ();
887   ns_updating_frame = NULL;
888   NSTRACE (ns_update_end);
891 static void
892 ns_focus (struct frame *f, NSRect *r, int n)
893 /* --------------------------------------------------------------------------
894    Internal: Focus on given frame.  During small local updates this is used to
895      draw, however during large updates, ns_update_begin and ns_update_end are
896      called to wrap the whole thing, in which case these calls are stubbed out.
897      Except, on GNUstep, we accumulate the rectangle being drawn into, because
898      the back end won't do this automatically, and will just end up flushing
899      the entire window.
900    -------------------------------------------------------------------------- */
902 //  NSTRACE (ns_focus);
903 /* static int c =0;
904    fprintf (stderr, "focus: %d", c++);
905    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
906    fprintf (stderr, "\n"); */
908   if (f != ns_updating_frame)
909     {
910       NSView *view = FRAME_NS_VIEW (f);
911       if (view != focus_view)
912         {
913           if (focus_view != NULL)
914             {
915               [focus_view unlockFocus];
916               [[focus_view window] flushWindow];
917 /*debug_lock--; */
918             }
920           if (view)
921             [view lockFocus];
922           focus_view = view;
923 /*if (view) debug_lock++; */
924         }
925     }
927   /* clipping */
928   if (r)
929     {
930       [[NSGraphicsContext currentContext] saveGraphicsState];
931       if (n == 2)
932         NSRectClipList (r, 2);
933       else
934         NSRectClip (*r);
935       gsaved = YES;
936     }
940 static void
941 ns_unfocus (struct frame *f)
942 /* --------------------------------------------------------------------------
943      Internal: Remove focus on given frame
944    -------------------------------------------------------------------------- */
946 //  NSTRACE (ns_unfocus);
948   if (gsaved)
949     {
950       [[NSGraphicsContext currentContext] restoreGraphicsState];
951       gsaved = NO;
952     }
954   if (f != ns_updating_frame)
955     {
956       if (focus_view != NULL)
957         {
958           [focus_view unlockFocus];
959           [[focus_view window] flushWindow];
960           focus_view = NULL;
961 /*debug_lock--; */
962         }
963     }
967 static void
968 ns_clip_to_row (struct window *w, struct glyph_row *row,
969                 enum glyph_row_area area, BOOL gc)
970 /* --------------------------------------------------------------------------
971      Internal (but parallels other terms): Focus drawing on given row
972    -------------------------------------------------------------------------- */
974   struct frame *f = XFRAME (WINDOW_FRAME (w));
975   NSRect clip_rect;
976   int window_x, window_y, window_width;
978   window_box (w, area, &window_x, &window_y, &window_width, 0);
980   clip_rect.origin.x = window_x;
981   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
982   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
983   clip_rect.size.width = window_width;
984   clip_rect.size.height = row->visible_height;
986   ns_focus (f, &clip_rect, 1);
990 static void
991 ns_ring_bell (struct frame *f)
992 /* --------------------------------------------------------------------------
993      "Beep" routine
994    -------------------------------------------------------------------------- */
996   NSTRACE (ns_ring_bell);
997   if (visible_bell)
998     {
999       NSAutoreleasePool *pool;
1000       struct frame *frame = SELECTED_FRAME ();
1001       NSView *view;
1003       block_input ();
1004       pool = [[NSAutoreleasePool alloc] init];
1006       view = FRAME_NS_VIEW (frame);
1007       if (view != nil)
1008         {
1009           NSRect r, surr;
1010           NSPoint dim = NSMakePoint (128, 128);
1012           r = [view bounds];
1013           r.origin.x += (r.size.width - dim.x) / 2;
1014           r.origin.y += (r.size.height - dim.y) / 2;
1015           r.size.width = dim.x;
1016           r.size.height = dim.y;
1017           surr = NSInsetRect (r, -2, -2);
1018           ns_focus (frame, &surr, 1);
1019           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1020           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1021                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
1022           NSRectFill (r);
1023           [[view window] flushWindow];
1024           ns_timeout (150000);
1025           [[view window] restoreCachedImage];
1026           [[view window] flushWindow];
1027           ns_unfocus (frame);
1028         }
1029       [pool release];
1030       unblock_input ();
1031     }
1032   else
1033     {
1034       NSBeep ();
1035     }
1038 /* ==========================================================================
1040     Frame / window manager related functions
1042    ========================================================================== */
1045 static void
1046 ns_raise_frame (struct frame *f)
1047 /* --------------------------------------------------------------------------
1048      Bring window to foreground and make it active
1049    -------------------------------------------------------------------------- */
1051   NSView *view;
1052   check_window_system (f);
1053   view = FRAME_NS_VIEW (f);
1054   block_input ();
1055   if (FRAME_VISIBLE_P (f))
1056     [[view window] makeKeyAndOrderFront: NSApp];
1057   unblock_input ();
1061 static void
1062 ns_lower_frame (struct frame *f)
1063 /* --------------------------------------------------------------------------
1064      Send window to back
1065    -------------------------------------------------------------------------- */
1067   NSView *view;
1068   check_window_system (f);
1069   view = FRAME_NS_VIEW (f);
1070   block_input ();
1071   [[view window] orderBack: NSApp];
1072   unblock_input ();
1076 static void
1077 ns_frame_raise_lower (struct frame *f, bool raise)
1078 /* --------------------------------------------------------------------------
1079      External (hook)
1080    -------------------------------------------------------------------------- */
1082   NSTRACE (ns_frame_raise_lower);
1084   if (raise)
1085     ns_raise_frame (f);
1086   else
1087     ns_lower_frame (f);
1091 static void
1092 ns_frame_rehighlight (struct frame *frame)
1093 /* --------------------------------------------------------------------------
1094      External (hook): called on things like window switching within frame
1095    -------------------------------------------------------------------------- */
1097   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1098   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1100   NSTRACE (ns_frame_rehighlight);
1101   if (dpyinfo->x_focus_frame)
1102     {
1103       dpyinfo->x_highlight_frame
1104         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1105            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1106            : dpyinfo->x_focus_frame);
1107       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1108         {
1109           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1110           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1111         }
1112     }
1113   else
1114       dpyinfo->x_highlight_frame = 0;
1116   if (dpyinfo->x_highlight_frame &&
1117          dpyinfo->x_highlight_frame != old_highlight)
1118     {
1119       if (old_highlight)
1120         {
1121           x_update_cursor (old_highlight, 1);
1122           x_set_frame_alpha (old_highlight);
1123         }
1124       if (dpyinfo->x_highlight_frame)
1125         {
1126           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1127           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1128         }
1129     }
1133 void
1134 x_make_frame_visible (struct frame *f)
1135 /* --------------------------------------------------------------------------
1136      External: Show the window (X11 semantics)
1137    -------------------------------------------------------------------------- */
1139   NSTRACE (x_make_frame_visible);
1140   /* XXX: at some points in past this was not needed, as the only place that
1141      called this (frame.c:Fraise_frame ()) also called raise_lower;
1142      if this ends up the case again, comment this out again. */
1143   if (!FRAME_VISIBLE_P (f))
1144     {
1145       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1147       SET_FRAME_VISIBLE (f, 1);
1148       ns_raise_frame (f);
1150       /* Making a new frame from a fullscreen frame will make the new frame
1151          fullscreen also.  So skip handleFS as this will print an error.  */
1152       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1153           && [view isFullscreen])
1154         return;
1156       if (f->want_fullscreen != FULLSCREEN_NONE)
1157         {
1158           block_input ();
1159           [view handleFS];
1160           unblock_input ();
1161         }
1162     }
1166 void
1167 x_make_frame_invisible (struct frame *f)
1168 /* --------------------------------------------------------------------------
1169      External: Hide the window (X11 semantics)
1170    -------------------------------------------------------------------------- */
1172   NSView *view;
1173   NSTRACE (x_make_frame_invisible);
1174   check_window_system (f);
1175   view = FRAME_NS_VIEW (f);
1176   [[view window] orderOut: NSApp];
1177   SET_FRAME_VISIBLE (f, 0);
1178   SET_FRAME_ICONIFIED (f, 0);
1182 void
1183 x_iconify_frame (struct frame *f)
1184 /* --------------------------------------------------------------------------
1185      External: Iconify window
1186    -------------------------------------------------------------------------- */
1188   NSView *view;
1189   struct ns_display_info *dpyinfo;
1191   NSTRACE (x_iconify_frame);
1192   check_window_system (f);
1193   view = FRAME_NS_VIEW (f);
1194   dpyinfo = FRAME_DISPLAY_INFO (f);
1196   if (dpyinfo->x_highlight_frame == f)
1197     dpyinfo->x_highlight_frame = 0;
1199   if ([[view window] windowNumber] <= 0)
1200     {
1201       /* the window is still deferred.  Make it very small, bring it
1202          on screen and order it out. */
1203       NSRect s = { { 100, 100}, {0, 0} };
1204       NSRect t;
1205       t = [[view window] frame];
1206       [[view window] setFrame: s display: NO];
1207       [[view window] orderBack: NSApp];
1208       [[view window] orderOut: NSApp];
1209       [[view window] setFrame: t display: NO];
1210     }
1211   [[view window] miniaturize: NSApp];
1214 /* Free X resources of frame F.  */
1216 void
1217 x_free_frame_resources (struct frame *f)
1219   NSView *view;
1220   struct ns_display_info *dpyinfo;
1221   Mouse_HLInfo *hlinfo;
1223   NSTRACE (x_free_frame_resources);
1224   check_window_system (f);
1225   view = FRAME_NS_VIEW (f);
1226   dpyinfo = FRAME_DISPLAY_INFO (f);
1227   hlinfo = MOUSE_HL_INFO (f);
1229   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1231   block_input ();
1233   free_frame_menubar (f);
1234   free_frame_faces (f);
1236   if (f == dpyinfo->x_focus_frame)
1237     dpyinfo->x_focus_frame = 0;
1238   if (f == dpyinfo->x_highlight_frame)
1239     dpyinfo->x_highlight_frame = 0;
1240   if (f == hlinfo->mouse_face_mouse_frame)
1241     reset_mouse_highlight (hlinfo);
1243   if (f->output_data.ns->miniimage != nil)
1244     [f->output_data.ns->miniimage release];
1246   [[view window] close];
1247   [view release];
1249   xfree (f->output_data.ns);
1251   unblock_input ();
1254 void
1255 x_destroy_window (struct frame *f)
1256 /* --------------------------------------------------------------------------
1257      External: Delete the window
1258    -------------------------------------------------------------------------- */
1260   NSTRACE (x_destroy_window);
1261   check_window_system (f);
1262   x_free_frame_resources (f);
1263   ns_window_num--;
1267 void
1268 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1269 /* --------------------------------------------------------------------------
1270      External: Position the window
1271    -------------------------------------------------------------------------- */
1273   NSView *view = FRAME_NS_VIEW (f);
1274   NSArray *screens = [NSScreen screens];
1275   NSScreen *fscreen = [screens objectAtIndex: 0];
1276   NSScreen *screen = [[view window] screen];
1278   NSTRACE (x_set_offset);
1280   block_input ();
1282   f->left_pos = xoff;
1283   f->top_pos = yoff;
1285   if (view != nil && screen && fscreen)
1286     {
1287       f->left_pos = f->size_hint_flags & XNegative
1288         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1289         : f->left_pos;
1290       /* We use visibleFrame here to take menu bar into account.
1291          Ideally we should also adjust left/top with visibleFrame.origin.  */
1293       f->top_pos = f->size_hint_flags & YNegative
1294         ? ([screen visibleFrame].size.height + f->top_pos
1295            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1296            - FRAME_TOOLBAR_HEIGHT (f))
1297         : f->top_pos;
1298 #ifdef NS_IMPL_GNUSTEP
1299       if (f->left_pos < 100)
1300         f->left_pos = 100;  /* don't overlap menu */
1301 #endif
1302       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1303          menu bar.  */
1304       [[view window] setFrameTopLeftPoint:
1305                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1306                                     SCREENMAXBOUND ([fscreen frame].size.height
1307                                                     - NS_TOP_POS (f)))];
1308       f->size_hint_flags &= ~(XNegative|YNegative);
1309     }
1311   unblock_input ();
1315 void
1316 x_set_window_size (struct frame *f,
1317                    bool change_gravity,
1318                    int width,
1319                    int height,
1320                    bool pixelwise)
1321 /* --------------------------------------------------------------------------
1322      Adjust window pixel size based on given character grid size
1323      Impl is a bit more complex than other terms, need to do some
1324      internal clipping.
1325    -------------------------------------------------------------------------- */
1327   EmacsView *view = FRAME_NS_VIEW (f);
1328   NSWindow *window = [view window];
1329   NSRect wr = [window frame];
1330   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1331   int pixelwidth, pixelheight;
1332   int rows, cols;
1333   int orig_height = wr.size.height;
1335   NSTRACE (x_set_window_size);
1337   if (view == nil)
1338     return;
1340 /*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));*/
1342   block_input ();
1344   if (pixelwise)
1345     {
1346       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1347       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1348       cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1349       rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1350     }
1351   else
1352     {
1353       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1354       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1355       cols = width;
1356       rows = height;
1357     }
1359   /* If we have a toolbar, take its height into account. */
1360   if (tb && ! [view isFullscreen])
1361     {
1362     /* NOTE: previously this would generate wrong result if toolbar not
1363              yet displayed and fixing toolbar_height=32 helped, but
1364              now (200903) seems no longer needed */
1365     FRAME_TOOLBAR_HEIGHT (f) =
1366       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1367         - FRAME_NS_TITLEBAR_HEIGHT (f);
1368 #ifdef NS_IMPL_GNUSTEP
1369       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1370 #endif
1371     }
1372   else
1373     FRAME_TOOLBAR_HEIGHT (f) = 0;
1375   wr.size.width = pixelwidth + f->border_width;
1376   wr.size.height = pixelheight;
1377   if (! [view isFullscreen])
1378     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1379       + FRAME_TOOLBAR_HEIGHT (f);
1381   /* Do not try to constrain to this screen.  We may have multiple
1382      screens, and want Emacs to span those.  Constraining to screen
1383      prevents that, and that is not nice to the user.  */
1384  if (f->output_data.ns->zooming)
1385    f->output_data.ns->zooming = 0;
1386  else
1387    wr.origin.y += orig_height - wr.size.height;
1389   [view setRows: rows andColumns: cols];
1390   [window setFrame: wr display: YES];
1392   /* This is a trick to compensate for Emacs' managing the scrollbar area
1393      as a fixed number of standard character columns.  Instead of leaving
1394      blank space for the extra, we chopped it off above.  Now for
1395      left-hand scrollbars, we shift all rendering to the left by the
1396      difference between the real width and Emacs' imagined one.  For
1397      right-hand bars, don't worry about it since the extra is never used.
1398      (Obviously doesn't work for vertically split windows tho..) */
1399   {
1400     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1401       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1402                      - NS_SCROLL_BAR_WIDTH (f), 0)
1403       : NSMakePoint (0, 0);
1404     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1405     [view setBoundsOrigin: origin];
1406   }
1408   [view updateFrameSize: NO];
1409   unblock_input ();
1413 static void
1414 ns_fullscreen_hook (struct frame *f)
1416   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1418   if (!FRAME_VISIBLE_P (f))
1419     return;
1421    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1422     {
1423       /* Old style fs don't initiate correctly if created from
1424          init/default-frame alist, so use a timer (not nice...).
1425       */
1426       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1427                                      selector: @selector (handleFS)
1428                                      userInfo: nil repeats: NO];
1429       return;
1430     }
1432   block_input ();
1433   [view handleFS];
1434   unblock_input ();
1437 /* ==========================================================================
1439     Color management
1441    ========================================================================== */
1444 NSColor *
1445 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1447   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1448   if (idx < 1 || idx >= color_table->avail)
1449     return nil;
1450   return color_table->colors[idx];
1454 unsigned long
1455 ns_index_color (NSColor *color, struct frame *f)
1457   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1458   ptrdiff_t idx;
1459   ptrdiff_t i;
1461   if (!color_table->colors)
1462     {
1463       color_table->size = NS_COLOR_CAPACITY;
1464       color_table->avail = 1; /* skip idx=0 as marker */
1465       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1466       color_table->colors[0] = nil;
1467       color_table->empty_indices = [[NSMutableSet alloc] init];
1468     }
1470   /* Do we already have this color?  */
1471   for (i = 1; i < color_table->avail; i++)
1472     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1473       return i;
1475   if ([color_table->empty_indices count] > 0)
1476     {
1477       NSNumber *index = [color_table->empty_indices anyObject];
1478       [color_table->empty_indices removeObject: index];
1479       idx = [index unsignedLongValue];
1480     }
1481   else
1482     {
1483       if (color_table->avail == color_table->size)
1484         color_table->colors =
1485           xpalloc (color_table->colors, &color_table->size, 1,
1486                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1487       idx = color_table->avail++;
1488     }
1490   color_table->colors[idx] = color;
1491   [color retain];
1492 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1493   return idx;
1497 void
1498 ns_free_indexed_color (unsigned long idx, struct frame *f)
1500   struct ns_color_table *color_table;
1501   NSColor *color;
1502   NSNumber *index;
1504   if (!f)
1505     return;
1507   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1509   if (idx <= 0 || idx >= color_table->size) {
1510     message1 ("ns_free_indexed_color: Color index out of range.\n");
1511     return;
1512   }
1514   index = [NSNumber numberWithUnsignedInt: idx];
1515   if ([color_table->empty_indices containsObject: index]) {
1516     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1517     return;
1518   }
1520   color = color_table->colors[idx];
1521   [color release];
1522   color_table->colors[idx] = nil;
1523   [color_table->empty_indices addObject: index];
1524 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1528 static int
1529 ns_get_color (const char *name, NSColor **col)
1530 /* --------------------------------------------------------------------------
1531      Parse a color name
1532    -------------------------------------------------------------------------- */
1533 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1534    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1535    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1537   NSColor *new = nil;
1538   static char hex[20];
1539   int scaling = 0;
1540   float r = -1.0, g, b;
1541   NSString *nsname = [NSString stringWithUTF8String: name];
1543 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1544   block_input ();
1546   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1547     {
1548 #ifdef NS_IMPL_COCOA
1549       NSString *defname = [[NSUserDefaults standardUserDefaults]
1550                             stringForKey: @"AppleHighlightColor"];
1551       if (defname != nil)
1552         nsname = defname;
1553       else
1554 #endif
1555       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1556         {
1557           *col = [new colorUsingDefaultColorSpace];
1558           unblock_input ();
1559           return 0;
1560         }
1561       else
1562         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1564       name = [nsname UTF8String];
1565     }
1566   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1567     {
1568       /* NOTE: OSX applications normally don't set foreground selection, but
1569          text may be unreadable if we don't.
1570       */
1571       if ((new = [NSColor selectedTextColor]) != nil)
1572         {
1573           *col = [new colorUsingDefaultColorSpace];
1574           unblock_input ();
1575           return 0;
1576         }
1578       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1579       name = [nsname UTF8String];
1580     }
1582   /* First, check for some sort of numeric specification. */
1583   hex[0] = '\0';
1585   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1586     {
1587       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1588       [scanner scanFloat: &r];
1589       [scanner scanFloat: &g];
1590       [scanner scanFloat: &b];
1591     }
1592   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1593     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1594   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1595     {
1596       int len = (strlen(name) - 1);
1597       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1598       int i;
1599       scaling = strlen(name+start) / 3;
1600       for (i = 0; i < 3; i++)
1601         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1602                  name + start + i * scaling);
1603       hex[3 * (scaling + 1) - 1] = '\0';
1604     }
1606   if (hex[0])
1607     {
1608       int rr, gg, bb;
1609       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1610       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1611         {
1612           r = rr / fscale;
1613           g = gg / fscale;
1614           b = bb / fscale;
1615         }
1616     }
1618   if (r >= 0.0F)
1619     {
1620       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1621       unblock_input ();
1622       return 0;
1623     }
1625   /* Otherwise, color is expected to be from a list */
1626   {
1627     NSEnumerator *lenum, *cenum;
1628     NSString *name;
1629     NSColorList *clist;
1631 #ifdef NS_IMPL_GNUSTEP
1632     /* XXX: who is wrong, the requestor or the implementation? */
1633     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1634         == NSOrderedSame)
1635       nsname = @"highlightColor";
1636 #endif
1638     lenum = [[NSColorList availableColorLists] objectEnumerator];
1639     while ( (clist = [lenum nextObject]) && new == nil)
1640       {
1641         cenum = [[clist allKeys] objectEnumerator];
1642         while ( (name = [cenum nextObject]) && new == nil )
1643           {
1644             if ([name compare: nsname
1645                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1646               new = [clist colorWithKey: name];
1647           }
1648       }
1649   }
1651   if (new)
1652     *col = [new colorUsingDefaultColorSpace];
1653   unblock_input ();
1654   return new ? 0 : 1;
1659 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1660 /* --------------------------------------------------------------------------
1661      Convert a Lisp string object to a NS color
1662    -------------------------------------------------------------------------- */
1664   NSTRACE (ns_lisp_to_color);
1665   if (STRINGP (color))
1666     return ns_get_color (SSDATA (color), col);
1667   else if (SYMBOLP (color))
1668     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1669   return 1;
1673 Lisp_Object
1674 ns_color_to_lisp (NSColor *col)
1675 /* --------------------------------------------------------------------------
1676      Convert a color to a lisp string with the RGB equivalent
1677    -------------------------------------------------------------------------- */
1679   EmacsCGFloat red, green, blue, alpha, gray;
1680   char buf[1024];
1681   const char *str;
1682   NSTRACE (ns_color_to_lisp);
1684   block_input ();
1685   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1687       if ((str =[[col colorNameComponent] UTF8String]))
1688         {
1689           unblock_input ();
1690           return build_string ((char *)str);
1691         }
1693     [[col colorUsingDefaultColorSpace]
1694         getRed: &red green: &green blue: &blue alpha: &alpha];
1695   if (red == green && red == blue)
1696     {
1697       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1698             getWhite: &gray alpha: &alpha];
1699       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1700                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1701       unblock_input ();
1702       return build_string (buf);
1703     }
1705   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1706             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1708   unblock_input ();
1709   return build_string (buf);
1713 void
1714 ns_query_color(void *col, XColor *color_def, int setPixel)
1715 /* --------------------------------------------------------------------------
1716          Get ARGB values out of NSColor col and put them into color_def.
1717          If setPixel, set the pixel to a concatenated version.
1718          and set color_def pixel to the resulting index.
1719    -------------------------------------------------------------------------- */
1721   EmacsCGFloat r, g, b, a;
1723   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1724   color_def->red   = r * 65535;
1725   color_def->green = g * 65535;
1726   color_def->blue  = b * 65535;
1728   if (setPixel == YES)
1729     color_def->pixel
1730       = ARGB_TO_ULONG((int)(a*255),
1731                       (int)(r*255), (int)(g*255), (int)(b*255));
1735 bool
1736 ns_defined_color (struct frame *f,
1737                   const char *name,
1738                   XColor *color_def,
1739                   bool alloc,
1740                   bool makeIndex)
1741 /* --------------------------------------------------------------------------
1742          Return true if named color found, and set color_def rgb accordingly.
1743          If makeIndex and alloc are nonzero put the color in the color_table,
1744          and set color_def pixel to the resulting index.
1745          If makeIndex is zero, set color_def pixel to ARGB.
1746          Return false if not found
1747    -------------------------------------------------------------------------- */
1749   NSColor *col;
1750   NSTRACE (ns_defined_color);
1752   block_input ();
1753   if (ns_get_color (name, &col) != 0) /* Color not found  */
1754     {
1755       unblock_input ();
1756       return 0;
1757     }
1758   if (makeIndex && alloc)
1759     color_def->pixel = ns_index_color (col, f);
1760   ns_query_color (col, color_def, !makeIndex);
1761   unblock_input ();
1762   return 1;
1766 void
1767 x_set_frame_alpha (struct frame *f)
1768 /* --------------------------------------------------------------------------
1769      change the entire-frame transparency
1770    -------------------------------------------------------------------------- */
1772   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1773   double alpha = 1.0;
1774   double alpha_min = 1.0;
1776   if (dpyinfo->x_highlight_frame == f)
1777     alpha = f->alpha[0];
1778   else
1779     alpha = f->alpha[1];
1781   if (FLOATP (Vframe_alpha_lower_limit))
1782     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1783   else if (INTEGERP (Vframe_alpha_lower_limit))
1784     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1786   if (alpha < 0.0)
1787     return;
1788   else if (1.0 < alpha)
1789     alpha = 1.0;
1790   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1791     alpha = alpha_min;
1793 #ifdef NS_IMPL_COCOA
1794   {
1795     EmacsView *view = FRAME_NS_VIEW (f);
1796   [[view window] setAlphaValue: alpha];
1797   }
1798 #endif
1802 /* ==========================================================================
1804     Mouse handling
1806    ========================================================================== */
1809 void
1810 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1811 /* --------------------------------------------------------------------------
1812      Programmatically reposition mouse pointer in pixel coordinates
1813    -------------------------------------------------------------------------- */
1815   NSTRACE (frame_set_mouse_pixel_position);
1816   ns_raise_frame (f);
1817 #if 0
1818   /* FIXME: this does not work, and what about GNUstep? */
1819 #ifdef NS_IMPL_COCOA
1820   [FRAME_NS_VIEW (f) lockFocus];
1821   PSsetmouse ((float)pix_x, (float)pix_y);
1822   [FRAME_NS_VIEW (f) unlockFocus];
1823 #endif
1824 #endif
1827 static int
1828 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1829 /*   ------------------------------------------------------------------------
1830      Called by EmacsView on mouseMovement events.  Passes on
1831      to emacs mainstream code if we moved off of a rect of interest
1832      known as last_mouse_glyph.
1833      ------------------------------------------------------------------------ */
1835   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1836   NSRect *r;
1838 //  NSTRACE (note_mouse_movement);
1840   dpyinfo->last_mouse_motion_frame = frame;
1841   r = &dpyinfo->last_mouse_glyph;
1843   /* Note, this doesn't get called for enter/leave, since we don't have a
1844      position.  Those are taken care of in the corresponding NSView methods. */
1846   /* has movement gone beyond last rect we were tracking? */
1847   if (x < r->origin.x || x >= r->origin.x + r->size.width
1848       || y < r->origin.y || y >= r->origin.y + r->size.height)
1849     {
1850       ns_update_begin (frame);
1851       frame->mouse_moved = 1;
1852       note_mouse_highlight (frame, x, y);
1853       remember_mouse_glyph (frame, x, y, r);
1854       ns_update_end (frame);
1855       return 1;
1856     }
1858   return 0;
1862 static void
1863 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1864                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1865                    Time *time)
1866 /* --------------------------------------------------------------------------
1867     External (hook): inform emacs about mouse position and hit parts.
1868     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1869     x & y should be position in the scrollbar (the whole bar, not the handle)
1870     and length of scrollbar respectively
1871    -------------------------------------------------------------------------- */
1873   id view;
1874   NSPoint position;
1875   Lisp_Object frame, tail;
1876   struct frame *f;
1877   struct ns_display_info *dpyinfo;
1879   NSTRACE (ns_mouse_position);
1881   if (*fp == NULL)
1882     {
1883       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1884       return;
1885     }
1887   dpyinfo = FRAME_DISPLAY_INFO (*fp);
1889   block_input ();
1891   /* Clear the mouse-moved flag for every frame on this display.  */
1892   FOR_EACH_FRAME (tail, frame)
1893     if (FRAME_NS_P (XFRAME (frame))
1894         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1895       XFRAME (frame)->mouse_moved = 0;
1897   dpyinfo->last_mouse_scroll_bar = nil;
1898   if (dpyinfo->last_mouse_frame
1899       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1900     f = dpyinfo->last_mouse_frame;
1901   else
1902     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
1904   if (f && FRAME_NS_P (f))
1905     {
1906       view = FRAME_NS_VIEW (*fp);
1908       position = [[view window] mouseLocationOutsideOfEventStream];
1909       position = [view convertPoint: position fromView: nil];
1910       remember_mouse_glyph (f, position.x, position.y,
1911                             &dpyinfo->last_mouse_glyph);
1912 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1914       if (bar_window) *bar_window = Qnil;
1915       if (part) *part = scroll_bar_above_handle;
1917       if (x) XSETINT (*x, lrint (position.x));
1918       if (y) XSETINT (*y, lrint (position.y));
1919       if (time)
1920         *time = dpyinfo->last_mouse_movement_time;
1921       *fp = f;
1922     }
1924   unblock_input ();
1928 static void
1929 ns_frame_up_to_date (struct frame *f)
1930 /* --------------------------------------------------------------------------
1931     External (hook): Fix up mouse highlighting right after a full update.
1932     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1933    -------------------------------------------------------------------------- */
1935   NSTRACE (ns_frame_up_to_date);
1937   if (FRAME_NS_P (f))
1938     {
1939       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1940       if (f == hlinfo->mouse_face_mouse_frame)
1941         {
1942           block_input ();
1943           ns_update_begin(f);
1944           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1945                                 hlinfo->mouse_face_mouse_x,
1946                                 hlinfo->mouse_face_mouse_y);
1947           ns_update_end(f);
1948           unblock_input ();
1949         }
1950     }
1954 static void
1955 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1956 /* --------------------------------------------------------------------------
1957     External (RIF): set frame mouse pointer type.
1958    -------------------------------------------------------------------------- */
1960   NSTRACE (ns_define_frame_cursor);
1961   if (FRAME_POINTER_TYPE (f) != cursor)
1962     {
1963       EmacsView *view = FRAME_NS_VIEW (f);
1964       FRAME_POINTER_TYPE (f) = cursor;
1965       [[view window] invalidateCursorRectsForView: view];
1966       /* Redisplay assumes this function also draws the changed frame
1967          cursor, but this function doesn't, so do it explicitly.  */
1968       x_update_cursor (f, 1);
1969     }
1974 /* ==========================================================================
1976     Keyboard handling
1978    ========================================================================== */
1981 static unsigned
1982 ns_convert_key (unsigned code)
1983 /* --------------------------------------------------------------------------
1984     Internal call used by NSView-keyDown.
1985    -------------------------------------------------------------------------- */
1987   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
1988   unsigned keysym;
1989   /* An array would be faster, but less easy to read. */
1990   for (keysym = 0; keysym < last_keysym; keysym += 2)
1991     if (code == convert_ns_to_X_keysym[keysym])
1992       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1993   return 0;
1994 /* if decide to use keyCode and Carbon table, use this line:
1995      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1999 char *
2000 x_get_keysym_name (int keysym)
2001 /* --------------------------------------------------------------------------
2002     Called by keyboard.c.  Not sure if the return val is important, except
2003     that it be unique.
2004    -------------------------------------------------------------------------- */
2006   static char value[16];
2007   NSTRACE (x_get_keysym_name);
2008   sprintf (value, "%d", keysym);
2009   return value;
2014 /* ==========================================================================
2016     Block drawing operations
2018    ========================================================================== */
2021 static void
2022 ns_redraw_scroll_bars (struct frame *f)
2024   int i;
2025   id view;
2026   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2027   NSTRACE (ns_redraw_scroll_bars);
2028   for (i =[subviews count]-1; i >= 0; i--)
2029     {
2030       view = [subviews objectAtIndex: i];
2031       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2032       [view display];
2033     }
2037 void
2038 ns_clear_frame (struct frame *f)
2039 /* --------------------------------------------------------------------------
2040       External (hook): Erase the entire frame
2041    -------------------------------------------------------------------------- */
2043   NSView *view = FRAME_NS_VIEW (f);
2044   NSRect r;
2046   NSTRACE (ns_clear_frame);
2048  /* comes on initial frame because we have
2049     after-make-frame-functions = select-frame */
2050  if (!FRAME_DEFAULT_FACE (f))
2051    return;
2053   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2055   r = [view bounds];
2057   block_input ();
2058   ns_focus (f, &r, 1);
2059   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2060   NSRectFill (r);
2061   ns_unfocus (f);
2063   /* as of 2006/11 or so this is now needed */
2064   ns_redraw_scroll_bars (f);
2065   unblock_input ();
2069 static void
2070 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2071 /* --------------------------------------------------------------------------
2072     External (RIF):  Clear section of frame
2073    -------------------------------------------------------------------------- */
2075   NSRect r = NSMakeRect (x, y, width, height);
2076   NSView *view = FRAME_NS_VIEW (f);
2077   struct face *face = FRAME_DEFAULT_FACE (f);
2079   if (!view || !face)
2080     return;
2082   NSTRACE (ns_clear_frame_area);
2084   r = NSIntersectionRect (r, [view frame]);
2085   ns_focus (f, &r, 1);
2086   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2088   NSRectFill (r);
2090   ns_unfocus (f);
2091   return;
2094 static void
2095 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2097   if (FRAME_NS_VIEW (f))
2098     {
2099       ns_focus (f, &dest, 1);
2100       [FRAME_NS_VIEW (f) scrollRect: src
2101                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2102                                                  dest.origin.y - src.origin.y)];
2103       ns_unfocus (f);
2104     }
2107 static void
2108 ns_scroll_run (struct window *w, struct run *run)
2109 /* --------------------------------------------------------------------------
2110     External (RIF):  Insert or delete n lines at line vpos
2111    -------------------------------------------------------------------------- */
2113   struct frame *f = XFRAME (w->frame);
2114   int x, y, width, height, from_y, to_y, bottom_y;
2116   NSTRACE (ns_scroll_run);
2118   /* begin copy from other terms */
2119   /* Get frame-relative bounding box of the text display area of W,
2120      without mode lines.  Include in this box the left and right
2121      fringe of W.  */
2122   window_box (w, ANY_AREA, &x, &y, &width, &height);
2124   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2125   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2126   bottom_y = y + height;
2128   if (to_y < from_y)
2129     {
2130       /* Scrolling up.  Make sure we don't copy part of the mode
2131          line at the bottom.  */
2132       if (from_y + run->height > bottom_y)
2133         height = bottom_y - from_y;
2134       else
2135         height = run->height;
2136     }
2137   else
2138     {
2139       /* Scrolling down.  Make sure we don't copy over the mode line.
2140          at the bottom.  */
2141       if (to_y + run->height > bottom_y)
2142         height = bottom_y - to_y;
2143       else
2144         height = run->height;
2145     }
2146   /* end copy from other terms */
2148   if (height == 0)
2149       return;
2151   block_input ();
2153   x_clear_cursor (w);
2155   {
2156     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2157     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2159     ns_copy_bits (f, srcRect , dstRect);
2160   }
2162   unblock_input ();
2166 static void
2167 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2168 /* --------------------------------------------------------------------------
2169     External (RIF): preparatory to fringe update after text was updated
2170    -------------------------------------------------------------------------- */
2172   struct frame *f;
2173   int width, height;
2175   NSTRACE (ns_after_update_window_line);
2177   /* begin copy from other terms */
2178   eassert (w);
2180   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2181     desired_row->redraw_fringe_bitmaps_p = 1;
2183   /* When a window has disappeared, make sure that no rest of
2184      full-width rows stays visible in the internal border.  */
2185   if (windows_or_buffers_changed
2186       && desired_row->full_width_p
2187       && (f = XFRAME (w->frame),
2188           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2189           width != 0)
2190       && (height = desired_row->visible_height,
2191           height > 0))
2192     {
2193       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2195       block_input ();
2196       ns_clear_frame_area (f, 0, y, width, height);
2197       ns_clear_frame_area (f,
2198                            FRAME_PIXEL_WIDTH (f) - width,
2199                            y, width, height);
2200       unblock_input ();
2201     }
2205 static void
2206 ns_shift_glyphs_for_insert (struct frame *f,
2207                            int x, int y, int width, int height,
2208                            int shift_by)
2209 /* --------------------------------------------------------------------------
2210     External (RIF): copy an area horizontally, don't worry about clearing src
2211    -------------------------------------------------------------------------- */
2213   NSRect srcRect = NSMakeRect (x, y, width, height);
2214   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2216   NSTRACE (ns_shift_glyphs_for_insert);
2218   ns_copy_bits (f, srcRect, dstRect);
2223 /* ==========================================================================
2225     Character encoding and metrics
2227    ========================================================================== */
2230 static void
2231 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2232 /* --------------------------------------------------------------------------
2233      External (RIF); compute left/right overhang of whole string and set in s
2234    -------------------------------------------------------------------------- */
2236   struct font *font = s->font;
2238   if (s->char2b)
2239     {
2240       struct font_metrics metrics;
2241       unsigned int codes[2];
2242       codes[0] = *(s->char2b);
2243       codes[1] = *(s->char2b + s->nchars - 1);
2245       font->driver->text_extents (font, codes, 2, &metrics);
2246       s->left_overhang = -metrics.lbearing;
2247       s->right_overhang
2248         = metrics.rbearing > metrics.width
2249         ? metrics.rbearing - metrics.width : 0;
2250     }
2251   else
2252     {
2253       s->left_overhang = 0;
2254       if (EQ (font->driver->type, Qns))
2255         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2256           FONT_HEIGHT (font) * 0.2 : 0;
2257       else
2258         s->right_overhang = 0;
2259     }
2264 /* ==========================================================================
2266     Fringe and cursor drawing
2268    ========================================================================== */
2271 extern int max_used_fringe_bitmap;
2272 static void
2273 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2274                       struct draw_fringe_bitmap_params *p)
2275 /* --------------------------------------------------------------------------
2276     External (RIF); fringe-related
2277    -------------------------------------------------------------------------- */
2279   struct frame *f = XFRAME (WINDOW_FRAME (w));
2280   struct face *face = p->face;
2281   static EmacsImage **bimgs = NULL;
2282   static int nBimgs = 0;
2284   /* grow bimgs if needed */
2285   if (nBimgs < max_used_fringe_bitmap)
2286     {
2287       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2288       memset (bimgs + nBimgs, 0,
2289               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2290       nBimgs = max_used_fringe_bitmap;
2291     }
2293   /* Must clip because of partially visible lines.  */
2294   ns_clip_to_row (w, row, ANY_AREA, YES);
2296   if (!p->overlay_p)
2297     {
2298       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2300       if (bx >= 0 && nx > 0)
2301         {
2302           NSRect r = NSMakeRect (bx, by, nx, ny);
2303           NSRectClip (r);
2304           [ns_lookup_indexed_color (face->background, f) set];
2305           NSRectFill (r);
2306         }
2307     }
2309   if (p->which)
2310     {
2311       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2312       EmacsImage *img = bimgs[p->which - 1];
2314       if (!img)
2315         {
2316           unsigned short *bits = p->bits + p->dh;
2317           int len = p->h;
2318           int i;
2319           unsigned char *cbits = xmalloc (len);
2321           for (i = 0; i < len; i++)
2322             cbits[i] = ~(bits[i] & 0xff);
2323           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2324                                              fg: 0 bg: 0];
2325           bimgs[p->which - 1] = img;
2326           xfree (cbits);
2327         }
2329       NSRectClip (r);
2330       /* Since we composite the bitmap instead of just blitting it, we need
2331          to erase the whole background. */
2332       [ns_lookup_indexed_color(face->background, f) set];
2333       NSRectFill (r);
2335       {
2336         NSColor *bm_color;
2337         if (!p->cursor_p)
2338           bm_color = ns_lookup_indexed_color(face->foreground, f);
2339         else if (p->overlay_p)
2340           bm_color = ns_lookup_indexed_color(face->background, f);
2341         else
2342           bm_color = f->output_data.ns->cursor_color;
2343         [img setXBMColor: bm_color];
2344       }
2346 #ifdef NS_IMPL_COCOA
2347       [img drawInRect: r
2348               fromRect: NSZeroRect
2349              operation: NSCompositeSourceOver
2350               fraction: 1.0
2351            respectFlipped: YES
2352                 hints: nil];
2353 #else
2354       {
2355         NSPoint pt = r.origin;
2356         pt.y += p->h;
2357         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2358       }
2359 #endif
2360     }
2361   ns_unfocus (f);
2365 static void
2366 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2367                        int x, int y, enum text_cursor_kinds cursor_type,
2368                        int cursor_width, bool on_p, bool active_p)
2369 /* --------------------------------------------------------------------------
2370      External call (RIF): draw cursor.
2371      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2372    -------------------------------------------------------------------------- */
2374   NSRect r, s;
2375   int fx, fy, h, cursor_height;
2376   struct frame *f = WINDOW_XFRAME (w);
2377   struct glyph *phys_cursor_glyph;
2378   struct glyph *cursor_glyph;
2379   struct face *face;
2380   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2382   /* If cursor is out of bounds, don't draw garbage.  This can happen
2383      in mini-buffer windows when switching between echo area glyphs
2384      and mini-buffer.  */
2386   NSTRACE (dumpcursor);
2388   if (!on_p)
2389     return;
2391   w->phys_cursor_type = cursor_type;
2392   w->phys_cursor_on_p = on_p;
2394   if (cursor_type == NO_CURSOR)
2395     {
2396       w->phys_cursor_width = 0;
2397       return;
2398     }
2400   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2401     {
2402       if (glyph_row->exact_window_width_line_p
2403           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2404         {
2405           glyph_row->cursor_in_fringe_p = 1;
2406           draw_fringe_bitmap (w, glyph_row, 0);
2407         }
2408       return;
2409     }
2411   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2412      (other terminals do it the other way round).  We must set
2413      w->phys_cursor_width to the cursor width.  For bar cursors, that
2414      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2415   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2417   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2418      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2419   if (cursor_type == BAR_CURSOR)
2420     {
2421       if (cursor_width < 1)
2422         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2423       w->phys_cursor_width = cursor_width;
2424     }
2425   /* If we have an HBAR, "cursor_width" MAY specify height. */
2426   else if (cursor_type == HBAR_CURSOR)
2427     {
2428       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2429       if (cursor_height > glyph_row->height)
2430         cursor_height = glyph_row->height;
2431       if (h > cursor_height) // Cursor smaller than line height, move down
2432         fy += h - cursor_height;
2433       h = cursor_height;
2434     }
2436   r.origin.x = fx, r.origin.y = fy;
2437   r.size.height = h;
2438   r.size.width = w->phys_cursor_width;
2440   /* TODO: only needed in rare cases with last-resort font in HELLO..
2441      should we do this more efficiently? */
2442   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2445   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2446   if (face && NS_FACE_BACKGROUND (face)
2447       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2448     {
2449       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2450       hollow_color = FRAME_CURSOR_COLOR (f);
2451     }
2452   else
2453     [FRAME_CURSOR_COLOR (f) set];
2455 #ifdef NS_IMPL_COCOA
2456   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2457            atomic.  Cleaner ways of doing this should be investigated.
2458            One way would be to set a global variable DRAWING_CURSOR
2459            when making the call to draw_phys..(), don't focus in that
2460            case, then move the ns_unfocus() here after that call. */
2461   NSDisableScreenUpdates ();
2462 #endif
2464   switch (cursor_type)
2465     {
2466     case DEFAULT_CURSOR:
2467     case NO_CURSOR:
2468       break;
2469     case FILLED_BOX_CURSOR:
2470       NSRectFill (r);
2471       break;
2472     case HOLLOW_BOX_CURSOR:
2473       NSRectFill (r);
2474       [hollow_color set];
2475       NSRectFill (NSInsetRect (r, 1, 1));
2476       [FRAME_CURSOR_COLOR (f) set];
2477       break;
2478     case HBAR_CURSOR:
2479       NSRectFill (r);
2480       break;
2481     case BAR_CURSOR:
2482       s = r;
2483       /* If the character under cursor is R2L, draw the bar cursor
2484          on the right of its glyph, rather than on the left.  */
2485       cursor_glyph = get_phys_cursor_glyph (w);
2486       if ((cursor_glyph->resolved_level & 1) != 0)
2487         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2489       NSRectFill (s);
2490       break;
2491     }
2492   ns_unfocus (f);
2494   /* draw the character under the cursor */
2495   if (cursor_type != NO_CURSOR)
2496     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2498 #ifdef NS_IMPL_COCOA
2499   NSEnableScreenUpdates ();
2500 #endif
2505 static void
2506 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2507 /* --------------------------------------------------------------------------
2508      External (RIF): Draw a vertical line.
2509    -------------------------------------------------------------------------- */
2511   struct frame *f = XFRAME (WINDOW_FRAME (w));
2512   struct face *face;
2513   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2515   NSTRACE (ns_draw_vertical_window_border);
2517   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2518   if (face)
2519       [ns_lookup_indexed_color(face->foreground, f) set];
2521   ns_focus (f, &r, 1);
2522   NSRectFill(r);
2523   ns_unfocus (f);
2527 static void
2528 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2529 /* --------------------------------------------------------------------------
2530      External (RIF): Draw a window divider.
2531    -------------------------------------------------------------------------- */
2533   struct frame *f = XFRAME (WINDOW_FRAME (w));
2534   struct face *face;
2535   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2537   NSTRACE (ns_draw_window_divider);
2539   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2540   if (face)
2541       [ns_lookup_indexed_color(face->foreground, f) set];
2543   ns_focus (f, &r, 1);
2544   NSRectFill(r);
2545   ns_unfocus (f);
2548 static void
2549 ns_show_hourglass (struct frame *f)
2551   /* TODO: add NSProgressIndicator to all frames.  */
2554 static void
2555 ns_hide_hourglass (struct frame *f)
2557   /* TODO: remove NSProgressIndicator from all frames.  */
2560 /* ==========================================================================
2562     Glyph drawing operations
2564    ========================================================================== */
2566 static int
2567 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2568 /* --------------------------------------------------------------------------
2569     Wrapper utility to account for internal border width on full-width lines,
2570     and allow top full-width rows to hit the frame top.  nr should be pointer
2571     to two successive NSRects.  Number of rects actually used is returned.
2572    -------------------------------------------------------------------------- */
2574   int n = get_glyph_string_clip_rects (s, nr, 2);
2575   return n;
2578 /* --------------------------------------------------------------------
2579    Draw a wavy line under glyph string s. The wave fills wave_height
2580    pixels from y.
2582                     x          wave_length = 2
2583                                  --
2584                 y    *   *   *   *   *
2585                      |* * * * * * * * *
2586     wave_height = 3  | *   *   *   *
2587   --------------------------------------------------------------------- */
2589 static void
2590 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2592   int wave_height = 3, wave_length = 2;
2593   int y, dx, dy, odd, xmax;
2594   NSPoint a, b;
2595   NSRect waveClip;
2597   dx = wave_length;
2598   dy = wave_height - 1;
2599   y =  s->ybase - wave_height + 3;
2600   xmax = x + width;
2602   /* Find and set clipping rectangle */
2603   waveClip = NSMakeRect (x, y, width, wave_height);
2604   [[NSGraphicsContext currentContext] saveGraphicsState];
2605   NSRectClip (waveClip);
2607   /* Draw the waves */
2608   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2609   b.x = a.x + dx;
2610   odd = (int)(a.x/dx) % 2;
2611   a.y = b.y = y + 0.5;
2613   if (odd)
2614     a.y += dy;
2615   else
2616     b.y += dy;
2618   while (a.x <= xmax)
2619     {
2620       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2621       a.x = b.x, a.y = b.y;
2622       b.x += dx, b.y = y + 0.5 + odd*dy;
2623       odd = !odd;
2624     }
2626   /* Restore previous clipping rectangle(s) */
2627   [[NSGraphicsContext currentContext] restoreGraphicsState];
2632 void
2633 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2634                          NSColor *defaultCol, CGFloat width, CGFloat x)
2635 /* --------------------------------------------------------------------------
2636    Draw underline, overline, and strike-through on glyph string s.
2637    -------------------------------------------------------------------------- */
2639   if (s->for_overlaps)
2640     return;
2642   /* Do underline. */
2643   if (face->underline_p)
2644     {
2645       if (s->face->underline_type == FACE_UNDER_WAVE)
2646         {
2647           if (face->underline_defaulted_p)
2648             [defaultCol set];
2649           else
2650             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2652           ns_draw_underwave (s, width, x);
2653         }
2654       else if (s->face->underline_type == FACE_UNDER_LINE)
2655         {
2657           NSRect r;
2658           unsigned long thickness, position;
2660           /* If the prev was underlined, match its appearance. */
2661           if (s->prev && s->prev->face->underline_p
2662               && s->prev->face->underline_type == FACE_UNDER_LINE
2663               && s->prev->underline_thickness > 0)
2664             {
2665               thickness = s->prev->underline_thickness;
2666               position = s->prev->underline_position;
2667             }
2668           else
2669             {
2670               struct font *font;
2671               unsigned long descent;
2673               font=s->font;
2674               descent = s->y + s->height - s->ybase;
2676               /* Use underline thickness of font, defaulting to 1. */
2677               thickness = (font && font->underline_thickness > 0)
2678                 ? font->underline_thickness : 1;
2680               /* Determine the offset of underlining from the baseline. */
2681               if (x_underline_at_descent_line)
2682                 position = descent - thickness;
2683               else if (x_use_underline_position_properties
2684                        && font && font->underline_position >= 0)
2685                 position = font->underline_position;
2686               else if (font)
2687                 position = lround (font->descent / 2);
2688               else
2689                 position = underline_minimum_offset;
2691               position = max (position, underline_minimum_offset);
2693               /* Ensure underlining is not cropped. */
2694               if (descent <= position)
2695                 {
2696                   position = descent - 1;
2697                   thickness = 1;
2698                 }
2699               else if (descent < position + thickness)
2700                 thickness = 1;
2701             }
2703           s->underline_thickness = thickness;
2704           s->underline_position = position;
2706           r = NSMakeRect (x, s->ybase + position, width, thickness);
2708           if (face->underline_defaulted_p)
2709             [defaultCol set];
2710           else
2711             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2712           NSRectFill (r);
2713         }
2714     }
2715   /* Do overline. We follow other terms in using a thickness of 1
2716      and ignoring overline_margin. */
2717   if (face->overline_p)
2718     {
2719       NSRect r;
2720       r = NSMakeRect (x, s->y, width, 1);
2722       if (face->overline_color_defaulted_p)
2723         [defaultCol set];
2724       else
2725         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2726       NSRectFill (r);
2727     }
2729   /* Do strike-through.  We follow other terms for thickness and
2730      vertical position.*/
2731   if (face->strike_through_p)
2732     {
2733       NSRect r;
2734       unsigned long dy;
2736       dy = lrint ((s->height - 1) / 2);
2737       r = NSMakeRect (x, s->y + dy, width, 1);
2739       if (face->strike_through_color_defaulted_p)
2740         [defaultCol set];
2741       else
2742         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2743       NSRectFill (r);
2744     }
2747 static void
2748 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2749              char left_p, char right_p)
2750 /* --------------------------------------------------------------------------
2751     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2752     Note we can't just use an NSDrawRect command, because of the possibility
2753     of some sides not being drawn, and because the rect will be filled.
2754    -------------------------------------------------------------------------- */
2756   NSRect s = r;
2757   [col set];
2759   /* top, bottom */
2760   s.size.height = thickness;
2761   NSRectFill (s);
2762   s.origin.y += r.size.height - thickness;
2763   NSRectFill (s);
2765   s.size.height = r.size.height;
2766   s.origin.y = r.origin.y;
2768   /* left, right (optional) */
2769   s.size.width = thickness;
2770   if (left_p)
2771     NSRectFill (s);
2772   if (right_p)
2773     {
2774       s.origin.x += r.size.width - thickness;
2775       NSRectFill (s);
2776     }
2780 static void
2781 ns_draw_relief (NSRect r, int thickness, char raised_p,
2782                char top_p, char bottom_p, char left_p, char right_p,
2783                struct glyph_string *s)
2784 /* --------------------------------------------------------------------------
2785     Draw a relief rect inside r, optionally leaving some sides open.
2786     Note we can't just use an NSDrawBezel command, because of the possibility
2787     of some sides not being drawn, and because the rect will be filled.
2788    -------------------------------------------------------------------------- */
2790   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2791   NSColor *newBaseCol = nil;
2792   NSRect sr = r;
2794   NSTRACE (ns_draw_relief);
2796   /* set up colors */
2798   if (s->face->use_box_color_for_shadows_p)
2799     {
2800       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2801     }
2802 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2803            && s->img->pixmap
2804            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2805        {
2806          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2807        } */
2808   else
2809     {
2810       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2811     }
2813   if (newBaseCol == nil)
2814     newBaseCol = [NSColor grayColor];
2816   if (newBaseCol != baseCol)  /* TODO: better check */
2817     {
2818       [baseCol release];
2819       baseCol = [newBaseCol retain];
2820       [lightCol release];
2821       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2822       [darkCol release];
2823       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2824     }
2826   [(raised_p ? lightCol : darkCol) set];
2828   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2830   /* top */
2831   sr.size.height = thickness;
2832   if (top_p) NSRectFill (sr);
2834   /* left */
2835   sr.size.height = r.size.height;
2836   sr.size.width = thickness;
2837   if (left_p) NSRectFill (sr);
2839   [(raised_p ? darkCol : lightCol) set];
2841   /* bottom */
2842   sr.size.width = r.size.width;
2843   sr.size.height = thickness;
2844   sr.origin.y += r.size.height - thickness;
2845   if (bottom_p) NSRectFill (sr);
2847   /* right */
2848   sr.size.height = r.size.height;
2849   sr.origin.y = r.origin.y;
2850   sr.size.width = thickness;
2851   sr.origin.x += r.size.width - thickness;
2852   if (right_p) NSRectFill (sr);
2856 static void
2857 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859       Function modeled after x_draw_glyph_string_box ().
2860       Sets up parameters for drawing.
2861    -------------------------------------------------------------------------- */
2863   int right_x, last_x;
2864   char left_p, right_p;
2865   struct glyph *last_glyph;
2866   NSRect r;
2867   int thickness;
2868   struct face *face;
2870   if (s->hl == DRAW_MOUSE_FACE)
2871     {
2872       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2873       if (!face)
2874         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2875     }
2876   else
2877     face = s->face;
2879   thickness = face->box_line_width;
2881   NSTRACE (ns_dumpglyphs_box_or_relief);
2883   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2884             ? WINDOW_RIGHT_EDGE_X (s->w)
2885             : window_box_right (s->w, s->area));
2886   last_glyph = (s->cmp || s->img
2887                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2889   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2890               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2892   left_p = (s->first_glyph->left_box_line_p
2893             || (s->hl == DRAW_MOUSE_FACE
2894                 && (s->prev == NULL || s->prev->hl != s->hl)));
2895   right_p = (last_glyph->right_box_line_p
2896              || (s->hl == DRAW_MOUSE_FACE
2897                  && (s->next == NULL || s->next->hl != s->hl)));
2899   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2901   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2902   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2903     {
2904       ns_draw_box (r, abs (thickness),
2905                    ns_lookup_indexed_color (face->box_color, s->f),
2906                   left_p, right_p);
2907     }
2908   else
2909     {
2910       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2911                      1, 1, left_p, right_p, s);
2912     }
2916 static void
2917 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2918 /* --------------------------------------------------------------------------
2919       Modeled after x_draw_glyph_string_background, which draws BG in
2920       certain cases.  Others are left to the text rendering routine.
2921    -------------------------------------------------------------------------- */
2923   NSTRACE (ns_maybe_dumpglyphs_background);
2925   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2926     {
2927       int box_line_width = max (s->face->box_line_width, 0);
2928       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2929           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
2930              dimensions, since the actual glyphs might be much
2931              smaller.  So in that case we always clear the rectangle
2932              with background color.  */
2933           || FONT_TOO_HIGH (s->font)
2934           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2935         {
2936           struct face *face;
2937           if (s->hl == DRAW_MOUSE_FACE)
2938             {
2939               face = FACE_FROM_ID (s->f,
2940                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2941               if (!face)
2942                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2943             }
2944           else
2945             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2946           if (!face->stipple)
2947             [(NS_FACE_BACKGROUND (face) != 0
2948               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2949               : FRAME_BACKGROUND_COLOR (s->f)) set];
2950           else
2951             {
2952               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2953               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2954             }
2956           if (s->hl != DRAW_CURSOR)
2957             {
2958               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2959                                     s->background_width,
2960                                     s->height-2*box_line_width);
2961               NSRectFill (r);
2962             }
2964           s->background_filled_p = 1;
2965         }
2966     }
2970 static void
2971 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2972 /* --------------------------------------------------------------------------
2973       Renders an image and associated borders.
2974    -------------------------------------------------------------------------- */
2976   EmacsImage *img = s->img->pixmap;
2977   int box_line_vwidth = max (s->face->box_line_width, 0);
2978   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2979   int bg_x, bg_y, bg_height;
2980   int th;
2981   char raised_p;
2982   NSRect br;
2983   struct face *face;
2984   NSColor *tdCol;
2986   NSTRACE (ns_dumpglyphs_image);
2988   if (s->face->box != FACE_NO_BOX
2989       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2990     x += abs (s->face->box_line_width);
2992   bg_x = x;
2993   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2994   bg_height = s->height;
2995   /* other terms have this, but was causing problems w/tabbar mode */
2996   /* - 2 * box_line_vwidth; */
2998   if (s->slice.x == 0) x += s->img->hmargin;
2999   if (s->slice.y == 0) y += s->img->vmargin;
3001   /* Draw BG: if we need larger area than image itself cleared, do that,
3002      otherwise, since we composite the image under NS (instead of mucking
3003      with its background color), we must clear just the image area. */
3004   if (s->hl == DRAW_MOUSE_FACE)
3005     {
3006       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3007       if (!face)
3008        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3009     }
3010   else
3011     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3013   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3015   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3016       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3017     {
3018       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3019       s->background_filled_p = 1;
3020     }
3021   else
3022     {
3023       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3024     }
3026   NSRectFill (br);
3028   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3029   if (img != nil)
3030     {
3031 #ifdef NS_IMPL_COCOA
3032       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3033       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3034                               s->slice.width, s->slice.height);
3035       [img drawInRect: dr
3036              fromRect: ir
3037              operation: NSCompositeSourceOver
3038               fraction: 1.0
3039            respectFlipped: YES
3040                 hints: nil];
3041 #else
3042       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3043                   operation: NSCompositeSourceOver];
3044 #endif
3045     }
3047   if (s->hl == DRAW_CURSOR)
3048     {
3049     [FRAME_CURSOR_COLOR (s->f) set];
3050     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3051       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3052     else
3053       /* Currently on NS img->mask is always 0. Since
3054          get_window_cursor_type specifies a hollow box cursor when on
3055          a non-masked image we never reach this clause. But we put it
3056          in in anticipation of better support for image masks on
3057          NS. */
3058       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3059     }
3060   else
3061     {
3062       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3063     }
3065   /* Draw underline, overline, strike-through. */
3066   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3068   /* Draw relief, if requested */
3069   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3070     {
3071       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3072         {
3073           th = tool_bar_button_relief >= 0 ?
3074             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3075           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3076         }
3077       else
3078         {
3079           th = abs (s->img->relief);
3080           raised_p = (s->img->relief > 0);
3081         }
3083       r.origin.x = x - th;
3084       r.origin.y = y - th;
3085       r.size.width = s->slice.width + 2*th-1;
3086       r.size.height = s->slice.height + 2*th-1;
3087       ns_draw_relief (r, th, raised_p,
3088                       s->slice.y == 0,
3089                       s->slice.y + s->slice.height == s->img->height,
3090                       s->slice.x == 0,
3091                       s->slice.x + s->slice.width == s->img->width, s);
3092     }
3094   /* If there is no mask, the background won't be seen,
3095      so draw a rectangle on the image for the cursor.
3096      Do this for all images, getting transparency right is not reliable.  */
3097   if (s->hl == DRAW_CURSOR)
3098     {
3099       int thickness = abs (s->img->relief);
3100       if (thickness == 0) thickness = 1;
3101       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3102     }
3106 static void
3107 ns_dumpglyphs_stretch (struct glyph_string *s)
3109   NSRect r[2];
3110   int n, i;
3111   struct face *face;
3112   NSColor *fgCol, *bgCol;
3114   if (!s->background_filled_p)
3115     {
3116       n = ns_get_glyph_string_clip_rect (s, r);
3117       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3119       ns_focus (s->f, r, n);
3121       if (s->hl == DRAW_MOUSE_FACE)
3122        {
3123          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3124          if (!face)
3125            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3126        }
3127       else
3128        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3130       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3131       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3133       for (i = 0; i < n; ++i)
3134         {
3135           if (!s->row->full_width_p)
3136             {
3137               int overrun, leftoverrun;
3139               /* truncate to avoid overwriting fringe and/or scrollbar */
3140               overrun = max (0, (s->x + s->background_width)
3141                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3142                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3143               r[i].size.width -= overrun;
3145               /* truncate to avoid overwriting to left of the window box */
3146               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3147                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3149               if (leftoverrun > 0)
3150                 {
3151                   r[i].origin.x += leftoverrun;
3152                   r[i].size.width -= leftoverrun;
3153                 }
3155               /* XXX: Try to work between problem where a stretch glyph on
3156                  a partially-visible bottom row will clear part of the
3157                  modeline, and another where list-buffers headers and similar
3158                  rows erroneously have visible_height set to 0.  Not sure
3159                  where this is coming from as other terms seem not to show. */
3160               r[i].size.height = min (s->height, s->row->visible_height);
3161             }
3163           [bgCol set];
3165           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3166              overwriting cursor (usually when cursor on a tab) */
3167           if (s->hl == DRAW_CURSOR)
3168             {
3169               CGFloat x, width;
3171               x = r[i].origin.x;
3172               width = s->w->phys_cursor_width;
3173               r[i].size.width -= width;
3174               r[i].origin.x += width;
3176               NSRectFill (r[i]);
3178               /* Draw overlining, etc. on the cursor. */
3179               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3180                 ns_draw_text_decoration (s, face, bgCol, width, x);
3181               else
3182                 ns_draw_text_decoration (s, face, fgCol, width, x);
3183             }
3184           else
3185             {
3186               NSRectFill (r[i]);
3187             }
3189           /* Draw overlining, etc. on the stretch glyph (or the part
3190              of the stretch glyph after the cursor). */
3191           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3192                                    r[i].origin.x);
3193         }
3194       ns_unfocus (s->f);
3195       s->background_filled_p = 1;
3196     }
3200 static void
3201 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3203   int i, j, x;
3204   struct font *font = s->font;
3206   /* If first glyph of S has a left box line, start drawing the text
3207      of S to the right of that box line.  */
3208   if (s->face && s->face->box != FACE_NO_BOX
3209       && s->first_glyph->left_box_line_p)
3210     x = s->x + eabs (s->face->box_line_width);
3211   else
3212     x = s->x;
3214   /* S is a glyph string for a composition.  S->cmp_from is the index
3215      of the first character drawn for glyphs of this composition.
3216      S->cmp_from == 0 means we are drawing the very first character of
3217      this composition.  */
3219   /* Draw a rectangle for the composition if the font for the very
3220      first character of the composition could not be loaded.  */
3221   if (s->font_not_found_p)
3222     {
3223       if (s->cmp_from == 0)
3224         {
3225           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3226           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3227         }
3228     }
3229   else if (! s->first_glyph->u.cmp.automatic)
3230     {
3231       int y = s->ybase;
3233       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3234         /* TAB in a composition means display glyphs with padding
3235            space on the left or right.  */
3236         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3237           {
3238             int xx = x + s->cmp->offsets[j * 2];
3239             int yy = y - s->cmp->offsets[j * 2 + 1];
3241             font->driver->draw (s, j, j + 1, xx, yy, false);
3242             if (s->face->overstrike)
3243               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3244           }
3245     }
3246   else
3247     {
3248       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3249       Lisp_Object glyph;
3250       int y = s->ybase;
3251       int width = 0;
3253       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3254         {
3255           glyph = LGSTRING_GLYPH (gstring, i);
3256           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3257             width += LGLYPH_WIDTH (glyph);
3258           else
3259             {
3260               int xoff, yoff, wadjust;
3262               if (j < i)
3263                 {
3264                   font->driver->draw (s, j, i, x, y, false);
3265                   if (s->face->overstrike)
3266                     font->driver->draw (s, j, i, x + 1, y, false);
3267                   x += width;
3268                 }
3269               xoff = LGLYPH_XOFF (glyph);
3270               yoff = LGLYPH_YOFF (glyph);
3271               wadjust = LGLYPH_WADJUST (glyph);
3272               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3273               if (s->face->overstrike)
3274                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3275                                     false);
3276               x += wadjust;
3277               j = i + 1;
3278               width = 0;
3279             }
3280         }
3281       if (j < i)
3282         {
3283           font->driver->draw (s, j, i, x, y, false);
3284           if (s->face->overstrike)
3285             font->driver->draw (s, j, i, x + 1, y, false);
3286         }
3287     }
3290 static void
3291 ns_draw_glyph_string (struct glyph_string *s)
3292 /* --------------------------------------------------------------------------
3293       External (RIF): Main draw-text call.
3294    -------------------------------------------------------------------------- */
3296   /* TODO (optimize): focus for box and contents draw */
3297   NSRect r[2];
3298   int n, flags;
3299   char box_drawn_p = 0;
3300   struct font *font = s->face->font;
3301   if (! font) font = FRAME_FONT (s->f);
3303   NSTRACE (ns_draw_glyph_string);
3305   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3306     {
3307       int width;
3308       struct glyph_string *next;
3310       for (width = 0, next = s->next;
3311            next && width < s->right_overhang;
3312            width += next->width, next = next->next)
3313         if (next->first_glyph->type != IMAGE_GLYPH)
3314           {
3315             if (next->first_glyph->type != STRETCH_GLYPH)
3316               {
3317                 n = ns_get_glyph_string_clip_rect (s->next, r);
3318                 ns_focus (s->f, r, n);
3319                 ns_maybe_dumpglyphs_background (s->next, 1);
3320                 ns_unfocus (s->f);
3321               }
3322             else
3323               {
3324                 ns_dumpglyphs_stretch (s->next);
3325               }
3326             next->num_clips = 0;
3327           }
3328     }
3330   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3331         && (s->first_glyph->type == CHAR_GLYPH
3332             || s->first_glyph->type == COMPOSITE_GLYPH))
3333     {
3334       n = ns_get_glyph_string_clip_rect (s, r);
3335       ns_focus (s->f, r, n);
3336       ns_maybe_dumpglyphs_background (s, 1);
3337       ns_dumpglyphs_box_or_relief (s);
3338       ns_unfocus (s->f);
3339       box_drawn_p = 1;
3340     }
3342   switch (s->first_glyph->type)
3343     {
3345     case IMAGE_GLYPH:
3346       n = ns_get_glyph_string_clip_rect (s, r);
3347       ns_focus (s->f, r, n);
3348       ns_dumpglyphs_image (s, r[0]);
3349       ns_unfocus (s->f);
3350       break;
3352     case STRETCH_GLYPH:
3353       ns_dumpglyphs_stretch (s);
3354       break;
3356     case CHAR_GLYPH:
3357     case COMPOSITE_GLYPH:
3358       n = ns_get_glyph_string_clip_rect (s, r);
3359       ns_focus (s->f, r, n);
3361       if (s->for_overlaps || (s->cmp_from > 0
3362                               && ! s->first_glyph->u.cmp.automatic))
3363         s->background_filled_p = 1;
3364       else
3365         ns_maybe_dumpglyphs_background
3366           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3368       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3369         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3370          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3371           NS_DUMPGLYPH_NORMAL));
3373       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3374         {
3375           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3376           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3377           NS_FACE_FOREGROUND (s->face) = tmp;
3378         }
3380       {
3381         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3383         if (isComposite)
3384           ns_draw_composite_glyph_string_foreground (s);
3385         else
3386           font->driver->draw
3387             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3388              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3389              || flags == NS_DUMPGLYPH_MOUSEFACE);
3390       }
3392       {
3393         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3394                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3395                                                    s->f)
3396                         : FRAME_FOREGROUND_COLOR (s->f));
3397         [col set];
3399         /* Draw underline, overline, strike-through. */
3400         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3401       }
3403       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3404         {
3405           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3406           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3407           NS_FACE_FOREGROUND (s->face) = tmp;
3408         }
3410       ns_unfocus (s->f);
3411       break;
3413     case GLYPHLESS_GLYPH:
3414       n = ns_get_glyph_string_clip_rect (s, r);
3415       ns_focus (s->f, r, n);
3417       if (s->for_overlaps || (s->cmp_from > 0
3418                               && ! s->first_glyph->u.cmp.automatic))
3419         s->background_filled_p = 1;
3420       else
3421         ns_maybe_dumpglyphs_background
3422           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3423       /* ... */
3424       /* Not yet implemented.  */
3425       /* ... */
3426       ns_unfocus (s->f);
3427       break;
3429     default:
3430       emacs_abort ();
3431     }
3433   /* Draw box if not done already. */
3434   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3435     {
3436       n = ns_get_glyph_string_clip_rect (s, r);
3437       ns_focus (s->f, r, n);
3438       ns_dumpglyphs_box_or_relief (s);
3439       ns_unfocus (s->f);
3440     }
3442   s->num_clips = 0;
3447 /* ==========================================================================
3449     Event loop
3451    ========================================================================== */
3454 static void
3455 ns_send_appdefined (int value)
3456 /* --------------------------------------------------------------------------
3457     Internal: post an appdefined event which EmacsApp-sendEvent will
3458               recognize and take as a command to halt the event loop.
3459    -------------------------------------------------------------------------- */
3461   /*NSTRACE (ns_send_appdefined); */
3463 #ifdef NS_IMPL_GNUSTEP
3464   // GNUstep needs postEvent to happen on the main thread.
3465   if (! [[NSThread currentThread] isMainThread])
3466     {
3467       EmacsApp *app = (EmacsApp *)NSApp;
3468       app->nextappdefined = value;
3469       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3470                             withObject:nil
3471                          waitUntilDone:YES];
3472       return;
3473     }
3474 #endif
3476   /* Only post this event if we haven't already posted one.  This will end
3477        the [NXApp run] main loop after having processed all events queued at
3478        this moment.  */
3480 #ifdef NS_IMPL_COCOA
3481   if (! send_appdefined)
3482     {
3483       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3484          in certain situations (rapid incoming events).
3485          So check if we have one, if not add one.  */
3486       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3487                                           untilDate:[NSDate distantPast]
3488                                              inMode:NSDefaultRunLoopMode
3489                                             dequeue:NO];
3490       if (! appev) send_appdefined = YES;
3491     }
3492 #endif
3494   if (send_appdefined)
3495     {
3496       NSEvent *nxev;
3498       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3499       send_appdefined = NO;
3501       /* Don't need wakeup timer any more */
3502       if (timed_entry)
3503         {
3504           [timed_entry invalidate];
3505           [timed_entry release];
3506           timed_entry = nil;
3507         }
3509       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3510                                 location: NSMakePoint (0, 0)
3511                            modifierFlags: 0
3512                                timestamp: 0
3513                             windowNumber: [[NSApp mainWindow] windowNumber]
3514                                  context: [NSApp context]
3515                                  subtype: 0
3516                                    data1: value
3517                                    data2: 0];
3519       /* Post an application defined event on the event queue.  When this is
3520          received the [NXApp run] will return, thus having processed all
3521          events which are currently queued.  */
3522       [NSApp postEvent: nxev atStart: NO];
3523     }
3526 #ifdef HAVE_NATIVE_FS
3527 static void
3528 check_native_fs ()
3530   Lisp_Object frame, tail;
3532   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3533     return;
3535   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3537   FOR_EACH_FRAME (tail, frame)
3538     {
3539       struct frame *f = XFRAME (frame);
3540       if (FRAME_NS_P (f))
3541         {
3542           EmacsView *view = FRAME_NS_VIEW (f);
3543           [view updateCollectionBehavior];
3544         }
3545     }
3547 #endif
3549 /* GNUstep does not have cancelTracking.  */
3550 #ifdef NS_IMPL_COCOA
3551 /* Check if menu open should be canceled or continued as normal.  */
3552 void
3553 ns_check_menu_open (NSMenu *menu)
3555   /* Click in menu bar? */
3556   NSArray *a = [[NSApp mainMenu] itemArray];
3557   int i;
3558   BOOL found = NO;
3560   if (menu == nil) // Menu tracking ended.
3561     {
3562       if (menu_will_open_state == MENU_OPENING)
3563         menu_will_open_state = MENU_NONE;
3564       return;
3565     }
3567   for (i = 0; ! found && i < [a count]; i++)
3568     found = menu == [[a objectAtIndex:i] submenu];
3569   if (found)
3570     {
3571       if (menu_will_open_state == MENU_NONE && emacs_event)
3572         {
3573           NSEvent *theEvent = [NSApp currentEvent];
3574           struct frame *emacsframe = SELECTED_FRAME ();
3576           [menu cancelTracking];
3577           menu_will_open_state = MENU_PENDING;
3578           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3579           EV_TRAILER (theEvent);
3581           CGEventRef ourEvent = CGEventCreate (NULL);
3582           menu_mouse_point = CGEventGetLocation (ourEvent);
3583           CFRelease (ourEvent);
3584         }
3585       else if (menu_will_open_state == MENU_OPENING)
3586         {
3587           menu_will_open_state = MENU_NONE;
3588         }
3589     }
3592 /* Redo saved menu click if state is MENU_PENDING.  */
3593 void
3594 ns_check_pending_open_menu ()
3596   if (menu_will_open_state == MENU_PENDING)
3597     {
3598       CGEventSourceRef source
3599         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3601       CGEventRef event = CGEventCreateMouseEvent (source,
3602                                                   kCGEventLeftMouseDown,
3603                                                   menu_mouse_point,
3604                                                   kCGMouseButtonLeft);
3605       CGEventSetType (event, kCGEventLeftMouseDown);
3606       CGEventPost (kCGHIDEventTap, event);
3607       CFRelease (event);
3608       CFRelease (source);
3610       menu_will_open_state = MENU_OPENING;
3611     }
3613 #endif /* NS_IMPL_COCOA */
3615 static void
3616 unwind_apploopnr (Lisp_Object not_used)
3618   --apploopnr;
3619   n_emacs_events_pending = 0;
3620   ns_finish_events ();
3621   q_event_ptr = NULL;
3624 static int
3625 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3626 /* --------------------------------------------------------------------------
3627      External (hook): Post an event to ourself and keep reading events until
3628      we read it back again.  In effect process all events which were waiting.
3629      From 21+ we have to manage the event buffer ourselves.
3630    -------------------------------------------------------------------------- */
3632   struct input_event ev;
3633   int nevents;
3635 /* NSTRACE (ns_read_socket); */
3637 #ifdef HAVE_NATIVE_FS
3638   check_native_fs ();
3639 #endif
3641   if ([NSApp modalWindow] != nil)
3642     return -1;
3644   if (hold_event_q.nr > 0)
3645     {
3646       int i;
3647       for (i = 0; i < hold_event_q.nr; ++i)
3648         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3649       hold_event_q.nr = 0;
3650       return i;
3651     }
3653   block_input ();
3654   n_emacs_events_pending = 0;
3655   ns_init_events (&ev);
3656   q_event_ptr = hold_quit;
3658   /* we manage autorelease pools by allocate/reallocate each time around
3659      the loop; strict nesting is occasionally violated but seems not to
3660      matter.. earlier methods using full nesting caused major memory leaks */
3661   [outerpool release];
3662   outerpool = [[NSAutoreleasePool alloc] init];
3664   /* If have pending open-file requests, attend to the next one of those. */
3665   if (ns_pending_files && [ns_pending_files count] != 0
3666       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3667     {
3668       [ns_pending_files removeObjectAtIndex: 0];
3669     }
3670   /* Deal with pending service requests. */
3671   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3672     && [(EmacsApp *)
3673          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3674                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3675     {
3676       [ns_pending_service_names removeObjectAtIndex: 0];
3677       [ns_pending_service_args removeObjectAtIndex: 0];
3678     }
3679   else
3680     {
3681       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3682       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3683          to ourself, otherwise [NXApp run] will never exit.  */
3684       send_appdefined = YES;
3685       ns_send_appdefined (-1);
3687       if (++apploopnr != 1)
3688         {
3689           emacs_abort ();
3690         }
3691       record_unwind_protect (unwind_apploopnr, Qt);
3692       [NSApp run];
3693       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3694     }
3696   nevents = n_emacs_events_pending;
3697   n_emacs_events_pending = 0;
3698   ns_finish_events ();
3699   q_event_ptr = NULL;
3700   unblock_input ();
3702   return nevents;
3707 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3708            fd_set *exceptfds, struct timespec const *timeout,
3709            sigset_t const *sigmask)
3710 /* --------------------------------------------------------------------------
3711      Replacement for select, checking for events
3712    -------------------------------------------------------------------------- */
3714   int result;
3715   int t, k, nr = 0;
3716   struct input_event event;
3717   char c;
3719 /*  NSTRACE (ns_select); */
3721 #ifdef HAVE_NATIVE_FS
3722   check_native_fs ();
3723 #endif
3725   if (hold_event_q.nr > 0)
3726     {
3727       /* We already have events pending. */
3728       raise (SIGIO);
3729       errno = EINTR;
3730       return -1;
3731     }
3733   for (k = 0; k < nfds+1; k++)
3734     {
3735       if (readfds && FD_ISSET(k, readfds)) ++nr;
3736       if (writefds && FD_ISSET(k, writefds)) ++nr;
3737     }
3739   if (NSApp == nil
3740       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3741     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3743   [outerpool release];
3744   outerpool = [[NSAutoreleasePool alloc] init];
3747   send_appdefined = YES;
3748   if (nr > 0)
3749     {
3750       pthread_mutex_lock (&select_mutex);
3751       select_nfds = nfds;
3752       select_valid = 0;
3753       if (readfds)
3754         {
3755           select_readfds = *readfds;
3756           select_valid += SELECT_HAVE_READ;
3757         }
3758       if (writefds)
3759         {
3760           select_writefds = *writefds;
3761           select_valid += SELECT_HAVE_WRITE;
3762         }
3764       if (timeout)
3765         {
3766           select_timeout = *timeout;
3767           select_valid += SELECT_HAVE_TMO;
3768         }
3770       pthread_mutex_unlock (&select_mutex);
3772       /* Inform fd_handler that select should be called */
3773       c = 'g';
3774       emacs_write_sig (selfds[1], &c, 1);
3775     }
3776   else if (nr == 0 && timeout)
3777     {
3778       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3779       double time = timespectod (*timeout);
3780       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3781                                                       target: NSApp
3782                                                     selector:
3783                                   @selector (timeout_handler:)
3784                                                     userInfo: 0
3785                                                      repeats: NO]
3786                       retain];
3787     }
3788   else /* No timeout and no file descriptors, can this happen?  */
3789     {
3790       /* Send appdefined so we exit from the loop */
3791       ns_send_appdefined (-1);
3792     }
3794   block_input ();
3795   ns_init_events (&event);
3796   if (++apploopnr != 1)
3797     {
3798       emacs_abort ();
3799     }
3801   {
3802     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3803     record_unwind_protect (unwind_apploopnr, Qt);
3804     [NSApp run];
3805     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3806   }
3808   ns_finish_events ();
3809   if (nr > 0 && readfds)
3810     {
3811       c = 's';
3812       emacs_write_sig (selfds[1], &c, 1);
3813     }
3814   unblock_input ();
3816   t = last_appdefined_event_data;
3818   if (t != NO_APPDEFINED_DATA)
3819     {
3820       last_appdefined_event_data = NO_APPDEFINED_DATA;
3822       if (t == -2)
3823         {
3824           /* The NX_APPDEFINED event we received was a timeout. */
3825           result = 0;
3826         }
3827       else if (t == -1)
3828         {
3829           /* The NX_APPDEFINED event we received was the result of
3830              at least one real input event arriving.  */
3831           errno = EINTR;
3832           result = -1;
3833         }
3834       else
3835         {
3836           /* Received back from select () in fd_handler; copy the results */
3837           pthread_mutex_lock (&select_mutex);
3838           if (readfds) *readfds = select_readfds;
3839           if (writefds) *writefds = select_writefds;
3840           pthread_mutex_unlock (&select_mutex);
3841           result = t;
3842         }
3843     }
3844   else
3845     {
3846       errno = EINTR;
3847       result = -1;
3848     }
3850   return result;
3855 /* ==========================================================================
3857     Scrollbar handling
3859    ========================================================================== */
3862 static void
3863 ns_set_vertical_scroll_bar (struct window *window,
3864                            int portion, int whole, int position)
3865 /* --------------------------------------------------------------------------
3866       External (hook): Update or add scrollbar
3867    -------------------------------------------------------------------------- */
3869   Lisp_Object win;
3870   NSRect r, v;
3871   struct frame *f = XFRAME (WINDOW_FRAME (window));
3872   EmacsView *view = FRAME_NS_VIEW (f);
3873   EmacsScroller *bar;
3874   int window_y, window_height;
3875   int top, left, height, width;
3876   BOOL update_p = YES;
3878   /* optimization; display engine sends WAY too many of these.. */
3879   if (!NILP (window->vertical_scroll_bar))
3880     {
3881       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3882       if ([bar checkSamePosition: position portion: portion whole: whole])
3883         {
3884           if (view->scrollbarsNeedingUpdate == 0)
3885             {
3886               if (!windows_or_buffers_changed)
3887                   return;
3888             }
3889           else
3890             view->scrollbarsNeedingUpdate--;
3891           update_p = NO;
3892         }
3893     }
3895   NSTRACE (ns_set_vertical_scroll_bar);
3897   /* Get dimensions.  */
3898   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3899   top = window_y;
3900   height = window_height;
3901   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3902   left = WINDOW_SCROLL_BAR_AREA_X (window);
3904   r = NSMakeRect (left, top, width, height);
3905   /* the parent view is flipped, so we need to flip y value */
3906   v = [view frame];
3907   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3909   XSETWINDOW (win, window);
3910   block_input ();
3912   /* we want at least 5 lines to display a scrollbar */
3913   if (WINDOW_TOTAL_LINES (window) < 5)
3914     {
3915       if (!NILP (window->vertical_scroll_bar))
3916         {
3917           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3918           [bar removeFromSuperview];
3919           wset_vertical_scroll_bar (window, Qnil);
3920           [bar release];
3921         }
3922       ns_clear_frame_area (f, left, top, width, height);
3923       unblock_input ();
3924       return;
3925     }
3927   if (NILP (window->vertical_scroll_bar))
3928     {
3929       if (width > 0 && height > 0)
3930         ns_clear_frame_area (f, left, top, width, height);
3932       bar = [[EmacsScroller alloc] initFrame: r window: win];
3933       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3934       update_p = YES;
3935     }
3936   else
3937     {
3938       NSRect oldRect;
3939       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3940       oldRect = [bar frame];
3941       r.size.width = oldRect.size.width;
3942       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3943         {
3944           if (oldRect.origin.x != r.origin.x)
3945               ns_clear_frame_area (f, left, top, width, height);
3946           [bar setFrame: r];
3947         }
3948     }
3950   if (update_p)
3951     [bar setPosition: position portion: portion whole: whole];
3952   unblock_input ();
3956 static void
3957 ns_set_horizontal_scroll_bar (struct window *window,
3958                               int portion, int whole, int position)
3959 /* --------------------------------------------------------------------------
3960       External (hook): Update or add scrollbar
3961    -------------------------------------------------------------------------- */
3963   Lisp_Object win;
3964   NSRect r, v;
3965   struct frame *f = XFRAME (WINDOW_FRAME (window));
3966   EmacsView *view = FRAME_NS_VIEW (f);
3967   EmacsScroller *bar;
3968   int top, height, left, width;
3969   int window_x, window_width;
3970   BOOL update_p = YES;
3972   /* optimization; display engine sends WAY too many of these.. */
3973   if (!NILP (window->horizontal_scroll_bar))
3974     {
3975       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3976       if ([bar checkSamePosition: position portion: portion whole: whole])
3977         {
3978           if (view->scrollbarsNeedingUpdate == 0)
3979             {
3980               if (!windows_or_buffers_changed)
3981                   return;
3982             }
3983           else
3984             view->scrollbarsNeedingUpdate--;
3985           update_p = NO;
3986         }
3987     }
3989   NSTRACE (ns_set_horizontal_scroll_bar);
3991   /* Get dimensions.  */
3992   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3993   left = window_x;
3994   width = window_width;
3995   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3996   top = WINDOW_SCROLL_BAR_AREA_Y (window);
3998   r = NSMakeRect (left, top, width, height);
3999   /* the parent view is flipped, so we need to flip y value */
4000   v = [view frame];
4001   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4002   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4004   XSETWINDOW (win, window);
4005   block_input ();
4007   if (WINDOW_TOTAL_COLS (window) < 5)
4008     {
4009       if (!NILP (window->horizontal_scroll_bar))
4010         {
4011           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4012           [bar removeFromSuperview];
4013           wset_horizontal_scroll_bar (window, Qnil);
4014         }
4015       ns_clear_frame_area (f, left, top, width, height);
4016       unblock_input ();
4017       return;
4018     }
4020   if (NILP (window->horizontal_scroll_bar))
4021     {
4022       if (width > 0 && height > 0)
4023         ns_clear_frame_area (f, left, top, width, height);
4025       bar = [[EmacsScroller alloc] initFrame: r window: win];
4026       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4027       update_p = YES;
4028     }
4029   else
4030     {
4031       NSRect oldRect;
4032       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4033       oldRect = [bar frame];
4034       r.size.width = oldRect.size.width;
4035       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4036         {
4037           if (oldRect.origin.x != r.origin.x)
4038               ns_clear_frame_area (f, left, top, width, height);
4039           [bar setFrame: r];
4040           update_p = YES;
4041         }
4042     }
4044   if (update_p)
4045     [bar setPosition: position portion: portion whole: whole];
4046   unblock_input ();
4050 static void
4051 ns_condemn_scroll_bars (struct frame *f)
4052 /* --------------------------------------------------------------------------
4053      External (hook): arrange for all frame's scrollbars to be removed
4054      at next call to judge_scroll_bars, except for those redeemed.
4055    -------------------------------------------------------------------------- */
4057   int i;
4058   id view;
4059   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4061   NSTRACE (ns_condemn_scroll_bars);
4063   for (i =[subviews count]-1; i >= 0; i--)
4064     {
4065       view = [subviews objectAtIndex: i];
4066       if ([view isKindOfClass: [EmacsScroller class]])
4067         [view condemn];
4068     }
4072 static void
4073 ns_redeem_scroll_bar (struct window *window)
4074 /* --------------------------------------------------------------------------
4075      External (hook): arrange to spare this window's scrollbar
4076      at next call to judge_scroll_bars.
4077    -------------------------------------------------------------------------- */
4079   id bar;
4080   NSTRACE (ns_redeem_scroll_bar);
4081   if (!NILP (window->vertical_scroll_bar))
4082     {
4083       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4084       [bar reprieve];
4085     }
4087   if (!NILP (window->horizontal_scroll_bar))
4088     {
4089       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4090       [bar reprieve];
4091     }
4095 static void
4096 ns_judge_scroll_bars (struct frame *f)
4097 /* --------------------------------------------------------------------------
4098      External (hook): destroy all scrollbars on frame that weren't
4099      redeemed after call to condemn_scroll_bars.
4100    -------------------------------------------------------------------------- */
4102   int i;
4103   id view;
4104   EmacsView *eview = FRAME_NS_VIEW (f);
4105   NSArray *subviews = [[eview superview] subviews];
4106   BOOL removed = NO;
4108   NSTRACE (ns_judge_scroll_bars);
4109   for (i = [subviews count]-1; i >= 0; --i)
4110     {
4111       view = [subviews objectAtIndex: i];
4112       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4113       if ([view judge])
4114         removed = YES;
4115     }
4117   if (removed)
4118     [eview updateFrameSize: NO];
4121 /* ==========================================================================
4123     Initialization
4125    ========================================================================== */
4128 x_display_pixel_height (struct ns_display_info *dpyinfo)
4130   NSArray *screens = [NSScreen screens];
4131   NSEnumerator *enumerator = [screens objectEnumerator];
4132   NSScreen *screen;
4133   NSRect frame;
4135   frame = NSZeroRect;
4136   while ((screen = [enumerator nextObject]) != nil)
4137     frame = NSUnionRect (frame, [screen frame]);
4139   return NSHeight (frame);
4143 x_display_pixel_width (struct ns_display_info *dpyinfo)
4145   NSArray *screens = [NSScreen screens];
4146   NSEnumerator *enumerator = [screens objectEnumerator];
4147   NSScreen *screen;
4148   NSRect frame;
4150   frame = NSZeroRect;
4151   while ((screen = [enumerator nextObject]) != nil)
4152     frame = NSUnionRect (frame, [screen frame]);
4154   return NSWidth (frame);
4158 static Lisp_Object ns_string_to_lispmod (const char *s)
4159 /* --------------------------------------------------------------------------
4160      Convert modifier name to lisp symbol
4161    -------------------------------------------------------------------------- */
4163   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4164     return Qmeta;
4165   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4166     return Qsuper;
4167   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4168     return Qcontrol;
4169   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4170     return Qalt;
4171   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4172     return Qhyper;
4173   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4174     return Qnone;
4175   else
4176     return Qnil;
4180 static void
4181 ns_default (const char *parameter, Lisp_Object *result,
4182            Lisp_Object yesval, Lisp_Object noval,
4183            BOOL is_float, BOOL is_modstring)
4184 /* --------------------------------------------------------------------------
4185       Check a parameter value in user's preferences
4186    -------------------------------------------------------------------------- */
4188   const char *value = ns_get_defaults_value (parameter);
4190   if (value)
4191     {
4192       double f;
4193       char *pos;
4194       if (c_strcasecmp (value, "YES") == 0)
4195         *result = yesval;
4196       else if (c_strcasecmp (value, "NO") == 0)
4197         *result = noval;
4198       else if (is_float && (f = strtod (value, &pos), pos != value))
4199         *result = make_float (f);
4200       else if (is_modstring && value)
4201         *result = ns_string_to_lispmod (value);
4202       else fprintf (stderr,
4203                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4204     }
4208 static void
4209 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4210 /* --------------------------------------------------------------------------
4211       Initialize global info and storage for display.
4212    -------------------------------------------------------------------------- */
4214     NSScreen *screen = [NSScreen mainScreen];
4215     NSWindowDepth depth = [screen depth];
4217     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4218     dpyinfo->resy = 72.27;
4219     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4220                                                   NSColorSpaceFromDepth (depth)]
4221                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4222                                                  NSColorSpaceFromDepth (depth)];
4223     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4224     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4225     dpyinfo->color_table->colors = NULL;
4226     dpyinfo->root_window = 42; /* a placeholder.. */
4227     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4228     dpyinfo->n_fonts = 0;
4229     dpyinfo->smallest_font_height = 1;
4230     dpyinfo->smallest_char_width = 1;
4232     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4236 /* This and next define (many of the) public functions in this file. */
4237 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4238          with using despite presence in the "system dependent" redisplay
4239          interface.  In addition, many of the ns_ methods have code that is
4240          shared with all terms, indicating need for further refactoring. */
4241 extern frame_parm_handler ns_frame_parm_handlers[];
4242 static struct redisplay_interface ns_redisplay_interface =
4244   ns_frame_parm_handlers,
4245   x_produce_glyphs,
4246   x_write_glyphs,
4247   x_insert_glyphs,
4248   x_clear_end_of_line,
4249   ns_scroll_run,
4250   ns_after_update_window_line,
4251   ns_update_window_begin,
4252   ns_update_window_end,
4253   0, /* flush_display */
4254   x_clear_window_mouse_face,
4255   x_get_glyph_overhangs,
4256   x_fix_overlapping_area,
4257   ns_draw_fringe_bitmap,
4258   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4259   0, /* destroy_fringe_bitmap */
4260   ns_compute_glyph_string_overhangs,
4261   ns_draw_glyph_string,
4262   ns_define_frame_cursor,
4263   ns_clear_frame_area,
4264   ns_draw_window_cursor,
4265   ns_draw_vertical_window_border,
4266   ns_draw_window_divider,
4267   ns_shift_glyphs_for_insert,
4268   ns_show_hourglass,
4269   ns_hide_hourglass
4273 static void
4274 ns_delete_display (struct ns_display_info *dpyinfo)
4276   /* TODO... */
4280 /* This function is called when the last frame on a display is deleted. */
4281 static void
4282 ns_delete_terminal (struct terminal *terminal)
4284   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4286   /* Protect against recursive calls.  delete_frame in
4287      delete_terminal calls us back when it deletes our last frame.  */
4288   if (!terminal->name)
4289     return;
4291   block_input ();
4293   x_destroy_all_bitmaps (dpyinfo);
4294   ns_delete_display (dpyinfo);
4295   unblock_input ();
4299 static struct terminal *
4300 ns_create_terminal (struct ns_display_info *dpyinfo)
4301 /* --------------------------------------------------------------------------
4302       Set up use of NS before we make the first connection.
4303    -------------------------------------------------------------------------- */
4305   struct terminal *terminal;
4307   NSTRACE (ns_create_terminal);
4309   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4311   terminal->display_info.ns = dpyinfo;
4312   dpyinfo->terminal = terminal;
4314   terminal->clear_frame_hook = ns_clear_frame;
4315   terminal->ring_bell_hook = ns_ring_bell;
4316   terminal->update_begin_hook = ns_update_begin;
4317   terminal->update_end_hook = ns_update_end;
4318   terminal->read_socket_hook = ns_read_socket;
4319   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4320   terminal->mouse_position_hook = ns_mouse_position;
4321   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4322   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4323   terminal->fullscreen_hook = ns_fullscreen_hook;
4324   terminal->menu_show_hook = ns_menu_show;
4325   terminal->popup_dialog_hook = ns_popup_dialog;
4326   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4327   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4328   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4329   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4330   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4331   terminal->delete_frame_hook = x_destroy_window;
4332   terminal->delete_terminal_hook = ns_delete_terminal;
4333   /* Other hooks are NULL by default.  */
4335   return terminal;
4339 struct ns_display_info *
4340 ns_term_init (Lisp_Object display_name)
4341 /* --------------------------------------------------------------------------
4342      Start the Application and get things rolling.
4343    -------------------------------------------------------------------------- */
4345   struct terminal *terminal;
4346   struct ns_display_info *dpyinfo;
4347   static int ns_initialized = 0;
4348   Lisp_Object tmp;
4350   if (ns_initialized) return x_display_list;
4351   ns_initialized = 1;
4353   NSTRACE (ns_term_init);
4355   [outerpool release];
4356   outerpool = [[NSAutoreleasePool alloc] init];
4358   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4359   /*GSDebugAllocationActive (YES); */
4360   block_input ();
4362   baud_rate = 38400;
4363   Fset_input_interrupt_mode (Qnil);
4365   if (selfds[0] == -1)
4366     {
4367       if (emacs_pipe (selfds) != 0)
4368         {
4369           fprintf (stderr, "Failed to create pipe: %s\n",
4370                    emacs_strerror (errno));
4371           emacs_abort ();
4372         }
4374       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4375       FD_ZERO (&select_readfds);
4376       FD_ZERO (&select_writefds);
4377       pthread_mutex_init (&select_mutex, NULL);
4378     }
4380   ns_pending_files = [[NSMutableArray alloc] init];
4381   ns_pending_service_names = [[NSMutableArray alloc] init];
4382   ns_pending_service_args = [[NSMutableArray alloc] init];
4384 /* Start app and create the main menu, window, view.
4385      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4386      The view will then ask the NSApp to stop and return to Emacs. */
4387   [EmacsApp sharedApplication];
4388   if (NSApp == nil)
4389     return NULL;
4390   [NSApp setDelegate: NSApp];
4392   /* Start the select thread.  */
4393   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4394                            toTarget:NSApp
4395                          withObject:nil];
4397   /* debugging: log all notifications */
4398   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4399                                          selector: @selector (logNotification:)
4400                                              name: nil object: nil]; */
4402   dpyinfo = xzalloc (sizeof *dpyinfo);
4404   ns_initialize_display_info (dpyinfo);
4405   terminal = ns_create_terminal (dpyinfo);
4407   terminal->kboard = allocate_kboard (Qns);
4408   /* Don't let the initial kboard remain current longer than necessary.
4409      That would cause problems if a file loaded on startup tries to
4410      prompt in the mini-buffer.  */
4411   if (current_kboard == initial_kboard)
4412     current_kboard = terminal->kboard;
4413   terminal->kboard->reference_count++;
4415   dpyinfo->next = x_display_list;
4416   x_display_list = dpyinfo;
4418   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4420   terminal->name = xlispstrdup (display_name);
4422   unblock_input ();
4424   if (!inhibit_x_resources)
4425     {
4426       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4427                  Qt, Qnil, NO, NO);
4428       tmp = Qnil;
4429       /* this is a standard variable */
4430       ns_default ("AppleAntiAliasingThreshold", &tmp,
4431                  make_float (10.0), make_float (6.0), YES, NO);
4432       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4433     }
4435   {
4436     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4438     if ( cl == nil )
4439       {
4440         Lisp_Object color_file, color_map, color;
4441         unsigned long c;
4442         char *name;
4444         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4445                          Fsymbol_value (intern ("data-directory")));
4447         color_map = Fx_load_color_file (color_file);
4448         if (NILP (color_map))
4449           fatal ("Could not read %s.\n", SDATA (color_file));
4451         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4452         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4453           {
4454             color = XCAR (color_map);
4455             name = SSDATA (XCAR (color));
4456             c = XINT (XCDR (color));
4457             [cl setColor:
4458                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4459                                       green: GREEN_FROM_ULONG (c) / 255.0
4460                                        blue: BLUE_FROM_ULONG (c) / 255.0
4461                                       alpha: 1.0]
4462                   forKey: [NSString stringWithUTF8String: name]];
4463           }
4464         [cl writeToFile: nil];
4465       }
4466   }
4468   {
4469 #ifdef NS_IMPL_GNUSTEP
4470     Vwindow_system_version = build_string (gnustep_base_version);
4471 #else
4472     /*PSnextrelease (128, c); */
4473     char c[DBL_BUFSIZE_BOUND];
4474     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4475     Vwindow_system_version = make_unibyte_string (c, len);
4476 #endif
4477   }
4479   delete_keyboard_wait_descriptor (0);
4481   ns_app_name = [[NSProcessInfo processInfo] processName];
4483 /* Set up OS X app menu */
4484 #ifdef NS_IMPL_COCOA
4485   {
4486     NSMenu *appMenu;
4487     NSMenuItem *item;
4488     /* set up the application menu */
4489     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4490     [svcsMenu setAutoenablesItems: NO];
4491     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4492     [appMenu setAutoenablesItems: NO];
4493     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4494     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4496     [appMenu insertItemWithTitle: @"About Emacs"
4497                           action: @selector (orderFrontStandardAboutPanel:)
4498                    keyEquivalent: @""
4499                          atIndex: 0];
4500     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4501     [appMenu insertItemWithTitle: @"Preferences..."
4502                           action: @selector (showPreferencesWindow:)
4503                    keyEquivalent: @","
4504                          atIndex: 2];
4505     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4506     item = [appMenu insertItemWithTitle: @"Services"
4507                                  action: @selector (menuDown:)
4508                           keyEquivalent: @""
4509                                 atIndex: 4];
4510     [appMenu setSubmenu: svcsMenu forItem: item];
4511     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4512     [appMenu insertItemWithTitle: @"Hide Emacs"
4513                           action: @selector (hide:)
4514                    keyEquivalent: @"h"
4515                          atIndex: 6];
4516     item =  [appMenu insertItemWithTitle: @"Hide Others"
4517                           action: @selector (hideOtherApplications:)
4518                    keyEquivalent: @"h"
4519                          atIndex: 7];
4520     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4521     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4522     [appMenu insertItemWithTitle: @"Quit Emacs"
4523                           action: @selector (terminate:)
4524                    keyEquivalent: @"q"
4525                          atIndex: 9];
4527     item = [mainMenu insertItemWithTitle: ns_app_name
4528                                   action: @selector (menuDown:)
4529                            keyEquivalent: @""
4530                                  atIndex: 0];
4531     [mainMenu setSubmenu: appMenu forItem: item];
4532     [dockMenu insertItemWithTitle: @"New Frame"
4533                            action: @selector (newFrame:)
4534                     keyEquivalent: @""
4535                           atIndex: 0];
4537     [NSApp setMainMenu: mainMenu];
4538     [NSApp setAppleMenu: appMenu];
4539     [NSApp setServicesMenu: svcsMenu];
4540     /* Needed at least on Cocoa, to get dock menu to show windows */
4541     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4543     [[NSNotificationCenter defaultCenter]
4544       addObserver: mainMenu
4545          selector: @selector (trackingNotification:)
4546              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4547     [[NSNotificationCenter defaultCenter]
4548       addObserver: mainMenu
4549          selector: @selector (trackingNotification:)
4550              name: NSMenuDidEndTrackingNotification object: mainMenu];
4551   }
4552 #endif /* MAC OS X menu setup */
4554   /* Register our external input/output types, used for determining
4555      applicable services and also drag/drop eligibility. */
4556   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4557   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4558                       retain];
4559   ns_drag_types = [[NSArray arrayWithObjects:
4560                             NSStringPboardType,
4561                             NSTabularTextPboardType,
4562                             NSFilenamesPboardType,
4563                             NSURLPboardType, nil] retain];
4565   /* If fullscreen is in init/default-frame-alist, focus isn't set
4566      right for fullscreen windows, so set this.  */
4567   [NSApp activateIgnoringOtherApps:YES];
4569   [NSApp run];
4570   ns_do_open_file = YES;
4572 #ifdef NS_IMPL_GNUSTEP
4573   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4574      We must re-catch it so subprocess works.  */
4575   catch_child_signal ();
4576 #endif
4577   return dpyinfo;
4581 void
4582 ns_term_shutdown (int sig)
4584   [[NSUserDefaults standardUserDefaults] synchronize];
4586   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4587   if (STRINGP (Vauto_save_list_file_name))
4588     unlink (SSDATA (Vauto_save_list_file_name));
4590   if (sig == 0 || sig == SIGTERM)
4591     {
4592       [NSApp terminate: NSApp];
4593     }
4594   else // force a stack trace to happen
4595     {
4596       emacs_abort ();
4597     }
4601 /* ==========================================================================
4603     EmacsApp implementation
4605    ========================================================================== */
4608 @implementation EmacsApp
4610 - (id)init
4612   if ((self = [super init]))
4613     {
4614 #ifdef NS_IMPL_COCOA
4615       self->isFirst = YES;
4616 #endif
4617 #ifdef NS_IMPL_GNUSTEP
4618       self->applicationDidFinishLaunchingCalled = NO;
4619 #endif
4620     }
4622   return self;
4625 #ifdef NS_IMPL_COCOA
4626 - (void)run
4628 #ifndef NSAppKitVersionNumber10_9
4629 #define NSAppKitVersionNumber10_9 1265
4630 #endif
4632     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4633       {
4634         [super run];
4635         return;
4636       }
4638   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4640   if (isFirst) [self finishLaunching];
4641   isFirst = NO;
4643   shouldKeepRunning = YES;
4644   do
4645     {
4646       [pool release];
4647       pool = [[NSAutoreleasePool alloc] init];
4649       NSEvent *event =
4650         [self nextEventMatchingMask:NSAnyEventMask
4651                           untilDate:[NSDate distantFuture]
4652                              inMode:NSDefaultRunLoopMode
4653                             dequeue:YES];
4655       [self sendEvent:event];
4656       [self updateWindows];
4657     } while (shouldKeepRunning);
4659   [pool release];
4662 - (void)stop: (id)sender
4664     shouldKeepRunning = NO;
4665     // Stop possible dialog also.  Noop if no dialog present.
4666     // The file dialog still leaks 7k - 10k on 10.9 though.
4667     [super stop:sender];
4669 #endif /* NS_IMPL_COCOA */
4671 - (void)logNotification: (NSNotification *)notification
4673   const char *name = [[notification name] UTF8String];
4674   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4675       && !strstr (name, "WindowNumber"))
4676     NSLog (@"notification: '%@'", [notification name]);
4680 - (void)sendEvent: (NSEvent *)theEvent
4681 /* --------------------------------------------------------------------------
4682      Called when NSApp is running for each event received.  Used to stop
4683      the loop when we choose, since there's no way to just run one iteration.
4684    -------------------------------------------------------------------------- */
4686   int type = [theEvent type];
4687   NSWindow *window = [theEvent window];
4689 /*  NSTRACE (sendEvent); */
4690 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4692 #ifdef NS_IMPL_GNUSTEP
4693   // Keyboard events aren't propagated to file dialogs for some reason.
4694   if ([NSApp modalWindow] != nil &&
4695       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4696     {
4697       [[NSApp modalWindow] sendEvent: theEvent];
4698       return;
4699     }
4700 #endif
4702   if (represented_filename != nil && represented_frame)
4703     {
4704       NSString *fstr = represented_filename;
4705       NSView *view = FRAME_NS_VIEW (represented_frame);
4706 #ifdef NS_IMPL_COCOA
4707       /* work around a bug observed on 10.3 and later where
4708          setTitleWithRepresentedFilename does not clear out previous state
4709          if given filename does not exist */
4710       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4711         [[view window] setRepresentedFilename: @""];
4712 #endif
4713       [[view window] setRepresentedFilename: fstr];
4714       [represented_filename release];
4715       represented_filename = nil;
4716       represented_frame = NULL;
4717     }
4719   if (type == NSApplicationDefined)
4720     {
4721       switch ([theEvent data2])
4722         {
4723 #ifdef NS_IMPL_COCOA
4724         case NSAPP_DATA2_RUNASSCRIPT:
4725           ns_run_ascript ();
4726           [self stop: self];
4727           return;
4728 #endif
4729         case NSAPP_DATA2_RUNFILEDIALOG:
4730           ns_run_file_dialog ();
4731           [self stop: self];
4732           return;
4733         }
4734     }
4736   if (type == NSCursorUpdate && window == nil)
4737     {
4738       fprintf (stderr, "Dropping external cursor update event.\n");
4739       return;
4740     }
4742   if (type == NSApplicationDefined)
4743     {
4744       /* Events posted by ns_send_appdefined interrupt the run loop here.
4745          But, if a modal window is up, an appdefined can still come through,
4746          (e.g., from a makeKeyWindow event) but stopping self also stops the
4747          modal loop. Just defer it until later. */
4748       if ([NSApp modalWindow] == nil)
4749         {
4750           last_appdefined_event_data = [theEvent data1];
4751           [self stop: self];
4752         }
4753       else
4754         {
4755           send_appdefined = YES;
4756         }
4757     }
4760 #ifdef NS_IMPL_COCOA
4761   /* If no dialog and none of our frames have focus and it is a move, skip it.
4762      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4763      such as Wifi, sound, date or similar.
4764      This prevents "spooky" highlighting in the frame under the menu.  */
4765   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4766     {
4767       struct ns_display_info *di;
4768       BOOL has_focus = NO;
4769       for (di = x_display_list; ! has_focus && di; di = di->next)
4770         has_focus = di->x_focus_frame != 0;
4771       if (! has_focus)
4772         return;
4773     }
4774 #endif
4776   [super sendEvent: theEvent];
4780 - (void)showPreferencesWindow: (id)sender
4782   struct frame *emacsframe = SELECTED_FRAME ();
4783   NSEvent *theEvent = [NSApp currentEvent];
4785   if (!emacs_event)
4786     return;
4787   emacs_event->kind = NS_NONKEY_EVENT;
4788   emacs_event->code = KEY_NS_SHOW_PREFS;
4789   emacs_event->modifiers = 0;
4790   EV_TRAILER (theEvent);
4794 - (void)newFrame: (id)sender
4796   struct frame *emacsframe = SELECTED_FRAME ();
4797   NSEvent *theEvent = [NSApp currentEvent];
4799   if (!emacs_event)
4800     return;
4801   emacs_event->kind = NS_NONKEY_EVENT;
4802   emacs_event->code = KEY_NS_NEW_FRAME;
4803   emacs_event->modifiers = 0;
4804   EV_TRAILER (theEvent);
4808 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4809 - (BOOL) openFile: (NSString *)fileName
4811   struct frame *emacsframe = SELECTED_FRAME ();
4812   NSEvent *theEvent = [NSApp currentEvent];
4814   if (!emacs_event)
4815     return NO;
4817   emacs_event->kind = NS_NONKEY_EVENT;
4818   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4819   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4820   ns_input_line = Qnil; /* can be start or cons start,end */
4821   emacs_event->modifiers =0;
4822   EV_TRAILER (theEvent);
4824   return YES;
4828 /* **************************************************************************
4830       EmacsApp delegate implementation
4832    ************************************************************************** */
4834 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4835 /* --------------------------------------------------------------------------
4836      When application is loaded, terminate event loop in ns_term_init
4837    -------------------------------------------------------------------------- */
4839   NSTRACE (applicationDidFinishLaunching);
4840 #ifdef NS_IMPL_GNUSTEP
4841   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4842 #endif
4843   [NSApp setServicesProvider: NSApp];
4845   [self antialiasThresholdDidChange:nil];
4846 #ifdef NS_IMPL_COCOA
4847   [[NSNotificationCenter defaultCenter]
4848     addObserver:self
4849        selector:@selector(antialiasThresholdDidChange:)
4850            name:NSAntialiasThresholdChangedNotification
4851          object:nil];
4852 #endif
4854   ns_send_appdefined (-2);
4857 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4859 #ifdef NS_IMPL_COCOA
4860   macfont_update_antialias_threshold ();
4861 #endif
4865 /* Termination sequences:
4866     C-x C-c:
4867     Cmd-Q:
4868     MenuBar | File | Exit:
4869     Select Quit from App menubar:
4870         -terminate
4871         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4872         ns_term_shutdown()
4874     Select Quit from Dock menu:
4875     Logout attempt:
4876         -appShouldTerminate
4877           Cancel -> Nothing else
4878           Accept ->
4880           -terminate
4881           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4882           ns_term_shutdown()
4886 - (void) terminate: (id)sender
4888   struct frame *emacsframe = SELECTED_FRAME ();
4890   if (!emacs_event)
4891     return;
4893   emacs_event->kind = NS_NONKEY_EVENT;
4894   emacs_event->code = KEY_NS_POWER_OFF;
4895   emacs_event->arg = Qt; /* mark as non-key event */
4896   EV_TRAILER ((id)nil);
4899 static bool
4900 runAlertPanel(NSString *title,
4901               NSString *msgFormat,
4902               NSString *defaultButton,
4903               NSString *alternateButton)
4905 #if !defined (NS_IMPL_COCOA) || \
4906   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
4907   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
4908     == NSAlertDefaultReturn;
4909 #else
4910   NSAlert *alert = [[NSAlert alloc] init];
4911   [alert setAlertStyle: NSCriticalAlertStyle];
4912   [alert setMessageText: msgFormat];
4913   [alert addButtonWithTitle: defaultButton];
4914   [alert addButtonWithTitle: alternateButton];
4915   NSInteger ret = [alert runModal];
4916   [alert release];
4917   return ret == NSAlertFirstButtonReturn;
4918 #endif
4922 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4924   bool ret;
4926   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4927     return NSTerminateNow;
4929     ret = runAlertPanel(ns_app_name,
4930                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4931                         @"Save Buffers and Exit", @"Cancel");
4933     if (ret)
4934         return NSTerminateNow;
4935     else
4936         return NSTerminateCancel;
4937     return NSTerminateNow;  /* just in case */
4940 static int
4941 not_in_argv (NSString *arg)
4943   int k;
4944   const char *a = [arg UTF8String];
4945   for (k = 1; k < initial_argc; ++k)
4946     if (strcmp (a, initial_argv[k]) == 0) return 0;
4947   return 1;
4950 /*   Notification from the Workspace to open a file */
4951 - (BOOL)application: sender openFile: (NSString *)file
4953   if (ns_do_open_file || not_in_argv (file))
4954     [ns_pending_files addObject: file];
4955   return YES;
4959 /*   Open a file as a temporary file */
4960 - (BOOL)application: sender openTempFile: (NSString *)file
4962   if (ns_do_open_file || not_in_argv (file))
4963     [ns_pending_files addObject: file];
4964   return YES;
4968 /*   Notification from the Workspace to open a file noninteractively (?) */
4969 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4971   if (ns_do_open_file || not_in_argv (file))
4972     [ns_pending_files addObject: file];
4973   return YES;
4976 /*   Notification from the Workspace to open multiple files */
4977 - (void)application: sender openFiles: (NSArray *)fileList
4979   NSEnumerator *files = [fileList objectEnumerator];
4980   NSString *file;
4981   /* Don't open files from the command line unconditionally,
4982      Cocoa parses the command line wrong, --option value tries to open value
4983      if --option is the last option.  */
4984   while ((file = [files nextObject]) != nil)
4985     if (ns_do_open_file || not_in_argv (file))
4986       [ns_pending_files addObject: file];
4988   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4993 /* Handle dock menu requests.  */
4994 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4996   return dockMenu;
5000 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5001 - (void)applicationWillBecomeActive: (NSNotification *)notification
5003   //ns_app_active=YES;
5005 - (void)applicationDidBecomeActive: (NSNotification *)notification
5007   NSTRACE (applicationDidBecomeActive);
5009 #ifdef NS_IMPL_GNUSTEP
5010   if (! applicationDidFinishLaunchingCalled)
5011     [self applicationDidFinishLaunching:notification];
5012 #endif
5013   //ns_app_active=YES;
5015   ns_update_auto_hide_menu_bar ();
5016   // No constraining takes place when the application is not active.
5017   ns_constrain_all_frames ();
5019 - (void)applicationDidResignActive: (NSNotification *)notification
5021   //ns_app_active=NO;
5022   ns_send_appdefined (-1);
5027 /* ==========================================================================
5029     EmacsApp aux handlers for managing event loop
5031    ========================================================================== */
5034 - (void)timeout_handler: (NSTimer *)timedEntry
5035 /* --------------------------------------------------------------------------
5036      The timeout specified to ns_select has passed.
5037    -------------------------------------------------------------------------- */
5039   /*NSTRACE (timeout_handler); */
5040   ns_send_appdefined (-2);
5043 #ifdef NS_IMPL_GNUSTEP
5044 - (void)sendFromMainThread:(id)unused
5046   ns_send_appdefined (nextappdefined);
5048 #endif
5050 - (void)fd_handler:(id)unused
5051 /* --------------------------------------------------------------------------
5052      Check data waiting on file descriptors and terminate if so
5053    -------------------------------------------------------------------------- */
5055   int result;
5056   int waiting = 1, nfds;
5057   char c;
5059   fd_set readfds, writefds, *wfds;
5060   struct timespec timeout, *tmo;
5061   NSAutoreleasePool *pool = nil;
5063   /* NSTRACE (fd_handler); */
5065   for (;;)
5066     {
5067       [pool release];
5068       pool = [[NSAutoreleasePool alloc] init];
5070       if (waiting)
5071         {
5072           fd_set fds;
5073           FD_ZERO (&fds);
5074           FD_SET (selfds[0], &fds);
5075           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5076           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5077             waiting = 0;
5078         }
5079       else
5080         {
5081           pthread_mutex_lock (&select_mutex);
5082           nfds = select_nfds;
5084           if (select_valid & SELECT_HAVE_READ)
5085             readfds = select_readfds;
5086           else
5087             FD_ZERO (&readfds);
5089           if (select_valid & SELECT_HAVE_WRITE)
5090             {
5091               writefds = select_writefds;
5092               wfds = &writefds;
5093             }
5094           else
5095             wfds = NULL;
5096           if (select_valid & SELECT_HAVE_TMO)
5097             {
5098               timeout = select_timeout;
5099               tmo = &timeout;
5100             }
5101           else
5102             tmo = NULL;
5104           pthread_mutex_unlock (&select_mutex);
5106           FD_SET (selfds[0], &readfds);
5107           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5109           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5111           if (result == 0)
5112             ns_send_appdefined (-2);
5113           else if (result > 0)
5114             {
5115               if (FD_ISSET (selfds[0], &readfds))
5116                 {
5117                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5118                     waiting = 1;
5119                 }
5120               else
5121                 {
5122                   pthread_mutex_lock (&select_mutex);
5123                   if (select_valid & SELECT_HAVE_READ)
5124                     select_readfds = readfds;
5125                   if (select_valid & SELECT_HAVE_WRITE)
5126                     select_writefds = writefds;
5127                   if (select_valid & SELECT_HAVE_TMO)
5128                     select_timeout = timeout;
5129                   pthread_mutex_unlock (&select_mutex);
5131                   ns_send_appdefined (result);
5132                 }
5133             }
5134           waiting = 1;
5135         }
5136     }
5141 /* ==========================================================================
5143     Service provision
5145    ========================================================================== */
5147 /* called from system: queue for next pass through event loop */
5148 - (void)requestService: (NSPasteboard *)pboard
5149               userData: (NSString *)userData
5150                  error: (NSString **)error
5152   [ns_pending_service_names addObject: userData];
5153   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5154       SSDATA (ns_string_from_pasteboard (pboard))]];
5158 /* called from ns_read_socket to clear queue */
5159 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5161   struct frame *emacsframe = SELECTED_FRAME ();
5162   NSEvent *theEvent = [NSApp currentEvent];
5164   if (!emacs_event)
5165     return NO;
5167   emacs_event->kind = NS_NONKEY_EVENT;
5168   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5169   ns_input_spi_name = build_string ([name UTF8String]);
5170   ns_input_spi_arg = build_string ([arg UTF8String]);
5171   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5172   EV_TRAILER (theEvent);
5174   return YES;
5178 @end  /* EmacsApp */
5182 /* ==========================================================================
5184     EmacsView implementation
5186    ========================================================================== */
5189 @implementation EmacsView
5191 /* needed to inform when window closed from LISP */
5192 - (void) setWindowClosing: (BOOL)closing
5194   windowClosing = closing;
5198 - (void)dealloc
5200   NSTRACE (EmacsView_dealloc);
5201   [toolbar release];
5202   if (fs_state == FULLSCREEN_BOTH)
5203     [nonfs_window release];
5204   [super dealloc];
5208 /* called on font panel selection */
5209 - (void)changeFont: (id)sender
5211   NSEvent *e = [[self window] currentEvent];
5212   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5213   struct font *font = face->font;
5214   id newFont;
5215   CGFloat size;
5216   NSFont *nsfont;
5218   NSTRACE (changeFont);
5220   if (!emacs_event)
5221     return;
5223 #ifdef NS_IMPL_GNUSTEP
5224   nsfont = ((struct nsfont_info *)font)->nsfont;
5225 #endif
5226 #ifdef NS_IMPL_COCOA
5227   nsfont = (NSFont *) macfont_get_nsctfont (font);
5228 #endif
5230   if ((newFont = [sender convertFont: nsfont]))
5231     {
5232       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5234       emacs_event->kind = NS_NONKEY_EVENT;
5235       emacs_event->modifiers = 0;
5236       emacs_event->code = KEY_NS_CHANGE_FONT;
5238       size = [newFont pointSize];
5239       ns_input_fontsize = make_number (lrint (size));
5240       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5241       EV_TRAILER (e);
5242     }
5246 - (BOOL)acceptsFirstResponder
5248   NSTRACE (acceptsFirstResponder);
5249   return YES;
5253 - (void)resetCursorRects
5255   NSRect visible = [self visibleRect];
5256   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5257   NSTRACE (resetCursorRects);
5259   if (currentCursor == nil)
5260     currentCursor = [NSCursor arrowCursor];
5262   if (!NSIsEmptyRect (visible))
5263     [self addCursorRect: visible cursor: currentCursor];
5264   [currentCursor setOnMouseEntered: YES];
5269 /*****************************************************************************/
5270 /* Keyboard handling. */
5271 #define NS_KEYLOG 0
5273 - (void)keyDown: (NSEvent *)theEvent
5275   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5276   int code;
5277   unsigned fnKeysym = 0;
5278   static NSMutableArray *nsEvArray;
5279   int left_is_none;
5280   unsigned int flags = [theEvent modifierFlags];
5282   NSTRACE (keyDown);
5284   /* Rhapsody and OS X give up and down events for the arrow keys */
5285   if (ns_fake_keydown == YES)
5286     ns_fake_keydown = NO;
5287   else if ([theEvent type] != NSKeyDown)
5288     return;
5290   if (!emacs_event)
5291     return;
5293  if (![[self window] isKeyWindow]
5294      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5295      /* we must avoid an infinite loop here. */
5296      && (EmacsView *)[[theEvent window] delegate] != self)
5297    {
5298      /* XXX: There is an occasional condition in which, when Emacs display
5299          updates a different frame from the current one, and temporarily
5300          selects it, then processes some interrupt-driven input
5301          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5302          for some reason that window has its first responder set to the NSView
5303          most recently updated (I guess), which is not the correct one. */
5304      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5305      return;
5306    }
5308   if (nsEvArray == nil)
5309     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5311   [NSCursor setHiddenUntilMouseMoves: YES];
5313   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5314     {
5315       clear_mouse_face (hlinfo);
5316       hlinfo->mouse_face_hidden = 1;
5317     }
5319   if (!processingCompose)
5320     {
5321       /* When using screen sharing, no left or right information is sent,
5322          so use Left key in those cases.  */
5323       int is_left_key, is_right_key;
5325       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5326         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5328       /* (Carbon way: [theEvent keyCode]) */
5330       /* is it a "function key"? */
5331       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5332          flag set (this is probably a bug in the OS).
5333       */
5334       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5335         {
5336           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5337         }
5338       if (fnKeysym == 0)
5339         {
5340           fnKeysym = ns_convert_key (code);
5341         }
5343       if (fnKeysym)
5344         {
5345           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5346              because Emacs treats Delete and KP-Delete same (in simple.el). */
5347           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5348 #ifdef NS_IMPL_GNUSTEP
5349               /*  GNUstep uses incompatible keycodes, even for those that are
5350                   supposed to be hardware independent.  Just check for delete.
5351                   Keypad delete does not have keysym 0xFFFF.
5352                   See http://savannah.gnu.org/bugs/?25395
5353               */
5354               || (fnKeysym == 0xFFFF && code == 127)
5355 #endif
5356             )
5357             code = 0xFF08; /* backspace */
5358           else
5359             code = fnKeysym;
5360         }
5362       /* are there modifiers? */
5363       emacs_event->modifiers = 0;
5365       if (flags & NSHelpKeyMask)
5366           emacs_event->modifiers |= hyper_modifier;
5368       if (flags & NSShiftKeyMask)
5369         emacs_event->modifiers |= shift_modifier;
5371       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5372       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5373         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5375       if (is_right_key)
5376         emacs_event->modifiers |= parse_solitary_modifier
5377           (EQ (ns_right_command_modifier, Qleft)
5378            ? ns_command_modifier
5379            : ns_right_command_modifier);
5381       if (is_left_key)
5382         {
5383           emacs_event->modifiers |= parse_solitary_modifier
5384             (ns_command_modifier);
5386           /* if super (default), take input manager's word so things like
5387              dvorak / qwerty layout work */
5388           if (EQ (ns_command_modifier, Qsuper)
5389               && !fnKeysym
5390               && [[theEvent characters] length] != 0)
5391             {
5392               /* XXX: the code we get will be unshifted, so if we have
5393                  a shift modifier, must convert ourselves */
5394               if (!(flags & NSShiftKeyMask))
5395                 code = [[theEvent characters] characterAtIndex: 0];
5396 #if 0
5397               /* this is ugly and also requires linking w/Carbon framework
5398                  (for LMGetKbdType) so for now leave this rare (?) case
5399                  undealt with.. in future look into CGEvent methods */
5400               else
5401                 {
5402                   long smv = GetScriptManagerVariable (smKeyScript);
5403                   Handle uchrHandle = GetResource
5404                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5405                   UInt32 dummy = 0;
5406                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5407                                  [[theEvent characters] characterAtIndex: 0],
5408                                  kUCKeyActionDisplay,
5409                                  (flags & ~NSCommandKeyMask) >> 8,
5410                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5411                                  &dummy, 1, &dummy, &code);
5412                   code &= 0xFF;
5413                 }
5414 #endif
5415             }
5416         }
5418       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5419       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5420         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5422       if (is_right_key)
5423           emacs_event->modifiers |= parse_solitary_modifier
5424               (EQ (ns_right_control_modifier, Qleft)
5425                ? ns_control_modifier
5426                : ns_right_control_modifier);
5428       if (is_left_key)
5429         emacs_event->modifiers |= parse_solitary_modifier
5430           (ns_control_modifier);
5432       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5433           emacs_event->modifiers |=
5434             parse_solitary_modifier (ns_function_modifier);
5436       left_is_none = NILP (ns_alternate_modifier)
5437         || EQ (ns_alternate_modifier, Qnone);
5439       is_right_key = (flags & NSRightAlternateKeyMask)
5440         == NSRightAlternateKeyMask;
5441       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5442         || (! is_right_key
5443             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5445       if (is_right_key)
5446         {
5447           if ((NILP (ns_right_alternate_modifier)
5448                || EQ (ns_right_alternate_modifier, Qnone)
5449                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5450               && !fnKeysym)
5451             {   /* accept pre-interp alt comb */
5452               if ([[theEvent characters] length] > 0)
5453                 code = [[theEvent characters] characterAtIndex: 0];
5454               /*HACK: clear lone shift modifier to stop next if from firing */
5455               if (emacs_event->modifiers == shift_modifier)
5456                 emacs_event->modifiers = 0;
5457             }
5458           else
5459             emacs_event->modifiers |= parse_solitary_modifier
5460               (EQ (ns_right_alternate_modifier, Qleft)
5461                ? ns_alternate_modifier
5462                : ns_right_alternate_modifier);
5463         }
5465       if (is_left_key) /* default = meta */
5466         {
5467           if (left_is_none && !fnKeysym)
5468             {   /* accept pre-interp alt comb */
5469               if ([[theEvent characters] length] > 0)
5470                 code = [[theEvent characters] characterAtIndex: 0];
5471               /*HACK: clear lone shift modifier to stop next if from firing */
5472               if (emacs_event->modifiers == shift_modifier)
5473                 emacs_event->modifiers = 0;
5474             }
5475           else
5476               emacs_event->modifiers |=
5477                 parse_solitary_modifier (ns_alternate_modifier);
5478         }
5480   if (NS_KEYLOG)
5481     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5482              code, fnKeysym, flags, emacs_event->modifiers);
5484       /* if it was a function key or had modifiers, pass it directly to emacs */
5485       if (fnKeysym || (emacs_event->modifiers
5486                        && (emacs_event->modifiers != shift_modifier)
5487                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5488 /*[[theEvent characters] length] */
5489         {
5490           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5491           if (code < 0x20)
5492             code |= (1<<28)|(3<<16);
5493           else if (code == 0x7f)
5494             code |= (1<<28)|(3<<16);
5495           else if (!fnKeysym)
5496             emacs_event->kind = code > 0xFF
5497               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5499           emacs_event->code = code;
5500           EV_TRAILER (theEvent);
5501           processingCompose = NO;
5502           return;
5503         }
5504     }
5507   if (NS_KEYLOG && !processingCompose)
5508     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5510   processingCompose = YES;
5511   [nsEvArray addObject: theEvent];
5512   [self interpretKeyEvents: nsEvArray];
5513   [nsEvArray removeObject: theEvent];
5517 #ifdef NS_IMPL_COCOA
5518 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5519    decided not to send key-down for.
5520    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5521    This only applies on Tiger and earlier.
5522    If it matches one of these, send it on to keyDown. */
5523 -(void)keyUp: (NSEvent *)theEvent
5525   int flags = [theEvent modifierFlags];
5526   int code = [theEvent keyCode];
5527   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5528       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5529     {
5530       if (NS_KEYLOG)
5531         fprintf (stderr, "keyUp: passed test");
5532       ns_fake_keydown = YES;
5533       [self keyDown: theEvent];
5534     }
5536 #endif
5539 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5542 /* <NSTextInput>: called when done composing;
5543    NOTE: also called when we delete over working text, followed immed.
5544          by doCommandBySelector: deleteBackward: */
5545 - (void)insertText: (id)aString
5547   int code;
5548   int len = [(NSString *)aString length];
5549   int i;
5551   if (NS_KEYLOG)
5552     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5553   processingCompose = NO;
5555   if (!emacs_event)
5556     return;
5558   /* first, clear any working text */
5559   if (workingText != nil)
5560     [self deleteWorkingText];
5562   /* now insert the string as keystrokes */
5563   for (i =0; i<len; i++)
5564     {
5565       code = [aString characterAtIndex: i];
5566       /* TODO: still need this? */
5567       if (code == 0x2DC)
5568         code = '~'; /* 0x7E */
5569       if (code != 32) /* Space */
5570         emacs_event->modifiers = 0;
5571       emacs_event->kind
5572         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5573       emacs_event->code = code;
5574       EV_TRAILER ((id)nil);
5575     }
5579 /* <NSTextInput>: inserts display of composing characters */
5580 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5582   NSString *str = [aString respondsToSelector: @selector (string)] ?
5583     [aString string] : aString;
5584   if (NS_KEYLOG)
5585     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5586            str, (unsigned long)[str length],
5587            (unsigned long)selRange.length,
5588            (unsigned long)selRange.location);
5590   if (workingText != nil)
5591     [self deleteWorkingText];
5592   if ([str length] == 0)
5593     return;
5595   if (!emacs_event)
5596     return;
5598   processingCompose = YES;
5599   workingText = [str copy];
5600   ns_working_text = build_string ([workingText UTF8String]);
5602   emacs_event->kind = NS_TEXT_EVENT;
5603   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5604   EV_TRAILER ((id)nil);
5608 /* delete display of composing characters [not in <NSTextInput>] */
5609 - (void)deleteWorkingText
5611   if (workingText == nil)
5612     return;
5613   if (NS_KEYLOG)
5614     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5615   [workingText release];
5616   workingText = nil;
5617   processingCompose = NO;
5619   if (!emacs_event)
5620     return;
5622   emacs_event->kind = NS_TEXT_EVENT;
5623   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5624   EV_TRAILER ((id)nil);
5628 - (BOOL)hasMarkedText
5630   return workingText != nil;
5634 - (NSRange)markedRange
5636   NSRange rng = workingText != nil
5637     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5638   if (NS_KEYLOG)
5639     NSLog (@"markedRange request");
5640   return rng;
5644 - (void)unmarkText
5646   if (NS_KEYLOG)
5647     NSLog (@"unmark (accept) text");
5648   [self deleteWorkingText];
5649   processingCompose = NO;
5653 /* used to position char selection windows, etc. */
5654 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5656   NSRect rect;
5657   NSPoint pt;
5658   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5659   if (NS_KEYLOG)
5660     NSLog (@"firstRectForCharRange request");
5662   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5663   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5664   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5665   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5666                                        +FRAME_LINE_HEIGHT (emacsframe));
5668   pt = [self convertPoint: pt toView: nil];
5669   pt = [[self window] convertBaseToScreen: pt];
5670   rect.origin = pt;
5671   return rect;
5675 - (NSInteger)conversationIdentifier
5677   return (NSInteger)self;
5681 - (void)doCommandBySelector: (SEL)aSelector
5683   if (NS_KEYLOG)
5684     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5686   processingCompose = NO;
5687   if (aSelector == @selector (deleteBackward:))
5688     {
5689       /* happens when user backspaces over an ongoing composition:
5690          throw a 'delete' into the event queue */
5691       if (!emacs_event)
5692         return;
5693       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5694       emacs_event->code = 0xFF08;
5695       EV_TRAILER ((id)nil);
5696     }
5699 - (NSArray *)validAttributesForMarkedText
5701   static NSArray *arr = nil;
5702   if (arr == nil) arr = [NSArray new];
5703  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5704   return arr;
5707 - (NSRange)selectedRange
5709   if (NS_KEYLOG)
5710     NSLog (@"selectedRange request");
5711   return NSMakeRange (NSNotFound, 0);
5714 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5715     GNUSTEP_GUI_MINOR_VERSION > 22
5716 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5717 #else
5718 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5719 #endif
5721   if (NS_KEYLOG)
5722     NSLog (@"characterIndexForPoint request");
5723   return 0;
5726 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5728   static NSAttributedString *str = nil;
5729   if (str == nil) str = [NSAttributedString new];
5730   if (NS_KEYLOG)
5731     NSLog (@"attributedSubstringFromRange request");
5732   return str;
5735 /* End <NSTextInput> impl. */
5736 /*****************************************************************************/
5739 /* This is what happens when the user presses a mouse button.  */
5740 - (void)mouseDown: (NSEvent *)theEvent
5742   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5743   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5745   NSTRACE (mouseDown);
5747   [self deleteWorkingText];
5749   if (!emacs_event)
5750     return;
5752   dpyinfo->last_mouse_frame = emacsframe;
5753   /* appears to be needed to prevent spurious movement events generated on
5754      button clicks */
5755   emacsframe->mouse_moved = 0;
5757   if ([theEvent type] == NSScrollWheel)
5758     {
5759       CGFloat delta = [theEvent deltaY];
5760       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5761       if (delta == 0)
5762         {
5763           delta = [theEvent deltaX];
5764           if (delta == 0)
5765             {
5766               NSTRACE (deltaIsZero);
5767               return;
5768             }
5769           emacs_event->kind = HORIZ_WHEEL_EVENT;
5770         }
5771       else
5772         emacs_event->kind = WHEEL_EVENT;
5774       emacs_event->code = 0;
5775       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5776         ((delta > 0) ? up_modifier : down_modifier);
5777     }
5778   else
5779     {
5780       emacs_event->kind = MOUSE_CLICK_EVENT;
5781       emacs_event->code = EV_BUTTON (theEvent);
5782       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5783                              | EV_UDMODIFIERS (theEvent);
5784     }
5785   XSETINT (emacs_event->x, lrint (p.x));
5786   XSETINT (emacs_event->y, lrint (p.y));
5787   EV_TRAILER (theEvent);
5791 - (void)rightMouseDown: (NSEvent *)theEvent
5793   NSTRACE (rightMouseDown);
5794   [self mouseDown: theEvent];
5798 - (void)otherMouseDown: (NSEvent *)theEvent
5800   NSTRACE (otherMouseDown);
5801   [self mouseDown: theEvent];
5805 - (void)mouseUp: (NSEvent *)theEvent
5807   NSTRACE (mouseUp);
5808   [self mouseDown: theEvent];
5812 - (void)rightMouseUp: (NSEvent *)theEvent
5814   NSTRACE (rightMouseUp);
5815   [self mouseDown: theEvent];
5819 - (void)otherMouseUp: (NSEvent *)theEvent
5821   NSTRACE (otherMouseUp);
5822   [self mouseDown: theEvent];
5826 - (void) scrollWheel: (NSEvent *)theEvent
5828   NSTRACE (scrollWheel);
5829   [self mouseDown: theEvent];
5833 /* Tell emacs the mouse has moved. */
5834 - (void)mouseMoved: (NSEvent *)e
5836   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5837   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5838   Lisp_Object frame;
5839   NSPoint pt;
5841 //  NSTRACE (mouseMoved);
5843   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5844   pt = [self convertPoint: [e locationInWindow] fromView: nil];
5845   dpyinfo->last_mouse_motion_x = pt.x;
5846   dpyinfo->last_mouse_motion_y = pt.y;
5848   /* update any mouse face */
5849   if (hlinfo->mouse_face_hidden)
5850     {
5851       hlinfo->mouse_face_hidden = 0;
5852       clear_mouse_face (hlinfo);
5853     }
5855   /* tooltip handling */
5856   previous_help_echo_string = help_echo_string;
5857   help_echo_string = Qnil;
5859   if (!NILP (Vmouse_autoselect_window))
5860     {
5861       NSTRACE (mouse_autoselect_window);
5862       static Lisp_Object last_mouse_window;
5863       Lisp_Object window
5864         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5866       if (WINDOWP (window)
5867           && !EQ (window, last_mouse_window)
5868           && !EQ (window, selected_window)
5869           && (focus_follows_mouse
5870               || (EQ (XWINDOW (window)->frame,
5871                       XWINDOW (selected_window)->frame))))
5872         {
5873           NSTRACE (in_window);
5874           emacs_event->kind = SELECT_WINDOW_EVENT;
5875           emacs_event->frame_or_window = window;
5876           EV_TRAILER2 (e);
5877         }
5878       /* Remember the last window where we saw the mouse.  */
5879       last_mouse_window = window;
5880     }
5882   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5883     help_echo_string = previous_help_echo_string;
5885   XSETFRAME (frame, emacsframe);
5886   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5887     {
5888       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5889          (note_mouse_highlight), which is called through the
5890          note_mouse_movement () call above */
5891       any_help_event_p = YES;
5892       gen_help_event (help_echo_string, frame, help_echo_window,
5893                       help_echo_object, help_echo_pos);
5894     }
5896   if (emacsframe->mouse_moved && send_appdefined)
5897     ns_send_appdefined (-1);
5901 - (void)mouseDragged: (NSEvent *)e
5903   NSTRACE (mouseDragged);
5904   [self mouseMoved: e];
5908 - (void)rightMouseDragged: (NSEvent *)e
5910   NSTRACE (rightMouseDragged);
5911   [self mouseMoved: e];
5915 - (void)otherMouseDragged: (NSEvent *)e
5917   NSTRACE (otherMouseDragged);
5918   [self mouseMoved: e];
5922 - (BOOL)windowShouldClose: (id)sender
5924   NSEvent *e =[[self window] currentEvent];
5926   NSTRACE (windowShouldClose);
5927   windowClosing = YES;
5928   if (!emacs_event)
5929     return NO;
5930   emacs_event->kind = DELETE_WINDOW_EVENT;
5931   emacs_event->modifiers = 0;
5932   emacs_event->code = 0;
5933   EV_TRAILER (e);
5934   /* Don't close this window, let this be done from lisp code.  */
5935   return NO;
5938 - (void) updateFrameSize: (BOOL) delay;
5940   NSWindow *window = [self window];
5941   NSRect wr = [window frame];
5942   int extra = 0;
5943   int oldc = cols, oldr = rows;
5944   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5945   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5946   int neww, newh;
5948   NSTRACE (updateFrameSize);
5949   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5951   if (! [self isFullscreen])
5952     {
5953 #ifdef NS_IMPL_GNUSTEP
5954       // GNUstep does not always update the tool bar height.  Force it.
5955       if (toolbar && [toolbar isVisible])
5956           update_frame_tool_bar (emacsframe);
5957 #endif
5959       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5960         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5961     }
5963   if (wait_for_tool_bar)
5964     {
5965       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5966         return;
5967       wait_for_tool_bar = NO;
5968     }
5970   neww = (int)wr.size.width - emacsframe->border_width;
5971   newh = (int)wr.size.height - extra;
5973   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5974   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5976   if (cols < MINWIDTH)
5977     cols = MINWIDTH;
5979   if (rows < MINHEIGHT)
5980     rows = MINHEIGHT;
5982   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5983     {
5984       NSView *view = FRAME_NS_VIEW (emacsframe);
5985       NSWindow *win = [view window];
5986       NSSize sz = [win resizeIncrements];
5988       change_frame_size (emacsframe,
5989                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5990                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5991                          0, delay, 0, 1);
5992       SET_FRAME_GARBAGED (emacsframe);
5993       cancel_mouse_face (emacsframe);
5995       // Did resize increments change because of a font change?
5996       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5997           sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5998           (frame_resize_pixelwise && sz.width != 1))
5999         {
6000           sz.width = frame_resize_pixelwise
6001             ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
6002           sz.height = frame_resize_pixelwise
6003             ? 1 : FRAME_LINE_HEIGHT (emacsframe);
6004           [win setResizeIncrements: sz];
6006           NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6007         }
6009       [view setFrame: NSMakeRect (0, 0, neww, newh)];
6010       [self windowDidMove:nil];   // Update top/left.
6011     }
6014 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6015 /* normalize frame to gridded text size */
6017   int extra = 0;
6019   NSTRACE (windowWillResize);
6020   NSTRACE_SIZE ("Original size", frameSize);
6021 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
6023   if (fs_state == FULLSCREEN_MAXIMIZED
6024       && (maximized_width != (int)frameSize.width
6025           || maximized_height != (int)frameSize.height))
6026     [self setFSValue: FULLSCREEN_NONE];
6027   else if (fs_state == FULLSCREEN_WIDTH
6028            && maximized_width != (int)frameSize.width)
6029     [self setFSValue: FULLSCREEN_NONE];
6030   else if (fs_state == FULLSCREEN_HEIGHT
6031            && maximized_height != (int)frameSize.height)
6032     [self setFSValue: FULLSCREEN_NONE];
6033   if (fs_state == FULLSCREEN_NONE)
6034     maximized_width = maximized_height = -1;
6036   if (! [self isFullscreen])
6037     {
6038       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6039         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6040     }
6042   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6043   if (cols < MINWIDTH)
6044     cols = MINWIDTH;
6046   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6047                                            frameSize.height - extra);
6048   if (rows < MINHEIGHT)
6049     rows = MINHEIGHT;
6050 #ifdef NS_IMPL_COCOA
6051   {
6052     /* this sets window title to have size in it; the wm does this under GS */
6053     NSRect r = [[self window] frame];
6054     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6055       {
6056         if (old_title != 0)
6057           {
6058             xfree (old_title);
6059             old_title = 0;
6060           }
6061       }
6062     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6063       {
6064         char *size_title;
6065         NSWindow *window = [self window];
6066         if (old_title == 0)
6067           {
6068             char *t = strdup ([[[self window] title] UTF8String]);
6069             char *pos = strstr (t, "  â€”  ");
6070             if (pos)
6071               *pos = '\0';
6072             old_title = t;
6073           }
6074         size_title = xmalloc (strlen (old_title) + 40);
6075         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6076         [window setTitle: [NSString stringWithUTF8String: size_title]];
6077         [window display];
6078         xfree (size_title);
6079       }
6080   }
6081 #endif /* NS_IMPL_COCOA */
6082 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
6084   return frameSize;
6088 - (void)windowDidResize: (NSNotification *)notification
6090   if (! [self fsIsNative])
6091     {
6092       NSWindow *theWindow = [notification object];
6093       /* We can get notification on the non-FS window when in
6094          fullscreen mode.  */
6095       if ([self window] != theWindow) return;
6096     }
6098 #ifdef NS_IMPL_GNUSTEP
6099   NSWindow *theWindow = [notification object];
6101    /* In GNUstep, at least currently, it's possible to get a didResize
6102       without getting a willResize.. therefore we need to act as if we got
6103       the willResize now */
6104   NSSize sz = [theWindow frame].size;
6105   sz = [self windowWillResize: theWindow toSize: sz];
6106 #endif /* NS_IMPL_GNUSTEP */
6108   NSTRACE (windowDidResize);
6109 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6111 if (cols > 0 && rows > 0)
6112     {
6113       [self updateFrameSize: YES];
6114     }
6116   ns_send_appdefined (-1);
6119 #ifdef NS_IMPL_COCOA
6120 - (void)viewDidEndLiveResize
6122   [super viewDidEndLiveResize];
6123   if (old_title != 0)
6124     {
6125       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6126       xfree (old_title);
6127       old_title = 0;
6128     }
6129   maximizing_resize = NO;
6131 #endif /* NS_IMPL_COCOA */
6134 - (void)windowDidBecomeKey: (NSNotification *)notification
6135 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6137   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6138   struct frame *old_focus = dpyinfo->x_focus_frame;
6140   NSTRACE (windowDidBecomeKey);
6142   if (emacsframe != old_focus)
6143     dpyinfo->x_focus_frame = emacsframe;
6145   ns_frame_rehighlight (emacsframe);
6147   if (emacs_event)
6148     {
6149       emacs_event->kind = FOCUS_IN_EVENT;
6150       EV_TRAILER ((id)nil);
6151     }
6155 - (void)windowDidResignKey: (NSNotification *)notification
6156 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6158   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6159   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6160   NSTRACE (windowDidResignKey);
6162   if (is_focus_frame)
6163     dpyinfo->x_focus_frame = 0;
6165   emacsframe->mouse_moved = 0;
6166   ns_frame_rehighlight (emacsframe);
6168   /* FIXME: for some reason needed on second and subsequent clicks away
6169             from sole-frame Emacs to get hollow box to show */
6170   if (!windowClosing && [[self window] isVisible] == YES)
6171     {
6172       x_update_cursor (emacsframe, 1);
6173       x_set_frame_alpha (emacsframe);
6174     }
6176   if (any_help_event_p)
6177     {
6178       Lisp_Object frame;
6179       XSETFRAME (frame, emacsframe);
6180       help_echo_string = Qnil;
6181       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6182     }
6184   if (emacs_event && is_focus_frame)
6185     {
6186       [self deleteWorkingText];
6187       emacs_event->kind = FOCUS_OUT_EVENT;
6188       EV_TRAILER ((id)nil);
6189     }
6193 - (void)windowWillMiniaturize: sender
6195   NSTRACE (windowWillMiniaturize);
6199 - (BOOL)isFlipped
6201   return YES;
6205 - (BOOL)isOpaque
6207   return NO;
6211 - initFrameFromEmacs: (struct frame *)f
6213   NSRect r, wr;
6214   Lisp_Object tem;
6215   NSWindow *win;
6216   NSSize sz;
6217   NSColor *col;
6218   NSString *name;
6220   NSTRACE (initFrameFromEmacs);
6222   windowClosing = NO;
6223   processingCompose = NO;
6224   scrollbarsNeedingUpdate = 0;
6225   fs_state = FULLSCREEN_NONE;
6226   fs_before_fs = next_maximized = -1;
6227 #ifdef HAVE_NATIVE_FS
6228   fs_is_native = ns_use_native_fullscreen;
6229 #else
6230   fs_is_native = NO;
6231 #endif
6232   maximized_width = maximized_height = -1;
6233   nonfs_window = nil;
6235 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6237   ns_userRect = NSMakeRect (0, 0, 0, 0);
6238   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6239                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6240   [self initWithFrame: r];
6241   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6243   FRAME_NS_VIEW (f) = self;
6244   emacsframe = f;
6245 #ifdef NS_IMPL_COCOA
6246   old_title = 0;
6247   maximizing_resize = NO;
6248 #endif
6250   win = [[EmacsWindow alloc]
6251             initWithContentRect: r
6252                       styleMask: (NSResizableWindowMask |
6253 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6254                                   NSTitledWindowMask |
6255 #endif
6256                                   NSMiniaturizableWindowMask |
6257                                   NSClosableWindowMask)
6258                         backing: NSBackingStoreBuffered
6259                           defer: YES];
6261 #ifdef HAVE_NATIVE_FS
6262     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6263 #endif
6265   wr = [win frame];
6266   bwidth = f->border_width = wr.size.width - r.size.width;
6267   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6269   [win setAcceptsMouseMovedEvents: YES];
6270   [win setDelegate: self];
6271 #if !defined (NS_IMPL_COCOA) || \
6272   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6273   [win useOptimizedDrawing: YES];
6274 #endif
6275   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6276   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6277   [win setResizeIncrements: sz];
6279   [[win contentView] addSubview: self];
6281   if (ns_drag_types)
6282     [self registerForDraggedTypes: ns_drag_types];
6284   tem = f->name;
6285   name = [NSString stringWithUTF8String:
6286                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6287   [win setTitle: name];
6289   /* toolbar support */
6290   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6291                          [NSString stringWithFormat: @"Emacs Frame %d",
6292                                    ns_window_num]];
6293   [win setToolbar: toolbar];
6294   [toolbar setVisible: NO];
6296   /* Don't set frame garbaged until tool bar is up to date?
6297      This avoids an extra clear and redraw (flicker) at frame creation.  */
6298   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6299   else wait_for_tool_bar = NO;
6302 #ifdef NS_IMPL_COCOA
6303   {
6304     NSButton *toggleButton;
6305   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6306   [toggleButton setTarget: self];
6307   [toggleButton setAction: @selector (toggleToolbar: )];
6308   }
6309 #endif
6310   FRAME_TOOLBAR_HEIGHT (f) = 0;
6312   tem = f->icon_name;
6313   if (!NILP (tem))
6314     [win setMiniwindowTitle:
6315            [NSString stringWithUTF8String: SSDATA (tem)]];
6317   {
6318     NSScreen *screen = [win screen];
6320     if (screen != 0)
6321       [win setFrameTopLeftPoint: NSMakePoint
6322            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6323             IN_BOUND (-SCREENMAX,
6324                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6325   }
6327   [win makeFirstResponder: self];
6329   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6330                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6331   [win setBackgroundColor: col];
6332   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6333     [win setOpaque: NO];
6335 #if !defined (NS_IMPL_COCOA) || \
6336   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6337   [self allocateGState];
6338 #endif
6339   [NSApp registerServicesMenuSendTypes: ns_send_types
6340                            returnTypes: nil];
6342   ns_window_num++;
6343   return self;
6347 - (void)windowDidMove: sender
6349   NSWindow *win = [self window];
6350   NSRect r = [win frame];
6351   NSArray *screens = [NSScreen screens];
6352   NSScreen *screen = [screens objectAtIndex: 0];
6354   NSTRACE (windowDidMove);
6356   if (!emacsframe->output_data.ns)
6357     return;
6358   if (screen != nil)
6359     {
6360       emacsframe->left_pos = r.origin.x;
6361       emacsframe->top_pos =
6362         [screen frame].size.height - (r.origin.y + r.size.height);
6363     }
6367 /* Called AFTER method below, but before our windowWillResize call there leads
6368    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6369    location so set_window_size moves the frame. */
6370 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6372   emacsframe->output_data.ns->zooming = 1;
6373   return YES;
6377 /* Override to do something slightly nonstandard, but nice.  First click on
6378    zoom button will zoom vertically.  Second will zoom completely.  Third
6379    returns to original. */
6380 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6381                         defaultFrame:(NSRect)defaultFrame
6383   NSRect result = [sender frame];
6385   NSTRACE (windowWillUseStandardFrame);
6387   if (fs_before_fs != -1) /* Entering fullscreen */
6388       {
6389         result = defaultFrame;
6390       }
6391   else if (next_maximized == FULLSCREEN_HEIGHT
6392       || (next_maximized == -1
6393           && abs ((int)(defaultFrame.size.height - result.size.height))
6394           > FRAME_LINE_HEIGHT (emacsframe)))
6395     {
6396       /* first click */
6397       ns_userRect = result;
6398       maximized_height = result.size.height = defaultFrame.size.height;
6399       maximized_width = -1;
6400       result.origin.y = defaultFrame.origin.y;
6401       [self setFSValue: FULLSCREEN_HEIGHT];
6402 #ifdef NS_IMPL_COCOA
6403       maximizing_resize = YES;
6404 #endif
6405     }
6406   else if (next_maximized == FULLSCREEN_WIDTH)
6407     {
6408       ns_userRect = result;
6409       maximized_width = result.size.width = defaultFrame.size.width;
6410       maximized_height = -1;
6411       result.origin.x = defaultFrame.origin.x;
6412       [self setFSValue: FULLSCREEN_WIDTH];
6413     }
6414   else if (next_maximized == FULLSCREEN_MAXIMIZED
6415            || (next_maximized == -1
6416                && abs ((int)(defaultFrame.size.width - result.size.width))
6417                > FRAME_COLUMN_WIDTH (emacsframe)))
6418     {
6419       result = defaultFrame;  /* second click */
6420       maximized_width = result.size.width;
6421       maximized_height = result.size.height;
6422       [self setFSValue: FULLSCREEN_MAXIMIZED];
6423 #ifdef NS_IMPL_COCOA
6424       maximizing_resize = YES;
6425 #endif
6426     }
6427   else
6428     {
6429       /* restore */
6430       result = ns_userRect.size.height ? ns_userRect : result;
6431       ns_userRect = NSMakeRect (0, 0, 0, 0);
6432 #ifdef NS_IMPL_COCOA
6433       maximizing_resize = fs_state != FULLSCREEN_NONE;
6434 #endif
6435       [self setFSValue: FULLSCREEN_NONE];
6436       maximized_width = maximized_height = -1;
6437     }
6439   if (fs_before_fs == -1) next_maximized = -1;
6440   [self windowWillResize: sender toSize: result.size];
6441   return result;
6445 - (void)windowDidDeminiaturize: sender
6447   NSTRACE (windowDidDeminiaturize);
6448   if (!emacsframe->output_data.ns)
6449     return;
6451   SET_FRAME_ICONIFIED (emacsframe, 0);
6452   SET_FRAME_VISIBLE (emacsframe, 1);
6453   windows_or_buffers_changed = 63;
6455   if (emacs_event)
6456     {
6457       emacs_event->kind = DEICONIFY_EVENT;
6458       EV_TRAILER ((id)nil);
6459     }
6463 - (void)windowDidExpose: sender
6465   NSTRACE (windowDidExpose);
6466   if (!emacsframe->output_data.ns)
6467     return;
6469   SET_FRAME_VISIBLE (emacsframe, 1);
6470   SET_FRAME_GARBAGED (emacsframe);
6472   if (send_appdefined)
6473     ns_send_appdefined (-1);
6477 - (void)windowDidMiniaturize: sender
6479   NSTRACE (windowDidMiniaturize);
6480   if (!emacsframe->output_data.ns)
6481     return;
6483   SET_FRAME_ICONIFIED (emacsframe, 1);
6484   SET_FRAME_VISIBLE (emacsframe, 0);
6486   if (emacs_event)
6487     {
6488       emacs_event->kind = ICONIFY_EVENT;
6489       EV_TRAILER ((id)nil);
6490     }
6493 #ifdef HAVE_NATIVE_FS
6494 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6495       willUseFullScreenPresentationOptions:
6496   (NSApplicationPresentationOptions)proposedOptions
6498   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6500 #endif
6502 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6504   fs_before_fs = fs_state;
6507 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6509   [self setFSValue: FULLSCREEN_BOTH];
6510   if (! [self fsIsNative])
6511     {
6512       [self windowDidBecomeKey:notification];
6513       [nonfs_window orderOut:self];
6514     }
6515   else
6516     {
6517       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6518 #ifdef NS_IMPL_COCOA
6519 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6520       unsigned val = (unsigned)[NSApp presentationOptions];
6522       // OSX 10.7 bug fix, the menu won't appear without this.
6523       // val is non-zero on other OSX versions.
6524       if (val == 0)
6525         {
6526           NSApplicationPresentationOptions options
6527             = NSApplicationPresentationAutoHideDock
6528             | NSApplicationPresentationAutoHideMenuBar
6529             | NSApplicationPresentationFullScreen
6530             | NSApplicationPresentationAutoHideToolbar;
6532           [NSApp setPresentationOptions: options];
6533         }
6534 #endif
6535 #endif
6536       [toolbar setVisible:tbar_visible];
6537     }
6540 - (void)windowWillExitFullScreen:(NSNotification *)notification
6542   if (next_maximized != -1)
6543     fs_before_fs = next_maximized;
6546 - (void)windowDidExitFullScreen:(NSNotification *)notification
6548   [self setFSValue: fs_before_fs];
6549   fs_before_fs = -1;
6550 #ifdef HAVE_NATIVE_FS
6551   [self updateCollectionBehavior];
6552 #endif
6553   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6554     {
6555       [toolbar setVisible:YES];
6556       update_frame_tool_bar (emacsframe);
6557       [self updateFrameSize:YES];
6558       [[self window] display];
6559     }
6560   else
6561     [toolbar setVisible:NO];
6563   if (next_maximized != -1)
6564     [[self window] performZoom:self];
6567 - (BOOL)fsIsNative
6569   return fs_is_native;
6572 - (BOOL)isFullscreen
6574   if (! fs_is_native) return nonfs_window != nil;
6575 #ifdef HAVE_NATIVE_FS
6576   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6577 #else
6578   return NO;
6579 #endif
6582 #ifdef HAVE_NATIVE_FS
6583 - (void)updateCollectionBehavior
6585   if (! [self isFullscreen])
6586     {
6587       NSWindow *win = [self window];
6588       NSWindowCollectionBehavior b = [win collectionBehavior];
6589       if (ns_use_native_fullscreen)
6590         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6591       else
6592         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6594       [win setCollectionBehavior: b];
6595       fs_is_native = ns_use_native_fullscreen;
6596     }
6598 #endif
6600 - (void)toggleFullScreen: (id)sender
6602   NSWindow *w, *fw;
6603   BOOL onFirstScreen;
6604   struct frame *f;
6605   NSSize sz;
6606   NSRect r, wr;
6607   NSColor *col;
6609   if (fs_is_native)
6610     {
6611 #ifdef HAVE_NATIVE_FS
6612       [[self window] toggleFullScreen:sender];
6613 #endif
6614       return;
6615     }
6617   w = [self window];
6618   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6619   f = emacsframe;
6620   wr = [w frame];
6621   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6622                                  (FRAME_DEFAULT_FACE (f)),
6623                                  f);
6625   sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6626   sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6628   if (fs_state != FULLSCREEN_BOTH)
6629     {
6630       NSScreen *screen = [w screen];
6632 #if defined (NS_IMPL_COCOA) && \
6633   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6634       /* Hide ghost menu bar on secondary monitor? */
6635       if (! onFirstScreen)
6636         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6637 #endif
6638       /* Hide dock and menubar if we are on the primary screen.  */
6639       if (onFirstScreen)
6640         {
6641 #ifdef NS_IMPL_COCOA
6642           NSApplicationPresentationOptions options
6643             = NSApplicationPresentationAutoHideDock
6644             | NSApplicationPresentationAutoHideMenuBar;
6646           [NSApp setPresentationOptions: options];
6647 #else
6648           [NSMenu setMenuBarVisible:NO];
6649 #endif
6650         }
6652       fw = [[EmacsFSWindow alloc]
6653                        initWithContentRect:[w contentRectForFrameRect:wr]
6654                                  styleMask:NSBorderlessWindowMask
6655                                    backing:NSBackingStoreBuffered
6656                                      defer:YES
6657                                     screen:screen];
6659       [fw setContentView:[w contentView]];
6660       [fw setTitle:[w title]];
6661       [fw setDelegate:self];
6662       [fw setAcceptsMouseMovedEvents: YES];
6663 #if !defined (NS_IMPL_COCOA) || \
6664   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6665       [fw useOptimizedDrawing: YES];
6666 #endif
6667       [fw setResizeIncrements: sz];
6668       [fw setBackgroundColor: col];
6669       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6670         [fw setOpaque: NO];
6672       f->border_width = 0;
6673       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6674       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6675       FRAME_TOOLBAR_HEIGHT (f) = 0;
6677       nonfs_window = w;
6679       [self windowWillEnterFullScreen:nil];
6680       [fw makeKeyAndOrderFront:NSApp];
6681       [fw makeFirstResponder:self];
6682       [w orderOut:self];
6683       r = [fw frameRectForContentRect:[screen frame]];
6684       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6685       [self windowDidEnterFullScreen:nil];
6686       [fw display];
6687     }
6688   else
6689     {
6690       fw = w;
6691       w = nonfs_window;
6692       nonfs_window = nil;
6694       if (onFirstScreen)
6695         {
6696 #ifdef NS_IMPL_COCOA
6697           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6698 #else
6699           [NSMenu setMenuBarVisible:YES];
6700 #endif
6701         }
6703       [w setContentView:[fw contentView]];
6704       [w setResizeIncrements: sz];
6705       [w setBackgroundColor: col];
6706       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6707         [w setOpaque: NO];
6709       f->border_width = bwidth;
6710       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6711       if (FRAME_EXTERNAL_TOOL_BAR (f))
6712         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6714       [self windowWillExitFullScreen:nil];
6715       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6716       [fw close];
6717       [w makeKeyAndOrderFront:NSApp];
6718       [self windowDidExitFullScreen:nil];
6719       [self updateFrameSize:YES];
6720     }
6723 - (void)handleFS
6725   if (fs_state != emacsframe->want_fullscreen)
6726     {
6727       NSSize sz;
6728       sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
6729       sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (emacsframe);
6730       [[self window] setResizeIncrements:sz];
6732       if (fs_state == FULLSCREEN_BOTH)
6733         {
6734           [self toggleFullScreen:self];
6735         }
6737       switch (emacsframe->want_fullscreen)
6738         {
6739         case FULLSCREEN_BOTH:
6740           [self toggleFullScreen:self];
6741           break;
6742         case FULLSCREEN_WIDTH:
6743           next_maximized = FULLSCREEN_WIDTH;
6744           if (fs_state != FULLSCREEN_BOTH)
6745             [[self window] performZoom:self];
6746           break;
6747         case FULLSCREEN_HEIGHT:
6748           next_maximized = FULLSCREEN_HEIGHT;
6749           if (fs_state != FULLSCREEN_BOTH)
6750             [[self window] performZoom:self];
6751           break;
6752         case FULLSCREEN_MAXIMIZED:
6753           next_maximized = FULLSCREEN_MAXIMIZED;
6754           if (fs_state != FULLSCREEN_BOTH)
6755             [[self window] performZoom:self];
6756           break;
6757         case FULLSCREEN_NONE:
6758           if (fs_state != FULLSCREEN_BOTH)
6759             {
6760               next_maximized = FULLSCREEN_NONE;
6761               [[self window] performZoom:self];
6762             }
6763           break;
6764         }
6766       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6767     }
6771 - (void) setFSValue: (int)value
6773   Lisp_Object lval = Qnil;
6774   switch (value)
6775     {
6776     case FULLSCREEN_BOTH:
6777       lval = Qfullboth;
6778       break;
6779     case FULLSCREEN_WIDTH:
6780       lval = Qfullwidth;
6781       break;
6782     case FULLSCREEN_HEIGHT:
6783       lval = Qfullheight;
6784       break;
6785     case FULLSCREEN_MAXIMIZED:
6786       lval = Qmaximized;
6787       break;
6788     }
6789   store_frame_param (emacsframe, Qfullscreen, lval);
6790   fs_state = value;
6793 - (void)mouseEntered: (NSEvent *)theEvent
6795   NSTRACE (mouseEntered);
6796   if (emacsframe)
6797     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6798       = EV_TIMESTAMP (theEvent);
6802 - (void)mouseExited: (NSEvent *)theEvent
6804   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6806   NSTRACE (mouseExited);
6808   if (!hlinfo)
6809     return;
6811   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6812     = EV_TIMESTAMP (theEvent);
6814   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6815     {
6816       clear_mouse_face (hlinfo);
6817       hlinfo->mouse_face_mouse_frame = 0;
6818     }
6822 - menuDown: sender
6824   NSTRACE (menuDown);
6825   if (context_menu_value == -1)
6826     context_menu_value = [sender tag];
6827   else
6828     {
6829       NSInteger tag = [sender tag];
6830       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6831                                     emacsframe->menu_bar_vector,
6832                                     (void *)tag);
6833     }
6835   ns_send_appdefined (-1);
6836   return self;
6840 - (EmacsToolbar *)toolbar
6842   return toolbar;
6846 /* this gets called on toolbar button click */
6847 - toolbarClicked: (id)item
6849   NSEvent *theEvent;
6850   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6852   NSTRACE (toolbarClicked);
6854   if (!emacs_event)
6855     return self;
6857   /* send first event (for some reason two needed) */
6858   theEvent = [[self window] currentEvent];
6859   emacs_event->kind = TOOL_BAR_EVENT;
6860   XSETFRAME (emacs_event->arg, emacsframe);
6861   EV_TRAILER (theEvent);
6863   emacs_event->kind = TOOL_BAR_EVENT;
6864 /*   XSETINT (emacs_event->code, 0); */
6865   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6866                            idx + TOOL_BAR_ITEM_KEY);
6867   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6868   EV_TRAILER (theEvent);
6869   return self;
6873 - toggleToolbar: (id)sender
6875   if (!emacs_event)
6876     return self;
6878   emacs_event->kind = NS_NONKEY_EVENT;
6879   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6880   EV_TRAILER ((id)nil);
6881   return self;
6885 - (void)drawRect: (NSRect)rect
6887   int x = NSMinX (rect), y = NSMinY (rect);
6888   int width = NSWidth (rect), height = NSHeight (rect);
6890   NSTRACE (drawRect);
6892   if (!emacsframe || !emacsframe->output_data.ns)
6893     return;
6895   ns_clear_frame_area (emacsframe, x, y, width, height);
6896   block_input ();
6897   expose_frame (emacsframe, x, y, width, height);
6898   unblock_input ();
6900   /*
6901     drawRect: may be called (at least in OS X 10.5) for invisible
6902     views as well for some reason.  Thus, do not infer visibility
6903     here.
6905     emacsframe->async_visible = 1;
6906     emacsframe->async_iconified = 0;
6907   */
6911 /* NSDraggingDestination protocol methods.  Actually this is not really a
6912    protocol, but a category of Object.  O well...  */
6914 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
6916   NSTRACE (draggingEntered);
6917   return NSDragOperationGeneric;
6921 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6923   return YES;
6927 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6929   id pb;
6930   int x, y;
6931   NSString *type;
6932   NSEvent *theEvent = [[self window] currentEvent];
6933   NSPoint position;
6934   NSDragOperation op = [sender draggingSourceOperationMask];
6935   int modifiers = 0;
6937   NSTRACE (performDragOperation);
6939   if (!emacs_event)
6940     return NO;
6942   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6943   x = lrint (position.x);  y = lrint (position.y);
6945   pb = [sender draggingPasteboard];
6946   type = [pb availableTypeFromArray: ns_drag_types];
6948   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6949       // URL drags contain all operations (0xf), don't allow all to be set.
6950       (op & 0xf) != 0xf)
6951     {
6952       if (op & NSDragOperationLink)
6953         modifiers |= NSControlKeyMask;
6954       if (op & NSDragOperationCopy)
6955         modifiers |= NSAlternateKeyMask;
6956       if (op & NSDragOperationGeneric)
6957         modifiers |= NSCommandKeyMask;
6958     }
6960   modifiers = EV_MODIFIERS2 (modifiers);
6961   if (type == 0)
6962     {
6963       return NO;
6964     }
6965   else if ([type isEqualToString: NSFilenamesPboardType])
6966     {
6967       NSArray *files;
6968       NSEnumerator *fenum;
6969       NSString *file;
6971       if (!(files = [pb propertyListForType: type]))
6972         return NO;
6974       fenum = [files objectEnumerator];
6975       while ( (file = [fenum nextObject]) )
6976         {
6977           emacs_event->kind = DRAG_N_DROP_EVENT;
6978           XSETINT (emacs_event->x, x);
6979           XSETINT (emacs_event->y, y);
6980           ns_input_file = append2 (ns_input_file,
6981                                    build_string ([file UTF8String]));
6982           emacs_event->modifiers = modifiers;
6983           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
6984           EV_TRAILER (theEvent);
6985         }
6986       return YES;
6987     }
6988   else if ([type isEqualToString: NSURLPboardType])
6989     {
6990       NSURL *url = [NSURL URLFromPasteboard: pb];
6991       if (url == nil) return NO;
6993       emacs_event->kind = DRAG_N_DROP_EVENT;
6994       XSETINT (emacs_event->x, x);
6995       XSETINT (emacs_event->y, y);
6996       emacs_event->modifiers = modifiers;
6997       emacs_event->arg =  list2 (Qurl,
6998                                  build_string ([[url absoluteString]
6999                                                  UTF8String]));
7000       EV_TRAILER (theEvent);
7002       if ([url isFileURL] != NO)
7003         {
7004           NSString *file = [url path];
7005           ns_input_file = append2 (ns_input_file,
7006                                    build_string ([file UTF8String]));
7007         }
7008       return YES;
7009     }
7010   else if ([type isEqualToString: NSStringPboardType]
7011            || [type isEqualToString: NSTabularTextPboardType])
7012     {
7013       NSString *data;
7015       if (! (data = [pb stringForType: type]))
7016         return NO;
7018       emacs_event->kind = DRAG_N_DROP_EVENT;
7019       XSETINT (emacs_event->x, x);
7020       XSETINT (emacs_event->y, y);
7021       emacs_event->modifiers = modifiers;
7022       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7023       EV_TRAILER (theEvent);
7024       return YES;
7025     }
7026   else
7027     {
7028       fprintf (stderr, "Invalid data type in dragging pasteboard");
7029       return NO;
7030     }
7034 - (id) validRequestorForSendType: (NSString *)typeSent
7035                       returnType: (NSString *)typeReturned
7037   NSTRACE (validRequestorForSendType);
7038   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7039       && typeReturned == nil)
7040     {
7041       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7042         return self;
7043     }
7045   return [super validRequestorForSendType: typeSent
7046                                returnType: typeReturned];
7050 /* The next two methods are part of NSServicesRequests informal protocol,
7051    supposedly called when a services menu item is chosen from this app.
7052    But this should not happen because we override the services menu with our
7053    own entries which call ns-perform-service.
7054    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7055    So let's at least stub them out until further investigation can be done. */
7057 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7059   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7060      be written into the buffer in place of the existing selection..
7061      ordinary service calls go through functions defined in ns-win.el */
7062   return NO;
7065 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7067   NSArray *typesDeclared;
7068   Lisp_Object val;
7070   /* We only support NSStringPboardType */
7071   if ([types containsObject:NSStringPboardType] == NO) {
7072     return NO;
7073   }
7075   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7076   if (CONSP (val) && SYMBOLP (XCAR (val)))
7077     {
7078       val = XCDR (val);
7079       if (CONSP (val) && NILP (XCDR (val)))
7080         val = XCAR (val);
7081     }
7082   if (! STRINGP (val))
7083     return NO;
7085   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7086   [pb declareTypes:typesDeclared owner:nil];
7087   ns_string_to_pasteboard (pb, val);
7088   return YES;
7092 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7093    (gives a miniaturized version of the window); currently we use the latter for
7094    frames whose active buffer doesn't correspond to any file
7095    (e.g., '*scratch*') */
7096 - setMiniwindowImage: (BOOL) setMini
7098   id image = [[self window] miniwindowImage];
7099   NSTRACE (setMiniwindowImage);
7101   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7102      about "AppleDockIconEnabled" notwithstanding, however the set message
7103      below has its effect nonetheless. */
7104   if (image != emacsframe->output_data.ns->miniimage)
7105     {
7106       if (image && [image isKindOfClass: [EmacsImage class]])
7107         [image release];
7108       [[self window] setMiniwindowImage:
7109                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7110     }
7112   return self;
7116 - (void) setRows: (int) r andColumns: (int) c
7118   rows = r;
7119   cols = c;
7122 @end  /* EmacsView */
7126 /* ==========================================================================
7128     EmacsWindow implementation
7130    ========================================================================== */
7132 @implementation EmacsWindow
7134 #ifdef NS_IMPL_COCOA
7135 - (id)accessibilityAttributeValue:(NSString *)attribute
7137   Lisp_Object str = Qnil;
7138   struct frame *f = SELECTED_FRAME ();
7139   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7141   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7142     return NSAccessibilityTextFieldRole;
7144   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7145       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7146     {
7147       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7148     }
7149   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7150     {
7151       if (! NILP (BVAR (curbuf, mark_active)))
7152           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7154       if (NILP (str))
7155         {
7156           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7157           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7158           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7160           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7161             str = make_uninit_multibyte_string (range, byte_range);
7162           else
7163             str = make_uninit_string (range);
7164           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7165              Is this a problem?  */
7166           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7167         }
7168     }
7171   if (! NILP (str))
7172     {
7173       if (CONSP (str) && SYMBOLP (XCAR (str)))
7174         {
7175           str = XCDR (str);
7176           if (CONSP (str) && NILP (XCDR (str)))
7177             str = XCAR (str);
7178         }
7179       if (STRINGP (str))
7180         {
7181           const char *utfStr = SSDATA (str);
7182           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7183           return nsStr;
7184         }
7185     }
7187   return [super accessibilityAttributeValue:attribute];
7189 #endif /* NS_IMPL_COCOA */
7191 /* If we have multiple monitors, one above the other, we don't want to
7192    restrict the height to just one monitor.  So we override this.  */
7193 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7195   /* When making the frame visible for the first time or if there is just
7196      one screen, we want to constrain.  Other times not.  */
7197   NSArray *screens = [NSScreen screens];
7198   NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7199   NSTRACE (constrainFrameRect);
7200   NSTRACE_RECT ("input", frameRect);
7202   if (ns_menu_bar_should_be_hidden ())
7203     return frameRect;
7205   if (nr_screens == 1)
7206     return [super constrainFrameRect:frameRect toScreen:screen];
7208 #ifdef NS_IMPL_COCOA
7209 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7210   // If separate spaces is on, it is like each screen is independent.  There is
7211   // no spanning of frames across screens.
7212   if ([NSScreen screensHaveSeparateSpaces])
7213     return [super constrainFrameRect:frameRect toScreen:screen];
7214 #endif
7215 #endif
7217   for (i = 0; i < nr_screens; ++i)
7218     {
7219       NSScreen *s = [screens objectAtIndex: i];
7220       NSRect scrrect = [s frame];
7221       NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7223       if (intersect.size.width > 0 || intersect.size.height > 0)
7224         ++nr_eff_screens;
7225     }
7227   if (nr_eff_screens == 1)
7228     return [super constrainFrameRect:frameRect toScreen:screen];
7230   /* The default implementation does two things 1) ensure that the top
7231      of the rectangle is below the menu bar (or below the top of the
7232      screen) and 2) resizes windows larger than the screen. As we
7233      don't want the latter, a smaller rectangle is used. */
7234 #define FAKE_HEIGHT 64
7235   float old_top = frameRect.origin.y + frameRect.size.height;
7236   NSRect r;
7237   r.size.height = FAKE_HEIGHT;
7238   r.size.width = frameRect.size.width;
7239   r.origin.x = frameRect.origin.x;
7240   r.origin.y = old_top - FAKE_HEIGHT;
7242   NSTRACE_RECT ("input to super", r);
7244   r = [super constrainFrameRect:r toScreen:screen];
7246   NSTRACE_RECT ("output from super", r);
7248   float new_top = r.origin.y + FAKE_HEIGHT;
7249   if (new_top < old_top)
7250   {
7251     frameRect.origin.y = new_top - frameRect.size.height;
7252   }
7254   NSTRACE_RECT ("output", frameRect);
7256   return frameRect;
7257 #undef FAKE_HEIGHT
7260 @end /* EmacsWindow */
7263 @implementation EmacsFSWindow
7265 - (BOOL)canBecomeKeyWindow
7267   return YES;
7270 - (BOOL)canBecomeMainWindow
7272   return YES;
7275 @end
7277 /* ==========================================================================
7279     EmacsScroller implementation
7281    ========================================================================== */
7284 @implementation EmacsScroller
7286 /* for repeat button push */
7287 #define SCROLL_BAR_FIRST_DELAY 0.5
7288 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7290 + (CGFloat) scrollerWidth
7292   /* TODO: if we want to allow variable widths, this is the place to do it,
7293            however neither GNUstep nor Cocoa support it very well */
7294   CGFloat r;
7295 #if !defined (NS_IMPL_COCOA) || \
7296   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7297   r = [NSScroller scrollerWidth];
7298 #else
7299   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7300                                 scrollerStyle: NSScrollerStyleLegacy];
7301 #endif
7302   return r;
7306 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7308   NSTRACE (EmacsScroller_initFrame);
7310   r.size.width = [EmacsScroller scrollerWidth];
7311   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7312   [self setContinuous: YES];
7313   [self setEnabled: YES];
7315   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7316      locked against the top and bottom edges, and right edge on OS X, where
7317      scrollers are on right. */
7318 #ifdef NS_IMPL_GNUSTEP
7319   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7320 #else
7321   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7322 #endif
7324   window = XWINDOW (nwin);
7325   condemned = NO;
7326   pixel_height = NSHeight (r);
7327   if (pixel_height == 0) pixel_height = 1;
7328   min_portion = 20 / pixel_height;
7330   frame = XFRAME (window->frame);
7331   if (FRAME_LIVE_P (frame))
7332     {
7333       int i;
7334       EmacsView *view = FRAME_NS_VIEW (frame);
7335       NSView *sview = [[view window] contentView];
7336       NSArray *subs = [sview subviews];
7338       /* disable optimization stopping redraw of other scrollbars */
7339       view->scrollbarsNeedingUpdate = 0;
7340       for (i =[subs count]-1; i >= 0; i--)
7341         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7342           view->scrollbarsNeedingUpdate++;
7343       [sview addSubview: self];
7344     }
7346 /*  [self setFrame: r]; */
7348   return self;
7352 - (void)setFrame: (NSRect)newRect
7354   NSTRACE (EmacsScroller_setFrame);
7355 /*  block_input (); */
7356   pixel_height = NSHeight (newRect);
7357   if (pixel_height == 0) pixel_height = 1;
7358   min_portion = 20 / pixel_height;
7359   [super setFrame: newRect];
7360 /*  unblock_input (); */
7364 - (void)dealloc
7366   NSTRACE (EmacsScroller_dealloc);
7367   if (window)
7368     wset_vertical_scroll_bar (window, Qnil);
7369   window = 0;
7370   [super dealloc];
7374 - condemn
7376   NSTRACE (condemn);
7377   condemned =YES;
7378   return self;
7382 - reprieve
7384   NSTRACE (reprieve);
7385   condemned =NO;
7386   return self;
7390 -(bool)judge
7392   NSTRACE (judge);
7393   bool ret = condemned;
7394   if (condemned)
7395     {
7396       EmacsView *view;
7397       block_input ();
7398       /* ensure other scrollbar updates after deletion */
7399       view = (EmacsView *)FRAME_NS_VIEW (frame);
7400       if (view != nil)
7401         view->scrollbarsNeedingUpdate++;
7402       if (window)
7403         wset_vertical_scroll_bar (window, Qnil);
7404       window = 0;
7405       [self removeFromSuperview];
7406       [self release];
7407       unblock_input ();
7408     }
7409   return ret;
7413 - (void)resetCursorRects
7415   NSRect visible = [self visibleRect];
7416   NSTRACE (resetCursorRects);
7418   if (!NSIsEmptyRect (visible))
7419     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7420   [[NSCursor arrowCursor] setOnMouseEntered: YES];
7424 - (int) checkSamePosition: (int) position portion: (int) portion
7425                     whole: (int) whole
7427   return em_position ==position && em_portion ==portion && em_whole ==whole
7428     && portion != whole; /* needed for resize empty buf */
7432 - setPosition: (int)position portion: (int)portion whole: (int)whole
7434   NSTRACE (setPosition);
7436   em_position = position;
7437   em_portion = portion;
7438   em_whole = whole;
7440   if (portion >= whole)
7441     {
7442 #ifdef NS_IMPL_COCOA
7443       [self setKnobProportion: 1.0];
7444       [self setDoubleValue: 1.0];
7445 #else
7446       [self setFloatValue: 0.0 knobProportion: 1.0];
7447 #endif
7448     }
7449   else
7450     {
7451       float pos;
7452       CGFloat por;
7453       portion = max ((float)whole*min_portion/pixel_height, portion);
7454       pos = (float)position / (whole - portion);
7455       por = (CGFloat)portion/whole;
7456 #ifdef NS_IMPL_COCOA
7457       [self setKnobProportion: por];
7458       [self setDoubleValue: pos];
7459 #else
7460       [self setFloatValue: pos knobProportion: por];
7461 #endif
7462     }
7464   return self;
7467 /* set up emacs_event */
7468 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7470   Lisp_Object win;
7471   if (!emacs_event)
7472     return;
7474   emacs_event->part = last_hit_part;
7475   emacs_event->code = 0;
7476   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7477   XSETWINDOW (win, window);
7478   emacs_event->frame_or_window = win;
7479   emacs_event->timestamp = EV_TIMESTAMP (e);
7480   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7481   emacs_event->arg = Qnil;
7482   XSETINT (emacs_event->x, loc * pixel_height);
7483   XSETINT (emacs_event->y, pixel_height-20);
7485   if (q_event_ptr)
7486     {
7487       n_emacs_events_pending++;
7488       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7489     }
7490   else
7491     hold_event (emacs_event);
7492   EVENT_INIT (*emacs_event);
7493   ns_send_appdefined (-1);
7497 /* called manually thru timer to implement repeated button action w/hold-down */
7498 - repeatScroll: (NSTimer *)scrollEntry
7500   NSEvent *e = [[self window] currentEvent];
7501   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7502   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7504   /* clear timer if need be */
7505   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7506     {
7507         [scroll_repeat_entry invalidate];
7508         [scroll_repeat_entry release];
7509         scroll_repeat_entry = nil;
7511         if (inKnob)
7512           return self;
7514         scroll_repeat_entry
7515           = [[NSTimer scheduledTimerWithTimeInterval:
7516                         SCROLL_BAR_CONTINUOUS_DELAY
7517                                             target: self
7518                                           selector: @selector (repeatScroll:)
7519                                           userInfo: 0
7520                                            repeats: YES]
7521               retain];
7522     }
7524   [self sendScrollEventAtLoc: 0 fromEvent: e];
7525   return self;
7529 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7530    mouseDragged events without going into a modal loop. */
7531 - (void)mouseDown: (NSEvent *)e
7533   NSRect sr, kr;
7534   /* hitPart is only updated AFTER event is passed on */
7535   NSScrollerPart part = [self testPart: [e locationInWindow]];
7536   CGFloat inc = 0.0, loc, kloc, pos;
7537   int edge = 0;
7539   NSTRACE (EmacsScroller_mouseDown);
7541   switch (part)
7542     {
7543     case NSScrollerDecrementPage:
7544         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7545     case NSScrollerIncrementPage:
7546         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7547     case NSScrollerDecrementLine:
7548       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7549     case NSScrollerIncrementLine:
7550       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7551     case NSScrollerKnob:
7552       last_hit_part = scroll_bar_handle; break;
7553     case NSScrollerKnobSlot:  /* GNUstep-only */
7554       last_hit_part = scroll_bar_move_ratio; break;
7555     default:  /* NSScrollerNoPart? */
7556       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7557                (long) part);
7558       return;
7559     }
7561   if (inc != 0.0)
7562     {
7563       pos = 0;      /* ignored */
7565       /* set a timer to repeat, as we can't let superclass do this modally */
7566       scroll_repeat_entry
7567         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7568                                             target: self
7569                                           selector: @selector (repeatScroll:)
7570                                           userInfo: 0
7571                                            repeats: YES]
7572             retain];
7573     }
7574   else
7575     {
7576       /* handle, or on GNUstep possibly slot */
7577       NSEvent *fake_event;
7579       /* compute float loc in slot and mouse offset on knob */
7580       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7581                       toView: nil];
7582       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7583       if (loc <= 0.0)
7584         {
7585           loc = 0.0;
7586           edge = -1;
7587         }
7588       else if (loc >= NSHeight (sr))
7589         {
7590           loc = NSHeight (sr);
7591           edge = 1;
7592         }
7594       if (edge)
7595         kloc = 0.5 * edge;
7596       else
7597         {
7598           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7599                           toView: nil];
7600           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7601         }
7602       last_mouse_offset = kloc;
7604       /* if knob, tell emacs a location offset by knob pos
7605          (to indicate top of handle) */
7606       if (part == NSScrollerKnob)
7607           pos = (loc - last_mouse_offset) / NSHeight (sr);
7608       else
7609         /* else this is a slot click on GNUstep: go straight there */
7610         pos = loc / NSHeight (sr);
7612       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7613       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7614                                       location: [e locationInWindow]
7615                                  modifierFlags: [e modifierFlags]
7616                                      timestamp: [e timestamp]
7617                                   windowNumber: [e windowNumber]
7618                                        context: [e context]
7619                                    eventNumber: [e eventNumber]
7620                                     clickCount: [e clickCount]
7621                                       pressure: [e pressure]];
7622       [super mouseUp: fake_event];
7623     }
7625   if (part != NSScrollerKnob)
7626     [self sendScrollEventAtLoc: pos fromEvent: e];
7630 /* Called as we manually track scroller drags, rather than superclass. */
7631 - (void)mouseDragged: (NSEvent *)e
7633     NSRect sr;
7634     double loc, pos;
7636     NSTRACE (EmacsScroller_mouseDragged);
7638       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7639                       toView: nil];
7640       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7642       if (loc <= 0.0)
7643         {
7644           loc = 0.0;
7645         }
7646       else if (loc >= NSHeight (sr) + last_mouse_offset)
7647         {
7648           loc = NSHeight (sr) + last_mouse_offset;
7649         }
7651       pos = (loc - last_mouse_offset) / NSHeight (sr);
7652       [self sendScrollEventAtLoc: pos fromEvent: e];
7656 - (void)mouseUp: (NSEvent *)e
7658   if (scroll_repeat_entry)
7659     {
7660       [scroll_repeat_entry invalidate];
7661       [scroll_repeat_entry release];
7662       scroll_repeat_entry = nil;
7663     }
7664   last_hit_part = scroll_bar_above_handle;
7668 /* treat scrollwheel events in the bar as though they were in the main window */
7669 - (void) scrollWheel: (NSEvent *)theEvent
7671   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7672   [view mouseDown: theEvent];
7675 @end  /* EmacsScroller */
7678 #ifdef NS_IMPL_GNUSTEP
7679 /* Dummy class to get rid of startup warnings.  */
7680 @implementation EmacsDocument
7682 @end
7683 #endif
7686 /* ==========================================================================
7688    Font-related functions; these used to be in nsfaces.m
7690    ========================================================================== */
7693 Lisp_Object
7694 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7696   struct font *font = XFONT_OBJECT (font_object);
7697   EmacsView *view = FRAME_NS_VIEW (f);
7698   int font_ascent, font_descent;
7700   if (fontset < 0)
7701     fontset = fontset_from_font (font_object);
7702   FRAME_FONTSET (f) = fontset;
7704   if (FRAME_FONT (f) == font)
7705     /* This font is already set in frame F.  There's nothing more to
7706        do.  */
7707     return font_object;
7709   FRAME_FONT (f) = font;
7711   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7712   FRAME_COLUMN_WIDTH (f) = font->average_width;
7713   get_font_ascent_descent (font, &font_ascent, &font_descent);
7714   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
7716   /* Compute the scroll bar width in character columns.  */
7717   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7718     {
7719       int wid = FRAME_COLUMN_WIDTH (f);
7720       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7721         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7722     }
7723   else
7724     {
7725       int wid = FRAME_COLUMN_WIDTH (f);
7726       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7727     }
7729   /* Compute the scroll bar height in character lines.  */
7730   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7731     {
7732       int height = FRAME_LINE_HEIGHT (f);
7733       FRAME_CONFIG_SCROLL_BAR_LINES (f)
7734         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7735     }
7736   else
7737     {
7738       int height = FRAME_LINE_HEIGHT (f);
7739       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7740     }
7742   /* Now make the frame display the given font.  */
7743   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7744     x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7745                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7747   return font_object;
7751 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7752 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7753          in 1.43. */
7755 const char *
7756 ns_xlfd_to_fontname (const char *xlfd)
7757 /* --------------------------------------------------------------------------
7758     Convert an X font name (XLFD) to an NS font name.
7759     Only family is used.
7760     The string returned is temporarily allocated.
7761    -------------------------------------------------------------------------- */
7763   char *name = xmalloc (180);
7764   int i, len;
7765   const char *ret;
7767   if (!strncmp (xlfd, "--", 2))
7768     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7769   else
7770     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7772   /* stopgap for malformed XLFD input */
7773   if (strlen (name) == 0)
7774     strcpy (name, "Monaco");
7776   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7777      also uppercase after '-' or ' ' */
7778   name[0] = c_toupper (name[0]);
7779   for (len =strlen (name), i =0; i<len; i++)
7780     {
7781       if (name[i] == '$')
7782         {
7783           name[i] = '-';
7784           if (i+1<len)
7785             name[i+1] = c_toupper (name[i+1]);
7786         }
7787       else if (name[i] == '_')
7788         {
7789           name[i] = ' ';
7790           if (i+1<len)
7791             name[i+1] = c_toupper (name[i+1]);
7792         }
7793     }
7794 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7795   ret = [[NSString stringWithUTF8String: name] UTF8String];
7796   xfree (name);
7797   return ret;
7801 void
7802 syms_of_nsterm (void)
7804   NSTRACE (syms_of_nsterm);
7806   ns_antialias_threshold = 10.0;
7808   /* from 23+ we need to tell emacs what modifiers there are.. */
7809   DEFSYM (Qmodifier_value, "modifier-value");
7810   DEFSYM (Qalt, "alt");
7811   DEFSYM (Qhyper, "hyper");
7812   DEFSYM (Qmeta, "meta");
7813   DEFSYM (Qsuper, "super");
7814   DEFSYM (Qcontrol, "control");
7815   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7817   DEFSYM (Qfile, "file");
7818   DEFSYM (Qurl, "url");
7820   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7821   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7822   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7823   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7824   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7826   DEFVAR_LISP ("ns-input-file", ns_input_file,
7827               "The file specified in the last NS event.");
7828   ns_input_file =Qnil;
7830   DEFVAR_LISP ("ns-working-text", ns_working_text,
7831               "String for visualizing working composition sequence.");
7832   ns_working_text =Qnil;
7834   DEFVAR_LISP ("ns-input-font", ns_input_font,
7835               "The font specified in the last NS event.");
7836   ns_input_font =Qnil;
7838   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7839               "The fontsize specified in the last NS event.");
7840   ns_input_fontsize =Qnil;
7842   DEFVAR_LISP ("ns-input-line", ns_input_line,
7843                "The line specified in the last NS event.");
7844   ns_input_line =Qnil;
7846   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7847                "The service name specified in the last NS event.");
7848   ns_input_spi_name =Qnil;
7850   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7851                "The service argument specified in the last NS event.");
7852   ns_input_spi_arg =Qnil;
7854   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7855                "This variable describes the behavior of the alternate or option key.\n\
7856 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7857 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7858 at all, allowing it to be used at a lower level for accented character entry.");
7859   ns_alternate_modifier = Qmeta;
7861   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7862                "This variable describes the behavior of the right alternate or option key.\n\
7863 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7864 Set to left means be the same key as `ns-alternate-modifier'.\n\
7865 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7866 at all, allowing it to be used at a lower level for accented character entry.");
7867   ns_right_alternate_modifier = Qleft;
7869   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7870                "This variable describes the behavior of the command key.\n\
7871 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7872   ns_command_modifier = Qsuper;
7874   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7875                "This variable describes the behavior of the right command key.\n\
7876 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7877 Set to left means be the same key as `ns-command-modifier'.\n\
7878 Set to none means that the command / option key is not interpreted by Emacs\n\
7879 at all, allowing it to be used at a lower level for accented character entry.");
7880   ns_right_command_modifier = Qleft;
7882   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7883                "This variable describes the behavior of the control key.\n\
7884 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7885   ns_control_modifier = Qcontrol;
7887   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7888                "This variable describes the behavior of the right control key.\n\
7889 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7890 Set to left means be the same key as `ns-control-modifier'.\n\
7891 Set to none means that the control / option key is not interpreted by Emacs\n\
7892 at all, allowing it to be used at a lower level for accented character entry.");
7893   ns_right_control_modifier = Qleft;
7895   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7896                "This variable describes the behavior of the function key (on laptops).\n\
7897 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7898 Set to none means that the function key is not interpreted by Emacs at all,\n\
7899 allowing it to be used at a lower level for accented character entry.");
7900   ns_function_modifier = Qnone;
7902   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7903                "Non-nil (the default) means to render text antialiased.");
7904   ns_antialias_text = Qt;
7906   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7907                "Whether to confirm application quit using dialog.");
7908   ns_confirm_quit = Qnil;
7910   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7911                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7912 Only works on OSX 10.6 or later.  */);
7913   ns_auto_hide_menu_bar = Qnil;
7915   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7916      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7917 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7918 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7919 Default is t for OSX >= 10.7, nil otherwise.  */);
7920 #ifdef HAVE_NATIVE_FS
7921   ns_use_native_fullscreen = YES;
7922 #else
7923   ns_use_native_fullscreen = NO;
7924 #endif
7925   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7927   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7928      doc: /*Non-nil means use animation on non-native fullscreen.
7929 For native fullscreen, this does nothing.
7930 Default is nil.  */);
7931   ns_use_fullscreen_animation = NO;
7933   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7934      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7935 Note that this does not apply to images.
7936 This variable is ignored on OSX < 10.7 and GNUstep.  */);
7937   ns_use_srgb_colorspace = YES;
7939   /* TODO: move to common code */
7940   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7941                doc: /* Which toolkit scroll bars Emacs uses, if any.
7942 A value of nil means Emacs doesn't use toolkit scroll bars.
7943 With the X Window system, the value is a symbol describing the
7944 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7945 With MS Windows or Nextstep, the value is t.  */);
7946   Vx_toolkit_scroll_bars = Qt;
7948   DEFVAR_BOOL ("x-use-underline-position-properties",
7949                x_use_underline_position_properties,
7950      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7951 A value of nil means ignore them.  If you encounter fonts with bogus
7952 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7953 to 4.1, set this to nil. */);
7954   x_use_underline_position_properties = 0;
7956   DEFVAR_BOOL ("x-underline-at-descent-line",
7957                x_underline_at_descent_line,
7958      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7959 A value of nil means to draw the underline according to the value of the
7960 variable `x-use-underline-position-properties', which is usually at the
7961 baseline level.  The default value is nil.  */);
7962   x_underline_at_descent_line = 0;
7964   /* Tell Emacs about this window system.  */
7965   Fprovide (Qns, Qnil);
7967   DEFSYM (Qcocoa, "cocoa");
7968   DEFSYM (Qgnustep, "gnustep");
7970 #ifdef NS_IMPL_COCOA
7971   Fprovide (Qcocoa, Qnil);
7972   syms_of_macfont ();
7973 #else
7974   Fprovide (Qgnustep, Qnil);
7975   syms_of_nsfont ();
7976 #endif