Mention web bugs
[emacs.git] / src / nsterm.m
blobf77aadba67c59712b69d3fc82f23031876fe8ccb
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    Note: Don't use this when fullscreen is enabled -- the screen
643    sometimes includes, sometimes excludes the menu bar area. */
645   CGFloat res;
647   if (ns_menu_bar_should_be_hidden())
648     {
649       res = 0;
650     }
651   else
652     {
653       NSRect screenFrame = [screen frame];
654       NSRect screenVisibleFrame = [screen visibleFrame];
656       CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
657       CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
658                                  + screenVisibleFrame.size.height);
660       res = frameTop - visibleFrameTop;
662     }
664   NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
666   return res;
670 /* ==========================================================================
672     Focus (clipping) and screen update
674    ========================================================================== */
677 // Window constraining
678 // -------------------
680 // To ensure that the windows are not placed under the menu bar, they
681 // are typically moved by the call-back constrainFrameRect. However,
682 // by overriding it, it's possible to inhibit this, leaving the window
683 // in it's original position.
685 // It's possible to hide the menu bar. However, technically, it's only
686 // possible to hide it when the application is active. To ensure that
687 // this work properly, the menu bar and window constraining are
688 // deferred until the application becomes active.
690 // Even though it's not possible to manually move a window above the
691 // top of the screen, it is allowed if it's done programmatically,
692 // when the menu is hidden. This allows the editable area to cover the
693 // full screen height.
695 // Test cases
696 // ----------
698 // Use the following extra files:
700 //    init.el:
701 //       ;; Hide menu and place frame slightly above the top of the screen.
702 //       (setq ns-auto-hide-menu-bar t)
703 //       (set-frame-position (selected-frame) 0 -20)
705 // Test 1:
707 //    emacs -Q -l init.el
709 //    Result: No menu bar, and the title bar should be above the screen.
711 // Test 2:
713 //    emacs -Q
715 //    Result: Menu bar visible, frame placed immediately below the menu.
718 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
720   NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
721              NSTRACE_ARG_RECT (frameRect));
723   // --------------------
724   // Collect information about the screen the frame is covering.
725   //
727   NSArray *screens = [NSScreen screens];
728   NSUInteger nr_screens = [screens count];
730   int i;
732   // The height of the menu bar, if present in any screen the frame is
733   // displayed in.
734   int menu_bar_height = 0;
736   // A rectangle covering all the screen the frame is displayed in.
737   NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
738   for (i = 0; i < nr_screens; ++i )
739     {
740       NSScreen *s = [screens objectAtIndex: i];
741       NSRect scrRect = [s frame];
743       NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
744                    i, NSTRACE_ARG_RECT (scrRect));
746       if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
747         {
748           multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
750           if (!isFullscreen)
751             {
752               CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
753               menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
754             }
755         }
756     }
758   NSTRACE_RECT ("multiscreenRect", multiscreenRect);
760   NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
762   if (multiscreenRect.size.width == 0
763       || multiscreenRect.size.height == 0)
764     {
765       // Failed to find any monitor, give up.
766       NSTRACE_MSG ("multiscreenRect empty");
767       NSTRACE_RETURN_RECT (frameRect);
768       return frameRect;
769     }
772   // --------------------
773   // Find a suitable placement.
774   //
776   if (ns_menu_bar_should_be_hidden())
777     {
778       // When the menu bar is hidden, the user may place part of the
779       // frame above the top of the screen, for example to hide the
780       // title bar.
781       //
782       // Hence, keep the original position.
783     }
784   else
785     {
786       // Ensure that the frame is below the menu bar, or below the top
787       // of the screen.
788       //
789       // This assume that the menu bar is placed at the top in the
790       // rectangle that covers the monitors.  (It doesn't have to be,
791       // but if it's not it's hard to do anything useful.)
792       CGFloat topOfWorkArea = (multiscreenRect.origin.y
793                                + multiscreenRect.size.height
794                                - menu_bar_height);
796       CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
797       if (topOfFrame > topOfWorkArea)
798         {
799           frameRect.origin.y -= topOfFrame - topOfWorkArea;
800           NSTRACE_RECT ("After placement adjust", frameRect);
801         }
802     }
804   // Include the following section to restrict frame to the screens.
805   // (If so, update it to allow the frame to stretch down below the
806   // screen.)
807 #if 0
808   // --------------------
809   // Ensure frame doesn't stretch below the screens.
810   //
812   CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
814   if (diff > 0)
815     {
816       frameRect.origin.y = multiscreenRect.origin.y;
817       frameRect.size.height -= diff;
818     }
819 #endif
821   NSTRACE_RETURN_RECT (frameRect);
822   return frameRect;
826 static void
827 ns_constrain_all_frames (void)
828 /* --------------------------------------------------------------------------
829      Ensure that the menu bar doesn't cover any frames.
830    -------------------------------------------------------------------------- */
832   Lisp_Object tail, frame;
834   NSTRACE ("ns_constrain_all_frames");
836   block_input ();
838   FOR_EACH_FRAME (tail, frame)
839     {
840       struct frame *f = XFRAME (frame);
841       if (FRAME_NS_P (f))
842         {
843           EmacsView *view = FRAME_NS_VIEW (f);
845           if (![view isFullscreen])
846             {
847               [[view window]
848                 setFrame:constrain_frame_rect([[view window] frame], false)
849                  display:NO];
850             }
851         }
852     }
854   unblock_input ();
858 static void
859 ns_update_auto_hide_menu_bar (void)
860 /* --------------------------------------------------------------------------
861      Show or hide the menu bar, based on user setting.
862    -------------------------------------------------------------------------- */
864 #ifdef NS_IMPL_COCOA
865   NSTRACE ("ns_update_auto_hide_menu_bar");
867   block_input ();
869   if (NSApp != nil && [NSApp isActive])
870     {
871       // Note, "setPresentationOptions" triggers an error unless the
872       // application is active.
873       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
875       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
876         {
877           NSApplicationPresentationOptions options
878             = NSApplicationPresentationDefault;
880           if (menu_bar_should_be_hidden)
881             options |= NSApplicationPresentationAutoHideMenuBar
882               | NSApplicationPresentationAutoHideDock;
884           [NSApp setPresentationOptions: options];
886           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
888           if (!ns_menu_bar_is_hidden)
889             {
890               ns_constrain_all_frames ();
891             }
892         }
893     }
895   unblock_input ();
896 #endif
900 static void
901 ns_update_begin (struct frame *f)
902 /* --------------------------------------------------------------------------
903    Prepare for a grouped sequence of drawing calls
904    external (RIF) call; whole frame, called before update_window_begin
905    -------------------------------------------------------------------------- */
907   EmacsView *view = FRAME_NS_VIEW (f);
908   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
910   ns_update_auto_hide_menu_bar ();
912 #ifdef NS_IMPL_COCOA
913   if ([view isFullscreen] && [view fsIsNative])
914   {
915     // Fix reappearing tool bar in fullscreen for OSX 10.7
916     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
917     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
918     if (! tbar_visible != ! [toolbar isVisible])
919       [toolbar setVisible: tbar_visible];
920   }
921 #endif
923   ns_updating_frame = f;
924   [view lockFocus];
926   /* drawRect may have been called for say the minibuffer, and then clip path
927      is for the minibuffer.  But the display engine may draw more because
928      we have set the frame as garbaged.  So reset clip path to the whole
929      view.  */
930 #ifdef NS_IMPL_COCOA
931   {
932     NSBezierPath *bp;
933     NSRect r = [view frame];
934     NSRect cr = [[view window] frame];
935     /* If a large frame size is set, r may be larger than the window frame
936        before constrained.  In that case don't change the clip path, as we
937        will clear in to the tool bar and title bar.  */
938     if (r.size.height
939         + FRAME_NS_TITLEBAR_HEIGHT (f)
940         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
941       {
942         bp = [[NSBezierPath bezierPathWithRect: r] retain];
943         [bp setClip];
944         [bp release];
945       }
946   }
947 #endif
949 #ifdef NS_IMPL_GNUSTEP
950   uRect = NSMakeRect (0, 0, 0, 0);
951 #endif
955 static void
956 ns_update_window_begin (struct window *w)
957 /* --------------------------------------------------------------------------
958    Prepare for a grouped sequence of drawing calls
959    external (RIF) call; for one window, called after update_begin
960    -------------------------------------------------------------------------- */
962   struct frame *f = XFRAME (WINDOW_FRAME (w));
963   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
965   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
966   w->output_cursor = w->cursor;
968   block_input ();
970   if (f == hlinfo->mouse_face_mouse_frame)
971     {
972       /* Don't do highlighting for mouse motion during the update.  */
973       hlinfo->mouse_face_defer = 1;
975         /* If the frame needs to be redrawn,
976            simply forget about any prior mouse highlighting.  */
977       if (FRAME_GARBAGED_P (f))
978         hlinfo->mouse_face_window = Qnil;
980       /* (further code for mouse faces ifdef'd out in other terms elided) */
981     }
983   unblock_input ();
987 static void
988 ns_update_window_end (struct window *w, bool cursor_on_p,
989                       bool mouse_face_overwritten_p)
990 /* --------------------------------------------------------------------------
991    Finished a grouped sequence of drawing calls
992    external (RIF) call; for one window called before update_end
993    -------------------------------------------------------------------------- */
995   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
997   /* note: this fn is nearly identical in all terms */
998   if (!w->pseudo_window_p)
999     {
1000       block_input ();
1002       if (cursor_on_p)
1003         display_and_set_cursor (w, 1,
1004                                 w->output_cursor.hpos, w->output_cursor.vpos,
1005                                 w->output_cursor.x, w->output_cursor.y);
1007       if (draw_window_fringes (w, 1))
1008         {
1009           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1010             x_draw_right_divider (w);
1011           else
1012             x_draw_vertical_border (w);
1013         }
1015       unblock_input ();
1016     }
1018   /* If a row with mouse-face was overwritten, arrange for
1019      frame_up_to_date to redisplay the mouse highlight.  */
1020   if (mouse_face_overwritten_p)
1021     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1025 static void
1026 ns_update_end (struct frame *f)
1027 /* --------------------------------------------------------------------------
1028    Finished a grouped sequence of drawing calls
1029    external (RIF) call; for whole frame, called after update_window_end
1030    -------------------------------------------------------------------------- */
1032   EmacsView *view = FRAME_NS_VIEW (f);
1034   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1036 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1037   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1039   block_input ();
1041   [view unlockFocus];
1042   [[view window] flushWindow];
1044   unblock_input ();
1045   ns_updating_frame = NULL;
1048 static void
1049 ns_focus (struct frame *f, NSRect *r, int n)
1050 /* --------------------------------------------------------------------------
1051    Internal: Focus on given frame.  During small local updates this is used to
1052      draw, however during large updates, ns_update_begin and ns_update_end are
1053      called to wrap the whole thing, in which case these calls are stubbed out.
1054      Except, on GNUstep, we accumulate the rectangle being drawn into, because
1055      the back end won't do this automatically, and will just end up flushing
1056      the entire window.
1057    -------------------------------------------------------------------------- */
1059   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1060   if (r != NULL)
1061     {
1062       NSTRACE_RECT ("r", *r);
1063     }
1065   if (f != ns_updating_frame)
1066     {
1067       NSView *view = FRAME_NS_VIEW (f);
1068       if (view != focus_view)
1069         {
1070           if (focus_view != NULL)
1071             {
1072               [focus_view unlockFocus];
1073               [[focus_view window] flushWindow];
1074 /*debug_lock--; */
1075             }
1077           if (view)
1078             [view lockFocus];
1079           focus_view = view;
1080 /*if (view) debug_lock++; */
1081         }
1082     }
1084   /* clipping */
1085   if (r)
1086     {
1087       [[NSGraphicsContext currentContext] saveGraphicsState];
1088       if (n == 2)
1089         NSRectClipList (r, 2);
1090       else
1091         NSRectClip (*r);
1092       gsaved = YES;
1093     }
1097 static void
1098 ns_unfocus (struct frame *f)
1099 /* --------------------------------------------------------------------------
1100      Internal: Remove focus on given frame
1101    -------------------------------------------------------------------------- */
1103   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1105   if (gsaved)
1106     {
1107       [[NSGraphicsContext currentContext] restoreGraphicsState];
1108       gsaved = NO;
1109     }
1111   if (f != ns_updating_frame)
1112     {
1113       if (focus_view != NULL)
1114         {
1115           [focus_view unlockFocus];
1116           [[focus_view window] flushWindow];
1117           focus_view = NULL;
1118 /*debug_lock--; */
1119         }
1120     }
1124 static void
1125 ns_clip_to_row (struct window *w, struct glyph_row *row,
1126                 enum glyph_row_area area, BOOL gc)
1127 /* --------------------------------------------------------------------------
1128      Internal (but parallels other terms): Focus drawing on given row
1129    -------------------------------------------------------------------------- */
1131   struct frame *f = XFRAME (WINDOW_FRAME (w));
1132   NSRect clip_rect;
1133   int window_x, window_y, window_width;
1135   window_box (w, area, &window_x, &window_y, &window_width, 0);
1137   clip_rect.origin.x = window_x;
1138   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1139   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1140   clip_rect.size.width = window_width;
1141   clip_rect.size.height = row->visible_height;
1143   ns_focus (f, &clip_rect, 1);
1147 /* ==========================================================================
1149     Visible bell and beep.
1151    ========================================================================== */
1154 @interface EmacsBell : NSImageView
1156   // Number of currently active bell:s.
1157   unsigned int nestCount;
1158   bool isAttached;
1160 - (void)show:(NSView *)view;
1161 - (void)hide;
1162 - (void)remove;
1163 @end
1165 @implementation EmacsBell
1167 - (id)init;
1169   NSTRACE ("[EmacsBell init]");
1170   if ((self = [super init]))
1171     {
1172       nestCount = 0;
1173       isAttached = false;
1174 #ifdef NS_IMPL_GNUSTEP
1175       // GNUstep doesn't provide named images.  This was reported in
1176       // 2011, see https://savannah.gnu.org/bugs/?33396
1177       //
1178       // As a drop in replacement, a semitransparent gray square is used.
1179       self.image = [[NSImage alloc] initWithSize:NSMakeSize(32, 32)];
1180       [self.image lockFocus];
1181       [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1182       NSRectFill(NSMakeRect(0, 0, 32, 32));
1183       [self.image unlockFocus];
1184 #else
1185       self.image = [NSImage imageNamed:NSImageNameCaution];
1186 #endif
1187     }
1188   return self;
1191 - (void)show:(NSView *)view
1193   NSTRACE ("[EmacsBell show:]");
1194   NSTRACE_MSG ("nestCount: %u", nestCount);
1196   // Show the image, unless it's already shown.
1197   if (nestCount == 0)
1198     {
1199       NSRect rect = [view bounds];
1200       NSPoint pos;
1201       pos.x = rect.origin.x + (rect.size.width  - self.image.size.width )/2;
1202       pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1204       [self setFrameOrigin:pos];
1205       [self setFrameSize:self.image.size];
1207       isAttached = true;
1208       [[[view window] contentView] addSubview:self
1209                                    positioned:NSWindowAbove
1210                                    relativeTo:nil];
1211     }
1213   ++nestCount;
1215   [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1219 - (void)hide
1221   // Note: Trace output from this method isn't shown, reason unknown.
1222   // NSTRACE ("[EmacsBell hide]");
1224   if (nestCount > 0)
1225     --nestCount;
1227   // Remove the image once the last bell became inactive.
1228   if (nestCount == 0)
1229     {
1230       [self remove];
1231     }
1235 -(void)remove
1237   if (isAttached)
1238     {
1239       [self removeFromSuperview];
1240       isAttached = false;
1241     }
1244 @end
1247 static EmacsBell * bell_view = nil;
1249 static void
1250 ns_ring_bell (struct frame *f)
1251 /* --------------------------------------------------------------------------
1252      "Beep" routine
1253    -------------------------------------------------------------------------- */
1255   NSTRACE ("ns_ring_bell");
1256   if (visible_bell)
1257     {
1258       struct frame *frame = SELECTED_FRAME ();
1259       NSView *view;
1261       if (bell_view == nil)
1262         {
1263           bell_view = [[EmacsBell alloc] init];
1264           [bell_view retain];
1265         }
1267       block_input ();
1269       view = FRAME_NS_VIEW (frame);
1270       if (view != nil)
1271         {
1272           [bell_view show:view];
1273         }
1275       unblock_input ();
1276     }
1277   else
1278     {
1279       NSBeep ();
1280     }
1284 static void hide_bell ()
1285 /* --------------------------------------------------------------------------
1286      Ensure the bell is hidden.
1287    -------------------------------------------------------------------------- */
1289   if (bell_view != nil)
1290     {
1291       [bell_view remove];
1292     }
1296 /* ==========================================================================
1298     Frame / window manager related functions
1300    ========================================================================== */
1303 static void
1304 ns_raise_frame (struct frame *f)
1305 /* --------------------------------------------------------------------------
1306      Bring window to foreground and make it active
1307    -------------------------------------------------------------------------- */
1309   NSView *view;
1311   check_window_system (f);
1312   view = FRAME_NS_VIEW (f);
1313   block_input ();
1314   if (FRAME_VISIBLE_P (f))
1315     [[view window] makeKeyAndOrderFront: NSApp];
1316   unblock_input ();
1320 static void
1321 ns_lower_frame (struct frame *f)
1322 /* --------------------------------------------------------------------------
1323      Send window to back
1324    -------------------------------------------------------------------------- */
1326   NSView *view;
1328   check_window_system (f);
1329   view = FRAME_NS_VIEW (f);
1330   block_input ();
1331   [[view window] orderBack: NSApp];
1332   unblock_input ();
1336 static void
1337 ns_frame_raise_lower (struct frame *f, bool raise)
1338 /* --------------------------------------------------------------------------
1339      External (hook)
1340    -------------------------------------------------------------------------- */
1342   NSTRACE ("ns_frame_raise_lower");
1344   if (raise)
1345     ns_raise_frame (f);
1346   else
1347     ns_lower_frame (f);
1351 static void
1352 ns_frame_rehighlight (struct frame *frame)
1353 /* --------------------------------------------------------------------------
1354      External (hook): called on things like window switching within frame
1355    -------------------------------------------------------------------------- */
1357   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1358   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1360   NSTRACE ("ns_frame_rehighlight");
1361   if (dpyinfo->x_focus_frame)
1362     {
1363       dpyinfo->x_highlight_frame
1364         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1365            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1366            : dpyinfo->x_focus_frame);
1367       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1368         {
1369           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1370           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1371         }
1372     }
1373   else
1374       dpyinfo->x_highlight_frame = 0;
1376   if (dpyinfo->x_highlight_frame &&
1377          dpyinfo->x_highlight_frame != old_highlight)
1378     {
1379       if (old_highlight)
1380         {
1381           x_update_cursor (old_highlight, 1);
1382           x_set_frame_alpha (old_highlight);
1383         }
1384       if (dpyinfo->x_highlight_frame)
1385         {
1386           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1387           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1388         }
1389     }
1393 void
1394 x_make_frame_visible (struct frame *f)
1395 /* --------------------------------------------------------------------------
1396      External: Show the window (X11 semantics)
1397    -------------------------------------------------------------------------- */
1399   NSTRACE ("x_make_frame_visible");
1400   /* XXX: at some points in past this was not needed, as the only place that
1401      called this (frame.c:Fraise_frame ()) also called raise_lower;
1402      if this ends up the case again, comment this out again. */
1403   if (!FRAME_VISIBLE_P (f))
1404     {
1405       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1407       SET_FRAME_VISIBLE (f, 1);
1408       ns_raise_frame (f);
1410       /* Making a new frame from a fullscreen frame will make the new frame
1411          fullscreen also.  So skip handleFS as this will print an error.  */
1412       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1413           && [view isFullscreen])
1414         return;
1416       if (f->want_fullscreen != FULLSCREEN_NONE)
1417         {
1418           block_input ();
1419           [view handleFS];
1420           unblock_input ();
1421         }
1422     }
1426 void
1427 x_make_frame_invisible (struct frame *f)
1428 /* --------------------------------------------------------------------------
1429      External: Hide the window (X11 semantics)
1430    -------------------------------------------------------------------------- */
1432   NSView *view;
1433   NSTRACE ("x_make_frame_invisible");
1434   check_window_system (f);
1435   view = FRAME_NS_VIEW (f);
1436   [[view window] orderOut: NSApp];
1437   SET_FRAME_VISIBLE (f, 0);
1438   SET_FRAME_ICONIFIED (f, 0);
1442 void
1443 x_iconify_frame (struct frame *f)
1444 /* --------------------------------------------------------------------------
1445      External: Iconify window
1446    -------------------------------------------------------------------------- */
1448   NSView *view;
1449   struct ns_display_info *dpyinfo;
1451   NSTRACE ("x_iconify_frame");
1452   check_window_system (f);
1453   view = FRAME_NS_VIEW (f);
1454   dpyinfo = FRAME_DISPLAY_INFO (f);
1456   if (dpyinfo->x_highlight_frame == f)
1457     dpyinfo->x_highlight_frame = 0;
1459   if ([[view window] windowNumber] <= 0)
1460     {
1461       /* the window is still deferred.  Make it very small, bring it
1462          on screen and order it out. */
1463       NSRect s = { { 100, 100}, {0, 0} };
1464       NSRect t;
1465       t = [[view window] frame];
1466       [[view window] setFrame: s display: NO];
1467       [[view window] orderBack: NSApp];
1468       [[view window] orderOut: NSApp];
1469       [[view window] setFrame: t display: NO];
1470     }
1471   [[view window] miniaturize: NSApp];
1474 /* Free X resources of frame F.  */
1476 void
1477 x_free_frame_resources (struct frame *f)
1479   NSView *view;
1480   struct ns_display_info *dpyinfo;
1481   Mouse_HLInfo *hlinfo;
1483   NSTRACE ("x_free_frame_resources");
1484   check_window_system (f);
1485   view = FRAME_NS_VIEW (f);
1486   dpyinfo = FRAME_DISPLAY_INFO (f);
1487   hlinfo = MOUSE_HL_INFO (f);
1489   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1491   block_input ();
1493   free_frame_menubar (f);
1494   free_frame_faces (f);
1496   if (f == dpyinfo->x_focus_frame)
1497     dpyinfo->x_focus_frame = 0;
1498   if (f == dpyinfo->x_highlight_frame)
1499     dpyinfo->x_highlight_frame = 0;
1500   if (f == hlinfo->mouse_face_mouse_frame)
1501     reset_mouse_highlight (hlinfo);
1503   if (f->output_data.ns->miniimage != nil)
1504     [f->output_data.ns->miniimage release];
1506   [[view window] close];
1507   [view release];
1509   xfree (f->output_data.ns);
1511   unblock_input ();
1514 void
1515 x_destroy_window (struct frame *f)
1516 /* --------------------------------------------------------------------------
1517      External: Delete the window
1518    -------------------------------------------------------------------------- */
1520   NSTRACE ("x_destroy_window");
1521   check_window_system (f);
1522   x_free_frame_resources (f);
1523   ns_window_num--;
1527 void
1528 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1529 /* --------------------------------------------------------------------------
1530      External: Position the window
1531    -------------------------------------------------------------------------- */
1533   NSView *view = FRAME_NS_VIEW (f);
1534   NSArray *screens = [NSScreen screens];
1535   NSScreen *fscreen = [screens objectAtIndex: 0];
1536   NSScreen *screen = [[view window] screen];
1538   NSTRACE ("x_set_offset");
1540   block_input ();
1542   f->left_pos = xoff;
1543   f->top_pos = yoff;
1545   if (view != nil && screen && fscreen)
1546     {
1547       f->left_pos = f->size_hint_flags & XNegative
1548         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1549         : f->left_pos;
1550       /* We use visibleFrame here to take menu bar into account.
1551          Ideally we should also adjust left/top with visibleFrame.origin.  */
1553       f->top_pos = f->size_hint_flags & YNegative
1554         ? ([screen visibleFrame].size.height + f->top_pos
1555            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1556            - FRAME_TOOLBAR_HEIGHT (f))
1557         : f->top_pos;
1558 #ifdef NS_IMPL_GNUSTEP
1559       if (f->left_pos < 100)
1560         f->left_pos = 100;  /* don't overlap menu */
1561 #endif
1562       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1563          menu bar.  */
1564       NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1565                                 SCREENMAXBOUND ([fscreen frame].size.height
1566                                                 - NS_TOP_POS (f)));
1567       NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1568       [[view window] setFrameTopLeftPoint: pt];
1569       f->size_hint_flags &= ~(XNegative|YNegative);
1570     }
1572   unblock_input ();
1576 void
1577 x_set_window_size (struct frame *f,
1578                    bool change_gravity,
1579                    int width,
1580                    int height,
1581                    bool pixelwise)
1582 /* --------------------------------------------------------------------------
1583      Adjust window pixel size based on given character grid size
1584      Impl is a bit more complex than other terms, need to do some
1585      internal clipping.
1586    -------------------------------------------------------------------------- */
1588   EmacsView *view = FRAME_NS_VIEW (f);
1589   NSWindow *window = [view window];
1590   NSRect wr = [window frame];
1591   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1592   int pixelwidth, pixelheight;
1593   int orig_height = wr.size.height;
1595   NSTRACE ("x_set_window_size");
1597   if (view == nil)
1598     return;
1600   NSTRACE_RECT ("current", wr);
1601   NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1602   NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1604   block_input ();
1606   if (pixelwise)
1607     {
1608       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1609       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1610     }
1611   else
1612     {
1613       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1614       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1615     }
1617   /* If we have a toolbar, take its height into account. */
1618   if (tb && ! [view isFullscreen])
1619     {
1620     /* NOTE: previously this would generate wrong result if toolbar not
1621              yet displayed and fixing toolbar_height=32 helped, but
1622              now (200903) seems no longer needed */
1623     FRAME_TOOLBAR_HEIGHT (f) =
1624       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1625         - FRAME_NS_TITLEBAR_HEIGHT (f);
1626 #if 0
1627       /* Only breaks things here, removed by martin 2015-09-30.  */
1628 #ifdef NS_IMPL_GNUSTEP
1629       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1630 #endif
1631 #endif
1632     }
1633   else
1634     FRAME_TOOLBAR_HEIGHT (f) = 0;
1636   wr.size.width = pixelwidth + f->border_width;
1637   wr.size.height = pixelheight;
1638   if (! [view isFullscreen])
1639     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1640       + FRAME_TOOLBAR_HEIGHT (f);
1642   /* Do not try to constrain to this screen.  We may have multiple
1643      screens, and want Emacs to span those.  Constraining to screen
1644      prevents that, and that is not nice to the user.  */
1645  if (f->output_data.ns->zooming)
1646    f->output_data.ns->zooming = 0;
1647  else
1648    wr.origin.y += orig_height - wr.size.height;
1650  frame_size_history_add
1651    (f, Qx_set_window_size_1, width, height,
1652     list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1653            Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1654            make_number (f->border_width),
1655            make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1656            make_number (FRAME_TOOLBAR_HEIGHT (f))));
1658   [window setFrame: wr display: YES];
1660   /* This is a trick to compensate for Emacs' managing the scrollbar area
1661      as a fixed number of standard character columns.  Instead of leaving
1662      blank space for the extra, we chopped it off above.  Now for
1663      left-hand scrollbars, we shift all rendering to the left by the
1664      difference between the real width and Emacs' imagined one.  For
1665      right-hand bars, don't worry about it since the extra is never used.
1666      (Obviously doesn't work for vertically split windows tho..) */
1667   {
1668     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1669       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1670                      - NS_SCROLL_BAR_WIDTH (f), 0)
1671       : NSMakePoint (0, 0);
1673     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1674     [view setBoundsOrigin: origin];
1675   }
1677   [view updateFrameSize: NO];
1678   unblock_input ();
1682 static void
1683 ns_fullscreen_hook (struct frame *f)
1685   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1687   NSTRACE ("ns_fullscreen_hook");
1689   if (!FRAME_VISIBLE_P (f))
1690     return;
1692    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1693     {
1694       /* Old style fs don't initiate correctly if created from
1695          init/default-frame alist, so use a timer (not nice...).
1696       */
1697       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1698                                      selector: @selector (handleFS)
1699                                      userInfo: nil repeats: NO];
1700       return;
1701     }
1703   block_input ();
1704   [view handleFS];
1705   unblock_input ();
1708 /* ==========================================================================
1710     Color management
1712    ========================================================================== */
1715 NSColor *
1716 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1718   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1719   if (idx < 1 || idx >= color_table->avail)
1720     return nil;
1721   return color_table->colors[idx];
1725 unsigned long
1726 ns_index_color (NSColor *color, struct frame *f)
1728   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1729   ptrdiff_t idx;
1730   ptrdiff_t i;
1732   if (!color_table->colors)
1733     {
1734       color_table->size = NS_COLOR_CAPACITY;
1735       color_table->avail = 1; /* skip idx=0 as marker */
1736       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1737       color_table->colors[0] = nil;
1738       color_table->empty_indices = [[NSMutableSet alloc] init];
1739     }
1741   /* Do we already have this color?  */
1742   for (i = 1; i < color_table->avail; i++)
1743     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1744       return i;
1746   if ([color_table->empty_indices count] > 0)
1747     {
1748       NSNumber *index = [color_table->empty_indices anyObject];
1749       [color_table->empty_indices removeObject: index];
1750       idx = [index unsignedLongValue];
1751     }
1752   else
1753     {
1754       if (color_table->avail == color_table->size)
1755         color_table->colors =
1756           xpalloc (color_table->colors, &color_table->size, 1,
1757                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1758       idx = color_table->avail++;
1759     }
1761   color_table->colors[idx] = color;
1762   [color retain];
1763 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1764   return idx;
1768 void
1769 ns_free_indexed_color (unsigned long idx, struct frame *f)
1771   struct ns_color_table *color_table;
1772   NSColor *color;
1773   NSNumber *index;
1775   if (!f)
1776     return;
1778   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1780   if (idx <= 0 || idx >= color_table->size) {
1781     message1 ("ns_free_indexed_color: Color index out of range.\n");
1782     return;
1783   }
1785   index = [NSNumber numberWithUnsignedInt: idx];
1786   if ([color_table->empty_indices containsObject: index]) {
1787     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1788     return;
1789   }
1791   color = color_table->colors[idx];
1792   [color release];
1793   color_table->colors[idx] = nil;
1794   [color_table->empty_indices addObject: index];
1795 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1799 static int
1800 ns_get_color (const char *name, NSColor **col)
1801 /* --------------------------------------------------------------------------
1802      Parse a color name
1803    -------------------------------------------------------------------------- */
1804 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1805    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1806    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1808   NSColor *new = nil;
1809   static char hex[20];
1810   int scaling = 0;
1811   float r = -1.0, g, b;
1812   NSString *nsname = [NSString stringWithUTF8String: name];
1814   NSTRACE ("ns_get_color(%s, **)", name);
1816   block_input ();
1818   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1819     {
1820 #ifdef NS_IMPL_COCOA
1821       NSString *defname = [[NSUserDefaults standardUserDefaults]
1822                             stringForKey: @"AppleHighlightColor"];
1823       if (defname != nil)
1824         nsname = defname;
1825       else
1826 #endif
1827       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1828         {
1829           *col = [new colorUsingDefaultColorSpace];
1830           unblock_input ();
1831           return 0;
1832         }
1833       else
1834         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1836       name = [nsname UTF8String];
1837     }
1838   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1839     {
1840       /* NOTE: OSX applications normally don't set foreground selection, but
1841          text may be unreadable if we don't.
1842       */
1843       if ((new = [NSColor selectedTextColor]) != nil)
1844         {
1845           *col = [new colorUsingDefaultColorSpace];
1846           unblock_input ();
1847           return 0;
1848         }
1850       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1851       name = [nsname UTF8String];
1852     }
1854   /* First, check for some sort of numeric specification. */
1855   hex[0] = '\0';
1857   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1858     {
1859       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1860       [scanner scanFloat: &r];
1861       [scanner scanFloat: &g];
1862       [scanner scanFloat: &b];
1863     }
1864   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1865     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1866   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1867     {
1868       int len = (strlen(name) - 1);
1869       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1870       int i;
1871       scaling = strlen(name+start) / 3;
1872       for (i = 0; i < 3; i++)
1873         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1874                  name + start + i * scaling);
1875       hex[3 * (scaling + 1) - 1] = '\0';
1876     }
1878   if (hex[0])
1879     {
1880       int rr, gg, bb;
1881       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1882       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1883         {
1884           r = rr / fscale;
1885           g = gg / fscale;
1886           b = bb / fscale;
1887         }
1888     }
1890   if (r >= 0.0F)
1891     {
1892       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1893       unblock_input ();
1894       return 0;
1895     }
1897   /* Otherwise, color is expected to be from a list */
1898   {
1899     NSEnumerator *lenum, *cenum;
1900     NSString *name;
1901     NSColorList *clist;
1903 #ifdef NS_IMPL_GNUSTEP
1904     /* XXX: who is wrong, the requestor or the implementation? */
1905     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1906         == NSOrderedSame)
1907       nsname = @"highlightColor";
1908 #endif
1910     lenum = [[NSColorList availableColorLists] objectEnumerator];
1911     while ( (clist = [lenum nextObject]) && new == nil)
1912       {
1913         cenum = [[clist allKeys] objectEnumerator];
1914         while ( (name = [cenum nextObject]) && new == nil )
1915           {
1916             if ([name compare: nsname
1917                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1918               new = [clist colorWithKey: name];
1919           }
1920       }
1921   }
1923   if (new)
1924     *col = [new colorUsingDefaultColorSpace];
1925   unblock_input ();
1926   return new ? 0 : 1;
1931 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1932 /* --------------------------------------------------------------------------
1933      Convert a Lisp string object to a NS color
1934    -------------------------------------------------------------------------- */
1936   NSTRACE ("ns_lisp_to_color");
1937   if (STRINGP (color))
1938     return ns_get_color (SSDATA (color), col);
1939   else if (SYMBOLP (color))
1940     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1941   return 1;
1945 Lisp_Object
1946 ns_color_to_lisp (NSColor *col)
1947 /* --------------------------------------------------------------------------
1948      Convert a color to a lisp string with the RGB equivalent
1949    -------------------------------------------------------------------------- */
1951   EmacsCGFloat red, green, blue, alpha, gray;
1952   char buf[1024];
1953   const char *str;
1954   NSTRACE ("ns_color_to_lisp");
1956   block_input ();
1957   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1959       if ((str =[[col colorNameComponent] UTF8String]))
1960         {
1961           unblock_input ();
1962           return build_string ((char *)str);
1963         }
1965     [[col colorUsingDefaultColorSpace]
1966         getRed: &red green: &green blue: &blue alpha: &alpha];
1967   if (red == green && red == blue)
1968     {
1969       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1970             getWhite: &gray alpha: &alpha];
1971       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1972                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1973       unblock_input ();
1974       return build_string (buf);
1975     }
1977   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1978             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1980   unblock_input ();
1981   return build_string (buf);
1985 void
1986 ns_query_color(void *col, XColor *color_def, int setPixel)
1987 /* --------------------------------------------------------------------------
1988          Get ARGB values out of NSColor col and put them into color_def.
1989          If setPixel, set the pixel to a concatenated version.
1990          and set color_def pixel to the resulting index.
1991    -------------------------------------------------------------------------- */
1993   EmacsCGFloat r, g, b, a;
1995   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1996   color_def->red   = r * 65535;
1997   color_def->green = g * 65535;
1998   color_def->blue  = b * 65535;
2000   if (setPixel == YES)
2001     color_def->pixel
2002       = ARGB_TO_ULONG((int)(a*255),
2003                       (int)(r*255), (int)(g*255), (int)(b*255));
2007 bool
2008 ns_defined_color (struct frame *f,
2009                   const char *name,
2010                   XColor *color_def,
2011                   bool alloc,
2012                   bool makeIndex)
2013 /* --------------------------------------------------------------------------
2014          Return true if named color found, and set color_def rgb accordingly.
2015          If makeIndex and alloc are nonzero put the color in the color_table,
2016          and set color_def pixel to the resulting index.
2017          If makeIndex is zero, set color_def pixel to ARGB.
2018          Return false if not found
2019    -------------------------------------------------------------------------- */
2021   NSColor *col;
2022   NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2024   block_input ();
2025   if (ns_get_color (name, &col) != 0) /* Color not found  */
2026     {
2027       unblock_input ();
2028       return 0;
2029     }
2030   if (makeIndex && alloc)
2031     color_def->pixel = ns_index_color (col, f);
2032   ns_query_color (col, color_def, !makeIndex);
2033   unblock_input ();
2034   return 1;
2038 void
2039 x_set_frame_alpha (struct frame *f)
2040 /* --------------------------------------------------------------------------
2041      change the entire-frame transparency
2042    -------------------------------------------------------------------------- */
2044   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2045   double alpha = 1.0;
2046   double alpha_min = 1.0;
2048   NSTRACE ("x_set_frame_alpha");
2050   if (dpyinfo->x_highlight_frame == f)
2051     alpha = f->alpha[0];
2052   else
2053     alpha = f->alpha[1];
2055   if (FLOATP (Vframe_alpha_lower_limit))
2056     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2057   else if (INTEGERP (Vframe_alpha_lower_limit))
2058     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2060   if (alpha < 0.0)
2061     return;
2062   else if (1.0 < alpha)
2063     alpha = 1.0;
2064   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2065     alpha = alpha_min;
2067 #ifdef NS_IMPL_COCOA
2068   {
2069     EmacsView *view = FRAME_NS_VIEW (f);
2070   [[view window] setAlphaValue: alpha];
2071   }
2072 #endif
2076 /* ==========================================================================
2078     Mouse handling
2080    ========================================================================== */
2083 void
2084 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2085 /* --------------------------------------------------------------------------
2086      Programmatically reposition mouse pointer in pixel coordinates
2087    -------------------------------------------------------------------------- */
2089   NSTRACE ("frame_set_mouse_pixel_position");
2090   ns_raise_frame (f);
2091 #if 0
2092   /* FIXME: this does not work, and what about GNUstep? */
2093 #ifdef NS_IMPL_COCOA
2094   [FRAME_NS_VIEW (f) lockFocus];
2095   PSsetmouse ((float)pix_x, (float)pix_y);
2096   [FRAME_NS_VIEW (f) unlockFocus];
2097 #endif
2098 #endif
2101 static int
2102 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2103 /*   ------------------------------------------------------------------------
2104      Called by EmacsView on mouseMovement events.  Passes on
2105      to emacs mainstream code if we moved off of a rect of interest
2106      known as last_mouse_glyph.
2107      ------------------------------------------------------------------------ */
2109   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2110   NSRect *r;
2112 //  NSTRACE ("note_mouse_movement");
2114   dpyinfo->last_mouse_motion_frame = frame;
2115   r = &dpyinfo->last_mouse_glyph;
2117   /* Note, this doesn't get called for enter/leave, since we don't have a
2118      position.  Those are taken care of in the corresponding NSView methods. */
2120   /* has movement gone beyond last rect we were tracking? */
2121   if (x < r->origin.x || x >= r->origin.x + r->size.width
2122       || y < r->origin.y || y >= r->origin.y + r->size.height)
2123     {
2124       ns_update_begin (frame);
2125       frame->mouse_moved = 1;
2126       note_mouse_highlight (frame, x, y);
2127       remember_mouse_glyph (frame, x, y, r);
2128       ns_update_end (frame);
2129       return 1;
2130     }
2132   return 0;
2136 static void
2137 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2138                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2139                    Time *time)
2140 /* --------------------------------------------------------------------------
2141     External (hook): inform emacs about mouse position and hit parts.
2142     If a scrollbar is being dragged, set bar_window, part, x, y, time.
2143     x & y should be position in the scrollbar (the whole bar, not the handle)
2144     and length of scrollbar respectively
2145    -------------------------------------------------------------------------- */
2147   id view;
2148   NSPoint position;
2149   Lisp_Object frame, tail;
2150   struct frame *f;
2151   struct ns_display_info *dpyinfo;
2153   NSTRACE ("ns_mouse_position");
2155   if (*fp == NULL)
2156     {
2157       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2158       return;
2159     }
2161   dpyinfo = FRAME_DISPLAY_INFO (*fp);
2163   block_input ();
2165   /* Clear the mouse-moved flag for every frame on this display.  */
2166   FOR_EACH_FRAME (tail, frame)
2167     if (FRAME_NS_P (XFRAME (frame))
2168         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2169       XFRAME (frame)->mouse_moved = 0;
2171   dpyinfo->last_mouse_scroll_bar = nil;
2172   if (dpyinfo->last_mouse_frame
2173       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2174     f = dpyinfo->last_mouse_frame;
2175   else
2176     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2178   if (f && FRAME_NS_P (f))
2179     {
2180       view = FRAME_NS_VIEW (*fp);
2182       position = [[view window] mouseLocationOutsideOfEventStream];
2183       position = [view convertPoint: position fromView: nil];
2184       remember_mouse_glyph (f, position.x, position.y,
2185                             &dpyinfo->last_mouse_glyph);
2186       NSTRACE_POINT ("position", position);
2188       if (bar_window) *bar_window = Qnil;
2189       if (part) *part = scroll_bar_above_handle;
2191       if (x) XSETINT (*x, lrint (position.x));
2192       if (y) XSETINT (*y, lrint (position.y));
2193       if (time)
2194         *time = dpyinfo->last_mouse_movement_time;
2195       *fp = f;
2196     }
2198   unblock_input ();
2202 static void
2203 ns_frame_up_to_date (struct frame *f)
2204 /* --------------------------------------------------------------------------
2205     External (hook): Fix up mouse highlighting right after a full update.
2206     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2207    -------------------------------------------------------------------------- */
2209   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2211   if (FRAME_NS_P (f))
2212     {
2213       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2214       if (f == hlinfo->mouse_face_mouse_frame)
2215         {
2216           block_input ();
2217           ns_update_begin(f);
2218           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2219                                 hlinfo->mouse_face_mouse_x,
2220                                 hlinfo->mouse_face_mouse_y);
2221           ns_update_end(f);
2222           unblock_input ();
2223         }
2224     }
2228 static void
2229 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2230 /* --------------------------------------------------------------------------
2231     External (RIF): set frame mouse pointer type.
2232    -------------------------------------------------------------------------- */
2234   NSTRACE ("ns_define_frame_cursor");
2235   if (FRAME_POINTER_TYPE (f) != cursor)
2236     {
2237       EmacsView *view = FRAME_NS_VIEW (f);
2238       FRAME_POINTER_TYPE (f) = cursor;
2239       [[view window] invalidateCursorRectsForView: view];
2240       /* Redisplay assumes this function also draws the changed frame
2241          cursor, but this function doesn't, so do it explicitly.  */
2242       x_update_cursor (f, 1);
2243     }
2248 /* ==========================================================================
2250     Keyboard handling
2252    ========================================================================== */
2255 static unsigned
2256 ns_convert_key (unsigned code)
2257 /* --------------------------------------------------------------------------
2258     Internal call used by NSView-keyDown.
2259    -------------------------------------------------------------------------- */
2261   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2262   unsigned keysym;
2263   /* An array would be faster, but less easy to read. */
2264   for (keysym = 0; keysym < last_keysym; keysym += 2)
2265     if (code == convert_ns_to_X_keysym[keysym])
2266       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2267   return 0;
2268 /* if decide to use keyCode and Carbon table, use this line:
2269      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2273 char *
2274 x_get_keysym_name (int keysym)
2275 /* --------------------------------------------------------------------------
2276     Called by keyboard.c.  Not sure if the return val is important, except
2277     that it be unique.
2278    -------------------------------------------------------------------------- */
2280   static char value[16];
2281   NSTRACE ("x_get_keysym_name");
2282   sprintf (value, "%d", keysym);
2283   return value;
2288 /* ==========================================================================
2290     Block drawing operations
2292    ========================================================================== */
2295 static void
2296 ns_redraw_scroll_bars (struct frame *f)
2298   int i;
2299   id view;
2300   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2301   NSTRACE ("ns_redraw_scroll_bars");
2302   for (i =[subviews count]-1; i >= 0; i--)
2303     {
2304       view = [subviews objectAtIndex: i];
2305       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2306       [view display];
2307     }
2311 void
2312 ns_clear_frame (struct frame *f)
2313 /* --------------------------------------------------------------------------
2314       External (hook): Erase the entire frame
2315    -------------------------------------------------------------------------- */
2317   NSView *view = FRAME_NS_VIEW (f);
2318   NSRect r;
2320   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2322  /* comes on initial frame because we have
2323     after-make-frame-functions = select-frame */
2324  if (!FRAME_DEFAULT_FACE (f))
2325    return;
2327   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2329   r = [view bounds];
2331   block_input ();
2332   ns_focus (f, &r, 1);
2333   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2334   NSRectFill (r);
2335   ns_unfocus (f);
2337   /* as of 2006/11 or so this is now needed */
2338   ns_redraw_scroll_bars (f);
2339   unblock_input ();
2343 static void
2344 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2345 /* --------------------------------------------------------------------------
2346     External (RIF):  Clear section of frame
2347    -------------------------------------------------------------------------- */
2349   NSRect r = NSMakeRect (x, y, width, height);
2350   NSView *view = FRAME_NS_VIEW (f);
2351   struct face *face = FRAME_DEFAULT_FACE (f);
2353   if (!view || !face)
2354     return;
2356   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2358   r = NSIntersectionRect (r, [view frame]);
2359   ns_focus (f, &r, 1);
2360   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2362   NSRectFill (r);
2364   ns_unfocus (f);
2365   return;
2368 static void
2369 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2371   if (FRAME_NS_VIEW (f))
2372     {
2373       hide_bell();              // Ensure the bell image isn't scrolled.
2375       ns_focus (f, &dest, 1);
2376       [FRAME_NS_VIEW (f) scrollRect: src
2377                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2378                                                  dest.origin.y - src.origin.y)];
2379       ns_unfocus (f);
2380     }
2383 static void
2384 ns_scroll_run (struct window *w, struct run *run)
2385 /* --------------------------------------------------------------------------
2386     External (RIF):  Insert or delete n lines at line vpos
2387    -------------------------------------------------------------------------- */
2389   struct frame *f = XFRAME (w->frame);
2390   int x, y, width, height, from_y, to_y, bottom_y;
2392   NSTRACE ("ns_scroll_run");
2394   /* begin copy from other terms */
2395   /* Get frame-relative bounding box of the text display area of W,
2396      without mode lines.  Include in this box the left and right
2397      fringe of W.  */
2398   window_box (w, ANY_AREA, &x, &y, &width, &height);
2400   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2401   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2402   bottom_y = y + height;
2404   if (to_y < from_y)
2405     {
2406       /* Scrolling up.  Make sure we don't copy part of the mode
2407          line at the bottom.  */
2408       if (from_y + run->height > bottom_y)
2409         height = bottom_y - from_y;
2410       else
2411         height = run->height;
2412     }
2413   else
2414     {
2415       /* Scrolling down.  Make sure we don't copy over the mode line.
2416          at the bottom.  */
2417       if (to_y + run->height > bottom_y)
2418         height = bottom_y - to_y;
2419       else
2420         height = run->height;
2421     }
2422   /* end copy from other terms */
2424   if (height == 0)
2425       return;
2427   block_input ();
2429   x_clear_cursor (w);
2431   {
2432     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2433     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2435     ns_copy_bits (f, srcRect , dstRect);
2436   }
2438   unblock_input ();
2442 static void
2443 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2444 /* --------------------------------------------------------------------------
2445     External (RIF): preparatory to fringe update after text was updated
2446    -------------------------------------------------------------------------- */
2448   struct frame *f;
2449   int width, height;
2451   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2453   /* begin copy from other terms */
2454   eassert (w);
2456   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2457     desired_row->redraw_fringe_bitmaps_p = 1;
2459   /* When a window has disappeared, make sure that no rest of
2460      full-width rows stays visible in the internal border.  */
2461   if (windows_or_buffers_changed
2462       && desired_row->full_width_p
2463       && (f = XFRAME (w->frame),
2464           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2465           width != 0)
2466       && (height = desired_row->visible_height,
2467           height > 0))
2468     {
2469       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2471       block_input ();
2472       ns_clear_frame_area (f, 0, y, width, height);
2473       ns_clear_frame_area (f,
2474                            FRAME_PIXEL_WIDTH (f) - width,
2475                            y, width, height);
2476       unblock_input ();
2477     }
2481 static void
2482 ns_shift_glyphs_for_insert (struct frame *f,
2483                            int x, int y, int width, int height,
2484                            int shift_by)
2485 /* --------------------------------------------------------------------------
2486     External (RIF): copy an area horizontally, don't worry about clearing src
2487    -------------------------------------------------------------------------- */
2489   NSRect srcRect = NSMakeRect (x, y, width, height);
2490   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2492   NSTRACE ("ns_shift_glyphs_for_insert");
2494   ns_copy_bits (f, srcRect, dstRect);
2499 /* ==========================================================================
2501     Character encoding and metrics
2503    ========================================================================== */
2506 static void
2507 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2508 /* --------------------------------------------------------------------------
2509      External (RIF); compute left/right overhang of whole string and set in s
2510    -------------------------------------------------------------------------- */
2512   struct font *font = s->font;
2514   if (s->char2b)
2515     {
2516       struct font_metrics metrics;
2517       unsigned int codes[2];
2518       codes[0] = *(s->char2b);
2519       codes[1] = *(s->char2b + s->nchars - 1);
2521       font->driver->text_extents (font, codes, 2, &metrics);
2522       s->left_overhang = -metrics.lbearing;
2523       s->right_overhang
2524         = metrics.rbearing > metrics.width
2525         ? metrics.rbearing - metrics.width : 0;
2526     }
2527   else
2528     {
2529       s->left_overhang = 0;
2530       if (EQ (font->driver->type, Qns))
2531         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2532           FONT_HEIGHT (font) * 0.2 : 0;
2533       else
2534         s->right_overhang = 0;
2535     }
2540 /* ==========================================================================
2542     Fringe and cursor drawing
2544    ========================================================================== */
2547 extern int max_used_fringe_bitmap;
2548 static void
2549 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2550                       struct draw_fringe_bitmap_params *p)
2551 /* --------------------------------------------------------------------------
2552     External (RIF); fringe-related
2553    -------------------------------------------------------------------------- */
2555   /* Fringe bitmaps comes in two variants, normal and periodic.  A
2556      periodic bitmap is used to create a continuous pattern.  Since a
2557      bitmap is rendered one text line at a time, the start offset (dh)
2558      of the bitmap varies.  Concretely, this is used for the empty
2559      line indicator.
2561      For a bitmap, "h + dh" is the full height and is always
2562      invariant.  For a normal bitmap "dh" is zero.
2564      For example, when the period is three and the full height is 72
2565      the following combinations exists:
2567        h=72 dh=0
2568        h=71 dh=1
2569        h=70 dh=2 */
2571   struct frame *f = XFRAME (WINDOW_FRAME (w));
2572   struct face *face = p->face;
2573   static EmacsImage **bimgs = NULL;
2574   static int nBimgs = 0;
2576   NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2577   NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2578                p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2580   /* grow bimgs if needed */
2581   if (nBimgs < max_used_fringe_bitmap)
2582     {
2583       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2584       memset (bimgs + nBimgs, 0,
2585               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2586       nBimgs = max_used_fringe_bitmap;
2587     }
2589   /* Must clip because of partially visible lines.  */
2590   ns_clip_to_row (w, row, ANY_AREA, YES);
2592   if (!p->overlay_p)
2593     {
2594       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2596       if (bx >= 0 && nx > 0)
2597         {
2598           NSRect r = NSMakeRect (bx, by, nx, ny);
2599           NSRectClip (r);
2600           [ns_lookup_indexed_color (face->background, f) set];
2601           NSRectFill (r);
2602         }
2603     }
2605   if (p->which)
2606     {
2607       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2608       EmacsImage *img = bimgs[p->which - 1];
2610       if (!img)
2611         {
2612           // Note: For "periodic" images, allocate one EmacsImage for
2613           // the base image, and use it for all dh:s.
2614           unsigned short *bits = p->bits;
2615           int full_height = p->h + p->dh;
2616           int i;
2617           unsigned char *cbits = xmalloc (full_height);
2619           for (i = 0; i < full_height; i++)
2620             cbits[i] = bits[i];
2621           img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2622                                          height: full_height
2623                                              fg: 0 bg: 0];
2624           bimgs[p->which - 1] = img;
2625           xfree (cbits);
2626         }
2628       NSTRACE_RECT ("r", r);
2630       NSRectClip (r);
2631       /* Since we composite the bitmap instead of just blitting it, we need
2632          to erase the whole background. */
2633       [ns_lookup_indexed_color(face->background, f) set];
2634       NSRectFill (r);
2636       {
2637         NSColor *bm_color;
2638         if (!p->cursor_p)
2639           bm_color = ns_lookup_indexed_color(face->foreground, f);
2640         else if (p->overlay_p)
2641           bm_color = ns_lookup_indexed_color(face->background, f);
2642         else
2643           bm_color = f->output_data.ns->cursor_color;
2644         [img setXBMColor: bm_color];
2645       }
2647 #ifdef NS_IMPL_COCOA
2648       // Note: For periodic images, the full image height is "h + hd".
2649       // By using the height h, a suitable part of the image is used.
2650       NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2652       NSTRACE_RECT ("fromRect", fromRect);
2654       [img drawInRect: r
2655               fromRect: fromRect
2656              operation: NSCompositeSourceOver
2657               fraction: 1.0
2658            respectFlipped: YES
2659                 hints: nil];
2660 #else
2661       {
2662         NSPoint pt = r.origin;
2663         pt.y += p->h;
2664         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2665       }
2666 #endif
2667     }
2668   ns_unfocus (f);
2672 static void
2673 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2674                        int x, int y, enum text_cursor_kinds cursor_type,
2675                        int cursor_width, bool on_p, bool active_p)
2676 /* --------------------------------------------------------------------------
2677      External call (RIF): draw cursor.
2678      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2679    -------------------------------------------------------------------------- */
2681   NSRect r, s;
2682   int fx, fy, h, cursor_height;
2683   struct frame *f = WINDOW_XFRAME (w);
2684   struct glyph *phys_cursor_glyph;
2685   struct glyph *cursor_glyph;
2686   struct face *face;
2687   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2689   /* If cursor is out of bounds, don't draw garbage.  This can happen
2690      in mini-buffer windows when switching between echo area glyphs
2691      and mini-buffer.  */
2693   NSTRACE ("ns_draw_window_cursor");
2695   if (!on_p)
2696     return;
2698   w->phys_cursor_type = cursor_type;
2699   w->phys_cursor_on_p = on_p;
2701   if (cursor_type == NO_CURSOR)
2702     {
2703       w->phys_cursor_width = 0;
2704       return;
2705     }
2707   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2708     {
2709       if (glyph_row->exact_window_width_line_p
2710           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2711         {
2712           glyph_row->cursor_in_fringe_p = 1;
2713           draw_fringe_bitmap (w, glyph_row, 0);
2714         }
2715       return;
2716     }
2718   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2719      (other terminals do it the other way round).  We must set
2720      w->phys_cursor_width to the cursor width.  For bar cursors, that
2721      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2722   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2724   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2725      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2726   if (cursor_type == BAR_CURSOR)
2727     {
2728       if (cursor_width < 1)
2729         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2730       w->phys_cursor_width = cursor_width;
2731     }
2732   /* If we have an HBAR, "cursor_width" MAY specify height. */
2733   else if (cursor_type == HBAR_CURSOR)
2734     {
2735       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2736       if (cursor_height > glyph_row->height)
2737         cursor_height = glyph_row->height;
2738       if (h > cursor_height) // Cursor smaller than line height, move down
2739         fy += h - cursor_height;
2740       h = cursor_height;
2741     }
2743   r.origin.x = fx, r.origin.y = fy;
2744   r.size.height = h;
2745   r.size.width = w->phys_cursor_width;
2747   /* TODO: only needed in rare cases with last-resort font in HELLO..
2748      should we do this more efficiently? */
2749   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2752   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2753   if (face && NS_FACE_BACKGROUND (face)
2754       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2755     {
2756       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2757       hollow_color = FRAME_CURSOR_COLOR (f);
2758     }
2759   else
2760     [FRAME_CURSOR_COLOR (f) set];
2762 #ifdef NS_IMPL_COCOA
2763   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2764            atomic.  Cleaner ways of doing this should be investigated.
2765            One way would be to set a global variable DRAWING_CURSOR
2766            when making the call to draw_phys..(), don't focus in that
2767            case, then move the ns_unfocus() here after that call. */
2768   NSDisableScreenUpdates ();
2769 #endif
2771   switch (cursor_type)
2772     {
2773     case DEFAULT_CURSOR:
2774     case NO_CURSOR:
2775       break;
2776     case FILLED_BOX_CURSOR:
2777       NSRectFill (r);
2778       break;
2779     case HOLLOW_BOX_CURSOR:
2780       NSRectFill (r);
2781       [hollow_color set];
2782       NSRectFill (NSInsetRect (r, 1, 1));
2783       [FRAME_CURSOR_COLOR (f) set];
2784       break;
2785     case HBAR_CURSOR:
2786       NSRectFill (r);
2787       break;
2788     case BAR_CURSOR:
2789       s = r;
2790       /* If the character under cursor is R2L, draw the bar cursor
2791          on the right of its glyph, rather than on the left.  */
2792       cursor_glyph = get_phys_cursor_glyph (w);
2793       if ((cursor_glyph->resolved_level & 1) != 0)
2794         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2796       NSRectFill (s);
2797       break;
2798     }
2799   ns_unfocus (f);
2801   /* draw the character under the cursor */
2802   if (cursor_type != NO_CURSOR)
2803     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2805 #ifdef NS_IMPL_COCOA
2806   NSEnableScreenUpdates ();
2807 #endif
2812 static void
2813 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2814 /* --------------------------------------------------------------------------
2815      External (RIF): Draw a vertical line.
2816    -------------------------------------------------------------------------- */
2818   struct frame *f = XFRAME (WINDOW_FRAME (w));
2819   struct face *face;
2820   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2822   NSTRACE ("ns_draw_vertical_window_border");
2824   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2825   if (face)
2826       [ns_lookup_indexed_color(face->foreground, f) set];
2828   ns_focus (f, &r, 1);
2829   NSRectFill(r);
2830   ns_unfocus (f);
2834 static void
2835 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2836 /* --------------------------------------------------------------------------
2837      External (RIF): Draw a window divider.
2838    -------------------------------------------------------------------------- */
2840   struct frame *f = XFRAME (WINDOW_FRAME (w));
2841   struct face *face;
2842   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2844   NSTRACE ("ns_draw_window_divider");
2846   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2847   if (face)
2848       [ns_lookup_indexed_color(face->foreground, f) set];
2850   ns_focus (f, &r, 1);
2851   NSRectFill(r);
2852   ns_unfocus (f);
2855 static void
2856 ns_show_hourglass (struct frame *f)
2858   /* TODO: add NSProgressIndicator to all frames.  */
2861 static void
2862 ns_hide_hourglass (struct frame *f)
2864   /* TODO: remove NSProgressIndicator from all frames.  */
2867 /* ==========================================================================
2869     Glyph drawing operations
2871    ========================================================================== */
2873 static int
2874 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2875 /* --------------------------------------------------------------------------
2876     Wrapper utility to account for internal border width on full-width lines,
2877     and allow top full-width rows to hit the frame top.  nr should be pointer
2878     to two successive NSRects.  Number of rects actually used is returned.
2879    -------------------------------------------------------------------------- */
2881   int n = get_glyph_string_clip_rects (s, nr, 2);
2882   return n;
2885 /* --------------------------------------------------------------------
2886    Draw a wavy line under glyph string s. The wave fills wave_height
2887    pixels from y.
2889                     x          wave_length = 2
2890                                  --
2891                 y    *   *   *   *   *
2892                      |* * * * * * * * *
2893     wave_height = 3  | *   *   *   *
2894   --------------------------------------------------------------------- */
2896 static void
2897 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2899   int wave_height = 3, wave_length = 2;
2900   int y, dx, dy, odd, xmax;
2901   NSPoint a, b;
2902   NSRect waveClip;
2904   dx = wave_length;
2905   dy = wave_height - 1;
2906   y =  s->ybase - wave_height + 3;
2907   xmax = x + width;
2909   /* Find and set clipping rectangle */
2910   waveClip = NSMakeRect (x, y, width, wave_height);
2911   [[NSGraphicsContext currentContext] saveGraphicsState];
2912   NSRectClip (waveClip);
2914   /* Draw the waves */
2915   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2916   b.x = a.x + dx;
2917   odd = (int)(a.x/dx) % 2;
2918   a.y = b.y = y + 0.5;
2920   if (odd)
2921     a.y += dy;
2922   else
2923     b.y += dy;
2925   while (a.x <= xmax)
2926     {
2927       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2928       a.x = b.x, a.y = b.y;
2929       b.x += dx, b.y = y + 0.5 + odd*dy;
2930       odd = !odd;
2931     }
2933   /* Restore previous clipping rectangle(s) */
2934   [[NSGraphicsContext currentContext] restoreGraphicsState];
2939 void
2940 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2941                          NSColor *defaultCol, CGFloat width, CGFloat x)
2942 /* --------------------------------------------------------------------------
2943    Draw underline, overline, and strike-through on glyph string s.
2944    -------------------------------------------------------------------------- */
2946   if (s->for_overlaps)
2947     return;
2949   /* Do underline. */
2950   if (face->underline_p)
2951     {
2952       if (s->face->underline_type == FACE_UNDER_WAVE)
2953         {
2954           if (face->underline_defaulted_p)
2955             [defaultCol set];
2956           else
2957             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2959           ns_draw_underwave (s, width, x);
2960         }
2961       else if (s->face->underline_type == FACE_UNDER_LINE)
2962         {
2964           NSRect r;
2965           unsigned long thickness, position;
2967           /* If the prev was underlined, match its appearance. */
2968           if (s->prev && s->prev->face->underline_p
2969               && s->prev->face->underline_type == FACE_UNDER_LINE
2970               && s->prev->underline_thickness > 0)
2971             {
2972               thickness = s->prev->underline_thickness;
2973               position = s->prev->underline_position;
2974             }
2975           else
2976             {
2977               struct font *font;
2978               unsigned long descent;
2980               font=s->font;
2981               descent = s->y + s->height - s->ybase;
2983               /* Use underline thickness of font, defaulting to 1. */
2984               thickness = (font && font->underline_thickness > 0)
2985                 ? font->underline_thickness : 1;
2987               /* Determine the offset of underlining from the baseline. */
2988               if (x_underline_at_descent_line)
2989                 position = descent - thickness;
2990               else if (x_use_underline_position_properties
2991                        && font && font->underline_position >= 0)
2992                 position = font->underline_position;
2993               else if (font)
2994                 position = lround (font->descent / 2);
2995               else
2996                 position = underline_minimum_offset;
2998               position = max (position, underline_minimum_offset);
3000               /* Ensure underlining is not cropped. */
3001               if (descent <= position)
3002                 {
3003                   position = descent - 1;
3004                   thickness = 1;
3005                 }
3006               else if (descent < position + thickness)
3007                 thickness = 1;
3008             }
3010           s->underline_thickness = thickness;
3011           s->underline_position = position;
3013           r = NSMakeRect (x, s->ybase + position, width, thickness);
3015           if (face->underline_defaulted_p)
3016             [defaultCol set];
3017           else
3018             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3019           NSRectFill (r);
3020         }
3021     }
3022   /* Do overline. We follow other terms in using a thickness of 1
3023      and ignoring overline_margin. */
3024   if (face->overline_p)
3025     {
3026       NSRect r;
3027       r = NSMakeRect (x, s->y, width, 1);
3029       if (face->overline_color_defaulted_p)
3030         [defaultCol set];
3031       else
3032         [ns_lookup_indexed_color (face->overline_color, s->f) set];
3033       NSRectFill (r);
3034     }
3036   /* Do strike-through.  We follow other terms for thickness and
3037      vertical position.*/
3038   if (face->strike_through_p)
3039     {
3040       NSRect r;
3041       unsigned long dy;
3043       dy = lrint ((s->height - 1) / 2);
3044       r = NSMakeRect (x, s->y + dy, width, 1);
3046       if (face->strike_through_color_defaulted_p)
3047         [defaultCol set];
3048       else
3049         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3050       NSRectFill (r);
3051     }
3054 static void
3055 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3056              char left_p, char right_p)
3057 /* --------------------------------------------------------------------------
3058     Draw an unfilled rect inside r, optionally leaving left and/or right open.
3059     Note we can't just use an NSDrawRect command, because of the possibility
3060     of some sides not being drawn, and because the rect will be filled.
3061    -------------------------------------------------------------------------- */
3063   NSRect s = r;
3064   [col set];
3066   /* top, bottom */
3067   s.size.height = thickness;
3068   NSRectFill (s);
3069   s.origin.y += r.size.height - thickness;
3070   NSRectFill (s);
3072   s.size.height = r.size.height;
3073   s.origin.y = r.origin.y;
3075   /* left, right (optional) */
3076   s.size.width = thickness;
3077   if (left_p)
3078     NSRectFill (s);
3079   if (right_p)
3080     {
3081       s.origin.x += r.size.width - thickness;
3082       NSRectFill (s);
3083     }
3087 static void
3088 ns_draw_relief (NSRect r, int thickness, char raised_p,
3089                char top_p, char bottom_p, char left_p, char right_p,
3090                struct glyph_string *s)
3091 /* --------------------------------------------------------------------------
3092     Draw a relief rect inside r, optionally leaving some sides open.
3093     Note we can't just use an NSDrawBezel command, because of the possibility
3094     of some sides not being drawn, and because the rect will be filled.
3095    -------------------------------------------------------------------------- */
3097   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3098   NSColor *newBaseCol = nil;
3099   NSRect sr = r;
3101   NSTRACE ("ns_draw_relief");
3103   /* set up colors */
3105   if (s->face->use_box_color_for_shadows_p)
3106     {
3107       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3108     }
3109 /*     else if (s->first_glyph->type == IMAGE_GLYPH
3110            && s->img->pixmap
3111            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3112        {
3113          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
3114        } */
3115   else
3116     {
3117       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3118     }
3120   if (newBaseCol == nil)
3121     newBaseCol = [NSColor grayColor];
3123   if (newBaseCol != baseCol)  /* TODO: better check */
3124     {
3125       [baseCol release];
3126       baseCol = [newBaseCol retain];
3127       [lightCol release];
3128       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3129       [darkCol release];
3130       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3131     }
3133   [(raised_p ? lightCol : darkCol) set];
3135   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3137   /* top */
3138   sr.size.height = thickness;
3139   if (top_p) NSRectFill (sr);
3141   /* left */
3142   sr.size.height = r.size.height;
3143   sr.size.width = thickness;
3144   if (left_p) NSRectFill (sr);
3146   [(raised_p ? darkCol : lightCol) set];
3148   /* bottom */
3149   sr.size.width = r.size.width;
3150   sr.size.height = thickness;
3151   sr.origin.y += r.size.height - thickness;
3152   if (bottom_p) NSRectFill (sr);
3154   /* right */
3155   sr.size.height = r.size.height;
3156   sr.origin.y = r.origin.y;
3157   sr.size.width = thickness;
3158   sr.origin.x += r.size.width - thickness;
3159   if (right_p) NSRectFill (sr);
3163 static void
3164 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3165 /* --------------------------------------------------------------------------
3166       Function modeled after x_draw_glyph_string_box ().
3167       Sets up parameters for drawing.
3168    -------------------------------------------------------------------------- */
3170   int right_x, last_x;
3171   char left_p, right_p;
3172   struct glyph *last_glyph;
3173   NSRect r;
3174   int thickness;
3175   struct face *face;
3177   if (s->hl == DRAW_MOUSE_FACE)
3178     {
3179       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3180       if (!face)
3181         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3182     }
3183   else
3184     face = s->face;
3186   thickness = face->box_line_width;
3188   NSTRACE ("ns_dumpglyphs_box_or_relief");
3190   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3191             ? WINDOW_RIGHT_EDGE_X (s->w)
3192             : window_box_right (s->w, s->area));
3193   last_glyph = (s->cmp || s->img
3194                 ? s->first_glyph : s->first_glyph + s->nchars-1);
3196   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3197               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3199   left_p = (s->first_glyph->left_box_line_p
3200             || (s->hl == DRAW_MOUSE_FACE
3201                 && (s->prev == NULL || s->prev->hl != s->hl)));
3202   right_p = (last_glyph->right_box_line_p
3203              || (s->hl == DRAW_MOUSE_FACE
3204                  && (s->next == NULL || s->next->hl != s->hl)));
3206   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3208   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3209   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3210     {
3211       ns_draw_box (r, abs (thickness),
3212                    ns_lookup_indexed_color (face->box_color, s->f),
3213                   left_p, right_p);
3214     }
3215   else
3216     {
3217       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3218                      1, 1, left_p, right_p, s);
3219     }
3223 static void
3224 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3225 /* --------------------------------------------------------------------------
3226       Modeled after x_draw_glyph_string_background, which draws BG in
3227       certain cases.  Others are left to the text rendering routine.
3228    -------------------------------------------------------------------------- */
3230   NSTRACE ("ns_maybe_dumpglyphs_background");
3232   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3233     {
3234       int box_line_width = max (s->face->box_line_width, 0);
3235       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3236           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3237              dimensions, since the actual glyphs might be much
3238              smaller.  So in that case we always clear the rectangle
3239              with background color.  */
3240           || FONT_TOO_HIGH (s->font)
3241           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3242         {
3243           struct face *face;
3244           if (s->hl == DRAW_MOUSE_FACE)
3245             {
3246               face = FACE_FROM_ID (s->f,
3247                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3248               if (!face)
3249                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3250             }
3251           else
3252             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3253           if (!face->stipple)
3254             [(NS_FACE_BACKGROUND (face) != 0
3255               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3256               : FRAME_BACKGROUND_COLOR (s->f)) set];
3257           else
3258             {
3259               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3260               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3261             }
3263           if (s->hl != DRAW_CURSOR)
3264             {
3265               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3266                                     s->background_width,
3267                                     s->height-2*box_line_width);
3268               NSRectFill (r);
3269             }
3271           s->background_filled_p = 1;
3272         }
3273     }
3277 static void
3278 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3279 /* --------------------------------------------------------------------------
3280       Renders an image and associated borders.
3281    -------------------------------------------------------------------------- */
3283   EmacsImage *img = s->img->pixmap;
3284   int box_line_vwidth = max (s->face->box_line_width, 0);
3285   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3286   int bg_x, bg_y, bg_height;
3287   int th;
3288   char raised_p;
3289   NSRect br;
3290   struct face *face;
3291   NSColor *tdCol;
3293   NSTRACE ("ns_dumpglyphs_image");
3295   if (s->face->box != FACE_NO_BOX
3296       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3297     x += abs (s->face->box_line_width);
3299   bg_x = x;
3300   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3301   bg_height = s->height;
3302   /* other terms have this, but was causing problems w/tabbar mode */
3303   /* - 2 * box_line_vwidth; */
3305   if (s->slice.x == 0) x += s->img->hmargin;
3306   if (s->slice.y == 0) y += s->img->vmargin;
3308   /* Draw BG: if we need larger area than image itself cleared, do that,
3309      otherwise, since we composite the image under NS (instead of mucking
3310      with its background color), we must clear just the image area. */
3311   if (s->hl == DRAW_MOUSE_FACE)
3312     {
3313       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3314       if (!face)
3315        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3316     }
3317   else
3318     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3320   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3322   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3323       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3324     {
3325       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3326       s->background_filled_p = 1;
3327     }
3328   else
3329     {
3330       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3331     }
3333   NSRectFill (br);
3335   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3336   if (img != nil)
3337     {
3338 #ifdef NS_IMPL_COCOA
3339       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3340       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3341                               s->slice.width, s->slice.height);
3342       [img drawInRect: dr
3343              fromRect: ir
3344              operation: NSCompositeSourceOver
3345               fraction: 1.0
3346            respectFlipped: YES
3347                 hints: nil];
3348 #else
3349       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3350                   operation: NSCompositeSourceOver];
3351 #endif
3352     }
3354   if (s->hl == DRAW_CURSOR)
3355     {
3356     [FRAME_CURSOR_COLOR (s->f) set];
3357     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3358       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3359     else
3360       /* Currently on NS img->mask is always 0. Since
3361          get_window_cursor_type specifies a hollow box cursor when on
3362          a non-masked image we never reach this clause. But we put it
3363          in in anticipation of better support for image masks on
3364          NS. */
3365       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3366     }
3367   else
3368     {
3369       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3370     }
3372   /* Draw underline, overline, strike-through. */
3373   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3375   /* Draw relief, if requested */
3376   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3377     {
3378       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3379         {
3380           th = tool_bar_button_relief >= 0 ?
3381             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3382           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3383         }
3384       else
3385         {
3386           th = abs (s->img->relief);
3387           raised_p = (s->img->relief > 0);
3388         }
3390       r.origin.x = x - th;
3391       r.origin.y = y - th;
3392       r.size.width = s->slice.width + 2*th-1;
3393       r.size.height = s->slice.height + 2*th-1;
3394       ns_draw_relief (r, th, raised_p,
3395                       s->slice.y == 0,
3396                       s->slice.y + s->slice.height == s->img->height,
3397                       s->slice.x == 0,
3398                       s->slice.x + s->slice.width == s->img->width, s);
3399     }
3401   /* If there is no mask, the background won't be seen,
3402      so draw a rectangle on the image for the cursor.
3403      Do this for all images, getting transparency right is not reliable.  */
3404   if (s->hl == DRAW_CURSOR)
3405     {
3406       int thickness = abs (s->img->relief);
3407       if (thickness == 0) thickness = 1;
3408       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3409     }
3413 static void
3414 ns_dumpglyphs_stretch (struct glyph_string *s)
3416   NSRect r[2];
3417   int n, i;
3418   struct face *face;
3419   NSColor *fgCol, *bgCol;
3421   if (!s->background_filled_p)
3422     {
3423       n = ns_get_glyph_string_clip_rect (s, r);
3424       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3426       ns_focus (s->f, r, n);
3428       if (s->hl == DRAW_MOUSE_FACE)
3429        {
3430          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3431          if (!face)
3432            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3433        }
3434       else
3435        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3437       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3438       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3440       for (i = 0; i < n; ++i)
3441         {
3442           if (!s->row->full_width_p)
3443             {
3444               int overrun, leftoverrun;
3446               /* truncate to avoid overwriting fringe and/or scrollbar */
3447               overrun = max (0, (s->x + s->background_width)
3448                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3449                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3450               r[i].size.width -= overrun;
3452               /* truncate to avoid overwriting to left of the window box */
3453               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3454                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3456               if (leftoverrun > 0)
3457                 {
3458                   r[i].origin.x += leftoverrun;
3459                   r[i].size.width -= leftoverrun;
3460                 }
3462               /* XXX: Try to work between problem where a stretch glyph on
3463                  a partially-visible bottom row will clear part of the
3464                  modeline, and another where list-buffers headers and similar
3465                  rows erroneously have visible_height set to 0.  Not sure
3466                  where this is coming from as other terms seem not to show. */
3467               r[i].size.height = min (s->height, s->row->visible_height);
3468             }
3470           [bgCol set];
3472           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3473              overwriting cursor (usually when cursor on a tab) */
3474           if (s->hl == DRAW_CURSOR)
3475             {
3476               CGFloat x, width;
3478               x = r[i].origin.x;
3479               width = s->w->phys_cursor_width;
3480               r[i].size.width -= width;
3481               r[i].origin.x += width;
3483               NSRectFill (r[i]);
3485               /* Draw overlining, etc. on the cursor. */
3486               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3487                 ns_draw_text_decoration (s, face, bgCol, width, x);
3488               else
3489                 ns_draw_text_decoration (s, face, fgCol, width, x);
3490             }
3491           else
3492             {
3493               NSRectFill (r[i]);
3494             }
3496           /* Draw overlining, etc. on the stretch glyph (or the part
3497              of the stretch glyph after the cursor). */
3498           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3499                                    r[i].origin.x);
3500         }
3501       ns_unfocus (s->f);
3502       s->background_filled_p = 1;
3503     }
3507 static void
3508 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3510   int i, j, x;
3511   struct font *font = s->font;
3513   /* If first glyph of S has a left box line, start drawing the text
3514      of S to the right of that box line.  */
3515   if (s->face && s->face->box != FACE_NO_BOX
3516       && s->first_glyph->left_box_line_p)
3517     x = s->x + eabs (s->face->box_line_width);
3518   else
3519     x = s->x;
3521   /* S is a glyph string for a composition.  S->cmp_from is the index
3522      of the first character drawn for glyphs of this composition.
3523      S->cmp_from == 0 means we are drawing the very first character of
3524      this composition.  */
3526   /* Draw a rectangle for the composition if the font for the very
3527      first character of the composition could not be loaded.  */
3528   if (s->font_not_found_p)
3529     {
3530       if (s->cmp_from == 0)
3531         {
3532           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3533           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3534         }
3535     }
3536   else if (! s->first_glyph->u.cmp.automatic)
3537     {
3538       int y = s->ybase;
3540       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3541         /* TAB in a composition means display glyphs with padding
3542            space on the left or right.  */
3543         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3544           {
3545             int xx = x + s->cmp->offsets[j * 2];
3546             int yy = y - s->cmp->offsets[j * 2 + 1];
3548             font->driver->draw (s, j, j + 1, xx, yy, false);
3549             if (s->face->overstrike)
3550               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3551           }
3552     }
3553   else
3554     {
3555       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3556       Lisp_Object glyph;
3557       int y = s->ybase;
3558       int width = 0;
3560       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3561         {
3562           glyph = LGSTRING_GLYPH (gstring, i);
3563           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3564             width += LGLYPH_WIDTH (glyph);
3565           else
3566             {
3567               int xoff, yoff, wadjust;
3569               if (j < i)
3570                 {
3571                   font->driver->draw (s, j, i, x, y, false);
3572                   if (s->face->overstrike)
3573                     font->driver->draw (s, j, i, x + 1, y, false);
3574                   x += width;
3575                 }
3576               xoff = LGLYPH_XOFF (glyph);
3577               yoff = LGLYPH_YOFF (glyph);
3578               wadjust = LGLYPH_WADJUST (glyph);
3579               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3580               if (s->face->overstrike)
3581                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3582                                     false);
3583               x += wadjust;
3584               j = i + 1;
3585               width = 0;
3586             }
3587         }
3588       if (j < i)
3589         {
3590           font->driver->draw (s, j, i, x, y, false);
3591           if (s->face->overstrike)
3592             font->driver->draw (s, j, i, x + 1, y, false);
3593         }
3594     }
3597 static void
3598 ns_draw_glyph_string (struct glyph_string *s)
3599 /* --------------------------------------------------------------------------
3600       External (RIF): Main draw-text call.
3601    -------------------------------------------------------------------------- */
3603   /* TODO (optimize): focus for box and contents draw */
3604   NSRect r[2];
3605   int n, flags;
3606   char box_drawn_p = 0;
3607   struct font *font = s->face->font;
3608   if (! font) font = FRAME_FONT (s->f);
3610   NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3612   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3613     {
3614       int width;
3615       struct glyph_string *next;
3617       for (width = 0, next = s->next;
3618            next && width < s->right_overhang;
3619            width += next->width, next = next->next)
3620         if (next->first_glyph->type != IMAGE_GLYPH)
3621           {
3622             if (next->first_glyph->type != STRETCH_GLYPH)
3623               {
3624                 n = ns_get_glyph_string_clip_rect (s->next, r);
3625                 ns_focus (s->f, r, n);
3626                 ns_maybe_dumpglyphs_background (s->next, 1);
3627                 ns_unfocus (s->f);
3628               }
3629             else
3630               {
3631                 ns_dumpglyphs_stretch (s->next);
3632               }
3633             next->num_clips = 0;
3634           }
3635     }
3637   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3638         && (s->first_glyph->type == CHAR_GLYPH
3639             || s->first_glyph->type == COMPOSITE_GLYPH))
3640     {
3641       n = ns_get_glyph_string_clip_rect (s, r);
3642       ns_focus (s->f, r, n);
3643       ns_maybe_dumpglyphs_background (s, 1);
3644       ns_dumpglyphs_box_or_relief (s);
3645       ns_unfocus (s->f);
3646       box_drawn_p = 1;
3647     }
3649   switch (s->first_glyph->type)
3650     {
3652     case IMAGE_GLYPH:
3653       n = ns_get_glyph_string_clip_rect (s, r);
3654       ns_focus (s->f, r, n);
3655       ns_dumpglyphs_image (s, r[0]);
3656       ns_unfocus (s->f);
3657       break;
3659     case STRETCH_GLYPH:
3660       ns_dumpglyphs_stretch (s);
3661       break;
3663     case CHAR_GLYPH:
3664     case COMPOSITE_GLYPH:
3665       n = ns_get_glyph_string_clip_rect (s, r);
3666       ns_focus (s->f, r, n);
3668       if (s->for_overlaps || (s->cmp_from > 0
3669                               && ! s->first_glyph->u.cmp.automatic))
3670         s->background_filled_p = 1;
3671       else
3672         ns_maybe_dumpglyphs_background
3673           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3675       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3676         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3677          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3678           NS_DUMPGLYPH_NORMAL));
3680       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3681         {
3682           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3683           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3684           NS_FACE_FOREGROUND (s->face) = tmp;
3685         }
3687       {
3688         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3690         if (isComposite)
3691           ns_draw_composite_glyph_string_foreground (s);
3692         else
3693           font->driver->draw
3694             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3695              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3696              || flags == NS_DUMPGLYPH_MOUSEFACE);
3697       }
3699       {
3700         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3701                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3702                                                    s->f)
3703                         : FRAME_FOREGROUND_COLOR (s->f));
3704         [col set];
3706         /* Draw underline, overline, strike-through. */
3707         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3708       }
3710       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3711         {
3712           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3713           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3714           NS_FACE_FOREGROUND (s->face) = tmp;
3715         }
3717       ns_unfocus (s->f);
3718       break;
3720     case GLYPHLESS_GLYPH:
3721       n = ns_get_glyph_string_clip_rect (s, r);
3722       ns_focus (s->f, r, n);
3724       if (s->for_overlaps || (s->cmp_from > 0
3725                               && ! s->first_glyph->u.cmp.automatic))
3726         s->background_filled_p = 1;
3727       else
3728         ns_maybe_dumpglyphs_background
3729           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3730       /* ... */
3731       /* Not yet implemented.  */
3732       /* ... */
3733       ns_unfocus (s->f);
3734       break;
3736     default:
3737       emacs_abort ();
3738     }
3740   /* Draw box if not done already. */
3741   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3742     {
3743       n = ns_get_glyph_string_clip_rect (s, r);
3744       ns_focus (s->f, r, n);
3745       ns_dumpglyphs_box_or_relief (s);
3746       ns_unfocus (s->f);
3747     }
3749   s->num_clips = 0;
3754 /* ==========================================================================
3756     Event loop
3758    ========================================================================== */
3761 static void
3762 ns_send_appdefined (int value)
3763 /* --------------------------------------------------------------------------
3764     Internal: post an appdefined event which EmacsApp-sendEvent will
3765               recognize and take as a command to halt the event loop.
3766    -------------------------------------------------------------------------- */
3768   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3770 #ifdef NS_IMPL_GNUSTEP
3771   // GNUstep needs postEvent to happen on the main thread.
3772   if (! [[NSThread currentThread] isMainThread])
3773     {
3774       EmacsApp *app = (EmacsApp *)NSApp;
3775       app->nextappdefined = value;
3776       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3777                             withObject:nil
3778                          waitUntilDone:YES];
3779       return;
3780     }
3781 #endif
3783   /* Only post this event if we haven't already posted one.  This will end
3784        the [NXApp run] main loop after having processed all events queued at
3785        this moment.  */
3787 #ifdef NS_IMPL_COCOA
3788   if (! send_appdefined)
3789     {
3790       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3791          in certain situations (rapid incoming events).
3792          So check if we have one, if not add one.  */
3793       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3794                                           untilDate:[NSDate distantPast]
3795                                              inMode:NSDefaultRunLoopMode
3796                                             dequeue:NO];
3797       if (! appev) send_appdefined = YES;
3798     }
3799 #endif
3801   if (send_appdefined)
3802     {
3803       NSEvent *nxev;
3805       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3806       send_appdefined = NO;
3808       /* Don't need wakeup timer any more */
3809       if (timed_entry)
3810         {
3811           [timed_entry invalidate];
3812           [timed_entry release];
3813           timed_entry = nil;
3814         }
3816       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3817                                 location: NSMakePoint (0, 0)
3818                            modifierFlags: 0
3819                                timestamp: 0
3820                             windowNumber: [[NSApp mainWindow] windowNumber]
3821                                  context: [NSApp context]
3822                                  subtype: 0
3823                                    data1: value
3824                                    data2: 0];
3826       /* Post an application defined event on the event queue.  When this is
3827          received the [NXApp run] will return, thus having processed all
3828          events which are currently queued.  */
3829       [NSApp postEvent: nxev atStart: NO];
3830     }
3833 #ifdef HAVE_NATIVE_FS
3834 static void
3835 check_native_fs ()
3837   Lisp_Object frame, tail;
3839   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3840     return;
3842   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3844   FOR_EACH_FRAME (tail, frame)
3845     {
3846       struct frame *f = XFRAME (frame);
3847       if (FRAME_NS_P (f))
3848         {
3849           EmacsView *view = FRAME_NS_VIEW (f);
3850           [view updateCollectionBehavior];
3851         }
3852     }
3854 #endif
3856 /* GNUstep does not have cancelTracking.  */
3857 #ifdef NS_IMPL_COCOA
3858 /* Check if menu open should be canceled or continued as normal.  */
3859 void
3860 ns_check_menu_open (NSMenu *menu)
3862   /* Click in menu bar? */
3863   NSArray *a = [[NSApp mainMenu] itemArray];
3864   int i;
3865   BOOL found = NO;
3867   if (menu == nil) // Menu tracking ended.
3868     {
3869       if (menu_will_open_state == MENU_OPENING)
3870         menu_will_open_state = MENU_NONE;
3871       return;
3872     }
3874   for (i = 0; ! found && i < [a count]; i++)
3875     found = menu == [[a objectAtIndex:i] submenu];
3876   if (found)
3877     {
3878       if (menu_will_open_state == MENU_NONE && emacs_event)
3879         {
3880           NSEvent *theEvent = [NSApp currentEvent];
3881           struct frame *emacsframe = SELECTED_FRAME ();
3883           [menu cancelTracking];
3884           menu_will_open_state = MENU_PENDING;
3885           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3886           EV_TRAILER (theEvent);
3888           CGEventRef ourEvent = CGEventCreate (NULL);
3889           menu_mouse_point = CGEventGetLocation (ourEvent);
3890           CFRelease (ourEvent);
3891         }
3892       else if (menu_will_open_state == MENU_OPENING)
3893         {
3894           menu_will_open_state = MENU_NONE;
3895         }
3896     }
3899 /* Redo saved menu click if state is MENU_PENDING.  */
3900 void
3901 ns_check_pending_open_menu ()
3903   if (menu_will_open_state == MENU_PENDING)
3904     {
3905       CGEventSourceRef source
3906         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3908       CGEventRef event = CGEventCreateMouseEvent (source,
3909                                                   kCGEventLeftMouseDown,
3910                                                   menu_mouse_point,
3911                                                   kCGMouseButtonLeft);
3912       CGEventSetType (event, kCGEventLeftMouseDown);
3913       CGEventPost (kCGHIDEventTap, event);
3914       CFRelease (event);
3915       CFRelease (source);
3917       menu_will_open_state = MENU_OPENING;
3918     }
3920 #endif /* NS_IMPL_COCOA */
3922 static void
3923 unwind_apploopnr (Lisp_Object not_used)
3925   --apploopnr;
3926   n_emacs_events_pending = 0;
3927   ns_finish_events ();
3928   q_event_ptr = NULL;
3931 static int
3932 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3933 /* --------------------------------------------------------------------------
3934      External (hook): Post an event to ourself and keep reading events until
3935      we read it back again.  In effect process all events which were waiting.
3936      From 21+ we have to manage the event buffer ourselves.
3937    -------------------------------------------------------------------------- */
3939   struct input_event ev;
3940   int nevents;
3942   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
3944 #ifdef HAVE_NATIVE_FS
3945   check_native_fs ();
3946 #endif
3948   if ([NSApp modalWindow] != nil)
3949     return -1;
3951   if (hold_event_q.nr > 0)
3952     {
3953       int i;
3954       for (i = 0; i < hold_event_q.nr; ++i)
3955         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3956       hold_event_q.nr = 0;
3957       return i;
3958     }
3960   block_input ();
3961   n_emacs_events_pending = 0;
3962   ns_init_events (&ev);
3963   q_event_ptr = hold_quit;
3965   /* we manage autorelease pools by allocate/reallocate each time around
3966      the loop; strict nesting is occasionally violated but seems not to
3967      matter.. earlier methods using full nesting caused major memory leaks */
3968   [outerpool release];
3969   outerpool = [[NSAutoreleasePool alloc] init];
3971   /* If have pending open-file requests, attend to the next one of those. */
3972   if (ns_pending_files && [ns_pending_files count] != 0
3973       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3974     {
3975       [ns_pending_files removeObjectAtIndex: 0];
3976     }
3977   /* Deal with pending service requests. */
3978   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3979     && [(EmacsApp *)
3980          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3981                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3982     {
3983       [ns_pending_service_names removeObjectAtIndex: 0];
3984       [ns_pending_service_args removeObjectAtIndex: 0];
3985     }
3986   else
3987     {
3988       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3989       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3990          to ourself, otherwise [NXApp run] will never exit.  */
3991       send_appdefined = YES;
3992       ns_send_appdefined (-1);
3994       if (++apploopnr != 1)
3995         {
3996           emacs_abort ();
3997         }
3998       record_unwind_protect (unwind_apploopnr, Qt);
3999       [NSApp run];
4000       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4001     }
4003   nevents = n_emacs_events_pending;
4004   n_emacs_events_pending = 0;
4005   ns_finish_events ();
4006   q_event_ptr = NULL;
4007   unblock_input ();
4009   return nevents;
4014 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4015            fd_set *exceptfds, struct timespec const *timeout,
4016            sigset_t const *sigmask)
4017 /* --------------------------------------------------------------------------
4018      Replacement for select, checking for events
4019    -------------------------------------------------------------------------- */
4021   int result;
4022   int t, k, nr = 0;
4023   struct input_event event;
4024   char c;
4026   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4028 #ifdef HAVE_NATIVE_FS
4029   check_native_fs ();
4030 #endif
4032   if (hold_event_q.nr > 0)
4033     {
4034       /* We already have events pending. */
4035       raise (SIGIO);
4036       errno = EINTR;
4037       return -1;
4038     }
4040   for (k = 0; k < nfds+1; k++)
4041     {
4042       if (readfds && FD_ISSET(k, readfds)) ++nr;
4043       if (writefds && FD_ISSET(k, writefds)) ++nr;
4044     }
4046   if (NSApp == nil
4047       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4048     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4050   [outerpool release];
4051   outerpool = [[NSAutoreleasePool alloc] init];
4054   send_appdefined = YES;
4055   if (nr > 0)
4056     {
4057       pthread_mutex_lock (&select_mutex);
4058       select_nfds = nfds;
4059       select_valid = 0;
4060       if (readfds)
4061         {
4062           select_readfds = *readfds;
4063           select_valid += SELECT_HAVE_READ;
4064         }
4065       if (writefds)
4066         {
4067           select_writefds = *writefds;
4068           select_valid += SELECT_HAVE_WRITE;
4069         }
4071       if (timeout)
4072         {
4073           select_timeout = *timeout;
4074           select_valid += SELECT_HAVE_TMO;
4075         }
4077       pthread_mutex_unlock (&select_mutex);
4079       /* Inform fd_handler that select should be called */
4080       c = 'g';
4081       emacs_write_sig (selfds[1], &c, 1);
4082     }
4083   else if (nr == 0 && timeout)
4084     {
4085       /* No file descriptor, just a timeout, no need to wake fd_handler  */
4086       double time = timespectod (*timeout);
4087       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4088                                                       target: NSApp
4089                                                     selector:
4090                                   @selector (timeout_handler:)
4091                                                     userInfo: 0
4092                                                      repeats: NO]
4093                       retain];
4094     }
4095   else /* No timeout and no file descriptors, can this happen?  */
4096     {
4097       /* Send appdefined so we exit from the loop */
4098       ns_send_appdefined (-1);
4099     }
4101   block_input ();
4102   ns_init_events (&event);
4103   if (++apploopnr != 1)
4104     {
4105       emacs_abort ();
4106     }
4108   {
4109     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4110     record_unwind_protect (unwind_apploopnr, Qt);
4111     [NSApp run];
4112     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4113   }
4115   ns_finish_events ();
4116   if (nr > 0 && readfds)
4117     {
4118       c = 's';
4119       emacs_write_sig (selfds[1], &c, 1);
4120     }
4121   unblock_input ();
4123   t = last_appdefined_event_data;
4125   if (t != NO_APPDEFINED_DATA)
4126     {
4127       last_appdefined_event_data = NO_APPDEFINED_DATA;
4129       if (t == -2)
4130         {
4131           /* The NX_APPDEFINED event we received was a timeout. */
4132           result = 0;
4133         }
4134       else if (t == -1)
4135         {
4136           /* The NX_APPDEFINED event we received was the result of
4137              at least one real input event arriving.  */
4138           errno = EINTR;
4139           result = -1;
4140         }
4141       else
4142         {
4143           /* Received back from select () in fd_handler; copy the results */
4144           pthread_mutex_lock (&select_mutex);
4145           if (readfds) *readfds = select_readfds;
4146           if (writefds) *writefds = select_writefds;
4147           pthread_mutex_unlock (&select_mutex);
4148           result = t;
4149         }
4150     }
4151   else
4152     {
4153       errno = EINTR;
4154       result = -1;
4155     }
4157   return result;
4162 /* ==========================================================================
4164     Scrollbar handling
4166    ========================================================================== */
4169 static void
4170 ns_set_vertical_scroll_bar (struct window *window,
4171                            int portion, int whole, int position)
4172 /* --------------------------------------------------------------------------
4173       External (hook): Update or add scrollbar
4174    -------------------------------------------------------------------------- */
4176   Lisp_Object win;
4177   NSRect r, v;
4178   struct frame *f = XFRAME (WINDOW_FRAME (window));
4179   EmacsView *view = FRAME_NS_VIEW (f);
4180   EmacsScroller *bar;
4181   int window_y, window_height;
4182   int top, left, height, width;
4183   BOOL update_p = YES;
4185   /* optimization; display engine sends WAY too many of these.. */
4186   if (!NILP (window->vertical_scroll_bar))
4187     {
4188       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4189       if ([bar checkSamePosition: position portion: portion whole: whole])
4190         {
4191           if (view->scrollbarsNeedingUpdate == 0)
4192             {
4193               if (!windows_or_buffers_changed)
4194                   return;
4195             }
4196           else
4197             view->scrollbarsNeedingUpdate--;
4198           update_p = NO;
4199         }
4200     }
4202   NSTRACE ("ns_set_vertical_scroll_bar");
4204   /* Get dimensions.  */
4205   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4206   top = window_y;
4207   height = window_height;
4208   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4209   left = WINDOW_SCROLL_BAR_AREA_X (window);
4211   r = NSMakeRect (left, top, width, height);
4212   /* the parent view is flipped, so we need to flip y value */
4213   v = [view frame];
4214   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4216   XSETWINDOW (win, window);
4217   block_input ();
4219   /* we want at least 5 lines to display a scrollbar */
4220   if (WINDOW_TOTAL_LINES (window) < 5)
4221     {
4222       if (!NILP (window->vertical_scroll_bar))
4223         {
4224           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4225           [bar removeFromSuperview];
4226           wset_vertical_scroll_bar (window, Qnil);
4227           [bar release];
4228         }
4229       ns_clear_frame_area (f, left, top, width, height);
4230       unblock_input ();
4231       return;
4232     }
4234   if (NILP (window->vertical_scroll_bar))
4235     {
4236       if (width > 0 && height > 0)
4237         ns_clear_frame_area (f, left, top, width, height);
4239       bar = [[EmacsScroller alloc] initFrame: r window: win];
4240       wset_vertical_scroll_bar (window, make_save_ptr (bar));
4241       update_p = YES;
4242     }
4243   else
4244     {
4245       NSRect oldRect;
4246       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4247       oldRect = [bar frame];
4248       r.size.width = oldRect.size.width;
4249       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4250         {
4251           if (oldRect.origin.x != r.origin.x)
4252               ns_clear_frame_area (f, left, top, width, height);
4253           [bar setFrame: r];
4254         }
4255     }
4257   if (update_p)
4258     [bar setPosition: position portion: portion whole: whole];
4259   unblock_input ();
4263 static void
4264 ns_set_horizontal_scroll_bar (struct window *window,
4265                               int portion, int whole, int position)
4266 /* --------------------------------------------------------------------------
4267       External (hook): Update or add scrollbar
4268    -------------------------------------------------------------------------- */
4270   Lisp_Object win;
4271   NSRect r, v;
4272   struct frame *f = XFRAME (WINDOW_FRAME (window));
4273   EmacsView *view = FRAME_NS_VIEW (f);
4274   EmacsScroller *bar;
4275   int top, height, left, width;
4276   int window_x, window_width;
4277   BOOL update_p = YES;
4279   /* optimization; display engine sends WAY too many of these.. */
4280   if (!NILP (window->horizontal_scroll_bar))
4281     {
4282       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4283       if ([bar checkSamePosition: position portion: portion whole: whole])
4284         {
4285           if (view->scrollbarsNeedingUpdate == 0)
4286             {
4287               if (!windows_or_buffers_changed)
4288                   return;
4289             }
4290           else
4291             view->scrollbarsNeedingUpdate--;
4292           update_p = NO;
4293         }
4294     }
4296   NSTRACE ("ns_set_horizontal_scroll_bar");
4298   /* Get dimensions.  */
4299   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4300   left = window_x;
4301   width = window_width;
4302   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4303   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4305   r = NSMakeRect (left, top, width, height);
4306   /* the parent view is flipped, so we need to flip y value */
4307   v = [view frame];
4308   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4309   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4311   XSETWINDOW (win, window);
4312   block_input ();
4314   if (WINDOW_TOTAL_COLS (window) < 5)
4315     {
4316       if (!NILP (window->horizontal_scroll_bar))
4317         {
4318           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4319           [bar removeFromSuperview];
4320           wset_horizontal_scroll_bar (window, Qnil);
4321         }
4322       ns_clear_frame_area (f, left, top, width, height);
4323       unblock_input ();
4324       return;
4325     }
4327   if (NILP (window->horizontal_scroll_bar))
4328     {
4329       if (width > 0 && height > 0)
4330         ns_clear_frame_area (f, left, top, width, height);
4332       bar = [[EmacsScroller alloc] initFrame: r window: win];
4333       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4334       update_p = YES;
4335     }
4336   else
4337     {
4338       NSRect oldRect;
4339       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4340       oldRect = [bar frame];
4341       r.size.width = oldRect.size.width;
4342       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4343         {
4344           if (oldRect.origin.x != r.origin.x)
4345               ns_clear_frame_area (f, left, top, width, height);
4346           [bar setFrame: r];
4347           update_p = YES;
4348         }
4349     }
4351   if (update_p)
4352     [bar setPosition: position portion: portion whole: whole];
4353   unblock_input ();
4357 static void
4358 ns_condemn_scroll_bars (struct frame *f)
4359 /* --------------------------------------------------------------------------
4360      External (hook): arrange for all frame's scrollbars to be removed
4361      at next call to judge_scroll_bars, except for those redeemed.
4362    -------------------------------------------------------------------------- */
4364   int i;
4365   id view;
4366   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4368   NSTRACE ("ns_condemn_scroll_bars");
4370   for (i =[subviews count]-1; i >= 0; i--)
4371     {
4372       view = [subviews objectAtIndex: i];
4373       if ([view isKindOfClass: [EmacsScroller class]])
4374         [view condemn];
4375     }
4379 static void
4380 ns_redeem_scroll_bar (struct window *window)
4381 /* --------------------------------------------------------------------------
4382      External (hook): arrange to spare this window's scrollbar
4383      at next call to judge_scroll_bars.
4384    -------------------------------------------------------------------------- */
4386   id bar;
4387   NSTRACE ("ns_redeem_scroll_bar");
4388   if (!NILP (window->vertical_scroll_bar))
4389     {
4390       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4391       [bar reprieve];
4392     }
4394   if (!NILP (window->horizontal_scroll_bar))
4395     {
4396       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4397       [bar reprieve];
4398     }
4402 static void
4403 ns_judge_scroll_bars (struct frame *f)
4404 /* --------------------------------------------------------------------------
4405      External (hook): destroy all scrollbars on frame that weren't
4406      redeemed after call to condemn_scroll_bars.
4407    -------------------------------------------------------------------------- */
4409   int i;
4410   id view;
4411   EmacsView *eview = FRAME_NS_VIEW (f);
4412   NSArray *subviews = [[eview superview] subviews];
4413   BOOL removed = NO;
4415   NSTRACE ("ns_judge_scroll_bars");
4416   for (i = [subviews count]-1; i >= 0; --i)
4417     {
4418       view = [subviews objectAtIndex: i];
4419       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4420       if ([view judge])
4421         removed = YES;
4422     }
4424   if (removed)
4425     [eview updateFrameSize: NO];
4428 /* ==========================================================================
4430     Initialization
4432    ========================================================================== */
4435 x_display_pixel_height (struct ns_display_info *dpyinfo)
4437   NSArray *screens = [NSScreen screens];
4438   NSEnumerator *enumerator = [screens objectEnumerator];
4439   NSScreen *screen;
4440   NSRect frame;
4442   frame = NSZeroRect;
4443   while ((screen = [enumerator nextObject]) != nil)
4444     frame = NSUnionRect (frame, [screen frame]);
4446   return NSHeight (frame);
4450 x_display_pixel_width (struct ns_display_info *dpyinfo)
4452   NSArray *screens = [NSScreen screens];
4453   NSEnumerator *enumerator = [screens objectEnumerator];
4454   NSScreen *screen;
4455   NSRect frame;
4457   frame = NSZeroRect;
4458   while ((screen = [enumerator nextObject]) != nil)
4459     frame = NSUnionRect (frame, [screen frame]);
4461   return NSWidth (frame);
4465 static Lisp_Object ns_string_to_lispmod (const char *s)
4466 /* --------------------------------------------------------------------------
4467      Convert modifier name to lisp symbol
4468    -------------------------------------------------------------------------- */
4470   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4471     return Qmeta;
4472   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4473     return Qsuper;
4474   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4475     return Qcontrol;
4476   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4477     return Qalt;
4478   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4479     return Qhyper;
4480   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4481     return Qnone;
4482   else
4483     return Qnil;
4487 static void
4488 ns_default (const char *parameter, Lisp_Object *result,
4489            Lisp_Object yesval, Lisp_Object noval,
4490            BOOL is_float, BOOL is_modstring)
4491 /* --------------------------------------------------------------------------
4492       Check a parameter value in user's preferences
4493    -------------------------------------------------------------------------- */
4495   const char *value = ns_get_defaults_value (parameter);
4497   if (value)
4498     {
4499       double f;
4500       char *pos;
4501       if (c_strcasecmp (value, "YES") == 0)
4502         *result = yesval;
4503       else if (c_strcasecmp (value, "NO") == 0)
4504         *result = noval;
4505       else if (is_float && (f = strtod (value, &pos), pos != value))
4506         *result = make_float (f);
4507       else if (is_modstring && value)
4508         *result = ns_string_to_lispmod (value);
4509       else fprintf (stderr,
4510                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4511     }
4515 static void
4516 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4517 /* --------------------------------------------------------------------------
4518       Initialize global info and storage for display.
4519    -------------------------------------------------------------------------- */
4521     NSScreen *screen = [NSScreen mainScreen];
4522     NSWindowDepth depth = [screen depth];
4524     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4525     dpyinfo->resy = 72.27;
4526     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4527                                                   NSColorSpaceFromDepth (depth)]
4528                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4529                                                  NSColorSpaceFromDepth (depth)];
4530     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4531     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4532     dpyinfo->color_table->colors = NULL;
4533     dpyinfo->root_window = 42; /* a placeholder.. */
4534     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4535     dpyinfo->n_fonts = 0;
4536     dpyinfo->smallest_font_height = 1;
4537     dpyinfo->smallest_char_width = 1;
4539     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4543 /* This and next define (many of the) public functions in this file. */
4544 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4545          with using despite presence in the "system dependent" redisplay
4546          interface.  In addition, many of the ns_ methods have code that is
4547          shared with all terms, indicating need for further refactoring. */
4548 extern frame_parm_handler ns_frame_parm_handlers[];
4549 static struct redisplay_interface ns_redisplay_interface =
4551   ns_frame_parm_handlers,
4552   x_produce_glyphs,
4553   x_write_glyphs,
4554   x_insert_glyphs,
4555   x_clear_end_of_line,
4556   ns_scroll_run,
4557   ns_after_update_window_line,
4558   ns_update_window_begin,
4559   ns_update_window_end,
4560   0, /* flush_display */
4561   x_clear_window_mouse_face,
4562   x_get_glyph_overhangs,
4563   x_fix_overlapping_area,
4564   ns_draw_fringe_bitmap,
4565   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4566   0, /* destroy_fringe_bitmap */
4567   ns_compute_glyph_string_overhangs,
4568   ns_draw_glyph_string,
4569   ns_define_frame_cursor,
4570   ns_clear_frame_area,
4571   ns_draw_window_cursor,
4572   ns_draw_vertical_window_border,
4573   ns_draw_window_divider,
4574   ns_shift_glyphs_for_insert,
4575   ns_show_hourglass,
4576   ns_hide_hourglass
4580 static void
4581 ns_delete_display (struct ns_display_info *dpyinfo)
4583   /* TODO... */
4587 /* This function is called when the last frame on a display is deleted. */
4588 static void
4589 ns_delete_terminal (struct terminal *terminal)
4591   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4593   NSTRACE ("ns_delete_terminal");
4595   /* Protect against recursive calls.  delete_frame in
4596      delete_terminal calls us back when it deletes our last frame.  */
4597   if (!terminal->name)
4598     return;
4600   block_input ();
4602   x_destroy_all_bitmaps (dpyinfo);
4603   ns_delete_display (dpyinfo);
4604   unblock_input ();
4608 static struct terminal *
4609 ns_create_terminal (struct ns_display_info *dpyinfo)
4610 /* --------------------------------------------------------------------------
4611       Set up use of NS before we make the first connection.
4612    -------------------------------------------------------------------------- */
4614   struct terminal *terminal;
4616   NSTRACE ("ns_create_terminal");
4618   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4620   terminal->display_info.ns = dpyinfo;
4621   dpyinfo->terminal = terminal;
4623   terminal->clear_frame_hook = ns_clear_frame;
4624   terminal->ring_bell_hook = ns_ring_bell;
4625   terminal->update_begin_hook = ns_update_begin;
4626   terminal->update_end_hook = ns_update_end;
4627   terminal->read_socket_hook = ns_read_socket;
4628   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4629   terminal->mouse_position_hook = ns_mouse_position;
4630   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4631   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4632   terminal->fullscreen_hook = ns_fullscreen_hook;
4633   terminal->menu_show_hook = ns_menu_show;
4634   terminal->popup_dialog_hook = ns_popup_dialog;
4635   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4636   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4637   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4638   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4639   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4640   terminal->delete_frame_hook = x_destroy_window;
4641   terminal->delete_terminal_hook = ns_delete_terminal;
4642   /* Other hooks are NULL by default.  */
4644   return terminal;
4648 struct ns_display_info *
4649 ns_term_init (Lisp_Object display_name)
4650 /* --------------------------------------------------------------------------
4651      Start the Application and get things rolling.
4652    -------------------------------------------------------------------------- */
4654   struct terminal *terminal;
4655   struct ns_display_info *dpyinfo;
4656   static int ns_initialized = 0;
4657   Lisp_Object tmp;
4659   if (ns_initialized) return x_display_list;
4660   ns_initialized = 1;
4662   block_input ();
4664   NSTRACE ("ns_term_init");
4666   [outerpool release];
4667   outerpool = [[NSAutoreleasePool alloc] init];
4669   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4670   /*GSDebugAllocationActive (YES); */
4671   block_input ();
4673   baud_rate = 38400;
4674   Fset_input_interrupt_mode (Qnil);
4676   if (selfds[0] == -1)
4677     {
4678       if (emacs_pipe (selfds) != 0)
4679         {
4680           fprintf (stderr, "Failed to create pipe: %s\n",
4681                    emacs_strerror (errno));
4682           emacs_abort ();
4683         }
4685       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4686       FD_ZERO (&select_readfds);
4687       FD_ZERO (&select_writefds);
4688       pthread_mutex_init (&select_mutex, NULL);
4689     }
4691   ns_pending_files = [[NSMutableArray alloc] init];
4692   ns_pending_service_names = [[NSMutableArray alloc] init];
4693   ns_pending_service_args = [[NSMutableArray alloc] init];
4695 /* Start app and create the main menu, window, view.
4696      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4697      The view will then ask the NSApp to stop and return to Emacs. */
4698   [EmacsApp sharedApplication];
4699   if (NSApp == nil)
4700     return NULL;
4701   [NSApp setDelegate: NSApp];
4703   /* Start the select thread.  */
4704   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4705                            toTarget:NSApp
4706                          withObject:nil];
4708   /* debugging: log all notifications */
4709   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4710                                          selector: @selector (logNotification:)
4711                                              name: nil object: nil]; */
4713   dpyinfo = xzalloc (sizeof *dpyinfo);
4715   ns_initialize_display_info (dpyinfo);
4716   terminal = ns_create_terminal (dpyinfo);
4718   terminal->kboard = allocate_kboard (Qns);
4719   /* Don't let the initial kboard remain current longer than necessary.
4720      That would cause problems if a file loaded on startup tries to
4721      prompt in the mini-buffer.  */
4722   if (current_kboard == initial_kboard)
4723     current_kboard = terminal->kboard;
4724   terminal->kboard->reference_count++;
4726   dpyinfo->next = x_display_list;
4727   x_display_list = dpyinfo;
4729   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4731   terminal->name = xlispstrdup (display_name);
4733   unblock_input ();
4735   if (!inhibit_x_resources)
4736     {
4737       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4738                  Qt, Qnil, NO, NO);
4739       tmp = Qnil;
4740       /* this is a standard variable */
4741       ns_default ("AppleAntiAliasingThreshold", &tmp,
4742                  make_float (10.0), make_float (6.0), YES, NO);
4743       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4744     }
4746   NSTRACE_MSG ("Colors");
4748   {
4749     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4751     if ( cl == nil )
4752       {
4753         Lisp_Object color_file, color_map, color;
4754         unsigned long c;
4755         char *name;
4757         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4758                          Fsymbol_value (intern ("data-directory")));
4760         color_map = Fx_load_color_file (color_file);
4761         if (NILP (color_map))
4762           fatal ("Could not read %s.\n", SDATA (color_file));
4764         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4765         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4766           {
4767             color = XCAR (color_map);
4768             name = SSDATA (XCAR (color));
4769             c = XINT (XCDR (color));
4770             [cl setColor:
4771                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4772                                       green: GREEN_FROM_ULONG (c) / 255.0
4773                                        blue: BLUE_FROM_ULONG (c) / 255.0
4774                                       alpha: 1.0]
4775                   forKey: [NSString stringWithUTF8String: name]];
4776           }
4777         [cl writeToFile: nil];
4778       }
4779   }
4781   NSTRACE_MSG ("Versions");
4783   {
4784 #ifdef NS_IMPL_GNUSTEP
4785     Vwindow_system_version = build_string (gnustep_base_version);
4786 #else
4787     /*PSnextrelease (128, c); */
4788     char c[DBL_BUFSIZE_BOUND];
4789     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4790     Vwindow_system_version = make_unibyte_string (c, len);
4791 #endif
4792   }
4794   delete_keyboard_wait_descriptor (0);
4796   ns_app_name = [[NSProcessInfo processInfo] processName];
4798   /* Set up OS X app menu */
4800   NSTRACE_MSG ("Menu init");
4802 #ifdef NS_IMPL_COCOA
4803   {
4804     NSMenu *appMenu;
4805     NSMenuItem *item;
4806     /* set up the application menu */
4807     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4808     [svcsMenu setAutoenablesItems: NO];
4809     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4810     [appMenu setAutoenablesItems: NO];
4811     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4812     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4814     [appMenu insertItemWithTitle: @"About Emacs"
4815                           action: @selector (orderFrontStandardAboutPanel:)
4816                    keyEquivalent: @""
4817                          atIndex: 0];
4818     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4819     [appMenu insertItemWithTitle: @"Preferences..."
4820                           action: @selector (showPreferencesWindow:)
4821                    keyEquivalent: @","
4822                          atIndex: 2];
4823     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4824     item = [appMenu insertItemWithTitle: @"Services"
4825                                  action: @selector (menuDown:)
4826                           keyEquivalent: @""
4827                                 atIndex: 4];
4828     [appMenu setSubmenu: svcsMenu forItem: item];
4829     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4830     [appMenu insertItemWithTitle: @"Hide Emacs"
4831                           action: @selector (hide:)
4832                    keyEquivalent: @"h"
4833                          atIndex: 6];
4834     item =  [appMenu insertItemWithTitle: @"Hide Others"
4835                           action: @selector (hideOtherApplications:)
4836                    keyEquivalent: @"h"
4837                          atIndex: 7];
4838     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4839     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4840     [appMenu insertItemWithTitle: @"Quit Emacs"
4841                           action: @selector (terminate:)
4842                    keyEquivalent: @"q"
4843                          atIndex: 9];
4845     item = [mainMenu insertItemWithTitle: ns_app_name
4846                                   action: @selector (menuDown:)
4847                            keyEquivalent: @""
4848                                  atIndex: 0];
4849     [mainMenu setSubmenu: appMenu forItem: item];
4850     [dockMenu insertItemWithTitle: @"New Frame"
4851                            action: @selector (newFrame:)
4852                     keyEquivalent: @""
4853                           atIndex: 0];
4855     [NSApp setMainMenu: mainMenu];
4856     [NSApp setAppleMenu: appMenu];
4857     [NSApp setServicesMenu: svcsMenu];
4858     /* Needed at least on Cocoa, to get dock menu to show windows */
4859     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4861     [[NSNotificationCenter defaultCenter]
4862       addObserver: mainMenu
4863          selector: @selector (trackingNotification:)
4864              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4865     [[NSNotificationCenter defaultCenter]
4866       addObserver: mainMenu
4867          selector: @selector (trackingNotification:)
4868              name: NSMenuDidEndTrackingNotification object: mainMenu];
4869   }
4870 #endif /* MAC OS X menu setup */
4872   /* Register our external input/output types, used for determining
4873      applicable services and also drag/drop eligibility. */
4875   NSTRACE_MSG ("Input/output types");
4877   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4878   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4879                       retain];
4880   ns_drag_types = [[NSArray arrayWithObjects:
4881                             NSStringPboardType,
4882                             NSTabularTextPboardType,
4883                             NSFilenamesPboardType,
4884                             NSURLPboardType, nil] retain];
4886   /* If fullscreen is in init/default-frame-alist, focus isn't set
4887      right for fullscreen windows, so set this.  */
4888   [NSApp activateIgnoringOtherApps:YES];
4890   NSTRACE_MSG ("Call NSApp run");
4892   [NSApp run];
4893   ns_do_open_file = YES;
4895 #ifdef NS_IMPL_GNUSTEP
4896   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4897      We must re-catch it so subprocess works.  */
4898   catch_child_signal ();
4899 #endif
4901   NSTRACE_MSG ("ns_term_init done");
4903   unblock_input ();
4905   return dpyinfo;
4909 void
4910 ns_term_shutdown (int sig)
4912   [[NSUserDefaults standardUserDefaults] synchronize];
4914   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4915   if (STRINGP (Vauto_save_list_file_name))
4916     unlink (SSDATA (Vauto_save_list_file_name));
4918   if (sig == 0 || sig == SIGTERM)
4919     {
4920       [NSApp terminate: NSApp];
4921     }
4922   else // force a stack trace to happen
4923     {
4924       emacs_abort ();
4925     }
4929 /* ==========================================================================
4931     EmacsApp implementation
4933    ========================================================================== */
4936 @implementation EmacsApp
4938 - (id)init
4940   NSTRACE ("[EmacsApp init]");
4942   if ((self = [super init]))
4943     {
4944 #ifdef NS_IMPL_COCOA
4945       self->isFirst = YES;
4946 #endif
4947 #ifdef NS_IMPL_GNUSTEP
4948       self->applicationDidFinishLaunchingCalled = NO;
4949 #endif
4950     }
4952   return self;
4955 #ifdef NS_IMPL_COCOA
4956 - (void)run
4958   NSTRACE ("[EmacsApp run]");
4960 #ifndef NSAppKitVersionNumber10_9
4961 #define NSAppKitVersionNumber10_9 1265
4962 #endif
4964     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4965       {
4966         [super run];
4967         return;
4968       }
4970   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4972   if (isFirst) [self finishLaunching];
4973   isFirst = NO;
4975   shouldKeepRunning = YES;
4976   do
4977     {
4978       [pool release];
4979       pool = [[NSAutoreleasePool alloc] init];
4981       NSEvent *event =
4982         [self nextEventMatchingMask:NSAnyEventMask
4983                           untilDate:[NSDate distantFuture]
4984                              inMode:NSDefaultRunLoopMode
4985                             dequeue:YES];
4987       [self sendEvent:event];
4988       [self updateWindows];
4989     } while (shouldKeepRunning);
4991   [pool release];
4994 - (void)stop: (id)sender
4996   NSTRACE ("[EmacsApp stop:]");
4998     shouldKeepRunning = NO;
4999     // Stop possible dialog also.  Noop if no dialog present.
5000     // The file dialog still leaks 7k - 10k on 10.9 though.
5001     [super stop:sender];
5003 #endif /* NS_IMPL_COCOA */
5005 - (void)logNotification: (NSNotification *)notification
5007   NSTRACE ("[EmacsApp logNotification:]");
5009   const char *name = [[notification name] UTF8String];
5010   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5011       && !strstr (name, "WindowNumber"))
5012     NSLog (@"notification: '%@'", [notification name]);
5016 - (void)sendEvent: (NSEvent *)theEvent
5017 /* --------------------------------------------------------------------------
5018      Called when NSApp is running for each event received.  Used to stop
5019      the loop when we choose, since there's no way to just run one iteration.
5020    -------------------------------------------------------------------------- */
5022   int type = [theEvent type];
5023   NSWindow *window = [theEvent window];
5025   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5026   NSTRACE_MSG ("Type: %d", type);
5028 #ifdef NS_IMPL_GNUSTEP
5029   // Keyboard events aren't propagated to file dialogs for some reason.
5030   if ([NSApp modalWindow] != nil &&
5031       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5032     {
5033       [[NSApp modalWindow] sendEvent: theEvent];
5034       return;
5035     }
5036 #endif
5038   if (represented_filename != nil && represented_frame)
5039     {
5040       NSString *fstr = represented_filename;
5041       NSView *view = FRAME_NS_VIEW (represented_frame);
5042 #ifdef NS_IMPL_COCOA
5043       /* work around a bug observed on 10.3 and later where
5044          setTitleWithRepresentedFilename does not clear out previous state
5045          if given filename does not exist */
5046       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5047         [[view window] setRepresentedFilename: @""];
5048 #endif
5049       [[view window] setRepresentedFilename: fstr];
5050       [represented_filename release];
5051       represented_filename = nil;
5052       represented_frame = NULL;
5053     }
5055   if (type == NSApplicationDefined)
5056     {
5057       switch ([theEvent data2])
5058         {
5059 #ifdef NS_IMPL_COCOA
5060         case NSAPP_DATA2_RUNASSCRIPT:
5061           ns_run_ascript ();
5062           [self stop: self];
5063           return;
5064 #endif
5065         case NSAPP_DATA2_RUNFILEDIALOG:
5066           ns_run_file_dialog ();
5067           [self stop: self];
5068           return;
5069         }
5070     }
5072   if (type == NSCursorUpdate && window == nil)
5073     {
5074       fprintf (stderr, "Dropping external cursor update event.\n");
5075       return;
5076     }
5078   if (type == NSApplicationDefined)
5079     {
5080       /* Events posted by ns_send_appdefined interrupt the run loop here.
5081          But, if a modal window is up, an appdefined can still come through,
5082          (e.g., from a makeKeyWindow event) but stopping self also stops the
5083          modal loop. Just defer it until later. */
5084       if ([NSApp modalWindow] == nil)
5085         {
5086           last_appdefined_event_data = [theEvent data1];
5087           [self stop: self];
5088         }
5089       else
5090         {
5091           send_appdefined = YES;
5092         }
5093     }
5096 #ifdef NS_IMPL_COCOA
5097   /* If no dialog and none of our frames have focus and it is a move, skip it.
5098      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5099      such as Wifi, sound, date or similar.
5100      This prevents "spooky" highlighting in the frame under the menu.  */
5101   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5102     {
5103       struct ns_display_info *di;
5104       BOOL has_focus = NO;
5105       for (di = x_display_list; ! has_focus && di; di = di->next)
5106         has_focus = di->x_focus_frame != 0;
5107       if (! has_focus)
5108         return;
5109     }
5110 #endif
5112   NSTRACE_UNSILENCE();
5114   [super sendEvent: theEvent];
5118 - (void)showPreferencesWindow: (id)sender
5120   struct frame *emacsframe = SELECTED_FRAME ();
5121   NSEvent *theEvent = [NSApp currentEvent];
5123   if (!emacs_event)
5124     return;
5125   emacs_event->kind = NS_NONKEY_EVENT;
5126   emacs_event->code = KEY_NS_SHOW_PREFS;
5127   emacs_event->modifiers = 0;
5128   EV_TRAILER (theEvent);
5132 - (void)newFrame: (id)sender
5134   NSTRACE ("[EmacsApp newFrame:]");
5136   struct frame *emacsframe = SELECTED_FRAME ();
5137   NSEvent *theEvent = [NSApp currentEvent];
5139   if (!emacs_event)
5140     return;
5141   emacs_event->kind = NS_NONKEY_EVENT;
5142   emacs_event->code = KEY_NS_NEW_FRAME;
5143   emacs_event->modifiers = 0;
5144   EV_TRAILER (theEvent);
5148 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5149 - (BOOL) openFile: (NSString *)fileName
5151   NSTRACE ("[EmacsApp openFile:]");
5153   struct frame *emacsframe = SELECTED_FRAME ();
5154   NSEvent *theEvent = [NSApp currentEvent];
5156   if (!emacs_event)
5157     return NO;
5159   emacs_event->kind = NS_NONKEY_EVENT;
5160   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5161   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5162   ns_input_line = Qnil; /* can be start or cons start,end */
5163   emacs_event->modifiers =0;
5164   EV_TRAILER (theEvent);
5166   return YES;
5170 /* **************************************************************************
5172       EmacsApp delegate implementation
5174    ************************************************************************** */
5176 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5177 /* --------------------------------------------------------------------------
5178      When application is loaded, terminate event loop in ns_term_init
5179    -------------------------------------------------------------------------- */
5181   NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5183 #ifdef NS_IMPL_GNUSTEP
5184   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5185 #endif
5186   [NSApp setServicesProvider: NSApp];
5188   [self antialiasThresholdDidChange:nil];
5189 #ifdef NS_IMPL_COCOA
5190   [[NSNotificationCenter defaultCenter]
5191     addObserver:self
5192        selector:@selector(antialiasThresholdDidChange:)
5193            name:NSAntialiasThresholdChangedNotification
5194          object:nil];
5195 #endif
5197   ns_send_appdefined (-2);
5200 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5202 #ifdef NS_IMPL_COCOA
5203   macfont_update_antialias_threshold ();
5204 #endif
5208 /* Termination sequences:
5209     C-x C-c:
5210     Cmd-Q:
5211     MenuBar | File | Exit:
5212     Select Quit from App menubar:
5213         -terminate
5214         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5215         ns_term_shutdown()
5217     Select Quit from Dock menu:
5218     Logout attempt:
5219         -appShouldTerminate
5220           Cancel -> Nothing else
5221           Accept ->
5223           -terminate
5224           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5225           ns_term_shutdown()
5229 - (void) terminate: (id)sender
5231   NSTRACE ("[EmacsApp terminate:]");
5233   struct frame *emacsframe = SELECTED_FRAME ();
5235   if (!emacs_event)
5236     return;
5238   emacs_event->kind = NS_NONKEY_EVENT;
5239   emacs_event->code = KEY_NS_POWER_OFF;
5240   emacs_event->arg = Qt; /* mark as non-key event */
5241   EV_TRAILER ((id)nil);
5244 static bool
5245 runAlertPanel(NSString *title,
5246               NSString *msgFormat,
5247               NSString *defaultButton,
5248               NSString *alternateButton)
5250 #if !defined (NS_IMPL_COCOA) || \
5251   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5252   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5253     == NSAlertDefaultReturn;
5254 #else
5255   NSAlert *alert = [[NSAlert alloc] init];
5256   [alert setAlertStyle: NSCriticalAlertStyle];
5257   [alert setMessageText: msgFormat];
5258   [alert addButtonWithTitle: defaultButton];
5259   [alert addButtonWithTitle: alternateButton];
5260   NSInteger ret = [alert runModal];
5261   [alert release];
5262   return ret == NSAlertFirstButtonReturn;
5263 #endif
5267 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5269   NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5271   bool ret;
5273   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
5274     return NSTerminateNow;
5276     ret = runAlertPanel(ns_app_name,
5277                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
5278                         @"Save Buffers and Exit", @"Cancel");
5280     if (ret)
5281         return NSTerminateNow;
5282     else
5283         return NSTerminateCancel;
5284     return NSTerminateNow;  /* just in case */
5287 static int
5288 not_in_argv (NSString *arg)
5290   int k;
5291   const char *a = [arg UTF8String];
5292   for (k = 1; k < initial_argc; ++k)
5293     if (strcmp (a, initial_argv[k]) == 0) return 0;
5294   return 1;
5297 /*   Notification from the Workspace to open a file */
5298 - (BOOL)application: sender openFile: (NSString *)file
5300   if (ns_do_open_file || not_in_argv (file))
5301     [ns_pending_files addObject: file];
5302   return YES;
5306 /*   Open a file as a temporary file */
5307 - (BOOL)application: sender openTempFile: (NSString *)file
5309   if (ns_do_open_file || not_in_argv (file))
5310     [ns_pending_files addObject: file];
5311   return YES;
5315 /*   Notification from the Workspace to open a file noninteractively (?) */
5316 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5318   if (ns_do_open_file || not_in_argv (file))
5319     [ns_pending_files addObject: file];
5320   return YES;
5323 /*   Notification from the Workspace to open multiple files */
5324 - (void)application: sender openFiles: (NSArray *)fileList
5326   NSEnumerator *files = [fileList objectEnumerator];
5327   NSString *file;
5328   /* Don't open files from the command line unconditionally,
5329      Cocoa parses the command line wrong, --option value tries to open value
5330      if --option is the last option.  */
5331   while ((file = [files nextObject]) != nil)
5332     if (ns_do_open_file || not_in_argv (file))
5333       [ns_pending_files addObject: file];
5335   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5340 /* Handle dock menu requests.  */
5341 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5343   return dockMenu;
5347 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5348 - (void)applicationWillBecomeActive: (NSNotification *)notification
5350   NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5351   //ns_app_active=YES;
5354 - (void)applicationDidBecomeActive: (NSNotification *)notification
5356   NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5358 #ifdef NS_IMPL_GNUSTEP
5359   if (! applicationDidFinishLaunchingCalled)
5360     [self applicationDidFinishLaunching:notification];
5361 #endif
5362   //ns_app_active=YES;
5364   ns_update_auto_hide_menu_bar ();
5365   // No constraining takes place when the application is not active.
5366   ns_constrain_all_frames ();
5368 - (void)applicationDidResignActive: (NSNotification *)notification
5370   NSTRACE ("[EmacsApp applicationDidResignActive:]");
5372   //ns_app_active=NO;
5373   ns_send_appdefined (-1);
5378 /* ==========================================================================
5380     EmacsApp aux handlers for managing event loop
5382    ========================================================================== */
5385 - (void)timeout_handler: (NSTimer *)timedEntry
5386 /* --------------------------------------------------------------------------
5387      The timeout specified to ns_select has passed.
5388    -------------------------------------------------------------------------- */
5390   /*NSTRACE ("timeout_handler"); */
5391   ns_send_appdefined (-2);
5394 #ifdef NS_IMPL_GNUSTEP
5395 - (void)sendFromMainThread:(id)unused
5397   ns_send_appdefined (nextappdefined);
5399 #endif
5401 - (void)fd_handler:(id)unused
5402 /* --------------------------------------------------------------------------
5403      Check data waiting on file descriptors and terminate if so
5404    -------------------------------------------------------------------------- */
5406   int result;
5407   int waiting = 1, nfds;
5408   char c;
5410   fd_set readfds, writefds, *wfds;
5411   struct timespec timeout, *tmo;
5412   NSAutoreleasePool *pool = nil;
5414   /* NSTRACE ("fd_handler"); */
5416   for (;;)
5417     {
5418       [pool release];
5419       pool = [[NSAutoreleasePool alloc] init];
5421       if (waiting)
5422         {
5423           fd_set fds;
5424           FD_ZERO (&fds);
5425           FD_SET (selfds[0], &fds);
5426           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5427           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5428             waiting = 0;
5429         }
5430       else
5431         {
5432           pthread_mutex_lock (&select_mutex);
5433           nfds = select_nfds;
5435           if (select_valid & SELECT_HAVE_READ)
5436             readfds = select_readfds;
5437           else
5438             FD_ZERO (&readfds);
5440           if (select_valid & SELECT_HAVE_WRITE)
5441             {
5442               writefds = select_writefds;
5443               wfds = &writefds;
5444             }
5445           else
5446             wfds = NULL;
5447           if (select_valid & SELECT_HAVE_TMO)
5448             {
5449               timeout = select_timeout;
5450               tmo = &timeout;
5451             }
5452           else
5453             tmo = NULL;
5455           pthread_mutex_unlock (&select_mutex);
5457           FD_SET (selfds[0], &readfds);
5458           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5460           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5462           if (result == 0)
5463             ns_send_appdefined (-2);
5464           else if (result > 0)
5465             {
5466               if (FD_ISSET (selfds[0], &readfds))
5467                 {
5468                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5469                     waiting = 1;
5470                 }
5471               else
5472                 {
5473                   pthread_mutex_lock (&select_mutex);
5474                   if (select_valid & SELECT_HAVE_READ)
5475                     select_readfds = readfds;
5476                   if (select_valid & SELECT_HAVE_WRITE)
5477                     select_writefds = writefds;
5478                   if (select_valid & SELECT_HAVE_TMO)
5479                     select_timeout = timeout;
5480                   pthread_mutex_unlock (&select_mutex);
5482                   ns_send_appdefined (result);
5483                 }
5484             }
5485           waiting = 1;
5486         }
5487     }
5492 /* ==========================================================================
5494     Service provision
5496    ========================================================================== */
5498 /* called from system: queue for next pass through event loop */
5499 - (void)requestService: (NSPasteboard *)pboard
5500               userData: (NSString *)userData
5501                  error: (NSString **)error
5503   [ns_pending_service_names addObject: userData];
5504   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5505       SSDATA (ns_string_from_pasteboard (pboard))]];
5509 /* called from ns_read_socket to clear queue */
5510 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5512   struct frame *emacsframe = SELECTED_FRAME ();
5513   NSEvent *theEvent = [NSApp currentEvent];
5515   NSTRACE ("[EmacsApp fulfillService:withArg:]");
5517   if (!emacs_event)
5518     return NO;
5520   emacs_event->kind = NS_NONKEY_EVENT;
5521   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5522   ns_input_spi_name = build_string ([name UTF8String]);
5523   ns_input_spi_arg = build_string ([arg UTF8String]);
5524   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5525   EV_TRAILER (theEvent);
5527   return YES;
5531 @end  /* EmacsApp */
5535 /* ==========================================================================
5537     EmacsView implementation
5539    ========================================================================== */
5542 @implementation EmacsView
5544 /* needed to inform when window closed from LISP */
5545 - (void) setWindowClosing: (BOOL)closing
5547   NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5549   windowClosing = closing;
5553 - (void)dealloc
5555   NSTRACE ("[EmacsView dealloc]");
5556   [toolbar release];
5557   if (fs_state == FULLSCREEN_BOTH)
5558     [nonfs_window release];
5559   [super dealloc];
5563 /* called on font panel selection */
5564 - (void)changeFont: (id)sender
5566   NSEvent *e = [[self window] currentEvent];
5567   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5568   struct font *font = face->font;
5569   id newFont;
5570   CGFloat size;
5571   NSFont *nsfont;
5573   NSTRACE ("[EmacsView changeFont:]");
5575   if (!emacs_event)
5576     return;
5578 #ifdef NS_IMPL_GNUSTEP
5579   nsfont = ((struct nsfont_info *)font)->nsfont;
5580 #endif
5581 #ifdef NS_IMPL_COCOA
5582   nsfont = (NSFont *) macfont_get_nsctfont (font);
5583 #endif
5585   if ((newFont = [sender convertFont: nsfont]))
5586     {
5587       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5589       emacs_event->kind = NS_NONKEY_EVENT;
5590       emacs_event->modifiers = 0;
5591       emacs_event->code = KEY_NS_CHANGE_FONT;
5593       size = [newFont pointSize];
5594       ns_input_fontsize = make_number (lrint (size));
5595       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5596       EV_TRAILER (e);
5597     }
5601 - (BOOL)acceptsFirstResponder
5603   NSTRACE ("[EmacsView acceptsFirstResponder]");
5604   return YES;
5608 - (void)resetCursorRects
5610   NSRect visible = [self visibleRect];
5611   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5612   NSTRACE ("[EmacsView resetCursorRects]");
5614   if (currentCursor == nil)
5615     currentCursor = [NSCursor arrowCursor];
5617   if (!NSIsEmptyRect (visible))
5618     [self addCursorRect: visible cursor: currentCursor];
5619   [currentCursor setOnMouseEntered: YES];
5624 /*****************************************************************************/
5625 /* Keyboard handling. */
5626 #define NS_KEYLOG 0
5628 - (void)keyDown: (NSEvent *)theEvent
5630   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5631   int code;
5632   unsigned fnKeysym = 0;
5633   static NSMutableArray *nsEvArray;
5634   int left_is_none;
5635   unsigned int flags = [theEvent modifierFlags];
5637   NSTRACE ("[EmacsView keyDown:]");
5639   /* Rhapsody and OS X give up and down events for the arrow keys */
5640   if (ns_fake_keydown == YES)
5641     ns_fake_keydown = NO;
5642   else if ([theEvent type] != NSKeyDown)
5643     return;
5645   if (!emacs_event)
5646     return;
5648  if (![[self window] isKeyWindow]
5649      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5650      /* we must avoid an infinite loop here. */
5651      && (EmacsView *)[[theEvent window] delegate] != self)
5652    {
5653      /* XXX: There is an occasional condition in which, when Emacs display
5654          updates a different frame from the current one, and temporarily
5655          selects it, then processes some interrupt-driven input
5656          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5657          for some reason that window has its first responder set to the NSView
5658          most recently updated (I guess), which is not the correct one. */
5659      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5660      return;
5661    }
5663   if (nsEvArray == nil)
5664     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5666   [NSCursor setHiddenUntilMouseMoves: YES];
5668   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5669     {
5670       clear_mouse_face (hlinfo);
5671       hlinfo->mouse_face_hidden = 1;
5672     }
5674   if (!processingCompose)
5675     {
5676       /* When using screen sharing, no left or right information is sent,
5677          so use Left key in those cases.  */
5678       int is_left_key, is_right_key;
5680       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5681         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5683       /* (Carbon way: [theEvent keyCode]) */
5685       /* is it a "function key"? */
5686       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5687          flag set (this is probably a bug in the OS).
5688       */
5689       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5690         {
5691           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5692         }
5693       if (fnKeysym == 0)
5694         {
5695           fnKeysym = ns_convert_key (code);
5696         }
5698       if (fnKeysym)
5699         {
5700           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5701              because Emacs treats Delete and KP-Delete same (in simple.el). */
5702           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5703 #ifdef NS_IMPL_GNUSTEP
5704               /*  GNUstep uses incompatible keycodes, even for those that are
5705                   supposed to be hardware independent.  Just check for delete.
5706                   Keypad delete does not have keysym 0xFFFF.
5707                   See http://savannah.gnu.org/bugs/?25395
5708               */
5709               || (fnKeysym == 0xFFFF && code == 127)
5710 #endif
5711             )
5712             code = 0xFF08; /* backspace */
5713           else
5714             code = fnKeysym;
5715         }
5717       /* are there modifiers? */
5718       emacs_event->modifiers = 0;
5720       if (flags & NSHelpKeyMask)
5721           emacs_event->modifiers |= hyper_modifier;
5723       if (flags & NSShiftKeyMask)
5724         emacs_event->modifiers |= shift_modifier;
5726       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5727       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5728         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5730       if (is_right_key)
5731         emacs_event->modifiers |= parse_solitary_modifier
5732           (EQ (ns_right_command_modifier, Qleft)
5733            ? ns_command_modifier
5734            : ns_right_command_modifier);
5736       if (is_left_key)
5737         {
5738           emacs_event->modifiers |= parse_solitary_modifier
5739             (ns_command_modifier);
5741           /* if super (default), take input manager's word so things like
5742              dvorak / qwerty layout work */
5743           if (EQ (ns_command_modifier, Qsuper)
5744               && !fnKeysym
5745               && [[theEvent characters] length] != 0)
5746             {
5747               /* XXX: the code we get will be unshifted, so if we have
5748                  a shift modifier, must convert ourselves */
5749               if (!(flags & NSShiftKeyMask))
5750                 code = [[theEvent characters] characterAtIndex: 0];
5751 #if 0
5752               /* this is ugly and also requires linking w/Carbon framework
5753                  (for LMGetKbdType) so for now leave this rare (?) case
5754                  undealt with.. in future look into CGEvent methods */
5755               else
5756                 {
5757                   long smv = GetScriptManagerVariable (smKeyScript);
5758                   Handle uchrHandle = GetResource
5759                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5760                   UInt32 dummy = 0;
5761                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5762                                  [[theEvent characters] characterAtIndex: 0],
5763                                  kUCKeyActionDisplay,
5764                                  (flags & ~NSCommandKeyMask) >> 8,
5765                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5766                                  &dummy, 1, &dummy, &code);
5767                   code &= 0xFF;
5768                 }
5769 #endif
5770             }
5771         }
5773       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5774       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5775         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5777       if (is_right_key)
5778           emacs_event->modifiers |= parse_solitary_modifier
5779               (EQ (ns_right_control_modifier, Qleft)
5780                ? ns_control_modifier
5781                : ns_right_control_modifier);
5783       if (is_left_key)
5784         emacs_event->modifiers |= parse_solitary_modifier
5785           (ns_control_modifier);
5787       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5788           emacs_event->modifiers |=
5789             parse_solitary_modifier (ns_function_modifier);
5791       left_is_none = NILP (ns_alternate_modifier)
5792         || EQ (ns_alternate_modifier, Qnone);
5794       is_right_key = (flags & NSRightAlternateKeyMask)
5795         == NSRightAlternateKeyMask;
5796       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5797         || (! is_right_key
5798             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5800       if (is_right_key)
5801         {
5802           if ((NILP (ns_right_alternate_modifier)
5803                || EQ (ns_right_alternate_modifier, Qnone)
5804                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5805               && !fnKeysym)
5806             {   /* accept pre-interp alt comb */
5807               if ([[theEvent characters] length] > 0)
5808                 code = [[theEvent characters] characterAtIndex: 0];
5809               /*HACK: clear lone shift modifier to stop next if from firing */
5810               if (emacs_event->modifiers == shift_modifier)
5811                 emacs_event->modifiers = 0;
5812             }
5813           else
5814             emacs_event->modifiers |= parse_solitary_modifier
5815               (EQ (ns_right_alternate_modifier, Qleft)
5816                ? ns_alternate_modifier
5817                : ns_right_alternate_modifier);
5818         }
5820       if (is_left_key) /* default = meta */
5821         {
5822           if (left_is_none && !fnKeysym)
5823             {   /* accept pre-interp alt comb */
5824               if ([[theEvent characters] length] > 0)
5825                 code = [[theEvent characters] characterAtIndex: 0];
5826               /*HACK: clear lone shift modifier to stop next if from firing */
5827               if (emacs_event->modifiers == shift_modifier)
5828                 emacs_event->modifiers = 0;
5829             }
5830           else
5831               emacs_event->modifiers |=
5832                 parse_solitary_modifier (ns_alternate_modifier);
5833         }
5835   if (NS_KEYLOG)
5836     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5837              code, fnKeysym, flags, emacs_event->modifiers);
5839       /* if it was a function key or had modifiers, pass it directly to emacs */
5840       if (fnKeysym || (emacs_event->modifiers
5841                        && (emacs_event->modifiers != shift_modifier)
5842                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5843 /*[[theEvent characters] length] */
5844         {
5845           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5846           if (code < 0x20)
5847             code |= (1<<28)|(3<<16);
5848           else if (code == 0x7f)
5849             code |= (1<<28)|(3<<16);
5850           else if (!fnKeysym)
5851             emacs_event->kind = code > 0xFF
5852               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5854           emacs_event->code = code;
5855           EV_TRAILER (theEvent);
5856           processingCompose = NO;
5857           return;
5858         }
5859     }
5862   if (NS_KEYLOG && !processingCompose)
5863     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5865   processingCompose = YES;
5866   [nsEvArray addObject: theEvent];
5867   [self interpretKeyEvents: nsEvArray];
5868   [nsEvArray removeObject: theEvent];
5872 #ifdef NS_IMPL_COCOA
5873 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5874    decided not to send key-down for.
5875    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5876    This only applies on Tiger and earlier.
5877    If it matches one of these, send it on to keyDown. */
5878 -(void)keyUp: (NSEvent *)theEvent
5880   int flags = [theEvent modifierFlags];
5881   int code = [theEvent keyCode];
5883   NSTRACE ("[EmacsView keyUp:]");
5885   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5886       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5887     {
5888       if (NS_KEYLOG)
5889         fprintf (stderr, "keyUp: passed test");
5890       ns_fake_keydown = YES;
5891       [self keyDown: theEvent];
5892     }
5894 #endif
5897 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5900 /* <NSTextInput>: called when done composing;
5901    NOTE: also called when we delete over working text, followed immed.
5902          by doCommandBySelector: deleteBackward: */
5903 - (void)insertText: (id)aString
5905   int code;
5906   int len = [(NSString *)aString length];
5907   int i;
5909   NSTRACE ("[EmacsView insertText:]");
5911   if (NS_KEYLOG)
5912     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5913   processingCompose = NO;
5915   if (!emacs_event)
5916     return;
5918   /* first, clear any working text */
5919   if (workingText != nil)
5920     [self deleteWorkingText];
5922   /* now insert the string as keystrokes */
5923   for (i =0; i<len; i++)
5924     {
5925       code = [aString characterAtIndex: i];
5926       /* TODO: still need this? */
5927       if (code == 0x2DC)
5928         code = '~'; /* 0x7E */
5929       if (code != 32) /* Space */
5930         emacs_event->modifiers = 0;
5931       emacs_event->kind
5932         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5933       emacs_event->code = code;
5934       EV_TRAILER ((id)nil);
5935     }
5939 /* <NSTextInput>: inserts display of composing characters */
5940 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5942   NSString *str = [aString respondsToSelector: @selector (string)] ?
5943     [aString string] : aString;
5945   NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
5947   if (NS_KEYLOG)
5948     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5949            str, (unsigned long)[str length],
5950            (unsigned long)selRange.length,
5951            (unsigned long)selRange.location);
5953   if (workingText != nil)
5954     [self deleteWorkingText];
5955   if ([str length] == 0)
5956     return;
5958   if (!emacs_event)
5959     return;
5961   processingCompose = YES;
5962   workingText = [str copy];
5963   ns_working_text = build_string ([workingText UTF8String]);
5965   emacs_event->kind = NS_TEXT_EVENT;
5966   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5967   EV_TRAILER ((id)nil);
5971 /* delete display of composing characters [not in <NSTextInput>] */
5972 - (void)deleteWorkingText
5974   NSTRACE ("[EmacsView deleteWorkingText]");
5976   if (workingText == nil)
5977     return;
5978   if (NS_KEYLOG)
5979     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5980   [workingText release];
5981   workingText = nil;
5982   processingCompose = NO;
5984   if (!emacs_event)
5985     return;
5987   emacs_event->kind = NS_TEXT_EVENT;
5988   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5989   EV_TRAILER ((id)nil);
5993 - (BOOL)hasMarkedText
5995   NSTRACE ("[EmacsView hasMarkedText]");
5997   return workingText != nil;
6001 - (NSRange)markedRange
6003   NSTRACE ("[EmacsView markedRange]");
6005   NSRange rng = workingText != nil
6006     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6007   if (NS_KEYLOG)
6008     NSLog (@"markedRange request");
6009   return rng;
6013 - (void)unmarkText
6015   NSTRACE ("[EmacsView unmarkText]");
6017   if (NS_KEYLOG)
6018     NSLog (@"unmark (accept) text");
6019   [self deleteWorkingText];
6020   processingCompose = NO;
6024 /* used to position char selection windows, etc. */
6025 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6027   NSRect rect;
6028   NSPoint pt;
6029   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6031   NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6033   if (NS_KEYLOG)
6034     NSLog (@"firstRectForCharRange request");
6036   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6037   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6038   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6039   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6040                                        +FRAME_LINE_HEIGHT (emacsframe));
6042   pt = [self convertPoint: pt toView: nil];
6043   pt = [[self window] convertBaseToScreen: pt];
6044   rect.origin = pt;
6045   return rect;
6049 - (NSInteger)conversationIdentifier
6051   return (NSInteger)self;
6055 - (void)doCommandBySelector: (SEL)aSelector
6057   NSTRACE ("[EmacsView doCommandBySelector:]");
6059   if (NS_KEYLOG)
6060     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6062   processingCompose = NO;
6063   if (aSelector == @selector (deleteBackward:))
6064     {
6065       /* happens when user backspaces over an ongoing composition:
6066          throw a 'delete' into the event queue */
6067       if (!emacs_event)
6068         return;
6069       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6070       emacs_event->code = 0xFF08;
6071       EV_TRAILER ((id)nil);
6072     }
6075 - (NSArray *)validAttributesForMarkedText
6077   static NSArray *arr = nil;
6078   if (arr == nil) arr = [NSArray new];
6079  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6080   return arr;
6083 - (NSRange)selectedRange
6085   if (NS_KEYLOG)
6086     NSLog (@"selectedRange request");
6087   return NSMakeRange (NSNotFound, 0);
6090 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6091     GNUSTEP_GUI_MINOR_VERSION > 22
6092 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6093 #else
6094 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6095 #endif
6097   if (NS_KEYLOG)
6098     NSLog (@"characterIndexForPoint request");
6099   return 0;
6102 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6104   static NSAttributedString *str = nil;
6105   if (str == nil) str = [NSAttributedString new];
6106   if (NS_KEYLOG)
6107     NSLog (@"attributedSubstringFromRange request");
6108   return str;
6111 /* End <NSTextInput> impl. */
6112 /*****************************************************************************/
6115 /* This is what happens when the user presses a mouse button.  */
6116 - (void)mouseDown: (NSEvent *)theEvent
6118   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6119   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6121   NSTRACE ("[EmacsView mouseDown:]");
6123   [self deleteWorkingText];
6125   if (!emacs_event)
6126     return;
6128   dpyinfo->last_mouse_frame = emacsframe;
6129   /* appears to be needed to prevent spurious movement events generated on
6130      button clicks */
6131   emacsframe->mouse_moved = 0;
6133   if ([theEvent type] == NSScrollWheel)
6134     {
6135       CGFloat delta = [theEvent deltaY];
6136       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6137       if (delta == 0)
6138         {
6139           delta = [theEvent deltaX];
6140           if (delta == 0)
6141             {
6142               NSTRACE_MSG ("deltaIsZero");
6143               return;
6144             }
6145           emacs_event->kind = HORIZ_WHEEL_EVENT;
6146         }
6147       else
6148         emacs_event->kind = WHEEL_EVENT;
6150       emacs_event->code = 0;
6151       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6152         ((delta > 0) ? up_modifier : down_modifier);
6153     }
6154   else
6155     {
6156       emacs_event->kind = MOUSE_CLICK_EVENT;
6157       emacs_event->code = EV_BUTTON (theEvent);
6158       emacs_event->modifiers = EV_MODIFIERS (theEvent)
6159                              | EV_UDMODIFIERS (theEvent);
6160     }
6161   XSETINT (emacs_event->x, lrint (p.x));
6162   XSETINT (emacs_event->y, lrint (p.y));
6163   EV_TRAILER (theEvent);
6167 - (void)rightMouseDown: (NSEvent *)theEvent
6169   NSTRACE ("[EmacsView rightMouseDown:]");
6170   [self mouseDown: theEvent];
6174 - (void)otherMouseDown: (NSEvent *)theEvent
6176   NSTRACE ("[EmacsView otherMouseDown:]");
6177   [self mouseDown: theEvent];
6181 - (void)mouseUp: (NSEvent *)theEvent
6183   NSTRACE ("[EmacsView mouseUp:]");
6184   [self mouseDown: theEvent];
6188 - (void)rightMouseUp: (NSEvent *)theEvent
6190   NSTRACE ("[EmacsView rightMouseUp:]");
6191   [self mouseDown: theEvent];
6195 - (void)otherMouseUp: (NSEvent *)theEvent
6197   NSTRACE ("[EmacsView otherMouseUp:]");
6198   [self mouseDown: theEvent];
6202 - (void) scrollWheel: (NSEvent *)theEvent
6204   NSTRACE ("[EmacsView scrollWheel:]");
6205   [self mouseDown: theEvent];
6209 /* Tell emacs the mouse has moved. */
6210 - (void)mouseMoved: (NSEvent *)e
6212   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6213   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6214   Lisp_Object frame;
6215   NSPoint pt;
6217   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6219   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6220   pt = [self convertPoint: [e locationInWindow] fromView: nil];
6221   dpyinfo->last_mouse_motion_x = pt.x;
6222   dpyinfo->last_mouse_motion_y = pt.y;
6224   /* update any mouse face */
6225   if (hlinfo->mouse_face_hidden)
6226     {
6227       hlinfo->mouse_face_hidden = 0;
6228       clear_mouse_face (hlinfo);
6229     }
6231   /* tooltip handling */
6232   previous_help_echo_string = help_echo_string;
6233   help_echo_string = Qnil;
6235   if (!NILP (Vmouse_autoselect_window))
6236     {
6237       NSTRACE_MSG ("mouse_autoselect_window");
6238       static Lisp_Object last_mouse_window;
6239       Lisp_Object window
6240         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6242       if (WINDOWP (window)
6243           && !EQ (window, last_mouse_window)
6244           && !EQ (window, selected_window)
6245           && (focus_follows_mouse
6246               || (EQ (XWINDOW (window)->frame,
6247                       XWINDOW (selected_window)->frame))))
6248         {
6249           NSTRACE_MSG ("in_window");
6250           emacs_event->kind = SELECT_WINDOW_EVENT;
6251           emacs_event->frame_or_window = window;
6252           EV_TRAILER2 (e);
6253         }
6254       /* Remember the last window where we saw the mouse.  */
6255       last_mouse_window = window;
6256     }
6258   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6259     help_echo_string = previous_help_echo_string;
6261   XSETFRAME (frame, emacsframe);
6262   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6263     {
6264       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6265          (note_mouse_highlight), which is called through the
6266          note_mouse_movement () call above */
6267       any_help_event_p = YES;
6268       gen_help_event (help_echo_string, frame, help_echo_window,
6269                       help_echo_object, help_echo_pos);
6270     }
6272   if (emacsframe->mouse_moved && send_appdefined)
6273     ns_send_appdefined (-1);
6277 - (void)mouseDragged: (NSEvent *)e
6279   NSTRACE ("[EmacsView mouseDragged:]");
6280   [self mouseMoved: e];
6284 - (void)rightMouseDragged: (NSEvent *)e
6286   NSTRACE ("[EmacsView rightMouseDragged:]");
6287   [self mouseMoved: e];
6291 - (void)otherMouseDragged: (NSEvent *)e
6293   NSTRACE ("[EmacsView otherMouseDragged:]");
6294   [self mouseMoved: e];
6298 - (BOOL)windowShouldClose: (id)sender
6300   NSEvent *e =[[self window] currentEvent];
6302   NSTRACE ("[EmacsView windowShouldClose:]");
6303   windowClosing = YES;
6304   if (!emacs_event)
6305     return NO;
6306   emacs_event->kind = DELETE_WINDOW_EVENT;
6307   emacs_event->modifiers = 0;
6308   emacs_event->code = 0;
6309   EV_TRAILER (e);
6310   /* Don't close this window, let this be done from lisp code.  */
6311   return NO;
6314 - (void) updateFrameSize: (BOOL) delay;
6316   NSWindow *window = [self window];
6317   NSRect wr = [window frame];
6318   int extra = 0;
6319   int oldc = cols, oldr = rows;
6320   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6321   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6322   int neww, newh;
6324   NSTRACE ("[EmacsView updateFrameSize:]");
6325   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6326   NSTRACE_RECT ("Original frame", wr);
6327   NSTRACE_MSG  ("Original columns: %d", cols);
6328   NSTRACE_MSG  ("Original rows: %d", rows);
6330   if (! [self isFullscreen])
6331     {
6332 #ifdef NS_IMPL_GNUSTEP
6333       // GNUstep does not always update the tool bar height.  Force it.
6334       if (toolbar && [toolbar isVisible])
6335           update_frame_tool_bar (emacsframe);
6336 #endif
6338       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6339         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6340     }
6342   if (wait_for_tool_bar)
6343     {
6344       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6345         {
6346           NSTRACE_MSG ("Waiting for toolbar");
6347           return;
6348         }
6349       wait_for_tool_bar = NO;
6350     }
6352   neww = (int)wr.size.width - emacsframe->border_width;
6353   newh = (int)wr.size.height - extra;
6355   NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6356   NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6358   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6359   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6361   if (cols < MINWIDTH)
6362     cols = MINWIDTH;
6364   if (rows < MINHEIGHT)
6365     rows = MINHEIGHT;
6367   NSTRACE_MSG ("New columns: %d", cols);
6368   NSTRACE_MSG ("New rows: %d", rows);
6370   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6371     {
6372       NSView *view = FRAME_NS_VIEW (emacsframe);
6374       change_frame_size (emacsframe,
6375                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6376                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6377                          0, delay, 0, 1);
6378       SET_FRAME_GARBAGED (emacsframe);
6379       cancel_mouse_face (emacsframe);
6381       wr = NSMakeRect (0, 0, neww, newh);
6383       [view setFrame: wr];
6385       // to do: consider using [NSNotificationCenter postNotificationName:].
6386       [self windowDidMove: // Update top/left.
6387               [NSNotification notificationWithName:NSWindowDidMoveNotification
6388                                             object:[view window]]];
6389     }
6390   else
6391     {
6392       NSTRACE_MSG ("No change");
6393     }
6396 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6397 /* normalize frame to gridded text size */
6399   int extra = 0;
6401   NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6402            NSTRACE_ARG_SIZE (frameSize));
6403   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6404   NSTRACE_FSTYPE ("fs_state", fs_state);
6406   if (fs_state == FULLSCREEN_MAXIMIZED
6407       && (maximized_width != (int)frameSize.width
6408           || maximized_height != (int)frameSize.height))
6409     [self setFSValue: FULLSCREEN_NONE];
6410   else if (fs_state == FULLSCREEN_WIDTH
6411            && maximized_width != (int)frameSize.width)
6412     [self setFSValue: FULLSCREEN_NONE];
6413   else if (fs_state == FULLSCREEN_HEIGHT
6414            && maximized_height != (int)frameSize.height)
6415     [self setFSValue: FULLSCREEN_NONE];
6417   if (fs_state == FULLSCREEN_NONE)
6418     maximized_width = maximized_height = -1;
6420   if (! [self isFullscreen])
6421     {
6422       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6423         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6424     }
6426   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6427   if (cols < MINWIDTH)
6428     cols = MINWIDTH;
6430   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6431                                            frameSize.height - extra);
6432   if (rows < MINHEIGHT)
6433     rows = MINHEIGHT;
6434 #ifdef NS_IMPL_COCOA
6435   {
6436     /* this sets window title to have size in it; the wm does this under GS */
6437     NSRect r = [[self window] frame];
6438     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6439       {
6440         if (old_title != 0)
6441           {
6442             xfree (old_title);
6443             old_title = 0;
6444           }
6445       }
6446     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6447       {
6448         char *size_title;
6449         NSWindow *window = [self window];
6450         if (old_title == 0)
6451           {
6452             char *t = strdup ([[[self window] title] UTF8String]);
6453             char *pos = strstr (t, "  â€”  ");
6454             if (pos)
6455               *pos = '\0';
6456             old_title = t;
6457           }
6458         size_title = xmalloc (strlen (old_title) + 40);
6459         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6460         [window setTitle: [NSString stringWithUTF8String: size_title]];
6461         [window display];
6462         xfree (size_title);
6463       }
6464   }
6465 #endif /* NS_IMPL_COCOA */
6467   NSTRACE_MSG ("cols: %d  rows: %d", cols, rows);
6469   /* Restrict the new size to the text gird.
6471      Don't restrict the width if the user only adjusted the height, and
6472      vice versa.  (Without this, the frame would shrink, and move
6473      slightly, if the window was resized by dragging one of its
6474      borders.) */
6475   if (!frame_resize_pixelwise)
6476     {
6477       NSRect r = [[self window] frame];
6479       if (r.size.width != frameSize.width)
6480         {
6481           frameSize.width =
6482             FRAME_TEXT_COLS_TO_PIXEL_WIDTH  (emacsframe, cols);
6483         }
6485       if (r.size.height != frameSize.height)
6486         {
6487           frameSize.height =
6488             FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6489         }
6490     }
6492   NSTRACE_RETURN_SIZE (frameSize);
6494   return frameSize;
6498 - (void)windowDidResize: (NSNotification *)notification
6500   NSTRACE ("[EmacsView windowDidResize:]");
6501   if (!FRAME_LIVE_P (emacsframe))
6502     {
6503       NSTRACE_MSG ("Ignored (frame dead)");
6504       return;
6505     }
6506   if (emacsframe->output_data.ns->in_animation)
6507     {
6508       NSTRACE_MSG ("Ignored (in animation)");
6509       return;
6510     }
6512   if (! [self fsIsNative])
6513     {
6514       NSWindow *theWindow = [notification object];
6515       /* We can get notification on the non-FS window when in
6516          fullscreen mode.  */
6517       if ([self window] != theWindow) return;
6518     }
6520   NSTRACE_RECT ("frame", [[notification object] frame]);
6522 #ifdef NS_IMPL_GNUSTEP
6523   NSWindow *theWindow = [notification object];
6525    /* In GNUstep, at least currently, it's possible to get a didResize
6526       without getting a willResize.. therefore we need to act as if we got
6527       the willResize now */
6528   NSSize sz = [theWindow frame].size;
6529   sz = [self windowWillResize: theWindow toSize: sz];
6530 #endif /* NS_IMPL_GNUSTEP */
6532   if (cols > 0 && rows > 0)
6533     {
6534       [self updateFrameSize: YES];
6535     }
6537   ns_send_appdefined (-1);
6540 #ifdef NS_IMPL_COCOA
6541 - (void)viewDidEndLiveResize
6543   NSTRACE ("[EmacsView viewDidEndLiveResize]");
6545   [super viewDidEndLiveResize];
6546   if (old_title != 0)
6547     {
6548       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6549       xfree (old_title);
6550       old_title = 0;
6551     }
6552   maximizing_resize = NO;
6554 #endif /* NS_IMPL_COCOA */
6557 - (void)windowDidBecomeKey: (NSNotification *)notification
6558 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6560   [self windowDidBecomeKey];
6564 - (void)windowDidBecomeKey      /* for direct calls */
6566   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6567   struct frame *old_focus = dpyinfo->x_focus_frame;
6569   NSTRACE ("[EmacsView windowDidBecomeKey]");
6571   if (emacsframe != old_focus)
6572     dpyinfo->x_focus_frame = emacsframe;
6574   ns_frame_rehighlight (emacsframe);
6576   if (emacs_event)
6577     {
6578       emacs_event->kind = FOCUS_IN_EVENT;
6579       EV_TRAILER ((id)nil);
6580     }
6584 - (void)windowDidResignKey: (NSNotification *)notification
6585 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6587   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6588   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6589   NSTRACE ("[EmacsView windowDidResignKey:]");
6591   if (is_focus_frame)
6592     dpyinfo->x_focus_frame = 0;
6594   emacsframe->mouse_moved = 0;
6595   ns_frame_rehighlight (emacsframe);
6597   /* FIXME: for some reason needed on second and subsequent clicks away
6598             from sole-frame Emacs to get hollow box to show */
6599   if (!windowClosing && [[self window] isVisible] == YES)
6600     {
6601       x_update_cursor (emacsframe, 1);
6602       x_set_frame_alpha (emacsframe);
6603     }
6605   if (any_help_event_p)
6606     {
6607       Lisp_Object frame;
6608       XSETFRAME (frame, emacsframe);
6609       help_echo_string = Qnil;
6610       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6611     }
6613   if (emacs_event && is_focus_frame)
6614     {
6615       [self deleteWorkingText];
6616       emacs_event->kind = FOCUS_OUT_EVENT;
6617       EV_TRAILER ((id)nil);
6618     }
6622 - (void)windowWillMiniaturize: sender
6624   NSTRACE ("[EmacsView windowWillMiniaturize:]");
6628 - (void)setFrame:(NSRect)frameRect;
6630   NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6631            NSTRACE_ARG_RECT (frameRect));
6633   [super setFrame:(NSRect)frameRect];
6637 - (BOOL)isFlipped
6639   return YES;
6643 - (BOOL)isOpaque
6645   return NO;
6649 - initFrameFromEmacs: (struct frame *)f
6651   NSRect r, wr;
6652   Lisp_Object tem;
6653   NSWindow *win;
6654   NSColor *col;
6655   NSString *name;
6657   NSTRACE ("[EmacsView initFrameFromEmacs:]");
6658   NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6660   windowClosing = NO;
6661   processingCompose = NO;
6662   scrollbarsNeedingUpdate = 0;
6663   fs_state = FULLSCREEN_NONE;
6664   fs_before_fs = next_maximized = -1;
6665 #ifdef HAVE_NATIVE_FS
6666   fs_is_native = ns_use_native_fullscreen;
6667 #else
6668   fs_is_native = NO;
6669 #endif
6670   maximized_width = maximized_height = -1;
6671   nonfs_window = nil;
6673   ns_userRect = NSMakeRect (0, 0, 0, 0);
6674   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6675                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6676   [self initWithFrame: r];
6677   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6679   FRAME_NS_VIEW (f) = self;
6680   emacsframe = f;
6681 #ifdef NS_IMPL_COCOA
6682   old_title = 0;
6683   maximizing_resize = NO;
6684 #endif
6686   win = [[EmacsWindow alloc]
6687             initWithContentRect: r
6688                       styleMask: (NSResizableWindowMask |
6689 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6690                                   NSTitledWindowMask |
6691 #endif
6692                                   NSMiniaturizableWindowMask |
6693                                   NSClosableWindowMask)
6694                         backing: NSBackingStoreBuffered
6695                           defer: YES];
6697 #ifdef HAVE_NATIVE_FS
6698     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6699 #endif
6701   wr = [win frame];
6702   bwidth = f->border_width = wr.size.width - r.size.width;
6703   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6705   [win setAcceptsMouseMovedEvents: YES];
6706   [win setDelegate: self];
6707 #if !defined (NS_IMPL_COCOA) || \
6708   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6709   [win useOptimizedDrawing: YES];
6710 #endif
6712   [[win contentView] addSubview: self];
6714   if (ns_drag_types)
6715     [self registerForDraggedTypes: ns_drag_types];
6717   tem = f->name;
6718   name = [NSString stringWithUTF8String:
6719                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6720   [win setTitle: name];
6722   /* toolbar support */
6723   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6724                          [NSString stringWithFormat: @"Emacs Frame %d",
6725                                    ns_window_num]];
6726   [win setToolbar: toolbar];
6727   [toolbar setVisible: NO];
6729   /* Don't set frame garbaged until tool bar is up to date?
6730      This avoids an extra clear and redraw (flicker) at frame creation.  */
6731   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6732   else wait_for_tool_bar = NO;
6735 #ifdef NS_IMPL_COCOA
6736   {
6737     NSButton *toggleButton;
6738   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6739   [toggleButton setTarget: self];
6740   [toggleButton setAction: @selector (toggleToolbar: )];
6741   }
6742 #endif
6743   FRAME_TOOLBAR_HEIGHT (f) = 0;
6745   tem = f->icon_name;
6746   if (!NILP (tem))
6747     [win setMiniwindowTitle:
6748            [NSString stringWithUTF8String: SSDATA (tem)]];
6750   {
6751     NSScreen *screen = [win screen];
6753     if (screen != 0)
6754       {
6755         NSPoint pt = NSMakePoint
6756           (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6757            IN_BOUND (-SCREENMAX,
6758                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6760         [win setFrameTopLeftPoint: pt];
6762         NSTRACE_RECT ("new frame", [win frame]);
6763       }
6764   }
6766   [win makeFirstResponder: self];
6768   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6769                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6770   [win setBackgroundColor: col];
6771   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6772     [win setOpaque: NO];
6774 #if !defined (NS_IMPL_COCOA) || \
6775   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6776   [self allocateGState];
6777 #endif
6778   [NSApp registerServicesMenuSendTypes: ns_send_types
6779                            returnTypes: nil];
6781   ns_window_num++;
6782   return self;
6786 - (void)windowDidMove: sender
6788   NSWindow *win = [self window];
6789   NSRect r = [win frame];
6790   NSArray *screens = [NSScreen screens];
6791   NSScreen *screen = [screens objectAtIndex: 0];
6793   NSTRACE ("[EmacsView windowDidMove:]");
6795   if (!emacsframe->output_data.ns)
6796     return;
6797   if (screen != nil)
6798     {
6799       emacsframe->left_pos = r.origin.x;
6800       emacsframe->top_pos =
6801         [screen frame].size.height - (r.origin.y + r.size.height);
6802     }
6806 /* Called AFTER method below, but before our windowWillResize call there leads
6807    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6808    location so set_window_size moves the frame. */
6809 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6811   NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6812             NSTRACE_FMT_RETURN "YES"),
6813            NSTRACE_ARG_RECT (newFrame));
6815   emacsframe->output_data.ns->zooming = 1;
6816   return YES;
6820 /* Override to do something slightly nonstandard, but nice.  First click on
6821    zoom button will zoom vertically.  Second will zoom completely.  Third
6822    returns to original. */
6823 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6824                         defaultFrame:(NSRect)defaultFrame
6826   // TODO: Rename to "currentFrame" and assign "result" properly in
6827   // all paths.
6828   NSRect result = [sender frame];
6830   NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6831             NSTRACE_FMT_RECT "]"),
6832            NSTRACE_ARG_RECT (defaultFrame));
6833   NSTRACE_FSTYPE ("fs_state", fs_state);
6834   NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6835   NSTRACE_FSTYPE ("next_maximized", next_maximized);
6836   NSTRACE_RECT   ("ns_userRect", ns_userRect);
6837   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6839   if (fs_before_fs != -1) /* Entering fullscreen */
6840     {
6841       NSTRACE_MSG ("Entering fullscreen");
6842       result = defaultFrame;
6843     }
6844   else
6845     {
6846       // Save the window size and position (frame) before the resize.
6847       if (fs_state != FULLSCREEN_MAXIMIZED
6848           && fs_state != FULLSCREEN_WIDTH)
6849         {
6850           ns_userRect.size.width = result.size.width;
6851           ns_userRect.origin.x   = result.origin.x;
6852         }
6854       if (fs_state != FULLSCREEN_MAXIMIZED
6855           && fs_state != FULLSCREEN_HEIGHT)
6856         {
6857           ns_userRect.size.height = result.size.height;
6858           ns_userRect.origin.y    = result.origin.y;
6859         }
6861       NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6863       if (next_maximized == FULLSCREEN_HEIGHT
6864           || (next_maximized == -1
6865               && abs ((int)(defaultFrame.size.height - result.size.height))
6866               > FRAME_LINE_HEIGHT (emacsframe)))
6867         {
6868           /* first click */
6869           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6870           maximized_height = result.size.height = defaultFrame.size.height;
6871           maximized_width = -1;
6872           result.origin.y = defaultFrame.origin.y;
6873           if (ns_userRect.size.height != 0)
6874             {
6875               result.origin.x = ns_userRect.origin.x;
6876               result.size.width = ns_userRect.size.width;
6877             }
6878           [self setFSValue: FULLSCREEN_HEIGHT];
6879 #ifdef NS_IMPL_COCOA
6880           maximizing_resize = YES;
6881 #endif
6882         }
6883       else if (next_maximized == FULLSCREEN_WIDTH)
6884         {
6885           NSTRACE_MSG ("FULLSCREEN_WIDTH");
6886           maximized_width = result.size.width = defaultFrame.size.width;
6887           maximized_height = -1;
6888           result.origin.x = defaultFrame.origin.x;
6889           if (ns_userRect.size.width != 0)
6890             {
6891               result.origin.y = ns_userRect.origin.y;
6892               result.size.height = ns_userRect.size.height;
6893             }
6894           [self setFSValue: FULLSCREEN_WIDTH];
6895         }
6896       else if (next_maximized == FULLSCREEN_MAXIMIZED
6897                || (next_maximized == -1
6898                    && abs ((int)(defaultFrame.size.width - result.size.width))
6899                    > FRAME_COLUMN_WIDTH (emacsframe)))
6900         {
6901           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6903           result = defaultFrame;  /* second click */
6904           maximized_width = result.size.width;
6905           maximized_height = result.size.height;
6906           [self setFSValue: FULLSCREEN_MAXIMIZED];
6907 #ifdef NS_IMPL_COCOA
6908           maximizing_resize = YES;
6909 #endif
6910         }
6911       else
6912         {
6913           /* restore */
6914           NSTRACE_MSG ("Restore");
6915           result = ns_userRect.size.height ? ns_userRect : result;
6916           NSTRACE_RECT ("restore (2)", result);
6917           ns_userRect = NSMakeRect (0, 0, 0, 0);
6918 #ifdef NS_IMPL_COCOA
6919           maximizing_resize = fs_state != FULLSCREEN_NONE;
6920 #endif
6921           [self setFSValue: FULLSCREEN_NONE];
6922           maximized_width = maximized_height = -1;
6923         }
6924     }
6926   if (fs_before_fs == -1) next_maximized = -1;
6928   NSTRACE_RECT   ("Final ns_userRect", ns_userRect);
6929   NSTRACE_MSG    ("Final maximized_width: %d", maximized_width);
6930   NSTRACE_MSG    ("Final maximized_height: %d", maximized_height);
6931   NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6933   [self windowWillResize: sender toSize: result.size];
6935   NSTRACE_RETURN_RECT (result);
6937   return result;
6941 - (void)windowDidDeminiaturize: sender
6943   NSTRACE ("[EmacsView windowDidDeminiaturize:]");
6944   if (!emacsframe->output_data.ns)
6945     return;
6947   SET_FRAME_ICONIFIED (emacsframe, 0);
6948   SET_FRAME_VISIBLE (emacsframe, 1);
6949   windows_or_buffers_changed = 63;
6951   if (emacs_event)
6952     {
6953       emacs_event->kind = DEICONIFY_EVENT;
6954       EV_TRAILER ((id)nil);
6955     }
6959 - (void)windowDidExpose: sender
6961   NSTRACE ("[EmacsView windowDidExpose:]");
6962   if (!emacsframe->output_data.ns)
6963     return;
6965   SET_FRAME_VISIBLE (emacsframe, 1);
6966   SET_FRAME_GARBAGED (emacsframe);
6968   if (send_appdefined)
6969     ns_send_appdefined (-1);
6973 - (void)windowDidMiniaturize: sender
6975   NSTRACE ("[EmacsView windowDidMiniaturize:]");
6976   if (!emacsframe->output_data.ns)
6977     return;
6979   SET_FRAME_ICONIFIED (emacsframe, 1);
6980   SET_FRAME_VISIBLE (emacsframe, 0);
6982   if (emacs_event)
6983     {
6984       emacs_event->kind = ICONIFY_EVENT;
6985       EV_TRAILER ((id)nil);
6986     }
6989 #ifdef HAVE_NATIVE_FS
6990 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6991       willUseFullScreenPresentationOptions:
6992   (NSApplicationPresentationOptions)proposedOptions
6994   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6996 #endif
6998 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7000   NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7001   [self windowWillEnterFullScreen];
7003 - (void)windowWillEnterFullScreen /* provided for direct calls */
7005   NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7006   fs_before_fs = fs_state;
7009 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7011   NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7012   [self windowDidEnterFullScreen];
7015 - (void)windowDidEnterFullScreen /* provided for direct calls */
7017   NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7018   [self setFSValue: FULLSCREEN_BOTH];
7019   if (! [self fsIsNative])
7020     {
7021       [self windowDidBecomeKey];
7022       [nonfs_window orderOut:self];
7023     }
7024   else
7025     {
7026       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7027 #ifdef NS_IMPL_COCOA
7028 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7029       unsigned val = (unsigned)[NSApp presentationOptions];
7031       // OSX 10.7 bug fix, the menu won't appear without this.
7032       // val is non-zero on other OSX versions.
7033       if (val == 0)
7034         {
7035           NSApplicationPresentationOptions options
7036             = NSApplicationPresentationAutoHideDock
7037             | NSApplicationPresentationAutoHideMenuBar
7038             | NSApplicationPresentationFullScreen
7039             | NSApplicationPresentationAutoHideToolbar;
7041           [NSApp setPresentationOptions: options];
7042         }
7043 #endif
7044 #endif
7045       [toolbar setVisible:tbar_visible];
7046     }
7049 - (void)windowWillExitFullScreen:(NSNotification *)notification
7051   NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7052   [self windowWillExitFullScreen];
7055 - (void)windowWillExitFullScreen /* provided for direct calls */
7057   NSTRACE ("[EmacsView windowWillExitFullScreen]");
7058   if (!FRAME_LIVE_P (emacsframe))
7059     {
7060       NSTRACE_MSG ("Ignored (frame dead)");
7061       return;
7062     }
7063   if (next_maximized != -1)
7064     fs_before_fs = next_maximized;
7067 - (void)windowDidExitFullScreen:(NSNotification *)notification
7069   NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7070   [self windowDidExitFullScreen];
7073 - (void)windowDidExitFullScreen /* provided for direct calls */
7075   NSTRACE ("[EmacsView windowDidExitFullScreen]");
7076   if (!FRAME_LIVE_P (emacsframe))
7077     {
7078       NSTRACE_MSG ("Ignored (frame dead)");
7079       return;
7080     }
7081   [self setFSValue: fs_before_fs];
7082   fs_before_fs = -1;
7083 #ifdef HAVE_NATIVE_FS
7084   [self updateCollectionBehavior];
7085 #endif
7086   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7087     {
7088       [toolbar setVisible:YES];
7089       update_frame_tool_bar (emacsframe);
7090       [self updateFrameSize:YES];
7091       [[self window] display];
7092     }
7093   else
7094     [toolbar setVisible:NO];
7096   if (next_maximized != -1)
7097     [[self window] performZoom:self];
7100 - (BOOL)fsIsNative
7102   return fs_is_native;
7105 - (BOOL)isFullscreen
7107   BOOL res;
7109   if (! fs_is_native)
7110     {
7111       res = (nonfs_window != nil);
7112     }
7113   else
7114     {
7115 #ifdef HAVE_NATIVE_FS
7116       res = (([[self window] styleMask] & NSFullScreenWindowMask) != 0);
7117 #else
7118       res = NO;
7119 #endif
7120     }
7122   NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7123            (int) res);
7125   return res;
7128 #ifdef HAVE_NATIVE_FS
7129 - (void)updateCollectionBehavior
7131   NSTRACE ("[EmacsView updateCollectionBehavior]");
7133   if (! [self isFullscreen])
7134     {
7135       NSWindow *win = [self window];
7136       NSWindowCollectionBehavior b = [win collectionBehavior];
7137       if (ns_use_native_fullscreen)
7138         b |= NSWindowCollectionBehaviorFullScreenPrimary;
7139       else
7140         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7142       [win setCollectionBehavior: b];
7143       fs_is_native = ns_use_native_fullscreen;
7144     }
7146 #endif
7148 - (void)toggleFullScreen: (id)sender
7150   NSWindow *w, *fw;
7151   BOOL onFirstScreen;
7152   struct frame *f;
7153   NSRect r, wr;
7154   NSColor *col;
7156   NSTRACE ("[EmacsView toggleFullScreen:]");
7158   if (fs_is_native)
7159     {
7160 #ifdef HAVE_NATIVE_FS
7161       [[self window] toggleFullScreen:sender];
7162 #endif
7163       return;
7164     }
7166   w = [self window];
7167   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7168   f = emacsframe;
7169   wr = [w frame];
7170   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7171                                  (FRAME_DEFAULT_FACE (f)),
7172                                  f);
7174   if (fs_state != FULLSCREEN_BOTH)
7175     {
7176       NSScreen *screen = [w screen];
7178 #if defined (NS_IMPL_COCOA) && \
7179   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7180       /* Hide ghost menu bar on secondary monitor? */
7181       if (! onFirstScreen)
7182         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7183 #endif
7184       /* Hide dock and menubar if we are on the primary screen.  */
7185       if (onFirstScreen)
7186         {
7187 #ifdef NS_IMPL_COCOA
7188           NSApplicationPresentationOptions options
7189             = NSApplicationPresentationAutoHideDock
7190             | NSApplicationPresentationAutoHideMenuBar;
7192           [NSApp setPresentationOptions: options];
7193 #else
7194           [NSMenu setMenuBarVisible:NO];
7195 #endif
7196         }
7198       fw = [[EmacsFSWindow alloc]
7199                        initWithContentRect:[w contentRectForFrameRect:wr]
7200                                  styleMask:NSBorderlessWindowMask
7201                                    backing:NSBackingStoreBuffered
7202                                      defer:YES
7203                                     screen:screen];
7205       [fw setContentView:[w contentView]];
7206       [fw setTitle:[w title]];
7207       [fw setDelegate:self];
7208       [fw setAcceptsMouseMovedEvents: YES];
7209 #if !defined (NS_IMPL_COCOA) || \
7210   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7211       [fw useOptimizedDrawing: YES];
7212 #endif
7213       [fw setBackgroundColor: col];
7214       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7215         [fw setOpaque: NO];
7217       f->border_width = 0;
7218       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7219       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7220       FRAME_TOOLBAR_HEIGHT (f) = 0;
7222       nonfs_window = w;
7224       [self windowWillEnterFullScreen];
7225       [fw makeKeyAndOrderFront:NSApp];
7226       [fw makeFirstResponder:self];
7227       [w orderOut:self];
7228       r = [fw frameRectForContentRect:[screen frame]];
7229       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7230       [self windowDidEnterFullScreen];
7231       [fw display];
7232     }
7233   else
7234     {
7235       fw = w;
7236       w = nonfs_window;
7237       nonfs_window = nil;
7239       if (onFirstScreen)
7240         {
7241 #ifdef NS_IMPL_COCOA
7242           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7243 #else
7244           [NSMenu setMenuBarVisible:YES];
7245 #endif
7246         }
7248       [w setContentView:[fw contentView]];
7249       [w setBackgroundColor: col];
7250       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7251         [w setOpaque: NO];
7253       f->border_width = bwidth;
7254       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7255       if (FRAME_EXTERNAL_TOOL_BAR (f))
7256         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7258       // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7260       [self windowWillExitFullScreen];
7261       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7262       [fw close];
7263       [w makeKeyAndOrderFront:NSApp];
7264       [self windowDidExitFullScreen];
7265       [self updateFrameSize:YES];
7266     }
7269 - (void)handleFS
7271   NSTRACE ("[EmacsView handleFS]");
7273   if (fs_state != emacsframe->want_fullscreen)
7274     {
7275       if (fs_state == FULLSCREEN_BOTH)
7276         {
7277           NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7278           [self toggleFullScreen:self];
7279         }
7281       switch (emacsframe->want_fullscreen)
7282         {
7283         case FULLSCREEN_BOTH:
7284           NSTRACE_MSG ("FULLSCREEN_BOTH");
7285           [self toggleFullScreen:self];
7286           break;
7287         case FULLSCREEN_WIDTH:
7288           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7289           next_maximized = FULLSCREEN_WIDTH;
7290           if (fs_state != FULLSCREEN_BOTH)
7291             [[self window] performZoom:self];
7292           break;
7293         case FULLSCREEN_HEIGHT:
7294           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7295           next_maximized = FULLSCREEN_HEIGHT;
7296           if (fs_state != FULLSCREEN_BOTH)
7297             [[self window] performZoom:self];
7298           break;
7299         case FULLSCREEN_MAXIMIZED:
7300           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7301           next_maximized = FULLSCREEN_MAXIMIZED;
7302           if (fs_state != FULLSCREEN_BOTH)
7303             [[self window] performZoom:self];
7304           break;
7305         case FULLSCREEN_NONE:
7306           NSTRACE_MSG ("FULLSCREEN_NONE");
7307           if (fs_state != FULLSCREEN_BOTH)
7308             {
7309               next_maximized = FULLSCREEN_NONE;
7310               [[self window] performZoom:self];
7311             }
7312           break;
7313         }
7315       emacsframe->want_fullscreen = FULLSCREEN_NONE;
7316     }
7320 - (void) setFSValue: (int)value
7322   NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7323            NSTRACE_ARG_FSTYPE(value));
7325   Lisp_Object lval = Qnil;
7326   switch (value)
7327     {
7328     case FULLSCREEN_BOTH:
7329       lval = Qfullboth;
7330       break;
7331     case FULLSCREEN_WIDTH:
7332       lval = Qfullwidth;
7333       break;
7334     case FULLSCREEN_HEIGHT:
7335       lval = Qfullheight;
7336       break;
7337     case FULLSCREEN_MAXIMIZED:
7338       lval = Qmaximized;
7339       break;
7340     }
7341   store_frame_param (emacsframe, Qfullscreen, lval);
7342   fs_state = value;
7345 - (void)mouseEntered: (NSEvent *)theEvent
7347   NSTRACE ("[EmacsView mouseEntered:]");
7348   if (emacsframe)
7349     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7350       = EV_TIMESTAMP (theEvent);
7354 - (void)mouseExited: (NSEvent *)theEvent
7356   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7358   NSTRACE ("[EmacsView mouseExited:]");
7360   if (!hlinfo)
7361     return;
7363   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7364     = EV_TIMESTAMP (theEvent);
7366   if (emacsframe == hlinfo->mouse_face_mouse_frame)
7367     {
7368       clear_mouse_face (hlinfo);
7369       hlinfo->mouse_face_mouse_frame = 0;
7370     }
7374 - menuDown: sender
7376   NSTRACE ("[EmacsView menuDown:]");
7377   if (context_menu_value == -1)
7378     context_menu_value = [sender tag];
7379   else
7380     {
7381       NSInteger tag = [sender tag];
7382       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7383                                     emacsframe->menu_bar_vector,
7384                                     (void *)tag);
7385     }
7387   ns_send_appdefined (-1);
7388   return self;
7392 - (EmacsToolbar *)toolbar
7394   return toolbar;
7398 /* this gets called on toolbar button click */
7399 - toolbarClicked: (id)item
7401   NSEvent *theEvent;
7402   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7404   NSTRACE ("[EmacsView toolbarClicked:]");
7406   if (!emacs_event)
7407     return self;
7409   /* send first event (for some reason two needed) */
7410   theEvent = [[self window] currentEvent];
7411   emacs_event->kind = TOOL_BAR_EVENT;
7412   XSETFRAME (emacs_event->arg, emacsframe);
7413   EV_TRAILER (theEvent);
7415   emacs_event->kind = TOOL_BAR_EVENT;
7416 /*   XSETINT (emacs_event->code, 0); */
7417   emacs_event->arg = AREF (emacsframe->tool_bar_items,
7418                            idx + TOOL_BAR_ITEM_KEY);
7419   emacs_event->modifiers = EV_MODIFIERS (theEvent);
7420   EV_TRAILER (theEvent);
7421   return self;
7425 - toggleToolbar: (id)sender
7427   NSTRACE ("[EmacsView toggleToolbar:]");
7429   if (!emacs_event)
7430     return self;
7432   emacs_event->kind = NS_NONKEY_EVENT;
7433   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7434   EV_TRAILER ((id)nil);
7435   return self;
7439 - (void)drawRect: (NSRect)rect
7441   int x = NSMinX (rect), y = NSMinY (rect);
7442   int width = NSWidth (rect), height = NSHeight (rect);
7444   NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7445            NSTRACE_ARG_RECT(rect));
7447   if (!emacsframe || !emacsframe->output_data.ns)
7448     return;
7450   ns_clear_frame_area (emacsframe, x, y, width, height);
7451   block_input ();
7452   expose_frame (emacsframe, x, y, width, height);
7453   unblock_input ();
7455   /*
7456     drawRect: may be called (at least in OS X 10.5) for invisible
7457     views as well for some reason.  Thus, do not infer visibility
7458     here.
7460     emacsframe->async_visible = 1;
7461     emacsframe->async_iconified = 0;
7462   */
7466 /* NSDraggingDestination protocol methods.  Actually this is not really a
7467    protocol, but a category of Object.  O well...  */
7469 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7471   NSTRACE ("[EmacsView draggingEntered:]");
7472   return NSDragOperationGeneric;
7476 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7478   return YES;
7482 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7484   id pb;
7485   int x, y;
7486   NSString *type;
7487   NSEvent *theEvent = [[self window] currentEvent];
7488   NSPoint position;
7489   NSDragOperation op = [sender draggingSourceOperationMask];
7490   int modifiers = 0;
7492   NSTRACE ("[EmacsView performDragOperation:]");
7494   if (!emacs_event)
7495     return NO;
7497   position = [self convertPoint: [sender draggingLocation] fromView: nil];
7498   x = lrint (position.x);  y = lrint (position.y);
7500   pb = [sender draggingPasteboard];
7501   type = [pb availableTypeFromArray: ns_drag_types];
7503   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7504       // URL drags contain all operations (0xf), don't allow all to be set.
7505       (op & 0xf) != 0xf)
7506     {
7507       if (op & NSDragOperationLink)
7508         modifiers |= NSControlKeyMask;
7509       if (op & NSDragOperationCopy)
7510         modifiers |= NSAlternateKeyMask;
7511       if (op & NSDragOperationGeneric)
7512         modifiers |= NSCommandKeyMask;
7513     }
7515   modifiers = EV_MODIFIERS2 (modifiers);
7516   if (type == 0)
7517     {
7518       return NO;
7519     }
7520   else if ([type isEqualToString: NSFilenamesPboardType])
7521     {
7522       NSArray *files;
7523       NSEnumerator *fenum;
7524       NSString *file;
7526       if (!(files = [pb propertyListForType: type]))
7527         return NO;
7529       fenum = [files objectEnumerator];
7530       while ( (file = [fenum nextObject]) )
7531         {
7532           emacs_event->kind = DRAG_N_DROP_EVENT;
7533           XSETINT (emacs_event->x, x);
7534           XSETINT (emacs_event->y, y);
7535           ns_input_file = append2 (ns_input_file,
7536                                    build_string ([file UTF8String]));
7537           emacs_event->modifiers = modifiers;
7538           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
7539           EV_TRAILER (theEvent);
7540         }
7541       return YES;
7542     }
7543   else if ([type isEqualToString: NSURLPboardType])
7544     {
7545       NSURL *url = [NSURL URLFromPasteboard: pb];
7546       if (url == nil) return NO;
7548       emacs_event->kind = DRAG_N_DROP_EVENT;
7549       XSETINT (emacs_event->x, x);
7550       XSETINT (emacs_event->y, y);
7551       emacs_event->modifiers = modifiers;
7552       emacs_event->arg =  list2 (Qurl,
7553                                  build_string ([[url absoluteString]
7554                                                  UTF8String]));
7555       EV_TRAILER (theEvent);
7557       if ([url isFileURL] != NO)
7558         {
7559           NSString *file = [url path];
7560           ns_input_file = append2 (ns_input_file,
7561                                    build_string ([file UTF8String]));
7562         }
7563       return YES;
7564     }
7565   else if ([type isEqualToString: NSStringPboardType]
7566            || [type isEqualToString: NSTabularTextPboardType])
7567     {
7568       NSString *data;
7570       if (! (data = [pb stringForType: type]))
7571         return NO;
7573       emacs_event->kind = DRAG_N_DROP_EVENT;
7574       XSETINT (emacs_event->x, x);
7575       XSETINT (emacs_event->y, y);
7576       emacs_event->modifiers = modifiers;
7577       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7578       EV_TRAILER (theEvent);
7579       return YES;
7580     }
7581   else
7582     {
7583       fprintf (stderr, "Invalid data type in dragging pasteboard");
7584       return NO;
7585     }
7589 - (id) validRequestorForSendType: (NSString *)typeSent
7590                       returnType: (NSString *)typeReturned
7592   NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7593   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7594       && typeReturned == nil)
7595     {
7596       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7597         return self;
7598     }
7600   return [super validRequestorForSendType: typeSent
7601                                returnType: typeReturned];
7605 /* The next two methods are part of NSServicesRequests informal protocol,
7606    supposedly called when a services menu item is chosen from this app.
7607    But this should not happen because we override the services menu with our
7608    own entries which call ns-perform-service.
7609    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7610    So let's at least stub them out until further investigation can be done. */
7612 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7614   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7615      be written into the buffer in place of the existing selection..
7616      ordinary service calls go through functions defined in ns-win.el */
7617   return NO;
7620 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7622   NSArray *typesDeclared;
7623   Lisp_Object val;
7625   NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7627   /* We only support NSStringPboardType */
7628   if ([types containsObject:NSStringPboardType] == NO) {
7629     return NO;
7630   }
7632   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7633   if (CONSP (val) && SYMBOLP (XCAR (val)))
7634     {
7635       val = XCDR (val);
7636       if (CONSP (val) && NILP (XCDR (val)))
7637         val = XCAR (val);
7638     }
7639   if (! STRINGP (val))
7640     return NO;
7642   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7643   [pb declareTypes:typesDeclared owner:nil];
7644   ns_string_to_pasteboard (pb, val);
7645   return YES;
7649 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7650    (gives a miniaturized version of the window); currently we use the latter for
7651    frames whose active buffer doesn't correspond to any file
7652    (e.g., '*scratch*') */
7653 - setMiniwindowImage: (BOOL) setMini
7655   id image = [[self window] miniwindowImage];
7656   NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7658   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7659      about "AppleDockIconEnabled" notwithstanding, however the set message
7660      below has its effect nonetheless. */
7661   if (image != emacsframe->output_data.ns->miniimage)
7662     {
7663       if (image && [image isKindOfClass: [EmacsImage class]])
7664         [image release];
7665       [[self window] setMiniwindowImage:
7666                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7667     }
7669   return self;
7673 - (void) setRows: (int) r andColumns: (int) c
7675   NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7676   rows = r;
7677   cols = c;
7680 - (int) fullscreenState
7682   return fs_state;
7685 @end  /* EmacsView */
7689 /* ==========================================================================
7691     EmacsWindow implementation
7693    ========================================================================== */
7695 @implementation EmacsWindow
7697 #ifdef NS_IMPL_COCOA
7698 - (id)accessibilityAttributeValue:(NSString *)attribute
7700   Lisp_Object str = Qnil;
7701   struct frame *f = SELECTED_FRAME ();
7702   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7704   NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7706   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7707     return NSAccessibilityTextFieldRole;
7709   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7710       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7711     {
7712       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7713     }
7714   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7715     {
7716       if (! NILP (BVAR (curbuf, mark_active)))
7717           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7719       if (NILP (str))
7720         {
7721           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7722           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7723           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7725           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7726             str = make_uninit_multibyte_string (range, byte_range);
7727           else
7728             str = make_uninit_string (range);
7729           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7730              Is this a problem?  */
7731           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7732         }
7733     }
7736   if (! NILP (str))
7737     {
7738       if (CONSP (str) && SYMBOLP (XCAR (str)))
7739         {
7740           str = XCDR (str);
7741           if (CONSP (str) && NILP (XCDR (str)))
7742             str = XCAR (str);
7743         }
7744       if (STRINGP (str))
7745         {
7746           const char *utfStr = SSDATA (str);
7747           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7748           return nsStr;
7749         }
7750     }
7752   return [super accessibilityAttributeValue:attribute];
7754 #endif /* NS_IMPL_COCOA */
7756 /* Constrain size and placement of a frame.
7758    By returning the original "frameRect", the frame is not
7759    constrained. This can lead to unwanted situations where, for
7760    example, the menu bar covers the frame.
7762    The default implementation (accessed using "super") constrains the
7763    frame to the visible area of SCREEN, minus the menu bar (if
7764    present) and the Dock.  Note that default implementation also calls
7765    windowWillResize, with the frame it thinks should have.  (This can
7766    make the frame exit maximized mode.)
7768    Note that this should work in situations where multiple monitors
7769    are present.  Common configurations are side-by-side monitors and a
7770    monitor on top of another (e.g. when a laptop is placed under a
7771    large screen). */
7772 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7774   NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7775              NSTRACE_ARG_RECT (frameRect));
7777 #ifdef NS_IMPL_COCOA
7778 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7779   // If separate spaces is on, it is like each screen is independent.  There is
7780   // no spanning of frames across screens.
7781   if ([NSScreen screensHaveSeparateSpaces])
7782     {
7783       NSTRACE_MSG ("Screens have separate spaces");
7784       frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7785       NSTRACE_RETURN_RECT (frameRect);
7786       return frameRect;
7787     }
7788 #endif
7789 #endif
7791   return constrain_frame_rect(frameRect,
7792                               [(EmacsView *)[self delegate] isFullscreen]);
7796 - (void)performZoom:(id)sender
7798   NSTRACE ("[EmacsWindow performZoom:]");
7800   return [super performZoom:sender];
7803 - (void)zoom:(id)sender
7805   NSTRACE ("[EmacsWindow zoom:]");
7807   ns_update_auto_hide_menu_bar();
7809   // Below are three zoom implementations.  In the final commit, the
7810   // idea is that the last should be included.
7812 #if 0
7813   // Native zoom done using the standard zoom animation.  Size of the
7814   // resulting frame reduced to accommodate the Dock and, if present,
7815   // the menu-bar.
7816   [super zoom:sender];
7818 #elsif 0
7819   // Native zoom done using the standard zoom animation, plus an
7820   // explicit resize to cover the full screen.
7821   [super zoom:sender];
7823   // After the native zoom, resize the resulting frame to fill the
7824   // entire screen, except the menu-bar.
7825   //
7826   // This works for all practical purposes.  (The only minor oddity is
7827   // when transiting from full-height frame to a maximized, the
7828   // animation reduces the height of the frame slightly (to the 4
7829   // pixels needed to accommodate the Doc) before it snaps back into
7830   // full height.  The user would need a very trained eye to spot
7831   // this.)
7832   NSScreen * screen = [self screen];
7833   if (screen != nil)
7834     {
7835       int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7837       NSTRACE_FSTYPE ("fullscreenState", fs_state);
7839       NSRect sr = [screen frame];
7840       NSRect wr = [self frame];
7841       NSTRACE_RECT ("Rect after zoom", wr);
7843       NSRect newWr = wr;
7845       if (fs_state == FULLSCREEN_MAXIMIZED
7846           || fs_state == FULLSCREEN_HEIGHT)
7847         {
7848           newWr.origin.x = 0;
7849           newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7850         }
7852       if (fs_state == FULLSCREEN_MAXIMIZED
7853           || fs_state == FULLSCREEN_WIDTH)
7854         {
7855           newWr.origin.y = 0;
7856           newWr.size.width = sr.size.width;
7857         }
7859       if (newWr.size.width     != wr.size.width
7860           || newWr.size.height != wr.size.height
7861           || newWr.origin.x    != wr.origin.x
7862           || newWr.origin.y    != wr.origin.y)
7863         {
7864           NSTRACE_MSG ("New frame different");
7865           [self setFrame: newWr display: NO];
7866         }
7867     }
7868 #else
7869   // Non-native zoom which is done instantaneously.  The resulting frame
7870   // covers the entire screen, except the menu-bar, if present.
7871   NSScreen * screen = [self screen];
7872   if (screen != nil)
7873     {
7874       NSRect sr = [screen frame];
7875       sr.size.height -= ns_menu_bar_height (screen);
7877       sr = [[self delegate] windowWillUseStandardFrame:self
7878                                           defaultFrame:sr];
7879       [self setFrame: sr display: NO];
7880     }
7881 #endif
7884 - (void)setFrame:(NSRect)windowFrame
7885          display:(BOOL)displayViews
7887   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7888            NSTRACE_ARG_RECT (windowFrame), displayViews);
7890   [super setFrame:windowFrame display:displayViews];
7893 - (void)setFrame:(NSRect)windowFrame
7894          display:(BOOL)displayViews
7895          animate:(BOOL)performAnimation
7897   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7898            " display:%d performAnimation:%d]",
7899            NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7901   [super setFrame:windowFrame display:displayViews animate:performAnimation];
7904 - (void)setFrameTopLeftPoint:(NSPoint)point
7906   NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7907            NSTRACE_ARG_POINT (point));
7909   [super setFrameTopLeftPoint:point];
7911 @end /* EmacsWindow */
7914 @implementation EmacsFSWindow
7916 - (BOOL)canBecomeKeyWindow
7918   return YES;
7921 - (BOOL)canBecomeMainWindow
7923   return YES;
7926 @end
7928 /* ==========================================================================
7930     EmacsScroller implementation
7932    ========================================================================== */
7935 @implementation EmacsScroller
7937 /* for repeat button push */
7938 #define SCROLL_BAR_FIRST_DELAY 0.5
7939 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7941 + (CGFloat) scrollerWidth
7943   /* TODO: if we want to allow variable widths, this is the place to do it,
7944            however neither GNUstep nor Cocoa support it very well */
7945   CGFloat r;
7946 #if !defined (NS_IMPL_COCOA) || \
7947   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7948   r = [NSScroller scrollerWidth];
7949 #else
7950   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7951                                 scrollerStyle: NSScrollerStyleLegacy];
7952 #endif
7953   return r;
7957 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7959   NSTRACE ("[EmacsScroller initFrame: window:]");
7961   r.size.width = [EmacsScroller scrollerWidth];
7962   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7963   [self setContinuous: YES];
7964   [self setEnabled: YES];
7966   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7967      locked against the top and bottom edges, and right edge on OS X, where
7968      scrollers are on right. */
7969 #ifdef NS_IMPL_GNUSTEP
7970   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7971 #else
7972   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7973 #endif
7975   window = XWINDOW (nwin);
7976   condemned = NO;
7977   pixel_height = NSHeight (r);
7978   if (pixel_height == 0) pixel_height = 1;
7979   min_portion = 20 / pixel_height;
7981   frame = XFRAME (window->frame);
7982   if (FRAME_LIVE_P (frame))
7983     {
7984       int i;
7985       EmacsView *view = FRAME_NS_VIEW (frame);
7986       NSView *sview = [[view window] contentView];
7987       NSArray *subs = [sview subviews];
7989       /* disable optimization stopping redraw of other scrollbars */
7990       view->scrollbarsNeedingUpdate = 0;
7991       for (i =[subs count]-1; i >= 0; i--)
7992         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7993           view->scrollbarsNeedingUpdate++;
7994       [sview addSubview: self];
7995     }
7997 /*  [self setFrame: r]; */
7999   return self;
8003 - (void)setFrame: (NSRect)newRect
8005   NSTRACE ("[EmacsScroller setFrame:]");
8007 /*  block_input (); */
8008   pixel_height = NSHeight (newRect);
8009   if (pixel_height == 0) pixel_height = 1;
8010   min_portion = 20 / pixel_height;
8011   [super setFrame: newRect];
8012 /*  unblock_input (); */
8016 - (void)dealloc
8018   NSTRACE ("[EmacsScroller dealloc]");
8019   if (window)
8020     wset_vertical_scroll_bar (window, Qnil);
8021   window = 0;
8022   [super dealloc];
8026 - condemn
8028   NSTRACE ("[EmacsScroller condemn]");
8029   condemned =YES;
8030   return self;
8034 - reprieve
8036   NSTRACE ("[EmacsScroller reprieve]");
8037   condemned =NO;
8038   return self;
8042 -(bool)judge
8044   NSTRACE ("[EmacsScroller judge]");
8045   bool ret = condemned;
8046   if (condemned)
8047     {
8048       EmacsView *view;
8049       block_input ();
8050       /* ensure other scrollbar updates after deletion */
8051       view = (EmacsView *)FRAME_NS_VIEW (frame);
8052       if (view != nil)
8053         view->scrollbarsNeedingUpdate++;
8054       if (window)
8055         wset_vertical_scroll_bar (window, Qnil);
8056       window = 0;
8057       [self removeFromSuperview];
8058       [self release];
8059       unblock_input ();
8060     }
8061   return ret;
8065 - (void)resetCursorRects
8067   NSRect visible = [self visibleRect];
8068   NSTRACE ("[EmacsScroller resetCursorRects]");
8070   if (!NSIsEmptyRect (visible))
8071     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8072   [[NSCursor arrowCursor] setOnMouseEntered: YES];
8076 - (int) checkSamePosition: (int) position portion: (int) portion
8077                     whole: (int) whole
8079   return em_position ==position && em_portion ==portion && em_whole ==whole
8080     && portion != whole; /* needed for resize empty buf */
8084 - setPosition: (int)position portion: (int)portion whole: (int)whole
8086   NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8088   em_position = position;
8089   em_portion = portion;
8090   em_whole = whole;
8092   if (portion >= whole)
8093     {
8094 #ifdef NS_IMPL_COCOA
8095       [self setKnobProportion: 1.0];
8096       [self setDoubleValue: 1.0];
8097 #else
8098       [self setFloatValue: 0.0 knobProportion: 1.0];
8099 #endif
8100     }
8101   else
8102     {
8103       float pos;
8104       CGFloat por;
8105       portion = max ((float)whole*min_portion/pixel_height, portion);
8106       pos = (float)position / (whole - portion);
8107       por = (CGFloat)portion/whole;
8108 #ifdef NS_IMPL_COCOA
8109       [self setKnobProportion: por];
8110       [self setDoubleValue: pos];
8111 #else
8112       [self setFloatValue: pos knobProportion: por];
8113 #endif
8114     }
8116   return self;
8119 /* set up emacs_event */
8120 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8122   Lisp_Object win;
8124   NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8126   if (!emacs_event)
8127     return;
8129   emacs_event->part = last_hit_part;
8130   emacs_event->code = 0;
8131   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8132   XSETWINDOW (win, window);
8133   emacs_event->frame_or_window = win;
8134   emacs_event->timestamp = EV_TIMESTAMP (e);
8135   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8136   emacs_event->arg = Qnil;
8137   XSETINT (emacs_event->x, loc * pixel_height);
8138   XSETINT (emacs_event->y, pixel_height-20);
8140   if (q_event_ptr)
8141     {
8142       n_emacs_events_pending++;
8143       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8144     }
8145   else
8146     hold_event (emacs_event);
8147   EVENT_INIT (*emacs_event);
8148   ns_send_appdefined (-1);
8152 /* called manually thru timer to implement repeated button action w/hold-down */
8153 - repeatScroll: (NSTimer *)scrollEntry
8155   NSEvent *e = [[self window] currentEvent];
8156   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
8157   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8159   NSTRACE ("[EmacsScroller repeatScroll:]");
8161   /* clear timer if need be */
8162   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8163     {
8164         [scroll_repeat_entry invalidate];
8165         [scroll_repeat_entry release];
8166         scroll_repeat_entry = nil;
8168         if (inKnob)
8169           return self;
8171         scroll_repeat_entry
8172           = [[NSTimer scheduledTimerWithTimeInterval:
8173                         SCROLL_BAR_CONTINUOUS_DELAY
8174                                             target: self
8175                                           selector: @selector (repeatScroll:)
8176                                           userInfo: 0
8177                                            repeats: YES]
8178               retain];
8179     }
8181   [self sendScrollEventAtLoc: 0 fromEvent: e];
8182   return self;
8186 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
8187    mouseDragged events without going into a modal loop. */
8188 - (void)mouseDown: (NSEvent *)e
8190   NSRect sr, kr;
8191   /* hitPart is only updated AFTER event is passed on */
8192   NSScrollerPart part = [self testPart: [e locationInWindow]];
8193   CGFloat inc = 0.0, loc, kloc, pos;
8194   int edge = 0;
8196   NSTRACE ("[EmacsScroller mouseDown:]");
8198   switch (part)
8199     {
8200     case NSScrollerDecrementPage:
8201         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8202     case NSScrollerIncrementPage:
8203         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8204     case NSScrollerDecrementLine:
8205       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8206     case NSScrollerIncrementLine:
8207       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8208     case NSScrollerKnob:
8209       last_hit_part = scroll_bar_handle; break;
8210     case NSScrollerKnobSlot:  /* GNUstep-only */
8211       last_hit_part = scroll_bar_move_ratio; break;
8212     default:  /* NSScrollerNoPart? */
8213       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8214                (long) part);
8215       return;
8216     }
8218   if (inc != 0.0)
8219     {
8220       pos = 0;      /* ignored */
8222       /* set a timer to repeat, as we can't let superclass do this modally */
8223       scroll_repeat_entry
8224         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8225                                             target: self
8226                                           selector: @selector (repeatScroll:)
8227                                           userInfo: 0
8228                                            repeats: YES]
8229             retain];
8230     }
8231   else
8232     {
8233       /* handle, or on GNUstep possibly slot */
8234       NSEvent *fake_event;
8236       /* compute float loc in slot and mouse offset on knob */
8237       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8238                       toView: nil];
8239       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8240       if (loc <= 0.0)
8241         {
8242           loc = 0.0;
8243           edge = -1;
8244         }
8245       else if (loc >= NSHeight (sr))
8246         {
8247           loc = NSHeight (sr);
8248           edge = 1;
8249         }
8251       if (edge)
8252         kloc = 0.5 * edge;
8253       else
8254         {
8255           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8256                           toView: nil];
8257           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8258         }
8259       last_mouse_offset = kloc;
8261       /* if knob, tell emacs a location offset by knob pos
8262          (to indicate top of handle) */
8263       if (part == NSScrollerKnob)
8264           pos = (loc - last_mouse_offset) / NSHeight (sr);
8265       else
8266         /* else this is a slot click on GNUstep: go straight there */
8267         pos = loc / NSHeight (sr);
8269       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8270       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8271                                       location: [e locationInWindow]
8272                                  modifierFlags: [e modifierFlags]
8273                                      timestamp: [e timestamp]
8274                                   windowNumber: [e windowNumber]
8275                                        context: [e context]
8276                                    eventNumber: [e eventNumber]
8277                                     clickCount: [e clickCount]
8278                                       pressure: [e pressure]];
8279       [super mouseUp: fake_event];
8280     }
8282   if (part != NSScrollerKnob)
8283     [self sendScrollEventAtLoc: pos fromEvent: e];
8287 /* Called as we manually track scroller drags, rather than superclass. */
8288 - (void)mouseDragged: (NSEvent *)e
8290     NSRect sr;
8291     double loc, pos;
8293     NSTRACE ("[EmacsScroller mouseDragged:]");
8295       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8296                       toView: nil];
8297       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8299       if (loc <= 0.0)
8300         {
8301           loc = 0.0;
8302         }
8303       else if (loc >= NSHeight (sr) + last_mouse_offset)
8304         {
8305           loc = NSHeight (sr) + last_mouse_offset;
8306         }
8308       pos = (loc - last_mouse_offset) / NSHeight (sr);
8309       [self sendScrollEventAtLoc: pos fromEvent: e];
8313 - (void)mouseUp: (NSEvent *)e
8315   NSTRACE ("[EmacsScroller mouseUp:]");
8317   if (scroll_repeat_entry)
8318     {
8319       [scroll_repeat_entry invalidate];
8320       [scroll_repeat_entry release];
8321       scroll_repeat_entry = nil;
8322     }
8323   last_hit_part = scroll_bar_above_handle;
8327 /* treat scrollwheel events in the bar as though they were in the main window */
8328 - (void) scrollWheel: (NSEvent *)theEvent
8330   NSTRACE ("[EmacsScroller scrollWheel:]");
8332   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8333   [view mouseDown: theEvent];
8336 @end  /* EmacsScroller */
8339 #ifdef NS_IMPL_GNUSTEP
8340 /* Dummy class to get rid of startup warnings.  */
8341 @implementation EmacsDocument
8343 @end
8344 #endif
8347 /* ==========================================================================
8349    Font-related functions; these used to be in nsfaces.m
8351    ========================================================================== */
8354 Lisp_Object
8355 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8357   struct font *font = XFONT_OBJECT (font_object);
8358   EmacsView *view = FRAME_NS_VIEW (f);
8359   int font_ascent, font_descent;
8361   if (fontset < 0)
8362     fontset = fontset_from_font (font_object);
8363   FRAME_FONTSET (f) = fontset;
8365   if (FRAME_FONT (f) == font)
8366     /* This font is already set in frame F.  There's nothing more to
8367        do.  */
8368     return font_object;
8370   FRAME_FONT (f) = font;
8372   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8373   FRAME_COLUMN_WIDTH (f) = font->average_width;
8374   get_font_ascent_descent (font, &font_ascent, &font_descent);
8375   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8377   /* Compute the scroll bar width in character columns.  */
8378   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8379     {
8380       int wid = FRAME_COLUMN_WIDTH (f);
8381       FRAME_CONFIG_SCROLL_BAR_COLS (f)
8382         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8383     }
8384   else
8385     {
8386       int wid = FRAME_COLUMN_WIDTH (f);
8387       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8388     }
8390   /* Compute the scroll bar height in character lines.  */
8391   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8392     {
8393       int height = FRAME_LINE_HEIGHT (f);
8394       FRAME_CONFIG_SCROLL_BAR_LINES (f)
8395         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8396     }
8397   else
8398     {
8399       int height = FRAME_LINE_HEIGHT (f);
8400       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8401     }
8403   /* Now make the frame display the given font.  */
8404   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8405     adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8406                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8407                        false, Qfont);
8409   return font_object;
8413 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8414 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8415          in 1.43. */
8417 const char *
8418 ns_xlfd_to_fontname (const char *xlfd)
8419 /* --------------------------------------------------------------------------
8420     Convert an X font name (XLFD) to an NS font name.
8421     Only family is used.
8422     The string returned is temporarily allocated.
8423    -------------------------------------------------------------------------- */
8425   char *name = xmalloc (180);
8426   int i, len;
8427   const char *ret;
8429   if (!strncmp (xlfd, "--", 2))
8430     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8431   else
8432     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8434   /* stopgap for malformed XLFD input */
8435   if (strlen (name) == 0)
8436     strcpy (name, "Monaco");
8438   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8439      also uppercase after '-' or ' ' */
8440   name[0] = c_toupper (name[0]);
8441   for (len =strlen (name), i =0; i<len; i++)
8442     {
8443       if (name[i] == '$')
8444         {
8445           name[i] = '-';
8446           if (i+1<len)
8447             name[i+1] = c_toupper (name[i+1]);
8448         }
8449       else if (name[i] == '_')
8450         {
8451           name[i] = ' ';
8452           if (i+1<len)
8453             name[i+1] = c_toupper (name[i+1]);
8454         }
8455     }
8456 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
8457   ret = [[NSString stringWithUTF8String: name] UTF8String];
8458   xfree (name);
8459   return ret;
8463 void
8464 syms_of_nsterm (void)
8466   NSTRACE ("syms_of_nsterm");
8468   ns_antialias_threshold = 10.0;
8470   /* from 23+ we need to tell emacs what modifiers there are.. */
8471   DEFSYM (Qmodifier_value, "modifier-value");
8472   DEFSYM (Qalt, "alt");
8473   DEFSYM (Qhyper, "hyper");
8474   DEFSYM (Qmeta, "meta");
8475   DEFSYM (Qsuper, "super");
8476   DEFSYM (Qcontrol, "control");
8477   DEFSYM (QUTF8_STRING, "UTF8_STRING");
8479   DEFSYM (Qfile, "file");
8480   DEFSYM (Qurl, "url");
8482   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8483   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8484   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8485   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8486   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8488   DEFVAR_LISP ("ns-input-file", ns_input_file,
8489               "The file specified in the last NS event.");
8490   ns_input_file =Qnil;
8492   DEFVAR_LISP ("ns-working-text", ns_working_text,
8493               "String for visualizing working composition sequence.");
8494   ns_working_text =Qnil;
8496   DEFVAR_LISP ("ns-input-font", ns_input_font,
8497               "The font specified in the last NS event.");
8498   ns_input_font =Qnil;
8500   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8501               "The fontsize specified in the last NS event.");
8502   ns_input_fontsize =Qnil;
8504   DEFVAR_LISP ("ns-input-line", ns_input_line,
8505                "The line specified in the last NS event.");
8506   ns_input_line =Qnil;
8508   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8509                "The service name specified in the last NS event.");
8510   ns_input_spi_name =Qnil;
8512   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8513                "The service argument specified in the last NS event.");
8514   ns_input_spi_arg =Qnil;
8516   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8517                "This variable describes the behavior of the alternate or option key.\n\
8518 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8519 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8520 at all, allowing it to be used at a lower level for accented character entry.");
8521   ns_alternate_modifier = Qmeta;
8523   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8524                "This variable describes the behavior of the right alternate or option key.\n\
8525 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8526 Set to left means be the same key as `ns-alternate-modifier'.\n\
8527 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8528 at all, allowing it to be used at a lower level for accented character entry.");
8529   ns_right_alternate_modifier = Qleft;
8531   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8532                "This variable describes the behavior of the command key.\n\
8533 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8534   ns_command_modifier = Qsuper;
8536   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8537                "This variable describes the behavior of the right command key.\n\
8538 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8539 Set to left means be the same key as `ns-command-modifier'.\n\
8540 Set to none means that the command / option key is not interpreted by Emacs\n\
8541 at all, allowing it to be used at a lower level for accented character entry.");
8542   ns_right_command_modifier = Qleft;
8544   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8545                "This variable describes the behavior of the control key.\n\
8546 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8547   ns_control_modifier = Qcontrol;
8549   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8550                "This variable describes the behavior of the right control key.\n\
8551 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8552 Set to left means be the same key as `ns-control-modifier'.\n\
8553 Set to none means that the control / option key is not interpreted by Emacs\n\
8554 at all, allowing it to be used at a lower level for accented character entry.");
8555   ns_right_control_modifier = Qleft;
8557   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8558                "This variable describes the behavior of the function key (on laptops).\n\
8559 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8560 Set to none means that the function key is not interpreted by Emacs at all,\n\
8561 allowing it to be used at a lower level for accented character entry.");
8562   ns_function_modifier = Qnone;
8564   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8565                "Non-nil (the default) means to render text antialiased.");
8566   ns_antialias_text = Qt;
8568   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8569                "Whether to confirm application quit using dialog.");
8570   ns_confirm_quit = Qnil;
8572   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8573                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8574 Only works on OSX 10.6 or later.  */);
8575   ns_auto_hide_menu_bar = Qnil;
8577   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8578      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8579 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
8580 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
8581 Default is t for OSX >= 10.7, nil otherwise.  */);
8582 #ifdef HAVE_NATIVE_FS
8583   ns_use_native_fullscreen = YES;
8584 #else
8585   ns_use_native_fullscreen = NO;
8586 #endif
8587   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8589   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8590      doc: /*Non-nil means use animation on non-native fullscreen.
8591 For native fullscreen, this does nothing.
8592 Default is nil.  */);
8593   ns_use_fullscreen_animation = NO;
8595   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8596      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8597 Note that this does not apply to images.
8598 This variable is ignored on OSX < 10.7 and GNUstep.  */);
8599   ns_use_srgb_colorspace = YES;
8601   /* TODO: move to common code */
8602   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8603                doc: /* Which toolkit scroll bars Emacs uses, if any.
8604 A value of nil means Emacs doesn't use toolkit scroll bars.
8605 With the X Window system, the value is a symbol describing the
8606 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
8607 With MS Windows or Nextstep, the value is t.  */);
8608   Vx_toolkit_scroll_bars = Qt;
8610   DEFVAR_BOOL ("x-use-underline-position-properties",
8611                x_use_underline_position_properties,
8612      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8613 A value of nil means ignore them.  If you encounter fonts with bogus
8614 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8615 to 4.1, set this to nil. */);
8616   x_use_underline_position_properties = 0;
8618   DEFVAR_BOOL ("x-underline-at-descent-line",
8619                x_underline_at_descent_line,
8620      doc: /* Non-nil means to draw the underline at the same place as the descent line.
8621 A value of nil means to draw the underline according to the value of the
8622 variable `x-use-underline-position-properties', which is usually at the
8623 baseline level.  The default value is nil.  */);
8624   x_underline_at_descent_line = 0;
8626   /* Tell Emacs about this window system.  */
8627   Fprovide (Qns, Qnil);
8629   DEFSYM (Qcocoa, "cocoa");
8630   DEFSYM (Qgnustep, "gnustep");
8632 #ifdef NS_IMPL_COCOA
8633   Fprovide (Qcocoa, Qnil);
8634   syms_of_macfont ();
8635 #else
8636   Fprovide (Qgnustep, Qnil);
8637   syms_of_nsfont ();
8638 #endif