Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / src / nsterm.m
blob0097b5b30e4607a2606b1158df07a78ef327acd7
1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2014 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <signal.h>
39 #include <unistd.h>
41 #include <c-ctype.h>
42 #include <c-strcase.h>
43 #include <ftoastr.h>
45 #include "lisp.h"
46 #include "blockinput.h"
47 #include "sysselect.h"
48 #include "nsterm.h"
49 #include "systime.h"
50 #include "character.h"
51 #include "fontset.h"
52 #include "composite.h"
53 #include "ccl.h"
55 #include "termhooks.h"
56 #include "termchar.h"
58 #include "window.h"
59 #include "keyboard.h"
60 #include "buffer.h"
61 #include "font.h"
63 #ifdef NS_IMPL_GNUSTEP
64 #include "process.h"
65 #endif
67 #ifdef NS_IMPL_COCOA
68 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
69 #include "macfont.h"
70 #endif
71 #endif
73 /* call tracing */
74 #if 0
75 int term_trace_num = 0;
76 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
77                                 __FILE__, __LINE__, ++term_trace_num)
78 #else
79 #define NSTRACE(x)
80 #endif
82 /* Detailed tracing. "S" means "size" and "LL" stands for "lower left". */
83 #if 0
84 int term_trace_num = 0;
85 #define NSTRACE_SIZE(str,size) fprintf (stderr,                         \
86                                    "%s:%d: [%d]   " str                 \
87                                    " (S:%.0f x %.0f)\n", \
88                                    __FILE__, __LINE__, ++term_trace_num,\
89                                    size.height,                       \
90                                    size.width)
91 #define NSTRACE_RECT(s,r) fprintf (stderr,                              \
92                                    "%s:%d: [%d]   " s                   \
93                                    " (LL:%.0f x %.0f -> S:%.0f x %.0f)\n", \
94                                    __FILE__, __LINE__, ++term_trace_num,\
95                                    r.origin.x,                          \
96                                    r.origin.y,                          \
97                                    r.size.height,                       \
98                                    r.size.width)
99 #else
100 #define NSTRACE_SIZE(str,size)
101 #define NSTRACE_RECT(s,r)
102 #endif
104 extern NSString *NSMenuDidBeginTrackingNotification;
106 /* ==========================================================================
108    NSColor, EmacsColor category.
110    ========================================================================== */
111 @implementation NSColor (EmacsColor)
112 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
113                          blue:(CGFloat)blue alpha:(CGFloat)alpha
115 #ifdef NS_IMPL_COCOA
116 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
117   if (ns_use_srgb_colorspace)
118       return [NSColor colorWithSRGBRed: red
119                                  green: green
120                                   blue: blue
121                                  alpha: alpha];
122 #endif
123 #endif
124   return [NSColor colorWithCalibratedRed: red
125                                    green: green
126                                     blue: blue
127                                    alpha: alpha];
130 - (NSColor *)colorUsingDefaultColorSpace
132 #ifdef NS_IMPL_COCOA
133 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
134   if (ns_use_srgb_colorspace)
135     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
136 #endif
137 #endif
138   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
141 @end
143 /* ==========================================================================
145     Local declarations
147    ========================================================================== */
149 /* Convert a symbol indexed with an NSxxx value to a value as defined
150    in keyboard.c (lispy_function_key). I hope this is a correct way
151    of doing things... */
152 static unsigned convert_ns_to_X_keysym[] =
154   NSHomeFunctionKey,            0x50,
155   NSLeftArrowFunctionKey,       0x51,
156   NSUpArrowFunctionKey,         0x52,
157   NSRightArrowFunctionKey,      0x53,
158   NSDownArrowFunctionKey,       0x54,
159   NSPageUpFunctionKey,          0x55,
160   NSPageDownFunctionKey,        0x56,
161   NSEndFunctionKey,             0x57,
162   NSBeginFunctionKey,           0x58,
163   NSSelectFunctionKey,          0x60,
164   NSPrintFunctionKey,           0x61,
165   NSClearLineFunctionKey,       0x0B,
166   NSExecuteFunctionKey,         0x62,
167   NSInsertFunctionKey,          0x63,
168   NSUndoFunctionKey,            0x65,
169   NSRedoFunctionKey,            0x66,
170   NSMenuFunctionKey,            0x67,
171   NSFindFunctionKey,            0x68,
172   NSHelpFunctionKey,            0x6A,
173   NSBreakFunctionKey,           0x6B,
175   NSF1FunctionKey,              0xBE,
176   NSF2FunctionKey,              0xBF,
177   NSF3FunctionKey,              0xC0,
178   NSF4FunctionKey,              0xC1,
179   NSF5FunctionKey,              0xC2,
180   NSF6FunctionKey,              0xC3,
181   NSF7FunctionKey,              0xC4,
182   NSF8FunctionKey,              0xC5,
183   NSF9FunctionKey,              0xC6,
184   NSF10FunctionKey,             0xC7,
185   NSF11FunctionKey,             0xC8,
186   NSF12FunctionKey,             0xC9,
187   NSF13FunctionKey,             0xCA,
188   NSF14FunctionKey,             0xCB,
189   NSF15FunctionKey,             0xCC,
190   NSF16FunctionKey,             0xCD,
191   NSF17FunctionKey,             0xCE,
192   NSF18FunctionKey,             0xCF,
193   NSF19FunctionKey,             0xD0,
194   NSF20FunctionKey,             0xD1,
195   NSF21FunctionKey,             0xD2,
196   NSF22FunctionKey,             0xD3,
197   NSF23FunctionKey,             0xD4,
198   NSF24FunctionKey,             0xD5,
200   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
201   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
202   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
204   NSTabCharacter,               0x09,
205   0x19,                         0x09,  /* left tab->regular since pass shift */
206   NSCarriageReturnCharacter,    0x0D,
207   NSNewlineCharacter,           0x0D,
208   NSEnterCharacter,             0x8D,
210   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
211   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
212   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
213   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
214   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
215   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
216   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
217   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
218   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
219   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
220   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
221   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
222   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
223   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
224   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
225   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
227   0x1B,                         0x1B   /* escape */
230 static Lisp_Object Qmodifier_value;
231 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
232 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
234 static Lisp_Object QUTF8_STRING;
235 static Lisp_Object Qcocoa, Qgnustep;
236 static Lisp_Object Qfile, Qurl;
238 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
239    the maximum font size to NOT antialias.  On GNUstep there is currently
240    no way to control this behavior. */
241 float ns_antialias_threshold;
243 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
244 NSString *ns_app_name = @"Emacs";  /* default changed later */
246 /* Display variables */
247 struct ns_display_info *x_display_list; /* Chain of existing displays */
248 long context_menu_value = 0;
250 /* display update */
251 static struct frame *ns_updating_frame;
252 static NSView *focus_view = NULL;
253 static int ns_window_num = 0;
254 #ifdef NS_IMPL_GNUSTEP
255 static NSRect uRect;
256 #endif
257 static BOOL gsaved = NO;
258 static BOOL ns_fake_keydown = NO;
259 #ifdef NS_IMPL_COCOA
260 static BOOL ns_menu_bar_is_hidden = NO;
261 #endif
262 /*static int debug_lock = 0; */
264 /* event loop */
265 static BOOL send_appdefined = YES;
266 #define NO_APPDEFINED_DATA (-8)
267 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
268 static NSTimer *timed_entry = 0;
269 static NSTimer *scroll_repeat_entry = nil;
270 static fd_set select_readfds, select_writefds;
271 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
272 static int select_nfds = 0, select_valid = 0;
273 static struct timespec select_timeout = { 0, 0 };
274 static int selfds[2] = { -1, -1 };
275 static pthread_mutex_t select_mutex;
276 static int apploopnr = 0;
277 static NSAutoreleasePool *outerpool;
278 static struct input_event *emacs_event = NULL;
279 static struct input_event *q_event_ptr = NULL;
280 static int n_emacs_events_pending = 0;
281 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
282   *ns_pending_service_args;
283 static BOOL ns_do_open_file = NO;
284 static BOOL ns_last_use_native_fullscreen;
286 static struct {
287   struct input_event *q;
288   int nr, cap;
289 } hold_event_q = {
290   NULL, 0, 0
293 #ifdef NS_IMPL_COCOA
295  * State for pending menu activation:
296  * MENU_NONE     Normal state
297  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
298  *               run lisp to update the menu.
299  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
300  *               will open.
301  */
302 #define MENU_NONE 0
303 #define MENU_PENDING 1
304 #define MENU_OPENING 2
305 static int menu_will_open_state = MENU_NONE;
307 /* Saved position for menu click.  */
308 static CGPoint menu_mouse_point;
309 #endif
311 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
312 #define NS_FUNCTION_KEY_MASK 0x800000
313 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
314 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
315 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
316 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
317 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
318 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
319 #define EV_MODIFIERS2(flags)                          \
320     (((flags & NSHelpKeyMask) ?           \
321            hyper_modifier : 0)                        \
322      | (!EQ (ns_right_alternate_modifier, Qleft) && \
323         ((flags & NSRightAlternateKeyMask) \
324          == NSRightAlternateKeyMask) ? \
325            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
326      | ((flags & NSAlternateKeyMask) ?                 \
327            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
328      | ((flags & NSShiftKeyMask) ?     \
329            shift_modifier : 0)                        \
330      | (!EQ (ns_right_control_modifier, Qleft) && \
331         ((flags & NSRightControlKeyMask) \
332          == NSRightControlKeyMask) ? \
333            parse_solitary_modifier (ns_right_control_modifier) : 0) \
334      | ((flags & NSControlKeyMask) ?      \
335            parse_solitary_modifier (ns_control_modifier) : 0)     \
336      | ((flags & NS_FUNCTION_KEY_MASK) ?  \
337            parse_solitary_modifier (ns_function_modifier) : 0)    \
338      | (!EQ (ns_right_command_modifier, Qleft) && \
339         ((flags & NSRightCommandKeyMask) \
340          == NSRightCommandKeyMask) ? \
341            parse_solitary_modifier (ns_right_command_modifier) : 0) \
342      | ((flags & NSCommandKeyMask) ?      \
343            parse_solitary_modifier (ns_command_modifier):0))
344 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
346 #define EV_UDMODIFIERS(e)                                      \
347     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
348      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
349      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
350      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
351      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
352      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
353      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
354      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
355      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
357 #define EV_BUTTON(e)                                                         \
358     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
359       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
360      [e buttonNumber] - 1)
362 /* Convert the time field to a timestamp in milliseconds. */
363 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
365 /* This is a piece of code which is common to all the event handling
366    methods.  Maybe it should even be a function.  */
367 #define EV_TRAILER(e)                                                   \
368   {                                                                     \
369     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
370     EV_TRAILER2 (e);                                                    \
371   }
373 #define EV_TRAILER2(e)                                                  \
374   {                                                                     \
375       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
376       if (q_event_ptr)                                                  \
377         {                                                               \
378           n_emacs_events_pending++;                                     \
379           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
380         }                                                               \
381       else                                                              \
382         hold_event (emacs_event);                                       \
383       EVENT_INIT (*emacs_event);                                        \
384       ns_send_appdefined (-1);                                          \
385     }
387 /* TODO: get rid of need for these forward declarations */
388 static void ns_condemn_scroll_bars (struct frame *f);
389 static void ns_judge_scroll_bars (struct frame *f);
390 void x_set_frame_alpha (struct frame *f);
393 /* ==========================================================================
395     Utilities
397    ========================================================================== */
399 static void
400 hold_event (struct input_event *event)
402   if (hold_event_q.nr == hold_event_q.cap)
403     {
404       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
405       else hold_event_q.cap *= 2;
406       hold_event_q.q =
407         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
408     }
410   hold_event_q.q[hold_event_q.nr++] = *event;
411   /* Make sure ns_read_socket is called, i.e. we have input.  */
412   raise (SIGIO);
413   send_appdefined = YES;
416 static Lisp_Object
417 append2 (Lisp_Object list, Lisp_Object item)
418 /* --------------------------------------------------------------------------
419    Utility to append to a list
420    -------------------------------------------------------------------------- */
422   Lisp_Object array[2];
423   array[0] = list;
424   array[1] = list1 (item);
425   return Fnconc (2, &array[0]);
429 const char *
430 ns_etc_directory (void)
431 /* If running as a self-contained app bundle, return as a string the
432    filename of the etc directory, if present; else nil.  */
434   NSBundle *bundle = [NSBundle mainBundle];
435   NSString *resourceDir = [bundle resourcePath];
436   NSString *resourcePath;
437   NSFileManager *fileManager = [NSFileManager defaultManager];
438   BOOL isDir;
440   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
441   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
442     {
443       if (isDir) return [resourcePath UTF8String];
444     }
445   return NULL;
449 const char *
450 ns_exec_path (void)
451 /* If running as a self-contained app bundle, return as a path string
452    the filenames of the libexec and bin directories, ie libexec:bin.
453    Otherwise, return nil.
454    Normally, Emacs does not add its own bin/ directory to the PATH.
455    However, a self-contained NS build has a different layout, with
456    bin/ and libexec/ subdirectories in the directory that contains
457    Emacs.app itself.
458    We put libexec first, because init_callproc_1 uses the first
459    element to initialize exec-directory.  An alternative would be
460    for init_callproc to check for invocation-directory/libexec.
463   NSBundle *bundle = [NSBundle mainBundle];
464   NSString *resourceDir = [bundle resourcePath];
465   NSString *binDir = [bundle bundlePath];
466   NSString *resourcePath, *resourcePaths;
467   NSRange range;
468   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
469   NSFileManager *fileManager = [NSFileManager defaultManager];
470   NSArray *paths;
471   NSEnumerator *pathEnum;
472   BOOL isDir;
474   range = [resourceDir rangeOfString: @"Contents"];
475   if (range.location != NSNotFound)
476     {
477       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
478 #ifdef NS_IMPL_COCOA
479       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
480 #endif
481     }
483   paths = [binDir stringsByAppendingPaths:
484                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
485   pathEnum = [paths objectEnumerator];
486   resourcePaths = @"";
488   while ((resourcePath = [pathEnum nextObject]))
489     {
490       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
491         if (isDir)
492           {
493             if ([resourcePaths length] > 0)
494               resourcePaths
495                 = [resourcePaths stringByAppendingString: pathSeparator];
496             resourcePaths
497               = [resourcePaths stringByAppendingString: resourcePath];
498           }
499     }
500   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
502   return NULL;
506 const char *
507 ns_load_path (void)
508 /* If running as a self-contained app bundle, return as a path string
509    the filenames of the site-lisp and lisp directories.
510    Ie, site-lisp:lisp.  Otherwise, return nil.  */
512   NSBundle *bundle = [NSBundle mainBundle];
513   NSString *resourceDir = [bundle resourcePath];
514   NSString *resourcePath, *resourcePaths;
515   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
516   NSFileManager *fileManager = [NSFileManager defaultManager];
517   BOOL isDir;
518   NSArray *paths = [resourceDir stringsByAppendingPaths:
519                               [NSArray arrayWithObjects:
520                                          @"site-lisp", @"lisp", nil]];
521   NSEnumerator *pathEnum = [paths objectEnumerator];
522   resourcePaths = @"";
524   /* Hack to skip site-lisp.  */
525   if (no_site_lisp) resourcePath = [pathEnum nextObject];
527   while ((resourcePath = [pathEnum nextObject]))
528     {
529       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
530         if (isDir)
531           {
532             if ([resourcePaths length] > 0)
533               resourcePaths
534                 = [resourcePaths stringByAppendingString: pathSeparator];
535             resourcePaths
536               = [resourcePaths stringByAppendingString: resourcePath];
537           }
538     }
539   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
541   return NULL;
544 static void
545 ns_timeout (int usecs)
546 /* --------------------------------------------------------------------------
547      Blocking timer utility used by ns_ring_bell
548    -------------------------------------------------------------------------- */
550   struct timespec wakeup = timespec_add (current_timespec (),
551                                          make_timespec (0, usecs * 1000));
553   /* Keep waiting until past the time wakeup.  */
554   while (1)
555     {
556       struct timespec timeout, now = current_timespec ();
557       if (timespec_cmp (wakeup, now) <= 0)
558         break;
559       timeout = timespec_sub (wakeup, now);
561       /* Try to wait that long--but we might wake up sooner.  */
562       pselect (0, NULL, NULL, NULL, &timeout, NULL);
563     }
567 void
568 ns_release_object (void *obj)
569 /* --------------------------------------------------------------------------
570     Release an object (callable from C)
571    -------------------------------------------------------------------------- */
573     [(id)obj release];
577 void
578 ns_retain_object (void *obj)
579 /* --------------------------------------------------------------------------
580     Retain an object (callable from C)
581    -------------------------------------------------------------------------- */
583     [(id)obj retain];
587 void *
588 ns_alloc_autorelease_pool (void)
589 /* --------------------------------------------------------------------------
590      Allocate a pool for temporary objects (callable from C)
591    -------------------------------------------------------------------------- */
593   return [[NSAutoreleasePool alloc] init];
597 void
598 ns_release_autorelease_pool (void *pool)
599 /* --------------------------------------------------------------------------
600      Free a pool and temporary objects it refers to (callable from C)
601    -------------------------------------------------------------------------- */
603   ns_release_object (pool);
608 /* ==========================================================================
610     Focus (clipping) and screen update
612    ========================================================================== */
615 // Window constraining
616 // -------------------
618 // To ensure that the windows are not placed under the menu bar, they
619 // are typically moved by the call-back constrainFrameRect. However,
620 // by overriding it, it's possible to inhibit this, leaving the window
621 // in it's original position.
623 // It's possible to hide the menu bar. However, technically, it's only
624 // possible to hide it when the application is active. To ensure that
625 // this work properly, the menu bar and window constraining are
626 // deferred until the application becomes active.
628 // Even though it's not possible to manually move a window above the
629 // top of the screen, it is allowed if it's done programmatically,
630 // when the menu is hidden. This allows the editable area to cover the
631 // full screen height.
633 // Test cases
634 // ----------
636 // Use the following extra files:
638 //    init.el:
639 //       ;; Hide menu and place frame slightly above the top of the screen.
640 //       (setq ns-auto-hide-menu-bar t)
641 //       (set-frame-position (selected-frame) 0 -20)
643 // Test 1:
645 //    emacs -Q -l init.el
647 //    Result: No menu bar, and the title bar should be above the screen.
649 // Test 2:
651 //    emacs -Q
653 //    Result: Menu bar visible, frame placed immediately below the menu.
656 static void
657 ns_constrain_all_frames (void)
659   Lisp_Object tail, frame;
661   FOR_EACH_FRAME (tail, frame)
662     {
663       struct frame *f = XFRAME (frame);
664       if (FRAME_NS_P (f))
665         {
666           NSView *view = FRAME_NS_VIEW (f);
667           /* This no-op will trigger the default window placing
668            * constraint system. */
669           [[view window] setFrameOrigin:[[view window] frame].origin];
670         }
671     }
675 /* True, if the menu bar should be hidden.  */
677 static BOOL
678 ns_menu_bar_should_be_hidden (void)
680   return !NILP (ns_auto_hide_menu_bar)
681     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
685 /* Show or hide the menu bar, based on user setting.  */
687 static void
688 ns_update_auto_hide_menu_bar (void)
690 #ifdef NS_IMPL_COCOA
691 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
692   block_input ();
694   NSTRACE (ns_update_auto_hide_menu_bar);
696   if (NSApp != nil && [NSApp isActive])
697     {
698       // Note, "setPresentationOptions" triggers an error unless the
699       // application is active.
700       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
702       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
703         {
704           NSApplicationPresentationOptions options
705             = NSApplicationPresentationDefault;
707           if (menu_bar_should_be_hidden)
708             options |= NSApplicationPresentationAutoHideMenuBar
709               | NSApplicationPresentationAutoHideDock;
711           [NSApp setPresentationOptions: options];
713           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
715           if (!ns_menu_bar_is_hidden)
716             {
717               ns_constrain_all_frames ();
718             }
719         }
720     }
722   unblock_input ();
723 #endif
724 #endif
728 static void
729 ns_update_begin (struct frame *f)
730 /* --------------------------------------------------------------------------
731    Prepare for a grouped sequence of drawing calls
732    external (RIF) call; whole frame, called before update_window_begin
733    -------------------------------------------------------------------------- */
735   EmacsView *view = FRAME_NS_VIEW (f);
736   NSTRACE (ns_update_begin);
738   ns_update_auto_hide_menu_bar ();
740 #ifdef NS_IMPL_COCOA
741   if ([view isFullscreen] && [view fsIsNative])
742   {
743     // Fix reappearing tool bar in fullscreen for OSX 10.7
744     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
745     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
746     if (! tbar_visible != ! [toolbar isVisible])
747       [toolbar setVisible: tbar_visible];
748   }
749 #endif
751   ns_updating_frame = f;
752   [view lockFocus];
754   /* drawRect may have been called for say the minibuffer, and then clip path
755      is for the minibuffer.  But the display engine may draw more because
756      we have set the frame as garbaged.  So reset clip path to the whole
757      view.  */
758 #ifdef NS_IMPL_COCOA
759   {
760     NSBezierPath *bp;
761     NSRect r = [view frame];
762     NSRect cr = [[view window] frame];
763     /* If a large frame size is set, r may be larger than the window frame
764        before constrained.  In that case don't change the clip path, as we
765        will clear in to the tool bar and title bar.  */
766     if (r.size.height
767         + FRAME_NS_TITLEBAR_HEIGHT (f)
768         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
769       {
770         bp = [[NSBezierPath bezierPathWithRect: r] retain];
771         [bp setClip];
772         [bp release];
773       }
774   }
775 #endif
777 #ifdef NS_IMPL_GNUSTEP
778   uRect = NSMakeRect (0, 0, 0, 0);
779 #endif
783 static void
784 ns_update_window_begin (struct window *w)
785 /* --------------------------------------------------------------------------
786    Prepare for a grouped sequence of drawing calls
787    external (RIF) call; for one window, called after update_begin
788    -------------------------------------------------------------------------- */
790   struct frame *f = XFRAME (WINDOW_FRAME (w));
791   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
793   NSTRACE (ns_update_window_begin);
794   w->output_cursor = w->cursor;
796   block_input ();
798   if (f == hlinfo->mouse_face_mouse_frame)
799     {
800       /* Don't do highlighting for mouse motion during the update.  */
801       hlinfo->mouse_face_defer = 1;
803         /* If the frame needs to be redrawn,
804            simply forget about any prior mouse highlighting.  */
805       if (FRAME_GARBAGED_P (f))
806         hlinfo->mouse_face_window = Qnil;
808       /* (further code for mouse faces ifdef'd out in other terms elided) */
809     }
811   unblock_input ();
815 static void
816 ns_update_window_end (struct window *w, bool cursor_on_p,
817                       bool mouse_face_overwritten_p)
818 /* --------------------------------------------------------------------------
819    Finished a grouped sequence of drawing calls
820    external (RIF) call; for one window called before update_end
821    -------------------------------------------------------------------------- */
823   /* note: this fn is nearly identical in all terms */
824   if (!w->pseudo_window_p)
825     {
826       block_input ();
828       if (cursor_on_p)
829         display_and_set_cursor (w, 1,
830                                 w->output_cursor.hpos, w->output_cursor.vpos,
831                                 w->output_cursor.x, w->output_cursor.y);
833       if (draw_window_fringes (w, 1))
834         {
835           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
836             x_draw_right_divider (w);
837           else
838             x_draw_vertical_border (w);
839         }
841       unblock_input ();
842     }
844   /* If a row with mouse-face was overwritten, arrange for
845      frame_up_to_date to redisplay the mouse highlight.  */
846   if (mouse_face_overwritten_p)
847     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
849   NSTRACE (update_window_end);
853 static void
854 ns_update_end (struct frame *f)
855 /* --------------------------------------------------------------------------
856    Finished a grouped sequence of drawing calls
857    external (RIF) call; for whole frame, called after update_window_end
858    -------------------------------------------------------------------------- */
860   EmacsView *view = FRAME_NS_VIEW (f);
862 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
863   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
865   block_input ();
867   [view unlockFocus];
868   [[view window] flushWindow];
870   unblock_input ();
871   ns_updating_frame = NULL;
872   NSTRACE (ns_update_end);
875 static void
876 ns_focus (struct frame *f, NSRect *r, int n)
877 /* --------------------------------------------------------------------------
878    Internal: Focus on given frame.  During small local updates this is used to
879      draw, however during large updates, ns_update_begin and ns_update_end are
880      called to wrap the whole thing, in which case these calls are stubbed out.
881      Except, on GNUstep, we accumulate the rectangle being drawn into, because
882      the back end won't do this automatically, and will just end up flushing
883      the entire window.
884    -------------------------------------------------------------------------- */
886 //  NSTRACE (ns_focus);
887 /* static int c =0;
888    fprintf (stderr, "focus: %d", c++);
889    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
890    fprintf (stderr, "\n"); */
892   if (f != ns_updating_frame)
893     {
894       NSView *view = FRAME_NS_VIEW (f);
895       if (view != focus_view)
896         {
897           if (focus_view != NULL)
898             {
899               [focus_view unlockFocus];
900               [[focus_view window] flushWindow];
901 /*debug_lock--; */
902             }
904           if (view)
905             [view lockFocus];
906           focus_view = view;
907 /*if (view) debug_lock++; */
908         }
909     }
911   /* clipping */
912   if (r)
913     {
914       [[NSGraphicsContext currentContext] saveGraphicsState];
915       if (n == 2)
916         NSRectClipList (r, 2);
917       else
918         NSRectClip (*r);
919       gsaved = YES;
920     }
924 static void
925 ns_unfocus (struct frame *f)
926 /* --------------------------------------------------------------------------
927      Internal: Remove focus on given frame
928    -------------------------------------------------------------------------- */
930 //  NSTRACE (ns_unfocus);
932   if (gsaved)
933     {
934       [[NSGraphicsContext currentContext] restoreGraphicsState];
935       gsaved = NO;
936     }
938   if (f != ns_updating_frame)
939     {
940       if (focus_view != NULL)
941         {
942           [focus_view unlockFocus];
943           [[focus_view window] flushWindow];
944           focus_view = NULL;
945 /*debug_lock--; */
946         }
947     }
951 static void
952 ns_clip_to_row (struct window *w, struct glyph_row *row,
953                 enum glyph_row_area area, BOOL gc)
954 /* --------------------------------------------------------------------------
955      Internal (but parallels other terms): Focus drawing on given row
956    -------------------------------------------------------------------------- */
958   struct frame *f = XFRAME (WINDOW_FRAME (w));
959   NSRect clip_rect;
960   int window_x, window_y, window_width;
962   window_box (w, area, &window_x, &window_y, &window_width, 0);
964   clip_rect.origin.x = window_x;
965   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
966   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
967   clip_rect.size.width = window_width;
968   clip_rect.size.height = row->visible_height;
970   ns_focus (f, &clip_rect, 1);
974 static void
975 ns_ring_bell (struct frame *f)
976 /* --------------------------------------------------------------------------
977      "Beep" routine
978    -------------------------------------------------------------------------- */
980   NSTRACE (ns_ring_bell);
981   if (visible_bell)
982     {
983       NSAutoreleasePool *pool;
984       struct frame *frame = SELECTED_FRAME ();
985       NSView *view;
987       block_input ();
988       pool = [[NSAutoreleasePool alloc] init];
990       view = FRAME_NS_VIEW (frame);
991       if (view != nil)
992         {
993           NSRect r, surr;
994           NSPoint dim = NSMakePoint (128, 128);
996           r = [view bounds];
997           r.origin.x += (r.size.width - dim.x) / 2;
998           r.origin.y += (r.size.height - dim.y) / 2;
999           r.size.width = dim.x;
1000           r.size.height = dim.y;
1001           surr = NSInsetRect (r, -2, -2);
1002           ns_focus (frame, &surr, 1);
1003           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1004           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1005                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
1006           NSRectFill (r);
1007           [[view window] flushWindow];
1008           ns_timeout (150000);
1009           [[view window] restoreCachedImage];
1010           [[view window] flushWindow];
1011           ns_unfocus (frame);
1012         }
1013       [pool release];
1014       unblock_input ();
1015     }
1016   else
1017     {
1018       NSBeep ();
1019     }
1022 /* ==========================================================================
1024     Frame / window manager related functions
1026    ========================================================================== */
1029 static void
1030 ns_raise_frame (struct frame *f)
1031 /* --------------------------------------------------------------------------
1032      Bring window to foreground and make it active
1033    -------------------------------------------------------------------------- */
1035   NSView *view;
1036   check_window_system (f);
1037   view = FRAME_NS_VIEW (f);
1038   block_input ();
1039   if (FRAME_VISIBLE_P (f))
1040     [[view window] makeKeyAndOrderFront: NSApp];
1041   unblock_input ();
1045 static void
1046 ns_lower_frame (struct frame *f)
1047 /* --------------------------------------------------------------------------
1048      Send window to back
1049    -------------------------------------------------------------------------- */
1051   NSView *view;
1052   check_window_system (f);
1053   view = FRAME_NS_VIEW (f);
1054   block_input ();
1055   [[view window] orderBack: NSApp];
1056   unblock_input ();
1060 static void
1061 ns_frame_raise_lower (struct frame *f, int raise)
1062 /* --------------------------------------------------------------------------
1063      External (hook)
1064    -------------------------------------------------------------------------- */
1066   NSTRACE (ns_frame_raise_lower);
1068   if (raise)
1069     ns_raise_frame (f);
1070   else
1071     ns_lower_frame (f);
1075 static void
1076 ns_frame_rehighlight (struct frame *frame)
1077 /* --------------------------------------------------------------------------
1078      External (hook): called on things like window switching within frame
1079    -------------------------------------------------------------------------- */
1081   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1082   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1084   NSTRACE (ns_frame_rehighlight);
1085   if (dpyinfo->x_focus_frame)
1086     {
1087       dpyinfo->x_highlight_frame
1088         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1089            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1090            : dpyinfo->x_focus_frame);
1091       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1092         {
1093           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1094           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1095         }
1096     }
1097   else
1098       dpyinfo->x_highlight_frame = 0;
1100   if (dpyinfo->x_highlight_frame &&
1101          dpyinfo->x_highlight_frame != old_highlight)
1102     {
1103       if (old_highlight)
1104         {
1105           x_update_cursor (old_highlight, 1);
1106           x_set_frame_alpha (old_highlight);
1107         }
1108       if (dpyinfo->x_highlight_frame)
1109         {
1110           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1111           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1112         }
1113     }
1117 void
1118 x_make_frame_visible (struct frame *f)
1119 /* --------------------------------------------------------------------------
1120      External: Show the window (X11 semantics)
1121    -------------------------------------------------------------------------- */
1123   NSTRACE (x_make_frame_visible);
1124   /* XXX: at some points in past this was not needed, as the only place that
1125      called this (frame.c:Fraise_frame ()) also called raise_lower;
1126      if this ends up the case again, comment this out again. */
1127   if (!FRAME_VISIBLE_P (f))
1128     {
1129       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1131       SET_FRAME_VISIBLE (f, 1);
1132       ns_raise_frame (f);
1134       /* Making a new frame from a fullscreen frame will make the new frame
1135          fullscreen also.  So skip handleFS as this will print an error.  */
1136       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1137           && [view isFullscreen])
1138         return;
1140       if (f->want_fullscreen != FULLSCREEN_NONE)
1141         {
1142           block_input ();
1143           [view handleFS];
1144           unblock_input ();
1145         }
1146     }
1150 void
1151 x_make_frame_invisible (struct frame *f)
1152 /* --------------------------------------------------------------------------
1153      External: Hide the window (X11 semantics)
1154    -------------------------------------------------------------------------- */
1156   NSView *view;
1157   NSTRACE (x_make_frame_invisible);
1158   check_window_system (f);
1159   view = FRAME_NS_VIEW (f);
1160   [[view window] orderOut: NSApp];
1161   SET_FRAME_VISIBLE (f, 0);
1162   SET_FRAME_ICONIFIED (f, 0);
1166 void
1167 x_iconify_frame (struct frame *f)
1168 /* --------------------------------------------------------------------------
1169      External: Iconify window
1170    -------------------------------------------------------------------------- */
1172   NSView *view;
1173   struct ns_display_info *dpyinfo;
1175   NSTRACE (x_iconify_frame);
1176   check_window_system (f);
1177   view = FRAME_NS_VIEW (f);
1178   dpyinfo = FRAME_DISPLAY_INFO (f);
1180   if (dpyinfo->x_highlight_frame == f)
1181     dpyinfo->x_highlight_frame = 0;
1183   if ([[view window] windowNumber] <= 0)
1184     {
1185       /* the window is still deferred.  Make it very small, bring it
1186          on screen and order it out. */
1187       NSRect s = { { 100, 100}, {0, 0} };
1188       NSRect t;
1189       t = [[view window] frame];
1190       [[view window] setFrame: s display: NO];
1191       [[view window] orderBack: NSApp];
1192       [[view window] orderOut: NSApp];
1193       [[view window] setFrame: t display: NO];
1194     }
1195   [[view window] miniaturize: NSApp];
1198 /* Free X resources of frame F.  */
1200 void
1201 x_free_frame_resources (struct frame *f)
1203   NSView *view;
1204   struct ns_display_info *dpyinfo;
1205   Mouse_HLInfo *hlinfo;
1207   NSTRACE (x_free_frame_resources);
1208   check_window_system (f);
1209   view = FRAME_NS_VIEW (f);
1210   dpyinfo = FRAME_DISPLAY_INFO (f);
1211   hlinfo = MOUSE_HL_INFO (f);
1213   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1215   block_input ();
1217   free_frame_menubar (f);
1218   free_frame_faces (f);
1220   if (f == dpyinfo->x_focus_frame)
1221     dpyinfo->x_focus_frame = 0;
1222   if (f == dpyinfo->x_highlight_frame)
1223     dpyinfo->x_highlight_frame = 0;
1224   if (f == hlinfo->mouse_face_mouse_frame)
1225     reset_mouse_highlight (hlinfo);
1227   if (f->output_data.ns->miniimage != nil)
1228     [f->output_data.ns->miniimage release];
1230   [[view window] close];
1231   [view release];
1233   xfree (f->output_data.ns);
1235   unblock_input ();
1238 void
1239 x_destroy_window (struct frame *f)
1240 /* --------------------------------------------------------------------------
1241      External: Delete the window
1242    -------------------------------------------------------------------------- */
1244   NSTRACE (x_destroy_window);
1245   check_window_system (f);
1246   x_free_frame_resources (f);
1247   ns_window_num--;
1251 void
1252 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1253 /* --------------------------------------------------------------------------
1254      External: Position the window
1255    -------------------------------------------------------------------------- */
1257   NSView *view = FRAME_NS_VIEW (f);
1258   NSArray *screens = [NSScreen screens];
1259   NSScreen *fscreen = [screens objectAtIndex: 0];
1260   NSScreen *screen = [[view window] screen];
1262   NSTRACE (x_set_offset);
1264   block_input ();
1266   f->left_pos = xoff;
1267   f->top_pos = yoff;
1269   if (view != nil && screen && fscreen)
1270     {
1271       f->left_pos = f->size_hint_flags & XNegative
1272         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1273         : f->left_pos;
1274       /* We use visibleFrame here to take menu bar into account.
1275          Ideally we should also adjust left/top with visibleFrame.origin.  */
1277       f->top_pos = f->size_hint_flags & YNegative
1278         ? ([screen visibleFrame].size.height + f->top_pos
1279            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1280            - FRAME_TOOLBAR_HEIGHT (f))
1281         : f->top_pos;
1282 #ifdef NS_IMPL_GNUSTEP
1283       if (f->left_pos < 100)
1284         f->left_pos = 100;  /* don't overlap menu */
1285 #endif
1286       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1287          menu bar.  */
1288       [[view window] setFrameTopLeftPoint:
1289                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1290                                     SCREENMAXBOUND ([fscreen frame].size.height
1291                                                     - NS_TOP_POS (f)))];
1292       f->size_hint_flags &= ~(XNegative|YNegative);
1293     }
1295   unblock_input ();
1299 void
1300 x_set_window_size (struct frame *f,
1301                    int change_grav,
1302                    int width,
1303                    int height,
1304                    bool pixelwise)
1305 /* --------------------------------------------------------------------------
1306      Adjust window pixel size based on given character grid size
1307      Impl is a bit more complex than other terms, need to do some
1308      internal clipping.
1309    -------------------------------------------------------------------------- */
1311   EmacsView *view = FRAME_NS_VIEW (f);
1312   NSWindow *window = [view window];
1313   NSRect wr = [window frame];
1314   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1315   int pixelwidth, pixelheight;
1316   int rows, cols;
1318   NSTRACE (x_set_window_size);
1320   if (view == nil)
1321     return;
1323 /*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));*/
1325   block_input ();
1327   check_frame_size (f, &width, &height, pixelwise);
1329   compute_fringe_widths (f, 0);
1331   if (pixelwise)
1332     {
1333       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1334       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1335       cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1336       rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1337     }
1338   else
1339     {
1340       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1341       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1342       cols = width;
1343       rows = height;
1344     }
1346   /* If we have a toolbar, take its height into account. */
1347   if (tb && ! [view isFullscreen])
1348     {
1349     /* NOTE: previously this would generate wrong result if toolbar not
1350              yet displayed and fixing toolbar_height=32 helped, but
1351              now (200903) seems no longer needed */
1352     FRAME_TOOLBAR_HEIGHT (f) =
1353       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1354         - FRAME_NS_TITLEBAR_HEIGHT (f);
1355 #ifdef NS_IMPL_GNUSTEP
1356       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1357 #endif
1358     }
1359   else
1360     FRAME_TOOLBAR_HEIGHT (f) = 0;
1362   wr.size.width = pixelwidth + f->border_width;
1363   wr.size.height = pixelheight;
1364   if (! [view isFullscreen])
1365     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1366       + FRAME_TOOLBAR_HEIGHT (f);
1368   /* Do not try to constrain to this screen.  We may have multiple
1369      screens, and want Emacs to span those.  Constraining to screen
1370      prevents that, and that is not nice to the user.  */
1371  if (f->output_data.ns->zooming)
1372    f->output_data.ns->zooming = 0;
1373  else
1374    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1376   [view setRows: rows andColumns: cols];
1377   [window setFrame: wr display: YES];
1379   /* This is a trick to compensate for Emacs' managing the scrollbar area
1380      as a fixed number of standard character columns.  Instead of leaving
1381      blank space for the extra, we chopped it off above.  Now for
1382      left-hand scrollbars, we shift all rendering to the left by the
1383      difference between the real width and Emacs' imagined one.  For
1384      right-hand bars, don't worry about it since the extra is never used.
1385      (Obviously doesn't work for vertically split windows tho..) */
1386   {
1387     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1388       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1389                      - NS_SCROLL_BAR_WIDTH (f), 0)
1390       : NSMakePoint (0, 0);
1391     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1392     [view setBoundsOrigin: origin];
1393   }
1395   change_frame_size (f, width, height, 0, 1, 0, pixelwise);
1396 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1398   mark_window_cursors_off (XWINDOW (f->root_window));
1399   cancel_mouse_face (f);
1401   unblock_input ();
1405 static void
1406 ns_fullscreen_hook (struct frame *f)
1408   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1410   if (!FRAME_VISIBLE_P (f))
1411     return;
1413    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1414     {
1415       /* Old style fs don't initiate correctly if created from
1416          init/default-frame alist, so use a timer (not nice...).
1417       */
1418       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1419                                      selector: @selector (handleFS)
1420                                      userInfo: nil repeats: NO];
1421       return;
1422     }
1424   block_input ();
1425   [view handleFS];
1426   unblock_input ();
1429 /* ==========================================================================
1431     Color management
1433    ========================================================================== */
1436 NSColor *
1437 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1439   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1440   if (idx < 1 || idx >= color_table->avail)
1441     return nil;
1442   return color_table->colors[idx];
1446 unsigned long
1447 ns_index_color (NSColor *color, struct frame *f)
1449   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1450   ptrdiff_t idx;
1451   ptrdiff_t i;
1453   if (!color_table->colors)
1454     {
1455       color_table->size = NS_COLOR_CAPACITY;
1456       color_table->avail = 1; /* skip idx=0 as marker */
1457       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1458       color_table->colors[0] = nil;
1459       color_table->empty_indices = [[NSMutableSet alloc] init];
1460     }
1462   /* Do we already have this color?  */
1463   for (i = 1; i < color_table->avail; i++)
1464     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1465       return i;
1467   if ([color_table->empty_indices count] > 0)
1468     {
1469       NSNumber *index = [color_table->empty_indices anyObject];
1470       [color_table->empty_indices removeObject: index];
1471       idx = [index unsignedLongValue];
1472     }
1473   else
1474     {
1475       if (color_table->avail == color_table->size)
1476         color_table->colors =
1477           xpalloc (color_table->colors, &color_table->size, 1,
1478                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1479       idx = color_table->avail++;
1480     }
1482   color_table->colors[idx] = color;
1483   [color retain];
1484 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1485   return idx;
1489 void
1490 ns_free_indexed_color (unsigned long idx, struct frame *f)
1492   struct ns_color_table *color_table;
1493   NSColor *color;
1494   NSNumber *index;
1496   if (!f)
1497     return;
1499   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1501   if (idx <= 0 || idx >= color_table->size) {
1502     message1 ("ns_free_indexed_color: Color index out of range.\n");
1503     return;
1504   }
1506   index = [NSNumber numberWithUnsignedInt: idx];
1507   if ([color_table->empty_indices containsObject: index]) {
1508     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1509     return;
1510   }
1512   color = color_table->colors[idx];
1513   [color release];
1514   color_table->colors[idx] = nil;
1515   [color_table->empty_indices addObject: index];
1516 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1520 static int
1521 ns_get_color (const char *name, NSColor **col)
1522 /* --------------------------------------------------------------------------
1523      Parse a color name
1524    -------------------------------------------------------------------------- */
1525 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1526    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1527    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1529   NSColor *new = nil;
1530   static char hex[20];
1531   int scaling;
1532   float r = -1.0, g, b;
1533   NSString *nsname = [NSString stringWithUTF8String: name];
1535 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1536   block_input ();
1538   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1539     {
1540 #ifdef NS_IMPL_COCOA
1541       NSString *defname = [[NSUserDefaults standardUserDefaults]
1542                             stringForKey: @"AppleHighlightColor"];
1543       if (defname != nil)
1544         nsname = defname;
1545       else
1546 #endif
1547       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1548         {
1549           *col = [new colorUsingDefaultColorSpace];
1550           unblock_input ();
1551           return 0;
1552         }
1553       else
1554         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1556       name = [nsname UTF8String];
1557     }
1558   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1559     {
1560       /* NOTE: OSX applications normally don't set foreground selection, but
1561          text may be unreadable if we don't.
1562       */
1563       if ((new = [NSColor selectedTextColor]) != nil)
1564         {
1565           *col = [new colorUsingDefaultColorSpace];
1566           unblock_input ();
1567           return 0;
1568         }
1570       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1571       name = [nsname UTF8String];
1572     }
1574   /* First, check for some sort of numeric specification. */
1575   hex[0] = '\0';
1577   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1578     {
1579       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1580       [scanner scanFloat: &r];
1581       [scanner scanFloat: &g];
1582       [scanner scanFloat: &b];
1583     }
1584   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1585     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1586   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1587     {
1588       int len = (strlen(name) - 1);
1589       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1590       int i;
1591       scaling = strlen(name+start) / 3;
1592       for (i = 0; i < 3; i++)
1593         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1594                  name + start + i * scaling);
1595       hex[3 * (scaling + 1) - 1] = '\0';
1596     }
1598   if (hex[0])
1599     {
1600       int rr, gg, bb;
1601       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1602       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1603         {
1604           r = rr / fscale;
1605           g = gg / fscale;
1606           b = bb / fscale;
1607         }
1608     }
1610   if (r >= 0.0F)
1611     {
1612       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1613       unblock_input ();
1614       return 0;
1615     }
1617   /* Otherwise, color is expected to be from a list */
1618   {
1619     NSEnumerator *lenum, *cenum;
1620     NSString *name;
1621     NSColorList *clist;
1623 #ifdef NS_IMPL_GNUSTEP
1624     /* XXX: who is wrong, the requestor or the implementation? */
1625     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1626         == NSOrderedSame)
1627       nsname = @"highlightColor";
1628 #endif
1630     lenum = [[NSColorList availableColorLists] objectEnumerator];
1631     while ( (clist = [lenum nextObject]) && new == nil)
1632       {
1633         cenum = [[clist allKeys] objectEnumerator];
1634         while ( (name = [cenum nextObject]) && new == nil )
1635           {
1636             if ([name compare: nsname
1637                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1638               new = [clist colorWithKey: name];
1639           }
1640       }
1641   }
1643   if (new)
1644     *col = [new colorUsingDefaultColorSpace];
1645   unblock_input ();
1646   return new ? 0 : 1;
1651 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1652 /* --------------------------------------------------------------------------
1653      Convert a Lisp string object to a NS color
1654    -------------------------------------------------------------------------- */
1656   NSTRACE (ns_lisp_to_color);
1657   if (STRINGP (color))
1658     return ns_get_color (SSDATA (color), col);
1659   else if (SYMBOLP (color))
1660     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1661   return 1;
1665 Lisp_Object
1666 ns_color_to_lisp (NSColor *col)
1667 /* --------------------------------------------------------------------------
1668      Convert a color to a lisp string with the RGB equivalent
1669    -------------------------------------------------------------------------- */
1671   EmacsCGFloat red, green, blue, alpha, gray;
1672   char buf[1024];
1673   const char *str;
1674   NSTRACE (ns_color_to_lisp);
1676   block_input ();
1677   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1679       if ((str =[[col colorNameComponent] UTF8String]))
1680         {
1681           unblock_input ();
1682           return build_string ((char *)str);
1683         }
1685     [[col colorUsingDefaultColorSpace]
1686         getRed: &red green: &green blue: &blue alpha: &alpha];
1687   if (red == green && red == blue)
1688     {
1689       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1690             getWhite: &gray alpha: &alpha];
1691       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1692                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1693       unblock_input ();
1694       return build_string (buf);
1695     }
1697   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1698             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1700   unblock_input ();
1701   return build_string (buf);
1705 void
1706 ns_query_color(void *col, XColor *color_def, int setPixel)
1707 /* --------------------------------------------------------------------------
1708          Get ARGB values out of NSColor col and put them into color_def.
1709          If setPixel, set the pixel to a concatenated version.
1710          and set color_def pixel to the resulting index.
1711    -------------------------------------------------------------------------- */
1713   EmacsCGFloat r, g, b, a;
1715   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1716   color_def->red   = r * 65535;
1717   color_def->green = g * 65535;
1718   color_def->blue  = b * 65535;
1720   if (setPixel == YES)
1721     color_def->pixel
1722       = ARGB_TO_ULONG((int)(a*255),
1723                       (int)(r*255), (int)(g*255), (int)(b*255));
1727 bool
1728 ns_defined_color (struct frame *f,
1729                   const char *name,
1730                   XColor *color_def,
1731                   bool alloc,
1732                   bool makeIndex)
1733 /* --------------------------------------------------------------------------
1734          Return true if named color found, and set color_def rgb accordingly.
1735          If makeIndex and alloc are nonzero put the color in the color_table,
1736          and set color_def pixel to the resulting index.
1737          If makeIndex is zero, set color_def pixel to ARGB.
1738          Return false if not found
1739    -------------------------------------------------------------------------- */
1741   NSColor *col;
1742   NSTRACE (ns_defined_color);
1744   block_input ();
1745   if (ns_get_color (name, &col) != 0) /* Color not found  */
1746     {
1747       unblock_input ();
1748       return 0;
1749     }
1750   if (makeIndex && alloc)
1751     color_def->pixel = ns_index_color (col, f);
1752   ns_query_color (col, color_def, !makeIndex);
1753   unblock_input ();
1754   return 1;
1758 void
1759 x_set_frame_alpha (struct frame *f)
1760 /* --------------------------------------------------------------------------
1761      change the entire-frame transparency
1762    -------------------------------------------------------------------------- */
1764   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1765   double alpha = 1.0;
1766   double alpha_min = 1.0;
1768   if (dpyinfo->x_highlight_frame == f)
1769     alpha = f->alpha[0];
1770   else
1771     alpha = f->alpha[1];
1773   if (FLOATP (Vframe_alpha_lower_limit))
1774     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1775   else if (INTEGERP (Vframe_alpha_lower_limit))
1776     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1778   if (alpha < 0.0)
1779     return;
1780   else if (1.0 < alpha)
1781     alpha = 1.0;
1782   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1783     alpha = alpha_min;
1785 #ifdef NS_IMPL_COCOA
1786   {
1787     EmacsView *view = FRAME_NS_VIEW (f);
1788   [[view window] setAlphaValue: alpha];
1789   }
1790 #endif
1794 /* ==========================================================================
1796     Mouse handling
1798    ========================================================================== */
1801 void
1802 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1803 /* --------------------------------------------------------------------------
1804      Programmatically reposition mouse pointer in pixel coordinates
1805    -------------------------------------------------------------------------- */
1807   NSTRACE (x_set_mouse_pixel_position);
1808   ns_raise_frame (f);
1809 #if 0
1810   /* FIXME: this does not work, and what about GNUstep? */
1811 #ifdef NS_IMPL_COCOA
1812   [FRAME_NS_VIEW (f) lockFocus];
1813   PSsetmouse ((float)pix_x, (float)pix_y);
1814   [FRAME_NS_VIEW (f) unlockFocus];
1815 #endif
1816 #endif
1820 void
1821 x_set_mouse_position (struct frame *f, int h, int v)
1822 /* --------------------------------------------------------------------------
1823      Programmatically reposition mouse pointer in character coordinates
1824    -------------------------------------------------------------------------- */
1826   int pix_x, pix_y;
1828   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1829   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1831   if (pix_x < 0) pix_x = 0;
1832   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1834   if (pix_y < 0) pix_y = 0;
1835   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1837   x_set_mouse_pixel_position (f, pix_x, pix_y);
1841 static int
1842 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1843 /*   ------------------------------------------------------------------------
1844      Called by EmacsView on mouseMovement events.  Passes on
1845      to emacs mainstream code if we moved off of a rect of interest
1846      known as last_mouse_glyph.
1847      ------------------------------------------------------------------------ */
1849   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1850   NSRect *r;
1852 //  NSTRACE (note_mouse_movement);
1854   dpyinfo->last_mouse_motion_frame = frame;
1855   r = &dpyinfo->last_mouse_glyph;
1857   /* Note, this doesn't get called for enter/leave, since we don't have a
1858      position.  Those are taken care of in the corresponding NSView methods. */
1860   /* has movement gone beyond last rect we were tracking? */
1861   if (x < r->origin.x || x >= r->origin.x + r->size.width
1862       || y < r->origin.y || y >= r->origin.y + r->size.height)
1863     {
1864       ns_update_begin (frame);
1865       frame->mouse_moved = 1;
1866       note_mouse_highlight (frame, x, y);
1867       remember_mouse_glyph (frame, x, y, r);
1868       ns_update_end (frame);
1869       return 1;
1870     }
1872   return 0;
1876 static void
1877 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1878                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1879                    Time *time)
1880 /* --------------------------------------------------------------------------
1881     External (hook): inform emacs about mouse position and hit parts.
1882     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1883     x & y should be position in the scrollbar (the whole bar, not the handle)
1884     and length of scrollbar respectively
1885    -------------------------------------------------------------------------- */
1887   id view;
1888   NSPoint position;
1889   Lisp_Object frame, tail;
1890   struct frame *f;
1891   struct ns_display_info *dpyinfo;
1893   NSTRACE (ns_mouse_position);
1895   if (*fp == NULL)
1896     {
1897       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1898       return;
1899     }
1901   dpyinfo = FRAME_DISPLAY_INFO (*fp);
1903   block_input ();
1905   if (dpyinfo->last_mouse_scroll_bar != nil && insist == 0)
1906     {
1907       /* TODO: we do not use this path at the moment because drag events will
1908            go directly to the EmacsScroller.  Leaving code in for now. */
1909       [dpyinfo->last_mouse_scroll_bar
1910           getMouseMotionPart: (int *)part window: bar_window x: x y: y];
1911       if (time)
1912         *time = dpyinfo->last_mouse_movement_time;
1913       dpyinfo->last_mouse_scroll_bar = nil;
1914     }
1915   else
1916     {
1917       /* Clear the mouse-moved flag for every frame on this display.  */
1918       FOR_EACH_FRAME (tail, frame)
1919         if (FRAME_NS_P (XFRAME (frame))
1920             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1921           XFRAME (frame)->mouse_moved = 0;
1923       dpyinfo->last_mouse_scroll_bar = nil;
1924       if (dpyinfo->last_mouse_frame
1925           && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1926         f = dpyinfo->last_mouse_frame;
1927       else
1928         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1929                                     : SELECTED_FRAME ();
1931       if (f && FRAME_NS_P (f))
1932         {
1933           view = FRAME_NS_VIEW (*fp);
1935           position = [[view window] mouseLocationOutsideOfEventStream];
1936           position = [view convertPoint: position fromView: nil];
1937           remember_mouse_glyph (f, position.x, position.y,
1938                                 &dpyinfo->last_mouse_glyph);
1939 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1941           if (bar_window) *bar_window = Qnil;
1942           if (part) *part = 0; /*scroll_bar_handle; */
1944           if (x) XSETINT (*x, lrint (position.x));
1945           if (y) XSETINT (*y, lrint (position.y));
1946           if (time)
1947             *time = dpyinfo->last_mouse_movement_time;
1948           *fp = f;
1949         }
1950     }
1952   unblock_input ();
1956 static void
1957 ns_frame_up_to_date (struct frame *f)
1958 /* --------------------------------------------------------------------------
1959     External (hook): Fix up mouse highlighting right after a full update.
1960     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1961    -------------------------------------------------------------------------- */
1963   NSTRACE (ns_frame_up_to_date);
1965   if (FRAME_NS_P (f))
1966     {
1967       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1968       if (f == hlinfo->mouse_face_mouse_frame)
1969         {
1970           block_input ();
1971           ns_update_begin(f);
1972           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1973                                 hlinfo->mouse_face_mouse_x,
1974                                 hlinfo->mouse_face_mouse_y);
1975           ns_update_end(f);
1976           unblock_input ();
1977         }
1978     }
1982 static void
1983 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1984 /* --------------------------------------------------------------------------
1985     External (RIF): set frame mouse pointer type.
1986    -------------------------------------------------------------------------- */
1988   NSTRACE (ns_define_frame_cursor);
1989   if (FRAME_POINTER_TYPE (f) != cursor)
1990     {
1991       EmacsView *view = FRAME_NS_VIEW (f);
1992       FRAME_POINTER_TYPE (f) = cursor;
1993       [[view window] invalidateCursorRectsForView: view];
1994       /* Redisplay assumes this function also draws the changed frame
1995          cursor, but this function doesn't, so do it explicitly.  */
1996       x_update_cursor (f, 1);
1997     }
2002 /* ==========================================================================
2004     Keyboard handling
2006    ========================================================================== */
2009 static unsigned
2010 ns_convert_key (unsigned code)
2011 /* --------------------------------------------------------------------------
2012     Internal call used by NSView-keyDown.
2013    -------------------------------------------------------------------------- */
2015   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
2016                                 / sizeof (convert_ns_to_X_keysym[0]));
2017   unsigned keysym;
2018   /* An array would be faster, but less easy to read. */
2019   for (keysym = 0; keysym < last_keysym; keysym += 2)
2020     if (code == convert_ns_to_X_keysym[keysym])
2021       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2022   return 0;
2023 /* if decide to use keyCode and Carbon table, use this line:
2024      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2028 char *
2029 x_get_keysym_name (int keysym)
2030 /* --------------------------------------------------------------------------
2031     Called by keyboard.c.  Not sure if the return val is important, except
2032     that it be unique.
2033    -------------------------------------------------------------------------- */
2035   static char value[16];
2036   NSTRACE (x_get_keysym_name);
2037   sprintf (value, "%d", keysym);
2038   return value;
2043 /* ==========================================================================
2045     Block drawing operations
2047    ========================================================================== */
2050 static void
2051 ns_redraw_scroll_bars (struct frame *f)
2053   int i;
2054   id view;
2055   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2056   NSTRACE (ns_redraw_scroll_bars);
2057   for (i =[subviews count]-1; i >= 0; i--)
2058     {
2059       view = [subviews objectAtIndex: i];
2060       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2061       [view display];
2062     }
2066 void
2067 ns_clear_frame (struct frame *f)
2068 /* --------------------------------------------------------------------------
2069       External (hook): Erase the entire frame
2070    -------------------------------------------------------------------------- */
2072   NSView *view = FRAME_NS_VIEW (f);
2073   NSRect r;
2075   NSTRACE (ns_clear_frame);
2077  /* comes on initial frame because we have
2078     after-make-frame-functions = select-frame */
2079  if (!FRAME_DEFAULT_FACE (f))
2080    return;
2082   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2084   r = [view bounds];
2086   block_input ();
2087   ns_focus (f, &r, 1);
2088   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2089   NSRectFill (r);
2090   ns_unfocus (f);
2092   /* as of 2006/11 or so this is now needed */
2093   ns_redraw_scroll_bars (f);
2094   unblock_input ();
2098 static void
2099 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2100 /* --------------------------------------------------------------------------
2101     External (RIF):  Clear section of frame
2102    -------------------------------------------------------------------------- */
2104   NSRect r = NSMakeRect (x, y, width, height);
2105   NSView *view = FRAME_NS_VIEW (f);
2106   struct face *face = FRAME_DEFAULT_FACE (f);
2108   if (!view || !face)
2109     return;
2111   NSTRACE (ns_clear_frame_area);
2113   r = NSIntersectionRect (r, [view frame]);
2114   ns_focus (f, &r, 1);
2115   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2117   NSRectFill (r);
2119   ns_unfocus (f);
2120   return;
2124 static void
2125 ns_scroll_run (struct window *w, struct run *run)
2126 /* --------------------------------------------------------------------------
2127     External (RIF):  Insert or delete n lines at line vpos
2128    -------------------------------------------------------------------------- */
2130   struct frame *f = XFRAME (w->frame);
2131   int x, y, width, height, from_y, to_y, bottom_y;
2133   NSTRACE (ns_scroll_run);
2135   /* begin copy from other terms */
2136   /* Get frame-relative bounding box of the text display area of W,
2137      without mode lines.  Include in this box the left and right
2138      fringe of W.  */
2139   window_box (w, ANY_AREA, &x, &y, &width, &height);
2141   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2142   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2143   bottom_y = y + height;
2145   if (to_y < from_y)
2146     {
2147       /* Scrolling up.  Make sure we don't copy part of the mode
2148          line at the bottom.  */
2149       if (from_y + run->height > bottom_y)
2150         height = bottom_y - from_y;
2151       else
2152         height = run->height;
2153     }
2154   else
2155     {
2156       /* Scrolling down.  Make sure we don't copy over the mode line.
2157          at the bottom.  */
2158       if (to_y + run->height > bottom_y)
2159         height = bottom_y - to_y;
2160       else
2161         height = run->height;
2162     }
2163   /* end copy from other terms */
2165   if (height == 0)
2166       return;
2168   block_input ();
2170   x_clear_cursor (w);
2172   {
2173     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2174     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2175     NSPoint dstOrigin = NSMakePoint (x, to_y);
2177     ns_focus (f, &dstRect, 1);
2178     NSCopyBits (0, srcRect , dstOrigin);
2179     ns_unfocus (f);
2180   }
2182   unblock_input ();
2186 static void
2187 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2188 /* --------------------------------------------------------------------------
2189     External (RIF): preparatory to fringe update after text was updated
2190    -------------------------------------------------------------------------- */
2192   struct frame *f;
2193   int width, height;
2195   NSTRACE (ns_after_update_window_line);
2197   /* begin copy from other terms */
2198   eassert (w);
2200   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2201     desired_row->redraw_fringe_bitmaps_p = 1;
2203   /* When a window has disappeared, make sure that no rest of
2204      full-width rows stays visible in the internal border.  */
2205   if (windows_or_buffers_changed
2206       && desired_row->full_width_p
2207       && (f = XFRAME (w->frame),
2208           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2209           width != 0)
2210       && (height = desired_row->visible_height,
2211           height > 0))
2212     {
2213       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2215       block_input ();
2216       ns_clear_frame_area (f, 0, y, width, height);
2217       ns_clear_frame_area (f,
2218                            FRAME_PIXEL_WIDTH (f) - width,
2219                            y, width, height);
2220       unblock_input ();
2221     }
2225 static void
2226 ns_shift_glyphs_for_insert (struct frame *f,
2227                            int x, int y, int width, int height,
2228                            int shift_by)
2229 /* --------------------------------------------------------------------------
2230     External (RIF): copy an area horizontally, don't worry about clearing src
2231    -------------------------------------------------------------------------- */
2233   NSRect srcRect = NSMakeRect (x, y, width, height);
2234   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2235   NSPoint dstOrigin = dstRect.origin;
2237   NSTRACE (ns_shift_glyphs_for_insert);
2239   ns_focus (f, &dstRect, 1);
2240   NSCopyBits (0, srcRect, dstOrigin);
2241   ns_unfocus (f);
2246 /* ==========================================================================
2248     Character encoding and metrics
2250    ========================================================================== */
2253 static void
2254 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2255 /* --------------------------------------------------------------------------
2256      External (RIF); compute left/right overhang of whole string and set in s
2257    -------------------------------------------------------------------------- */
2259   struct font *font = s->font;
2261   if (s->char2b)
2262     {
2263       struct font_metrics metrics;
2264       unsigned int codes[2];
2265       codes[0] = *(s->char2b);
2266       codes[1] = *(s->char2b + s->nchars - 1);
2268       font->driver->text_extents (font, codes, 2, &metrics);
2269       s->left_overhang = -metrics.lbearing;
2270       s->right_overhang
2271         = metrics.rbearing > metrics.width
2272         ? metrics.rbearing - metrics.width : 0;
2273     }
2274   else
2275     {
2276       s->left_overhang = 0;
2277       if (EQ (font->driver->type, Qns))
2278         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2279           FONT_HEIGHT (font) * 0.2 : 0;
2280       else
2281         s->right_overhang = 0;
2282     }
2287 /* ==========================================================================
2289     Fringe and cursor drawing
2291    ========================================================================== */
2294 extern int max_used_fringe_bitmap;
2295 static void
2296 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2297                       struct draw_fringe_bitmap_params *p)
2298 /* --------------------------------------------------------------------------
2299     External (RIF); fringe-related
2300    -------------------------------------------------------------------------- */
2302   struct frame *f = XFRAME (WINDOW_FRAME (w));
2303   struct face *face = p->face;
2304   static EmacsImage **bimgs = NULL;
2305   static int nBimgs = 0;
2307   /* grow bimgs if needed */
2308   if (nBimgs < max_used_fringe_bitmap)
2309     {
2310       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2311       memset (bimgs + nBimgs, 0,
2312               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2313       nBimgs = max_used_fringe_bitmap;
2314     }
2316   /* Must clip because of partially visible lines.  */
2317   ns_clip_to_row (w, row, ANY_AREA, YES);
2319   if (!p->overlay_p)
2320     {
2321       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2323       /* If the fringe is adjacent to the left (right) scroll bar of a
2324          leftmost (rightmost, respectively) window, then extend its
2325          background to the gap between the fringe and the bar.  */
2326       if ((WINDOW_LEFTMOST_P (w)
2327            && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2328           || (WINDOW_RIGHTMOST_P (w)
2329               && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2330         {
2331           int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2333           if (sb_width > 0)
2334             {
2335               int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2336               int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2337                                     * FRAME_COLUMN_WIDTH (f));
2339               if (bx < 0)
2340                 {
2341                   /* Bitmap fills the fringe.  */
2342                   if (bar_area_x + bar_area_width == p->x)
2343                     bx = bar_area_x + sb_width;
2344                   else if (p->x + p->wd == bar_area_x)
2345                     bx = bar_area_x;
2346                   if (bx >= 0)
2347                     {
2348                       int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2350                       nx = bar_area_width - sb_width;
2351                       by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2352                                                             row->y));
2353                       ny = row->visible_height;
2354                     }
2355                 }
2356               else
2357                 {
2358                   if (bar_area_x + bar_area_width == bx)
2359                     {
2360                       bx = bar_area_x + sb_width;
2361                       nx += bar_area_width - sb_width;
2362                     }
2363                   else if (bx + nx == bar_area_x)
2364                     nx += bar_area_width - sb_width;
2365                 }
2366             }
2367         }
2369       if (bx >= 0 && nx > 0)
2370         {
2371           NSRect r = NSMakeRect (bx, by, nx, ny);
2372           NSRectClip (r);
2373           [ns_lookup_indexed_color (face->background, f) set];
2374           NSRectFill (r);
2375         }
2376     }
2378   if (p->which)
2379     {
2380       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2381       EmacsImage *img = bimgs[p->which - 1];
2383       if (!img)
2384         {
2385           unsigned short *bits = p->bits + p->dh;
2386           int len = p->h;
2387           int i;
2388           unsigned char *cbits = xmalloc (len);
2390           for (i = 0; i < len; i++)
2391             cbits[i] = ~(bits[i] & 0xff);
2392           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2393                                            flip: NO];
2394           bimgs[p->which - 1] = img;
2395           xfree (cbits);
2396         }
2398       NSRectClip (r);
2399       /* Since we composite the bitmap instead of just blitting it, we need
2400          to erase the whole background. */
2401       [ns_lookup_indexed_color(face->background, f) set];
2402       NSRectFill (r);
2403       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2404 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2405       [img drawInRect: r
2406               fromRect: NSZeroRect
2407              operation: NSCompositeSourceOver
2408               fraction: 1.0
2409            respectFlipped: YES
2410                 hints: nil];
2411 #else
2412       {
2413         NSPoint pt = r.origin;
2414         pt.y += p->h;
2415         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2416       }
2417 #endif
2418     }
2419   ns_unfocus (f);
2423 static void
2424 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2425                        int x, int y, enum text_cursor_kinds cursor_type,
2426                        int cursor_width, bool on_p, bool active_p)
2427 /* --------------------------------------------------------------------------
2428      External call (RIF): draw cursor.
2429      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2430    -------------------------------------------------------------------------- */
2432   NSRect r, s;
2433   int fx, fy, h, cursor_height;
2434   struct frame *f = WINDOW_XFRAME (w);
2435   struct glyph *phys_cursor_glyph;
2436   struct glyph *cursor_glyph;
2437   struct face *face;
2438   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2440   /* If cursor is out of bounds, don't draw garbage.  This can happen
2441      in mini-buffer windows when switching between echo area glyphs
2442      and mini-buffer.  */
2444   NSTRACE (dumpcursor);
2446   if (!on_p)
2447     return;
2449   w->phys_cursor_type = cursor_type;
2450   w->phys_cursor_on_p = on_p;
2452   if (cursor_type == NO_CURSOR)
2453     {
2454       w->phys_cursor_width = 0;
2455       return;
2456     }
2458   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2459     {
2460       if (glyph_row->exact_window_width_line_p
2461           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2462         {
2463           glyph_row->cursor_in_fringe_p = 1;
2464           draw_fringe_bitmap (w, glyph_row, 0);
2465         }
2466       return;
2467     }
2469   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2470      (other terminals do it the other way round).  We must set
2471      w->phys_cursor_width to the cursor width.  For bar cursors, that
2472      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2473   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2475   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2476      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2477   if (cursor_type == BAR_CURSOR)
2478     {
2479       if (cursor_width < 1)
2480         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2481       w->phys_cursor_width = cursor_width;
2482     }
2483   /* If we have an HBAR, "cursor_width" MAY specify height. */
2484   else if (cursor_type == HBAR_CURSOR)
2485     {
2486       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2487       fy += h - cursor_height;
2488       h = cursor_height;
2489     }
2491   r.origin.x = fx, r.origin.y = fy;
2492   r.size.height = h;
2493   r.size.width = w->phys_cursor_width;
2495   /* TODO: only needed in rare cases with last-resort font in HELLO..
2496      should we do this more efficiently? */
2497   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2500   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2501   if (face && NS_FACE_BACKGROUND (face)
2502       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2503     {
2504       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2505       hollow_color = FRAME_CURSOR_COLOR (f);
2506     }
2507   else
2508     [FRAME_CURSOR_COLOR (f) set];
2510 #ifdef NS_IMPL_COCOA
2511   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2512            atomic.  Cleaner ways of doing this should be investigated.
2513            One way would be to set a global variable DRAWING_CURSOR
2514            when making the call to draw_phys..(), don't focus in that
2515            case, then move the ns_unfocus() here after that call. */
2516   NSDisableScreenUpdates ();
2517 #endif
2519   switch (cursor_type)
2520     {
2521     case NO_CURSOR:
2522       break;
2523     case FILLED_BOX_CURSOR:
2524       NSRectFill (r);
2525       break;
2526     case HOLLOW_BOX_CURSOR:
2527       NSRectFill (r);
2528       [hollow_color set];
2529       NSRectFill (NSInsetRect (r, 1, 1));
2530       [FRAME_CURSOR_COLOR (f) set];
2531       break;
2532     case HBAR_CURSOR:
2533       NSRectFill (r);
2534       break;
2535     case BAR_CURSOR:
2536       s = r;
2537       /* If the character under cursor is R2L, draw the bar cursor
2538          on the right of its glyph, rather than on the left.  */
2539       cursor_glyph = get_phys_cursor_glyph (w);
2540       if ((cursor_glyph->resolved_level & 1) != 0)
2541         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2543       NSRectFill (s);
2544       break;
2545     }
2546   ns_unfocus (f);
2548   /* draw the character under the cursor */
2549   if (cursor_type != NO_CURSOR)
2550     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2552 #ifdef NS_IMPL_COCOA
2553   NSEnableScreenUpdates ();
2554 #endif
2559 static void
2560 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2561 /* --------------------------------------------------------------------------
2562      External (RIF): Draw a vertical line.
2563    -------------------------------------------------------------------------- */
2565   struct frame *f = XFRAME (WINDOW_FRAME (w));
2566   struct face *face;
2567   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2569   NSTRACE (ns_draw_vertical_window_border);
2571   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2572   if (face)
2573       [ns_lookup_indexed_color(face->foreground, f) set];
2575   ns_focus (f, &r, 1);
2576   NSRectFill(r);
2577   ns_unfocus (f);
2581 static void
2582 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2583 /* --------------------------------------------------------------------------
2584      External (RIF): Draw a window divider.
2585    -------------------------------------------------------------------------- */
2587   struct frame *f = XFRAME (WINDOW_FRAME (w));
2588   struct face *face;
2589   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2591   NSTRACE (ns_draw_window_divider);
2593   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2594   if (face)
2595       [ns_lookup_indexed_color(face->foreground, f) set];
2597   ns_focus (f, &r, 1);
2598   NSRectFill(r);
2599   ns_unfocus (f);
2603 void
2604 show_hourglass (struct atimer *timer)
2606   if (hourglass_shown_p)
2607     return;
2609   block_input ();
2611   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2613   hourglass_shown_p = 1;
2614   unblock_input ();
2618 void
2619 hide_hourglass (void)
2621   if (!hourglass_shown_p)
2622     return;
2624   block_input ();
2626   /* TODO: remove NSProgressIndicator from all frames */
2628   hourglass_shown_p = 0;
2629   unblock_input ();
2634 /* ==========================================================================
2636     Glyph drawing operations
2638    ========================================================================== */
2640 static int
2641 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2642 /* --------------------------------------------------------------------------
2643     Wrapper utility to account for internal border width on full-width lines,
2644     and allow top full-width rows to hit the frame top.  nr should be pointer
2645     to two successive NSRects.  Number of rects actually used is returned.
2646    -------------------------------------------------------------------------- */
2648   int n = get_glyph_string_clip_rects (s, nr, 2);
2649   return n;
2652 /* --------------------------------------------------------------------
2653    Draw a wavy line under glyph string s. The wave fills wave_height
2654    pixels from y.
2656                     x          wave_length = 2
2657                                  --
2658                 y    *   *   *   *   *
2659                      |* * * * * * * * *
2660     wave_height = 3  | *   *   *   *
2661   --------------------------------------------------------------------- */
2663 static void
2664 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2666   int wave_height = 3, wave_length = 2;
2667   int y, dx, dy, odd, xmax;
2668   NSPoint a, b;
2669   NSRect waveClip;
2671   dx = wave_length;
2672   dy = wave_height - 1;
2673   y =  s->ybase - wave_height + 3;
2674   xmax = x + width;
2676   /* Find and set clipping rectangle */
2677   waveClip = NSMakeRect (x, y, width, wave_height);
2678   [[NSGraphicsContext currentContext] saveGraphicsState];
2679   NSRectClip (waveClip);
2681   /* Draw the waves */
2682   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2683   b.x = a.x + dx;
2684   odd = (int)(a.x/dx) % 2;
2685   a.y = b.y = y + 0.5;
2687   if (odd)
2688     a.y += dy;
2689   else
2690     b.y += dy;
2692   while (a.x <= xmax)
2693     {
2694       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2695       a.x = b.x, a.y = b.y;
2696       b.x += dx, b.y = y + 0.5 + odd*dy;
2697       odd = !odd;
2698     }
2700   /* Restore previous clipping rectangle(s) */
2701   [[NSGraphicsContext currentContext] restoreGraphicsState];
2706 void
2707 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2708                          NSColor *defaultCol, CGFloat width, CGFloat x)
2709 /* --------------------------------------------------------------------------
2710    Draw underline, overline, and strike-through on glyph string s.
2711    -------------------------------------------------------------------------- */
2713   if (s->for_overlaps)
2714     return;
2716   /* Do underline. */
2717   if (face->underline_p)
2718     {
2719       if (s->face->underline_type == FACE_UNDER_WAVE)
2720         {
2721           if (face->underline_defaulted_p)
2722             [defaultCol set];
2723           else
2724             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2726           ns_draw_underwave (s, width, x);
2727         }
2728       else if (s->face->underline_type == FACE_UNDER_LINE)
2729         {
2731           NSRect r;
2732           unsigned long thickness, position;
2734           /* If the prev was underlined, match its appearance. */
2735           if (s->prev && s->prev->face->underline_p
2736               && s->prev->face->underline_type == FACE_UNDER_LINE
2737               && s->prev->underline_thickness > 0)
2738             {
2739               thickness = s->prev->underline_thickness;
2740               position = s->prev->underline_position;
2741             }
2742           else
2743             {
2744               struct font *font;
2745               unsigned long descent;
2747               font=s->font;
2748               descent = s->y + s->height - s->ybase;
2750               /* Use underline thickness of font, defaulting to 1. */
2751               thickness = (font && font->underline_thickness > 0)
2752                 ? font->underline_thickness : 1;
2754               /* Determine the offset of underlining from the baseline. */
2755               if (x_underline_at_descent_line)
2756                 position = descent - thickness;
2757               else if (x_use_underline_position_properties
2758                        && font && font->underline_position >= 0)
2759                 position = font->underline_position;
2760               else if (font)
2761                 position = lround (font->descent / 2);
2762               else
2763                 position = underline_minimum_offset;
2765               position = max (position, underline_minimum_offset);
2767               /* Ensure underlining is not cropped. */
2768               if (descent <= position)
2769                 {
2770                   position = descent - 1;
2771                   thickness = 1;
2772                 }
2773               else if (descent < position + thickness)
2774                 thickness = 1;
2775             }
2777           s->underline_thickness = thickness;
2778           s->underline_position = position;
2780           r = NSMakeRect (x, s->ybase + position, width, thickness);
2782           if (face->underline_defaulted_p)
2783             [defaultCol set];
2784           else
2785             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2786           NSRectFill (r);
2787         }
2788     }
2789   /* Do overline. We follow other terms in using a thickness of 1
2790      and ignoring overline_margin. */
2791   if (face->overline_p)
2792     {
2793       NSRect r;
2794       r = NSMakeRect (x, s->y, width, 1);
2796       if (face->overline_color_defaulted_p)
2797         [defaultCol set];
2798       else
2799         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2800       NSRectFill (r);
2801     }
2803   /* Do strike-through.  We follow other terms for thickness and
2804      vertical position.*/
2805   if (face->strike_through_p)
2806     {
2807       NSRect r;
2808       unsigned long dy;
2810       dy = lrint ((s->height - 1) / 2);
2811       r = NSMakeRect (x, s->y + dy, width, 1);
2813       if (face->strike_through_color_defaulted_p)
2814         [defaultCol set];
2815       else
2816         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2817       NSRectFill (r);
2818     }
2821 static void
2822 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2823              char left_p, char right_p)
2824 /* --------------------------------------------------------------------------
2825     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2826     Note we can't just use an NSDrawRect command, because of the possibility
2827     of some sides not being drawn, and because the rect will be filled.
2828    -------------------------------------------------------------------------- */
2830   NSRect s = r;
2831   [col set];
2833   /* top, bottom */
2834   s.size.height = thickness;
2835   NSRectFill (s);
2836   s.origin.y += r.size.height - thickness;
2837   NSRectFill (s);
2839   s.size.height = r.size.height;
2840   s.origin.y = r.origin.y;
2842   /* left, right (optional) */
2843   s.size.width = thickness;
2844   if (left_p)
2845     NSRectFill (s);
2846   if (right_p)
2847     {
2848       s.origin.x += r.size.width - thickness;
2849       NSRectFill (s);
2850     }
2854 static void
2855 ns_draw_relief (NSRect r, int thickness, char raised_p,
2856                char top_p, char bottom_p, char left_p, char right_p,
2857                struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859     Draw a relief rect inside r, optionally leaving some sides open.
2860     Note we can't just use an NSDrawBezel command, because of the possibility
2861     of some sides not being drawn, and because the rect will be filled.
2862    -------------------------------------------------------------------------- */
2864   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2865   NSColor *newBaseCol = nil;
2866   NSRect sr = r;
2868   NSTRACE (ns_draw_relief);
2870   /* set up colors */
2872   if (s->face->use_box_color_for_shadows_p)
2873     {
2874       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2875     }
2876 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2877            && s->img->pixmap
2878            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2879        {
2880          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2881        } */
2882   else
2883     {
2884       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2885     }
2887   if (newBaseCol == nil)
2888     newBaseCol = [NSColor grayColor];
2890   if (newBaseCol != baseCol)  /* TODO: better check */
2891     {
2892       [baseCol release];
2893       baseCol = [newBaseCol retain];
2894       [lightCol release];
2895       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2896       [darkCol release];
2897       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2898     }
2900   [(raised_p ? lightCol : darkCol) set];
2902   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2904   /* top */
2905   sr.size.height = thickness;
2906   if (top_p) NSRectFill (sr);
2908   /* left */
2909   sr.size.height = r.size.height;
2910   sr.size.width = thickness;
2911   if (left_p) NSRectFill (sr);
2913   [(raised_p ? darkCol : lightCol) set];
2915   /* bottom */
2916   sr.size.width = r.size.width;
2917   sr.size.height = thickness;
2918   sr.origin.y += r.size.height - thickness;
2919   if (bottom_p) NSRectFill (sr);
2921   /* right */
2922   sr.size.height = r.size.height;
2923   sr.origin.y = r.origin.y;
2924   sr.size.width = thickness;
2925   sr.origin.x += r.size.width - thickness;
2926   if (right_p) NSRectFill (sr);
2930 static void
2931 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2932 /* --------------------------------------------------------------------------
2933       Function modeled after x_draw_glyph_string_box ().
2934       Sets up parameters for drawing.
2935    -------------------------------------------------------------------------- */
2937   int right_x, last_x;
2938   char left_p, right_p;
2939   struct glyph *last_glyph;
2940   NSRect r;
2941   int thickness;
2942   struct face *face;
2944   if (s->hl == DRAW_MOUSE_FACE)
2945     {
2946       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2947       if (!face)
2948         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2949     }
2950   else
2951     face = s->face;
2953   thickness = face->box_line_width;
2955   NSTRACE (ns_dumpglyphs_box_or_relief);
2957   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2958             ? WINDOW_RIGHT_EDGE_X (s->w)
2959             : window_box_right (s->w, s->area));
2960   last_glyph = (s->cmp || s->img
2961                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2963   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2964               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2966   left_p = (s->first_glyph->left_box_line_p
2967             || (s->hl == DRAW_MOUSE_FACE
2968                 && (s->prev == NULL || s->prev->hl != s->hl)));
2969   right_p = (last_glyph->right_box_line_p
2970              || (s->hl == DRAW_MOUSE_FACE
2971                  && (s->next == NULL || s->next->hl != s->hl)));
2973   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2975   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2976   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2977     {
2978       ns_draw_box (r, abs (thickness),
2979                    ns_lookup_indexed_color (face->box_color, s->f),
2980                   left_p, right_p);
2981     }
2982   else
2983     {
2984       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2985                      1, 1, left_p, right_p, s);
2986     }
2990 static void
2991 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2992 /* --------------------------------------------------------------------------
2993       Modeled after x_draw_glyph_string_background, which draws BG in
2994       certain cases.  Others are left to the text rendering routine.
2995    -------------------------------------------------------------------------- */
2997   NSTRACE (ns_maybe_dumpglyphs_background);
2999   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3000     {
3001       int box_line_width = max (s->face->box_line_width, 0);
3002       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3003           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3004         {
3005           struct face *face;
3006           if (s->hl == DRAW_MOUSE_FACE)
3007             {
3008               face = FACE_FROM_ID (s->f,
3009                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3010               if (!face)
3011                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3012             }
3013           else
3014             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3015           if (!face->stipple)
3016             [(NS_FACE_BACKGROUND (face) != 0
3017               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3018               : FRAME_BACKGROUND_COLOR (s->f)) set];
3019           else
3020             {
3021               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3022               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3023             }
3025           if (s->hl != DRAW_CURSOR)
3026             {
3027               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3028                                     s->background_width,
3029                                     s->height-2*box_line_width);
3030               NSRectFill (r);
3031             }
3033           s->background_filled_p = 1;
3034         }
3035     }
3039 static void
3040 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3041 /* --------------------------------------------------------------------------
3042       Renders an image and associated borders.
3043    -------------------------------------------------------------------------- */
3045   EmacsImage *img = s->img->pixmap;
3046   int box_line_vwidth = max (s->face->box_line_width, 0);
3047   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3048   int bg_x, bg_y, bg_height;
3049   int th;
3050   char raised_p;
3051   NSRect br;
3052   struct face *face;
3053   NSColor *tdCol;
3055   NSTRACE (ns_dumpglyphs_image);
3057   if (s->face->box != FACE_NO_BOX
3058       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3059     x += abs (s->face->box_line_width);
3061   bg_x = x;
3062   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3063   bg_height = s->height;
3064   /* other terms have this, but was causing problems w/tabbar mode */
3065   /* - 2 * box_line_vwidth; */
3067   if (s->slice.x == 0) x += s->img->hmargin;
3068   if (s->slice.y == 0) y += s->img->vmargin;
3070   /* Draw BG: if we need larger area than image itself cleared, do that,
3071      otherwise, since we composite the image under NS (instead of mucking
3072      with its background color), we must clear just the image area. */
3073   if (s->hl == DRAW_MOUSE_FACE)
3074     {
3075       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3076       if (!face)
3077        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3078     }
3079   else
3080     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3082   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3084   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3085       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3086     {
3087       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3088       s->background_filled_p = 1;
3089     }
3090   else
3091     {
3092       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3093     }
3095   NSRectFill (br);
3097   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3098   if (img != nil)
3099     {
3100 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
3101       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3102       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3103                               s->slice.width, s->slice.height);
3104       [img drawInRect: dr
3105              fromRect: ir
3106              operation: NSCompositeSourceOver
3107               fraction: 1.0
3108            respectFlipped: YES
3109                 hints: nil];
3110 #else
3111       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3112                   operation: NSCompositeSourceOver];
3113 #endif
3114     }
3116   if (s->hl == DRAW_CURSOR)
3117     {
3118     [FRAME_CURSOR_COLOR (s->f) set];
3119     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3120       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3121     else
3122       /* Currently on NS img->mask is always 0. Since
3123          get_window_cursor_type specifies a hollow box cursor when on
3124          a non-masked image we never reach this clause. But we put it
3125          in in anticipation of better support for image masks on
3126          NS. */
3127       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3128     }
3129   else
3130     {
3131       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3132     }
3134   /* Draw underline, overline, strike-through. */
3135   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3137   /* Draw relief, if requested */
3138   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3139     {
3140       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3141         {
3142           th = tool_bar_button_relief >= 0 ?
3143             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3144           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3145         }
3146       else
3147         {
3148           th = abs (s->img->relief);
3149           raised_p = (s->img->relief > 0);
3150         }
3152       r.origin.x = x - th;
3153       r.origin.y = y - th;
3154       r.size.width = s->slice.width + 2*th-1;
3155       r.size.height = s->slice.height + 2*th-1;
3156       ns_draw_relief (r, th, raised_p,
3157                       s->slice.y == 0,
3158                       s->slice.y + s->slice.height == s->img->height,
3159                       s->slice.x == 0,
3160                       s->slice.x + s->slice.width == s->img->width, s);
3161     }
3163   /* If there is no mask, the background won't be seen,
3164      so draw a rectangle on the image for the cursor.
3165      Do this for all images, getting transparency right is not reliable.  */
3166   if (s->hl == DRAW_CURSOR)
3167     {
3168       int thickness = abs (s->img->relief);
3169       if (thickness == 0) thickness = 1;
3170       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3171     }
3175 static void
3176 ns_dumpglyphs_stretch (struct glyph_string *s)
3178   NSRect r[2];
3179   int n, i;
3180   struct face *face;
3181   NSColor *fgCol, *bgCol;
3183   if (!s->background_filled_p)
3184     {
3185       n = ns_get_glyph_string_clip_rect (s, r);
3186       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3188       ns_focus (s->f, r, n);
3190       if (s->hl == DRAW_MOUSE_FACE)
3191        {
3192          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3193          if (!face)
3194            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3195        }
3196       else
3197        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3199       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3200       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3202       for (i = 0; i < n; ++i)
3203         {
3204           if (!s->row->full_width_p)
3205             {
3206               int overrun, leftoverrun;
3208               /* truncate to avoid overwriting fringe and/or scrollbar */
3209               overrun = max (0, (s->x + s->background_width)
3210                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3211                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3212               r[i].size.width -= overrun;
3214               /* truncate to avoid overwriting to left of the window box */
3215               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3216                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3218               if (leftoverrun > 0)
3219                 {
3220                   r[i].origin.x += leftoverrun;
3221                   r[i].size.width -= leftoverrun;
3222                 }
3224               /* XXX: Try to work between problem where a stretch glyph on
3225                  a partially-visible bottom row will clear part of the
3226                  modeline, and another where list-buffers headers and similar
3227                  rows erroneously have visible_height set to 0.  Not sure
3228                  where this is coming from as other terms seem not to show. */
3229               r[i].size.height = min (s->height, s->row->visible_height);
3230             }
3232           [bgCol set];
3234           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3235              overwriting cursor (usually when cursor on a tab) */
3236           if (s->hl == DRAW_CURSOR)
3237             {
3238               CGFloat x, width;
3240               x = r[i].origin.x;
3241               width = s->w->phys_cursor_width;
3242               r[i].size.width -= width;
3243               r[i].origin.x += width;
3245               NSRectFill (r[i]);
3247               /* Draw overlining, etc. on the cursor. */
3248               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3249                 ns_draw_text_decoration (s, face, bgCol, width, x);
3250               else
3251                 ns_draw_text_decoration (s, face, fgCol, width, x);
3252             }
3253           else
3254             {
3255               NSRectFill (r[i]);
3256             }
3258           /* Draw overlining, etc. on the stretch glyph (or the part
3259              of the stretch glyph after the cursor). */
3260           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3261                                    r[i].origin.x);
3262         }
3263       ns_unfocus (s->f);
3264       s->background_filled_p = 1;
3265     }
3269 static void
3270 ns_draw_glyph_string (struct glyph_string *s)
3271 /* --------------------------------------------------------------------------
3272       External (RIF): Main draw-text call.
3273    -------------------------------------------------------------------------- */
3275   /* TODO (optimize): focus for box and contents draw */
3276   NSRect r[2];
3277   int n, flags;
3278   char box_drawn_p = 0;
3279   struct font *font = s->face->font;
3280   if (! font) font = FRAME_FONT (s->f);
3282   NSTRACE (ns_draw_glyph_string);
3284   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3285     {
3286       int width;
3287       struct glyph_string *next;
3289       for (width = 0, next = s->next;
3290            next && width < s->right_overhang;
3291            width += next->width, next = next->next)
3292         if (next->first_glyph->type != IMAGE_GLYPH)
3293           {
3294             if (next->first_glyph->type != STRETCH_GLYPH)
3295               {
3296                 n = ns_get_glyph_string_clip_rect (s->next, r);
3297                 ns_focus (s->f, r, n);
3298                 ns_maybe_dumpglyphs_background (s->next, 1);
3299                 ns_unfocus (s->f);
3300               }
3301             else
3302               {
3303                 ns_dumpglyphs_stretch (s->next);
3304               }
3305             next->num_clips = 0;
3306           }
3307     }
3309   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3310         && (s->first_glyph->type == CHAR_GLYPH
3311             || s->first_glyph->type == COMPOSITE_GLYPH))
3312     {
3313       n = ns_get_glyph_string_clip_rect (s, r);
3314       ns_focus (s->f, r, n);
3315       ns_maybe_dumpglyphs_background (s, 1);
3316       ns_dumpglyphs_box_or_relief (s);
3317       ns_unfocus (s->f);
3318       box_drawn_p = 1;
3319     }
3321   switch (s->first_glyph->type)
3322     {
3324     case IMAGE_GLYPH:
3325       n = ns_get_glyph_string_clip_rect (s, r);
3326       ns_focus (s->f, r, n);
3327       ns_dumpglyphs_image (s, r[0]);
3328       ns_unfocus (s->f);
3329       break;
3331     case STRETCH_GLYPH:
3332       ns_dumpglyphs_stretch (s);
3333       break;
3335     case CHAR_GLYPH:
3336     case COMPOSITE_GLYPH:
3337       n = ns_get_glyph_string_clip_rect (s, r);
3338       ns_focus (s->f, r, n);
3340       if (s->for_overlaps || (s->cmp_from > 0
3341                               && ! s->first_glyph->u.cmp.automatic))
3342         s->background_filled_p = 1;
3343       else
3344         ns_maybe_dumpglyphs_background
3345           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3347       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3348         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3349          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3350           NS_DUMPGLYPH_NORMAL));
3352       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3353         {
3354           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3355           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3356           NS_FACE_FOREGROUND (s->face) = tmp;
3357         }
3359       font->driver->draw
3360         (s, 0, s->nchars, s->x, s->y,
3361          (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3362          || flags == NS_DUMPGLYPH_MOUSEFACE);
3364       {
3365         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3366                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3367                                                    s->f)
3368                         : FRAME_FOREGROUND_COLOR (s->f));
3369         [col set];
3371         /* Draw underline, overline, strike-through. */
3372         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3373       }
3375       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3376         {
3377           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3378           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3379           NS_FACE_FOREGROUND (s->face) = tmp;
3380         }
3382       ns_unfocus (s->f);
3383       break;
3385     case GLYPHLESS_GLYPH:
3386       n = ns_get_glyph_string_clip_rect (s, r);
3387       ns_focus (s->f, r, n);
3389       if (s->for_overlaps || (s->cmp_from > 0
3390                               && ! s->first_glyph->u.cmp.automatic))
3391         s->background_filled_p = 1;
3392       else
3393         ns_maybe_dumpglyphs_background
3394           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3395       /* ... */
3396       /* Not yet implemented.  */
3397       /* ... */
3398       ns_unfocus (s->f);
3399       break;
3401     default:
3402       emacs_abort ();
3403     }
3405   /* Draw box if not done already. */
3406   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3407     {
3408       n = ns_get_glyph_string_clip_rect (s, r);
3409       ns_focus (s->f, r, n);
3410       ns_dumpglyphs_box_or_relief (s);
3411       ns_unfocus (s->f);
3412     }
3414   s->num_clips = 0;
3419 /* ==========================================================================
3421     Event loop
3423    ========================================================================== */
3426 static void
3427 ns_send_appdefined (int value)
3428 /* --------------------------------------------------------------------------
3429     Internal: post an appdefined event which EmacsApp-sendEvent will
3430               recognize and take as a command to halt the event loop.
3431    -------------------------------------------------------------------------- */
3433   /*NSTRACE (ns_send_appdefined); */
3435 #ifdef NS_IMPL_GNUSTEP
3436   // GNUStep needs postEvent to happen on the main thread.
3437   if (! [[NSThread currentThread] isMainThread])
3438     {
3439       EmacsApp *app = (EmacsApp *)NSApp;
3440       app->nextappdefined = value;
3441       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3442                             withObject:nil
3443                          waitUntilDone:YES];
3444       return;
3445     }
3446 #endif
3448   /* Only post this event if we haven't already posted one.  This will end
3449        the [NXApp run] main loop after having processed all events queued at
3450        this moment.  */
3451   if (send_appdefined)
3452     {
3453       NSEvent *nxev;
3455       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3456       send_appdefined = NO;
3458       /* Don't need wakeup timer any more */
3459       if (timed_entry)
3460         {
3461           [timed_entry invalidate];
3462           [timed_entry release];
3463           timed_entry = nil;
3464         }
3466       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3467                                 location: NSMakePoint (0, 0)
3468                            modifierFlags: 0
3469                                timestamp: 0
3470                             windowNumber: [[NSApp mainWindow] windowNumber]
3471                                  context: [NSApp context]
3472                                  subtype: 0
3473                                    data1: value
3474                                    data2: 0];
3476       /* Post an application defined event on the event queue.  When this is
3477          received the [NXApp run] will return, thus having processed all
3478          events which are currently queued.  */
3479       [NSApp postEvent: nxev atStart: NO];
3480     }
3483 #ifdef HAVE_NATIVE_FS
3484 static void
3485 check_native_fs ()
3487   Lisp_Object frame, tail;
3489   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3490     return;
3492   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3494   FOR_EACH_FRAME (tail, frame)
3495     {
3496       struct frame *f = XFRAME (frame);
3497       if (FRAME_NS_P (f))
3498         {
3499           EmacsView *view = FRAME_NS_VIEW (f);
3500           [view updateCollectionBehaviour];
3501         }
3502     }
3504 #endif
3506 /* GNUStep and OSX <= 10.4 does not have cancelTracking.  */
3507 #if defined (NS_IMPL_COCOA) && \
3508   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
3509 /* Check if menu open should be cancelled or continued as normal.  */
3510 void
3511 ns_check_menu_open (NSMenu *menu)
3513   /* Click in menu bar? */
3514   NSArray *a = [[NSApp mainMenu] itemArray];
3515   int i;
3516   BOOL found = NO;
3518   if (menu == nil) // Menu tracking ended.
3519     {
3520       if (menu_will_open_state == MENU_OPENING)
3521         menu_will_open_state = MENU_NONE;
3522       return;
3523     }
3525   for (i = 0; ! found && i < [a count]; i++)
3526     found = menu == [[a objectAtIndex:i] submenu];
3527   if (found)
3528     {
3529       if (menu_will_open_state == MENU_NONE && emacs_event)
3530         {
3531           NSEvent *theEvent = [NSApp currentEvent];
3532           struct frame *emacsframe = SELECTED_FRAME ();
3534           [menu cancelTracking];
3535           menu_will_open_state = MENU_PENDING;
3536           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3537           EV_TRAILER (theEvent);
3539           CGEventRef ourEvent = CGEventCreate (NULL);
3540           menu_mouse_point = CGEventGetLocation (ourEvent);
3541           CFRelease (ourEvent);
3542         }
3543       else if (menu_will_open_state == MENU_OPENING)
3544         {
3545           menu_will_open_state = MENU_NONE;
3546         }
3547     }
3550 /* Redo saved menu click if state is MENU_PENDING.  */
3551 void
3552 ns_check_pending_open_menu ()
3554   if (menu_will_open_state == MENU_PENDING)
3555     {
3556       CGEventSourceRef source
3557         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3559       CGEventRef event = CGEventCreateMouseEvent (source,
3560                                                   kCGEventLeftMouseDown,
3561                                                   menu_mouse_point,
3562                                                   kCGMouseButtonLeft);
3563       CGEventSetType (event, kCGEventLeftMouseDown);
3564       CGEventPost (kCGHIDEventTap, event);
3565       CFRelease (event);
3566       CFRelease (source);
3568       menu_will_open_state = MENU_OPENING;
3569     }
3571 #endif /* NS_IMPL_COCOA) && >= MAC_OS_X_VERSION_10_5 */
3573 static int
3574 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3575 /* --------------------------------------------------------------------------
3576      External (hook): Post an event to ourself and keep reading events until
3577      we read it back again.  In effect process all events which were waiting.
3578      From 21+ we have to manage the event buffer ourselves.
3579    -------------------------------------------------------------------------- */
3581   struct input_event ev;
3582   int nevents;
3584 /* NSTRACE (ns_read_socket); */
3586 #ifdef HAVE_NATIVE_FS
3587   check_native_fs ();
3588 #endif
3590   if ([NSApp modalWindow] != nil)
3591     return -1;
3593   if (hold_event_q.nr > 0)
3594     {
3595       int i;
3596       for (i = 0; i < hold_event_q.nr; ++i)
3597         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3598       hold_event_q.nr = 0;
3599       return i;
3600     }
3602   block_input ();
3603   n_emacs_events_pending = 0;
3604   EVENT_INIT (ev);
3605   emacs_event = &ev;
3606   q_event_ptr = hold_quit;
3608   /* we manage autorelease pools by allocate/reallocate each time around
3609      the loop; strict nesting is occasionally violated but seems not to
3610      matter.. earlier methods using full nesting caused major memory leaks */
3611   [outerpool release];
3612   outerpool = [[NSAutoreleasePool alloc] init];
3614   /* If have pending open-file requests, attend to the next one of those. */
3615   if (ns_pending_files && [ns_pending_files count] != 0
3616       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3617     {
3618       [ns_pending_files removeObjectAtIndex: 0];
3619     }
3620   /* Deal with pending service requests. */
3621   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3622     && [(EmacsApp *)
3623          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3624                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3625     {
3626       [ns_pending_service_names removeObjectAtIndex: 0];
3627       [ns_pending_service_args removeObjectAtIndex: 0];
3628     }
3629   else
3630     {
3631       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3632          to ourself, otherwise [NXApp run] will never exit.  */
3633       send_appdefined = YES;
3634       ns_send_appdefined (-1);
3636       if (++apploopnr != 1)
3637         {
3638           emacs_abort ();
3639         }
3640       [NSApp run];
3641       --apploopnr;
3642     }
3644   nevents = n_emacs_events_pending;
3645   n_emacs_events_pending = 0;
3646   emacs_event = q_event_ptr = NULL;
3647   unblock_input ();
3649   return nevents;
3654 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3655            fd_set *exceptfds, struct timespec const *timeout,
3656            sigset_t const *sigmask)
3657 /* --------------------------------------------------------------------------
3658      Replacement for select, checking for events
3659    -------------------------------------------------------------------------- */
3661   int result;
3662   int t, k, nr = 0;
3663   struct input_event event;
3664   char c;
3666 /*  NSTRACE (ns_select); */
3668 #ifdef HAVE_NATIVE_FS
3669   check_native_fs ();
3670 #endif
3672   if (hold_event_q.nr > 0)
3673     {
3674       /* We already have events pending. */
3675       raise (SIGIO);
3676       errno = EINTR;
3677       return -1;
3678     }
3680   for (k = 0; k < nfds+1; k++)
3681     {
3682       if (readfds && FD_ISSET(k, readfds)) ++nr;
3683       if (writefds && FD_ISSET(k, writefds)) ++nr;
3684     }
3686   if (NSApp == nil
3687       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3688     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3690   [outerpool release];
3691   outerpool = [[NSAutoreleasePool alloc] init];
3694   send_appdefined = YES;
3695   if (nr > 0)
3696     {
3697       pthread_mutex_lock (&select_mutex);
3698       select_nfds = nfds;
3699       select_valid = 0;
3700       if (readfds)
3701         {
3702           select_readfds = *readfds;
3703           select_valid += SELECT_HAVE_READ;
3704         }
3705       if (writefds)
3706         {
3707           select_writefds = *writefds;
3708           select_valid += SELECT_HAVE_WRITE;
3709         }
3711       if (timeout)
3712         {
3713           select_timeout = *timeout;
3714           select_valid += SELECT_HAVE_TMO;
3715         }
3717       pthread_mutex_unlock (&select_mutex);
3719       /* Inform fd_handler that select should be called */
3720       c = 'g';
3721       emacs_write_sig (selfds[1], &c, 1);
3722     }
3723   else if (nr == 0 && timeout)
3724     {
3725       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3726       double time = timespectod (*timeout);
3727       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3728                                                       target: NSApp
3729                                                     selector:
3730                                   @selector (timeout_handler:)
3731                                                     userInfo: 0
3732                                                      repeats: NO]
3733                       retain];
3734     }
3735   else /* No timeout and no file descriptors, can this happen?  */
3736     {
3737       /* Send appdefined so we exit from the loop */
3738       ns_send_appdefined (-1);
3739     }
3741   EVENT_INIT (event);
3742   block_input ();
3743   emacs_event = &event;
3744   if (++apploopnr != 1)
3745     {
3746       emacs_abort ();
3747     }
3748   [NSApp run];
3749   --apploopnr;
3750   emacs_event = NULL;
3751   if (nr > 0 && readfds)
3752     {
3753       c = 's';
3754       emacs_write_sig (selfds[1], &c, 1);
3755     }
3756   unblock_input ();
3758   t = last_appdefined_event_data;
3760   if (t != NO_APPDEFINED_DATA)
3761     {
3762       last_appdefined_event_data = NO_APPDEFINED_DATA;
3764       if (t == -2)
3765         {
3766           /* The NX_APPDEFINED event we received was a timeout. */
3767           result = 0;
3768         }
3769       else if (t == -1)
3770         {
3771           /* The NX_APPDEFINED event we received was the result of
3772              at least one real input event arriving.  */
3773           errno = EINTR;
3774           result = -1;
3775         }
3776       else
3777         {
3778           /* Received back from select () in fd_handler; copy the results */
3779           pthread_mutex_lock (&select_mutex);
3780           if (readfds) *readfds = select_readfds;
3781           if (writefds) *writefds = select_writefds;
3782           pthread_mutex_unlock (&select_mutex);
3783           result = t;
3784         }
3785     }
3786   else
3787     {
3788       errno = EINTR;
3789       result = -1;
3790     }
3792   return result;
3797 /* ==========================================================================
3799     Scrollbar handling
3801    ========================================================================== */
3804 static void
3805 ns_set_vertical_scroll_bar (struct window *window,
3806                            int portion, int whole, int position)
3807 /* --------------------------------------------------------------------------
3808       External (hook): Update or add scrollbar
3809    -------------------------------------------------------------------------- */
3811   Lisp_Object win;
3812   NSRect r, v;
3813   struct frame *f = XFRAME (WINDOW_FRAME (window));
3814   EmacsView *view = FRAME_NS_VIEW (f);
3815   int window_y, window_height;
3816   int top, left, height, width, sb_width, sb_left;
3817   EmacsScroller *bar;
3818   BOOL fringe_extended_p;
3820   /* optimization; display engine sends WAY too many of these.. */
3821   if (!NILP (window->vertical_scroll_bar))
3822     {
3823       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3824       if ([bar checkSamePosition: position portion: portion whole: whole])
3825         {
3826           if (view->scrollbarsNeedingUpdate == 0)
3827             {
3828               if (!windows_or_buffers_changed)
3829                   return;
3830             }
3831           else
3832             view->scrollbarsNeedingUpdate--;
3833         }
3834     }
3836   NSTRACE (ns_set_vertical_scroll_bar);
3838   /* Get dimensions.  */
3839   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3840   top = window_y;
3841   height = window_height;
3842   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3843   left = WINDOW_SCROLL_BAR_AREA_X (window);
3845   /* allow for displaying a skinnier scrollbar than char area allotted */
3846   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3847     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3848   sb_left = left;
3850   r = NSMakeRect (sb_left, top, sb_width, height);
3851   /* the parent view is flipped, so we need to flip y value */
3852   v = [view frame];
3853   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3855   fringe_extended_p = WINDOW_FRINGE_EXTENDED_P (window);
3857   XSETWINDOW (win, window);
3858   block_input ();
3860   /* we want at least 5 lines to display a scrollbar */
3861   if (WINDOW_TOTAL_LINES (window) < 5)
3862     {
3863       if (!NILP (window->vertical_scroll_bar))
3864         {
3865           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3866           [bar removeFromSuperview];
3867           wset_vertical_scroll_bar (window, Qnil);
3868         }
3869       ns_clear_frame_area (f, sb_left, top, width, height);
3870       unblock_input ();
3871       return;
3872     }
3874   if (NILP (window->vertical_scroll_bar))
3875     {
3876       if (width > 0 && height > 0)
3877         {
3878           if (fringe_extended_p)
3879             ns_clear_frame_area (f, sb_left, top, sb_width, height);
3880           else
3881             ns_clear_frame_area (f, left, top, width, height);
3882         }
3884       bar = [[EmacsScroller alloc] initFrame: r window: win];
3885       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3886     }
3887   else
3888     {
3889       NSRect oldRect;
3890       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3891       oldRect = [bar frame];
3892       r.size.width = oldRect.size.width;
3893       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3894         {
3895           if (oldRect.origin.x != r.origin.x)
3896               ns_clear_frame_area (f, sb_left, top, width, height);
3897           [bar setFrame: r];
3898         }
3899     }
3901   [bar setPosition: position portion: portion whole: whole];
3902   unblock_input ();
3906 static void
3907 ns_condemn_scroll_bars (struct frame *f)
3908 /* --------------------------------------------------------------------------
3909      External (hook): arrange for all frame's scrollbars to be removed
3910      at next call to judge_scroll_bars, except for those redeemed.
3911    -------------------------------------------------------------------------- */
3913   int i;
3914   id view;
3915   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3917   NSTRACE (ns_condemn_scroll_bars);
3919   for (i =[subviews count]-1; i >= 0; i--)
3920     {
3921       view = [subviews objectAtIndex: i];
3922       if ([view isKindOfClass: [EmacsScroller class]])
3923         [view condemn];
3924     }
3928 static void
3929 ns_redeem_scroll_bar (struct window *window)
3930 /* --------------------------------------------------------------------------
3931      External (hook): arrange to spare this window's scrollbar
3932      at next call to judge_scroll_bars.
3933    -------------------------------------------------------------------------- */
3935   id bar;
3936   NSTRACE (ns_redeem_scroll_bar);
3937   if (!NILP (window->vertical_scroll_bar))
3938     {
3939       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3940       [bar reprieve];
3941     }
3945 static void
3946 ns_judge_scroll_bars (struct frame *f)
3947 /* --------------------------------------------------------------------------
3948      External (hook): destroy all scrollbars on frame that weren't
3949      redeemed after call to condemn_scroll_bars.
3950    -------------------------------------------------------------------------- */
3952   int i;
3953   id view;
3954   EmacsView *eview = FRAME_NS_VIEW (f);
3955   NSArray *subviews = [[eview superview] subviews];
3956   BOOL removed = NO;
3958   NSTRACE (ns_judge_scroll_bars);
3959   for (i = [subviews count]-1; i >= 0; --i)
3960     {
3961       view = [subviews objectAtIndex: i];
3962       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3963       [view judge];
3964       removed = YES;
3965     }
3967   if (removed)
3968     [eview updateFrameSize: NO];
3971 /* ==========================================================================
3973     Initialization
3975    ========================================================================== */
3978 x_display_pixel_height (struct ns_display_info *dpyinfo)
3980   NSArray *screens = [NSScreen screens];
3981   NSEnumerator *enumerator = [screens objectEnumerator];
3982   NSScreen *screen;
3983   NSRect frame;
3985   frame = NSZeroRect;
3986   while ((screen = [enumerator nextObject]) != nil)
3987     frame = NSUnionRect (frame, [screen frame]);
3989   return NSHeight (frame);
3993 x_display_pixel_width (struct ns_display_info *dpyinfo)
3995   NSArray *screens = [NSScreen screens];
3996   NSEnumerator *enumerator = [screens objectEnumerator];
3997   NSScreen *screen;
3998   NSRect frame;
4000   frame = NSZeroRect;
4001   while ((screen = [enumerator nextObject]) != nil)
4002     frame = NSUnionRect (frame, [screen frame]);
4004   return NSWidth (frame);
4008 static Lisp_Object ns_string_to_lispmod (const char *s)
4009 /* --------------------------------------------------------------------------
4010      Convert modifier name to lisp symbol
4011    -------------------------------------------------------------------------- */
4013   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4014     return Qmeta;
4015   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4016     return Qsuper;
4017   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4018     return Qcontrol;
4019   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4020     return Qalt;
4021   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4022     return Qhyper;
4023   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4024     return Qnone;
4025   else
4026     return Qnil;
4030 static void
4031 ns_default (const char *parameter, Lisp_Object *result,
4032            Lisp_Object yesval, Lisp_Object noval,
4033            BOOL is_float, BOOL is_modstring)
4034 /* --------------------------------------------------------------------------
4035       Check a parameter value in user's preferences
4036    -------------------------------------------------------------------------- */
4038   const char *value = ns_get_defaults_value (parameter);
4040   if (value)
4041     {
4042       double f;
4043       char *pos;
4044       if (c_strcasecmp (value, "YES") == 0)
4045         *result = yesval;
4046       else if (c_strcasecmp (value, "NO") == 0)
4047         *result = noval;
4048       else if (is_float && (f = strtod (value, &pos), pos != value))
4049         *result = make_float (f);
4050       else if (is_modstring && value)
4051         *result = ns_string_to_lispmod (value);
4052       else fprintf (stderr,
4053                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4054     }
4058 static void
4059 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4060 /* --------------------------------------------------------------------------
4061       Initialize global info and storage for display.
4062    -------------------------------------------------------------------------- */
4064     NSScreen *screen = [NSScreen mainScreen];
4065     NSWindowDepth depth = [screen depth];
4067     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4068     dpyinfo->resy = 72.27;
4069     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4070                                                   NSColorSpaceFromDepth (depth)]
4071                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4072                                                  NSColorSpaceFromDepth (depth)];
4073     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4074     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4075     dpyinfo->color_table->colors = NULL;
4076     dpyinfo->root_window = 42; /* a placeholder.. */
4077     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4078     dpyinfo->n_fonts = 0;
4079     dpyinfo->smallest_font_height = 1;
4080     dpyinfo->smallest_char_width = 1;
4082     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4086 /* This and next define (many of the) public functions in this file. */
4087 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4088          with using despite presence in the "system dependent" redisplay
4089          interface.  In addition, many of the ns_ methods have code that is
4090          shared with all terms, indicating need for further refactoring. */
4091 extern frame_parm_handler ns_frame_parm_handlers[];
4092 static struct redisplay_interface ns_redisplay_interface =
4094   ns_frame_parm_handlers,
4095   x_produce_glyphs,
4096   x_write_glyphs,
4097   x_insert_glyphs,
4098   x_clear_end_of_line,
4099   ns_scroll_run,
4100   ns_after_update_window_line,
4101   ns_update_window_begin,
4102   ns_update_window_end,
4103   0, /* flush_display */
4104   x_clear_window_mouse_face,
4105   x_get_glyph_overhangs,
4106   x_fix_overlapping_area,
4107   ns_draw_fringe_bitmap,
4108   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4109   0, /* destroy_fringe_bitmap */
4110   ns_compute_glyph_string_overhangs,
4111   ns_draw_glyph_string,
4112   ns_define_frame_cursor,
4113   ns_clear_frame_area,
4114   ns_draw_window_cursor,
4115   ns_draw_vertical_window_border,
4116   ns_draw_window_divider,
4117   ns_shift_glyphs_for_insert
4121 static void
4122 ns_delete_display (struct ns_display_info *dpyinfo)
4124   /* TODO... */
4128 /* This function is called when the last frame on a display is deleted. */
4129 static void
4130 ns_delete_terminal (struct terminal *terminal)
4132   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4134   /* Protect against recursive calls.  delete_frame in
4135      delete_terminal calls us back when it deletes our last frame.  */
4136   if (!terminal->name)
4137     return;
4139   block_input ();
4141   x_destroy_all_bitmaps (dpyinfo);
4142   ns_delete_display (dpyinfo);
4143   unblock_input ();
4147 static struct terminal *
4148 ns_create_terminal (struct ns_display_info *dpyinfo)
4149 /* --------------------------------------------------------------------------
4150       Set up use of NS before we make the first connection.
4151    -------------------------------------------------------------------------- */
4153   struct terminal *terminal;
4155   NSTRACE (ns_create_terminal);
4157   terminal = create_terminal ();
4159   terminal->type = output_ns;
4160   terminal->display_info.ns = dpyinfo;
4161   dpyinfo->terminal = terminal;
4163   terminal->rif = &ns_redisplay_interface;
4165   terminal->clear_frame_hook = ns_clear_frame;
4166   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
4167   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
4168   terminal->ring_bell_hook = ns_ring_bell;
4169   terminal->reset_terminal_modes_hook = NULL;
4170   terminal->set_terminal_modes_hook = NULL;
4171   terminal->update_begin_hook = ns_update_begin;
4172   terminal->update_end_hook = ns_update_end;
4173   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
4174   terminal->read_socket_hook = ns_read_socket;
4175   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4176   terminal->mouse_position_hook = ns_mouse_position;
4177   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4178   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4180   terminal->fullscreen_hook = ns_fullscreen_hook;
4182   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4183   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4184   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4185   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4187   terminal->delete_frame_hook = x_destroy_window;
4188   terminal->delete_terminal_hook = ns_delete_terminal;
4190   return terminal;
4194 struct ns_display_info *
4195 ns_term_init (Lisp_Object display_name)
4196 /* --------------------------------------------------------------------------
4197      Start the Application and get things rolling.
4198    -------------------------------------------------------------------------- */
4200   struct terminal *terminal;
4201   struct ns_display_info *dpyinfo;
4202   static int ns_initialized = 0;
4203   Lisp_Object tmp;
4205   if (ns_initialized) return x_display_list;
4206   ns_initialized = 1;
4208   NSTRACE (ns_term_init);
4210   [outerpool release];
4211   outerpool = [[NSAutoreleasePool alloc] init];
4213   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4214   /*GSDebugAllocationActive (YES); */
4215   block_input ();
4217   baud_rate = 38400;
4218   Fset_input_interrupt_mode (Qnil);
4220   if (selfds[0] == -1)
4221     {
4222       if (emacs_pipe (selfds) != 0)
4223         {
4224           fprintf (stderr, "Failed to create pipe: %s\n",
4225                    emacs_strerror (errno));
4226           emacs_abort ();
4227         }
4229       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4230       FD_ZERO (&select_readfds);
4231       FD_ZERO (&select_writefds);
4232       pthread_mutex_init (&select_mutex, NULL);
4233     }
4235   ns_pending_files = [[NSMutableArray alloc] init];
4236   ns_pending_service_names = [[NSMutableArray alloc] init];
4237   ns_pending_service_args = [[NSMutableArray alloc] init];
4239 /* Start app and create the main menu, window, view.
4240      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4241      The view will then ask the NSApp to stop and return to Emacs. */
4242   [EmacsApp sharedApplication];
4243   if (NSApp == nil)
4244     return NULL;
4245   [NSApp setDelegate: NSApp];
4247   /* Start the select thread.  */
4248   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4249                            toTarget:NSApp
4250                          withObject:nil];
4252   /* debugging: log all notifications */
4253   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4254                                          selector: @selector (logNotification:)
4255                                              name: nil object: nil]; */
4257   dpyinfo = xzalloc (sizeof *dpyinfo);
4259   ns_initialize_display_info (dpyinfo);
4260   terminal = ns_create_terminal (dpyinfo);
4262   terminal->kboard = allocate_kboard (Qns);
4263   /* Don't let the initial kboard remain current longer than necessary.
4264      That would cause problems if a file loaded on startup tries to
4265      prompt in the mini-buffer.  */
4266   if (current_kboard == initial_kboard)
4267     current_kboard = terminal->kboard;
4268   terminal->kboard->reference_count++;
4270   dpyinfo->next = x_display_list;
4271   x_display_list = dpyinfo;
4273   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4275   terminal->name = xstrdup (SSDATA (display_name));
4277   unblock_input ();
4279   if (!inhibit_x_resources)
4280     {
4281       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4282                  Qt, Qnil, NO, NO);
4283       tmp = Qnil;
4284       /* this is a standard variable */
4285       ns_default ("AppleAntiAliasingThreshold", &tmp,
4286                  make_float (10.0), make_float (6.0), YES, NO);
4287       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4288     }
4290   {
4291     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4293     if ( cl == nil )
4294       {
4295         Lisp_Object color_file, color_map, color;
4296         unsigned long c;
4297         char *name;
4299         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4300                          Fsymbol_value (intern ("data-directory")));
4302         color_map = Fx_load_color_file (color_file);
4303         if (NILP (color_map))
4304           fatal ("Could not read %s.\n", SDATA (color_file));
4306         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4307         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4308           {
4309             color = XCAR (color_map);
4310             name = SSDATA (XCAR (color));
4311             c = XINT (XCDR (color));
4312             [cl setColor:
4313                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4314                                       green: GREEN_FROM_ULONG (c) / 255.0
4315                                        blue: BLUE_FROM_ULONG (c) / 255.0
4316                                       alpha: 1.0]
4317                   forKey: [NSString stringWithUTF8String: name]];
4318           }
4319         [cl writeToFile: nil];
4320       }
4321   }
4323   {
4324 #ifdef NS_IMPL_GNUSTEP
4325     Vwindow_system_version = build_string (gnustep_base_version);
4326 #else
4327     /*PSnextrelease (128, c); */
4328     char c[DBL_BUFSIZE_BOUND];
4329     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4330     Vwindow_system_version = make_unibyte_string (c, len);
4331 #endif
4332   }
4334   delete_keyboard_wait_descriptor (0);
4336   ns_app_name = [[NSProcessInfo processInfo] processName];
4338 /* Set up OS X app menu */
4339 #ifdef NS_IMPL_COCOA
4340   {
4341     NSMenu *appMenu;
4342     NSMenuItem *item;
4343     /* set up the application menu */
4344     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4345     [svcsMenu setAutoenablesItems: NO];
4346     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4347     [appMenu setAutoenablesItems: NO];
4348     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4349     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4351     [appMenu insertItemWithTitle: @"About Emacs"
4352                           action: @selector (orderFrontStandardAboutPanel:)
4353                    keyEquivalent: @""
4354                          atIndex: 0];
4355     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4356     [appMenu insertItemWithTitle: @"Preferences..."
4357                           action: @selector (showPreferencesWindow:)
4358                    keyEquivalent: @","
4359                          atIndex: 2];
4360     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4361     item = [appMenu insertItemWithTitle: @"Services"
4362                                  action: @selector (menuDown:)
4363                           keyEquivalent: @""
4364                                 atIndex: 4];
4365     [appMenu setSubmenu: svcsMenu forItem: item];
4366     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4367     [appMenu insertItemWithTitle: @"Hide Emacs"
4368                           action: @selector (hide:)
4369                    keyEquivalent: @"h"
4370                          atIndex: 6];
4371     item =  [appMenu insertItemWithTitle: @"Hide Others"
4372                           action: @selector (hideOtherApplications:)
4373                    keyEquivalent: @"h"
4374                          atIndex: 7];
4375     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4376     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4377     [appMenu insertItemWithTitle: @"Quit Emacs"
4378                           action: @selector (terminate:)
4379                    keyEquivalent: @"q"
4380                          atIndex: 9];
4382     item = [mainMenu insertItemWithTitle: ns_app_name
4383                                   action: @selector (menuDown:)
4384                            keyEquivalent: @""
4385                                  atIndex: 0];
4386     [mainMenu setSubmenu: appMenu forItem: item];
4387     [dockMenu insertItemWithTitle: @"New Frame"
4388                            action: @selector (newFrame:)
4389                     keyEquivalent: @""
4390                           atIndex: 0];
4392     [NSApp setMainMenu: mainMenu];
4393     [NSApp setAppleMenu: appMenu];
4394     [NSApp setServicesMenu: svcsMenu];
4395     /* Needed at least on Cocoa, to get dock menu to show windows */
4396     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4398     [[NSNotificationCenter defaultCenter]
4399       addObserver: mainMenu
4400          selector: @selector (trackingNotification:)
4401              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4402     [[NSNotificationCenter defaultCenter]
4403       addObserver: mainMenu
4404          selector: @selector (trackingNotification:)
4405              name: NSMenuDidEndTrackingNotification object: mainMenu];
4406   }
4407 #endif /* MAC OS X menu setup */
4409   /* Register our external input/output types, used for determining
4410      applicable services and also drag/drop eligibility. */
4411   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4412   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4413                       retain];
4414   ns_drag_types = [[NSArray arrayWithObjects:
4415                             NSStringPboardType,
4416                             NSTabularTextPboardType,
4417                             NSFilenamesPboardType,
4418                             NSURLPboardType, nil] retain];
4420   /* If fullscreen is in init/default-frame-alist, focus isn't set
4421      right for fullscreen windows, so set this.  */
4422   [NSApp activateIgnoringOtherApps:YES];
4424   [NSApp run];
4425   ns_do_open_file = YES;
4427 #ifdef NS_IMPL_GNUSTEP
4428   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4429      We must re-catch it so subprocess works.  */
4430   catch_child_signal ();
4431 #endif
4432   return dpyinfo;
4436 void
4437 ns_term_shutdown (int sig)
4439   [[NSUserDefaults standardUserDefaults] synchronize];
4441   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4442   if (STRINGP (Vauto_save_list_file_name))
4443     unlink (SSDATA (Vauto_save_list_file_name));
4445   if (sig == 0 || sig == SIGTERM)
4446     {
4447       [NSApp terminate: NSApp];
4448     }
4449   else // force a stack trace to happen
4450     {
4451       emacs_abort ();
4452     }
4456 /* ==========================================================================
4458     EmacsApp implementation
4460    ========================================================================== */
4463 @implementation EmacsApp
4465 - (id)init
4467   if (self = [super init])
4468     {
4469 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
4470       self->isFirst = YES;
4471 #endif
4472 #ifdef NS_IMPL_GNUSTEP
4473       self->applicationDidFinishLaunchingCalled = NO;
4474 #endif
4475     }
4477   return self;
4480 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
4481 - (void)run
4483     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4485     if (isFirst) [self finishLaunching];
4486     isFirst = NO;
4488     shouldKeepRunning = YES;
4489     do
4490       {
4491         [pool release];
4492         pool = [[NSAutoreleasePool alloc] init];
4494         NSEvent *event =
4495           [self nextEventMatchingMask:NSAnyEventMask
4496                             untilDate:[NSDate distantFuture]
4497                                inMode:NSDefaultRunLoopMode
4498                               dequeue:YES];
4499         [self sendEvent:event];
4500         [self updateWindows];
4501     } while (shouldKeepRunning);
4503     [pool release];
4506 - (void)stop: (id)sender
4508     shouldKeepRunning = NO;
4509     // Stop possible dialog also.  Noop if no dialog present.
4510     // The file dialog still leaks 7k - 10k on 10.9 though.
4511     [super stop:sender];
4513 #endif
4515 - (void)logNotification: (NSNotification *)notification
4517   const char *name = [[notification name] UTF8String];
4518   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4519       && !strstr (name, "WindowNumber"))
4520     NSLog (@"notification: '%@'", [notification name]);
4524 - (void)sendEvent: (NSEvent *)theEvent
4525 /* --------------------------------------------------------------------------
4526      Called when NSApp is running for each event received.  Used to stop
4527      the loop when we choose, since there's no way to just run one iteration.
4528    -------------------------------------------------------------------------- */
4530   int type = [theEvent type];
4531   NSWindow *window = [theEvent window];
4533 /*  NSTRACE (sendEvent); */
4534 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4536 #ifdef NS_IMPL_GNUSTEP
4537   // Keyboard events aren't propagated to file dialogs for some reason.
4538   if ([NSApp modalWindow] != nil &&
4539       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4540     {
4541       [[NSApp modalWindow] sendEvent: theEvent];
4542       return;
4543     }
4544 #endif
4546   if (type == NSApplicationDefined)
4547     {
4548       switch ([theEvent data2])
4549         {
4550 #ifdef NS_IMPL_COCOA
4551         case NSAPP_DATA2_RUNASSCRIPT:
4552           ns_run_ascript ();
4553           [self stop: self];
4554           return;
4555 #endif
4556         case NSAPP_DATA2_RUNFILEDIALOG:
4557           ns_run_file_dialog ();
4558           [self stop: self];
4559           return;
4560         }
4561     }
4563   if (type == NSCursorUpdate && window == nil)
4564     {
4565       fprintf (stderr, "Dropping external cursor update event.\n");
4566       return;
4567     }
4569   if (type == NSApplicationDefined)
4570     {
4571       /* Events posted by ns_send_appdefined interrupt the run loop here.
4572          But, if a modal window is up, an appdefined can still come through,
4573          (e.g., from a makeKeyWindow event) but stopping self also stops the
4574          modal loop. Just defer it until later. */
4575       if ([NSApp modalWindow] == nil)
4576         {
4577           last_appdefined_event_data = [theEvent data1];
4578           [self stop: self];
4579         }
4580       else
4581         {
4582           send_appdefined = YES;
4583         }
4584     }
4587 #ifdef NS_IMPL_COCOA
4588   /* If no dialog and none of our frames have focus and it is a move, skip it.
4589      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4590      such as Wifi, sound, date or similar.
4591      This prevents "spooky" highlighting in the frame under the menu.  */
4592   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4593     {
4594       struct ns_display_info *di;
4595       BOOL has_focus = NO;
4596       for (di = x_display_list; ! has_focus && di; di = di->next)
4597         has_focus = di->x_focus_frame != 0;
4598       if (! has_focus)
4599         return;
4600     }
4601 #endif
4603   [super sendEvent: theEvent];
4607 - (void)showPreferencesWindow: (id)sender
4609   struct frame *emacsframe = SELECTED_FRAME ();
4610   NSEvent *theEvent = [NSApp currentEvent];
4612   if (!emacs_event)
4613     return;
4614   emacs_event->kind = NS_NONKEY_EVENT;
4615   emacs_event->code = KEY_NS_SHOW_PREFS;
4616   emacs_event->modifiers = 0;
4617   EV_TRAILER (theEvent);
4621 - (void)newFrame: (id)sender
4623   struct frame *emacsframe = SELECTED_FRAME ();
4624   NSEvent *theEvent = [NSApp currentEvent];
4626   if (!emacs_event)
4627     return;
4628   emacs_event->kind = NS_NONKEY_EVENT;
4629   emacs_event->code = KEY_NS_NEW_FRAME;
4630   emacs_event->modifiers = 0;
4631   EV_TRAILER (theEvent);
4635 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4636 - (BOOL) openFile: (NSString *)fileName
4638   struct frame *emacsframe = SELECTED_FRAME ();
4639   NSEvent *theEvent = [NSApp currentEvent];
4641   if (!emacs_event)
4642     return NO;
4644   emacs_event->kind = NS_NONKEY_EVENT;
4645   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4646   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4647   ns_input_line = Qnil; /* can be start or cons start,end */
4648   emacs_event->modifiers =0;
4649   EV_TRAILER (theEvent);
4651   return YES;
4655 /* **************************************************************************
4657       EmacsApp delegate implementation
4659    ************************************************************************** */
4661 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4662 /* --------------------------------------------------------------------------
4663      When application is loaded, terminate event loop in ns_term_init
4664    -------------------------------------------------------------------------- */
4666   NSTRACE (applicationDidFinishLaunching);
4667 #ifdef NS_IMPL_GNUSTEP
4668   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4669 #endif
4670   [NSApp setServicesProvider: NSApp];
4671   ns_send_appdefined (-2);
4675 /* Termination sequences:
4676     C-x C-c:
4677     Cmd-Q:
4678     MenuBar | File | Exit:
4679     Select Quit from App menubar:
4680         -terminate
4681         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4682         ns_term_shutdown()
4684     Select Quit from Dock menu:
4685     Logout attempt:
4686         -appShouldTerminate
4687           Cancel -> Nothing else
4688           Accept ->
4690           -terminate
4691           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4692           ns_term_shutdown()
4696 - (void) terminate: (id)sender
4698   struct frame *emacsframe = SELECTED_FRAME ();
4700   if (!emacs_event)
4701     return;
4703   emacs_event->kind = NS_NONKEY_EVENT;
4704   emacs_event->code = KEY_NS_POWER_OFF;
4705   emacs_event->arg = Qt; /* mark as non-key event */
4706   EV_TRAILER ((id)nil);
4710 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4712   int ret;
4714   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4715     return NSTerminateNow;
4717     ret = NSRunAlertPanel(ns_app_name,
4718                           @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4719                           @"Save Buffers and Exit", @"Cancel", nil);
4721     if (ret == NSAlertDefaultReturn)
4722         return NSTerminateNow;
4723     else if (ret == NSAlertAlternateReturn)
4724         return NSTerminateCancel;
4725     return NSTerminateNow;  /* just in case */
4728 static int
4729 not_in_argv (NSString *arg)
4731   int k;
4732   const char *a = [arg UTF8String];
4733   for (k = 1; k < initial_argc; ++k)
4734     if (strcmp (a, initial_argv[k]) == 0) return 0;
4735   return 1;
4738 /*   Notification from the Workspace to open a file */
4739 - (BOOL)application: sender openFile: (NSString *)file
4741   if (ns_do_open_file || not_in_argv (file))
4742     [ns_pending_files addObject: file];
4743   return YES;
4747 /*   Open a file as a temporary file */
4748 - (BOOL)application: sender openTempFile: (NSString *)file
4750   if (ns_do_open_file || not_in_argv (file))
4751     [ns_pending_files addObject: file];
4752   return YES;
4756 /*   Notification from the Workspace to open a file noninteractively (?) */
4757 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4759   if (ns_do_open_file || not_in_argv (file))
4760     [ns_pending_files addObject: file];
4761   return YES;
4764 /*   Notification from the Workspace to open multiple files */
4765 - (void)application: sender openFiles: (NSArray *)fileList
4767   NSEnumerator *files = [fileList objectEnumerator];
4768   NSString *file;
4769   /* Don't open files from the command line unconditionally,
4770      Cocoa parses the command line wrong, --option value tries to open value
4771      if --option is the last option.  */
4772   while ((file = [files nextObject]) != nil)
4773     if (ns_do_open_file || not_in_argv (file))
4774       [ns_pending_files addObject: file];
4776   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4781 /* Handle dock menu requests.  */
4782 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4784   return dockMenu;
4788 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4789 - (void)applicationWillBecomeActive: (NSNotification *)notification
4791   //ns_app_active=YES;
4793 - (void)applicationDidBecomeActive: (NSNotification *)notification
4795   NSTRACE (applicationDidBecomeActive);
4797 #ifdef NS_IMPL_GNUSTEP
4798   if (! applicationDidFinishLaunchingCalled)
4799     [self applicationDidFinishLaunching:notification];
4800 #endif
4801   //ns_app_active=YES;
4803   ns_update_auto_hide_menu_bar ();
4804   // No constraining takes place when the application is not active.
4805   ns_constrain_all_frames ();
4807 - (void)applicationDidResignActive: (NSNotification *)notification
4809   //ns_app_active=NO;
4810   ns_send_appdefined (-1);
4815 /* ==========================================================================
4817     EmacsApp aux handlers for managing event loop
4819    ========================================================================== */
4822 - (void)timeout_handler: (NSTimer *)timedEntry
4823 /* --------------------------------------------------------------------------
4824      The timeout specified to ns_select has passed.
4825    -------------------------------------------------------------------------- */
4827   /*NSTRACE (timeout_handler); */
4828   ns_send_appdefined (-2);
4831 #ifdef NS_IMPL_GNUSTEP
4832 - (void)sendFromMainThread:(id)unused
4834   ns_send_appdefined (nextappdefined);
4836 #endif
4838 - (void)fd_handler:(id)unused
4839 /* --------------------------------------------------------------------------
4840      Check data waiting on file descriptors and terminate if so
4841    -------------------------------------------------------------------------- */
4843   int result;
4844   int waiting = 1, nfds;
4845   char c;
4847   fd_set readfds, writefds, *wfds;
4848   struct timespec timeout, *tmo;
4849   NSAutoreleasePool *pool = nil;
4851   /* NSTRACE (fd_handler); */
4853   for (;;)
4854     {
4855       [pool release];
4856       pool = [[NSAutoreleasePool alloc] init];
4858       if (waiting)
4859         {
4860           fd_set fds;
4861           FD_ZERO (&fds);
4862           FD_SET (selfds[0], &fds);
4863           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4864           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4865             waiting = 0;
4866         }
4867       else
4868         {
4869           pthread_mutex_lock (&select_mutex);
4870           nfds = select_nfds;
4872           if (select_valid & SELECT_HAVE_READ)
4873             readfds = select_readfds;
4874           else
4875             FD_ZERO (&readfds);
4877           if (select_valid & SELECT_HAVE_WRITE)
4878             {
4879               writefds = select_writefds;
4880               wfds = &writefds;
4881             }
4882           else
4883             wfds = NULL;
4884           if (select_valid & SELECT_HAVE_TMO)
4885             {
4886               timeout = select_timeout;
4887               tmo = &timeout;
4888             }
4889           else
4890             tmo = NULL;
4892           pthread_mutex_unlock (&select_mutex);
4894           FD_SET (selfds[0], &readfds);
4895           if (selfds[0] >= nfds) nfds = selfds[0]+1;
4897           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4899           if (result == 0)
4900             ns_send_appdefined (-2);
4901           else if (result > 0)
4902             {
4903               if (FD_ISSET (selfds[0], &readfds))
4904                 {
4905                   if (read (selfds[0], &c, 1) == 1 && c == 's')
4906                     waiting = 1;
4907                 }
4908               else
4909                 {
4910                   pthread_mutex_lock (&select_mutex);
4911                   if (select_valid & SELECT_HAVE_READ)
4912                     select_readfds = readfds;
4913                   if (select_valid & SELECT_HAVE_WRITE)
4914                     select_writefds = writefds;
4915                   if (select_valid & SELECT_HAVE_TMO)
4916                     select_timeout = timeout;
4917                   pthread_mutex_unlock (&select_mutex);
4919                   ns_send_appdefined (result);
4920                 }
4921             }
4922           waiting = 1;
4923         }
4924     }
4929 /* ==========================================================================
4931     Service provision
4933    ========================================================================== */
4935 /* called from system: queue for next pass through event loop */
4936 - (void)requestService: (NSPasteboard *)pboard
4937               userData: (NSString *)userData
4938                  error: (NSString **)error
4940   [ns_pending_service_names addObject: userData];
4941   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4942       SSDATA (ns_string_from_pasteboard (pboard))]];
4946 /* called from ns_read_socket to clear queue */
4947 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4949   struct frame *emacsframe = SELECTED_FRAME ();
4950   NSEvent *theEvent = [NSApp currentEvent];
4952   if (!emacs_event)
4953     return NO;
4955   emacs_event->kind = NS_NONKEY_EVENT;
4956   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4957   ns_input_spi_name = build_string ([name UTF8String]);
4958   ns_input_spi_arg = build_string ([arg UTF8String]);
4959   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4960   EV_TRAILER (theEvent);
4962   return YES;
4966 @end  /* EmacsApp */
4970 /* ==========================================================================
4972     EmacsView implementation
4974    ========================================================================== */
4977 @implementation EmacsView
4979 /* needed to inform when window closed from LISP */
4980 - (void) setWindowClosing: (BOOL)closing
4982   windowClosing = closing;
4986 - (void)dealloc
4988   NSTRACE (EmacsView_dealloc);
4989   [toolbar release];
4990   if (fs_state == FULLSCREEN_BOTH)
4991     [nonfs_window release];
4992   [super dealloc];
4996 /* called on font panel selection */
4997 - (void)changeFont: (id)sender
4999   NSEvent *e = [[self window] currentEvent];
5000   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5001   struct font *font = face->font;
5002   id newFont;
5003   CGFloat size;
5004   NSFont *nsfont;
5006   NSTRACE (changeFont);
5008   if (!emacs_event)
5009     return;
5011   if (EQ (font->driver->type, Qns))
5012     nsfont = ((struct nsfont_info *)font)->nsfont;
5013 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
5014   else
5015     nsfont = (NSFont *) macfont_get_nsctfont (font);
5016 #endif
5018   if ((newFont = [sender convertFont: nsfont]))
5019     {
5020       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5022       emacs_event->kind = NS_NONKEY_EVENT;
5023       emacs_event->modifiers = 0;
5024       emacs_event->code = KEY_NS_CHANGE_FONT;
5026       size = [newFont pointSize];
5027       ns_input_fontsize = make_number (lrint (size));
5028       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5029       EV_TRAILER (e);
5030     }
5034 - (BOOL)acceptsFirstResponder
5036   NSTRACE (acceptsFirstResponder);
5037   return YES;
5041 - (void)resetCursorRects
5043   NSRect visible = [self visibleRect];
5044   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5045   NSTRACE (resetCursorRects);
5047   if (currentCursor == nil)
5048     currentCursor = [NSCursor arrowCursor];
5050   if (!NSIsEmptyRect (visible))
5051     [self addCursorRect: visible cursor: currentCursor];
5052   [currentCursor setOnMouseEntered: YES];
5057 /*****************************************************************************/
5058 /* Keyboard handling. */
5059 #define NS_KEYLOG 0
5061 - (void)keyDown: (NSEvent *)theEvent
5063   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5064   int code;
5065   unsigned fnKeysym = 0;
5066   static NSMutableArray *nsEvArray;
5067 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5068   static BOOL firstTime = YES;
5069 #endif
5070   int left_is_none;
5071   unsigned int flags = [theEvent modifierFlags];
5073   NSTRACE (keyDown);
5075   /* Rhapsody and OS X give up and down events for the arrow keys */
5076   if (ns_fake_keydown == YES)
5077     ns_fake_keydown = NO;
5078   else if ([theEvent type] != NSKeyDown)
5079     return;
5081   if (!emacs_event)
5082     return;
5084  if (![[self window] isKeyWindow]
5085      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5086      /* we must avoid an infinite loop here. */
5087      && (EmacsView *)[[theEvent window] delegate] != self)
5088    {
5089      /* XXX: There is an occasional condition in which, when Emacs display
5090          updates a different frame from the current one, and temporarily
5091          selects it, then processes some interrupt-driven input
5092          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5093          for some reason that window has its first responder set to the NSView
5094          most recently updated (I guess), which is not the correct one. */
5095      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5096      return;
5097    }
5099   if (nsEvArray == nil)
5100     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5102   [NSCursor setHiddenUntilMouseMoves: YES];
5104   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5105     {
5106       clear_mouse_face (hlinfo);
5107       hlinfo->mouse_face_hidden = 1;
5108     }
5110   if (!processingCompose)
5111     {
5112       /* When using screen sharing, no left or right information is sent,
5113          so use Left key in those cases.  */
5114       int is_left_key, is_right_key;
5116       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5117         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5119       /* (Carbon way: [theEvent keyCode]) */
5121       /* is it a "function key"? */
5122       fnKeysym = (code < 0x00ff && (flags&NSNumericPadKeyMask))
5123         ? ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask)
5124         : ns_convert_key (code);
5126       if (fnKeysym)
5127         {
5128           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5129              because Emacs treats Delete and KP-Delete same (in simple.el). */
5130           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5131 #ifdef NS_IMPL_GNUSTEP
5132               /*  GNUstep uses incompatible keycodes, even for those that are
5133                   supposed to be hardware independent.  Just check for delete.
5134                   Keypad delete does not have keysym 0xFFFF.
5135                   See http://savannah.gnu.org/bugs/?25395
5136               */
5137               || (fnKeysym == 0xFFFF && code == 127)
5138 #endif
5139             )
5140             code = 0xFF08; /* backspace */
5141           else
5142             code = fnKeysym;
5143         }
5145       /* are there modifiers? */
5146       emacs_event->modifiers = 0;
5148       if (flags & NSHelpKeyMask)
5149           emacs_event->modifiers |= hyper_modifier;
5151       if (flags & NSShiftKeyMask)
5152         emacs_event->modifiers |= shift_modifier;
5154       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5155       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5156         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5158       if (is_right_key)
5159         emacs_event->modifiers |= parse_solitary_modifier
5160           (EQ (ns_right_command_modifier, Qleft)
5161            ? ns_command_modifier
5162            : ns_right_command_modifier);
5164       if (is_left_key)
5165         {
5166           emacs_event->modifiers |= parse_solitary_modifier
5167             (ns_command_modifier);
5169           /* if super (default), take input manager's word so things like
5170              dvorak / qwerty layout work */
5171           if (EQ (ns_command_modifier, Qsuper)
5172               && !fnKeysym
5173               && [[theEvent characters] length] != 0)
5174             {
5175               /* XXX: the code we get will be unshifted, so if we have
5176                  a shift modifier, must convert ourselves */
5177               if (!(flags & NSShiftKeyMask))
5178                 code = [[theEvent characters] characterAtIndex: 0];
5179 #if 0
5180               /* this is ugly and also requires linking w/Carbon framework
5181                  (for LMGetKbdType) so for now leave this rare (?) case
5182                  undealt with.. in future look into CGEvent methods */
5183               else
5184                 {
5185                   long smv = GetScriptManagerVariable (smKeyScript);
5186                   Handle uchrHandle = GetResource
5187                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5188                   UInt32 dummy = 0;
5189                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5190                                  [[theEvent characters] characterAtIndex: 0],
5191                                  kUCKeyActionDisplay,
5192                                  (flags & ~NSCommandKeyMask) >> 8,
5193                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5194                                  &dummy, 1, &dummy, &code);
5195                   code &= 0xFF;
5196                 }
5197 #endif
5198             }
5199         }
5201       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5202       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5203         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5205       if (is_right_key)
5206           emacs_event->modifiers |= parse_solitary_modifier
5207               (EQ (ns_right_control_modifier, Qleft)
5208                ? ns_control_modifier
5209                : ns_right_control_modifier);
5211       if (is_left_key)
5212         emacs_event->modifiers |= parse_solitary_modifier
5213           (ns_control_modifier);
5215       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5216           emacs_event->modifiers |=
5217             parse_solitary_modifier (ns_function_modifier);
5219       left_is_none = NILP (ns_alternate_modifier)
5220         || EQ (ns_alternate_modifier, Qnone);
5222       is_right_key = (flags & NSRightAlternateKeyMask)
5223         == NSRightAlternateKeyMask;
5224       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5225         || (! is_right_key
5226             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5228       if (is_right_key)
5229         {
5230           if ((NILP (ns_right_alternate_modifier)
5231                || EQ (ns_right_alternate_modifier, Qnone)
5232                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5233               && !fnKeysym)
5234             {   /* accept pre-interp alt comb */
5235               if ([[theEvent characters] length] > 0)
5236                 code = [[theEvent characters] characterAtIndex: 0];
5237               /*HACK: clear lone shift modifier to stop next if from firing */
5238               if (emacs_event->modifiers == shift_modifier)
5239                 emacs_event->modifiers = 0;
5240             }
5241           else
5242             emacs_event->modifiers |= parse_solitary_modifier
5243               (EQ (ns_right_alternate_modifier, Qleft)
5244                ? ns_alternate_modifier
5245                : ns_right_alternate_modifier);
5246         }
5248       if (is_left_key) /* default = meta */
5249         {
5250           if (left_is_none && !fnKeysym)
5251             {   /* accept pre-interp alt comb */
5252               if ([[theEvent characters] length] > 0)
5253                 code = [[theEvent characters] characterAtIndex: 0];
5254               /*HACK: clear lone shift modifier to stop next if from firing */
5255               if (emacs_event->modifiers == shift_modifier)
5256                 emacs_event->modifiers = 0;
5257             }
5258           else
5259               emacs_event->modifiers |=
5260                 parse_solitary_modifier (ns_alternate_modifier);
5261         }
5263   if (NS_KEYLOG)
5264     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5265              code, fnKeysym, flags, emacs_event->modifiers);
5267       /* if it was a function key or had modifiers, pass it directly to emacs */
5268       if (fnKeysym || (emacs_event->modifiers
5269                        && (emacs_event->modifiers != shift_modifier)
5270                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5271 /*[[theEvent characters] length] */
5272         {
5273           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5274           if (code < 0x20)
5275             code |= (1<<28)|(3<<16);
5276           else if (code == 0x7f)
5277             code |= (1<<28)|(3<<16);
5278           else if (!fnKeysym)
5279             emacs_event->kind = code > 0xFF
5280               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5282           emacs_event->code = code;
5283           EV_TRAILER (theEvent);
5284           processingCompose = NO;
5285           return;
5286         }
5287     }
5290 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5291   /* if we get here we should send the key for input manager processing */
5292   /* Disable warning, there is nothing a user can do about it anyway, and
5293      it does not seem to matter.  */
5294 #if 0
5295   if (firstTime && [[NSInputManager currentInputManager]
5296                      wantsToDelayTextChangeNotifications] == NO)
5297     fprintf (stderr,
5298           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5299 #endif
5300   firstTime = NO;
5301 #endif
5302   if (NS_KEYLOG && !processingCompose)
5303     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5305   processingCompose = YES;
5306   [nsEvArray addObject: theEvent];
5307   [self interpretKeyEvents: nsEvArray];
5308   [nsEvArray removeObject: theEvent];
5312 #ifdef NS_IMPL_COCOA
5313 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5314    decided not to send key-down for.
5315    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5316    This only applies on Tiger and earlier.
5317    If it matches one of these, send it on to keyDown. */
5318 -(void)keyUp: (NSEvent *)theEvent
5320   int flags = [theEvent modifierFlags];
5321   int code = [theEvent keyCode];
5322   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5323       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5324     {
5325       if (NS_KEYLOG)
5326         fprintf (stderr, "keyUp: passed test");
5327       ns_fake_keydown = YES;
5328       [self keyDown: theEvent];
5329     }
5331 #endif
5334 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5337 /* <NSTextInput>: called when done composing;
5338    NOTE: also called when we delete over working text, followed immed.
5339          by doCommandBySelector: deleteBackward: */
5340 - (void)insertText: (id)aString
5342   int code;
5343   int len = [(NSString *)aString length];
5344   int i;
5346   if (NS_KEYLOG)
5347     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5348   processingCompose = NO;
5350   if (!emacs_event)
5351     return;
5353   /* first, clear any working text */
5354   if (workingText != nil)
5355     [self deleteWorkingText];
5357   /* now insert the string as keystrokes */
5358   for (i =0; i<len; i++)
5359     {
5360       code = [aString characterAtIndex: i];
5361       /* TODO: still need this? */
5362       if (code == 0x2DC)
5363         code = '~'; /* 0x7E */
5364       if (code != 32) /* Space */
5365         emacs_event->modifiers = 0;
5366       emacs_event->kind
5367         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5368       emacs_event->code = code;
5369       EV_TRAILER ((id)nil);
5370     }
5374 /* <NSTextInput>: inserts display of composing characters */
5375 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5377   NSString *str = [aString respondsToSelector: @selector (string)] ?
5378     [aString string] : aString;
5379   if (NS_KEYLOG)
5380     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5381            str, (unsigned long)[str length],
5382            (unsigned long)selRange.length,
5383            (unsigned long)selRange.location);
5385   if (workingText != nil)
5386     [self deleteWorkingText];
5387   if ([str length] == 0)
5388     return;
5390   if (!emacs_event)
5391     return;
5393   processingCompose = YES;
5394   workingText = [str copy];
5395   ns_working_text = build_string ([workingText UTF8String]);
5397   emacs_event->kind = NS_TEXT_EVENT;
5398   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5399   EV_TRAILER ((id)nil);
5403 /* delete display of composing characters [not in <NSTextInput>] */
5404 - (void)deleteWorkingText
5406   if (workingText == nil)
5407     return;
5408   if (NS_KEYLOG)
5409     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5410   [workingText release];
5411   workingText = nil;
5412   processingCompose = NO;
5414   if (!emacs_event)
5415     return;
5417   emacs_event->kind = NS_TEXT_EVENT;
5418   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5419   EV_TRAILER ((id)nil);
5423 - (BOOL)hasMarkedText
5425   return workingText != nil;
5429 - (NSRange)markedRange
5431   NSRange rng = workingText != nil
5432     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5433   if (NS_KEYLOG)
5434     NSLog (@"markedRange request");
5435   return rng;
5439 - (void)unmarkText
5441   if (NS_KEYLOG)
5442     NSLog (@"unmark (accept) text");
5443   [self deleteWorkingText];
5444   processingCompose = NO;
5448 /* used to position char selection windows, etc. */
5449 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5451   NSRect rect;
5452   NSPoint pt;
5453   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5454   if (NS_KEYLOG)
5455     NSLog (@"firstRectForCharRange request");
5457   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5458   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5459   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5460   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5461                                        +FRAME_LINE_HEIGHT (emacsframe));
5463   pt = [self convertPoint: pt toView: nil];
5464   pt = [[self window] convertBaseToScreen: pt];
5465   rect.origin = pt;
5466   return rect;
5470 - (NSInteger)conversationIdentifier
5472   return (NSInteger)self;
5476 - (void)doCommandBySelector: (SEL)aSelector
5478   if (NS_KEYLOG)
5479     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5481   processingCompose = NO;
5482   if (aSelector == @selector (deleteBackward:))
5483     {
5484       /* happens when user backspaces over an ongoing composition:
5485          throw a 'delete' into the event queue */
5486       if (!emacs_event)
5487         return;
5488       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5489       emacs_event->code = 0xFF08;
5490       EV_TRAILER ((id)nil);
5491     }
5494 - (NSArray *)validAttributesForMarkedText
5496   static NSArray *arr = nil;
5497   if (arr == nil) arr = [NSArray new];
5498  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5499   return arr;
5502 - (NSRange)selectedRange
5504   if (NS_KEYLOG)
5505     NSLog (@"selectedRange request");
5506   return NSMakeRange (NSNotFound, 0);
5509 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5510     GNUSTEP_GUI_MINOR_VERSION > 22
5511 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5512 #else
5513 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5514 #endif
5516   if (NS_KEYLOG)
5517     NSLog (@"characterIndexForPoint request");
5518   return 0;
5521 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5523   static NSAttributedString *str = nil;
5524   if (str == nil) str = [NSAttributedString new];
5525   if (NS_KEYLOG)
5526     NSLog (@"attributedSubstringFromRange request");
5527   return str;
5530 /* End <NSTextInput> impl. */
5531 /*****************************************************************************/
5534 /* This is what happens when the user presses a mouse button.  */
5535 - (void)mouseDown: (NSEvent *)theEvent
5537   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5538   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5540   NSTRACE (mouseDown);
5542   [self deleteWorkingText];
5544   if (!emacs_event)
5545     return;
5547   dpyinfo->last_mouse_frame = emacsframe;
5548   /* appears to be needed to prevent spurious movement events generated on
5549      button clicks */
5550   emacsframe->mouse_moved = 0;
5552   if ([theEvent type] == NSScrollWheel)
5553     {
5554       CGFloat delta = [theEvent deltaY];
5555       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5556       if (delta == 0)
5557         {
5558           delta = [theEvent deltaX];
5559           if (delta == 0)
5560             {
5561               NSTRACE (deltaIsZero);
5562               return;
5563             }
5564           emacs_event->kind = HORIZ_WHEEL_EVENT;
5565         }
5566       else
5567         emacs_event->kind = WHEEL_EVENT;
5569       emacs_event->code = 0;
5570       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5571         ((delta > 0) ? up_modifier : down_modifier);
5572     }
5573   else
5574     {
5575       emacs_event->kind = MOUSE_CLICK_EVENT;
5576       emacs_event->code = EV_BUTTON (theEvent);
5577       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5578                              | EV_UDMODIFIERS (theEvent);
5579     }
5580   XSETINT (emacs_event->x, lrint (p.x));
5581   XSETINT (emacs_event->y, lrint (p.y));
5582   EV_TRAILER (theEvent);
5586 - (void)rightMouseDown: (NSEvent *)theEvent
5588   NSTRACE (rightMouseDown);
5589   [self mouseDown: theEvent];
5593 - (void)otherMouseDown: (NSEvent *)theEvent
5595   NSTRACE (otherMouseDown);
5596   [self mouseDown: theEvent];
5600 - (void)mouseUp: (NSEvent *)theEvent
5602   NSTRACE (mouseUp);
5603   [self mouseDown: theEvent];
5607 - (void)rightMouseUp: (NSEvent *)theEvent
5609   NSTRACE (rightMouseUp);
5610   [self mouseDown: theEvent];
5614 - (void)otherMouseUp: (NSEvent *)theEvent
5616   NSTRACE (otherMouseUp);
5617   [self mouseDown: theEvent];
5621 - (void) scrollWheel: (NSEvent *)theEvent
5623   NSTRACE (scrollWheel);
5624   [self mouseDown: theEvent];
5628 /* Tell emacs the mouse has moved. */
5629 - (void)mouseMoved: (NSEvent *)e
5631   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5632   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5633   Lisp_Object frame;
5634   NSPoint pt;
5636 //  NSTRACE (mouseMoved);
5638   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5639   pt = [self convertPoint: [e locationInWindow] fromView: nil];
5640   dpyinfo->last_mouse_motion_x = pt.x;
5641   dpyinfo->last_mouse_motion_y = pt.y;
5643   /* update any mouse face */
5644   if (hlinfo->mouse_face_hidden)
5645     {
5646       hlinfo->mouse_face_hidden = 0;
5647       clear_mouse_face (hlinfo);
5648     }
5650   /* tooltip handling */
5651   previous_help_echo_string = help_echo_string;
5652   help_echo_string = Qnil;
5654   if (!NILP (Vmouse_autoselect_window))
5655     {
5656       NSTRACE (mouse_autoselect_window);
5657       static Lisp_Object last_mouse_window;
5658       Lisp_Object window
5659         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5661       if (WINDOWP (window)
5662           && !EQ (window, last_mouse_window)
5663           && !EQ (window, selected_window)
5664           && (focus_follows_mouse
5665               || (EQ (XWINDOW (window)->frame,
5666                       XWINDOW (selected_window)->frame))))
5667         {
5668           NSTRACE (in_window);
5669           emacs_event->kind = SELECT_WINDOW_EVENT;
5670           emacs_event->frame_or_window = window;
5671           EV_TRAILER2 (e);
5672         }
5673       /* Remember the last window where we saw the mouse.  */
5674       last_mouse_window = window;
5675     }
5677   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5678     help_echo_string = previous_help_echo_string;
5680   XSETFRAME (frame, emacsframe);
5681   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5682     {
5683       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5684          (note_mouse_highlight), which is called through the
5685          note_mouse_movement () call above */
5686       gen_help_event (help_echo_string, frame, help_echo_window,
5687                       help_echo_object, help_echo_pos);
5688     }
5689   else
5690     {
5691       help_echo_string = Qnil;
5692       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5693     }
5695   if (emacsframe->mouse_moved && send_appdefined)
5696     ns_send_appdefined (-1);
5700 - (void)mouseDragged: (NSEvent *)e
5702   NSTRACE (mouseDragged);
5703   [self mouseMoved: e];
5707 - (void)rightMouseDragged: (NSEvent *)e
5709   NSTRACE (rightMouseDragged);
5710   [self mouseMoved: e];
5714 - (void)otherMouseDragged: (NSEvent *)e
5716   NSTRACE (otherMouseDragged);
5717   [self mouseMoved: e];
5721 - (BOOL)windowShouldClose: (id)sender
5723   NSEvent *e =[[self window] currentEvent];
5725   NSTRACE (windowShouldClose);
5726   windowClosing = YES;
5727   if (!emacs_event)
5728     return NO;
5729   emacs_event->kind = DELETE_WINDOW_EVENT;
5730   emacs_event->modifiers = 0;
5731   emacs_event->code = 0;
5732   EV_TRAILER (e);
5733   /* Don't close this window, let this be done from lisp code.  */
5734   return NO;
5737 - (void) updateFrameSize: (BOOL) delay;
5739   NSWindow *window = [self window];
5740   NSRect wr = [window frame];
5741   int extra = 0;
5742   int oldc = cols, oldr = rows;
5743   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5744   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5745   int neww, newh;
5747   NSTRACE (updateFrameSize);
5748   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5750   if (! [self isFullscreen])
5751     {
5752 #ifdef NS_IMPL_GNUSTEP
5753       // GNUStep does not always update the tool bar height.  Force it.
5754       if (toolbar) update_frame_tool_bar (emacsframe);
5755 #endif
5757       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5758         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5759     }
5761   neww = (int)wr.size.width - emacsframe->border_width;
5762   newh = (int)wr.size.height - extra;
5764   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5765   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5767   if (cols < MINWIDTH)
5768     cols = MINWIDTH;
5770   if (rows < MINHEIGHT)
5771     rows = MINHEIGHT;
5773   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5774     {
5775       NSView *view = FRAME_NS_VIEW (emacsframe);
5776       NSWindow *win = [view window];
5777       NSSize sz = [win resizeIncrements];
5779       change_frame_size (emacsframe,
5780                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5781                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5782                          0, delay, 0, 1);
5783       SET_FRAME_GARBAGED (emacsframe);
5784       cancel_mouse_face (emacsframe);
5786       // Did resize increments change because of a font change?
5787       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5788           sz.height != FRAME_LINE_HEIGHT (emacsframe))
5789         {
5790           sz.width = FRAME_COLUMN_WIDTH (emacsframe);
5791           sz.height = FRAME_LINE_HEIGHT (emacsframe);
5792           [win setResizeIncrements: sz];
5794           NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
5795         }
5797       [view setFrame: NSMakeRect (0, 0, neww, newh)];
5798       [self windowDidMove:nil];   // Update top/left.
5799     }
5802 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5803 /* normalize frame to gridded text size */
5805   int extra = 0;
5807   NSTRACE (windowWillResize);
5808   NSTRACE_SIZE ("Original size", frameSize);
5809 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5811   if (fs_state == FULLSCREEN_MAXIMIZED
5812       && (maximized_width != (int)frameSize.width
5813           || maximized_height != (int)frameSize.height))
5814     [self setFSValue: FULLSCREEN_NONE];
5815   else if (fs_state == FULLSCREEN_WIDTH
5816            && maximized_width != (int)frameSize.width)
5817     [self setFSValue: FULLSCREEN_NONE];
5818   else if (fs_state == FULLSCREEN_HEIGHT
5819            && maximized_height != (int)frameSize.height)
5820     [self setFSValue: FULLSCREEN_NONE];
5821   if (fs_state == FULLSCREEN_NONE)
5822     maximized_width = maximized_height = -1;
5824   if (! [self isFullscreen])
5825     {
5826       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5827         + FRAME_TOOLBAR_HEIGHT (emacsframe);
5828     }
5830   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
5831   if (cols < MINWIDTH)
5832     cols = MINWIDTH;
5834   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5835                                            frameSize.height - extra);
5836   if (rows < MINHEIGHT)
5837     rows = MINHEIGHT;
5838 #ifdef NS_IMPL_COCOA
5839   {
5840     /* this sets window title to have size in it; the wm does this under GS */
5841     NSRect r = [[self window] frame];
5842     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5843       {
5844         if (old_title != 0)
5845           {
5846             xfree (old_title);
5847             old_title = 0;
5848           }
5849       }
5850     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
5851       {
5852         char *size_title;
5853         NSWindow *window = [self window];
5854         if (old_title == 0)
5855           {
5856             char *t = strdup ([[[self window] title] UTF8String]);
5857             char *pos = strstr (t, "  â€”  ");
5858             if (pos)
5859               *pos = '\0';
5860             old_title = t;
5861           }
5862         size_title = xmalloc (strlen (old_title) + 40);
5863         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5864         [window setTitle: [NSString stringWithUTF8String: size_title]];
5865         [window display];
5866         xfree (size_title);
5867       }
5868   }
5869 #endif /* NS_IMPL_COCOA */
5870 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5872   return frameSize;
5876 - (void)windowDidResize: (NSNotification *)notification
5878   if (! [self fsIsNative])
5879     {
5880       NSWindow *theWindow = [notification object];
5881       /* We can get notification on the non-FS window when in
5882          fullscreen mode.  */
5883       if ([self window] != theWindow) return;
5884     }
5886 #ifdef NS_IMPL_GNUSTEP
5887   NSWindow *theWindow = [notification object];
5889    /* In GNUstep, at least currently, it's possible to get a didResize
5890       without getting a willResize.. therefore we need to act as if we got
5891       the willResize now */
5892   NSSize sz = [theWindow frame].size;
5893   sz = [self windowWillResize: theWindow toSize: sz];
5894 #endif /* NS_IMPL_GNUSTEP */
5896   NSTRACE (windowDidResize);
5897 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5899 if (cols > 0 && rows > 0)
5900     {
5901       [self updateFrameSize: YES];
5902     }
5904   ns_send_appdefined (-1);
5907 #ifdef NS_IMPL_COCOA
5908 - (void)viewDidEndLiveResize
5910   [super viewDidEndLiveResize];
5911   if (old_title != 0)
5912     {
5913       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
5914       xfree (old_title);
5915       old_title = 0;
5916     }
5917   maximizing_resize = NO;
5919 #endif /* NS_IMPL_COCOA */
5922 - (void)windowDidBecomeKey: (NSNotification *)notification
5923 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5925   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5926   struct frame *old_focus = dpyinfo->x_focus_frame;
5928   NSTRACE (windowDidBecomeKey);
5930   if (emacsframe != old_focus)
5931     dpyinfo->x_focus_frame = emacsframe;
5933   ns_frame_rehighlight (emacsframe);
5935   if (emacs_event)
5936     {
5937       emacs_event->kind = FOCUS_IN_EVENT;
5938       EV_TRAILER ((id)nil);
5939     }
5943 - (void)windowDidResignKey: (NSNotification *)notification
5944 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5946   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5947   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
5948   NSTRACE (windowDidResignKey);
5950   if (is_focus_frame)
5951     dpyinfo->x_focus_frame = 0;
5953   emacsframe->mouse_moved = 0;
5954   ns_frame_rehighlight (emacsframe);
5956   /* FIXME: for some reason needed on second and subsequent clicks away
5957             from sole-frame Emacs to get hollow box to show */
5958   if (!windowClosing && [[self window] isVisible] == YES)
5959     {
5960       x_update_cursor (emacsframe, 1);
5961       x_set_frame_alpha (emacsframe);
5962     }
5964   if (emacs_event && is_focus_frame)
5965     {
5966       [self deleteWorkingText];
5967       emacs_event->kind = FOCUS_OUT_EVENT;
5968       EV_TRAILER ((id)nil);
5969     }
5973 - (void)windowWillMiniaturize: sender
5975   NSTRACE (windowWillMiniaturize);
5979 - (BOOL)isFlipped
5981   return YES;
5985 - (BOOL)isOpaque
5987   return NO;
5991 - initFrameFromEmacs: (struct frame *)f
5993   NSRect r, wr;
5994   Lisp_Object tem;
5995   NSWindow *win;
5996   NSSize sz;
5997   NSColor *col;
5998   NSString *name;
6000   NSTRACE (initFrameFromEmacs);
6002   windowClosing = NO;
6003   processingCompose = NO;
6004   scrollbarsNeedingUpdate = 0;
6005   fs_state = FULLSCREEN_NONE;
6006   fs_before_fs = next_maximized = -1;
6007 #ifdef HAVE_NATIVE_FS
6008   fs_is_native = ns_use_native_fullscreen;
6009 #else
6010   fs_is_native = NO;
6011 #endif
6012   maximized_width = maximized_height = -1;
6013   nonfs_window = nil;
6015 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6017   ns_userRect = NSMakeRect (0, 0, 0, 0);
6018   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6019                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6020   [self initWithFrame: r];
6021   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6023   FRAME_NS_VIEW (f) = self;
6024   emacsframe = f;
6025 #ifdef NS_IMPL_COCOA
6026   old_title = 0;
6027   maximizing_resize = NO;
6028 #endif
6030   win = [[EmacsWindow alloc]
6031             initWithContentRect: r
6032                       styleMask: (NSResizableWindowMask |
6033 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6034                                   NSTitledWindowMask |
6035 #endif
6036                                   NSMiniaturizableWindowMask |
6037                                   NSClosableWindowMask)
6038                         backing: NSBackingStoreBuffered
6039                           defer: YES];
6041 #ifdef HAVE_NATIVE_FS
6042     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6043 #endif
6045   wr = [win frame];
6046   bwidth = f->border_width = wr.size.width - r.size.width;
6047   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6049   [win setAcceptsMouseMovedEvents: YES];
6050   [win setDelegate: self];
6051   [win useOptimizedDrawing: YES];
6053   sz.width = FRAME_COLUMN_WIDTH (f);
6054   sz.height = FRAME_LINE_HEIGHT (f);
6055   [win setResizeIncrements: sz];
6057   [[win contentView] addSubview: self];
6059   if (ns_drag_types)
6060     [self registerForDraggedTypes: ns_drag_types];
6062   tem = f->name;
6063   name = [NSString stringWithUTF8String:
6064                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6065   [win setTitle: name];
6067   /* toolbar support */
6068   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6069                          [NSString stringWithFormat: @"Emacs Frame %d",
6070                                    ns_window_num]];
6071   [win setToolbar: toolbar];
6072   [toolbar setVisible: NO];
6073 #ifdef NS_IMPL_COCOA
6074   {
6075     NSButton *toggleButton;
6076   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6077   [toggleButton setTarget: self];
6078   [toggleButton setAction: @selector (toggleToolbar: )];
6079   }
6080 #endif
6081   FRAME_TOOLBAR_HEIGHT (f) = 0;
6083   tem = f->icon_name;
6084   if (!NILP (tem))
6085     [win setMiniwindowTitle:
6086            [NSString stringWithUTF8String: SSDATA (tem)]];
6088   {
6089     NSScreen *screen = [win screen];
6091     if (screen != 0)
6092       [win setFrameTopLeftPoint: NSMakePoint
6093            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6094             IN_BOUND (-SCREENMAX,
6095                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6096   }
6098   [win makeFirstResponder: self];
6100   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6101                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6102   [win setBackgroundColor: col];
6103   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6104     [win setOpaque: NO];
6106   [self allocateGState];
6108   [NSApp registerServicesMenuSendTypes: ns_send_types
6109                            returnTypes: nil];
6111   ns_window_num++;
6112   return self;
6116 - (void)windowDidMove: sender
6118   NSWindow *win = [self window];
6119   NSRect r = [win frame];
6120   NSArray *screens = [NSScreen screens];
6121   NSScreen *screen = [screens objectAtIndex: 0];
6123   NSTRACE (windowDidMove);
6125   if (!emacsframe->output_data.ns)
6126     return;
6127   if (screen != nil)
6128     {
6129       emacsframe->left_pos = r.origin.x;
6130       emacsframe->top_pos =
6131         [screen frame].size.height - (r.origin.y + r.size.height);
6132     }
6136 /* Called AFTER method below, but before our windowWillResize call there leads
6137    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6138    location so set_window_size moves the frame. */
6139 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6141   emacsframe->output_data.ns->zooming = 1;
6142   return YES;
6146 /* Override to do something slightly nonstandard, but nice.  First click on
6147    zoom button will zoom vertically.  Second will zoom completely.  Third
6148    returns to original. */
6149 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6150                         defaultFrame:(NSRect)defaultFrame
6152   NSRect result = [sender frame];
6154   NSTRACE (windowWillUseStandardFrame);
6156   if (fs_before_fs != -1) /* Entering fullscreen */
6157       {
6158         result = defaultFrame;
6159       }
6160   else if (next_maximized == FULLSCREEN_HEIGHT
6161       || (next_maximized == -1
6162           && abs (defaultFrame.size.height - result.size.height)
6163           > FRAME_LINE_HEIGHT (emacsframe)))
6164     {
6165       /* first click */
6166       ns_userRect = result;
6167       maximized_height = result.size.height = defaultFrame.size.height;
6168       maximized_width = -1;
6169       result.origin.y = defaultFrame.origin.y;
6170       [self setFSValue: FULLSCREEN_HEIGHT];
6171 #ifdef NS_IMPL_COCOA
6172       maximizing_resize = YES;
6173 #endif
6174     }
6175   else if (next_maximized == FULLSCREEN_WIDTH)
6176     {
6177       ns_userRect = result;
6178       maximized_width = result.size.width = defaultFrame.size.width;
6179       maximized_height = -1;
6180       result.origin.x = defaultFrame.origin.x;
6181       [self setFSValue: FULLSCREEN_WIDTH];
6182     }
6183   else if (next_maximized == FULLSCREEN_MAXIMIZED
6184            || (next_maximized == -1
6185                && abs (defaultFrame.size.width - result.size.width)
6186                > FRAME_COLUMN_WIDTH (emacsframe)))
6187     {
6188       result = defaultFrame;  /* second click */
6189       maximized_width = result.size.width;
6190       maximized_height = result.size.height;
6191       [self setFSValue: FULLSCREEN_MAXIMIZED];
6192 #ifdef NS_IMPL_COCOA
6193       maximizing_resize = YES;
6194 #endif
6195     }
6196   else
6197     {
6198       /* restore */
6199       result = ns_userRect.size.height ? ns_userRect : result;
6200       ns_userRect = NSMakeRect (0, 0, 0, 0);
6201 #ifdef NS_IMPL_COCOA
6202       maximizing_resize = fs_state != FULLSCREEN_NONE;
6203 #endif
6204       [self setFSValue: FULLSCREEN_NONE];
6205       maximized_width = maximized_height = -1;
6206     }
6208   if (fs_before_fs == -1) next_maximized = -1;
6209   [self windowWillResize: sender toSize: result.size];
6210   return result;
6214 - (void)windowDidDeminiaturize: sender
6216   NSTRACE (windowDidDeminiaturize);
6217   if (!emacsframe->output_data.ns)
6218     return;
6220   SET_FRAME_ICONIFIED (emacsframe, 0);
6221   SET_FRAME_VISIBLE (emacsframe, 1);
6222   windows_or_buffers_changed = 63;
6224   if (emacs_event)
6225     {
6226       emacs_event->kind = DEICONIFY_EVENT;
6227       EV_TRAILER ((id)nil);
6228     }
6232 - (void)windowDidExpose: sender
6234   NSTRACE (windowDidExpose);
6235   if (!emacsframe->output_data.ns)
6236     return;
6238   SET_FRAME_VISIBLE (emacsframe, 1);
6239   SET_FRAME_GARBAGED (emacsframe);
6241   if (send_appdefined)
6242     ns_send_appdefined (-1);
6246 - (void)windowDidMiniaturize: sender
6248   NSTRACE (windowDidMiniaturize);
6249   if (!emacsframe->output_data.ns)
6250     return;
6252   SET_FRAME_ICONIFIED (emacsframe, 1);
6253   SET_FRAME_VISIBLE (emacsframe, 0);
6255   if (emacs_event)
6256     {
6257       emacs_event->kind = ICONIFY_EVENT;
6258       EV_TRAILER ((id)nil);
6259     }
6262 #ifdef HAVE_NATIVE_FS
6263 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6264       willUseFullScreenPresentationOptions:
6265   (NSApplicationPresentationOptions)proposedOptions
6267   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6269 #endif
6271 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6273   fs_before_fs = fs_state;
6276 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6278   [self setFSValue: FULLSCREEN_BOTH];
6279   if (! [self fsIsNative])
6280     {
6281       [self windowDidBecomeKey:notification];
6282       [nonfs_window orderOut:self];
6283     }
6284   else
6285     {
6286       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6287 #ifdef NS_IMPL_COCOA
6288 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6289       unsigned val = (unsigned)[NSApp presentationOptions];
6291       // OSX 10.7 bug fix, the menu won't appear without this.
6292       // val is non-zero on other OSX versions.
6293       if (val == 0)
6294         {
6295           NSApplicationPresentationOptions options
6296             = NSApplicationPresentationAutoHideDock
6297             | NSApplicationPresentationAutoHideMenuBar
6298             | NSApplicationPresentationFullScreen
6299             | NSApplicationPresentationAutoHideToolbar;
6301           [NSApp setPresentationOptions: options];
6302         }
6303 #endif
6304 #endif
6305       [toolbar setVisible:tbar_visible];
6306     }
6309 - (void)windowWillExitFullScreen:(NSNotification *)notification
6311   if (next_maximized != -1)
6312     fs_before_fs = next_maximized;
6315 - (void)windowDidExitFullScreen:(NSNotification *)notification
6317   [self setFSValue: fs_before_fs];
6318   fs_before_fs = -1;
6319 #ifdef HAVE_NATIVE_FS
6320   [self updateCollectionBehaviour];
6321 #endif
6322   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6323     {
6324       [toolbar setVisible:YES];
6325       update_frame_tool_bar (emacsframe);
6326       [self updateFrameSize:YES];
6327       [[self window] display];
6328     }
6329   else
6330     [toolbar setVisible:NO];
6332   if (next_maximized != -1)
6333     [[self window] performZoom:self];
6336 - (BOOL)fsIsNative
6338   return fs_is_native;
6341 - (BOOL)isFullscreen
6343   if (! fs_is_native) return nonfs_window != nil;
6344 #ifdef HAVE_NATIVE_FS
6345   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6346 #else
6347   return NO;
6348 #endif
6351 #ifdef HAVE_NATIVE_FS
6352 - (void)updateCollectionBehaviour
6354   if (! [self isFullscreen])
6355     {
6356       NSWindow *win = [self window];
6357       NSWindowCollectionBehavior b = [win collectionBehavior];
6358       if (ns_use_native_fullscreen)
6359         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6360       else
6361         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6363       [win setCollectionBehavior: b];
6364       fs_is_native = ns_use_native_fullscreen;
6365     }
6367 #endif
6369 - (void)toggleFullScreen: (id)sender
6371   NSWindow *w, *fw;
6372   BOOL onFirstScreen;
6373   struct frame *f;
6374   NSSize sz;
6375   NSRect r, wr;
6376   NSColor *col;
6378   if (fs_is_native)
6379     {
6380 #ifdef HAVE_NATIVE_FS
6381       [[self window] toggleFullScreen:sender];
6382 #endif
6383       return;
6384     }
6386   w = [self window];
6387   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6388   f = emacsframe;
6389   wr = [w frame];
6390   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6391                                  (FRAME_DEFAULT_FACE (f)),
6392                                  f);
6394   sz.width = FRAME_COLUMN_WIDTH (f);
6395   sz.height = FRAME_LINE_HEIGHT (f);
6397   if (fs_state != FULLSCREEN_BOTH)
6398     {
6399       /* Hide dock and menubar if we are on the primary screen.  */
6400       if (onFirstScreen)
6401         {
6402 #if defined (NS_IMPL_COCOA) && \
6403   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6404           NSApplicationPresentationOptions options
6405             = NSApplicationPresentationAutoHideDock
6406             | NSApplicationPresentationAutoHideMenuBar;
6408           [NSApp setPresentationOptions: options];
6409 #else
6410           [NSMenu setMenuBarVisible:NO];
6411 #endif
6412         }
6414       fw = [[EmacsFSWindow alloc]
6415                        initWithContentRect:[w contentRectForFrameRect:wr]
6416                                  styleMask:NSBorderlessWindowMask
6417                                    backing:NSBackingStoreBuffered
6418                                      defer:YES
6419                                     screen:[w screen]];
6421       [fw setContentView:[w contentView]];
6422       [fw setTitle:[w title]];
6423       [fw setDelegate:self];
6424       [fw setAcceptsMouseMovedEvents: YES];
6425       [fw useOptimizedDrawing: YES];
6426       [fw setResizeIncrements: sz];
6427       [fw setBackgroundColor: col];
6428       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6429         [fw setOpaque: NO];
6431       f->border_width = 0;
6432       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6433       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6434       FRAME_TOOLBAR_HEIGHT (f) = 0;
6436       nonfs_window = w;
6438       [self windowWillEnterFullScreen:nil];
6439       [fw makeKeyAndOrderFront:NSApp];
6440       [fw makeFirstResponder:self];
6441       [w orderOut:self];
6442       r = [fw frameRectForContentRect:[[fw screen] frame]];
6443       [fw setFrame: r display:YES animate:YES];
6444       [self windowDidEnterFullScreen:nil];
6445       [fw display];
6446     }
6447   else
6448     {
6449       fw = w;
6450       w = nonfs_window;
6451       nonfs_window = nil;
6453       if (onFirstScreen)
6454         {
6455 #if defined (NS_IMPL_COCOA) && \
6456   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6457           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6458 #else
6459           [NSMenu setMenuBarVisible:YES];
6460 #endif
6461         }
6463       [w setContentView:[fw contentView]];
6464       [w setResizeIncrements: sz];
6465       [w setBackgroundColor: col];
6466       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6467         [w setOpaque: NO];
6469       f->border_width = bwidth;
6470       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6471       if (FRAME_EXTERNAL_TOOL_BAR (f))
6472         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6474       [self windowWillExitFullScreen:nil];
6475       [fw setFrame: [w frame] display:YES animate:YES];
6476       [fw close];
6477       [w makeKeyAndOrderFront:NSApp];
6478       [self windowDidExitFullScreen:nil];
6479       [self updateFrameSize:YES];
6480     }
6483 - (void)handleFS
6485   if (fs_state != emacsframe->want_fullscreen)
6486     {
6487       if (fs_state == FULLSCREEN_BOTH)
6488         {
6489           [self toggleFullScreen:self];
6490         }
6492       switch (emacsframe->want_fullscreen)
6493         {
6494         case FULLSCREEN_BOTH:
6495           [self toggleFullScreen:self];
6496           break;
6497         case FULLSCREEN_WIDTH:
6498           next_maximized = FULLSCREEN_WIDTH;
6499           if (fs_state != FULLSCREEN_BOTH)
6500             [[self window] performZoom:self];
6501           break;
6502         case FULLSCREEN_HEIGHT:
6503           next_maximized = FULLSCREEN_HEIGHT;
6504           if (fs_state != FULLSCREEN_BOTH)
6505             [[self window] performZoom:self];
6506           break;
6507         case FULLSCREEN_MAXIMIZED:
6508           next_maximized = FULLSCREEN_MAXIMIZED;
6509           if (fs_state != FULLSCREEN_BOTH)
6510             [[self window] performZoom:self];
6511           break;
6512         case FULLSCREEN_NONE:
6513           if (fs_state != FULLSCREEN_BOTH)
6514             {
6515               next_maximized = FULLSCREEN_NONE;
6516               [[self window] performZoom:self];
6517             }
6518           break;
6519         }
6521       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6522     }
6526 - (void) setFSValue: (int)value
6528   Lisp_Object lval = Qnil;
6529   switch (value)
6530     {
6531     case FULLSCREEN_BOTH:
6532       lval = Qfullboth;
6533       break;
6534     case FULLSCREEN_WIDTH:
6535       lval = Qfullwidth;
6536       break;
6537     case FULLSCREEN_HEIGHT:
6538       lval = Qfullheight;
6539       break;
6540     case FULLSCREEN_MAXIMIZED:
6541       lval = Qmaximized;
6542       break;
6543     }
6544   store_frame_param (emacsframe, Qfullscreen, lval);
6545   fs_state = value;
6548 - (void)mouseEntered: (NSEvent *)theEvent
6550   NSTRACE (mouseEntered);
6551   if (emacsframe)
6552     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6553       = EV_TIMESTAMP (theEvent);
6557 - (void)mouseExited: (NSEvent *)theEvent
6559   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6561   NSTRACE (mouseExited);
6563   if (!hlinfo)
6564     return;
6566   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6567     = EV_TIMESTAMP (theEvent);
6569   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6570     {
6571       clear_mouse_face (hlinfo);
6572       hlinfo->mouse_face_mouse_frame = 0;
6573     }
6577 - menuDown: sender
6579   NSTRACE (menuDown);
6580   if (context_menu_value == -1)
6581     context_menu_value = [sender tag];
6582   else
6583     {
6584       NSInteger tag = [sender tag];
6585       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6586                                     emacsframe->menu_bar_vector,
6587                                     (void *)tag);
6588     }
6590   ns_send_appdefined (-1);
6591   return self;
6595 - (EmacsToolbar *)toolbar
6597   return toolbar;
6601 /* this gets called on toolbar button click */
6602 - toolbarClicked: (id)item
6604   NSEvent *theEvent;
6605   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6607   NSTRACE (toolbarClicked);
6609   if (!emacs_event)
6610     return self;
6612   /* send first event (for some reason two needed) */
6613   theEvent = [[self window] currentEvent];
6614   emacs_event->kind = TOOL_BAR_EVENT;
6615   XSETFRAME (emacs_event->arg, emacsframe);
6616   EV_TRAILER (theEvent);
6618   emacs_event->kind = TOOL_BAR_EVENT;
6619 /*   XSETINT (emacs_event->code, 0); */
6620   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6621                            idx + TOOL_BAR_ITEM_KEY);
6622   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6623   EV_TRAILER (theEvent);
6624   return self;
6628 - toggleToolbar: (id)sender
6630   if (!emacs_event)
6631     return self;
6633   emacs_event->kind = NS_NONKEY_EVENT;
6634   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6635   EV_TRAILER ((id)nil);
6636   return self;
6640 - (void)drawRect: (NSRect)rect
6642   int x = NSMinX (rect), y = NSMinY (rect);
6643   int width = NSWidth (rect), height = NSHeight (rect);
6645   NSTRACE (drawRect);
6647   if (!emacsframe || !emacsframe->output_data.ns)
6648     return;
6650   ns_clear_frame_area (emacsframe, x, y, width, height);
6651   expose_frame (emacsframe, x, y, width, height);
6653   /*
6654     drawRect: may be called (at least in OS X 10.5) for invisible
6655     views as well for some reason.  Thus, do not infer visibility
6656     here.
6658     emacsframe->async_visible = 1;
6659     emacsframe->async_iconified = 0;
6660   */
6664 /* NSDraggingDestination protocol methods.  Actually this is not really a
6665    protocol, but a category of Object.  O well...  */
6667 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6669   NSTRACE (draggingEntered);
6670   return NSDragOperationGeneric;
6674 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6676   return YES;
6680 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6682   id pb;
6683   int x, y;
6684   NSString *type;
6685   NSEvent *theEvent = [[self window] currentEvent];
6686   NSPoint position;
6687   NSDragOperation op = [sender draggingSourceOperationMask];
6688   int modifiers = 0;
6690   NSTRACE (performDragOperation);
6692   if (!emacs_event)
6693     return NO;
6695   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6696   x = lrint (position.x);  y = lrint (position.y);
6698   pb = [sender draggingPasteboard];
6699   type = [pb availableTypeFromArray: ns_drag_types];
6701   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6702       // URL drags contain all operations (0xf), don't allow all to be set.
6703       (op & 0xf) != 0xf)
6704     {
6705       if (op & NSDragOperationLink)
6706         modifiers |= NSControlKeyMask;
6707       if (op & NSDragOperationCopy)
6708         modifiers |= NSAlternateKeyMask;
6709       if (op & NSDragOperationGeneric)
6710         modifiers |= NSCommandKeyMask;
6711     }
6713   modifiers = EV_MODIFIERS2 (modifiers);
6714   if (type == 0)
6715     {
6716       return NO;
6717     }
6718   else if ([type isEqualToString: NSFilenamesPboardType])
6719     {
6720       NSArray *files;
6721       NSEnumerator *fenum;
6722       NSString *file;
6724       if (!(files = [pb propertyListForType: type]))
6725         return NO;
6727       fenum = [files objectEnumerator];
6728       while ( (file = [fenum nextObject]) )
6729         {
6730           emacs_event->kind = DRAG_N_DROP_EVENT;
6731           XSETINT (emacs_event->x, x);
6732           XSETINT (emacs_event->y, y);
6733           ns_input_file = append2 (ns_input_file,
6734                                    build_string ([file UTF8String]));
6735           emacs_event->modifiers = modifiers;
6736           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
6737           EV_TRAILER (theEvent);
6738         }
6739       return YES;
6740     }
6741   else if ([type isEqualToString: NSURLPboardType])
6742     {
6743       NSURL *url = [NSURL URLFromPasteboard: pb];
6744       if (url == nil) return NO;
6746       emacs_event->kind = DRAG_N_DROP_EVENT;
6747       XSETINT (emacs_event->x, x);
6748       XSETINT (emacs_event->y, y);
6749       emacs_event->modifiers = modifiers;
6750       emacs_event->arg =  list2 (Qurl,
6751                                  build_string ([[url absoluteString]
6752                                                  UTF8String]));
6753       EV_TRAILER (theEvent);
6755       if ([url isFileURL] != NO)
6756         {
6757           NSString *file = [url path];
6758           ns_input_file = append2 (ns_input_file,
6759                                    build_string ([file UTF8String]));
6760         }
6761       return YES;
6762     }
6763   else if ([type isEqualToString: NSStringPboardType]
6764            || [type isEqualToString: NSTabularTextPboardType])
6765     {
6766       NSString *data;
6768       if (! (data = [pb stringForType: type]))
6769         return NO;
6771       emacs_event->kind = DRAG_N_DROP_EVENT;
6772       XSETINT (emacs_event->x, x);
6773       XSETINT (emacs_event->y, y);
6774       emacs_event->modifiers = modifiers;
6775       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
6776       EV_TRAILER (theEvent);
6777       return YES;
6778     }
6779   else
6780     {
6781       error ("Invalid data type in dragging pasteboard.");
6782       return NO;
6783     }
6787 - (id) validRequestorForSendType: (NSString *)typeSent
6788                       returnType: (NSString *)typeReturned
6790   NSTRACE (validRequestorForSendType);
6791   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6792       && typeReturned == nil)
6793     {
6794       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6795         return self;
6796     }
6798   return [super validRequestorForSendType: typeSent
6799                                returnType: typeReturned];
6803 /* The next two methods are part of NSServicesRequests informal protocol,
6804    supposedly called when a services menu item is chosen from this app.
6805    But this should not happen because we override the services menu with our
6806    own entries which call ns-perform-service.
6807    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6808    So let's at least stub them out until further investigation can be done. */
6810 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6812   /* we could call ns_string_from_pasteboard(pboard) here but then it should
6813      be written into the buffer in place of the existing selection..
6814      ordinary service calls go through functions defined in ns-win.el */
6815   return NO;
6818 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6820   NSArray *typesDeclared;
6821   Lisp_Object val;
6823   /* We only support NSStringPboardType */
6824   if ([types containsObject:NSStringPboardType] == NO) {
6825     return NO;
6826   }
6828   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6829   if (CONSP (val) && SYMBOLP (XCAR (val)))
6830     {
6831       val = XCDR (val);
6832       if (CONSP (val) && NILP (XCDR (val)))
6833         val = XCAR (val);
6834     }
6835   if (! STRINGP (val))
6836     return NO;
6838   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6839   [pb declareTypes:typesDeclared owner:nil];
6840   ns_string_to_pasteboard (pb, val);
6841   return YES;
6845 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6846    (gives a miniaturized version of the window); currently we use the latter for
6847    frames whose active buffer doesn't correspond to any file
6848    (e.g., '*scratch*') */
6849 - setMiniwindowImage: (BOOL) setMini
6851   id image = [[self window] miniwindowImage];
6852   NSTRACE (setMiniwindowImage);
6854   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6855      about "AppleDockIconEnabled" notwithstanding, however the set message
6856      below has its effect nonetheless. */
6857   if (image != emacsframe->output_data.ns->miniimage)
6858     {
6859       if (image && [image isKindOfClass: [EmacsImage class]])
6860         [image release];
6861       [[self window] setMiniwindowImage:
6862                        setMini ? emacsframe->output_data.ns->miniimage : nil];
6863     }
6865   return self;
6869 - (void) setRows: (int) r andColumns: (int) c
6871   rows = r;
6872   cols = c;
6875 @end  /* EmacsView */
6879 /* ==========================================================================
6881     EmacsWindow implementation
6883    ========================================================================== */
6885 @implementation EmacsWindow
6887 #ifdef NS_IMPL_COCOA
6888 - (id)accessibilityAttributeValue:(NSString *)attribute
6890   Lisp_Object str = Qnil;
6891   struct frame *f = SELECTED_FRAME ();
6892   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
6894   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6895     return NSAccessibilityTextFieldRole;
6897   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6898       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6899     {
6900       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6901     }
6902   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6903     {
6904       if (! NILP (BVAR (curbuf, mark_active)))
6905           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6907       if (NILP (str))
6908         {
6909           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6910           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6911           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6913           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6914             str = make_uninit_multibyte_string (range, byte_range);
6915           else
6916             str = make_uninit_string (range);
6917           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6918              Is this a problem?  */
6919           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6920         }
6921     }
6924   if (! NILP (str))
6925     {
6926       if (CONSP (str) && SYMBOLP (XCAR (str)))
6927         {
6928           str = XCDR (str);
6929           if (CONSP (str) && NILP (XCDR (str)))
6930             str = XCAR (str);
6931         }
6932       if (STRINGP (str))
6933         {
6934           const char *utfStr = SSDATA (str);
6935           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6936           return nsStr;
6937         }
6938     }
6940   return [super accessibilityAttributeValue:attribute];
6942 #endif /* NS_IMPL_COCOA */
6944 /* If we have multiple monitors, one above the other, we don't want to
6945    restrict the height to just one monitor.  So we override this.  */
6946 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6948   /* When making the frame visible for the first time or if there is just
6949      one screen, we want to constrain.  Other times not.  */
6950   NSUInteger nr_screens = [[NSScreen screens] count];
6951   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6952   NSTRACE (constrainFrameRect);
6953   NSTRACE_RECT ("input", frameRect);
6955   if (ns_menu_bar_should_be_hidden ())
6956     return frameRect;
6958   /* The default implementation does two things 1) ensure that the top
6959      of the rectangle is below the menu bar (or below the top of the
6960      screen) and 2) resizes windows larger than the screen. As we
6961      don't want the latter, a smaller rectangle is used. */
6962 #define FAKE_HEIGHT 64
6963   float old_top = frameRect.origin.y + frameRect.size.height;
6964   NSRect r;
6965   r.size.height = FAKE_HEIGHT;
6966   r.size.width = frameRect.size.width;
6967   r.origin.x = frameRect.origin.x;
6968   r.origin.y = old_top - FAKE_HEIGHT;
6970   NSTRACE_RECT ("input to super", r);
6972   r = [super constrainFrameRect:r toScreen:screen];
6974   NSTRACE_RECT ("output from super", r);
6976   float new_top = r.origin.y + FAKE_HEIGHT;
6977   if (new_top < old_top)
6978   {
6979     frameRect.origin.y = new_top - frameRect.size.height;
6980   }
6982   NSTRACE_RECT ("output", frameRect);
6984   return frameRect;
6985 #undef FAKE_HEIGHT
6988 @end /* EmacsWindow */
6991 @implementation EmacsFSWindow
6993 - (BOOL)canBecomeKeyWindow
6995   return YES;
6998 - (BOOL)canBecomeMainWindow
7000   return YES;
7003 @end
7005 /* ==========================================================================
7007     EmacsScroller implementation
7009    ========================================================================== */
7012 @implementation EmacsScroller
7014 /* for repeat button push */
7015 #define SCROLL_BAR_FIRST_DELAY 0.5
7016 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7018 + (CGFloat) scrollerWidth
7020   /* TODO: if we want to allow variable widths, this is the place to do it,
7021            however neither GNUstep nor Cocoa support it very well */
7022   return [NSScroller scrollerWidth];
7026 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7028   NSTRACE (EmacsScroller_initFrame);
7030   r.size.width = [EmacsScroller scrollerWidth];
7031   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7032   [self setContinuous: YES];
7033   [self setEnabled: YES];
7035   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7036      locked against the top and bottom edges, and right edge on OS X, where
7037      scrollers are on right. */
7038 #ifdef NS_IMPL_GNUSTEP
7039   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7040 #else
7041   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7042 #endif
7044   win = nwin;
7045   condemned = NO;
7046   pixel_height = NSHeight (r);
7047   if (pixel_height == 0) pixel_height = 1;
7048   min_portion = 20 / pixel_height;
7050   frame = XFRAME (XWINDOW (win)->frame);
7051   if (FRAME_LIVE_P (frame))
7052     {
7053       int i;
7054       EmacsView *view = FRAME_NS_VIEW (frame);
7055       NSView *sview = [[view window] contentView];
7056       NSArray *subs = [sview subviews];
7058       /* disable optimization stopping redraw of other scrollbars */
7059       view->scrollbarsNeedingUpdate = 0;
7060       for (i =[subs count]-1; i >= 0; i--)
7061         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7062           view->scrollbarsNeedingUpdate++;
7063       [sview addSubview: self];
7064     }
7066 /*  [self setFrame: r]; */
7068   return self;
7072 - (void)setFrame: (NSRect)newRect
7074   NSTRACE (EmacsScroller_setFrame);
7075 /*  block_input (); */
7076   pixel_height = NSHeight (newRect);
7077   if (pixel_height == 0) pixel_height = 1;
7078   min_portion = 20 / pixel_height;
7079   [super setFrame: newRect];
7080   [self display];
7081 /*  unblock_input (); */
7085 - (void)dealloc
7087   NSTRACE (EmacsScroller_dealloc);
7088   if (!NILP (win))
7089     wset_vertical_scroll_bar (XWINDOW (win), Qnil);
7090   [super dealloc];
7094 - condemn
7096   NSTRACE (condemn);
7097   condemned =YES;
7098   return self;
7102 - reprieve
7104   NSTRACE (reprieve);
7105   condemned =NO;
7106   return self;
7110 - judge
7112   NSTRACE (judge);
7113   if (condemned)
7114     {
7115       EmacsView *view;
7116       block_input ();
7117       /* ensure other scrollbar updates after deletion */
7118       view = (EmacsView *)FRAME_NS_VIEW (frame);
7119       if (view != nil)
7120         view->scrollbarsNeedingUpdate++;
7121       [self removeFromSuperview];
7122       [self release];
7123       unblock_input ();
7124     }
7125   return self;
7129 - (void)resetCursorRects
7131   NSRect visible = [self visibleRect];
7132   NSTRACE (resetCursorRects);
7134   if (!NSIsEmptyRect (visible))
7135     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7136   [[NSCursor arrowCursor] setOnMouseEntered: YES];
7140 - (int) checkSamePosition: (int) position portion: (int) portion
7141                     whole: (int) whole
7143   return em_position ==position && em_portion ==portion && em_whole ==whole
7144     && portion != whole; /* needed for resize empty buf */
7148 - setPosition: (int)position portion: (int)portion whole: (int)whole
7150   NSTRACE (setPosition);
7152   em_position = position;
7153   em_portion = portion;
7154   em_whole = whole;
7156   if (portion >= whole)
7157     {
7158 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
7159       [self setKnobProportion: 1.0];
7160       [self setDoubleValue: 1.0];
7161 #else
7162       [self setFloatValue: 0.0 knobProportion: 1.0];
7163 #endif
7164     }
7165   else
7166     {
7167       float pos;
7168       CGFloat por;
7169       portion = max ((float)whole*min_portion/pixel_height, portion);
7170       pos = (float)position / (whole - portion);
7171       por = (CGFloat)portion/whole;
7172 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
7173       [self setKnobProportion: por];
7174       [self setDoubleValue: pos];
7175 #else
7176       [self setFloatValue: pos knobProportion: por];
7177 #endif
7178     }
7180   /* Events may come here even if the event loop is not running.
7181      If we don't enter the event loop, the scroll bar will not update.
7182      So send SIGIO to ourselves.  */
7183   if (apploopnr == 0) raise (SIGIO);
7185   return self;
7188 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
7189      drag events will go directly to the EmacsScroller.  Leaving in for now. */
7190 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
7191                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
7193   *part = last_hit_part;
7194   *window = win;
7195   XSETINT (*y, pixel_height);
7196   if ([self floatValue] > 0.999F)
7197     XSETINT (*x, pixel_height);
7198   else
7199     XSETINT (*x, pixel_height * [self floatValue]);
7203 /* set up emacs_event */
7204 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7206   if (!emacs_event)
7207     return;
7209   emacs_event->part = last_hit_part;
7210   emacs_event->code = 0;
7211   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7212   emacs_event->frame_or_window = win;
7213   emacs_event->timestamp = EV_TIMESTAMP (e);
7214   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7215   emacs_event->arg = Qnil;
7216   XSETINT (emacs_event->x, loc * pixel_height);
7217   XSETINT (emacs_event->y, pixel_height-20);
7219   if (q_event_ptr)
7220     {
7221       n_emacs_events_pending++;
7222       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7223     }
7224   else
7225     hold_event (emacs_event);
7226   EVENT_INIT (*emacs_event);
7227   ns_send_appdefined (-1);
7231 /* called manually thru timer to implement repeated button action w/hold-down */
7232 - repeatScroll: (NSTimer *)scrollEntry
7234   NSEvent *e = [[self window] currentEvent];
7235   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7236   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7238   /* clear timer if need be */
7239   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7240     {
7241         [scroll_repeat_entry invalidate];
7242         [scroll_repeat_entry release];
7243         scroll_repeat_entry = nil;
7245         if (inKnob)
7246           return self;
7248         scroll_repeat_entry
7249           = [[NSTimer scheduledTimerWithTimeInterval:
7250                         SCROLL_BAR_CONTINUOUS_DELAY
7251                                             target: self
7252                                           selector: @selector (repeatScroll:)
7253                                           userInfo: 0
7254                                            repeats: YES]
7255               retain];
7256     }
7258   [self sendScrollEventAtLoc: 0 fromEvent: e];
7259   return self;
7263 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7264    mouseDragged events without going into a modal loop. */
7265 - (void)mouseDown: (NSEvent *)e
7267   NSRect sr, kr;
7268   /* hitPart is only updated AFTER event is passed on */
7269   NSScrollerPart part = [self testPart: [e locationInWindow]];
7270   CGFloat inc = 0.0, loc, kloc, pos;
7271   int edge = 0;
7273   NSTRACE (EmacsScroller_mouseDown);
7275   switch (part)
7276     {
7277     case NSScrollerDecrementPage:
7278         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7279     case NSScrollerIncrementPage:
7280         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7281     case NSScrollerDecrementLine:
7282       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7283     case NSScrollerIncrementLine:
7284       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7285     case NSScrollerKnob:
7286       last_hit_part = scroll_bar_handle; break;
7287     case NSScrollerKnobSlot:  /* GNUstep-only */
7288       last_hit_part = scroll_bar_move_ratio; break;
7289     default:  /* NSScrollerNoPart? */
7290       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7291                (long) part);
7292       return;
7293     }
7295   if (inc != 0.0)
7296     {
7297       pos = 0;      /* ignored */
7299       /* set a timer to repeat, as we can't let superclass do this modally */
7300       scroll_repeat_entry
7301         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7302                                             target: self
7303                                           selector: @selector (repeatScroll:)
7304                                           userInfo: 0
7305                                            repeats: YES]
7306             retain];
7307     }
7308   else
7309     {
7310       /* handle, or on GNUstep possibly slot */
7311       NSEvent *fake_event;
7313       /* compute float loc in slot and mouse offset on knob */
7314       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7315                       toView: nil];
7316       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7317       if (loc <= 0.0)
7318         {
7319           loc = 0.0;
7320           edge = -1;
7321         }
7322       else if (loc >= NSHeight (sr))
7323         {
7324           loc = NSHeight (sr);
7325           edge = 1;
7326         }
7328       if (edge)
7329         kloc = 0.5 * edge;
7330       else
7331         {
7332           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7333                           toView: nil];
7334           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7335         }
7336       last_mouse_offset = kloc;
7338       /* if knob, tell emacs a location offset by knob pos
7339          (to indicate top of handle) */
7340       if (part == NSScrollerKnob)
7341           pos = (loc - last_mouse_offset) / NSHeight (sr);
7342       else
7343         /* else this is a slot click on GNUstep: go straight there */
7344         pos = loc / NSHeight (sr);
7346       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7347       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7348                                       location: [e locationInWindow]
7349                                  modifierFlags: [e modifierFlags]
7350                                      timestamp: [e timestamp]
7351                                   windowNumber: [e windowNumber]
7352                                        context: [e context]
7353                                    eventNumber: [e eventNumber]
7354                                     clickCount: [e clickCount]
7355                                       pressure: [e pressure]];
7356       [super mouseUp: fake_event];
7357     }
7359   if (part != NSScrollerKnob)
7360     [self sendScrollEventAtLoc: pos fromEvent: e];
7364 /* Called as we manually track scroller drags, rather than superclass. */
7365 - (void)mouseDragged: (NSEvent *)e
7367     NSRect sr;
7368     double loc, pos;
7370     NSTRACE (EmacsScroller_mouseDragged);
7372       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7373                       toView: nil];
7374       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7376       if (loc <= 0.0)
7377         {
7378           loc = 0.0;
7379         }
7380       else if (loc >= NSHeight (sr) + last_mouse_offset)
7381         {
7382           loc = NSHeight (sr) + last_mouse_offset;
7383         }
7385       pos = (loc - last_mouse_offset) / NSHeight (sr);
7386       [self sendScrollEventAtLoc: pos fromEvent: e];
7390 - (void)mouseUp: (NSEvent *)e
7392   if (scroll_repeat_entry)
7393     {
7394       [scroll_repeat_entry invalidate];
7395       [scroll_repeat_entry release];
7396       scroll_repeat_entry = nil;
7397     }
7398   last_hit_part = 0;
7402 /* treat scrollwheel events in the bar as though they were in the main window */
7403 - (void) scrollWheel: (NSEvent *)theEvent
7405   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7406   [view mouseDown: theEvent];
7409 @end  /* EmacsScroller */
7412 #ifdef NS_IMPL_GNUSTEP
7413 /* Dummy class to get rid of startup warnings.  */
7414 @implementation EmacsDocument
7416 @end
7417 #endif
7420 /* ==========================================================================
7422    Font-related functions; these used to be in nsfaces.m
7424    ========================================================================== */
7427 Lisp_Object
7428 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7430   struct font *font = XFONT_OBJECT (font_object);
7431   EmacsView *view = FRAME_NS_VIEW (f);
7433   if (fontset < 0)
7434     fontset = fontset_from_font (font_object);
7435   FRAME_FONTSET (f) = fontset;
7437   if (FRAME_FONT (f) == font)
7438     /* This font is already set in frame F.  There's nothing more to
7439        do.  */
7440     return font_object;
7442   FRAME_FONT (f) = font;
7444   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7445   FRAME_COLUMN_WIDTH (f) = font->average_width;
7446   FRAME_LINE_HEIGHT (f) = font->height;
7448   compute_fringe_widths (f, 1);
7450   /* Compute the scroll bar width in character columns.  */
7451   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7452     {
7453       int wid = FRAME_COLUMN_WIDTH (f);
7454       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7455         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7456     }
7457   else
7458     {
7459       int wid = FRAME_COLUMN_WIDTH (f);
7460       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7461     }
7463   /* Now make the frame display the given font.  */
7464   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7465     x_set_window_size (f, 0, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7466                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 1);
7468   return font_object;
7472 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7473 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7474          in 1.43. */
7476 const char *
7477 ns_xlfd_to_fontname (const char *xlfd)
7478 /* --------------------------------------------------------------------------
7479     Convert an X font name (XLFD) to an NS font name.
7480     Only family is used.
7481     The string returned is temporarily allocated.
7482    -------------------------------------------------------------------------- */
7484   char *name = xmalloc (180);
7485   int i, len;
7486   const char *ret;
7488   if (!strncmp (xlfd, "--", 2))
7489     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7490   else
7491     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7493   /* stopgap for malformed XLFD input */
7494   if (strlen (name) == 0)
7495     strcpy (name, "Monaco");
7497   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7498      also uppercase after '-' or ' ' */
7499   name[0] = c_toupper (name[0]);
7500   for (len =strlen (name), i =0; i<len; i++)
7501     {
7502       if (name[i] == '$')
7503         {
7504           name[i] = '-';
7505           if (i+1<len)
7506             name[i+1] = c_toupper (name[i+1]);
7507         }
7508       else if (name[i] == '_')
7509         {
7510           name[i] = ' ';
7511           if (i+1<len)
7512             name[i+1] = c_toupper (name[i+1]);
7513         }
7514     }
7515 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7516   ret = [[NSString stringWithUTF8String: name] UTF8String];
7517   xfree (name);
7518   return ret;
7522 void
7523 syms_of_nsterm (void)
7525   NSTRACE (syms_of_nsterm);
7527   ns_antialias_threshold = 10.0;
7529   /* from 23+ we need to tell emacs what modifiers there are.. */
7530   DEFSYM (Qmodifier_value, "modifier-value");
7531   DEFSYM (Qalt, "alt");
7532   DEFSYM (Qhyper, "hyper");
7533   DEFSYM (Qmeta, "meta");
7534   DEFSYM (Qsuper, "super");
7535   DEFSYM (Qcontrol, "control");
7536   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7538   DEFSYM (Qfile, "file");
7539   DEFSYM (Qurl, "url");
7541   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7542   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7543   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7544   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7545   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7547   DEFVAR_LISP ("ns-input-file", ns_input_file,
7548               "The file specified in the last NS event.");
7549   ns_input_file =Qnil;
7551   DEFVAR_LISP ("ns-working-text", ns_working_text,
7552               "String for visualizing working composition sequence.");
7553   ns_working_text =Qnil;
7555   DEFVAR_LISP ("ns-input-font", ns_input_font,
7556               "The font specified in the last NS event.");
7557   ns_input_font =Qnil;
7559   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7560               "The fontsize specified in the last NS event.");
7561   ns_input_fontsize =Qnil;
7563   DEFVAR_LISP ("ns-input-line", ns_input_line,
7564                "The line specified in the last NS event.");
7565   ns_input_line =Qnil;
7567   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7568                "The service name specified in the last NS event.");
7569   ns_input_spi_name =Qnil;
7571   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7572                "The service argument specified in the last NS event.");
7573   ns_input_spi_arg =Qnil;
7575   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7576                "This variable describes the behavior of the alternate or option key.\n\
7577 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7578 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7579 at all, allowing it to be used at a lower level for accented character entry.");
7580   ns_alternate_modifier = Qmeta;
7582   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7583                "This variable describes the behavior of the right alternate or option key.\n\
7584 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7585 Set to left means be the same key as `ns-alternate-modifier'.\n\
7586 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7587 at all, allowing it to be used at a lower level for accented character entry.");
7588   ns_right_alternate_modifier = Qleft;
7590   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7591                "This variable describes the behavior of the command key.\n\
7592 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7593   ns_command_modifier = Qsuper;
7595   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7596                "This variable describes the behavior of the right command key.\n\
7597 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7598 Set to left means be the same key as `ns-command-modifier'.\n\
7599 Set to none means that the command / option key is not interpreted by Emacs\n\
7600 at all, allowing it to be used at a lower level for accented character entry.");
7601   ns_right_command_modifier = Qleft;
7603   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7604                "This variable describes the behavior of the control key.\n\
7605 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7606   ns_control_modifier = Qcontrol;
7608   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7609                "This variable describes the behavior of the right control key.\n\
7610 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7611 Set to left means be the same key as `ns-control-modifier'.\n\
7612 Set to none means that the control / option key is not interpreted by Emacs\n\
7613 at all, allowing it to be used at a lower level for accented character entry.");
7614   ns_right_control_modifier = Qleft;
7616   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7617                "This variable describes the behavior of the function key (on laptops).\n\
7618 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7619 Set to none means that the function key is not interpreted by Emacs at all,\n\
7620 allowing it to be used at a lower level for accented character entry.");
7621   ns_function_modifier = Qnone;
7623   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7624                "Non-nil (the default) means to render text antialiased.");
7625   ns_antialias_text = Qt;
7627   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7628                "Whether to confirm application quit using dialog.");
7629   ns_confirm_quit = Qnil;
7631   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7632                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7633 Only works on OSX 10.6 or later.  */);
7634   ns_auto_hide_menu_bar = Qnil;
7636   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7637      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7638 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7639 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7640 Default is t for OSX >= 10.7, nil otherwise. */);
7641 #ifdef HAVE_NATIVE_FS
7642   ns_use_native_fullscreen = YES;
7643 #else
7644   ns_use_native_fullscreen = NO;
7645 #endif
7646   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7648   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7649      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7650 Note that this does not apply to images.            
7651 This variable is ignored on OSX < 10.7 and GNUStep.  Default is t. */);
7652   ns_use_srgb_colorspace = YES;
7654   /* TODO: move to common code */
7655   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7656                doc: /* Which toolkit scroll bars Emacs uses, if any.
7657 A value of nil means Emacs doesn't use toolkit scroll bars.
7658 With the X Window system, the value is a symbol describing the
7659 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7660 With MS Windows or Nextstep, the value is t.  */);
7661   Vx_toolkit_scroll_bars = Qt;
7663   DEFVAR_BOOL ("x-use-underline-position-properties",
7664                x_use_underline_position_properties,
7665      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7666 A value of nil means ignore them.  If you encounter fonts with bogus
7667 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7668 to 4.1, set this to nil. */);
7669   x_use_underline_position_properties = 0;
7671   DEFVAR_BOOL ("x-underline-at-descent-line",
7672                x_underline_at_descent_line,
7673      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7674 A value of nil means to draw the underline according to the value of the
7675 variable `x-use-underline-position-properties', which is usually at the
7676 baseline level.  The default value is nil.  */);
7677   x_underline_at_descent_line = 0;
7679   /* Tell Emacs about this window system.  */
7680   Fprovide (Qns, Qnil);
7682   DEFSYM (Qcocoa, "cocoa");
7683   DEFSYM (Qgnustep, "gnustep");
7685   syms_of_nsfont ();
7686 #ifdef NS_IMPL_COCOA
7687   Fprovide (Qcocoa, Qnil);
7688 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
7689   syms_of_macfont ();
7690 #endif
7691 #else
7692   Fprovide (Qgnustep, Qnil);
7693 #endif