Refactor mml-smime.el, mml1991.el, mml2015.el
[emacs.git] / src / nsterm.m
blobb270e0e58b54c8c0c7a549f706bf6504f399827b
1 /* NeXT/Open/GNUstep / MacOSX communication module.      -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2016 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <signal.h>
39 #include <unistd.h>
41 #include <c-ctype.h>
42 #include <c-strcase.h>
43 #include <ftoastr.h>
45 #include "lisp.h"
46 #include "blockinput.h"
47 #include "sysselect.h"
48 #include "nsterm.h"
49 #include "systime.h"
50 #include "character.h"
51 #include "fontset.h"
52 #include "composite.h"
53 #include "ccl.h"
55 #include "termhooks.h"
56 #include "termchar.h"
57 #include "menu.h"
58 #include "window.h"
59 #include "keyboard.h"
60 #include "buffer.h"
61 #include "font.h"
63 #ifdef NS_IMPL_GNUSTEP
64 #include "process.h"
65 #endif
67 #ifdef NS_IMPL_COCOA
68 #include "macfont.h"
69 #endif
72 extern NSString *NSMenuDidBeginTrackingNotification;
75 /* ==========================================================================
77    NSTRACE, Trace support.
79    ========================================================================== */
81 #if NSTRACE_ENABLED
83 /* The following use "volatile" since they can be accessed from
84    parallel threads. */
85 volatile int nstrace_num = 0;
86 volatile int nstrace_depth = 0;
88 /* When 0, no trace is emitted.  This is used by NSTRACE_WHEN and
89    NSTRACE_UNLESS to silence functions called.
91    TODO: This should really be a thread-local variable, to avoid that
92    a function with disabled trace thread silence trace output in
93    another.  However, in practice this seldom is a problem. */
94 volatile int nstrace_enabled_global = 1;
96 /* Called when nstrace_enabled goes out of scope. */
97 void nstrace_leave(int * pointer_to_nstrace_enabled)
99   if (*pointer_to_nstrace_enabled)
100     {
101       --nstrace_depth;
102     }
106 /* Called when nstrace_saved_enabled_global goes out of scope. */
107 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
109   nstrace_enabled_global = *pointer_to_saved_enabled_global;
113 char const * nstrace_fullscreen_type_name (int fs_type)
115   switch (fs_type)
116     {
117     case -1:                   return "-1";
118     case FULLSCREEN_NONE:      return "FULLSCREEN_NONE";
119     case FULLSCREEN_WIDTH:     return "FULLSCREEN_WIDTH";
120     case FULLSCREEN_HEIGHT:    return "FULLSCREEN_HEIGHT";
121     case FULLSCREEN_BOTH:      return "FULLSCREEN_BOTH";
122     case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
123     default:                   return "FULLSCREEN_?????";
124     }
126 #endif
129 /* ==========================================================================
131    NSColor, EmacsColor category.
133    ========================================================================== */
134 @implementation NSColor (EmacsColor)
135 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
136                          blue:(CGFloat)blue alpha:(CGFloat)alpha
138 #ifdef NS_IMPL_COCOA
139 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
140   if (ns_use_srgb_colorspace)
141       return [NSColor colorWithSRGBRed: red
142                                  green: green
143                                   blue: blue
144                                  alpha: alpha];
145 #endif
146 #endif
147   return [NSColor colorWithCalibratedRed: red
148                                    green: green
149                                     blue: blue
150                                    alpha: alpha];
153 - (NSColor *)colorUsingDefaultColorSpace
155 #ifdef NS_IMPL_COCOA
156 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
157   if (ns_use_srgb_colorspace)
158     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
159 #endif
160 #endif
161   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
164 @end
166 /* ==========================================================================
168     Local declarations
170    ========================================================================== */
172 /* Convert a symbol indexed with an NSxxx value to a value as defined
173    in keyboard.c (lispy_function_key). I hope this is a correct way
174    of doing things... */
175 static unsigned convert_ns_to_X_keysym[] =
177   NSHomeFunctionKey,            0x50,
178   NSLeftArrowFunctionKey,       0x51,
179   NSUpArrowFunctionKey,         0x52,
180   NSRightArrowFunctionKey,      0x53,
181   NSDownArrowFunctionKey,       0x54,
182   NSPageUpFunctionKey,          0x55,
183   NSPageDownFunctionKey,        0x56,
184   NSEndFunctionKey,             0x57,
185   NSBeginFunctionKey,           0x58,
186   NSSelectFunctionKey,          0x60,
187   NSPrintFunctionKey,           0x61,
188   NSClearLineFunctionKey,       0x0B,
189   NSExecuteFunctionKey,         0x62,
190   NSInsertFunctionKey,          0x63,
191   NSUndoFunctionKey,            0x65,
192   NSRedoFunctionKey,            0x66,
193   NSMenuFunctionKey,            0x67,
194   NSFindFunctionKey,            0x68,
195   NSHelpFunctionKey,            0x6A,
196   NSBreakFunctionKey,           0x6B,
198   NSF1FunctionKey,              0xBE,
199   NSF2FunctionKey,              0xBF,
200   NSF3FunctionKey,              0xC0,
201   NSF4FunctionKey,              0xC1,
202   NSF5FunctionKey,              0xC2,
203   NSF6FunctionKey,              0xC3,
204   NSF7FunctionKey,              0xC4,
205   NSF8FunctionKey,              0xC5,
206   NSF9FunctionKey,              0xC6,
207   NSF10FunctionKey,             0xC7,
208   NSF11FunctionKey,             0xC8,
209   NSF12FunctionKey,             0xC9,
210   NSF13FunctionKey,             0xCA,
211   NSF14FunctionKey,             0xCB,
212   NSF15FunctionKey,             0xCC,
213   NSF16FunctionKey,             0xCD,
214   NSF17FunctionKey,             0xCE,
215   NSF18FunctionKey,             0xCF,
216   NSF19FunctionKey,             0xD0,
217   NSF20FunctionKey,             0xD1,
218   NSF21FunctionKey,             0xD2,
219   NSF22FunctionKey,             0xD3,
220   NSF23FunctionKey,             0xD4,
221   NSF24FunctionKey,             0xD5,
223   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
224   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
225   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
227   NSTabCharacter,               0x09,
228   0x19,                         0x09,  /* left tab->regular since pass shift */
229   NSCarriageReturnCharacter,    0x0D,
230   NSNewlineCharacter,           0x0D,
231   NSEnterCharacter,             0x8D,
233   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
234   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
235   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
236   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
237   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
238   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
239   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
240   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
241   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
242   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
243   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
244   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
245   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
246   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
247   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
248   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
250   0x1B,                         0x1B   /* escape */
253 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
254    the maximum font size to NOT antialias.  On GNUstep there is currently
255    no way to control this behavior. */
256 float ns_antialias_threshold;
258 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
259 NSString *ns_app_name = @"Emacs";  /* default changed later */
261 /* Display variables */
262 struct ns_display_info *x_display_list; /* Chain of existing displays */
263 long context_menu_value = 0;
265 /* display update */
266 static struct frame *ns_updating_frame;
267 static NSView *focus_view = NULL;
268 static int ns_window_num = 0;
269 #ifdef NS_IMPL_GNUSTEP
270 static NSRect uRect;            // TODO: This is dead, remove it?
271 #endif
272 static BOOL gsaved = NO;
273 static BOOL ns_fake_keydown = NO;
274 #ifdef NS_IMPL_COCOA
275 static BOOL ns_menu_bar_is_hidden = NO;
276 #endif
277 /*static int debug_lock = 0; */
279 /* event loop */
280 static BOOL send_appdefined = YES;
281 #define NO_APPDEFINED_DATA (-8)
282 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
283 static NSTimer *timed_entry = 0;
284 static NSTimer *scroll_repeat_entry = nil;
285 static fd_set select_readfds, select_writefds;
286 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
287 static int select_nfds = 0, select_valid = 0;
288 static struct timespec select_timeout = { 0, 0 };
289 static int selfds[2] = { -1, -1 };
290 static pthread_mutex_t select_mutex;
291 static int apploopnr = 0;
292 static NSAutoreleasePool *outerpool;
293 static struct input_event *emacs_event = NULL;
294 static struct input_event *q_event_ptr = NULL;
295 static int n_emacs_events_pending = 0;
296 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
297   *ns_pending_service_args;
298 static BOOL ns_do_open_file = NO;
299 static BOOL ns_last_use_native_fullscreen;
301 /* Non-zero means that a HELP_EVENT has been generated since Emacs
302    start.  */
304 static BOOL any_help_event_p = NO;
306 static struct {
307   struct input_event *q;
308   int nr, cap;
309 } hold_event_q = {
310   NULL, 0, 0
313 static NSString *represented_filename = nil;
314 static struct frame *represented_frame = 0;
316 #ifdef NS_IMPL_COCOA
318  * State for pending menu activation:
319  * MENU_NONE     Normal state
320  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
321  *               run lisp to update the menu.
322  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
323  *               will open.
324  */
325 #define MENU_NONE 0
326 #define MENU_PENDING 1
327 #define MENU_OPENING 2
328 static int menu_will_open_state = MENU_NONE;
330 /* Saved position for menu click.  */
331 static CGPoint menu_mouse_point;
332 #endif
334 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
335 #define NS_FUNCTION_KEY_MASK 0x800000
336 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
337 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
338 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
339 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
340 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
341 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
342 #define EV_MODIFIERS2(flags)                          \
343     (((flags & NSHelpKeyMask) ?           \
344            hyper_modifier : 0)                        \
345      | (!EQ (ns_right_alternate_modifier, Qleft) && \
346         ((flags & NSRightAlternateKeyMask) \
347          == NSRightAlternateKeyMask) ? \
348            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
349      | ((flags & NSAlternateKeyMask) ?                 \
350            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
351      | ((flags & NSShiftKeyMask) ?     \
352            shift_modifier : 0)                        \
353      | (!EQ (ns_right_control_modifier, Qleft) && \
354         ((flags & NSRightControlKeyMask) \
355          == NSRightControlKeyMask) ? \
356            parse_solitary_modifier (ns_right_control_modifier) : 0) \
357      | ((flags & NSControlKeyMask) ?      \
358            parse_solitary_modifier (ns_control_modifier) : 0)     \
359      | ((flags & NS_FUNCTION_KEY_MASK) ?  \
360            parse_solitary_modifier (ns_function_modifier) : 0)    \
361      | (!EQ (ns_right_command_modifier, Qleft) && \
362         ((flags & NSRightCommandKeyMask) \
363          == NSRightCommandKeyMask) ? \
364            parse_solitary_modifier (ns_right_command_modifier) : 0) \
365      | ((flags & NSCommandKeyMask) ?      \
366            parse_solitary_modifier (ns_command_modifier):0))
367 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
369 #define EV_UDMODIFIERS(e)                                      \
370     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
371      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
372      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
373      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
374      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
375      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
376      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
377      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
378      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
380 #define EV_BUTTON(e)                                                         \
381     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
382       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
383      [e buttonNumber] - 1)
385 /* Convert the time field to a timestamp in milliseconds. */
386 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
388 /* This is a piece of code which is common to all the event handling
389    methods.  Maybe it should even be a function.  */
390 #define EV_TRAILER(e)                                                   \
391   {                                                                     \
392     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
393     EV_TRAILER2 (e);                                                    \
394   }
396 #define EV_TRAILER2(e)                                                  \
397   {                                                                     \
398       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
399       if (q_event_ptr)                                                  \
400         {                                                               \
401           Lisp_Object tem = Vinhibit_quit;                              \
402           Vinhibit_quit = Qt;                                           \
403           n_emacs_events_pending++;                                     \
404           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
405           Vinhibit_quit = tem;                                          \
406         }                                                               \
407       else                                                              \
408         hold_event (emacs_event);                                       \
409       EVENT_INIT (*emacs_event);                                        \
410       ns_send_appdefined (-1);                                          \
411     }
413 /* TODO: get rid of need for these forward declarations */
414 static void ns_condemn_scroll_bars (struct frame *f);
415 static void ns_judge_scroll_bars (struct frame *f);
416 void x_set_frame_alpha (struct frame *f);
419 /* ==========================================================================
421     Utilities
423    ========================================================================== */
425 void
426 ns_set_represented_filename (NSString* fstr, struct frame *f)
428   represented_filename = [fstr retain];
429   represented_frame = f;
432 void
433 ns_init_events (struct input_event* ev)
435   EVENT_INIT (*ev);
436   emacs_event = ev;
439 void
440 ns_finish_events ()
442   emacs_event = NULL;
445 static void
446 hold_event (struct input_event *event)
448   if (hold_event_q.nr == hold_event_q.cap)
449     {
450       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
451       else hold_event_q.cap *= 2;
452       hold_event_q.q =
453         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
454     }
456   hold_event_q.q[hold_event_q.nr++] = *event;
457   /* Make sure ns_read_socket is called, i.e. we have input.  */
458   raise (SIGIO);
459   send_appdefined = YES;
462 static Lisp_Object
463 append2 (Lisp_Object list, Lisp_Object item)
464 /* --------------------------------------------------------------------------
465    Utility to append to a list
466    -------------------------------------------------------------------------- */
468   return CALLN (Fnconc, list, list1 (item));
472 const char *
473 ns_etc_directory (void)
474 /* If running as a self-contained app bundle, return as a string the
475    filename of the etc directory, if present; else nil.  */
477   NSBundle *bundle = [NSBundle mainBundle];
478   NSString *resourceDir = [bundle resourcePath];
479   NSString *resourcePath;
480   NSFileManager *fileManager = [NSFileManager defaultManager];
481   BOOL isDir;
483   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
484   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
485     {
486       if (isDir) return [resourcePath UTF8String];
487     }
488   return NULL;
492 const char *
493 ns_exec_path (void)
494 /* If running as a self-contained app bundle, return as a path string
495    the filenames of the libexec and bin directories, ie libexec:bin.
496    Otherwise, return nil.
497    Normally, Emacs does not add its own bin/ directory to the PATH.
498    However, a self-contained NS build has a different layout, with
499    bin/ and libexec/ subdirectories in the directory that contains
500    Emacs.app itself.
501    We put libexec first, because init_callproc_1 uses the first
502    element to initialize exec-directory.  An alternative would be
503    for init_callproc to check for invocation-directory/libexec.
506   NSBundle *bundle = [NSBundle mainBundle];
507   NSString *resourceDir = [bundle resourcePath];
508   NSString *binDir = [bundle bundlePath];
509   NSString *resourcePath, *resourcePaths;
510   NSRange range;
511   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
512   NSFileManager *fileManager = [NSFileManager defaultManager];
513   NSArray *paths;
514   NSEnumerator *pathEnum;
515   BOOL isDir;
517   range = [resourceDir rangeOfString: @"Contents"];
518   if (range.location != NSNotFound)
519     {
520       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
521 #ifdef NS_IMPL_COCOA
522       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
523 #endif
524     }
526   paths = [binDir stringsByAppendingPaths:
527                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
528   pathEnum = [paths objectEnumerator];
529   resourcePaths = @"";
531   while ((resourcePath = [pathEnum nextObject]))
532     {
533       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
534         if (isDir)
535           {
536             if ([resourcePaths length] > 0)
537               resourcePaths
538                 = [resourcePaths stringByAppendingString: pathSeparator];
539             resourcePaths
540               = [resourcePaths stringByAppendingString: resourcePath];
541           }
542     }
543   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
545   return NULL;
549 const char *
550 ns_load_path (void)
551 /* If running as a self-contained app bundle, return as a path string
552    the filenames of the site-lisp and lisp directories.
553    Ie, site-lisp:lisp.  Otherwise, return nil.  */
555   NSBundle *bundle = [NSBundle mainBundle];
556   NSString *resourceDir = [bundle resourcePath];
557   NSString *resourcePath, *resourcePaths;
558   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
559   NSFileManager *fileManager = [NSFileManager defaultManager];
560   BOOL isDir;
561   NSArray *paths = [resourceDir stringsByAppendingPaths:
562                               [NSArray arrayWithObjects:
563                                          @"site-lisp", @"lisp", nil]];
564   NSEnumerator *pathEnum = [paths objectEnumerator];
565   resourcePaths = @"";
567   /* Hack to skip site-lisp.  */
568   if (no_site_lisp) resourcePath = [pathEnum nextObject];
570   while ((resourcePath = [pathEnum nextObject]))
571     {
572       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
573         if (isDir)
574           {
575             if ([resourcePaths length] > 0)
576               resourcePaths
577                 = [resourcePaths stringByAppendingString: pathSeparator];
578             resourcePaths
579               = [resourcePaths stringByAppendingString: resourcePath];
580           }
581     }
582   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
584   return NULL;
588 void
589 ns_release_object (void *obj)
590 /* --------------------------------------------------------------------------
591     Release an object (callable from C)
592    -------------------------------------------------------------------------- */
594     [(id)obj release];
598 void
599 ns_retain_object (void *obj)
600 /* --------------------------------------------------------------------------
601     Retain an object (callable from C)
602    -------------------------------------------------------------------------- */
604     [(id)obj retain];
608 void *
609 ns_alloc_autorelease_pool (void)
610 /* --------------------------------------------------------------------------
611      Allocate a pool for temporary objects (callable from C)
612    -------------------------------------------------------------------------- */
614   return [[NSAutoreleasePool alloc] init];
618 void
619 ns_release_autorelease_pool (void *pool)
620 /* --------------------------------------------------------------------------
621      Free a pool and temporary objects it refers to (callable from C)
622    -------------------------------------------------------------------------- */
624   ns_release_object (pool);
628 /* True, if the menu bar should be hidden.  */
630 static BOOL
631 ns_menu_bar_should_be_hidden (void)
633   return !NILP (ns_auto_hide_menu_bar)
634     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
638 static CGFloat
639 ns_menu_bar_height (NSScreen *screen)
640 /* The height of the menu bar, if visible. */
642   //  NSTRACE ("ns_menu_bar_height");
644   CGFloat res;
646   if (ns_menu_bar_should_be_hidden())
647     {
648       res = 0;
649     }
650   else
651     {
652       NSRect screenFrame = [screen frame];
653       NSRect screenVisibleFrame = [screen visibleFrame];
655       CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
656       CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
657                                  + screenVisibleFrame.size.height);
659       res = frameTop - visibleFrameTop;
661     }
663   // NSTRACE_MSG (NSTRACE_FMT_RETURN "%.0f", res);
665   return res;
669 /* ==========================================================================
671     Focus (clipping) and screen update
673    ========================================================================== */
676 // Window constraining
677 // -------------------
679 // To ensure that the windows are not placed under the menu bar, they
680 // are typically moved by the call-back constrainFrameRect. However,
681 // by overriding it, it's possible to inhibit this, leaving the window
682 // in it's original position.
684 // It's possible to hide the menu bar. However, technically, it's only
685 // possible to hide it when the application is active. To ensure that
686 // this work properly, the menu bar and window constraining are
687 // deferred until the application becomes active.
689 // Even though it's not possible to manually move a window above the
690 // top of the screen, it is allowed if it's done programmatically,
691 // when the menu is hidden. This allows the editable area to cover the
692 // full screen height.
694 // Test cases
695 // ----------
697 // Use the following extra files:
699 //    init.el:
700 //       ;; Hide menu and place frame slightly above the top of the screen.
701 //       (setq ns-auto-hide-menu-bar t)
702 //       (set-frame-position (selected-frame) 0 -20)
704 // Test 1:
706 //    emacs -Q -l init.el
708 //    Result: No menu bar, and the title bar should be above the screen.
710 // Test 2:
712 //    emacs -Q
714 //    Result: Menu bar visible, frame placed immediately below the menu.
717 static NSRect constrain_frame_rect(NSRect frameRect)
719   NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
720              NSTRACE_ARG_RECT (frameRect));
722   // --------------------
723   // Collect information about the screen the frame is covering.
724   //
726   NSArray *screens = [NSScreen screens];
727   NSUInteger nr_screens = [screens count];
729   int i;
731   // The height of the menu bar, if present in any screen the frame is
732   // displayed in.
733   int menu_bar_height = 0;
735   // A rectangle covering all the screen the frame is displayed in.
736   NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
737   for (i = 0; i < nr_screens; ++i )
738     {
739       NSScreen *s = [screens objectAtIndex: i];
740       NSRect scrRect = [s frame];
742       NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
743                    i, NSTRACE_ARG_RECT (scrRect));
745       if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
746         {
747           multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
749           menu_bar_height = max(menu_bar_height, ns_menu_bar_height (s));
750         }
751     }
753   NSTRACE_RECT ("multiscreenRect", multiscreenRect);
755   NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
757   if (multiscreenRect.size.width == 0
758       || multiscreenRect.size.height == 0)
759     {
760       // Failed to find any monitor, give up.
761       NSTRACE_MSG ("multiscreenRect empty");
762       NSTRACE_RETURN_RECT (frameRect);
763       return frameRect;
764     }
767   // --------------------
768   // Find a suitable placement.
769   //
771   if (ns_menu_bar_should_be_hidden())
772     {
773       // When the menu bar is hidden, the user may place part of the
774       // frame above the top of the screen, for example to hide the
775       // title bar.
776       //
777       // Hence, keep the original position.
778     }
779   else
780     {
781       // Ensure that the frame is below the menu bar, or below the top
782       // of the screen.
783       //
784       // This assume that the menu bar is placed at the top in the
785       // rectangle that covers the monitors.  (It doesn't have to be,
786       // but if it's not it's hard to do anything useful.)
787       CGFloat topOfWorkArea = (multiscreenRect.origin.y
788                                + multiscreenRect.size.height
789                                - menu_bar_height);
791       CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
792       if (topOfFrame > topOfWorkArea)
793         {
794           frameRect.origin.y -= topOfFrame - topOfWorkArea;
795           NSTRACE_RECT ("After placement adjust", frameRect);
796         }
797     }
799   // Include the following section to restrict frame to the screens.
800   // (If so, update it to allow the frame to stretch down below the
801   // screen.)
802 #if 0
803   // --------------------
804   // Ensure frame doesn't stretch below the screens.
805   //
807   CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
809   if (diff > 0)
810     {
811       frameRect.origin.y = multiscreenRect.origin.y;
812       frameRect.size.height -= diff;
813     }
814 #endif
816   NSTRACE_RETURN_RECT (frameRect);
817   return frameRect;
821 static void
822 ns_constrain_all_frames (void)
823 /* --------------------------------------------------------------------------
824      Ensure that the menu bar doesn't cover any frames.
825    -------------------------------------------------------------------------- */
827   Lisp_Object tail, frame;
829   NSTRACE ("ns_constrain_all_frames");
831   block_input ();
833   FOR_EACH_FRAME (tail, frame)
834     {
835       struct frame *f = XFRAME (frame);
836       if (FRAME_NS_P (f))
837         {
838           EmacsView *view = FRAME_NS_VIEW (f);
840           if (![view isFullscreen])
841             {
842               [[view window]
843                 setFrame:constrain_frame_rect([[view window] frame])
844                  display:NO];
845             }
846         }
847     }
849   unblock_input ();
853 static void
854 ns_update_auto_hide_menu_bar (void)
855 /* --------------------------------------------------------------------------
856      Show or hide the menu bar, based on user setting.
857    -------------------------------------------------------------------------- */
859 #ifdef NS_IMPL_COCOA
860   NSTRACE ("ns_update_auto_hide_menu_bar");
862   block_input ();
864   if (NSApp != nil && [NSApp isActive])
865     {
866       // Note, "setPresentationOptions" triggers an error unless the
867       // application is active.
868       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
870       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
871         {
872           NSApplicationPresentationOptions options
873             = NSApplicationPresentationDefault;
875           if (menu_bar_should_be_hidden)
876             options |= NSApplicationPresentationAutoHideMenuBar
877               | NSApplicationPresentationAutoHideDock;
879           [NSApp setPresentationOptions: options];
881           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
883           if (!ns_menu_bar_is_hidden)
884             {
885               ns_constrain_all_frames ();
886             }
887         }
888     }
890   unblock_input ();
891 #endif
895 static void
896 ns_update_begin (struct frame *f)
897 /* --------------------------------------------------------------------------
898    Prepare for a grouped sequence of drawing calls
899    external (RIF) call; whole frame, called before update_window_begin
900    -------------------------------------------------------------------------- */
902   EmacsView *view = FRAME_NS_VIEW (f);
903   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
905   ns_update_auto_hide_menu_bar ();
907 #ifdef NS_IMPL_COCOA
908   if ([view isFullscreen] && [view fsIsNative])
909   {
910     // Fix reappearing tool bar in fullscreen for OSX 10.7
911     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
912     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
913     if (! tbar_visible != ! [toolbar isVisible])
914       [toolbar setVisible: tbar_visible];
915   }
916 #endif
918   ns_updating_frame = f;
919   [view lockFocus];
921   /* drawRect may have been called for say the minibuffer, and then clip path
922      is for the minibuffer.  But the display engine may draw more because
923      we have set the frame as garbaged.  So reset clip path to the whole
924      view.  */
925 #ifdef NS_IMPL_COCOA
926   {
927     NSBezierPath *bp;
928     NSRect r = [view frame];
929     NSRect cr = [[view window] frame];
930     /* If a large frame size is set, r may be larger than the window frame
931        before constrained.  In that case don't change the clip path, as we
932        will clear in to the tool bar and title bar.  */
933     if (r.size.height
934         + FRAME_NS_TITLEBAR_HEIGHT (f)
935         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
936       {
937         bp = [[NSBezierPath bezierPathWithRect: r] retain];
938         [bp setClip];
939         [bp release];
940       }
941   }
942 #endif
944 #ifdef NS_IMPL_GNUSTEP
945   uRect = NSMakeRect (0, 0, 0, 0);
946 #endif
950 static void
951 ns_update_window_begin (struct window *w)
952 /* --------------------------------------------------------------------------
953    Prepare for a grouped sequence of drawing calls
954    external (RIF) call; for one window, called after update_begin
955    -------------------------------------------------------------------------- */
957   struct frame *f = XFRAME (WINDOW_FRAME (w));
958   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
960   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
961   w->output_cursor = w->cursor;
963   block_input ();
965   if (f == hlinfo->mouse_face_mouse_frame)
966     {
967       /* Don't do highlighting for mouse motion during the update.  */
968       hlinfo->mouse_face_defer = 1;
970         /* If the frame needs to be redrawn,
971            simply forget about any prior mouse highlighting.  */
972       if (FRAME_GARBAGED_P (f))
973         hlinfo->mouse_face_window = Qnil;
975       /* (further code for mouse faces ifdef'd out in other terms elided) */
976     }
978   unblock_input ();
982 static void
983 ns_update_window_end (struct window *w, bool cursor_on_p,
984                       bool mouse_face_overwritten_p)
985 /* --------------------------------------------------------------------------
986    Finished a grouped sequence of drawing calls
987    external (RIF) call; for one window called before update_end
988    -------------------------------------------------------------------------- */
990   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
992   /* note: this fn is nearly identical in all terms */
993   if (!w->pseudo_window_p)
994     {
995       block_input ();
997       if (cursor_on_p)
998         display_and_set_cursor (w, 1,
999                                 w->output_cursor.hpos, w->output_cursor.vpos,
1000                                 w->output_cursor.x, w->output_cursor.y);
1002       if (draw_window_fringes (w, 1))
1003         {
1004           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1005             x_draw_right_divider (w);
1006           else
1007             x_draw_vertical_border (w);
1008         }
1010       unblock_input ();
1011     }
1013   /* If a row with mouse-face was overwritten, arrange for
1014      frame_up_to_date to redisplay the mouse highlight.  */
1015   if (mouse_face_overwritten_p)
1016     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1020 static void
1021 ns_update_end (struct frame *f)
1022 /* --------------------------------------------------------------------------
1023    Finished a grouped sequence of drawing calls
1024    external (RIF) call; for whole frame, called after update_window_end
1025    -------------------------------------------------------------------------- */
1027   EmacsView *view = FRAME_NS_VIEW (f);
1029   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1031 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1032   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1034   block_input ();
1036   [view unlockFocus];
1037   [[view window] flushWindow];
1039   unblock_input ();
1040   ns_updating_frame = NULL;
1043 static void
1044 ns_focus (struct frame *f, NSRect *r, int n)
1045 /* --------------------------------------------------------------------------
1046    Internal: Focus on given frame.  During small local updates this is used to
1047      draw, however during large updates, ns_update_begin and ns_update_end are
1048      called to wrap the whole thing, in which case these calls are stubbed out.
1049      Except, on GNUstep, we accumulate the rectangle being drawn into, because
1050      the back end won't do this automatically, and will just end up flushing
1051      the entire window.
1052    -------------------------------------------------------------------------- */
1054   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1055   if (r != NULL)
1056     {
1057       NSTRACE_RECT ("r", *r);
1058     }
1060   if (f != ns_updating_frame)
1061     {
1062       NSView *view = FRAME_NS_VIEW (f);
1063       if (view != focus_view)
1064         {
1065           if (focus_view != NULL)
1066             {
1067               [focus_view unlockFocus];
1068               [[focus_view window] flushWindow];
1069 /*debug_lock--; */
1070             }
1072           if (view)
1073             [view lockFocus];
1074           focus_view = view;
1075 /*if (view) debug_lock++; */
1076         }
1077     }
1079   /* clipping */
1080   if (r)
1081     {
1082       [[NSGraphicsContext currentContext] saveGraphicsState];
1083       if (n == 2)
1084         NSRectClipList (r, 2);
1085       else
1086         NSRectClip (*r);
1087       gsaved = YES;
1088     }
1092 static void
1093 ns_unfocus (struct frame *f)
1094 /* --------------------------------------------------------------------------
1095      Internal: Remove focus on given frame
1096    -------------------------------------------------------------------------- */
1098   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1100   if (gsaved)
1101     {
1102       [[NSGraphicsContext currentContext] restoreGraphicsState];
1103       gsaved = NO;
1104     }
1106   if (f != ns_updating_frame)
1107     {
1108       if (focus_view != NULL)
1109         {
1110           [focus_view unlockFocus];
1111           [[focus_view window] flushWindow];
1112           focus_view = NULL;
1113 /*debug_lock--; */
1114         }
1115     }
1119 static void
1120 ns_clip_to_row (struct window *w, struct glyph_row *row,
1121                 enum glyph_row_area area, BOOL gc)
1122 /* --------------------------------------------------------------------------
1123      Internal (but parallels other terms): Focus drawing on given row
1124    -------------------------------------------------------------------------- */
1126   struct frame *f = XFRAME (WINDOW_FRAME (w));
1127   NSRect clip_rect;
1128   int window_x, window_y, window_width;
1130   window_box (w, area, &window_x, &window_y, &window_width, 0);
1132   clip_rect.origin.x = window_x;
1133   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1134   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1135   clip_rect.size.width = window_width;
1136   clip_rect.size.height = row->visible_height;
1138   ns_focus (f, &clip_rect, 1);
1142 /* ==========================================================================
1144     Visible bell and beep.
1146    ========================================================================== */
1149 @interface EmacsBell : NSImageView
1151   // Number of currently active bell:s.
1152   unsigned int nestCount;
1153   bool isAttached;
1155 - (void)show:(NSView *)view;
1156 - (void)hide;
1157 - (void)remove;
1158 @end
1160 @implementation EmacsBell
1162 - (id)init;
1164   if ((self = [super init]))
1165     {
1166       nestCount = 0;
1167       isAttached = false;
1168       self.image = [NSImage imageNamed:NSImageNameCaution];
1169     }
1170   return self;
1173 - (void)show:(NSView *)view
1175   NSTRACE ("[EmacsBell show:]");
1176   NSTRACE_MSG ("nestCount: %u", nestCount);
1178   // Show the image, unless it's already shown.
1179   if (nestCount == 0)
1180     {
1181       NSRect rect = [view bounds];
1182       NSPoint pos;
1183       pos.x = rect.origin.x + (rect.size.width  - self.image.size.width )/2;
1184       pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1186       [self setFrameOrigin:pos];
1187       [self setFrameSize:self.image.size];
1189       isAttached = true;
1190       [[[view window] contentView] addSubview:self
1191                                    positioned:NSWindowAbove
1192                                    relativeTo:nil];
1193     }
1195   ++nestCount;
1197   [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1201 - (void)hide
1203   // Note: Trace output from this method isn't shown, reason unknown.
1204   // NSTRACE ("[EmacsBell hide]");
1206   if (nestCount > 0)
1207     --nestCount;
1209   // Remove the image once the last bell became inactive.
1210   if (nestCount == 0)
1211     {
1212       [self remove];
1213     }
1217 -(void)remove
1219   if (isAttached)
1220     {
1221       [self removeFromSuperview];
1222       isAttached = false;
1223     }
1226 @end
1229 static EmacsBell * bell_view = nil;
1231 static void
1232 ns_ring_bell (struct frame *f)
1233 /* --------------------------------------------------------------------------
1234      "Beep" routine
1235    -------------------------------------------------------------------------- */
1237   NSTRACE ("ns_ring_bell");
1238   if (visible_bell)
1239     {
1240       struct frame *frame = SELECTED_FRAME ();
1241       NSView *view;
1243       if (bell_view == nil)
1244         {
1245           bell_view = [[EmacsBell alloc] init];
1246           [bell_view retain];
1247         }
1249       block_input ();
1251       view = FRAME_NS_VIEW (frame);
1252       if (view != nil)
1253         {
1254           [bell_view show:view];
1255         }
1257       unblock_input ();
1258     }
1259   else
1260     {
1261       NSBeep ();
1262     }
1266 static void hide_bell ()
1267 /* --------------------------------------------------------------------------
1268      Ensure the bell is hidden.
1269    -------------------------------------------------------------------------- */
1271   if (bell_view != nil)
1272     {
1273       [bell_view remove];
1274     }
1278 /* ==========================================================================
1280     Frame / window manager related functions
1282    ========================================================================== */
1285 static void
1286 ns_raise_frame (struct frame *f)
1287 /* --------------------------------------------------------------------------
1288      Bring window to foreground and make it active
1289    -------------------------------------------------------------------------- */
1291   NSView *view;
1293   check_window_system (f);
1294   view = FRAME_NS_VIEW (f);
1295   block_input ();
1296   if (FRAME_VISIBLE_P (f))
1297     [[view window] makeKeyAndOrderFront: NSApp];
1298   unblock_input ();
1302 static void
1303 ns_lower_frame (struct frame *f)
1304 /* --------------------------------------------------------------------------
1305      Send window to back
1306    -------------------------------------------------------------------------- */
1308   NSView *view;
1310   check_window_system (f);
1311   view = FRAME_NS_VIEW (f);
1312   block_input ();
1313   [[view window] orderBack: NSApp];
1314   unblock_input ();
1318 static void
1319 ns_frame_raise_lower (struct frame *f, bool raise)
1320 /* --------------------------------------------------------------------------
1321      External (hook)
1322    -------------------------------------------------------------------------- */
1324   NSTRACE ("ns_frame_raise_lower");
1326   if (raise)
1327     ns_raise_frame (f);
1328   else
1329     ns_lower_frame (f);
1333 static void
1334 ns_frame_rehighlight (struct frame *frame)
1335 /* --------------------------------------------------------------------------
1336      External (hook): called on things like window switching within frame
1337    -------------------------------------------------------------------------- */
1339   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1340   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1342   NSTRACE ("ns_frame_rehighlight");
1343   if (dpyinfo->x_focus_frame)
1344     {
1345       dpyinfo->x_highlight_frame
1346         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1347            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1348            : dpyinfo->x_focus_frame);
1349       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1350         {
1351           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1352           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1353         }
1354     }
1355   else
1356       dpyinfo->x_highlight_frame = 0;
1358   if (dpyinfo->x_highlight_frame &&
1359          dpyinfo->x_highlight_frame != old_highlight)
1360     {
1361       if (old_highlight)
1362         {
1363           x_update_cursor (old_highlight, 1);
1364           x_set_frame_alpha (old_highlight);
1365         }
1366       if (dpyinfo->x_highlight_frame)
1367         {
1368           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1369           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1370         }
1371     }
1375 void
1376 x_make_frame_visible (struct frame *f)
1377 /* --------------------------------------------------------------------------
1378      External: Show the window (X11 semantics)
1379    -------------------------------------------------------------------------- */
1381   NSTRACE ("x_make_frame_visible");
1382   /* XXX: at some points in past this was not needed, as the only place that
1383      called this (frame.c:Fraise_frame ()) also called raise_lower;
1384      if this ends up the case again, comment this out again. */
1385   if (!FRAME_VISIBLE_P (f))
1386     {
1387       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1389       SET_FRAME_VISIBLE (f, 1);
1390       ns_raise_frame (f);
1392       /* Making a new frame from a fullscreen frame will make the new frame
1393          fullscreen also.  So skip handleFS as this will print an error.  */
1394       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1395           && [view isFullscreen])
1396         return;
1398       if (f->want_fullscreen != FULLSCREEN_NONE)
1399         {
1400           block_input ();
1401           [view handleFS];
1402           unblock_input ();
1403         }
1404     }
1408 void
1409 x_make_frame_invisible (struct frame *f)
1410 /* --------------------------------------------------------------------------
1411      External: Hide the window (X11 semantics)
1412    -------------------------------------------------------------------------- */
1414   NSView *view;
1415   NSTRACE ("x_make_frame_invisible");
1416   check_window_system (f);
1417   view = FRAME_NS_VIEW (f);
1418   [[view window] orderOut: NSApp];
1419   SET_FRAME_VISIBLE (f, 0);
1420   SET_FRAME_ICONIFIED (f, 0);
1424 void
1425 x_iconify_frame (struct frame *f)
1426 /* --------------------------------------------------------------------------
1427      External: Iconify window
1428    -------------------------------------------------------------------------- */
1430   NSView *view;
1431   struct ns_display_info *dpyinfo;
1433   NSTRACE ("x_iconify_frame");
1434   check_window_system (f);
1435   view = FRAME_NS_VIEW (f);
1436   dpyinfo = FRAME_DISPLAY_INFO (f);
1438   if (dpyinfo->x_highlight_frame == f)
1439     dpyinfo->x_highlight_frame = 0;
1441   if ([[view window] windowNumber] <= 0)
1442     {
1443       /* the window is still deferred.  Make it very small, bring it
1444          on screen and order it out. */
1445       NSRect s = { { 100, 100}, {0, 0} };
1446       NSRect t;
1447       t = [[view window] frame];
1448       [[view window] setFrame: s display: NO];
1449       [[view window] orderBack: NSApp];
1450       [[view window] orderOut: NSApp];
1451       [[view window] setFrame: t display: NO];
1452     }
1453   [[view window] miniaturize: NSApp];
1456 /* Free X resources of frame F.  */
1458 void
1459 x_free_frame_resources (struct frame *f)
1461   NSView *view;
1462   struct ns_display_info *dpyinfo;
1463   Mouse_HLInfo *hlinfo;
1465   NSTRACE ("x_free_frame_resources");
1466   check_window_system (f);
1467   view = FRAME_NS_VIEW (f);
1468   dpyinfo = FRAME_DISPLAY_INFO (f);
1469   hlinfo = MOUSE_HL_INFO (f);
1471   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1473   block_input ();
1475   free_frame_menubar (f);
1476   free_frame_faces (f);
1478   if (f == dpyinfo->x_focus_frame)
1479     dpyinfo->x_focus_frame = 0;
1480   if (f == dpyinfo->x_highlight_frame)
1481     dpyinfo->x_highlight_frame = 0;
1482   if (f == hlinfo->mouse_face_mouse_frame)
1483     reset_mouse_highlight (hlinfo);
1485   if (f->output_data.ns->miniimage != nil)
1486     [f->output_data.ns->miniimage release];
1488   [[view window] close];
1489   [view release];
1491   xfree (f->output_data.ns);
1493   unblock_input ();
1496 void
1497 x_destroy_window (struct frame *f)
1498 /* --------------------------------------------------------------------------
1499      External: Delete the window
1500    -------------------------------------------------------------------------- */
1502   NSTRACE ("x_destroy_window");
1503   check_window_system (f);
1504   x_free_frame_resources (f);
1505   ns_window_num--;
1509 void
1510 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1511 /* --------------------------------------------------------------------------
1512      External: Position the window
1513    -------------------------------------------------------------------------- */
1515   NSView *view = FRAME_NS_VIEW (f);
1516   NSArray *screens = [NSScreen screens];
1517   NSScreen *fscreen = [screens objectAtIndex: 0];
1518   NSScreen *screen = [[view window] screen];
1520   NSTRACE ("x_set_offset");
1522   block_input ();
1524   f->left_pos = xoff;
1525   f->top_pos = yoff;
1527   if (view != nil && screen && fscreen)
1528     {
1529       f->left_pos = f->size_hint_flags & XNegative
1530         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1531         : f->left_pos;
1532       /* We use visibleFrame here to take menu bar into account.
1533          Ideally we should also adjust left/top with visibleFrame.origin.  */
1535       f->top_pos = f->size_hint_flags & YNegative
1536         ? ([screen visibleFrame].size.height + f->top_pos
1537            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1538            - FRAME_TOOLBAR_HEIGHT (f))
1539         : f->top_pos;
1540 #ifdef NS_IMPL_GNUSTEP
1541       if (f->left_pos < 100)
1542         f->left_pos = 100;  /* don't overlap menu */
1543 #endif
1544       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1545          menu bar.  */
1546       NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1547                                 SCREENMAXBOUND ([fscreen frame].size.height
1548                                                 - NS_TOP_POS (f)));
1549       NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1550       [[view window] setFrameTopLeftPoint: pt];
1551       f->size_hint_flags &= ~(XNegative|YNegative);
1552     }
1554   unblock_input ();
1558 void
1559 x_set_window_size (struct frame *f,
1560                    bool change_gravity,
1561                    int width,
1562                    int height,
1563                    bool pixelwise)
1564 /* --------------------------------------------------------------------------
1565      Adjust window pixel size based on given character grid size
1566      Impl is a bit more complex than other terms, need to do some
1567      internal clipping.
1568    -------------------------------------------------------------------------- */
1570   EmacsView *view = FRAME_NS_VIEW (f);
1571   NSWindow *window = [view window];
1572   NSRect wr = [window frame];
1573   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1574   int pixelwidth, pixelheight;
1575   int rows, cols;
1576   int orig_height = wr.size.height;
1578   NSTRACE ("x_set_window_size");
1580   if (view == nil)
1581     return;
1583   NSTRACE_RECT ("current", wr);
1584   NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1585   NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1587   block_input ();
1589   if (pixelwise)
1590     {
1591       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1592       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1593       cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1594       rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1595     }
1596   else
1597     {
1598       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1599       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1600       cols = width;
1601       rows = height;
1602     }
1604   /* If we have a toolbar, take its height into account. */
1605   if (tb && ! [view isFullscreen])
1606     {
1607     /* NOTE: previously this would generate wrong result if toolbar not
1608              yet displayed and fixing toolbar_height=32 helped, but
1609              now (200903) seems no longer needed */
1610     FRAME_TOOLBAR_HEIGHT (f) =
1611       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1612         - FRAME_NS_TITLEBAR_HEIGHT (f);
1613 #if 0
1614       /* Only breaks things here, removed by martin 2015-09-30.  */
1615 #ifdef NS_IMPL_GNUSTEP
1616       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1617 #endif
1618 #endif
1619     }
1620   else
1621     FRAME_TOOLBAR_HEIGHT (f) = 0;
1623   wr.size.width = pixelwidth + f->border_width;
1624   wr.size.height = pixelheight;
1625   if (! [view isFullscreen])
1626     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1627       + FRAME_TOOLBAR_HEIGHT (f);
1629   /* Do not try to constrain to this screen.  We may have multiple
1630      screens, and want Emacs to span those.  Constraining to screen
1631      prevents that, and that is not nice to the user.  */
1632  if (f->output_data.ns->zooming)
1633    f->output_data.ns->zooming = 0;
1634  else
1635    wr.origin.y += orig_height - wr.size.height;
1637  frame_size_history_add
1638    (f, Qx_set_window_size_1, width, height,
1639     list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1640            Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1641            make_number (f->border_width),
1642            make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1643            make_number (FRAME_TOOLBAR_HEIGHT (f))));
1645   [window setFrame: wr display: YES];
1647   /* This is a trick to compensate for Emacs' managing the scrollbar area
1648      as a fixed number of standard character columns.  Instead of leaving
1649      blank space for the extra, we chopped it off above.  Now for
1650      left-hand scrollbars, we shift all rendering to the left by the
1651      difference between the real width and Emacs' imagined one.  For
1652      right-hand bars, don't worry about it since the extra is never used.
1653      (Obviously doesn't work for vertically split windows tho..) */
1654   {
1655     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1656       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1657                      - NS_SCROLL_BAR_WIDTH (f), 0)
1658       : NSMakePoint (0, 0);
1660     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1661     [view setBoundsOrigin: origin];
1662   }
1664   [view updateFrameSize: NO];
1665   unblock_input ();
1669 static void
1670 ns_fullscreen_hook (struct frame *f)
1672   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1674   NSTRACE ("ns_fullscreen_hook");
1676   if (!FRAME_VISIBLE_P (f))
1677     return;
1679    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1680     {
1681       /* Old style fs don't initiate correctly if created from
1682          init/default-frame alist, so use a timer (not nice...).
1683       */
1684       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1685                                      selector: @selector (handleFS)
1686                                      userInfo: nil repeats: NO];
1687       return;
1688     }
1690   block_input ();
1691   [view handleFS];
1692   unblock_input ();
1695 /* ==========================================================================
1697     Color management
1699    ========================================================================== */
1702 NSColor *
1703 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1705   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1706   if (idx < 1 || idx >= color_table->avail)
1707     return nil;
1708   return color_table->colors[idx];
1712 unsigned long
1713 ns_index_color (NSColor *color, struct frame *f)
1715   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1716   ptrdiff_t idx;
1717   ptrdiff_t i;
1719   if (!color_table->colors)
1720     {
1721       color_table->size = NS_COLOR_CAPACITY;
1722       color_table->avail = 1; /* skip idx=0 as marker */
1723       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1724       color_table->colors[0] = nil;
1725       color_table->empty_indices = [[NSMutableSet alloc] init];
1726     }
1728   /* Do we already have this color?  */
1729   for (i = 1; i < color_table->avail; i++)
1730     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1731       return i;
1733   if ([color_table->empty_indices count] > 0)
1734     {
1735       NSNumber *index = [color_table->empty_indices anyObject];
1736       [color_table->empty_indices removeObject: index];
1737       idx = [index unsignedLongValue];
1738     }
1739   else
1740     {
1741       if (color_table->avail == color_table->size)
1742         color_table->colors =
1743           xpalloc (color_table->colors, &color_table->size, 1,
1744                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1745       idx = color_table->avail++;
1746     }
1748   color_table->colors[idx] = color;
1749   [color retain];
1750 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1751   return idx;
1755 void
1756 ns_free_indexed_color (unsigned long idx, struct frame *f)
1758   struct ns_color_table *color_table;
1759   NSColor *color;
1760   NSNumber *index;
1762   if (!f)
1763     return;
1765   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1767   if (idx <= 0 || idx >= color_table->size) {
1768     message1 ("ns_free_indexed_color: Color index out of range.\n");
1769     return;
1770   }
1772   index = [NSNumber numberWithUnsignedInt: idx];
1773   if ([color_table->empty_indices containsObject: index]) {
1774     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1775     return;
1776   }
1778   color = color_table->colors[idx];
1779   [color release];
1780   color_table->colors[idx] = nil;
1781   [color_table->empty_indices addObject: index];
1782 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1786 static int
1787 ns_get_color (const char *name, NSColor **col)
1788 /* --------------------------------------------------------------------------
1789      Parse a color name
1790    -------------------------------------------------------------------------- */
1791 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1792    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1793    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1795   NSColor *new = nil;
1796   static char hex[20];
1797   int scaling = 0;
1798   float r = -1.0, g, b;
1799   NSString *nsname = [NSString stringWithUTF8String: name];
1801   NSTRACE ("ns_get_color(%s, **)", name);
1803   block_input ();
1805   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1806     {
1807 #ifdef NS_IMPL_COCOA
1808       NSString *defname = [[NSUserDefaults standardUserDefaults]
1809                             stringForKey: @"AppleHighlightColor"];
1810       if (defname != nil)
1811         nsname = defname;
1812       else
1813 #endif
1814       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1815         {
1816           *col = [new colorUsingDefaultColorSpace];
1817           unblock_input ();
1818           return 0;
1819         }
1820       else
1821         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1823       name = [nsname UTF8String];
1824     }
1825   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1826     {
1827       /* NOTE: OSX applications normally don't set foreground selection, but
1828          text may be unreadable if we don't.
1829       */
1830       if ((new = [NSColor selectedTextColor]) != nil)
1831         {
1832           *col = [new colorUsingDefaultColorSpace];
1833           unblock_input ();
1834           return 0;
1835         }
1837       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1838       name = [nsname UTF8String];
1839     }
1841   /* First, check for some sort of numeric specification. */
1842   hex[0] = '\0';
1844   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1845     {
1846       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1847       [scanner scanFloat: &r];
1848       [scanner scanFloat: &g];
1849       [scanner scanFloat: &b];
1850     }
1851   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1852     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1853   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1854     {
1855       int len = (strlen(name) - 1);
1856       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1857       int i;
1858       scaling = strlen(name+start) / 3;
1859       for (i = 0; i < 3; i++)
1860         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1861                  name + start + i * scaling);
1862       hex[3 * (scaling + 1) - 1] = '\0';
1863     }
1865   if (hex[0])
1866     {
1867       int rr, gg, bb;
1868       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1869       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1870         {
1871           r = rr / fscale;
1872           g = gg / fscale;
1873           b = bb / fscale;
1874         }
1875     }
1877   if (r >= 0.0F)
1878     {
1879       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1880       unblock_input ();
1881       return 0;
1882     }
1884   /* Otherwise, color is expected to be from a list */
1885   {
1886     NSEnumerator *lenum, *cenum;
1887     NSString *name;
1888     NSColorList *clist;
1890 #ifdef NS_IMPL_GNUSTEP
1891     /* XXX: who is wrong, the requestor or the implementation? */
1892     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1893         == NSOrderedSame)
1894       nsname = @"highlightColor";
1895 #endif
1897     lenum = [[NSColorList availableColorLists] objectEnumerator];
1898     while ( (clist = [lenum nextObject]) && new == nil)
1899       {
1900         cenum = [[clist allKeys] objectEnumerator];
1901         while ( (name = [cenum nextObject]) && new == nil )
1902           {
1903             if ([name compare: nsname
1904                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1905               new = [clist colorWithKey: name];
1906           }
1907       }
1908   }
1910   if (new)
1911     *col = [new colorUsingDefaultColorSpace];
1912   unblock_input ();
1913   return new ? 0 : 1;
1918 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1919 /* --------------------------------------------------------------------------
1920      Convert a Lisp string object to a NS color
1921    -------------------------------------------------------------------------- */
1923   NSTRACE ("ns_lisp_to_color");
1924   if (STRINGP (color))
1925     return ns_get_color (SSDATA (color), col);
1926   else if (SYMBOLP (color))
1927     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1928   return 1;
1932 Lisp_Object
1933 ns_color_to_lisp (NSColor *col)
1934 /* --------------------------------------------------------------------------
1935      Convert a color to a lisp string with the RGB equivalent
1936    -------------------------------------------------------------------------- */
1938   EmacsCGFloat red, green, blue, alpha, gray;
1939   char buf[1024];
1940   const char *str;
1941   NSTRACE ("ns_color_to_lisp");
1943   block_input ();
1944   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1946       if ((str =[[col colorNameComponent] UTF8String]))
1947         {
1948           unblock_input ();
1949           return build_string ((char *)str);
1950         }
1952     [[col colorUsingDefaultColorSpace]
1953         getRed: &red green: &green blue: &blue alpha: &alpha];
1954   if (red == green && red == blue)
1955     {
1956       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1957             getWhite: &gray alpha: &alpha];
1958       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1959                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1960       unblock_input ();
1961       return build_string (buf);
1962     }
1964   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1965             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1967   unblock_input ();
1968   return build_string (buf);
1972 void
1973 ns_query_color(void *col, XColor *color_def, int setPixel)
1974 /* --------------------------------------------------------------------------
1975          Get ARGB values out of NSColor col and put them into color_def.
1976          If setPixel, set the pixel to a concatenated version.
1977          and set color_def pixel to the resulting index.
1978    -------------------------------------------------------------------------- */
1980   EmacsCGFloat r, g, b, a;
1982   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1983   color_def->red   = r * 65535;
1984   color_def->green = g * 65535;
1985   color_def->blue  = b * 65535;
1987   if (setPixel == YES)
1988     color_def->pixel
1989       = ARGB_TO_ULONG((int)(a*255),
1990                       (int)(r*255), (int)(g*255), (int)(b*255));
1994 bool
1995 ns_defined_color (struct frame *f,
1996                   const char *name,
1997                   XColor *color_def,
1998                   bool alloc,
1999                   bool makeIndex)
2000 /* --------------------------------------------------------------------------
2001          Return true if named color found, and set color_def rgb accordingly.
2002          If makeIndex and alloc are nonzero put the color in the color_table,
2003          and set color_def pixel to the resulting index.
2004          If makeIndex is zero, set color_def pixel to ARGB.
2005          Return false if not found
2006    -------------------------------------------------------------------------- */
2008   NSColor *col;
2009   NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2011   block_input ();
2012   if (ns_get_color (name, &col) != 0) /* Color not found  */
2013     {
2014       unblock_input ();
2015       return 0;
2016     }
2017   if (makeIndex && alloc)
2018     color_def->pixel = ns_index_color (col, f);
2019   ns_query_color (col, color_def, !makeIndex);
2020   unblock_input ();
2021   return 1;
2025 void
2026 x_set_frame_alpha (struct frame *f)
2027 /* --------------------------------------------------------------------------
2028      change the entire-frame transparency
2029    -------------------------------------------------------------------------- */
2031   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2032   double alpha = 1.0;
2033   double alpha_min = 1.0;
2035   NSTRACE ("x_set_frame_alpha");
2037   if (dpyinfo->x_highlight_frame == f)
2038     alpha = f->alpha[0];
2039   else
2040     alpha = f->alpha[1];
2042   if (FLOATP (Vframe_alpha_lower_limit))
2043     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2044   else if (INTEGERP (Vframe_alpha_lower_limit))
2045     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2047   if (alpha < 0.0)
2048     return;
2049   else if (1.0 < alpha)
2050     alpha = 1.0;
2051   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2052     alpha = alpha_min;
2054 #ifdef NS_IMPL_COCOA
2055   {
2056     EmacsView *view = FRAME_NS_VIEW (f);
2057   [[view window] setAlphaValue: alpha];
2058   }
2059 #endif
2063 /* ==========================================================================
2065     Mouse handling
2067    ========================================================================== */
2070 void
2071 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2072 /* --------------------------------------------------------------------------
2073      Programmatically reposition mouse pointer in pixel coordinates
2074    -------------------------------------------------------------------------- */
2076   NSTRACE ("frame_set_mouse_pixel_position");
2077   ns_raise_frame (f);
2078 #if 0
2079   /* FIXME: this does not work, and what about GNUstep? */
2080 #ifdef NS_IMPL_COCOA
2081   [FRAME_NS_VIEW (f) lockFocus];
2082   PSsetmouse ((float)pix_x, (float)pix_y);
2083   [FRAME_NS_VIEW (f) unlockFocus];
2084 #endif
2085 #endif
2088 static int
2089 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2090 /*   ------------------------------------------------------------------------
2091      Called by EmacsView on mouseMovement events.  Passes on
2092      to emacs mainstream code if we moved off of a rect of interest
2093      known as last_mouse_glyph.
2094      ------------------------------------------------------------------------ */
2096   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2097   NSRect *r;
2099 //  NSTRACE ("note_mouse_movement");
2101   dpyinfo->last_mouse_motion_frame = frame;
2102   r = &dpyinfo->last_mouse_glyph;
2104   /* Note, this doesn't get called for enter/leave, since we don't have a
2105      position.  Those are taken care of in the corresponding NSView methods. */
2107   /* has movement gone beyond last rect we were tracking? */
2108   if (x < r->origin.x || x >= r->origin.x + r->size.width
2109       || y < r->origin.y || y >= r->origin.y + r->size.height)
2110     {
2111       ns_update_begin (frame);
2112       frame->mouse_moved = 1;
2113       note_mouse_highlight (frame, x, y);
2114       remember_mouse_glyph (frame, x, y, r);
2115       ns_update_end (frame);
2116       return 1;
2117     }
2119   return 0;
2123 static void
2124 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2125                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2126                    Time *time)
2127 /* --------------------------------------------------------------------------
2128     External (hook): inform emacs about mouse position and hit parts.
2129     If a scrollbar is being dragged, set bar_window, part, x, y, time.
2130     x & y should be position in the scrollbar (the whole bar, not the handle)
2131     and length of scrollbar respectively
2132    -------------------------------------------------------------------------- */
2134   id view;
2135   NSPoint position;
2136   Lisp_Object frame, tail;
2137   struct frame *f;
2138   struct ns_display_info *dpyinfo;
2140   NSTRACE ("ns_mouse_position");
2142   if (*fp == NULL)
2143     {
2144       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2145       return;
2146     }
2148   dpyinfo = FRAME_DISPLAY_INFO (*fp);
2150   block_input ();
2152   /* Clear the mouse-moved flag for every frame on this display.  */
2153   FOR_EACH_FRAME (tail, frame)
2154     if (FRAME_NS_P (XFRAME (frame))
2155         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2156       XFRAME (frame)->mouse_moved = 0;
2158   dpyinfo->last_mouse_scroll_bar = nil;
2159   if (dpyinfo->last_mouse_frame
2160       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2161     f = dpyinfo->last_mouse_frame;
2162   else
2163     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2165   if (f && FRAME_NS_P (f))
2166     {
2167       view = FRAME_NS_VIEW (*fp);
2169       position = [[view window] mouseLocationOutsideOfEventStream];
2170       position = [view convertPoint: position fromView: nil];
2171       remember_mouse_glyph (f, position.x, position.y,
2172                             &dpyinfo->last_mouse_glyph);
2173       NSTRACE_POINT ("position", position);
2175       if (bar_window) *bar_window = Qnil;
2176       if (part) *part = scroll_bar_above_handle;
2178       if (x) XSETINT (*x, lrint (position.x));
2179       if (y) XSETINT (*y, lrint (position.y));
2180       if (time)
2181         *time = dpyinfo->last_mouse_movement_time;
2182       *fp = f;
2183     }
2185   unblock_input ();
2189 static void
2190 ns_frame_up_to_date (struct frame *f)
2191 /* --------------------------------------------------------------------------
2192     External (hook): Fix up mouse highlighting right after a full update.
2193     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2194    -------------------------------------------------------------------------- */
2196   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2198   if (FRAME_NS_P (f))
2199     {
2200       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2201       if (f == hlinfo->mouse_face_mouse_frame)
2202         {
2203           block_input ();
2204           ns_update_begin(f);
2205           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2206                                 hlinfo->mouse_face_mouse_x,
2207                                 hlinfo->mouse_face_mouse_y);
2208           ns_update_end(f);
2209           unblock_input ();
2210         }
2211     }
2215 static void
2216 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2217 /* --------------------------------------------------------------------------
2218     External (RIF): set frame mouse pointer type.
2219    -------------------------------------------------------------------------- */
2221   NSTRACE ("ns_define_frame_cursor");
2222   if (FRAME_POINTER_TYPE (f) != cursor)
2223     {
2224       EmacsView *view = FRAME_NS_VIEW (f);
2225       FRAME_POINTER_TYPE (f) = cursor;
2226       [[view window] invalidateCursorRectsForView: view];
2227       /* Redisplay assumes this function also draws the changed frame
2228          cursor, but this function doesn't, so do it explicitly.  */
2229       x_update_cursor (f, 1);
2230     }
2235 /* ==========================================================================
2237     Keyboard handling
2239    ========================================================================== */
2242 static unsigned
2243 ns_convert_key (unsigned code)
2244 /* --------------------------------------------------------------------------
2245     Internal call used by NSView-keyDown.
2246    -------------------------------------------------------------------------- */
2248   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2249   unsigned keysym;
2250   /* An array would be faster, but less easy to read. */
2251   for (keysym = 0; keysym < last_keysym; keysym += 2)
2252     if (code == convert_ns_to_X_keysym[keysym])
2253       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2254   return 0;
2255 /* if decide to use keyCode and Carbon table, use this line:
2256      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2260 char *
2261 x_get_keysym_name (int keysym)
2262 /* --------------------------------------------------------------------------
2263     Called by keyboard.c.  Not sure if the return val is important, except
2264     that it be unique.
2265    -------------------------------------------------------------------------- */
2267   static char value[16];
2268   NSTRACE ("x_get_keysym_name");
2269   sprintf (value, "%d", keysym);
2270   return value;
2275 /* ==========================================================================
2277     Block drawing operations
2279    ========================================================================== */
2282 static void
2283 ns_redraw_scroll_bars (struct frame *f)
2285   int i;
2286   id view;
2287   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2288   NSTRACE ("ns_redraw_scroll_bars");
2289   for (i =[subviews count]-1; i >= 0; i--)
2290     {
2291       view = [subviews objectAtIndex: i];
2292       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2293       [view display];
2294     }
2298 void
2299 ns_clear_frame (struct frame *f)
2300 /* --------------------------------------------------------------------------
2301       External (hook): Erase the entire frame
2302    -------------------------------------------------------------------------- */
2304   NSView *view = FRAME_NS_VIEW (f);
2305   NSRect r;
2307   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2309  /* comes on initial frame because we have
2310     after-make-frame-functions = select-frame */
2311  if (!FRAME_DEFAULT_FACE (f))
2312    return;
2314   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2316   r = [view bounds];
2318   block_input ();
2319   ns_focus (f, &r, 1);
2320   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2321   NSRectFill (r);
2322   ns_unfocus (f);
2324   /* as of 2006/11 or so this is now needed */
2325   ns_redraw_scroll_bars (f);
2326   unblock_input ();
2330 static void
2331 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2332 /* --------------------------------------------------------------------------
2333     External (RIF):  Clear section of frame
2334    -------------------------------------------------------------------------- */
2336   NSRect r = NSMakeRect (x, y, width, height);
2337   NSView *view = FRAME_NS_VIEW (f);
2338   struct face *face = FRAME_DEFAULT_FACE (f);
2340   if (!view || !face)
2341     return;
2343   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2345   r = NSIntersectionRect (r, [view frame]);
2346   ns_focus (f, &r, 1);
2347   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2349   NSRectFill (r);
2351   ns_unfocus (f);
2352   return;
2355 static void
2356 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2358   if (FRAME_NS_VIEW (f))
2359     {
2360       hide_bell();              // Ensure the bell image isn't scrolled.
2362       ns_focus (f, &dest, 1);
2363       [FRAME_NS_VIEW (f) scrollRect: src
2364                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2365                                                  dest.origin.y - src.origin.y)];
2366       ns_unfocus (f);
2367     }
2370 static void
2371 ns_scroll_run (struct window *w, struct run *run)
2372 /* --------------------------------------------------------------------------
2373     External (RIF):  Insert or delete n lines at line vpos
2374    -------------------------------------------------------------------------- */
2376   struct frame *f = XFRAME (w->frame);
2377   int x, y, width, height, from_y, to_y, bottom_y;
2379   NSTRACE ("ns_scroll_run");
2381   /* begin copy from other terms */
2382   /* Get frame-relative bounding box of the text display area of W,
2383      without mode lines.  Include in this box the left and right
2384      fringe of W.  */
2385   window_box (w, ANY_AREA, &x, &y, &width, &height);
2387   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2388   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2389   bottom_y = y + height;
2391   if (to_y < from_y)
2392     {
2393       /* Scrolling up.  Make sure we don't copy part of the mode
2394          line at the bottom.  */
2395       if (from_y + run->height > bottom_y)
2396         height = bottom_y - from_y;
2397       else
2398         height = run->height;
2399     }
2400   else
2401     {
2402       /* Scrolling down.  Make sure we don't copy over the mode line.
2403          at the bottom.  */
2404       if (to_y + run->height > bottom_y)
2405         height = bottom_y - to_y;
2406       else
2407         height = run->height;
2408     }
2409   /* end copy from other terms */
2411   if (height == 0)
2412       return;
2414   block_input ();
2416   x_clear_cursor (w);
2418   {
2419     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2420     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2422     ns_copy_bits (f, srcRect , dstRect);
2423   }
2425   unblock_input ();
2429 static void
2430 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2431 /* --------------------------------------------------------------------------
2432     External (RIF): preparatory to fringe update after text was updated
2433    -------------------------------------------------------------------------- */
2435   struct frame *f;
2436   int width, height;
2438   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2440   /* begin copy from other terms */
2441   eassert (w);
2443   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2444     desired_row->redraw_fringe_bitmaps_p = 1;
2446   /* When a window has disappeared, make sure that no rest of
2447      full-width rows stays visible in the internal border.  */
2448   if (windows_or_buffers_changed
2449       && desired_row->full_width_p
2450       && (f = XFRAME (w->frame),
2451           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2452           width != 0)
2453       && (height = desired_row->visible_height,
2454           height > 0))
2455     {
2456       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2458       block_input ();
2459       ns_clear_frame_area (f, 0, y, width, height);
2460       ns_clear_frame_area (f,
2461                            FRAME_PIXEL_WIDTH (f) - width,
2462                            y, width, height);
2463       unblock_input ();
2464     }
2468 static void
2469 ns_shift_glyphs_for_insert (struct frame *f,
2470                            int x, int y, int width, int height,
2471                            int shift_by)
2472 /* --------------------------------------------------------------------------
2473     External (RIF): copy an area horizontally, don't worry about clearing src
2474    -------------------------------------------------------------------------- */
2476   NSRect srcRect = NSMakeRect (x, y, width, height);
2477   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2479   NSTRACE ("ns_shift_glyphs_for_insert");
2481   ns_copy_bits (f, srcRect, dstRect);
2486 /* ==========================================================================
2488     Character encoding and metrics
2490    ========================================================================== */
2493 static void
2494 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2495 /* --------------------------------------------------------------------------
2496      External (RIF); compute left/right overhang of whole string and set in s
2497    -------------------------------------------------------------------------- */
2499   struct font *font = s->font;
2501   if (s->char2b)
2502     {
2503       struct font_metrics metrics;
2504       unsigned int codes[2];
2505       codes[0] = *(s->char2b);
2506       codes[1] = *(s->char2b + s->nchars - 1);
2508       font->driver->text_extents (font, codes, 2, &metrics);
2509       s->left_overhang = -metrics.lbearing;
2510       s->right_overhang
2511         = metrics.rbearing > metrics.width
2512         ? metrics.rbearing - metrics.width : 0;
2513     }
2514   else
2515     {
2516       s->left_overhang = 0;
2517       if (EQ (font->driver->type, Qns))
2518         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2519           FONT_HEIGHT (font) * 0.2 : 0;
2520       else
2521         s->right_overhang = 0;
2522     }
2527 /* ==========================================================================
2529     Fringe and cursor drawing
2531    ========================================================================== */
2534 extern int max_used_fringe_bitmap;
2535 static void
2536 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2537                       struct draw_fringe_bitmap_params *p)
2538 /* --------------------------------------------------------------------------
2539     External (RIF); fringe-related
2540    -------------------------------------------------------------------------- */
2542   /* Fringe bitmaps comes in two variants, normal and periodic.  A
2543      periodic bitmap is used to create a continuous pattern.  Since a
2544      bitmap is rendered one text line at a time, the start offset (dh)
2545      of the bitmap varies.  Concretely, this is used for the empty
2546      line indicator.
2548      For a bitmap, "h + dh" is the full height and is always
2549      invariant.  For a normal bitmap "dh" is zero.
2551      For example, when the period is three and the full height is 72
2552      the following combinations exists:
2554        h=72 dh=0
2555        h=71 dh=1
2556        h=70 dh=2 */
2558   struct frame *f = XFRAME (WINDOW_FRAME (w));
2559   struct face *face = p->face;
2560   static EmacsImage **bimgs = NULL;
2561   static int nBimgs = 0;
2563   NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2564   NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2565                p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2567   /* grow bimgs if needed */
2568   if (nBimgs < max_used_fringe_bitmap)
2569     {
2570       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2571       memset (bimgs + nBimgs, 0,
2572               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2573       nBimgs = max_used_fringe_bitmap;
2574     }
2576   /* Must clip because of partially visible lines.  */
2577   ns_clip_to_row (w, row, ANY_AREA, YES);
2579   if (!p->overlay_p)
2580     {
2581       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2583       if (bx >= 0 && nx > 0)
2584         {
2585           NSRect r = NSMakeRect (bx, by, nx, ny);
2586           NSRectClip (r);
2587           [ns_lookup_indexed_color (face->background, f) set];
2588           NSRectFill (r);
2589         }
2590     }
2592   if (p->which)
2593     {
2594       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2595       EmacsImage *img = bimgs[p->which - 1];
2597       if (!img)
2598         {
2599           // Note: For "periodic" images, allocate one EmacsImage for
2600           // the base image, and use it for all dh:s.
2601           unsigned short *bits = p->bits;
2602           int full_height = p->h + p->dh;
2603           int i;
2604           unsigned char *cbits = xmalloc (full_height);
2606           for (i = 0; i < full_height; i++)
2607             cbits[i] = bits[i];
2608           img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2609                                          height: full_height
2610                                              fg: 0 bg: 0];
2611           bimgs[p->which - 1] = img;
2612           xfree (cbits);
2613         }
2615       NSTRACE_RECT ("r", r);
2617       NSRectClip (r);
2618       /* Since we composite the bitmap instead of just blitting it, we need
2619          to erase the whole background. */
2620       [ns_lookup_indexed_color(face->background, f) set];
2621       NSRectFill (r);
2623       {
2624         NSColor *bm_color;
2625         if (!p->cursor_p)
2626           bm_color = ns_lookup_indexed_color(face->foreground, f);
2627         else if (p->overlay_p)
2628           bm_color = ns_lookup_indexed_color(face->background, f);
2629         else
2630           bm_color = f->output_data.ns->cursor_color;
2631         [img setXBMColor: bm_color];
2632       }
2634       // Note: For periodic images, the full image height is "h + hd".
2635       // By using the height h, a suitable part of the image is used.
2636       NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2638       NSTRACE_RECT ("fromRect", fromRect);
2640 #ifdef NS_IMPL_COCOA
2641       [img drawInRect: r
2642               fromRect: fromRect
2643              operation: NSCompositeSourceOver
2644               fraction: 1.0
2645            respectFlipped: YES
2646                 hints: nil];
2647 #else
2648       {
2649         NSPoint pt = r.origin;
2650         pt.y += p->h;
2651         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2652       }
2653 #endif
2654     }
2655   ns_unfocus (f);
2659 static void
2660 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2661                        int x, int y, enum text_cursor_kinds cursor_type,
2662                        int cursor_width, bool on_p, bool active_p)
2663 /* --------------------------------------------------------------------------
2664      External call (RIF): draw cursor.
2665      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2666    -------------------------------------------------------------------------- */
2668   NSRect r, s;
2669   int fx, fy, h, cursor_height;
2670   struct frame *f = WINDOW_XFRAME (w);
2671   struct glyph *phys_cursor_glyph;
2672   struct glyph *cursor_glyph;
2673   struct face *face;
2674   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2676   /* If cursor is out of bounds, don't draw garbage.  This can happen
2677      in mini-buffer windows when switching between echo area glyphs
2678      and mini-buffer.  */
2680   NSTRACE ("ns_draw_window_cursor");
2682   if (!on_p)
2683     return;
2685   w->phys_cursor_type = cursor_type;
2686   w->phys_cursor_on_p = on_p;
2688   if (cursor_type == NO_CURSOR)
2689     {
2690       w->phys_cursor_width = 0;
2691       return;
2692     }
2694   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2695     {
2696       if (glyph_row->exact_window_width_line_p
2697           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2698         {
2699           glyph_row->cursor_in_fringe_p = 1;
2700           draw_fringe_bitmap (w, glyph_row, 0);
2701         }
2702       return;
2703     }
2705   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2706      (other terminals do it the other way round).  We must set
2707      w->phys_cursor_width to the cursor width.  For bar cursors, that
2708      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2709   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2711   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2712      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2713   if (cursor_type == BAR_CURSOR)
2714     {
2715       if (cursor_width < 1)
2716         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2717       w->phys_cursor_width = cursor_width;
2718     }
2719   /* If we have an HBAR, "cursor_width" MAY specify height. */
2720   else if (cursor_type == HBAR_CURSOR)
2721     {
2722       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2723       if (cursor_height > glyph_row->height)
2724         cursor_height = glyph_row->height;
2725       if (h > cursor_height) // Cursor smaller than line height, move down
2726         fy += h - cursor_height;
2727       h = cursor_height;
2728     }
2730   r.origin.x = fx, r.origin.y = fy;
2731   r.size.height = h;
2732   r.size.width = w->phys_cursor_width;
2734   /* TODO: only needed in rare cases with last-resort font in HELLO..
2735      should we do this more efficiently? */
2736   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2739   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2740   if (face && NS_FACE_BACKGROUND (face)
2741       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2742     {
2743       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2744       hollow_color = FRAME_CURSOR_COLOR (f);
2745     }
2746   else
2747     [FRAME_CURSOR_COLOR (f) set];
2749 #ifdef NS_IMPL_COCOA
2750   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2751            atomic.  Cleaner ways of doing this should be investigated.
2752            One way would be to set a global variable DRAWING_CURSOR
2753            when making the call to draw_phys..(), don't focus in that
2754            case, then move the ns_unfocus() here after that call. */
2755   NSDisableScreenUpdates ();
2756 #endif
2758   switch (cursor_type)
2759     {
2760     case DEFAULT_CURSOR:
2761     case NO_CURSOR:
2762       break;
2763     case FILLED_BOX_CURSOR:
2764       NSRectFill (r);
2765       break;
2766     case HOLLOW_BOX_CURSOR:
2767       NSRectFill (r);
2768       [hollow_color set];
2769       NSRectFill (NSInsetRect (r, 1, 1));
2770       [FRAME_CURSOR_COLOR (f) set];
2771       break;
2772     case HBAR_CURSOR:
2773       NSRectFill (r);
2774       break;
2775     case BAR_CURSOR:
2776       s = r;
2777       /* If the character under cursor is R2L, draw the bar cursor
2778          on the right of its glyph, rather than on the left.  */
2779       cursor_glyph = get_phys_cursor_glyph (w);
2780       if ((cursor_glyph->resolved_level & 1) != 0)
2781         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2783       NSRectFill (s);
2784       break;
2785     }
2786   ns_unfocus (f);
2788   /* draw the character under the cursor */
2789   if (cursor_type != NO_CURSOR)
2790     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2792 #ifdef NS_IMPL_COCOA
2793   NSEnableScreenUpdates ();
2794 #endif
2799 static void
2800 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2801 /* --------------------------------------------------------------------------
2802      External (RIF): Draw a vertical line.
2803    -------------------------------------------------------------------------- */
2805   struct frame *f = XFRAME (WINDOW_FRAME (w));
2806   struct face *face;
2807   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2809   NSTRACE ("ns_draw_vertical_window_border");
2811   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2812   if (face)
2813       [ns_lookup_indexed_color(face->foreground, f) set];
2815   ns_focus (f, &r, 1);
2816   NSRectFill(r);
2817   ns_unfocus (f);
2821 static void
2822 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2823 /* --------------------------------------------------------------------------
2824      External (RIF): Draw a window divider.
2825    -------------------------------------------------------------------------- */
2827   struct frame *f = XFRAME (WINDOW_FRAME (w));
2828   struct face *face;
2829   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2831   NSTRACE ("ns_draw_window_divider");
2833   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2834   if (face)
2835       [ns_lookup_indexed_color(face->foreground, f) set];
2837   ns_focus (f, &r, 1);
2838   NSRectFill(r);
2839   ns_unfocus (f);
2842 static void
2843 ns_show_hourglass (struct frame *f)
2845   /* TODO: add NSProgressIndicator to all frames.  */
2848 static void
2849 ns_hide_hourglass (struct frame *f)
2851   /* TODO: remove NSProgressIndicator from all frames.  */
2854 /* ==========================================================================
2856     Glyph drawing operations
2858    ========================================================================== */
2860 static int
2861 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2862 /* --------------------------------------------------------------------------
2863     Wrapper utility to account for internal border width on full-width lines,
2864     and allow top full-width rows to hit the frame top.  nr should be pointer
2865     to two successive NSRects.  Number of rects actually used is returned.
2866    -------------------------------------------------------------------------- */
2868   int n = get_glyph_string_clip_rects (s, nr, 2);
2869   return n;
2872 /* --------------------------------------------------------------------
2873    Draw a wavy line under glyph string s. The wave fills wave_height
2874    pixels from y.
2876                     x          wave_length = 2
2877                                  --
2878                 y    *   *   *   *   *
2879                      |* * * * * * * * *
2880     wave_height = 3  | *   *   *   *
2881   --------------------------------------------------------------------- */
2883 static void
2884 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2886   int wave_height = 3, wave_length = 2;
2887   int y, dx, dy, odd, xmax;
2888   NSPoint a, b;
2889   NSRect waveClip;
2891   dx = wave_length;
2892   dy = wave_height - 1;
2893   y =  s->ybase - wave_height + 3;
2894   xmax = x + width;
2896   /* Find and set clipping rectangle */
2897   waveClip = NSMakeRect (x, y, width, wave_height);
2898   [[NSGraphicsContext currentContext] saveGraphicsState];
2899   NSRectClip (waveClip);
2901   /* Draw the waves */
2902   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2903   b.x = a.x + dx;
2904   odd = (int)(a.x/dx) % 2;
2905   a.y = b.y = y + 0.5;
2907   if (odd)
2908     a.y += dy;
2909   else
2910     b.y += dy;
2912   while (a.x <= xmax)
2913     {
2914       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2915       a.x = b.x, a.y = b.y;
2916       b.x += dx, b.y = y + 0.5 + odd*dy;
2917       odd = !odd;
2918     }
2920   /* Restore previous clipping rectangle(s) */
2921   [[NSGraphicsContext currentContext] restoreGraphicsState];
2926 void
2927 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2928                          NSColor *defaultCol, CGFloat width, CGFloat x)
2929 /* --------------------------------------------------------------------------
2930    Draw underline, overline, and strike-through on glyph string s.
2931    -------------------------------------------------------------------------- */
2933   if (s->for_overlaps)
2934     return;
2936   /* Do underline. */
2937   if (face->underline_p)
2938     {
2939       if (s->face->underline_type == FACE_UNDER_WAVE)
2940         {
2941           if (face->underline_defaulted_p)
2942             [defaultCol set];
2943           else
2944             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2946           ns_draw_underwave (s, width, x);
2947         }
2948       else if (s->face->underline_type == FACE_UNDER_LINE)
2949         {
2951           NSRect r;
2952           unsigned long thickness, position;
2954           /* If the prev was underlined, match its appearance. */
2955           if (s->prev && s->prev->face->underline_p
2956               && s->prev->face->underline_type == FACE_UNDER_LINE
2957               && s->prev->underline_thickness > 0)
2958             {
2959               thickness = s->prev->underline_thickness;
2960               position = s->prev->underline_position;
2961             }
2962           else
2963             {
2964               struct font *font;
2965               unsigned long descent;
2967               font=s->font;
2968               descent = s->y + s->height - s->ybase;
2970               /* Use underline thickness of font, defaulting to 1. */
2971               thickness = (font && font->underline_thickness > 0)
2972                 ? font->underline_thickness : 1;
2974               /* Determine the offset of underlining from the baseline. */
2975               if (x_underline_at_descent_line)
2976                 position = descent - thickness;
2977               else if (x_use_underline_position_properties
2978                        && font && font->underline_position >= 0)
2979                 position = font->underline_position;
2980               else if (font)
2981                 position = lround (font->descent / 2);
2982               else
2983                 position = underline_minimum_offset;
2985               position = max (position, underline_minimum_offset);
2987               /* Ensure underlining is not cropped. */
2988               if (descent <= position)
2989                 {
2990                   position = descent - 1;
2991                   thickness = 1;
2992                 }
2993               else if (descent < position + thickness)
2994                 thickness = 1;
2995             }
2997           s->underline_thickness = thickness;
2998           s->underline_position = position;
3000           r = NSMakeRect (x, s->ybase + position, width, thickness);
3002           if (face->underline_defaulted_p)
3003             [defaultCol set];
3004           else
3005             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3006           NSRectFill (r);
3007         }
3008     }
3009   /* Do overline. We follow other terms in using a thickness of 1
3010      and ignoring overline_margin. */
3011   if (face->overline_p)
3012     {
3013       NSRect r;
3014       r = NSMakeRect (x, s->y, width, 1);
3016       if (face->overline_color_defaulted_p)
3017         [defaultCol set];
3018       else
3019         [ns_lookup_indexed_color (face->overline_color, s->f) set];
3020       NSRectFill (r);
3021     }
3023   /* Do strike-through.  We follow other terms for thickness and
3024      vertical position.*/
3025   if (face->strike_through_p)
3026     {
3027       NSRect r;
3028       unsigned long dy;
3030       dy = lrint ((s->height - 1) / 2);
3031       r = NSMakeRect (x, s->y + dy, width, 1);
3033       if (face->strike_through_color_defaulted_p)
3034         [defaultCol set];
3035       else
3036         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3037       NSRectFill (r);
3038     }
3041 static void
3042 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3043              char left_p, char right_p)
3044 /* --------------------------------------------------------------------------
3045     Draw an unfilled rect inside r, optionally leaving left and/or right open.
3046     Note we can't just use an NSDrawRect command, because of the possibility
3047     of some sides not being drawn, and because the rect will be filled.
3048    -------------------------------------------------------------------------- */
3050   NSRect s = r;
3051   [col set];
3053   /* top, bottom */
3054   s.size.height = thickness;
3055   NSRectFill (s);
3056   s.origin.y += r.size.height - thickness;
3057   NSRectFill (s);
3059   s.size.height = r.size.height;
3060   s.origin.y = r.origin.y;
3062   /* left, right (optional) */
3063   s.size.width = thickness;
3064   if (left_p)
3065     NSRectFill (s);
3066   if (right_p)
3067     {
3068       s.origin.x += r.size.width - thickness;
3069       NSRectFill (s);
3070     }
3074 static void
3075 ns_draw_relief (NSRect r, int thickness, char raised_p,
3076                char top_p, char bottom_p, char left_p, char right_p,
3077                struct glyph_string *s)
3078 /* --------------------------------------------------------------------------
3079     Draw a relief rect inside r, optionally leaving some sides open.
3080     Note we can't just use an NSDrawBezel command, because of the possibility
3081     of some sides not being drawn, and because the rect will be filled.
3082    -------------------------------------------------------------------------- */
3084   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3085   NSColor *newBaseCol = nil;
3086   NSRect sr = r;
3088   NSTRACE ("ns_draw_relief");
3090   /* set up colors */
3092   if (s->face->use_box_color_for_shadows_p)
3093     {
3094       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3095     }
3096 /*     else if (s->first_glyph->type == IMAGE_GLYPH
3097            && s->img->pixmap
3098            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3099        {
3100          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
3101        } */
3102   else
3103     {
3104       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3105     }
3107   if (newBaseCol == nil)
3108     newBaseCol = [NSColor grayColor];
3110   if (newBaseCol != baseCol)  /* TODO: better check */
3111     {
3112       [baseCol release];
3113       baseCol = [newBaseCol retain];
3114       [lightCol release];
3115       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3116       [darkCol release];
3117       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3118     }
3120   [(raised_p ? lightCol : darkCol) set];
3122   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3124   /* top */
3125   sr.size.height = thickness;
3126   if (top_p) NSRectFill (sr);
3128   /* left */
3129   sr.size.height = r.size.height;
3130   sr.size.width = thickness;
3131   if (left_p) NSRectFill (sr);
3133   [(raised_p ? darkCol : lightCol) set];
3135   /* bottom */
3136   sr.size.width = r.size.width;
3137   sr.size.height = thickness;
3138   sr.origin.y += r.size.height - thickness;
3139   if (bottom_p) NSRectFill (sr);
3141   /* right */
3142   sr.size.height = r.size.height;
3143   sr.origin.y = r.origin.y;
3144   sr.size.width = thickness;
3145   sr.origin.x += r.size.width - thickness;
3146   if (right_p) NSRectFill (sr);
3150 static void
3151 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3152 /* --------------------------------------------------------------------------
3153       Function modeled after x_draw_glyph_string_box ().
3154       Sets up parameters for drawing.
3155    -------------------------------------------------------------------------- */
3157   int right_x, last_x;
3158   char left_p, right_p;
3159   struct glyph *last_glyph;
3160   NSRect r;
3161   int thickness;
3162   struct face *face;
3164   if (s->hl == DRAW_MOUSE_FACE)
3165     {
3166       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3167       if (!face)
3168         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3169     }
3170   else
3171     face = s->face;
3173   thickness = face->box_line_width;
3175   NSTRACE ("ns_dumpglyphs_box_or_relief");
3177   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3178             ? WINDOW_RIGHT_EDGE_X (s->w)
3179             : window_box_right (s->w, s->area));
3180   last_glyph = (s->cmp || s->img
3181                 ? s->first_glyph : s->first_glyph + s->nchars-1);
3183   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3184               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3186   left_p = (s->first_glyph->left_box_line_p
3187             || (s->hl == DRAW_MOUSE_FACE
3188                 && (s->prev == NULL || s->prev->hl != s->hl)));
3189   right_p = (last_glyph->right_box_line_p
3190              || (s->hl == DRAW_MOUSE_FACE
3191                  && (s->next == NULL || s->next->hl != s->hl)));
3193   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3195   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3196   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3197     {
3198       ns_draw_box (r, abs (thickness),
3199                    ns_lookup_indexed_color (face->box_color, s->f),
3200                   left_p, right_p);
3201     }
3202   else
3203     {
3204       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3205                      1, 1, left_p, right_p, s);
3206     }
3210 static void
3211 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3212 /* --------------------------------------------------------------------------
3213       Modeled after x_draw_glyph_string_background, which draws BG in
3214       certain cases.  Others are left to the text rendering routine.
3215    -------------------------------------------------------------------------- */
3217   NSTRACE ("ns_maybe_dumpglyphs_background");
3219   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3220     {
3221       int box_line_width = max (s->face->box_line_width, 0);
3222       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3223           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3224              dimensions, since the actual glyphs might be much
3225              smaller.  So in that case we always clear the rectangle
3226              with background color.  */
3227           || FONT_TOO_HIGH (s->font)
3228           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3229         {
3230           struct face *face;
3231           if (s->hl == DRAW_MOUSE_FACE)
3232             {
3233               face = FACE_FROM_ID (s->f,
3234                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3235               if (!face)
3236                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3237             }
3238           else
3239             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3240           if (!face->stipple)
3241             [(NS_FACE_BACKGROUND (face) != 0
3242               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3243               : FRAME_BACKGROUND_COLOR (s->f)) set];
3244           else
3245             {
3246               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3247               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3248             }
3250           if (s->hl != DRAW_CURSOR)
3251             {
3252               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3253                                     s->background_width,
3254                                     s->height-2*box_line_width);
3255               NSRectFill (r);
3256             }
3258           s->background_filled_p = 1;
3259         }
3260     }
3264 static void
3265 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3266 /* --------------------------------------------------------------------------
3267       Renders an image and associated borders.
3268    -------------------------------------------------------------------------- */
3270   EmacsImage *img = s->img->pixmap;
3271   int box_line_vwidth = max (s->face->box_line_width, 0);
3272   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3273   int bg_x, bg_y, bg_height;
3274   int th;
3275   char raised_p;
3276   NSRect br;
3277   struct face *face;
3278   NSColor *tdCol;
3280   NSTRACE ("ns_dumpglyphs_image");
3282   if (s->face->box != FACE_NO_BOX
3283       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3284     x += abs (s->face->box_line_width);
3286   bg_x = x;
3287   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3288   bg_height = s->height;
3289   /* other terms have this, but was causing problems w/tabbar mode */
3290   /* - 2 * box_line_vwidth; */
3292   if (s->slice.x == 0) x += s->img->hmargin;
3293   if (s->slice.y == 0) y += s->img->vmargin;
3295   /* Draw BG: if we need larger area than image itself cleared, do that,
3296      otherwise, since we composite the image under NS (instead of mucking
3297      with its background color), we must clear just the image area. */
3298   if (s->hl == DRAW_MOUSE_FACE)
3299     {
3300       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3301       if (!face)
3302        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3303     }
3304   else
3305     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3307   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3309   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3310       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3311     {
3312       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3313       s->background_filled_p = 1;
3314     }
3315   else
3316     {
3317       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3318     }
3320   NSRectFill (br);
3322   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3323   if (img != nil)
3324     {
3325 #ifdef NS_IMPL_COCOA
3326       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3327       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3328                               s->slice.width, s->slice.height);
3329       [img drawInRect: dr
3330              fromRect: ir
3331              operation: NSCompositeSourceOver
3332               fraction: 1.0
3333            respectFlipped: YES
3334                 hints: nil];
3335 #else
3336       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3337                   operation: NSCompositeSourceOver];
3338 #endif
3339     }
3341   if (s->hl == DRAW_CURSOR)
3342     {
3343     [FRAME_CURSOR_COLOR (s->f) set];
3344     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3345       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3346     else
3347       /* Currently on NS img->mask is always 0. Since
3348          get_window_cursor_type specifies a hollow box cursor when on
3349          a non-masked image we never reach this clause. But we put it
3350          in in anticipation of better support for image masks on
3351          NS. */
3352       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3353     }
3354   else
3355     {
3356       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3357     }
3359   /* Draw underline, overline, strike-through. */
3360   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3362   /* Draw relief, if requested */
3363   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3364     {
3365       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3366         {
3367           th = tool_bar_button_relief >= 0 ?
3368             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3369           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3370         }
3371       else
3372         {
3373           th = abs (s->img->relief);
3374           raised_p = (s->img->relief > 0);
3375         }
3377       r.origin.x = x - th;
3378       r.origin.y = y - th;
3379       r.size.width = s->slice.width + 2*th-1;
3380       r.size.height = s->slice.height + 2*th-1;
3381       ns_draw_relief (r, th, raised_p,
3382                       s->slice.y == 0,
3383                       s->slice.y + s->slice.height == s->img->height,
3384                       s->slice.x == 0,
3385                       s->slice.x + s->slice.width == s->img->width, s);
3386     }
3388   /* If there is no mask, the background won't be seen,
3389      so draw a rectangle on the image for the cursor.
3390      Do this for all images, getting transparency right is not reliable.  */
3391   if (s->hl == DRAW_CURSOR)
3392     {
3393       int thickness = abs (s->img->relief);
3394       if (thickness == 0) thickness = 1;
3395       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3396     }
3400 static void
3401 ns_dumpglyphs_stretch (struct glyph_string *s)
3403   NSRect r[2];
3404   int n, i;
3405   struct face *face;
3406   NSColor *fgCol, *bgCol;
3408   if (!s->background_filled_p)
3409     {
3410       n = ns_get_glyph_string_clip_rect (s, r);
3411       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3413       ns_focus (s->f, r, n);
3415       if (s->hl == DRAW_MOUSE_FACE)
3416        {
3417          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3418          if (!face)
3419            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3420        }
3421       else
3422        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3424       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3425       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3427       for (i = 0; i < n; ++i)
3428         {
3429           if (!s->row->full_width_p)
3430             {
3431               int overrun, leftoverrun;
3433               /* truncate to avoid overwriting fringe and/or scrollbar */
3434               overrun = max (0, (s->x + s->background_width)
3435                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3436                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3437               r[i].size.width -= overrun;
3439               /* truncate to avoid overwriting to left of the window box */
3440               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3441                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3443               if (leftoverrun > 0)
3444                 {
3445                   r[i].origin.x += leftoverrun;
3446                   r[i].size.width -= leftoverrun;
3447                 }
3449               /* XXX: Try to work between problem where a stretch glyph on
3450                  a partially-visible bottom row will clear part of the
3451                  modeline, and another where list-buffers headers and similar
3452                  rows erroneously have visible_height set to 0.  Not sure
3453                  where this is coming from as other terms seem not to show. */
3454               r[i].size.height = min (s->height, s->row->visible_height);
3455             }
3457           [bgCol set];
3459           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3460              overwriting cursor (usually when cursor on a tab) */
3461           if (s->hl == DRAW_CURSOR)
3462             {
3463               CGFloat x, width;
3465               x = r[i].origin.x;
3466               width = s->w->phys_cursor_width;
3467               r[i].size.width -= width;
3468               r[i].origin.x += width;
3470               NSRectFill (r[i]);
3472               /* Draw overlining, etc. on the cursor. */
3473               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3474                 ns_draw_text_decoration (s, face, bgCol, width, x);
3475               else
3476                 ns_draw_text_decoration (s, face, fgCol, width, x);
3477             }
3478           else
3479             {
3480               NSRectFill (r[i]);
3481             }
3483           /* Draw overlining, etc. on the stretch glyph (or the part
3484              of the stretch glyph after the cursor). */
3485           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3486                                    r[i].origin.x);
3487         }
3488       ns_unfocus (s->f);
3489       s->background_filled_p = 1;
3490     }
3494 static void
3495 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3497   int i, j, x;
3498   struct font *font = s->font;
3500   /* If first glyph of S has a left box line, start drawing the text
3501      of S to the right of that box line.  */
3502   if (s->face && s->face->box != FACE_NO_BOX
3503       && s->first_glyph->left_box_line_p)
3504     x = s->x + eabs (s->face->box_line_width);
3505   else
3506     x = s->x;
3508   /* S is a glyph string for a composition.  S->cmp_from is the index
3509      of the first character drawn for glyphs of this composition.
3510      S->cmp_from == 0 means we are drawing the very first character of
3511      this composition.  */
3513   /* Draw a rectangle for the composition if the font for the very
3514      first character of the composition could not be loaded.  */
3515   if (s->font_not_found_p)
3516     {
3517       if (s->cmp_from == 0)
3518         {
3519           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3520           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3521         }
3522     }
3523   else if (! s->first_glyph->u.cmp.automatic)
3524     {
3525       int y = s->ybase;
3527       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3528         /* TAB in a composition means display glyphs with padding
3529            space on the left or right.  */
3530         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3531           {
3532             int xx = x + s->cmp->offsets[j * 2];
3533             int yy = y - s->cmp->offsets[j * 2 + 1];
3535             font->driver->draw (s, j, j + 1, xx, yy, false);
3536             if (s->face->overstrike)
3537               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3538           }
3539     }
3540   else
3541     {
3542       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3543       Lisp_Object glyph;
3544       int y = s->ybase;
3545       int width = 0;
3547       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3548         {
3549           glyph = LGSTRING_GLYPH (gstring, i);
3550           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3551             width += LGLYPH_WIDTH (glyph);
3552           else
3553             {
3554               int xoff, yoff, wadjust;
3556               if (j < i)
3557                 {
3558                   font->driver->draw (s, j, i, x, y, false);
3559                   if (s->face->overstrike)
3560                     font->driver->draw (s, j, i, x + 1, y, false);
3561                   x += width;
3562                 }
3563               xoff = LGLYPH_XOFF (glyph);
3564               yoff = LGLYPH_YOFF (glyph);
3565               wadjust = LGLYPH_WADJUST (glyph);
3566               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3567               if (s->face->overstrike)
3568                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3569                                     false);
3570               x += wadjust;
3571               j = i + 1;
3572               width = 0;
3573             }
3574         }
3575       if (j < i)
3576         {
3577           font->driver->draw (s, j, i, x, y, false);
3578           if (s->face->overstrike)
3579             font->driver->draw (s, j, i, x + 1, y, false);
3580         }
3581     }
3584 static void
3585 ns_draw_glyph_string (struct glyph_string *s)
3586 /* --------------------------------------------------------------------------
3587       External (RIF): Main draw-text call.
3588    -------------------------------------------------------------------------- */
3590   /* TODO (optimize): focus for box and contents draw */
3591   NSRect r[2];
3592   int n, flags;
3593   char box_drawn_p = 0;
3594   struct font *font = s->face->font;
3595   if (! font) font = FRAME_FONT (s->f);
3597   NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3599   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3600     {
3601       int width;
3602       struct glyph_string *next;
3604       for (width = 0, next = s->next;
3605            next && width < s->right_overhang;
3606            width += next->width, next = next->next)
3607         if (next->first_glyph->type != IMAGE_GLYPH)
3608           {
3609             if (next->first_glyph->type != STRETCH_GLYPH)
3610               {
3611                 n = ns_get_glyph_string_clip_rect (s->next, r);
3612                 ns_focus (s->f, r, n);
3613                 ns_maybe_dumpglyphs_background (s->next, 1);
3614                 ns_unfocus (s->f);
3615               }
3616             else
3617               {
3618                 ns_dumpglyphs_stretch (s->next);
3619               }
3620             next->num_clips = 0;
3621           }
3622     }
3624   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3625         && (s->first_glyph->type == CHAR_GLYPH
3626             || s->first_glyph->type == COMPOSITE_GLYPH))
3627     {
3628       n = ns_get_glyph_string_clip_rect (s, r);
3629       ns_focus (s->f, r, n);
3630       ns_maybe_dumpglyphs_background (s, 1);
3631       ns_dumpglyphs_box_or_relief (s);
3632       ns_unfocus (s->f);
3633       box_drawn_p = 1;
3634     }
3636   switch (s->first_glyph->type)
3637     {
3639     case IMAGE_GLYPH:
3640       n = ns_get_glyph_string_clip_rect (s, r);
3641       ns_focus (s->f, r, n);
3642       ns_dumpglyphs_image (s, r[0]);
3643       ns_unfocus (s->f);
3644       break;
3646     case STRETCH_GLYPH:
3647       ns_dumpglyphs_stretch (s);
3648       break;
3650     case CHAR_GLYPH:
3651     case COMPOSITE_GLYPH:
3652       n = ns_get_glyph_string_clip_rect (s, r);
3653       ns_focus (s->f, r, n);
3655       if (s->for_overlaps || (s->cmp_from > 0
3656                               && ! s->first_glyph->u.cmp.automatic))
3657         s->background_filled_p = 1;
3658       else
3659         ns_maybe_dumpglyphs_background
3660           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3662       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3663         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3664          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3665           NS_DUMPGLYPH_NORMAL));
3667       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3668         {
3669           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3670           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3671           NS_FACE_FOREGROUND (s->face) = tmp;
3672         }
3674       {
3675         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3677         if (isComposite)
3678           ns_draw_composite_glyph_string_foreground (s);
3679         else
3680           font->driver->draw
3681             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3682              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3683              || flags == NS_DUMPGLYPH_MOUSEFACE);
3684       }
3686       {
3687         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3688                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3689                                                    s->f)
3690                         : FRAME_FOREGROUND_COLOR (s->f));
3691         [col set];
3693         /* Draw underline, overline, strike-through. */
3694         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3695       }
3697       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3698         {
3699           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3700           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3701           NS_FACE_FOREGROUND (s->face) = tmp;
3702         }
3704       ns_unfocus (s->f);
3705       break;
3707     case GLYPHLESS_GLYPH:
3708       n = ns_get_glyph_string_clip_rect (s, r);
3709       ns_focus (s->f, r, n);
3711       if (s->for_overlaps || (s->cmp_from > 0
3712                               && ! s->first_glyph->u.cmp.automatic))
3713         s->background_filled_p = 1;
3714       else
3715         ns_maybe_dumpglyphs_background
3716           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3717       /* ... */
3718       /* Not yet implemented.  */
3719       /* ... */
3720       ns_unfocus (s->f);
3721       break;
3723     default:
3724       emacs_abort ();
3725     }
3727   /* Draw box if not done already. */
3728   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3729     {
3730       n = ns_get_glyph_string_clip_rect (s, r);
3731       ns_focus (s->f, r, n);
3732       ns_dumpglyphs_box_or_relief (s);
3733       ns_unfocus (s->f);
3734     }
3736   s->num_clips = 0;
3741 /* ==========================================================================
3743     Event loop
3745    ========================================================================== */
3748 static void
3749 ns_send_appdefined (int value)
3750 /* --------------------------------------------------------------------------
3751     Internal: post an appdefined event which EmacsApp-sendEvent will
3752               recognize and take as a command to halt the event loop.
3753    -------------------------------------------------------------------------- */
3755   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3757 #ifdef NS_IMPL_GNUSTEP
3758   // GNUstep needs postEvent to happen on the main thread.
3759   if (! [[NSThread currentThread] isMainThread])
3760     {
3761       EmacsApp *app = (EmacsApp *)NSApp;
3762       app->nextappdefined = value;
3763       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3764                             withObject:nil
3765                          waitUntilDone:YES];
3766       return;
3767     }
3768 #endif
3770   /* Only post this event if we haven't already posted one.  This will end
3771        the [NXApp run] main loop after having processed all events queued at
3772        this moment.  */
3774 #ifdef NS_IMPL_COCOA
3775   if (! send_appdefined)
3776     {
3777       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3778          in certain situations (rapid incoming events).
3779          So check if we have one, if not add one.  */
3780       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3781                                           untilDate:[NSDate distantPast]
3782                                              inMode:NSDefaultRunLoopMode
3783                                             dequeue:NO];
3784       if (! appev) send_appdefined = YES;
3785     }
3786 #endif
3788   if (send_appdefined)
3789     {
3790       NSEvent *nxev;
3792       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3793       send_appdefined = NO;
3795       /* Don't need wakeup timer any more */
3796       if (timed_entry)
3797         {
3798           [timed_entry invalidate];
3799           [timed_entry release];
3800           timed_entry = nil;
3801         }
3803       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3804                                 location: NSMakePoint (0, 0)
3805                            modifierFlags: 0
3806                                timestamp: 0
3807                             windowNumber: [[NSApp mainWindow] windowNumber]
3808                                  context: [NSApp context]
3809                                  subtype: 0
3810                                    data1: value
3811                                    data2: 0];
3813       /* Post an application defined event on the event queue.  When this is
3814          received the [NXApp run] will return, thus having processed all
3815          events which are currently queued.  */
3816       [NSApp postEvent: nxev atStart: NO];
3817     }
3820 #ifdef HAVE_NATIVE_FS
3821 static void
3822 check_native_fs ()
3824   Lisp_Object frame, tail;
3826   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3827     return;
3829   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3831   FOR_EACH_FRAME (tail, frame)
3832     {
3833       struct frame *f = XFRAME (frame);
3834       if (FRAME_NS_P (f))
3835         {
3836           EmacsView *view = FRAME_NS_VIEW (f);
3837           [view updateCollectionBehavior];
3838         }
3839     }
3841 #endif
3843 /* GNUstep does not have cancelTracking.  */
3844 #ifdef NS_IMPL_COCOA
3845 /* Check if menu open should be canceled or continued as normal.  */
3846 void
3847 ns_check_menu_open (NSMenu *menu)
3849   /* Click in menu bar? */
3850   NSArray *a = [[NSApp mainMenu] itemArray];
3851   int i;
3852   BOOL found = NO;
3854   if (menu == nil) // Menu tracking ended.
3855     {
3856       if (menu_will_open_state == MENU_OPENING)
3857         menu_will_open_state = MENU_NONE;
3858       return;
3859     }
3861   for (i = 0; ! found && i < [a count]; i++)
3862     found = menu == [[a objectAtIndex:i] submenu];
3863   if (found)
3864     {
3865       if (menu_will_open_state == MENU_NONE && emacs_event)
3866         {
3867           NSEvent *theEvent = [NSApp currentEvent];
3868           struct frame *emacsframe = SELECTED_FRAME ();
3870           [menu cancelTracking];
3871           menu_will_open_state = MENU_PENDING;
3872           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3873           EV_TRAILER (theEvent);
3875           CGEventRef ourEvent = CGEventCreate (NULL);
3876           menu_mouse_point = CGEventGetLocation (ourEvent);
3877           CFRelease (ourEvent);
3878         }
3879       else if (menu_will_open_state == MENU_OPENING)
3880         {
3881           menu_will_open_state = MENU_NONE;
3882         }
3883     }
3886 /* Redo saved menu click if state is MENU_PENDING.  */
3887 void
3888 ns_check_pending_open_menu ()
3890   if (menu_will_open_state == MENU_PENDING)
3891     {
3892       CGEventSourceRef source
3893         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3895       CGEventRef event = CGEventCreateMouseEvent (source,
3896                                                   kCGEventLeftMouseDown,
3897                                                   menu_mouse_point,
3898                                                   kCGMouseButtonLeft);
3899       CGEventSetType (event, kCGEventLeftMouseDown);
3900       CGEventPost (kCGHIDEventTap, event);
3901       CFRelease (event);
3902       CFRelease (source);
3904       menu_will_open_state = MENU_OPENING;
3905     }
3907 #endif /* NS_IMPL_COCOA */
3909 static void
3910 unwind_apploopnr (Lisp_Object not_used)
3912   --apploopnr;
3913   n_emacs_events_pending = 0;
3914   ns_finish_events ();
3915   q_event_ptr = NULL;
3918 static int
3919 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3920 /* --------------------------------------------------------------------------
3921      External (hook): Post an event to ourself and keep reading events until
3922      we read it back again.  In effect process all events which were waiting.
3923      From 21+ we have to manage the event buffer ourselves.
3924    -------------------------------------------------------------------------- */
3926   struct input_event ev;
3927   int nevents;
3929   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
3931 #ifdef HAVE_NATIVE_FS
3932   check_native_fs ();
3933 #endif
3935   if ([NSApp modalWindow] != nil)
3936     return -1;
3938   if (hold_event_q.nr > 0)
3939     {
3940       int i;
3941       for (i = 0; i < hold_event_q.nr; ++i)
3942         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3943       hold_event_q.nr = 0;
3944       return i;
3945     }
3947   block_input ();
3948   n_emacs_events_pending = 0;
3949   ns_init_events (&ev);
3950   q_event_ptr = hold_quit;
3952   /* we manage autorelease pools by allocate/reallocate each time around
3953      the loop; strict nesting is occasionally violated but seems not to
3954      matter.. earlier methods using full nesting caused major memory leaks */
3955   [outerpool release];
3956   outerpool = [[NSAutoreleasePool alloc] init];
3958   /* If have pending open-file requests, attend to the next one of those. */
3959   if (ns_pending_files && [ns_pending_files count] != 0
3960       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3961     {
3962       [ns_pending_files removeObjectAtIndex: 0];
3963     }
3964   /* Deal with pending service requests. */
3965   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3966     && [(EmacsApp *)
3967          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3968                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3969     {
3970       [ns_pending_service_names removeObjectAtIndex: 0];
3971       [ns_pending_service_args removeObjectAtIndex: 0];
3972     }
3973   else
3974     {
3975       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3976       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3977          to ourself, otherwise [NXApp run] will never exit.  */
3978       send_appdefined = YES;
3979       ns_send_appdefined (-1);
3981       if (++apploopnr != 1)
3982         {
3983           emacs_abort ();
3984         }
3985       record_unwind_protect (unwind_apploopnr, Qt);
3986       [NSApp run];
3987       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
3988     }
3990   nevents = n_emacs_events_pending;
3991   n_emacs_events_pending = 0;
3992   ns_finish_events ();
3993   q_event_ptr = NULL;
3994   unblock_input ();
3996   return nevents;
4001 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4002            fd_set *exceptfds, struct timespec const *timeout,
4003            sigset_t const *sigmask)
4004 /* --------------------------------------------------------------------------
4005      Replacement for select, checking for events
4006    -------------------------------------------------------------------------- */
4008   int result;
4009   int t, k, nr = 0;
4010   struct input_event event;
4011   char c;
4013   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4015 #ifdef HAVE_NATIVE_FS
4016   check_native_fs ();
4017 #endif
4019   if (hold_event_q.nr > 0)
4020     {
4021       /* We already have events pending. */
4022       raise (SIGIO);
4023       errno = EINTR;
4024       return -1;
4025     }
4027   for (k = 0; k < nfds+1; k++)
4028     {
4029       if (readfds && FD_ISSET(k, readfds)) ++nr;
4030       if (writefds && FD_ISSET(k, writefds)) ++nr;
4031     }
4033   if (NSApp == nil
4034       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4035     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4037   [outerpool release];
4038   outerpool = [[NSAutoreleasePool alloc] init];
4041   send_appdefined = YES;
4042   if (nr > 0)
4043     {
4044       pthread_mutex_lock (&select_mutex);
4045       select_nfds = nfds;
4046       select_valid = 0;
4047       if (readfds)
4048         {
4049           select_readfds = *readfds;
4050           select_valid += SELECT_HAVE_READ;
4051         }
4052       if (writefds)
4053         {
4054           select_writefds = *writefds;
4055           select_valid += SELECT_HAVE_WRITE;
4056         }
4058       if (timeout)
4059         {
4060           select_timeout = *timeout;
4061           select_valid += SELECT_HAVE_TMO;
4062         }
4064       pthread_mutex_unlock (&select_mutex);
4066       /* Inform fd_handler that select should be called */
4067       c = 'g';
4068       emacs_write_sig (selfds[1], &c, 1);
4069     }
4070   else if (nr == 0 && timeout)
4071     {
4072       /* No file descriptor, just a timeout, no need to wake fd_handler  */
4073       double time = timespectod (*timeout);
4074       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4075                                                       target: NSApp
4076                                                     selector:
4077                                   @selector (timeout_handler:)
4078                                                     userInfo: 0
4079                                                      repeats: NO]
4080                       retain];
4081     }
4082   else /* No timeout and no file descriptors, can this happen?  */
4083     {
4084       /* Send appdefined so we exit from the loop */
4085       ns_send_appdefined (-1);
4086     }
4088   block_input ();
4089   ns_init_events (&event);
4090   if (++apploopnr != 1)
4091     {
4092       emacs_abort ();
4093     }
4095   {
4096     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4097     record_unwind_protect (unwind_apploopnr, Qt);
4098     [NSApp run];
4099     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4100   }
4102   ns_finish_events ();
4103   if (nr > 0 && readfds)
4104     {
4105       c = 's';
4106       emacs_write_sig (selfds[1], &c, 1);
4107     }
4108   unblock_input ();
4110   t = last_appdefined_event_data;
4112   if (t != NO_APPDEFINED_DATA)
4113     {
4114       last_appdefined_event_data = NO_APPDEFINED_DATA;
4116       if (t == -2)
4117         {
4118           /* The NX_APPDEFINED event we received was a timeout. */
4119           result = 0;
4120         }
4121       else if (t == -1)
4122         {
4123           /* The NX_APPDEFINED event we received was the result of
4124              at least one real input event arriving.  */
4125           errno = EINTR;
4126           result = -1;
4127         }
4128       else
4129         {
4130           /* Received back from select () in fd_handler; copy the results */
4131           pthread_mutex_lock (&select_mutex);
4132           if (readfds) *readfds = select_readfds;
4133           if (writefds) *writefds = select_writefds;
4134           pthread_mutex_unlock (&select_mutex);
4135           result = t;
4136         }
4137     }
4138   else
4139     {
4140       errno = EINTR;
4141       result = -1;
4142     }
4144   return result;
4149 /* ==========================================================================
4151     Scrollbar handling
4153    ========================================================================== */
4156 static void
4157 ns_set_vertical_scroll_bar (struct window *window,
4158                            int portion, int whole, int position)
4159 /* --------------------------------------------------------------------------
4160       External (hook): Update or add scrollbar
4161    -------------------------------------------------------------------------- */
4163   Lisp_Object win;
4164   NSRect r, v;
4165   struct frame *f = XFRAME (WINDOW_FRAME (window));
4166   EmacsView *view = FRAME_NS_VIEW (f);
4167   EmacsScroller *bar;
4168   int window_y, window_height;
4169   int top, left, height, width;
4170   BOOL update_p = YES;
4172   /* optimization; display engine sends WAY too many of these.. */
4173   if (!NILP (window->vertical_scroll_bar))
4174     {
4175       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4176       if ([bar checkSamePosition: position portion: portion whole: whole])
4177         {
4178           if (view->scrollbarsNeedingUpdate == 0)
4179             {
4180               if (!windows_or_buffers_changed)
4181                   return;
4182             }
4183           else
4184             view->scrollbarsNeedingUpdate--;
4185           update_p = NO;
4186         }
4187     }
4189   NSTRACE ("ns_set_vertical_scroll_bar");
4191   /* Get dimensions.  */
4192   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4193   top = window_y;
4194   height = window_height;
4195   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4196   left = WINDOW_SCROLL_BAR_AREA_X (window);
4198   r = NSMakeRect (left, top, width, height);
4199   /* the parent view is flipped, so we need to flip y value */
4200   v = [view frame];
4201   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4203   XSETWINDOW (win, window);
4204   block_input ();
4206   /* we want at least 5 lines to display a scrollbar */
4207   if (WINDOW_TOTAL_LINES (window) < 5)
4208     {
4209       if (!NILP (window->vertical_scroll_bar))
4210         {
4211           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4212           [bar removeFromSuperview];
4213           wset_vertical_scroll_bar (window, Qnil);
4214           [bar release];
4215         }
4216       ns_clear_frame_area (f, left, top, width, height);
4217       unblock_input ();
4218       return;
4219     }
4221   if (NILP (window->vertical_scroll_bar))
4222     {
4223       if (width > 0 && height > 0)
4224         ns_clear_frame_area (f, left, top, width, height);
4226       bar = [[EmacsScroller alloc] initFrame: r window: win];
4227       wset_vertical_scroll_bar (window, make_save_ptr (bar));
4228       update_p = YES;
4229     }
4230   else
4231     {
4232       NSRect oldRect;
4233       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4234       oldRect = [bar frame];
4235       r.size.width = oldRect.size.width;
4236       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4237         {
4238           if (oldRect.origin.x != r.origin.x)
4239               ns_clear_frame_area (f, left, top, width, height);
4240           [bar setFrame: r];
4241         }
4242     }
4244   if (update_p)
4245     [bar setPosition: position portion: portion whole: whole];
4246   unblock_input ();
4250 static void
4251 ns_set_horizontal_scroll_bar (struct window *window,
4252                               int portion, int whole, int position)
4253 /* --------------------------------------------------------------------------
4254       External (hook): Update or add scrollbar
4255    -------------------------------------------------------------------------- */
4257   Lisp_Object win;
4258   NSRect r, v;
4259   struct frame *f = XFRAME (WINDOW_FRAME (window));
4260   EmacsView *view = FRAME_NS_VIEW (f);
4261   EmacsScroller *bar;
4262   int top, height, left, width;
4263   int window_x, window_width;
4264   BOOL update_p = YES;
4266   /* optimization; display engine sends WAY too many of these.. */
4267   if (!NILP (window->horizontal_scroll_bar))
4268     {
4269       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4270       if ([bar checkSamePosition: position portion: portion whole: whole])
4271         {
4272           if (view->scrollbarsNeedingUpdate == 0)
4273             {
4274               if (!windows_or_buffers_changed)
4275                   return;
4276             }
4277           else
4278             view->scrollbarsNeedingUpdate--;
4279           update_p = NO;
4280         }
4281     }
4283   NSTRACE ("ns_set_horizontal_scroll_bar");
4285   /* Get dimensions.  */
4286   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4287   left = window_x;
4288   width = window_width;
4289   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4290   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4292   r = NSMakeRect (left, top, width, height);
4293   /* the parent view is flipped, so we need to flip y value */
4294   v = [view frame];
4295   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4296   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4298   XSETWINDOW (win, window);
4299   block_input ();
4301   if (WINDOW_TOTAL_COLS (window) < 5)
4302     {
4303       if (!NILP (window->horizontal_scroll_bar))
4304         {
4305           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4306           [bar removeFromSuperview];
4307           wset_horizontal_scroll_bar (window, Qnil);
4308         }
4309       ns_clear_frame_area (f, left, top, width, height);
4310       unblock_input ();
4311       return;
4312     }
4314   if (NILP (window->horizontal_scroll_bar))
4315     {
4316       if (width > 0 && height > 0)
4317         ns_clear_frame_area (f, left, top, width, height);
4319       bar = [[EmacsScroller alloc] initFrame: r window: win];
4320       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4321       update_p = YES;
4322     }
4323   else
4324     {
4325       NSRect oldRect;
4326       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4327       oldRect = [bar frame];
4328       r.size.width = oldRect.size.width;
4329       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4330         {
4331           if (oldRect.origin.x != r.origin.x)
4332               ns_clear_frame_area (f, left, top, width, height);
4333           [bar setFrame: r];
4334           update_p = YES;
4335         }
4336     }
4338   if (update_p)
4339     [bar setPosition: position portion: portion whole: whole];
4340   unblock_input ();
4344 static void
4345 ns_condemn_scroll_bars (struct frame *f)
4346 /* --------------------------------------------------------------------------
4347      External (hook): arrange for all frame's scrollbars to be removed
4348      at next call to judge_scroll_bars, except for those redeemed.
4349    -------------------------------------------------------------------------- */
4351   int i;
4352   id view;
4353   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4355   NSTRACE ("ns_condemn_scroll_bars");
4357   for (i =[subviews count]-1; i >= 0; i--)
4358     {
4359       view = [subviews objectAtIndex: i];
4360       if ([view isKindOfClass: [EmacsScroller class]])
4361         [view condemn];
4362     }
4366 static void
4367 ns_redeem_scroll_bar (struct window *window)
4368 /* --------------------------------------------------------------------------
4369      External (hook): arrange to spare this window's scrollbar
4370      at next call to judge_scroll_bars.
4371    -------------------------------------------------------------------------- */
4373   id bar;
4374   NSTRACE ("ns_redeem_scroll_bar");
4375   if (!NILP (window->vertical_scroll_bar))
4376     {
4377       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4378       [bar reprieve];
4379     }
4381   if (!NILP (window->horizontal_scroll_bar))
4382     {
4383       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4384       [bar reprieve];
4385     }
4389 static void
4390 ns_judge_scroll_bars (struct frame *f)
4391 /* --------------------------------------------------------------------------
4392      External (hook): destroy all scrollbars on frame that weren't
4393      redeemed after call to condemn_scroll_bars.
4394    -------------------------------------------------------------------------- */
4396   int i;
4397   id view;
4398   EmacsView *eview = FRAME_NS_VIEW (f);
4399   NSArray *subviews = [[eview superview] subviews];
4400   BOOL removed = NO;
4402   NSTRACE ("ns_judge_scroll_bars");
4403   for (i = [subviews count]-1; i >= 0; --i)
4404     {
4405       view = [subviews objectAtIndex: i];
4406       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4407       if ([view judge])
4408         removed = YES;
4409     }
4411   if (removed)
4412     [eview updateFrameSize: NO];
4415 /* ==========================================================================
4417     Initialization
4419    ========================================================================== */
4422 x_display_pixel_height (struct ns_display_info *dpyinfo)
4424   NSArray *screens = [NSScreen screens];
4425   NSEnumerator *enumerator = [screens objectEnumerator];
4426   NSScreen *screen;
4427   NSRect frame;
4429   frame = NSZeroRect;
4430   while ((screen = [enumerator nextObject]) != nil)
4431     frame = NSUnionRect (frame, [screen frame]);
4433   return NSHeight (frame);
4437 x_display_pixel_width (struct ns_display_info *dpyinfo)
4439   NSArray *screens = [NSScreen screens];
4440   NSEnumerator *enumerator = [screens objectEnumerator];
4441   NSScreen *screen;
4442   NSRect frame;
4444   frame = NSZeroRect;
4445   while ((screen = [enumerator nextObject]) != nil)
4446     frame = NSUnionRect (frame, [screen frame]);
4448   return NSWidth (frame);
4452 static Lisp_Object ns_string_to_lispmod (const char *s)
4453 /* --------------------------------------------------------------------------
4454      Convert modifier name to lisp symbol
4455    -------------------------------------------------------------------------- */
4457   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4458     return Qmeta;
4459   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4460     return Qsuper;
4461   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4462     return Qcontrol;
4463   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4464     return Qalt;
4465   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4466     return Qhyper;
4467   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4468     return Qnone;
4469   else
4470     return Qnil;
4474 static void
4475 ns_default (const char *parameter, Lisp_Object *result,
4476            Lisp_Object yesval, Lisp_Object noval,
4477            BOOL is_float, BOOL is_modstring)
4478 /* --------------------------------------------------------------------------
4479       Check a parameter value in user's preferences
4480    -------------------------------------------------------------------------- */
4482   const char *value = ns_get_defaults_value (parameter);
4484   if (value)
4485     {
4486       double f;
4487       char *pos;
4488       if (c_strcasecmp (value, "YES") == 0)
4489         *result = yesval;
4490       else if (c_strcasecmp (value, "NO") == 0)
4491         *result = noval;
4492       else if (is_float && (f = strtod (value, &pos), pos != value))
4493         *result = make_float (f);
4494       else if (is_modstring && value)
4495         *result = ns_string_to_lispmod (value);
4496       else fprintf (stderr,
4497                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4498     }
4502 static void
4503 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4504 /* --------------------------------------------------------------------------
4505       Initialize global info and storage for display.
4506    -------------------------------------------------------------------------- */
4508     NSScreen *screen = [NSScreen mainScreen];
4509     NSWindowDepth depth = [screen depth];
4511     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4512     dpyinfo->resy = 72.27;
4513     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4514                                                   NSColorSpaceFromDepth (depth)]
4515                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4516                                                  NSColorSpaceFromDepth (depth)];
4517     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4518     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4519     dpyinfo->color_table->colors = NULL;
4520     dpyinfo->root_window = 42; /* a placeholder.. */
4521     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4522     dpyinfo->n_fonts = 0;
4523     dpyinfo->smallest_font_height = 1;
4524     dpyinfo->smallest_char_width = 1;
4526     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4530 /* This and next define (many of the) public functions in this file. */
4531 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4532          with using despite presence in the "system dependent" redisplay
4533          interface.  In addition, many of the ns_ methods have code that is
4534          shared with all terms, indicating need for further refactoring. */
4535 extern frame_parm_handler ns_frame_parm_handlers[];
4536 static struct redisplay_interface ns_redisplay_interface =
4538   ns_frame_parm_handlers,
4539   x_produce_glyphs,
4540   x_write_glyphs,
4541   x_insert_glyphs,
4542   x_clear_end_of_line,
4543   ns_scroll_run,
4544   ns_after_update_window_line,
4545   ns_update_window_begin,
4546   ns_update_window_end,
4547   0, /* flush_display */
4548   x_clear_window_mouse_face,
4549   x_get_glyph_overhangs,
4550   x_fix_overlapping_area,
4551   ns_draw_fringe_bitmap,
4552   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4553   0, /* destroy_fringe_bitmap */
4554   ns_compute_glyph_string_overhangs,
4555   ns_draw_glyph_string,
4556   ns_define_frame_cursor,
4557   ns_clear_frame_area,
4558   ns_draw_window_cursor,
4559   ns_draw_vertical_window_border,
4560   ns_draw_window_divider,
4561   ns_shift_glyphs_for_insert,
4562   ns_show_hourglass,
4563   ns_hide_hourglass
4567 static void
4568 ns_delete_display (struct ns_display_info *dpyinfo)
4570   /* TODO... */
4574 /* This function is called when the last frame on a display is deleted. */
4575 static void
4576 ns_delete_terminal (struct terminal *terminal)
4578   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4580   NSTRACE ("ns_delete_terminal");
4582   /* Protect against recursive calls.  delete_frame in
4583      delete_terminal calls us back when it deletes our last frame.  */
4584   if (!terminal->name)
4585     return;
4587   block_input ();
4589   x_destroy_all_bitmaps (dpyinfo);
4590   ns_delete_display (dpyinfo);
4591   unblock_input ();
4595 static struct terminal *
4596 ns_create_terminal (struct ns_display_info *dpyinfo)
4597 /* --------------------------------------------------------------------------
4598       Set up use of NS before we make the first connection.
4599    -------------------------------------------------------------------------- */
4601   struct terminal *terminal;
4603   NSTRACE ("ns_create_terminal");
4605   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4607   terminal->display_info.ns = dpyinfo;
4608   dpyinfo->terminal = terminal;
4610   terminal->clear_frame_hook = ns_clear_frame;
4611   terminal->ring_bell_hook = ns_ring_bell;
4612   terminal->update_begin_hook = ns_update_begin;
4613   terminal->update_end_hook = ns_update_end;
4614   terminal->read_socket_hook = ns_read_socket;
4615   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4616   terminal->mouse_position_hook = ns_mouse_position;
4617   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4618   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4619   terminal->fullscreen_hook = ns_fullscreen_hook;
4620   terminal->menu_show_hook = ns_menu_show;
4621   terminal->popup_dialog_hook = ns_popup_dialog;
4622   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4623   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4624   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4625   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4626   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4627   terminal->delete_frame_hook = x_destroy_window;
4628   terminal->delete_terminal_hook = ns_delete_terminal;
4629   /* Other hooks are NULL by default.  */
4631   return terminal;
4635 struct ns_display_info *
4636 ns_term_init (Lisp_Object display_name)
4637 /* --------------------------------------------------------------------------
4638      Start the Application and get things rolling.
4639    -------------------------------------------------------------------------- */
4641   struct terminal *terminal;
4642   struct ns_display_info *dpyinfo;
4643   static int ns_initialized = 0;
4644   Lisp_Object tmp;
4646   if (ns_initialized) return x_display_list;
4647   ns_initialized = 1;
4649   block_input ();
4651   NSTRACE ("ns_term_init");
4653   [outerpool release];
4654   outerpool = [[NSAutoreleasePool alloc] init];
4656   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4657   /*GSDebugAllocationActive (YES); */
4658   block_input ();
4660   baud_rate = 38400;
4661   Fset_input_interrupt_mode (Qnil);
4663   if (selfds[0] == -1)
4664     {
4665       if (emacs_pipe (selfds) != 0)
4666         {
4667           fprintf (stderr, "Failed to create pipe: %s\n",
4668                    emacs_strerror (errno));
4669           emacs_abort ();
4670         }
4672       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4673       FD_ZERO (&select_readfds);
4674       FD_ZERO (&select_writefds);
4675       pthread_mutex_init (&select_mutex, NULL);
4676     }
4678   ns_pending_files = [[NSMutableArray alloc] init];
4679   ns_pending_service_names = [[NSMutableArray alloc] init];
4680   ns_pending_service_args = [[NSMutableArray alloc] init];
4682 /* Start app and create the main menu, window, view.
4683      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4684      The view will then ask the NSApp to stop and return to Emacs. */
4685   [EmacsApp sharedApplication];
4686   if (NSApp == nil)
4687     return NULL;
4688   [NSApp setDelegate: NSApp];
4690   /* Start the select thread.  */
4691   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4692                            toTarget:NSApp
4693                          withObject:nil];
4695   /* debugging: log all notifications */
4696   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4697                                          selector: @selector (logNotification:)
4698                                              name: nil object: nil]; */
4700   dpyinfo = xzalloc (sizeof *dpyinfo);
4702   ns_initialize_display_info (dpyinfo);
4703   terminal = ns_create_terminal (dpyinfo);
4705   terminal->kboard = allocate_kboard (Qns);
4706   /* Don't let the initial kboard remain current longer than necessary.
4707      That would cause problems if a file loaded on startup tries to
4708      prompt in the mini-buffer.  */
4709   if (current_kboard == initial_kboard)
4710     current_kboard = terminal->kboard;
4711   terminal->kboard->reference_count++;
4713   dpyinfo->next = x_display_list;
4714   x_display_list = dpyinfo;
4716   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4718   terminal->name = xlispstrdup (display_name);
4720   unblock_input ();
4722   if (!inhibit_x_resources)
4723     {
4724       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4725                  Qt, Qnil, NO, NO);
4726       tmp = Qnil;
4727       /* this is a standard variable */
4728       ns_default ("AppleAntiAliasingThreshold", &tmp,
4729                  make_float (10.0), make_float (6.0), YES, NO);
4730       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4731     }
4733   NSTRACE_MSG ("Colors");
4735   {
4736     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4738     if ( cl == nil )
4739       {
4740         Lisp_Object color_file, color_map, color;
4741         unsigned long c;
4742         char *name;
4744         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4745                          Fsymbol_value (intern ("data-directory")));
4747         color_map = Fx_load_color_file (color_file);
4748         if (NILP (color_map))
4749           fatal ("Could not read %s.\n", SDATA (color_file));
4751         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4752         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4753           {
4754             color = XCAR (color_map);
4755             name = SSDATA (XCAR (color));
4756             c = XINT (XCDR (color));
4757             [cl setColor:
4758                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4759                                       green: GREEN_FROM_ULONG (c) / 255.0
4760                                        blue: BLUE_FROM_ULONG (c) / 255.0
4761                                       alpha: 1.0]
4762                   forKey: [NSString stringWithUTF8String: name]];
4763           }
4764         [cl writeToFile: nil];
4765       }
4766   }
4768   NSTRACE_MSG ("Versions");
4770   {
4771 #ifdef NS_IMPL_GNUSTEP
4772     Vwindow_system_version = build_string (gnustep_base_version);
4773 #else
4774     /*PSnextrelease (128, c); */
4775     char c[DBL_BUFSIZE_BOUND];
4776     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4777     Vwindow_system_version = make_unibyte_string (c, len);
4778 #endif
4779   }
4781   delete_keyboard_wait_descriptor (0);
4783   ns_app_name = [[NSProcessInfo processInfo] processName];
4785   /* Set up OS X app menu */
4787   NSTRACE_MSG ("Menu init");
4789 #ifdef NS_IMPL_COCOA
4790   {
4791     NSMenu *appMenu;
4792     NSMenuItem *item;
4793     /* set up the application menu */
4794     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4795     [svcsMenu setAutoenablesItems: NO];
4796     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4797     [appMenu setAutoenablesItems: NO];
4798     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4799     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4801     [appMenu insertItemWithTitle: @"About Emacs"
4802                           action: @selector (orderFrontStandardAboutPanel:)
4803                    keyEquivalent: @""
4804                          atIndex: 0];
4805     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4806     [appMenu insertItemWithTitle: @"Preferences..."
4807                           action: @selector (showPreferencesWindow:)
4808                    keyEquivalent: @","
4809                          atIndex: 2];
4810     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4811     item = [appMenu insertItemWithTitle: @"Services"
4812                                  action: @selector (menuDown:)
4813                           keyEquivalent: @""
4814                                 atIndex: 4];
4815     [appMenu setSubmenu: svcsMenu forItem: item];
4816     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4817     [appMenu insertItemWithTitle: @"Hide Emacs"
4818                           action: @selector (hide:)
4819                    keyEquivalent: @"h"
4820                          atIndex: 6];
4821     item =  [appMenu insertItemWithTitle: @"Hide Others"
4822                           action: @selector (hideOtherApplications:)
4823                    keyEquivalent: @"h"
4824                          atIndex: 7];
4825     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4826     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4827     [appMenu insertItemWithTitle: @"Quit Emacs"
4828                           action: @selector (terminate:)
4829                    keyEquivalent: @"q"
4830                          atIndex: 9];
4832     item = [mainMenu insertItemWithTitle: ns_app_name
4833                                   action: @selector (menuDown:)
4834                            keyEquivalent: @""
4835                                  atIndex: 0];
4836     [mainMenu setSubmenu: appMenu forItem: item];
4837     [dockMenu insertItemWithTitle: @"New Frame"
4838                            action: @selector (newFrame:)
4839                     keyEquivalent: @""
4840                           atIndex: 0];
4842     [NSApp setMainMenu: mainMenu];
4843     [NSApp setAppleMenu: appMenu];
4844     [NSApp setServicesMenu: svcsMenu];
4845     /* Needed at least on Cocoa, to get dock menu to show windows */
4846     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4848     [[NSNotificationCenter defaultCenter]
4849       addObserver: mainMenu
4850          selector: @selector (trackingNotification:)
4851              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4852     [[NSNotificationCenter defaultCenter]
4853       addObserver: mainMenu
4854          selector: @selector (trackingNotification:)
4855              name: NSMenuDidEndTrackingNotification object: mainMenu];
4856   }
4857 #endif /* MAC OS X menu setup */
4859   /* Register our external input/output types, used for determining
4860      applicable services and also drag/drop eligibility. */
4862   NSTRACE_MSG ("Input/output types");
4864   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4865   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4866                       retain];
4867   ns_drag_types = [[NSArray arrayWithObjects:
4868                             NSStringPboardType,
4869                             NSTabularTextPboardType,
4870                             NSFilenamesPboardType,
4871                             NSURLPboardType, nil] retain];
4873   /* If fullscreen is in init/default-frame-alist, focus isn't set
4874      right for fullscreen windows, so set this.  */
4875   [NSApp activateIgnoringOtherApps:YES];
4877   NSTRACE_MSG ("Call NSApp run");
4879   [NSApp run];
4880   ns_do_open_file = YES;
4882 #ifdef NS_IMPL_GNUSTEP
4883   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4884      We must re-catch it so subprocess works.  */
4885   catch_child_signal ();
4886 #endif
4888   NSTRACE_MSG ("ns_term_init done");
4890   unblock_input ();
4892   return dpyinfo;
4896 void
4897 ns_term_shutdown (int sig)
4899   [[NSUserDefaults standardUserDefaults] synchronize];
4901   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4902   if (STRINGP (Vauto_save_list_file_name))
4903     unlink (SSDATA (Vauto_save_list_file_name));
4905   if (sig == 0 || sig == SIGTERM)
4906     {
4907       [NSApp terminate: NSApp];
4908     }
4909   else // force a stack trace to happen
4910     {
4911       emacs_abort ();
4912     }
4916 /* ==========================================================================
4918     EmacsApp implementation
4920    ========================================================================== */
4923 @implementation EmacsApp
4925 - (id)init
4927   NSTRACE ("[EmacsApp init]");
4929   if ((self = [super init]))
4930     {
4931 #ifdef NS_IMPL_COCOA
4932       self->isFirst = YES;
4933 #endif
4934 #ifdef NS_IMPL_GNUSTEP
4935       self->applicationDidFinishLaunchingCalled = NO;
4936 #endif
4937     }
4939   return self;
4942 #ifdef NS_IMPL_COCOA
4943 - (void)run
4945   NSTRACE ("[EmacsApp run]");
4947 #ifndef NSAppKitVersionNumber10_9
4948 #define NSAppKitVersionNumber10_9 1265
4949 #endif
4951     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4952       {
4953         [super run];
4954         return;
4955       }
4957   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4959   if (isFirst) [self finishLaunching];
4960   isFirst = NO;
4962   shouldKeepRunning = YES;
4963   do
4964     {
4965       [pool release];
4966       pool = [[NSAutoreleasePool alloc] init];
4968       NSEvent *event =
4969         [self nextEventMatchingMask:NSAnyEventMask
4970                           untilDate:[NSDate distantFuture]
4971                              inMode:NSDefaultRunLoopMode
4972                             dequeue:YES];
4974       [self sendEvent:event];
4975       [self updateWindows];
4976     } while (shouldKeepRunning);
4978   [pool release];
4981 - (void)stop: (id)sender
4983   NSTRACE ("[EmacsApp stop:]");
4985     shouldKeepRunning = NO;
4986     // Stop possible dialog also.  Noop if no dialog present.
4987     // The file dialog still leaks 7k - 10k on 10.9 though.
4988     [super stop:sender];
4990 #endif /* NS_IMPL_COCOA */
4992 - (void)logNotification: (NSNotification *)notification
4994   NSTRACE ("[EmacsApp logNotification:]");
4996   const char *name = [[notification name] UTF8String];
4997   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4998       && !strstr (name, "WindowNumber"))
4999     NSLog (@"notification: '%@'", [notification name]);
5003 - (void)sendEvent: (NSEvent *)theEvent
5004 /* --------------------------------------------------------------------------
5005      Called when NSApp is running for each event received.  Used to stop
5006      the loop when we choose, since there's no way to just run one iteration.
5007    -------------------------------------------------------------------------- */
5009   int type = [theEvent type];
5010   NSWindow *window = [theEvent window];
5012   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5013   NSTRACE_MSG ("Type: %d", type);
5015 #ifdef NS_IMPL_GNUSTEP
5016   // Keyboard events aren't propagated to file dialogs for some reason.
5017   if ([NSApp modalWindow] != nil &&
5018       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5019     {
5020       [[NSApp modalWindow] sendEvent: theEvent];
5021       return;
5022     }
5023 #endif
5025   if (represented_filename != nil && represented_frame)
5026     {
5027       NSString *fstr = represented_filename;
5028       NSView *view = FRAME_NS_VIEW (represented_frame);
5029 #ifdef NS_IMPL_COCOA
5030       /* work around a bug observed on 10.3 and later where
5031          setTitleWithRepresentedFilename does not clear out previous state
5032          if given filename does not exist */
5033       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5034         [[view window] setRepresentedFilename: @""];
5035 #endif
5036       [[view window] setRepresentedFilename: fstr];
5037       [represented_filename release];
5038       represented_filename = nil;
5039       represented_frame = NULL;
5040     }
5042   if (type == NSApplicationDefined)
5043     {
5044       switch ([theEvent data2])
5045         {
5046 #ifdef NS_IMPL_COCOA
5047         case NSAPP_DATA2_RUNASSCRIPT:
5048           ns_run_ascript ();
5049           [self stop: self];
5050           return;
5051 #endif
5052         case NSAPP_DATA2_RUNFILEDIALOG:
5053           ns_run_file_dialog ();
5054           [self stop: self];
5055           return;
5056         }
5057     }
5059   if (type == NSCursorUpdate && window == nil)
5060     {
5061       fprintf (stderr, "Dropping external cursor update event.\n");
5062       return;
5063     }
5065   if (type == NSApplicationDefined)
5066     {
5067       /* Events posted by ns_send_appdefined interrupt the run loop here.
5068          But, if a modal window is up, an appdefined can still come through,
5069          (e.g., from a makeKeyWindow event) but stopping self also stops the
5070          modal loop. Just defer it until later. */
5071       if ([NSApp modalWindow] == nil)
5072         {
5073           last_appdefined_event_data = [theEvent data1];
5074           [self stop: self];
5075         }
5076       else
5077         {
5078           send_appdefined = YES;
5079         }
5080     }
5083 #ifdef NS_IMPL_COCOA
5084   /* If no dialog and none of our frames have focus and it is a move, skip it.
5085      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5086      such as Wifi, sound, date or similar.
5087      This prevents "spooky" highlighting in the frame under the menu.  */
5088   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5089     {
5090       struct ns_display_info *di;
5091       BOOL has_focus = NO;
5092       for (di = x_display_list; ! has_focus && di; di = di->next)
5093         has_focus = di->x_focus_frame != 0;
5094       if (! has_focus)
5095         return;
5096     }
5097 #endif
5099   NSTRACE_UNSILENCE();
5101   [super sendEvent: theEvent];
5105 - (void)showPreferencesWindow: (id)sender
5107   struct frame *emacsframe = SELECTED_FRAME ();
5108   NSEvent *theEvent = [NSApp currentEvent];
5110   if (!emacs_event)
5111     return;
5112   emacs_event->kind = NS_NONKEY_EVENT;
5113   emacs_event->code = KEY_NS_SHOW_PREFS;
5114   emacs_event->modifiers = 0;
5115   EV_TRAILER (theEvent);
5119 - (void)newFrame: (id)sender
5121   NSTRACE ("[EmacsApp newFrame:]");
5123   struct frame *emacsframe = SELECTED_FRAME ();
5124   NSEvent *theEvent = [NSApp currentEvent];
5126   if (!emacs_event)
5127     return;
5128   emacs_event->kind = NS_NONKEY_EVENT;
5129   emacs_event->code = KEY_NS_NEW_FRAME;
5130   emacs_event->modifiers = 0;
5131   EV_TRAILER (theEvent);
5135 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5136 - (BOOL) openFile: (NSString *)fileName
5138   NSTRACE ("[EmacsApp openFile:]");
5140   struct frame *emacsframe = SELECTED_FRAME ();
5141   NSEvent *theEvent = [NSApp currentEvent];
5143   if (!emacs_event)
5144     return NO;
5146   emacs_event->kind = NS_NONKEY_EVENT;
5147   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5148   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5149   ns_input_line = Qnil; /* can be start or cons start,end */
5150   emacs_event->modifiers =0;
5151   EV_TRAILER (theEvent);
5153   return YES;
5157 /* **************************************************************************
5159       EmacsApp delegate implementation
5161    ************************************************************************** */
5163 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5164 /* --------------------------------------------------------------------------
5165      When application is loaded, terminate event loop in ns_term_init
5166    -------------------------------------------------------------------------- */
5168   NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5170 #ifdef NS_IMPL_GNUSTEP
5171   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5172 #endif
5173   [NSApp setServicesProvider: NSApp];
5175   [self antialiasThresholdDidChange:nil];
5176 #ifdef NS_IMPL_COCOA
5177   [[NSNotificationCenter defaultCenter]
5178     addObserver:self
5179        selector:@selector(antialiasThresholdDidChange:)
5180            name:NSAntialiasThresholdChangedNotification
5181          object:nil];
5182 #endif
5184   ns_send_appdefined (-2);
5187 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5189 #ifdef NS_IMPL_COCOA
5190   macfont_update_antialias_threshold ();
5191 #endif
5195 /* Termination sequences:
5196     C-x C-c:
5197     Cmd-Q:
5198     MenuBar | File | Exit:
5199     Select Quit from App menubar:
5200         -terminate
5201         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5202         ns_term_shutdown()
5204     Select Quit from Dock menu:
5205     Logout attempt:
5206         -appShouldTerminate
5207           Cancel -> Nothing else
5208           Accept ->
5210           -terminate
5211           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5212           ns_term_shutdown()
5216 - (void) terminate: (id)sender
5218   NSTRACE ("[EmacsApp terminate:]");
5220   struct frame *emacsframe = SELECTED_FRAME ();
5222   if (!emacs_event)
5223     return;
5225   emacs_event->kind = NS_NONKEY_EVENT;
5226   emacs_event->code = KEY_NS_POWER_OFF;
5227   emacs_event->arg = Qt; /* mark as non-key event */
5228   EV_TRAILER ((id)nil);
5231 static bool
5232 runAlertPanel(NSString *title,
5233               NSString *msgFormat,
5234               NSString *defaultButton,
5235               NSString *alternateButton)
5237 #if !defined (NS_IMPL_COCOA) || \
5238   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5239   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5240     == NSAlertDefaultReturn;
5241 #else
5242   NSAlert *alert = [[NSAlert alloc] init];
5243   [alert setAlertStyle: NSCriticalAlertStyle];
5244   [alert setMessageText: msgFormat];
5245   [alert addButtonWithTitle: defaultButton];
5246   [alert addButtonWithTitle: alternateButton];
5247   NSInteger ret = [alert runModal];
5248   [alert release];
5249   return ret == NSAlertFirstButtonReturn;
5250 #endif
5254 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5256   NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5258   bool ret;
5260   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
5261     return NSTerminateNow;
5263     ret = runAlertPanel(ns_app_name,
5264                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
5265                         @"Save Buffers and Exit", @"Cancel");
5267     if (ret)
5268         return NSTerminateNow;
5269     else
5270         return NSTerminateCancel;
5271     return NSTerminateNow;  /* just in case */
5274 static int
5275 not_in_argv (NSString *arg)
5277   int k;
5278   const char *a = [arg UTF8String];
5279   for (k = 1; k < initial_argc; ++k)
5280     if (strcmp (a, initial_argv[k]) == 0) return 0;
5281   return 1;
5284 /*   Notification from the Workspace to open a file */
5285 - (BOOL)application: sender openFile: (NSString *)file
5287   if (ns_do_open_file || not_in_argv (file))
5288     [ns_pending_files addObject: file];
5289   return YES;
5293 /*   Open a file as a temporary file */
5294 - (BOOL)application: sender openTempFile: (NSString *)file
5296   if (ns_do_open_file || not_in_argv (file))
5297     [ns_pending_files addObject: file];
5298   return YES;
5302 /*   Notification from the Workspace to open a file noninteractively (?) */
5303 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5305   if (ns_do_open_file || not_in_argv (file))
5306     [ns_pending_files addObject: file];
5307   return YES;
5310 /*   Notification from the Workspace to open multiple files */
5311 - (void)application: sender openFiles: (NSArray *)fileList
5313   NSEnumerator *files = [fileList objectEnumerator];
5314   NSString *file;
5315   /* Don't open files from the command line unconditionally,
5316      Cocoa parses the command line wrong, --option value tries to open value
5317      if --option is the last option.  */
5318   while ((file = [files nextObject]) != nil)
5319     if (ns_do_open_file || not_in_argv (file))
5320       [ns_pending_files addObject: file];
5322   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5327 /* Handle dock menu requests.  */
5328 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5330   return dockMenu;
5334 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5335 - (void)applicationWillBecomeActive: (NSNotification *)notification
5337   NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5338   //ns_app_active=YES;
5341 - (void)applicationDidBecomeActive: (NSNotification *)notification
5343   NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5345 #ifdef NS_IMPL_GNUSTEP
5346   if (! applicationDidFinishLaunchingCalled)
5347     [self applicationDidFinishLaunching:notification];
5348 #endif
5349   //ns_app_active=YES;
5351   ns_update_auto_hide_menu_bar ();
5352   // No constraining takes place when the application is not active.
5353   ns_constrain_all_frames ();
5355 - (void)applicationDidResignActive: (NSNotification *)notification
5357   NSTRACE ("[EmacsApp applicationDidResignActive:]");
5359   //ns_app_active=NO;
5360   ns_send_appdefined (-1);
5365 /* ==========================================================================
5367     EmacsApp aux handlers for managing event loop
5369    ========================================================================== */
5372 - (void)timeout_handler: (NSTimer *)timedEntry
5373 /* --------------------------------------------------------------------------
5374      The timeout specified to ns_select has passed.
5375    -------------------------------------------------------------------------- */
5377   /*NSTRACE ("timeout_handler"); */
5378   ns_send_appdefined (-2);
5381 #ifdef NS_IMPL_GNUSTEP
5382 - (void)sendFromMainThread:(id)unused
5384   ns_send_appdefined (nextappdefined);
5386 #endif
5388 - (void)fd_handler:(id)unused
5389 /* --------------------------------------------------------------------------
5390      Check data waiting on file descriptors and terminate if so
5391    -------------------------------------------------------------------------- */
5393   int result;
5394   int waiting = 1, nfds;
5395   char c;
5397   fd_set readfds, writefds, *wfds;
5398   struct timespec timeout, *tmo;
5399   NSAutoreleasePool *pool = nil;
5401   /* NSTRACE ("fd_handler"); */
5403   for (;;)
5404     {
5405       [pool release];
5406       pool = [[NSAutoreleasePool alloc] init];
5408       if (waiting)
5409         {
5410           fd_set fds;
5411           FD_ZERO (&fds);
5412           FD_SET (selfds[0], &fds);
5413           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5414           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5415             waiting = 0;
5416         }
5417       else
5418         {
5419           pthread_mutex_lock (&select_mutex);
5420           nfds = select_nfds;
5422           if (select_valid & SELECT_HAVE_READ)
5423             readfds = select_readfds;
5424           else
5425             FD_ZERO (&readfds);
5427           if (select_valid & SELECT_HAVE_WRITE)
5428             {
5429               writefds = select_writefds;
5430               wfds = &writefds;
5431             }
5432           else
5433             wfds = NULL;
5434           if (select_valid & SELECT_HAVE_TMO)
5435             {
5436               timeout = select_timeout;
5437               tmo = &timeout;
5438             }
5439           else
5440             tmo = NULL;
5442           pthread_mutex_unlock (&select_mutex);
5444           FD_SET (selfds[0], &readfds);
5445           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5447           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5449           if (result == 0)
5450             ns_send_appdefined (-2);
5451           else if (result > 0)
5452             {
5453               if (FD_ISSET (selfds[0], &readfds))
5454                 {
5455                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5456                     waiting = 1;
5457                 }
5458               else
5459                 {
5460                   pthread_mutex_lock (&select_mutex);
5461                   if (select_valid & SELECT_HAVE_READ)
5462                     select_readfds = readfds;
5463                   if (select_valid & SELECT_HAVE_WRITE)
5464                     select_writefds = writefds;
5465                   if (select_valid & SELECT_HAVE_TMO)
5466                     select_timeout = timeout;
5467                   pthread_mutex_unlock (&select_mutex);
5469                   ns_send_appdefined (result);
5470                 }
5471             }
5472           waiting = 1;
5473         }
5474     }
5479 /* ==========================================================================
5481     Service provision
5483    ========================================================================== */
5485 /* called from system: queue for next pass through event loop */
5486 - (void)requestService: (NSPasteboard *)pboard
5487               userData: (NSString *)userData
5488                  error: (NSString **)error
5490   [ns_pending_service_names addObject: userData];
5491   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5492       SSDATA (ns_string_from_pasteboard (pboard))]];
5496 /* called from ns_read_socket to clear queue */
5497 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5499   struct frame *emacsframe = SELECTED_FRAME ();
5500   NSEvent *theEvent = [NSApp currentEvent];
5502   NSTRACE ("[EmacsApp fulfillService:withArg:]");
5504   if (!emacs_event)
5505     return NO;
5507   emacs_event->kind = NS_NONKEY_EVENT;
5508   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5509   ns_input_spi_name = build_string ([name UTF8String]);
5510   ns_input_spi_arg = build_string ([arg UTF8String]);
5511   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5512   EV_TRAILER (theEvent);
5514   return YES;
5518 @end  /* EmacsApp */
5522 /* ==========================================================================
5524     EmacsView implementation
5526    ========================================================================== */
5529 @implementation EmacsView
5531 /* needed to inform when window closed from LISP */
5532 - (void) setWindowClosing: (BOOL)closing
5534   NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5536   windowClosing = closing;
5540 - (void)dealloc
5542   NSTRACE ("[EmacsView dealloc]");
5543   [toolbar release];
5544   if (fs_state == FULLSCREEN_BOTH)
5545     [nonfs_window release];
5546   [super dealloc];
5550 /* called on font panel selection */
5551 - (void)changeFont: (id)sender
5553   NSEvent *e = [[self window] currentEvent];
5554   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5555   struct font *font = face->font;
5556   id newFont;
5557   CGFloat size;
5558   NSFont *nsfont;
5560   NSTRACE ("[EmacsView changeFont:]");
5562   if (!emacs_event)
5563     return;
5565 #ifdef NS_IMPL_GNUSTEP
5566   nsfont = ((struct nsfont_info *)font)->nsfont;
5567 #endif
5568 #ifdef NS_IMPL_COCOA
5569   nsfont = (NSFont *) macfont_get_nsctfont (font);
5570 #endif
5572   if ((newFont = [sender convertFont: nsfont]))
5573     {
5574       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5576       emacs_event->kind = NS_NONKEY_EVENT;
5577       emacs_event->modifiers = 0;
5578       emacs_event->code = KEY_NS_CHANGE_FONT;
5580       size = [newFont pointSize];
5581       ns_input_fontsize = make_number (lrint (size));
5582       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5583       EV_TRAILER (e);
5584     }
5588 - (BOOL)acceptsFirstResponder
5590   NSTRACE ("[EmacsView acceptsFirstResponder]");
5591   return YES;
5595 - (void)resetCursorRects
5597   NSRect visible = [self visibleRect];
5598   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5599   NSTRACE ("[EmacsView resetCursorRects]");
5601   if (currentCursor == nil)
5602     currentCursor = [NSCursor arrowCursor];
5604   if (!NSIsEmptyRect (visible))
5605     [self addCursorRect: visible cursor: currentCursor];
5606   [currentCursor setOnMouseEntered: YES];
5611 /*****************************************************************************/
5612 /* Keyboard handling. */
5613 #define NS_KEYLOG 0
5615 - (void)keyDown: (NSEvent *)theEvent
5617   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5618   int code;
5619   unsigned fnKeysym = 0;
5620   static NSMutableArray *nsEvArray;
5621   int left_is_none;
5622   unsigned int flags = [theEvent modifierFlags];
5624   NSTRACE ("[EmacsView keyDown:]");
5626   /* Rhapsody and OS X give up and down events for the arrow keys */
5627   if (ns_fake_keydown == YES)
5628     ns_fake_keydown = NO;
5629   else if ([theEvent type] != NSKeyDown)
5630     return;
5632   if (!emacs_event)
5633     return;
5635  if (![[self window] isKeyWindow]
5636      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5637      /* we must avoid an infinite loop here. */
5638      && (EmacsView *)[[theEvent window] delegate] != self)
5639    {
5640      /* XXX: There is an occasional condition in which, when Emacs display
5641          updates a different frame from the current one, and temporarily
5642          selects it, then processes some interrupt-driven input
5643          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5644          for some reason that window has its first responder set to the NSView
5645          most recently updated (I guess), which is not the correct one. */
5646      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5647      return;
5648    }
5650   if (nsEvArray == nil)
5651     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5653   [NSCursor setHiddenUntilMouseMoves: YES];
5655   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5656     {
5657       clear_mouse_face (hlinfo);
5658       hlinfo->mouse_face_hidden = 1;
5659     }
5661   if (!processingCompose)
5662     {
5663       /* When using screen sharing, no left or right information is sent,
5664          so use Left key in those cases.  */
5665       int is_left_key, is_right_key;
5667       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5668         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5670       /* (Carbon way: [theEvent keyCode]) */
5672       /* is it a "function key"? */
5673       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5674          flag set (this is probably a bug in the OS).
5675       */
5676       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5677         {
5678           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5679         }
5680       if (fnKeysym == 0)
5681         {
5682           fnKeysym = ns_convert_key (code);
5683         }
5685       if (fnKeysym)
5686         {
5687           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5688              because Emacs treats Delete and KP-Delete same (in simple.el). */
5689           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5690 #ifdef NS_IMPL_GNUSTEP
5691               /*  GNUstep uses incompatible keycodes, even for those that are
5692                   supposed to be hardware independent.  Just check for delete.
5693                   Keypad delete does not have keysym 0xFFFF.
5694                   See http://savannah.gnu.org/bugs/?25395
5695               */
5696               || (fnKeysym == 0xFFFF && code == 127)
5697 #endif
5698             )
5699             code = 0xFF08; /* backspace */
5700           else
5701             code = fnKeysym;
5702         }
5704       /* are there modifiers? */
5705       emacs_event->modifiers = 0;
5707       if (flags & NSHelpKeyMask)
5708           emacs_event->modifiers |= hyper_modifier;
5710       if (flags & NSShiftKeyMask)
5711         emacs_event->modifiers |= shift_modifier;
5713       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5714       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5715         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5717       if (is_right_key)
5718         emacs_event->modifiers |= parse_solitary_modifier
5719           (EQ (ns_right_command_modifier, Qleft)
5720            ? ns_command_modifier
5721            : ns_right_command_modifier);
5723       if (is_left_key)
5724         {
5725           emacs_event->modifiers |= parse_solitary_modifier
5726             (ns_command_modifier);
5728           /* if super (default), take input manager's word so things like
5729              dvorak / qwerty layout work */
5730           if (EQ (ns_command_modifier, Qsuper)
5731               && !fnKeysym
5732               && [[theEvent characters] length] != 0)
5733             {
5734               /* XXX: the code we get will be unshifted, so if we have
5735                  a shift modifier, must convert ourselves */
5736               if (!(flags & NSShiftKeyMask))
5737                 code = [[theEvent characters] characterAtIndex: 0];
5738 #if 0
5739               /* this is ugly and also requires linking w/Carbon framework
5740                  (for LMGetKbdType) so for now leave this rare (?) case
5741                  undealt with.. in future look into CGEvent methods */
5742               else
5743                 {
5744                   long smv = GetScriptManagerVariable (smKeyScript);
5745                   Handle uchrHandle = GetResource
5746                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5747                   UInt32 dummy = 0;
5748                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5749                                  [[theEvent characters] characterAtIndex: 0],
5750                                  kUCKeyActionDisplay,
5751                                  (flags & ~NSCommandKeyMask) >> 8,
5752                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5753                                  &dummy, 1, &dummy, &code);
5754                   code &= 0xFF;
5755                 }
5756 #endif
5757             }
5758         }
5760       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5761       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5762         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5764       if (is_right_key)
5765           emacs_event->modifiers |= parse_solitary_modifier
5766               (EQ (ns_right_control_modifier, Qleft)
5767                ? ns_control_modifier
5768                : ns_right_control_modifier);
5770       if (is_left_key)
5771         emacs_event->modifiers |= parse_solitary_modifier
5772           (ns_control_modifier);
5774       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5775           emacs_event->modifiers |=
5776             parse_solitary_modifier (ns_function_modifier);
5778       left_is_none = NILP (ns_alternate_modifier)
5779         || EQ (ns_alternate_modifier, Qnone);
5781       is_right_key = (flags & NSRightAlternateKeyMask)
5782         == NSRightAlternateKeyMask;
5783       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5784         || (! is_right_key
5785             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5787       if (is_right_key)
5788         {
5789           if ((NILP (ns_right_alternate_modifier)
5790                || EQ (ns_right_alternate_modifier, Qnone)
5791                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5792               && !fnKeysym)
5793             {   /* accept pre-interp alt comb */
5794               if ([[theEvent characters] length] > 0)
5795                 code = [[theEvent characters] characterAtIndex: 0];
5796               /*HACK: clear lone shift modifier to stop next if from firing */
5797               if (emacs_event->modifiers == shift_modifier)
5798                 emacs_event->modifiers = 0;
5799             }
5800           else
5801             emacs_event->modifiers |= parse_solitary_modifier
5802               (EQ (ns_right_alternate_modifier, Qleft)
5803                ? ns_alternate_modifier
5804                : ns_right_alternate_modifier);
5805         }
5807       if (is_left_key) /* default = meta */
5808         {
5809           if (left_is_none && !fnKeysym)
5810             {   /* accept pre-interp alt comb */
5811               if ([[theEvent characters] length] > 0)
5812                 code = [[theEvent characters] characterAtIndex: 0];
5813               /*HACK: clear lone shift modifier to stop next if from firing */
5814               if (emacs_event->modifiers == shift_modifier)
5815                 emacs_event->modifiers = 0;
5816             }
5817           else
5818               emacs_event->modifiers |=
5819                 parse_solitary_modifier (ns_alternate_modifier);
5820         }
5822   if (NS_KEYLOG)
5823     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5824              code, fnKeysym, flags, emacs_event->modifiers);
5826       /* if it was a function key or had modifiers, pass it directly to emacs */
5827       if (fnKeysym || (emacs_event->modifiers
5828                        && (emacs_event->modifiers != shift_modifier)
5829                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5830 /*[[theEvent characters] length] */
5831         {
5832           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5833           if (code < 0x20)
5834             code |= (1<<28)|(3<<16);
5835           else if (code == 0x7f)
5836             code |= (1<<28)|(3<<16);
5837           else if (!fnKeysym)
5838             emacs_event->kind = code > 0xFF
5839               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5841           emacs_event->code = code;
5842           EV_TRAILER (theEvent);
5843           processingCompose = NO;
5844           return;
5845         }
5846     }
5849   if (NS_KEYLOG && !processingCompose)
5850     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5852   processingCompose = YES;
5853   [nsEvArray addObject: theEvent];
5854   [self interpretKeyEvents: nsEvArray];
5855   [nsEvArray removeObject: theEvent];
5859 #ifdef NS_IMPL_COCOA
5860 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5861    decided not to send key-down for.
5862    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5863    This only applies on Tiger and earlier.
5864    If it matches one of these, send it on to keyDown. */
5865 -(void)keyUp: (NSEvent *)theEvent
5867   int flags = [theEvent modifierFlags];
5868   int code = [theEvent keyCode];
5870   NSTRACE ("[EmacsView keyUp:]");
5872   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5873       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5874     {
5875       if (NS_KEYLOG)
5876         fprintf (stderr, "keyUp: passed test");
5877       ns_fake_keydown = YES;
5878       [self keyDown: theEvent];
5879     }
5881 #endif
5884 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5887 /* <NSTextInput>: called when done composing;
5888    NOTE: also called when we delete over working text, followed immed.
5889          by doCommandBySelector: deleteBackward: */
5890 - (void)insertText: (id)aString
5892   int code;
5893   int len = [(NSString *)aString length];
5894   int i;
5896   NSTRACE ("[EmacsView insertText:]");
5898   if (NS_KEYLOG)
5899     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5900   processingCompose = NO;
5902   if (!emacs_event)
5903     return;
5905   /* first, clear any working text */
5906   if (workingText != nil)
5907     [self deleteWorkingText];
5909   /* now insert the string as keystrokes */
5910   for (i =0; i<len; i++)
5911     {
5912       code = [aString characterAtIndex: i];
5913       /* TODO: still need this? */
5914       if (code == 0x2DC)
5915         code = '~'; /* 0x7E */
5916       if (code != 32) /* Space */
5917         emacs_event->modifiers = 0;
5918       emacs_event->kind
5919         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5920       emacs_event->code = code;
5921       EV_TRAILER ((id)nil);
5922     }
5926 /* <NSTextInput>: inserts display of composing characters */
5927 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5929   NSString *str = [aString respondsToSelector: @selector (string)] ?
5930     [aString string] : aString;
5932   NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
5934   if (NS_KEYLOG)
5935     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5936            str, (unsigned long)[str length],
5937            (unsigned long)selRange.length,
5938            (unsigned long)selRange.location);
5940   if (workingText != nil)
5941     [self deleteWorkingText];
5942   if ([str length] == 0)
5943     return;
5945   if (!emacs_event)
5946     return;
5948   processingCompose = YES;
5949   workingText = [str copy];
5950   ns_working_text = build_string ([workingText UTF8String]);
5952   emacs_event->kind = NS_TEXT_EVENT;
5953   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5954   EV_TRAILER ((id)nil);
5958 /* delete display of composing characters [not in <NSTextInput>] */
5959 - (void)deleteWorkingText
5961   NSTRACE ("[EmacsView deleteWorkingText]");
5963   if (workingText == nil)
5964     return;
5965   if (NS_KEYLOG)
5966     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5967   [workingText release];
5968   workingText = nil;
5969   processingCompose = NO;
5971   if (!emacs_event)
5972     return;
5974   emacs_event->kind = NS_TEXT_EVENT;
5975   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5976   EV_TRAILER ((id)nil);
5980 - (BOOL)hasMarkedText
5982   NSTRACE ("[EmacsView hasMarkedText]");
5984   return workingText != nil;
5988 - (NSRange)markedRange
5990   NSTRACE ("[EmacsView markedRange]");
5992   NSRange rng = workingText != nil
5993     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5994   if (NS_KEYLOG)
5995     NSLog (@"markedRange request");
5996   return rng;
6000 - (void)unmarkText
6002   NSTRACE ("[EmacsView unmarkText]");
6004   if (NS_KEYLOG)
6005     NSLog (@"unmark (accept) text");
6006   [self deleteWorkingText];
6007   processingCompose = NO;
6011 /* used to position char selection windows, etc. */
6012 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6014   NSRect rect;
6015   NSPoint pt;
6016   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6018   NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6020   if (NS_KEYLOG)
6021     NSLog (@"firstRectForCharRange request");
6023   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6024   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6025   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6026   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6027                                        +FRAME_LINE_HEIGHT (emacsframe));
6029   pt = [self convertPoint: pt toView: nil];
6030   pt = [[self window] convertBaseToScreen: pt];
6031   rect.origin = pt;
6032   return rect;
6036 - (NSInteger)conversationIdentifier
6038   return (NSInteger)self;
6042 - (void)doCommandBySelector: (SEL)aSelector
6044   NSTRACE ("[EmacsView doCommandBySelector:]");
6046   if (NS_KEYLOG)
6047     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6049   processingCompose = NO;
6050   if (aSelector == @selector (deleteBackward:))
6051     {
6052       /* happens when user backspaces over an ongoing composition:
6053          throw a 'delete' into the event queue */
6054       if (!emacs_event)
6055         return;
6056       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6057       emacs_event->code = 0xFF08;
6058       EV_TRAILER ((id)nil);
6059     }
6062 - (NSArray *)validAttributesForMarkedText
6064   static NSArray *arr = nil;
6065   if (arr == nil) arr = [NSArray new];
6066  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6067   return arr;
6070 - (NSRange)selectedRange
6072   if (NS_KEYLOG)
6073     NSLog (@"selectedRange request");
6074   return NSMakeRange (NSNotFound, 0);
6077 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6078     GNUSTEP_GUI_MINOR_VERSION > 22
6079 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6080 #else
6081 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6082 #endif
6084   if (NS_KEYLOG)
6085     NSLog (@"characterIndexForPoint request");
6086   return 0;
6089 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6091   static NSAttributedString *str = nil;
6092   if (str == nil) str = [NSAttributedString new];
6093   if (NS_KEYLOG)
6094     NSLog (@"attributedSubstringFromRange request");
6095   return str;
6098 /* End <NSTextInput> impl. */
6099 /*****************************************************************************/
6102 /* This is what happens when the user presses a mouse button.  */
6103 - (void)mouseDown: (NSEvent *)theEvent
6105   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6106   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6108   NSTRACE ("[EmacsView mouseDown:]");
6110   [self deleteWorkingText];
6112   if (!emacs_event)
6113     return;
6115   dpyinfo->last_mouse_frame = emacsframe;
6116   /* appears to be needed to prevent spurious movement events generated on
6117      button clicks */
6118   emacsframe->mouse_moved = 0;
6120   if ([theEvent type] == NSScrollWheel)
6121     {
6122       CGFloat delta = [theEvent deltaY];
6123       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6124       if (delta == 0)
6125         {
6126           delta = [theEvent deltaX];
6127           if (delta == 0)
6128             {
6129               NSTRACE_MSG ("deltaIsZero");
6130               return;
6131             }
6132           emacs_event->kind = HORIZ_WHEEL_EVENT;
6133         }
6134       else
6135         emacs_event->kind = WHEEL_EVENT;
6137       emacs_event->code = 0;
6138       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6139         ((delta > 0) ? up_modifier : down_modifier);
6140     }
6141   else
6142     {
6143       emacs_event->kind = MOUSE_CLICK_EVENT;
6144       emacs_event->code = EV_BUTTON (theEvent);
6145       emacs_event->modifiers = EV_MODIFIERS (theEvent)
6146                              | EV_UDMODIFIERS (theEvent);
6147     }
6148   XSETINT (emacs_event->x, lrint (p.x));
6149   XSETINT (emacs_event->y, lrint (p.y));
6150   EV_TRAILER (theEvent);
6154 - (void)rightMouseDown: (NSEvent *)theEvent
6156   NSTRACE ("[EmacsView rightMouseDown:]");
6157   [self mouseDown: theEvent];
6161 - (void)otherMouseDown: (NSEvent *)theEvent
6163   NSTRACE ("[EmacsView otherMouseDown:]");
6164   [self mouseDown: theEvent];
6168 - (void)mouseUp: (NSEvent *)theEvent
6170   NSTRACE ("[EmacsView mouseUp:]");
6171   [self mouseDown: theEvent];
6175 - (void)rightMouseUp: (NSEvent *)theEvent
6177   NSTRACE ("[EmacsView rightMouseUp:]");
6178   [self mouseDown: theEvent];
6182 - (void)otherMouseUp: (NSEvent *)theEvent
6184   NSTRACE ("[EmacsView otherMouseUp:]");
6185   [self mouseDown: theEvent];
6189 - (void) scrollWheel: (NSEvent *)theEvent
6191   NSTRACE ("[EmacsView scrollWheel:]");
6192   [self mouseDown: theEvent];
6196 /* Tell emacs the mouse has moved. */
6197 - (void)mouseMoved: (NSEvent *)e
6199   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6200   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6201   Lisp_Object frame;
6202   NSPoint pt;
6204   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6206   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6207   pt = [self convertPoint: [e locationInWindow] fromView: nil];
6208   dpyinfo->last_mouse_motion_x = pt.x;
6209   dpyinfo->last_mouse_motion_y = pt.y;
6211   /* update any mouse face */
6212   if (hlinfo->mouse_face_hidden)
6213     {
6214       hlinfo->mouse_face_hidden = 0;
6215       clear_mouse_face (hlinfo);
6216     }
6218   /* tooltip handling */
6219   previous_help_echo_string = help_echo_string;
6220   help_echo_string = Qnil;
6222   if (!NILP (Vmouse_autoselect_window))
6223     {
6224       NSTRACE_MSG ("mouse_autoselect_window");
6225       static Lisp_Object last_mouse_window;
6226       Lisp_Object window
6227         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6229       if (WINDOWP (window)
6230           && !EQ (window, last_mouse_window)
6231           && !EQ (window, selected_window)
6232           && (focus_follows_mouse
6233               || (EQ (XWINDOW (window)->frame,
6234                       XWINDOW (selected_window)->frame))))
6235         {
6236           NSTRACE_MSG ("in_window");
6237           emacs_event->kind = SELECT_WINDOW_EVENT;
6238           emacs_event->frame_or_window = window;
6239           EV_TRAILER2 (e);
6240         }
6241       /* Remember the last window where we saw the mouse.  */
6242       last_mouse_window = window;
6243     }
6245   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6246     help_echo_string = previous_help_echo_string;
6248   XSETFRAME (frame, emacsframe);
6249   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6250     {
6251       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6252          (note_mouse_highlight), which is called through the
6253          note_mouse_movement () call above */
6254       any_help_event_p = YES;
6255       gen_help_event (help_echo_string, frame, help_echo_window,
6256                       help_echo_object, help_echo_pos);
6257     }
6259   if (emacsframe->mouse_moved && send_appdefined)
6260     ns_send_appdefined (-1);
6264 - (void)mouseDragged: (NSEvent *)e
6266   NSTRACE ("[EmacsView mouseDragged:]");
6267   [self mouseMoved: e];
6271 - (void)rightMouseDragged: (NSEvent *)e
6273   NSTRACE ("[EmacsView rightMouseDragged:]");
6274   [self mouseMoved: e];
6278 - (void)otherMouseDragged: (NSEvent *)e
6280   NSTRACE ("[EmacsView otherMouseDragged:]");
6281   [self mouseMoved: e];
6285 - (BOOL)windowShouldClose: (id)sender
6287   NSEvent *e =[[self window] currentEvent];
6289   NSTRACE ("[EmacsView windowShouldClose:]");
6290   windowClosing = YES;
6291   if (!emacs_event)
6292     return NO;
6293   emacs_event->kind = DELETE_WINDOW_EVENT;
6294   emacs_event->modifiers = 0;
6295   emacs_event->code = 0;
6296   EV_TRAILER (e);
6297   /* Don't close this window, let this be done from lisp code.  */
6298   return NO;
6301 - (void) updateFrameSize: (BOOL) delay;
6303   NSWindow *window = [self window];
6304   NSRect wr = [window frame];
6305   int extra = 0;
6306   int oldc = cols, oldr = rows;
6307   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6308   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6309   int neww, newh;
6311   NSTRACE ("[EmacsView updateFrameSize:]");
6312   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6313   NSTRACE_RECT ("Original frame", wr);
6314   NSTRACE_MSG  ("Original columns: %d", cols);
6315   NSTRACE_MSG  ("Original rows: %d", rows);
6317   if (! [self isFullscreen])
6318     {
6319 #ifdef NS_IMPL_GNUSTEP
6320       // GNUstep does not always update the tool bar height.  Force it.
6321       if (toolbar && [toolbar isVisible])
6322           update_frame_tool_bar (emacsframe);
6323 #endif
6325       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6326         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6327     }
6329   if (wait_for_tool_bar)
6330     {
6331       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6332         {
6333           NSTRACE_MSG ("Waiting for toolbar");
6334           return;
6335         }
6336       wait_for_tool_bar = NO;
6337     }
6339   neww = (int)wr.size.width - emacsframe->border_width;
6340   newh = (int)wr.size.height - extra;
6342   NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6343   NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6345   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6346   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6348   if (cols < MINWIDTH)
6349     cols = MINWIDTH;
6351   if (rows < MINHEIGHT)
6352     rows = MINHEIGHT;
6354   NSTRACE_MSG ("New columns: %d", cols);
6355   NSTRACE_MSG ("New rows: %d", rows);
6357   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6358     {
6359       NSView *view = FRAME_NS_VIEW (emacsframe);
6360       NSWindow *win = [view window];
6362       change_frame_size (emacsframe,
6363                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6364                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6365                          0, delay, 0, 1);
6366       SET_FRAME_GARBAGED (emacsframe);
6367       cancel_mouse_face (emacsframe);
6369       wr = NSMakeRect (0, 0, neww, newh);
6371       [view setFrame: wr];
6373       // to do: consider using [NSNotificationCenter postNotificationName:].
6374       [self windowDidMove: // Update top/left.
6375               [NSNotification notificationWithName:NSWindowDidMoveNotification
6376                                             object:[view window]]];
6377     }
6378   else
6379     {
6380       NSTRACE_MSG ("No change");
6381     }
6384 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6385 /* normalize frame to gridded text size */
6387   int extra = 0;
6389   NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6390            NSTRACE_ARG_SIZE (frameSize));
6391   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6392   NSTRACE_FSTYPE ("fs_state", fs_state);
6394   if (fs_state == FULLSCREEN_MAXIMIZED
6395       && (maximized_width != (int)frameSize.width
6396           || maximized_height != (int)frameSize.height))
6397     [self setFSValue: FULLSCREEN_NONE];
6398   else if (fs_state == FULLSCREEN_WIDTH
6399            && maximized_width != (int)frameSize.width)
6400     [self setFSValue: FULLSCREEN_NONE];
6401   else if (fs_state == FULLSCREEN_HEIGHT
6402            && maximized_height != (int)frameSize.height)
6403     [self setFSValue: FULLSCREEN_NONE];
6405   if (fs_state == FULLSCREEN_NONE)
6406     maximized_width = maximized_height = -1;
6408   if (! [self isFullscreen])
6409     {
6410       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6411         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6412     }
6414   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6415   if (cols < MINWIDTH)
6416     cols = MINWIDTH;
6418   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6419                                            frameSize.height - extra);
6420   if (rows < MINHEIGHT)
6421     rows = MINHEIGHT;
6422 #ifdef NS_IMPL_COCOA
6423   {
6424     /* this sets window title to have size in it; the wm does this under GS */
6425     NSRect r = [[self window] frame];
6426     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6427       {
6428         if (old_title != 0)
6429           {
6430             xfree (old_title);
6431             old_title = 0;
6432           }
6433       }
6434     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6435       {
6436         char *size_title;
6437         NSWindow *window = [self window];
6438         if (old_title == 0)
6439           {
6440             char *t = strdup ([[[self window] title] UTF8String]);
6441             char *pos = strstr (t, "  â€”  ");
6442             if (pos)
6443               *pos = '\0';
6444             old_title = t;
6445           }
6446         size_title = xmalloc (strlen (old_title) + 40);
6447         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6448         [window setTitle: [NSString stringWithUTF8String: size_title]];
6449         [window display];
6450         xfree (size_title);
6451       }
6452   }
6453 #endif /* NS_IMPL_COCOA */
6455   NSTRACE_MSG ("cols: %d  rows: %d", cols, rows);
6457   /* Restrict the new size to the text gird.
6459      Don't restrict the width if the user only adjusted the height, and
6460      vice versa.  (Without this, the frame would shrink, and move
6461      slightly, if the window was resized by dragging one of its
6462      borders.) */
6463   if (!frame_resize_pixelwise)
6464     {
6465       NSRect r = [[self window] frame];
6467       if (r.size.width != frameSize.width)
6468         {
6469           frameSize.width =
6470             FRAME_TEXT_COLS_TO_PIXEL_WIDTH  (emacsframe, cols);
6471         }
6473       if (r.size.height != frameSize.height)
6474         {
6475           frameSize.height =
6476             FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6477         }
6478     }
6480   NSTRACE_RETURN_SIZE (frameSize);
6482   return frameSize;
6486 - (void)windowDidResize: (NSNotification *)notification
6488   NSTRACE ("[EmacsView windowDidResize:]");
6489   if (!FRAME_LIVE_P (emacsframe))
6490     {
6491       NSTRACE_MSG ("Ignored (frame dead)");
6492       return;
6493     }
6494   if (emacsframe->output_data.ns->in_animation)
6495     {
6496       NSTRACE_MSG ("Ignored (in animation)");
6497       return;
6498     }
6500   if (! [self fsIsNative])
6501     {
6502       NSWindow *theWindow = [notification object];
6503       /* We can get notification on the non-FS window when in
6504          fullscreen mode.  */
6505       if ([self window] != theWindow) return;
6506     }
6508   NSTRACE_RECT ("frame", [[notification object] frame]);
6510 #ifdef NS_IMPL_GNUSTEP
6511   NSWindow *theWindow = [notification object];
6513    /* In GNUstep, at least currently, it's possible to get a didResize
6514       without getting a willResize.. therefore we need to act as if we got
6515       the willResize now */
6516   NSSize sz = [theWindow frame].size;
6517   sz = [self windowWillResize: theWindow toSize: sz];
6518 #endif /* NS_IMPL_GNUSTEP */
6520   if (cols > 0 && rows > 0)
6521     {
6522       [self updateFrameSize: YES];
6523     }
6525   ns_send_appdefined (-1);
6528 #ifdef NS_IMPL_COCOA
6529 - (void)viewDidEndLiveResize
6531   NSTRACE ("[EmacsView viewDidEndLiveResize]");
6533   [super viewDidEndLiveResize];
6534   if (old_title != 0)
6535     {
6536       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6537       xfree (old_title);
6538       old_title = 0;
6539     }
6540   maximizing_resize = NO;
6542 #endif /* NS_IMPL_COCOA */
6545 - (void)windowDidBecomeKey: (NSNotification *)notification
6546 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6548   [self windowDidBecomeKey];
6552 - (void)windowDidBecomeKey      /* for direct calls */
6554   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6555   struct frame *old_focus = dpyinfo->x_focus_frame;
6557   NSTRACE ("[EmacsView windowDidBecomeKey]");
6559   if (emacsframe != old_focus)
6560     dpyinfo->x_focus_frame = emacsframe;
6562   ns_frame_rehighlight (emacsframe);
6564   if (emacs_event)
6565     {
6566       emacs_event->kind = FOCUS_IN_EVENT;
6567       EV_TRAILER ((id)nil);
6568     }
6572 - (void)windowDidResignKey: (NSNotification *)notification
6573 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6575   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6576   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6577   NSTRACE ("[EmacsView windowDidResignKey:]");
6579   if (is_focus_frame)
6580     dpyinfo->x_focus_frame = 0;
6582   emacsframe->mouse_moved = 0;
6583   ns_frame_rehighlight (emacsframe);
6585   /* FIXME: for some reason needed on second and subsequent clicks away
6586             from sole-frame Emacs to get hollow box to show */
6587   if (!windowClosing && [[self window] isVisible] == YES)
6588     {
6589       x_update_cursor (emacsframe, 1);
6590       x_set_frame_alpha (emacsframe);
6591     }
6593   if (any_help_event_p)
6594     {
6595       Lisp_Object frame;
6596       XSETFRAME (frame, emacsframe);
6597       help_echo_string = Qnil;
6598       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6599     }
6601   if (emacs_event && is_focus_frame)
6602     {
6603       [self deleteWorkingText];
6604       emacs_event->kind = FOCUS_OUT_EVENT;
6605       EV_TRAILER ((id)nil);
6606     }
6610 - (void)windowWillMiniaturize: sender
6612   NSTRACE ("[EmacsView windowWillMiniaturize:]");
6616 - (void)setFrame:(NSRect)frameRect;
6618   NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6619            NSTRACE_ARG_RECT (frameRect));
6621   [super setFrame:(NSRect)frameRect];
6625 - (BOOL)isFlipped
6627   return YES;
6631 - (BOOL)isOpaque
6633   return NO;
6637 - initFrameFromEmacs: (struct frame *)f
6639   NSRect r, wr;
6640   Lisp_Object tem;
6641   NSWindow *win;
6642   NSColor *col;
6643   NSString *name;
6645   NSTRACE ("[EmacsView initFrameFromEmacs:]");
6646   NSTRACE_MSG ("cols:%d lines:%d\n", f->text_cols, f->text_lines);
6648   windowClosing = NO;
6649   processingCompose = NO;
6650   scrollbarsNeedingUpdate = 0;
6651   fs_state = FULLSCREEN_NONE;
6652   fs_before_fs = next_maximized = -1;
6653 #ifdef HAVE_NATIVE_FS
6654   fs_is_native = ns_use_native_fullscreen;
6655 #else
6656   fs_is_native = NO;
6657 #endif
6658   maximized_width = maximized_height = -1;
6659   nonfs_window = nil;
6661   ns_userRect = NSMakeRect (0, 0, 0, 0);
6662   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6663                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6664   [self initWithFrame: r];
6665   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6667   FRAME_NS_VIEW (f) = self;
6668   emacsframe = f;
6669 #ifdef NS_IMPL_COCOA
6670   old_title = 0;
6671   maximizing_resize = NO;
6672 #endif
6674   win = [[EmacsWindow alloc]
6675             initWithContentRect: r
6676                       styleMask: (NSResizableWindowMask |
6677 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6678                                   NSTitledWindowMask |
6679 #endif
6680                                   NSMiniaturizableWindowMask |
6681                                   NSClosableWindowMask)
6682                         backing: NSBackingStoreBuffered
6683                           defer: YES];
6685 #ifdef HAVE_NATIVE_FS
6686     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6687 #endif
6689   wr = [win frame];
6690   bwidth = f->border_width = wr.size.width - r.size.width;
6691   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6693   [win setAcceptsMouseMovedEvents: YES];
6694   [win setDelegate: self];
6695 #if !defined (NS_IMPL_COCOA) || \
6696   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6697   [win useOptimizedDrawing: YES];
6698 #endif
6700   [[win contentView] addSubview: self];
6702   if (ns_drag_types)
6703     [self registerForDraggedTypes: ns_drag_types];
6705   tem = f->name;
6706   name = [NSString stringWithUTF8String:
6707                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6708   [win setTitle: name];
6710   /* toolbar support */
6711   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6712                          [NSString stringWithFormat: @"Emacs Frame %d",
6713                                    ns_window_num]];
6714   [win setToolbar: toolbar];
6715   [toolbar setVisible: NO];
6717   /* Don't set frame garbaged until tool bar is up to date?
6718      This avoids an extra clear and redraw (flicker) at frame creation.  */
6719   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6720   else wait_for_tool_bar = NO;
6723 #ifdef NS_IMPL_COCOA
6724   {
6725     NSButton *toggleButton;
6726   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6727   [toggleButton setTarget: self];
6728   [toggleButton setAction: @selector (toggleToolbar: )];
6729   }
6730 #endif
6731   FRAME_TOOLBAR_HEIGHT (f) = 0;
6733   tem = f->icon_name;
6734   if (!NILP (tem))
6735     [win setMiniwindowTitle:
6736            [NSString stringWithUTF8String: SSDATA (tem)]];
6738   {
6739     NSScreen *screen = [win screen];
6741     if (screen != 0)
6742       {
6743         NSPoint pt = NSMakePoint
6744           (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6745            IN_BOUND (-SCREENMAX,
6746                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6748         [win setFrameTopLeftPoint: pt];
6750         NSTRACE_RECT ("new frame", [win frame]);
6751       }
6752   }
6754   [win makeFirstResponder: self];
6756   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6757                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6758   [win setBackgroundColor: col];
6759   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6760     [win setOpaque: NO];
6762 #if !defined (NS_IMPL_COCOA) || \
6763   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6764   [self allocateGState];
6765 #endif
6766   [NSApp registerServicesMenuSendTypes: ns_send_types
6767                            returnTypes: nil];
6769   ns_window_num++;
6770   return self;
6774 - (void)windowDidMove: sender
6776   NSWindow *win = [self window];
6777   NSRect r = [win frame];
6778   NSArray *screens = [NSScreen screens];
6779   NSScreen *screen = [screens objectAtIndex: 0];
6781   NSTRACE ("[EmacsView windowDidMove:]");
6783   if (!emacsframe->output_data.ns)
6784     return;
6785   if (screen != nil)
6786     {
6787       emacsframe->left_pos = r.origin.x;
6788       emacsframe->top_pos =
6789         [screen frame].size.height - (r.origin.y + r.size.height);
6790     }
6794 /* Called AFTER method below, but before our windowWillResize call there leads
6795    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6796    location so set_window_size moves the frame. */
6797 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6799   NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6800             NSTRACE_FMT_RETURN "YES"),
6801            NSTRACE_ARG_RECT (newFrame));
6803   emacsframe->output_data.ns->zooming = 1;
6804   return YES;
6808 /* Override to do something slightly nonstandard, but nice.  First click on
6809    zoom button will zoom vertically.  Second will zoom completely.  Third
6810    returns to original. */
6811 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6812                         defaultFrame:(NSRect)defaultFrame
6814   // TODO: Rename to "currentFrame" and assign "result" properly in
6815   // all paths.
6816   NSRect result = [sender frame];
6818   NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6819             NSTRACE_FMT_RECT "]"),
6820            NSTRACE_ARG_RECT (defaultFrame));
6821   NSTRACE_FSTYPE ("fs_state", fs_state);
6822   NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6823   NSTRACE_FSTYPE ("next_maximized", next_maximized);
6824   NSTRACE_RECT   ("ns_userRect", ns_userRect);
6825   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6827   if (fs_before_fs != -1) /* Entering fullscreen */
6828     {
6829       NSTRACE_MSG ("Entering fullscreen");
6830       result = defaultFrame;
6831     }
6832   else
6833     {
6834       // Save the window size and position (frame) before the resize.
6835       if (fs_state != FULLSCREEN_MAXIMIZED
6836           && fs_state != FULLSCREEN_WIDTH)
6837         {
6838           ns_userRect.size.width = result.size.width;
6839           ns_userRect.origin.x   = result.origin.x;
6840         }
6842       if (fs_state != FULLSCREEN_MAXIMIZED
6843           && fs_state != FULLSCREEN_HEIGHT)
6844         {
6845           ns_userRect.size.height = result.size.height;
6846           ns_userRect.origin.y    = result.origin.y;
6847         }
6849       NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6851       if (next_maximized == FULLSCREEN_HEIGHT
6852           || (next_maximized == -1
6853               && abs ((int)(defaultFrame.size.height - result.size.height))
6854               > FRAME_LINE_HEIGHT (emacsframe)))
6855         {
6856           /* first click */
6857           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6858           maximized_height = result.size.height = defaultFrame.size.height;
6859           maximized_width = -1;
6860           result.origin.y = defaultFrame.origin.y;
6861           if (ns_userRect.size.height != 0)
6862             {
6863               result.origin.x = ns_userRect.origin.x;
6864               result.size.width = ns_userRect.size.width;
6865             }
6866           [self setFSValue: FULLSCREEN_HEIGHT];
6867 #ifdef NS_IMPL_COCOA
6868           maximizing_resize = YES;
6869 #endif
6870         }
6871       else if (next_maximized == FULLSCREEN_WIDTH)
6872         {
6873           NSTRACE_MSG ("FULLSCREEN_WIDTH");
6874           maximized_width = result.size.width = defaultFrame.size.width;
6875           maximized_height = -1;
6876           result.origin.x = defaultFrame.origin.x;
6877           if (ns_userRect.size.width != 0)
6878             {
6879               result.origin.y = ns_userRect.origin.y;
6880               result.size.height = ns_userRect.size.height;
6881             }
6882           [self setFSValue: FULLSCREEN_WIDTH];
6883         }
6884       else if (next_maximized == FULLSCREEN_MAXIMIZED
6885                || (next_maximized == -1
6886                    && abs ((int)(defaultFrame.size.width - result.size.width))
6887                    > FRAME_COLUMN_WIDTH (emacsframe)))
6888         {
6889           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6891           result = defaultFrame;  /* second click */
6892           maximized_width = result.size.width;
6893           maximized_height = result.size.height;
6894           [self setFSValue: FULLSCREEN_MAXIMIZED];
6895 #ifdef NS_IMPL_COCOA
6896           maximizing_resize = YES;
6897 #endif
6898         }
6899       else
6900         {
6901           /* restore */
6902           NSTRACE_MSG ("Restore");
6903           result = ns_userRect.size.height ? ns_userRect : result;
6904           NSTRACE_RECT ("restore (2)", result);
6905           ns_userRect = NSMakeRect (0, 0, 0, 0);
6906 #ifdef NS_IMPL_COCOA
6907           maximizing_resize = fs_state != FULLSCREEN_NONE;
6908 #endif
6909           [self setFSValue: FULLSCREEN_NONE];
6910           maximized_width = maximized_height = -1;
6911         }
6912     }
6914   if (fs_before_fs == -1) next_maximized = -1;
6916   NSTRACE_RECT   ("Final ns_userRect", ns_userRect);
6917   NSTRACE_MSG    ("Final maximized_width: %d", maximized_width);
6918   NSTRACE_MSG    ("Final maximized_height: %d", maximized_height);
6919   NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6921   [self windowWillResize: sender toSize: result.size];
6923   NSTRACE_RETURN_RECT (result);
6925   return result;
6929 - (void)windowDidDeminiaturize: sender
6931   NSTRACE ("[EmacsView windowDidDeminiaturize:]");
6932   if (!emacsframe->output_data.ns)
6933     return;
6935   SET_FRAME_ICONIFIED (emacsframe, 0);
6936   SET_FRAME_VISIBLE (emacsframe, 1);
6937   windows_or_buffers_changed = 63;
6939   if (emacs_event)
6940     {
6941       emacs_event->kind = DEICONIFY_EVENT;
6942       EV_TRAILER ((id)nil);
6943     }
6947 - (void)windowDidExpose: sender
6949   NSTRACE ("[EmacsView windowDidExpose:]");
6950   if (!emacsframe->output_data.ns)
6951     return;
6953   SET_FRAME_VISIBLE (emacsframe, 1);
6954   SET_FRAME_GARBAGED (emacsframe);
6956   if (send_appdefined)
6957     ns_send_appdefined (-1);
6961 - (void)windowDidMiniaturize: sender
6963   NSTRACE ("[EmacsView windowDidMiniaturize:]");
6964   if (!emacsframe->output_data.ns)
6965     return;
6967   SET_FRAME_ICONIFIED (emacsframe, 1);
6968   SET_FRAME_VISIBLE (emacsframe, 0);
6970   if (emacs_event)
6971     {
6972       emacs_event->kind = ICONIFY_EVENT;
6973       EV_TRAILER ((id)nil);
6974     }
6977 #ifdef HAVE_NATIVE_FS
6978 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6979       willUseFullScreenPresentationOptions:
6980   (NSApplicationPresentationOptions)proposedOptions
6982   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6984 #endif
6986 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6988   NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
6989   [self windowWillEnterFullScreen];
6991 - (void)windowWillEnterFullScreen /* provided for direct calls */
6993   NSTRACE ("[EmacsView windowWillEnterFullScreen]");
6994   fs_before_fs = fs_state;
6997 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6999   NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7000   [self windowDidEnterFullScreen];
7003 - (void)windowDidEnterFullScreen /* provided for direct calls */
7005   NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7006   [self setFSValue: FULLSCREEN_BOTH];
7007   if (! [self fsIsNative])
7008     {
7009       [self windowDidBecomeKey];
7010       [nonfs_window orderOut:self];
7011     }
7012   else
7013     {
7014       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7015 #ifdef NS_IMPL_COCOA
7016 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7017       unsigned val = (unsigned)[NSApp presentationOptions];
7019       // OSX 10.7 bug fix, the menu won't appear without this.
7020       // val is non-zero on other OSX versions.
7021       if (val == 0)
7022         {
7023           NSApplicationPresentationOptions options
7024             = NSApplicationPresentationAutoHideDock
7025             | NSApplicationPresentationAutoHideMenuBar
7026             | NSApplicationPresentationFullScreen
7027             | NSApplicationPresentationAutoHideToolbar;
7029           [NSApp setPresentationOptions: options];
7030         }
7031 #endif
7032 #endif
7033       [toolbar setVisible:tbar_visible];
7034     }
7037 - (void)windowWillExitFullScreen:(NSNotification *)notification
7039   NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7040   [self windowWillExitFullScreen];
7043 - (void)windowWillExitFullScreen /* provided for direct calls */
7045   NSTRACE ("[EmacsView windowWillExitFullScreen]");
7046   if (!FRAME_LIVE_P (emacsframe))
7047     {
7048       NSTRACE_MSG ("Ignored (frame dead)");
7049       return;
7050     }
7051   if (next_maximized != -1)
7052     fs_before_fs = next_maximized;
7055 - (void)windowDidExitFullScreen:(NSNotification *)notification
7057   NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7058   [self windowDidExitFullScreen];
7061 - (void)windowDidExitFullScreen /* provided for direct calls */
7063   NSTRACE ("[EmacsView windowDidExitFullScreen]");
7064   if (!FRAME_LIVE_P (emacsframe))
7065     {
7066       NSTRACE_MSG ("Ignored (frame dead)");
7067       return;
7068     }
7069   [self setFSValue: fs_before_fs];
7070   fs_before_fs = -1;
7071 #ifdef HAVE_NATIVE_FS
7072   [self updateCollectionBehavior];
7073 #endif
7074   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7075     {
7076       [toolbar setVisible:YES];
7077       update_frame_tool_bar (emacsframe);
7078       [self updateFrameSize:YES];
7079       [[self window] display];
7080     }
7081   else
7082     [toolbar setVisible:NO];
7084   if (next_maximized != -1)
7085     [[self window] performZoom:self];
7088 - (BOOL)fsIsNative
7090   return fs_is_native;
7093 - (BOOL)isFullscreen
7095   NSTRACE ("[EmacsView isFullscreen]");
7097   if (! fs_is_native) return nonfs_window != nil;
7098 #ifdef HAVE_NATIVE_FS
7099   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
7100 #else
7101   return NO;
7102 #endif
7105 #ifdef HAVE_NATIVE_FS
7106 - (void)updateCollectionBehavior
7108   NSTRACE ("[EmacsView updateCollectionBehavior]");
7110   if (! [self isFullscreen])
7111     {
7112       NSWindow *win = [self window];
7113       NSWindowCollectionBehavior b = [win collectionBehavior];
7114       if (ns_use_native_fullscreen)
7115         b |= NSWindowCollectionBehaviorFullScreenPrimary;
7116       else
7117         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7119       [win setCollectionBehavior: b];
7120       fs_is_native = ns_use_native_fullscreen;
7121     }
7123 #endif
7125 - (void)toggleFullScreen: (id)sender
7127   NSWindow *w, *fw;
7128   BOOL onFirstScreen;
7129   struct frame *f;
7130   NSRect r, wr;
7131   NSColor *col;
7133   NSTRACE ("[EmacsView toggleFullScreen:]");
7135   if (fs_is_native)
7136     {
7137 #ifdef HAVE_NATIVE_FS
7138       [[self window] toggleFullScreen:sender];
7139 #endif
7140       return;
7141     }
7143   w = [self window];
7144   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7145   f = emacsframe;
7146   wr = [w frame];
7147   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7148                                  (FRAME_DEFAULT_FACE (f)),
7149                                  f);
7151   if (fs_state != FULLSCREEN_BOTH)
7152     {
7153       NSScreen *screen = [w screen];
7155 #if defined (NS_IMPL_COCOA) && \
7156   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7157       /* Hide ghost menu bar on secondary monitor? */
7158       if (! onFirstScreen)
7159         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7160 #endif
7161       /* Hide dock and menubar if we are on the primary screen.  */
7162       if (onFirstScreen)
7163         {
7164 #ifdef NS_IMPL_COCOA
7165           NSApplicationPresentationOptions options
7166             = NSApplicationPresentationAutoHideDock
7167             | NSApplicationPresentationAutoHideMenuBar;
7169           [NSApp setPresentationOptions: options];
7170 #else
7171           [NSMenu setMenuBarVisible:NO];
7172 #endif
7173         }
7175       fw = [[EmacsFSWindow alloc]
7176                        initWithContentRect:[w contentRectForFrameRect:wr]
7177                                  styleMask:NSBorderlessWindowMask
7178                                    backing:NSBackingStoreBuffered
7179                                      defer:YES
7180                                     screen:screen];
7182       [fw setContentView:[w contentView]];
7183       [fw setTitle:[w title]];
7184       [fw setDelegate:self];
7185       [fw setAcceptsMouseMovedEvents: YES];
7186 #if !defined (NS_IMPL_COCOA) || \
7187   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7188       [fw useOptimizedDrawing: YES];
7189 #endif
7190       [fw setBackgroundColor: col];
7191       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7192         [fw setOpaque: NO];
7194       f->border_width = 0;
7195       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7196       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7197       FRAME_TOOLBAR_HEIGHT (f) = 0;
7199       nonfs_window = w;
7201       [self windowWillEnterFullScreen];
7202       [fw makeKeyAndOrderFront:NSApp];
7203       [fw makeFirstResponder:self];
7204       [w orderOut:self];
7205       r = [fw frameRectForContentRect:[screen frame]];
7206       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7207       [self windowDidEnterFullScreen];
7208       [fw display];
7209     }
7210   else
7211     {
7212       fw = w;
7213       w = nonfs_window;
7214       nonfs_window = nil;
7216       if (onFirstScreen)
7217         {
7218 #ifdef NS_IMPL_COCOA
7219           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7220 #else
7221           [NSMenu setMenuBarVisible:YES];
7222 #endif
7223         }
7225       [w setContentView:[fw contentView]];
7226       [w setBackgroundColor: col];
7227       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7228         [w setOpaque: NO];
7230       f->border_width = bwidth;
7231       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7232       if (FRAME_EXTERNAL_TOOL_BAR (f))
7233         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7235       // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7237       [self windowWillExitFullScreen];
7238       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7239       [fw close];
7240       [w makeKeyAndOrderFront:NSApp];
7241       [self windowDidExitFullScreen];
7242       [self updateFrameSize:YES];
7243     }
7246 - (void)handleFS
7248   NSTRACE ("[EmacsView handleFS]");
7250   if (fs_state != emacsframe->want_fullscreen)
7251     {
7252       if (fs_state == FULLSCREEN_BOTH)
7253         {
7254           NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7255           [self toggleFullScreen:self];
7256         }
7258       switch (emacsframe->want_fullscreen)
7259         {
7260         case FULLSCREEN_BOTH:
7261           NSTRACE_MSG ("FULLSCREEN_BOTH");
7262           [self toggleFullScreen:self];
7263           break;
7264         case FULLSCREEN_WIDTH:
7265           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7266           next_maximized = FULLSCREEN_WIDTH;
7267           if (fs_state != FULLSCREEN_BOTH)
7268             [[self window] performZoom:self];
7269           break;
7270         case FULLSCREEN_HEIGHT:
7271           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7272           next_maximized = FULLSCREEN_HEIGHT;
7273           if (fs_state != FULLSCREEN_BOTH)
7274             [[self window] performZoom:self];
7275           break;
7276         case FULLSCREEN_MAXIMIZED:
7277           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7278           next_maximized = FULLSCREEN_MAXIMIZED;
7279           if (fs_state != FULLSCREEN_BOTH)
7280             [[self window] performZoom:self];
7281           break;
7282         case FULLSCREEN_NONE:
7283           NSTRACE_MSG ("FULLSCREEN_NONE");
7284           if (fs_state != FULLSCREEN_BOTH)
7285             {
7286               next_maximized = FULLSCREEN_NONE;
7287               [[self window] performZoom:self];
7288             }
7289           break;
7290         }
7292       emacsframe->want_fullscreen = FULLSCREEN_NONE;
7293     }
7297 - (void) setFSValue: (int)value
7299   NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7300            NSTRACE_ARG_FSTYPE(value));
7302   Lisp_Object lval = Qnil;
7303   switch (value)
7304     {
7305     case FULLSCREEN_BOTH:
7306       lval = Qfullboth;
7307       break;
7308     case FULLSCREEN_WIDTH:
7309       lval = Qfullwidth;
7310       break;
7311     case FULLSCREEN_HEIGHT:
7312       lval = Qfullheight;
7313       break;
7314     case FULLSCREEN_MAXIMIZED:
7315       lval = Qmaximized;
7316       break;
7317     }
7318   store_frame_param (emacsframe, Qfullscreen, lval);
7319   fs_state = value;
7322 - (void)mouseEntered: (NSEvent *)theEvent
7324   NSTRACE ("[EmacsView mouseEntered:]");
7325   if (emacsframe)
7326     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7327       = EV_TIMESTAMP (theEvent);
7331 - (void)mouseExited: (NSEvent *)theEvent
7333   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7335   NSTRACE ("[EmacsView mouseExited:]");
7337   if (!hlinfo)
7338     return;
7340   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7341     = EV_TIMESTAMP (theEvent);
7343   if (emacsframe == hlinfo->mouse_face_mouse_frame)
7344     {
7345       clear_mouse_face (hlinfo);
7346       hlinfo->mouse_face_mouse_frame = 0;
7347     }
7351 - menuDown: sender
7353   NSTRACE ("[EmacsView menuDown:]");
7354   if (context_menu_value == -1)
7355     context_menu_value = [sender tag];
7356   else
7357     {
7358       NSInteger tag = [sender tag];
7359       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7360                                     emacsframe->menu_bar_vector,
7361                                     (void *)tag);
7362     }
7364   ns_send_appdefined (-1);
7365   return self;
7369 - (EmacsToolbar *)toolbar
7371   return toolbar;
7375 /* this gets called on toolbar button click */
7376 - toolbarClicked: (id)item
7378   NSEvent *theEvent;
7379   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7381   NSTRACE ("[EmacsView toolbarClicked:]");
7383   if (!emacs_event)
7384     return self;
7386   /* send first event (for some reason two needed) */
7387   theEvent = [[self window] currentEvent];
7388   emacs_event->kind = TOOL_BAR_EVENT;
7389   XSETFRAME (emacs_event->arg, emacsframe);
7390   EV_TRAILER (theEvent);
7392   emacs_event->kind = TOOL_BAR_EVENT;
7393 /*   XSETINT (emacs_event->code, 0); */
7394   emacs_event->arg = AREF (emacsframe->tool_bar_items,
7395                            idx + TOOL_BAR_ITEM_KEY);
7396   emacs_event->modifiers = EV_MODIFIERS (theEvent);
7397   EV_TRAILER (theEvent);
7398   return self;
7402 - toggleToolbar: (id)sender
7404   NSTRACE ("[EmacsView toggleToolbar:]");
7406   if (!emacs_event)
7407     return self;
7409   emacs_event->kind = NS_NONKEY_EVENT;
7410   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7411   EV_TRAILER ((id)nil);
7412   return self;
7416 - (void)drawRect: (NSRect)rect
7418   int x = NSMinX (rect), y = NSMinY (rect);
7419   int width = NSWidth (rect), height = NSHeight (rect);
7421   NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7422            NSTRACE_ARG_RECT(rect));
7424   if (!emacsframe || !emacsframe->output_data.ns)
7425     return;
7427   ns_clear_frame_area (emacsframe, x, y, width, height);
7428   block_input ();
7429   expose_frame (emacsframe, x, y, width, height);
7430   unblock_input ();
7432   /*
7433     drawRect: may be called (at least in OS X 10.5) for invisible
7434     views as well for some reason.  Thus, do not infer visibility
7435     here.
7437     emacsframe->async_visible = 1;
7438     emacsframe->async_iconified = 0;
7439   */
7443 /* NSDraggingDestination protocol methods.  Actually this is not really a
7444    protocol, but a category of Object.  O well...  */
7446 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7448   NSTRACE ("[EmacsView draggingEntered:]");
7449   return NSDragOperationGeneric;
7453 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7455   return YES;
7459 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7461   id pb;
7462   int x, y;
7463   NSString *type;
7464   NSEvent *theEvent = [[self window] currentEvent];
7465   NSPoint position;
7466   NSDragOperation op = [sender draggingSourceOperationMask];
7467   int modifiers = 0;
7469   NSTRACE ("[EmacsView performDragOperation:]");
7471   if (!emacs_event)
7472     return NO;
7474   position = [self convertPoint: [sender draggingLocation] fromView: nil];
7475   x = lrint (position.x);  y = lrint (position.y);
7477   pb = [sender draggingPasteboard];
7478   type = [pb availableTypeFromArray: ns_drag_types];
7480   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7481       // URL drags contain all operations (0xf), don't allow all to be set.
7482       (op & 0xf) != 0xf)
7483     {
7484       if (op & NSDragOperationLink)
7485         modifiers |= NSControlKeyMask;
7486       if (op & NSDragOperationCopy)
7487         modifiers |= NSAlternateKeyMask;
7488       if (op & NSDragOperationGeneric)
7489         modifiers |= NSCommandKeyMask;
7490     }
7492   modifiers = EV_MODIFIERS2 (modifiers);
7493   if (type == 0)
7494     {
7495       return NO;
7496     }
7497   else if ([type isEqualToString: NSFilenamesPboardType])
7498     {
7499       NSArray *files;
7500       NSEnumerator *fenum;
7501       NSString *file;
7503       if (!(files = [pb propertyListForType: type]))
7504         return NO;
7506       fenum = [files objectEnumerator];
7507       while ( (file = [fenum nextObject]) )
7508         {
7509           emacs_event->kind = DRAG_N_DROP_EVENT;
7510           XSETINT (emacs_event->x, x);
7511           XSETINT (emacs_event->y, y);
7512           ns_input_file = append2 (ns_input_file,
7513                                    build_string ([file UTF8String]));
7514           emacs_event->modifiers = modifiers;
7515           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
7516           EV_TRAILER (theEvent);
7517         }
7518       return YES;
7519     }
7520   else if ([type isEqualToString: NSURLPboardType])
7521     {
7522       NSURL *url = [NSURL URLFromPasteboard: pb];
7523       if (url == nil) return NO;
7525       emacs_event->kind = DRAG_N_DROP_EVENT;
7526       XSETINT (emacs_event->x, x);
7527       XSETINT (emacs_event->y, y);
7528       emacs_event->modifiers = modifiers;
7529       emacs_event->arg =  list2 (Qurl,
7530                                  build_string ([[url absoluteString]
7531                                                  UTF8String]));
7532       EV_TRAILER (theEvent);
7534       if ([url isFileURL] != NO)
7535         {
7536           NSString *file = [url path];
7537           ns_input_file = append2 (ns_input_file,
7538                                    build_string ([file UTF8String]));
7539         }
7540       return YES;
7541     }
7542   else if ([type isEqualToString: NSStringPboardType]
7543            || [type isEqualToString: NSTabularTextPboardType])
7544     {
7545       NSString *data;
7547       if (! (data = [pb stringForType: type]))
7548         return NO;
7550       emacs_event->kind = DRAG_N_DROP_EVENT;
7551       XSETINT (emacs_event->x, x);
7552       XSETINT (emacs_event->y, y);
7553       emacs_event->modifiers = modifiers;
7554       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7555       EV_TRAILER (theEvent);
7556       return YES;
7557     }
7558   else
7559     {
7560       fprintf (stderr, "Invalid data type in dragging pasteboard");
7561       return NO;
7562     }
7566 - (id) validRequestorForSendType: (NSString *)typeSent
7567                       returnType: (NSString *)typeReturned
7569   NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7570   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7571       && typeReturned == nil)
7572     {
7573       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7574         return self;
7575     }
7577   return [super validRequestorForSendType: typeSent
7578                                returnType: typeReturned];
7582 /* The next two methods are part of NSServicesRequests informal protocol,
7583    supposedly called when a services menu item is chosen from this app.
7584    But this should not happen because we override the services menu with our
7585    own entries which call ns-perform-service.
7586    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7587    So let's at least stub them out until further investigation can be done. */
7589 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7591   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7592      be written into the buffer in place of the existing selection..
7593      ordinary service calls go through functions defined in ns-win.el */
7594   return NO;
7597 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7599   NSArray *typesDeclared;
7600   Lisp_Object val;
7602   NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7604   /* We only support NSStringPboardType */
7605   if ([types containsObject:NSStringPboardType] == NO) {
7606     return NO;
7607   }
7609   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7610   if (CONSP (val) && SYMBOLP (XCAR (val)))
7611     {
7612       val = XCDR (val);
7613       if (CONSP (val) && NILP (XCDR (val)))
7614         val = XCAR (val);
7615     }
7616   if (! STRINGP (val))
7617     return NO;
7619   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7620   [pb declareTypes:typesDeclared owner:nil];
7621   ns_string_to_pasteboard (pb, val);
7622   return YES;
7626 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7627    (gives a miniaturized version of the window); currently we use the latter for
7628    frames whose active buffer doesn't correspond to any file
7629    (e.g., '*scratch*') */
7630 - setMiniwindowImage: (BOOL) setMini
7632   id image = [[self window] miniwindowImage];
7633   NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7635   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7636      about "AppleDockIconEnabled" notwithstanding, however the set message
7637      below has its effect nonetheless. */
7638   if (image != emacsframe->output_data.ns->miniimage)
7639     {
7640       if (image && [image isKindOfClass: [EmacsImage class]])
7641         [image release];
7642       [[self window] setMiniwindowImage:
7643                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7644     }
7646   return self;
7650 - (void) setRows: (int) r andColumns: (int) c
7652   NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7653   rows = r;
7654   cols = c;
7657 - (int) fullscreenState
7659   return fs_state;
7662 @end  /* EmacsView */
7666 /* ==========================================================================
7668     EmacsWindow implementation
7670    ========================================================================== */
7672 @implementation EmacsWindow
7674 #ifdef NS_IMPL_COCOA
7675 - (id)accessibilityAttributeValue:(NSString *)attribute
7677   Lisp_Object str = Qnil;
7678   struct frame *f = SELECTED_FRAME ();
7679   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7681   NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7683   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7684     return NSAccessibilityTextFieldRole;
7686   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7687       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7688     {
7689       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7690     }
7691   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7692     {
7693       if (! NILP (BVAR (curbuf, mark_active)))
7694           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7696       if (NILP (str))
7697         {
7698           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7699           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7700           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7702           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7703             str = make_uninit_multibyte_string (range, byte_range);
7704           else
7705             str = make_uninit_string (range);
7706           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7707              Is this a problem?  */
7708           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7709         }
7710     }
7713   if (! NILP (str))
7714     {
7715       if (CONSP (str) && SYMBOLP (XCAR (str)))
7716         {
7717           str = XCDR (str);
7718           if (CONSP (str) && NILP (XCDR (str)))
7719             str = XCAR (str);
7720         }
7721       if (STRINGP (str))
7722         {
7723           const char *utfStr = SSDATA (str);
7724           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7725           return nsStr;
7726         }
7727     }
7729   return [super accessibilityAttributeValue:attribute];
7731 #endif /* NS_IMPL_COCOA */
7733 /* Constrain size and placement of a frame.
7735    By returning the original "frameRect", the frame is not
7736    constrained. This can lead to unwanted situations where, for
7737    example, the menu bar covers the frame.
7739    The default implementation (accessed using "super") constrains the
7740    frame to the visible area of SCREEN, minus the menu bar (if
7741    present) and the Dock.  Note that default implementation also calls
7742    windowWillResize, with the frame it thinks should have.  (This can
7743    make the frame exit maximized mode.)
7745    Note that this should work in situations where multiple monitors
7746    are present.  Common configurations are side-by-side monitors and a
7747    monitor on top of another (e.g. when a laptop is placed under a
7748    large screen). */
7749 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7751   NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7752              NSTRACE_ARG_RECT (frameRect));
7754 #ifdef NS_IMPL_COCOA
7755 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7756   // If separate spaces is on, it is like each screen is independent.  There is
7757   // no spanning of frames across screens.
7758   if ([NSScreen screensHaveSeparateSpaces])
7759     {
7760       NSTRACE_MSG ("Screens have separate spaces");
7761       frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7762       NSTRACE_RETURN_RECT (frameRect);
7763       return frameRect;
7764     }
7765 #endif
7766 #endif
7768   return constrain_frame_rect(frameRect);
7772 - (void)performZoom:(id)sender
7774   NSTRACE ("[EmacsWindow performZoom:]");
7776   return [super performZoom:sender];
7779 - (void)zoom:(id)sender
7781   struct frame * f = SELECTED_FRAME ();
7783   NSTRACE ("[EmacsWindow zoom:]");
7785   ns_update_auto_hide_menu_bar();
7787   // Below are three zoom implementations.  In the final commit, the
7788   // idea is that the last should be included.
7790 #if 0
7791   // Native zoom done using the standard zoom animation.  Size of the
7792   // resulting frame reduced to accommodate the Dock and, if present,
7793   // the menu-bar.
7794   [super zoom:sender];
7796 #elsif 0
7797   // Native zoom done using the standard zoom animation, plus an
7798   // explicit resize to cover the full screen.
7799   [super zoom:sender];
7801   // After the native zoom, resize the resulting frame to fill the
7802   // entire screen, except the menu-bar.
7803   //
7804   // This works for all practical purposes.  (The only minor oddity is
7805   // when transiting from full-height frame to a maximized, the
7806   // animation reduces the height of the frame slightly (to the 4
7807   // pixels needed to accommodate the Doc) before it snaps back into
7808   // full height.  The user would need a very trained eye to spot
7809   // this.)
7810   NSScreen * screen = [self screen];
7811   if (screen != nil)
7812     {
7813       int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7815       NSTRACE_FSTYPE ("fullscreenState", fs_state);
7817       NSRect sr = [screen frame];
7818       NSRect wr = [self frame];
7819       NSTRACE_RECT ("Rect after zoom", wr);
7821       NSRect newWr = wr;
7823       if (fs_state == FULLSCREEN_MAXIMIZED
7824           || fs_state == FULLSCREEN_HEIGHT)
7825         {
7826           newWr.origin.x = 0;
7827           newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7828         }
7830       if (fs_state == FULLSCREEN_MAXIMIZED
7831           || fs_state == FULLSCREEN_WIDTH)
7832         {
7833           newWr.origin.y = 0;
7834           newWr.size.width = sr.size.width;
7835         }
7837       if (newWr.size.width     != wr.size.width
7838           || newWr.size.height != wr.size.height
7839           || newWr.origin.x    != wr.origin.x
7840           || newWr.origin.y    != wr.origin.y)
7841         {
7842           NSTRACE_MSG ("New frame different");
7843           [self setFrame: newWr display: NO];
7844         }
7845     }
7846 #else
7847   // Non-native zoom which is done instantaneously.  The resulting frame
7848   // covers the entire screen, except the menu-bar, if present.
7849   NSScreen * screen = [self screen];
7850   if (screen != nil)
7851     {
7852       NSRect sr = [screen frame];
7853       sr.size.height -= ns_menu_bar_height (screen);
7855       sr = [[self delegate] windowWillUseStandardFrame:self
7856                                           defaultFrame:sr];
7857       [self setFrame: sr display: NO];
7858     }
7859 #endif
7862 - (void)setFrame:(NSRect)windowFrame
7863          display:(BOOL)displayViews
7865   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7866            NSTRACE_ARG_RECT (windowFrame), displayViews);
7868   [super setFrame:windowFrame display:displayViews];
7871 - (void)setFrame:(NSRect)windowFrame
7872          display:(BOOL)displayViews
7873          animate:(BOOL)performAnimation
7875   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7876            " display:%d performAnimation:%d]",
7877            NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7879   [super setFrame:windowFrame display:displayViews animate:performAnimation];
7882 - (void)setFrameTopLeftPoint:(NSPoint)point
7884   NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7885            NSTRACE_ARG_POINT (point));
7887   [super setFrameTopLeftPoint:point];
7889 @end /* EmacsWindow */
7892 @implementation EmacsFSWindow
7894 - (BOOL)canBecomeKeyWindow
7896   return YES;
7899 - (BOOL)canBecomeMainWindow
7901   return YES;
7904 @end
7906 /* ==========================================================================
7908     EmacsScroller implementation
7910    ========================================================================== */
7913 @implementation EmacsScroller
7915 /* for repeat button push */
7916 #define SCROLL_BAR_FIRST_DELAY 0.5
7917 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7919 + (CGFloat) scrollerWidth
7921   /* TODO: if we want to allow variable widths, this is the place to do it,
7922            however neither GNUstep nor Cocoa support it very well */
7923   CGFloat r;
7924 #if !defined (NS_IMPL_COCOA) || \
7925   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7926   r = [NSScroller scrollerWidth];
7927 #else
7928   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7929                                 scrollerStyle: NSScrollerStyleLegacy];
7930 #endif
7931   return r;
7935 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7937   NSTRACE ("[EmacsScroller initFrame: window:]");
7939   r.size.width = [EmacsScroller scrollerWidth];
7940   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7941   [self setContinuous: YES];
7942   [self setEnabled: YES];
7944   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7945      locked against the top and bottom edges, and right edge on OS X, where
7946      scrollers are on right. */
7947 #ifdef NS_IMPL_GNUSTEP
7948   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7949 #else
7950   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7951 #endif
7953   window = XWINDOW (nwin);
7954   condemned = NO;
7955   pixel_height = NSHeight (r);
7956   if (pixel_height == 0) pixel_height = 1;
7957   min_portion = 20 / pixel_height;
7959   frame = XFRAME (window->frame);
7960   if (FRAME_LIVE_P (frame))
7961     {
7962       int i;
7963       EmacsView *view = FRAME_NS_VIEW (frame);
7964       NSView *sview = [[view window] contentView];
7965       NSArray *subs = [sview subviews];
7967       /* disable optimization stopping redraw of other scrollbars */
7968       view->scrollbarsNeedingUpdate = 0;
7969       for (i =[subs count]-1; i >= 0; i--)
7970         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7971           view->scrollbarsNeedingUpdate++;
7972       [sview addSubview: self];
7973     }
7975 /*  [self setFrame: r]; */
7977   return self;
7981 - (void)setFrame: (NSRect)newRect
7983   NSTRACE ("[EmacsScroller setFrame:]");
7985 /*  block_input (); */
7986   pixel_height = NSHeight (newRect);
7987   if (pixel_height == 0) pixel_height = 1;
7988   min_portion = 20 / pixel_height;
7989   [super setFrame: newRect];
7990 /*  unblock_input (); */
7994 - (void)dealloc
7996   NSTRACE ("[EmacsScroller dealloc]");
7997   if (window)
7998     wset_vertical_scroll_bar (window, Qnil);
7999   window = 0;
8000   [super dealloc];
8004 - condemn
8006   NSTRACE ("[EmacsScroller condemn]");
8007   condemned =YES;
8008   return self;
8012 - reprieve
8014   NSTRACE ("[EmacsScroller reprieve]");
8015   condemned =NO;
8016   return self;
8020 -(bool)judge
8022   NSTRACE ("[EmacsScroller judge]");
8023   bool ret = condemned;
8024   if (condemned)
8025     {
8026       EmacsView *view;
8027       block_input ();
8028       /* ensure other scrollbar updates after deletion */
8029       view = (EmacsView *)FRAME_NS_VIEW (frame);
8030       if (view != nil)
8031         view->scrollbarsNeedingUpdate++;
8032       if (window)
8033         wset_vertical_scroll_bar (window, Qnil);
8034       window = 0;
8035       [self removeFromSuperview];
8036       [self release];
8037       unblock_input ();
8038     }
8039   return ret;
8043 - (void)resetCursorRects
8045   NSRect visible = [self visibleRect];
8046   NSTRACE ("[EmacsScroller resetCursorRects]");
8048   if (!NSIsEmptyRect (visible))
8049     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8050   [[NSCursor arrowCursor] setOnMouseEntered: YES];
8054 - (int) checkSamePosition: (int) position portion: (int) portion
8055                     whole: (int) whole
8057   return em_position ==position && em_portion ==portion && em_whole ==whole
8058     && portion != whole; /* needed for resize empty buf */
8062 - setPosition: (int)position portion: (int)portion whole: (int)whole
8064   NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8066   em_position = position;
8067   em_portion = portion;
8068   em_whole = whole;
8070   if (portion >= whole)
8071     {
8072 #ifdef NS_IMPL_COCOA
8073       [self setKnobProportion: 1.0];
8074       [self setDoubleValue: 1.0];
8075 #else
8076       [self setFloatValue: 0.0 knobProportion: 1.0];
8077 #endif
8078     }
8079   else
8080     {
8081       float pos;
8082       CGFloat por;
8083       portion = max ((float)whole*min_portion/pixel_height, portion);
8084       pos = (float)position / (whole - portion);
8085       por = (CGFloat)portion/whole;
8086 #ifdef NS_IMPL_COCOA
8087       [self setKnobProportion: por];
8088       [self setDoubleValue: pos];
8089 #else
8090       [self setFloatValue: pos knobProportion: por];
8091 #endif
8092     }
8094   return self;
8097 /* set up emacs_event */
8098 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8100   Lisp_Object win;
8102   NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8104   if (!emacs_event)
8105     return;
8107   emacs_event->part = last_hit_part;
8108   emacs_event->code = 0;
8109   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8110   XSETWINDOW (win, window);
8111   emacs_event->frame_or_window = win;
8112   emacs_event->timestamp = EV_TIMESTAMP (e);
8113   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8114   emacs_event->arg = Qnil;
8115   XSETINT (emacs_event->x, loc * pixel_height);
8116   XSETINT (emacs_event->y, pixel_height-20);
8118   if (q_event_ptr)
8119     {
8120       n_emacs_events_pending++;
8121       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8122     }
8123   else
8124     hold_event (emacs_event);
8125   EVENT_INIT (*emacs_event);
8126   ns_send_appdefined (-1);
8130 /* called manually thru timer to implement repeated button action w/hold-down */
8131 - repeatScroll: (NSTimer *)scrollEntry
8133   NSEvent *e = [[self window] currentEvent];
8134   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
8135   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8137   NSTRACE ("[EmacsScroller repeatScroll:]");
8139   /* clear timer if need be */
8140   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8141     {
8142         [scroll_repeat_entry invalidate];
8143         [scroll_repeat_entry release];
8144         scroll_repeat_entry = nil;
8146         if (inKnob)
8147           return self;
8149         scroll_repeat_entry
8150           = [[NSTimer scheduledTimerWithTimeInterval:
8151                         SCROLL_BAR_CONTINUOUS_DELAY
8152                                             target: self
8153                                           selector: @selector (repeatScroll:)
8154                                           userInfo: 0
8155                                            repeats: YES]
8156               retain];
8157     }
8159   [self sendScrollEventAtLoc: 0 fromEvent: e];
8160   return self;
8164 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
8165    mouseDragged events without going into a modal loop. */
8166 - (void)mouseDown: (NSEvent *)e
8168   NSRect sr, kr;
8169   /* hitPart is only updated AFTER event is passed on */
8170   NSScrollerPart part = [self testPart: [e locationInWindow]];
8171   CGFloat inc = 0.0, loc, kloc, pos;
8172   int edge = 0;
8174   NSTRACE ("[EmacsScroller mouseDown:]");
8176   switch (part)
8177     {
8178     case NSScrollerDecrementPage:
8179         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8180     case NSScrollerIncrementPage:
8181         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8182     case NSScrollerDecrementLine:
8183       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8184     case NSScrollerIncrementLine:
8185       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8186     case NSScrollerKnob:
8187       last_hit_part = scroll_bar_handle; break;
8188     case NSScrollerKnobSlot:  /* GNUstep-only */
8189       last_hit_part = scroll_bar_move_ratio; break;
8190     default:  /* NSScrollerNoPart? */
8191       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8192                (long) part);
8193       return;
8194     }
8196   if (inc != 0.0)
8197     {
8198       pos = 0;      /* ignored */
8200       /* set a timer to repeat, as we can't let superclass do this modally */
8201       scroll_repeat_entry
8202         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8203                                             target: self
8204                                           selector: @selector (repeatScroll:)
8205                                           userInfo: 0
8206                                            repeats: YES]
8207             retain];
8208     }
8209   else
8210     {
8211       /* handle, or on GNUstep possibly slot */
8212       NSEvent *fake_event;
8214       /* compute float loc in slot and mouse offset on knob */
8215       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8216                       toView: nil];
8217       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8218       if (loc <= 0.0)
8219         {
8220           loc = 0.0;
8221           edge = -1;
8222         }
8223       else if (loc >= NSHeight (sr))
8224         {
8225           loc = NSHeight (sr);
8226           edge = 1;
8227         }
8229       if (edge)
8230         kloc = 0.5 * edge;
8231       else
8232         {
8233           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8234                           toView: nil];
8235           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8236         }
8237       last_mouse_offset = kloc;
8239       /* if knob, tell emacs a location offset by knob pos
8240          (to indicate top of handle) */
8241       if (part == NSScrollerKnob)
8242           pos = (loc - last_mouse_offset) / NSHeight (sr);
8243       else
8244         /* else this is a slot click on GNUstep: go straight there */
8245         pos = loc / NSHeight (sr);
8247       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8248       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8249                                       location: [e locationInWindow]
8250                                  modifierFlags: [e modifierFlags]
8251                                      timestamp: [e timestamp]
8252                                   windowNumber: [e windowNumber]
8253                                        context: [e context]
8254                                    eventNumber: [e eventNumber]
8255                                     clickCount: [e clickCount]
8256                                       pressure: [e pressure]];
8257       [super mouseUp: fake_event];
8258     }
8260   if (part != NSScrollerKnob)
8261     [self sendScrollEventAtLoc: pos fromEvent: e];
8265 /* Called as we manually track scroller drags, rather than superclass. */
8266 - (void)mouseDragged: (NSEvent *)e
8268     NSRect sr;
8269     double loc, pos;
8271     NSTRACE ("[EmacsScroller mouseDragged:]");
8273       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8274                       toView: nil];
8275       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8277       if (loc <= 0.0)
8278         {
8279           loc = 0.0;
8280         }
8281       else if (loc >= NSHeight (sr) + last_mouse_offset)
8282         {
8283           loc = NSHeight (sr) + last_mouse_offset;
8284         }
8286       pos = (loc - last_mouse_offset) / NSHeight (sr);
8287       [self sendScrollEventAtLoc: pos fromEvent: e];
8291 - (void)mouseUp: (NSEvent *)e
8293   NSTRACE ("[EmacsScroller mouseUp:]");
8295   if (scroll_repeat_entry)
8296     {
8297       [scroll_repeat_entry invalidate];
8298       [scroll_repeat_entry release];
8299       scroll_repeat_entry = nil;
8300     }
8301   last_hit_part = scroll_bar_above_handle;
8305 /* treat scrollwheel events in the bar as though they were in the main window */
8306 - (void) scrollWheel: (NSEvent *)theEvent
8308   NSTRACE ("[EmacsScroller scrollWheel:]");
8310   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8311   [view mouseDown: theEvent];
8314 @end  /* EmacsScroller */
8317 #ifdef NS_IMPL_GNUSTEP
8318 /* Dummy class to get rid of startup warnings.  */
8319 @implementation EmacsDocument
8321 @end
8322 #endif
8325 /* ==========================================================================
8327    Font-related functions; these used to be in nsfaces.m
8329    ========================================================================== */
8332 Lisp_Object
8333 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8335   struct font *font = XFONT_OBJECT (font_object);
8336   EmacsView *view = FRAME_NS_VIEW (f);
8337   int font_ascent, font_descent;
8339   if (fontset < 0)
8340     fontset = fontset_from_font (font_object);
8341   FRAME_FONTSET (f) = fontset;
8343   if (FRAME_FONT (f) == font)
8344     /* This font is already set in frame F.  There's nothing more to
8345        do.  */
8346     return font_object;
8348   FRAME_FONT (f) = font;
8350   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8351   FRAME_COLUMN_WIDTH (f) = font->average_width;
8352   get_font_ascent_descent (font, &font_ascent, &font_descent);
8353   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8355   /* Compute the scroll bar width in character columns.  */
8356   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8357     {
8358       int wid = FRAME_COLUMN_WIDTH (f);
8359       FRAME_CONFIG_SCROLL_BAR_COLS (f)
8360         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8361     }
8362   else
8363     {
8364       int wid = FRAME_COLUMN_WIDTH (f);
8365       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8366     }
8368   /* Compute the scroll bar height in character lines.  */
8369   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8370     {
8371       int height = FRAME_LINE_HEIGHT (f);
8372       FRAME_CONFIG_SCROLL_BAR_LINES (f)
8373         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8374     }
8375   else
8376     {
8377       int height = FRAME_LINE_HEIGHT (f);
8378       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8379     }
8381   /* Now make the frame display the given font.  */
8382   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8383     adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8384                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8385                        false, Qfont);
8387   return font_object;
8391 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8392 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8393          in 1.43. */
8395 const char *
8396 ns_xlfd_to_fontname (const char *xlfd)
8397 /* --------------------------------------------------------------------------
8398     Convert an X font name (XLFD) to an NS font name.
8399     Only family is used.
8400     The string returned is temporarily allocated.
8401    -------------------------------------------------------------------------- */
8403   char *name = xmalloc (180);
8404   int i, len;
8405   const char *ret;
8407   if (!strncmp (xlfd, "--", 2))
8408     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8409   else
8410     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8412   /* stopgap for malformed XLFD input */
8413   if (strlen (name) == 0)
8414     strcpy (name, "Monaco");
8416   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8417      also uppercase after '-' or ' ' */
8418   name[0] = c_toupper (name[0]);
8419   for (len =strlen (name), i =0; i<len; i++)
8420     {
8421       if (name[i] == '$')
8422         {
8423           name[i] = '-';
8424           if (i+1<len)
8425             name[i+1] = c_toupper (name[i+1]);
8426         }
8427       else if (name[i] == '_')
8428         {
8429           name[i] = ' ';
8430           if (i+1<len)
8431             name[i+1] = c_toupper (name[i+1]);
8432         }
8433     }
8434 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
8435   ret = [[NSString stringWithUTF8String: name] UTF8String];
8436   xfree (name);
8437   return ret;
8441 void
8442 syms_of_nsterm (void)
8444   NSTRACE ("syms_of_nsterm");
8446   ns_antialias_threshold = 10.0;
8448   /* from 23+ we need to tell emacs what modifiers there are.. */
8449   DEFSYM (Qmodifier_value, "modifier-value");
8450   DEFSYM (Qalt, "alt");
8451   DEFSYM (Qhyper, "hyper");
8452   DEFSYM (Qmeta, "meta");
8453   DEFSYM (Qsuper, "super");
8454   DEFSYM (Qcontrol, "control");
8455   DEFSYM (QUTF8_STRING, "UTF8_STRING");
8457   DEFSYM (Qfile, "file");
8458   DEFSYM (Qurl, "url");
8460   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8461   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8462   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8463   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8464   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8466   DEFVAR_LISP ("ns-input-file", ns_input_file,
8467               "The file specified in the last NS event.");
8468   ns_input_file =Qnil;
8470   DEFVAR_LISP ("ns-working-text", ns_working_text,
8471               "String for visualizing working composition sequence.");
8472   ns_working_text =Qnil;
8474   DEFVAR_LISP ("ns-input-font", ns_input_font,
8475               "The font specified in the last NS event.");
8476   ns_input_font =Qnil;
8478   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8479               "The fontsize specified in the last NS event.");
8480   ns_input_fontsize =Qnil;
8482   DEFVAR_LISP ("ns-input-line", ns_input_line,
8483                "The line specified in the last NS event.");
8484   ns_input_line =Qnil;
8486   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8487                "The service name specified in the last NS event.");
8488   ns_input_spi_name =Qnil;
8490   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8491                "The service argument specified in the last NS event.");
8492   ns_input_spi_arg =Qnil;
8494   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8495                "This variable describes the behavior of the alternate or option key.\n\
8496 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8497 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8498 at all, allowing it to be used at a lower level for accented character entry.");
8499   ns_alternate_modifier = Qmeta;
8501   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8502                "This variable describes the behavior of the right alternate or option key.\n\
8503 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8504 Set to left means be the same key as `ns-alternate-modifier'.\n\
8505 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8506 at all, allowing it to be used at a lower level for accented character entry.");
8507   ns_right_alternate_modifier = Qleft;
8509   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8510                "This variable describes the behavior of the command key.\n\
8511 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8512   ns_command_modifier = Qsuper;
8514   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8515                "This variable describes the behavior of the right command key.\n\
8516 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8517 Set to left means be the same key as `ns-command-modifier'.\n\
8518 Set to none means that the command / option key is not interpreted by Emacs\n\
8519 at all, allowing it to be used at a lower level for accented character entry.");
8520   ns_right_command_modifier = Qleft;
8522   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8523                "This variable describes the behavior of the control key.\n\
8524 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8525   ns_control_modifier = Qcontrol;
8527   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8528                "This variable describes the behavior of the right control key.\n\
8529 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8530 Set to left means be the same key as `ns-control-modifier'.\n\
8531 Set to none means that the control / option key is not interpreted by Emacs\n\
8532 at all, allowing it to be used at a lower level for accented character entry.");
8533   ns_right_control_modifier = Qleft;
8535   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8536                "This variable describes the behavior of the function key (on laptops).\n\
8537 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8538 Set to none means that the function key is not interpreted by Emacs at all,\n\
8539 allowing it to be used at a lower level for accented character entry.");
8540   ns_function_modifier = Qnone;
8542   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8543                "Non-nil (the default) means to render text antialiased.");
8544   ns_antialias_text = Qt;
8546   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8547                "Whether to confirm application quit using dialog.");
8548   ns_confirm_quit = Qnil;
8550   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8551                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8552 Only works on OSX 10.6 or later.  */);
8553   ns_auto_hide_menu_bar = Qnil;
8555   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8556      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8557 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
8558 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
8559 Default is t for OSX >= 10.7, nil otherwise.  */);
8560 #ifdef HAVE_NATIVE_FS
8561   ns_use_native_fullscreen = YES;
8562 #else
8563   ns_use_native_fullscreen = NO;
8564 #endif
8565   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8567   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8568      doc: /*Non-nil means use animation on non-native fullscreen.
8569 For native fullscreen, this does nothing.
8570 Default is nil.  */);
8571   ns_use_fullscreen_animation = NO;
8573   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8574      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8575 Note that this does not apply to images.
8576 This variable is ignored on OSX < 10.7 and GNUstep.  */);
8577   ns_use_srgb_colorspace = YES;
8579   /* TODO: move to common code */
8580   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8581                doc: /* Which toolkit scroll bars Emacs uses, if any.
8582 A value of nil means Emacs doesn't use toolkit scroll bars.
8583 With the X Window system, the value is a symbol describing the
8584 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
8585 With MS Windows or Nextstep, the value is t.  */);
8586   Vx_toolkit_scroll_bars = Qt;
8588   DEFVAR_BOOL ("x-use-underline-position-properties",
8589                x_use_underline_position_properties,
8590      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8591 A value of nil means ignore them.  If you encounter fonts with bogus
8592 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8593 to 4.1, set this to nil. */);
8594   x_use_underline_position_properties = 0;
8596   DEFVAR_BOOL ("x-underline-at-descent-line",
8597                x_underline_at_descent_line,
8598      doc: /* Non-nil means to draw the underline at the same place as the descent line.
8599 A value of nil means to draw the underline according to the value of the
8600 variable `x-use-underline-position-properties', which is usually at the
8601 baseline level.  The default value is nil.  */);
8602   x_underline_at_descent_line = 0;
8604   /* Tell Emacs about this window system.  */
8605   Fprovide (Qns, Qnil);
8607   DEFSYM (Qcocoa, "cocoa");
8608   DEFSYM (Qgnustep, "gnustep");
8610 #ifdef NS_IMPL_COCOA
8611   Fprovide (Qcocoa, Qnil);
8612   syms_of_macfont ();
8613 #else
8614   Fprovide (Qgnustep, Qnil);
8615   syms_of_nsfont ();
8616 #endif