Remove two uses of 'min' in Fwindow_text_pixel_size
[emacs.git] / src / nsterm.m
blobf2b0d9017707856e0ab4b64a7b5be006e003d0bf
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 (at
11 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_init_locale (void)
590 /* OS X doesn't set any environment variables for the locale when run
591    from the GUI. Get the locale from the OS and set LANG. */
593   NSLocale *locale = [NSLocale currentLocale];
595   NSTRACE ("ns_init_locale");
597   @try
598     {
599       /* It seems OS X should probably use UTF-8 everywhere.
600          'localeIdentifier' does not specify the encoding, and I can't
601          find any way to get the OS to tell us which encoding to use,
602          so hard-code '.UTF-8'. */
603       NSString *localeID = [NSString stringWithFormat:@"%@.UTF-8",
604                                      [locale localeIdentifier]];
606       /* Set LANG to locale, but not if LANG is already set. */
607       setenv("LANG", [localeID UTF8String], 0);
608     }
609   @catch (NSException *e)
610     {
611       NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
612     }
616 void
617 ns_release_object (void *obj)
618 /* --------------------------------------------------------------------------
619     Release an object (callable from C)
620    -------------------------------------------------------------------------- */
622     [(id)obj release];
626 void
627 ns_retain_object (void *obj)
628 /* --------------------------------------------------------------------------
629     Retain an object (callable from C)
630    -------------------------------------------------------------------------- */
632     [(id)obj retain];
636 void *
637 ns_alloc_autorelease_pool (void)
638 /* --------------------------------------------------------------------------
639      Allocate a pool for temporary objects (callable from C)
640    -------------------------------------------------------------------------- */
642   return [[NSAutoreleasePool alloc] init];
646 void
647 ns_release_autorelease_pool (void *pool)
648 /* --------------------------------------------------------------------------
649      Free a pool and temporary objects it refers to (callable from C)
650    -------------------------------------------------------------------------- */
652   ns_release_object (pool);
656 static BOOL
657 ns_menu_bar_should_be_hidden (void)
658 /* True, if the menu bar should be hidden.  */
660   return !NILP (ns_auto_hide_menu_bar)
661     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
665 struct EmacsMargins
667   CGFloat top;
668   CGFloat bottom;
669   CGFloat left;
670   CGFloat right;
674 static struct EmacsMargins
675 ns_screen_margins (NSScreen *screen)
676 /* The parts of SCREEN used by the operating system.  */
678   NSTRACE ("ns_screen_margins");
680   struct EmacsMargins margins;
682   NSRect screenFrame = [screen frame];
683   NSRect screenVisibleFrame = [screen visibleFrame];
685   /* Sometimes, visibleFrame isn't up-to-date with respect to a hidden
686      menu bar, check this explicitly.  */
687   if (ns_menu_bar_should_be_hidden())
688     {
689       margins.top = 0;
690     }
691   else
692     {
693       CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
694       CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
695                                  + screenVisibleFrame.size.height);
697       margins.top = frameTop - visibleFrameTop;
698     }
700   {
701     CGFloat frameRight = screenFrame.origin.x + screenFrame.size.width;
702     CGFloat visibleFrameRight = (screenVisibleFrame.origin.x
703                                  + screenVisibleFrame.size.width);
704     margins.right = frameRight - visibleFrameRight;
705   }
707   margins.bottom = screenVisibleFrame.origin.y - screenFrame.origin.y;
708   margins.left   = screenVisibleFrame.origin.x - screenFrame.origin.x;
710   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
711                margins.left,
712                margins.right,
713                margins.top,
714                margins.bottom);
716   return margins;
720 /* A screen margin between 1 and DOCK_IGNORE_LIMIT (inclusive) is
721    assumed to contain a hidden dock.  OS X currently use 4 pixels for
722    this, however, to be future compatible, a larger value is used.  */
723 #define DOCK_IGNORE_LIMIT 6
725 static struct EmacsMargins
726 ns_screen_margins_ignoring_hidden_dock (NSScreen *screen)
727 /* The parts of SCREEN used by the operating system, excluding the parts
728 reserved for an hidden dock.  */
730   NSTRACE ("ns_screen_margins_ignoring_hidden_dock");
732   struct EmacsMargins margins = ns_screen_margins(screen);
734   /* OS X (currently) reserved 4 pixels along the edge where a hidden
735      dock is located.  Unfortunately, it's not possible to find the
736      location and information about if the dock is hidden.  Instead,
737      it is assumed that if the margin of an edge is less than
738      DOCK_IGNORE_LIMIT, it contains a hidden dock.  */
739   if (margins.left <= DOCK_IGNORE_LIMIT)
740     {
741       margins.left = 0;
742     }
743   if (margins.right <= DOCK_IGNORE_LIMIT)
744     {
745       margins.right = 0;
746     }
747   if (margins.top <= DOCK_IGNORE_LIMIT)
748     {
749       margins.top = 0;
750     }
751   /* Note: This doesn't occur in current versions of OS X, but
752      included for completeness and future compatibility.  */
753   if (margins.bottom <= DOCK_IGNORE_LIMIT)
754     {
755       margins.bottom = 0;
756     }
758   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
759                margins.left,
760                margins.right,
761                margins.top,
762                margins.bottom);
764   return margins;
768 static CGFloat
769 ns_menu_bar_height (NSScreen *screen)
770 /* The height of the menu bar, if visible.
772    Note: Don't use this when fullscreen is enabled -- the screen
773    sometimes includes, sometimes excludes the menu bar area.  */
775   struct EmacsMargins margins = ns_screen_margins(screen);
777   CGFloat res = margins.top;
779   NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
781   return res;
785 /* ==========================================================================
787     Focus (clipping) and screen update
789    ========================================================================== */
792 // Window constraining
793 // -------------------
795 // To ensure that the windows are not placed under the menu bar, they
796 // are typically moved by the call-back constrainFrameRect. However,
797 // by overriding it, it's possible to inhibit this, leaving the window
798 // in it's original position.
800 // It's possible to hide the menu bar. However, technically, it's only
801 // possible to hide it when the application is active. To ensure that
802 // this work properly, the menu bar and window constraining are
803 // deferred until the application becomes active.
805 // Even though it's not possible to manually move a window above the
806 // top of the screen, it is allowed if it's done programmatically,
807 // when the menu is hidden. This allows the editable area to cover the
808 // full screen height.
810 // Test cases
811 // ----------
813 // Use the following extra files:
815 //    init.el:
816 //       ;; Hide menu and place frame slightly above the top of the screen.
817 //       (setq ns-auto-hide-menu-bar t)
818 //       (set-frame-position (selected-frame) 0 -20)
820 // Test 1:
822 //    emacs -Q -l init.el
824 //    Result: No menu bar, and the title bar should be above the screen.
826 // Test 2:
828 //    emacs -Q
830 //    Result: Menu bar visible, frame placed immediately below the menu.
833 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
835   NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
836              NSTRACE_ARG_RECT (frameRect));
838   // --------------------
839   // Collect information about the screen the frame is covering.
840   //
842   NSArray *screens = [NSScreen screens];
843   NSUInteger nr_screens = [screens count];
845   int i;
847   // The height of the menu bar, if present in any screen the frame is
848   // displayed in.
849   int menu_bar_height = 0;
851   // A rectangle covering all the screen the frame is displayed in.
852   NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
853   for (i = 0; i < nr_screens; ++i )
854     {
855       NSScreen *s = [screens objectAtIndex: i];
856       NSRect scrRect = [s frame];
858       NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
859                    i, NSTRACE_ARG_RECT (scrRect));
861       if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
862         {
863           multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
865           if (!isFullscreen)
866             {
867               CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
868               menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
869             }
870         }
871     }
873   NSTRACE_RECT ("multiscreenRect", multiscreenRect);
875   NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
877   if (multiscreenRect.size.width == 0
878       || multiscreenRect.size.height == 0)
879     {
880       // Failed to find any monitor, give up.
881       NSTRACE_MSG ("multiscreenRect empty");
882       NSTRACE_RETURN_RECT (frameRect);
883       return frameRect;
884     }
887   // --------------------
888   // Find a suitable placement.
889   //
891   if (ns_menu_bar_should_be_hidden())
892     {
893       // When the menu bar is hidden, the user may place part of the
894       // frame above the top of the screen, for example to hide the
895       // title bar.
896       //
897       // Hence, keep the original position.
898     }
899   else
900     {
901       // Ensure that the frame is below the menu bar, or below the top
902       // of the screen.
903       //
904       // This assume that the menu bar is placed at the top in the
905       // rectangle that covers the monitors.  (It doesn't have to be,
906       // but if it's not it's hard to do anything useful.)
907       CGFloat topOfWorkArea = (multiscreenRect.origin.y
908                                + multiscreenRect.size.height
909                                - menu_bar_height);
911       CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
912       if (topOfFrame > topOfWorkArea)
913         {
914           frameRect.origin.y -= topOfFrame - topOfWorkArea;
915           NSTRACE_RECT ("After placement adjust", frameRect);
916         }
917     }
919   // Include the following section to restrict frame to the screens.
920   // (If so, update it to allow the frame to stretch down below the
921   // screen.)
922 #if 0
923   // --------------------
924   // Ensure frame doesn't stretch below the screens.
925   //
927   CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
929   if (diff > 0)
930     {
931       frameRect.origin.y = multiscreenRect.origin.y;
932       frameRect.size.height -= diff;
933     }
934 #endif
936   NSTRACE_RETURN_RECT (frameRect);
937   return frameRect;
941 static void
942 ns_constrain_all_frames (void)
943 /* --------------------------------------------------------------------------
944      Ensure that the menu bar doesn't cover any frames.
945    -------------------------------------------------------------------------- */
947   Lisp_Object tail, frame;
949   NSTRACE ("ns_constrain_all_frames");
951   block_input ();
953   FOR_EACH_FRAME (tail, frame)
954     {
955       struct frame *f = XFRAME (frame);
956       if (FRAME_NS_P (f))
957         {
958           EmacsView *view = FRAME_NS_VIEW (f);
960           if (![view isFullscreen])
961             {
962               [[view window]
963                 setFrame:constrain_frame_rect([[view window] frame], false)
964                  display:NO];
965             }
966         }
967     }
969   unblock_input ();
973 static void
974 ns_update_auto_hide_menu_bar (void)
975 /* --------------------------------------------------------------------------
976      Show or hide the menu bar, based on user setting.
977    -------------------------------------------------------------------------- */
979 #ifdef NS_IMPL_COCOA
980   NSTRACE ("ns_update_auto_hide_menu_bar");
982   block_input ();
984   if (NSApp != nil && [NSApp isActive])
985     {
986       // Note, "setPresentationOptions" triggers an error unless the
987       // application is active.
988       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
990       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
991         {
992           NSApplicationPresentationOptions options
993             = NSApplicationPresentationDefault;
995           if (menu_bar_should_be_hidden)
996             options |= NSApplicationPresentationAutoHideMenuBar
997               | NSApplicationPresentationAutoHideDock;
999           [NSApp setPresentationOptions: options];
1001           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
1003           if (!ns_menu_bar_is_hidden)
1004             {
1005               ns_constrain_all_frames ();
1006             }
1007         }
1008     }
1010   unblock_input ();
1011 #endif
1015 static void
1016 ns_update_begin (struct frame *f)
1017 /* --------------------------------------------------------------------------
1018    Prepare for a grouped sequence of drawing calls
1019    external (RIF) call; whole frame, called before update_window_begin
1020    -------------------------------------------------------------------------- */
1022   EmacsView *view = FRAME_NS_VIEW (f);
1023   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
1025   ns_update_auto_hide_menu_bar ();
1027 #ifdef NS_IMPL_COCOA
1028   if ([view isFullscreen] && [view fsIsNative])
1029   {
1030     // Fix reappearing tool bar in fullscreen for OSX 10.7
1031     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
1032     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
1033     if (! tbar_visible != ! [toolbar isVisible])
1034       [toolbar setVisible: tbar_visible];
1035   }
1036 #endif
1038   ns_updating_frame = f;
1039   [view lockFocus];
1041   /* drawRect may have been called for say the minibuffer, and then clip path
1042      is for the minibuffer.  But the display engine may draw more because
1043      we have set the frame as garbaged.  So reset clip path to the whole
1044      view.  */
1045 #ifdef NS_IMPL_COCOA
1046   {
1047     NSBezierPath *bp;
1048     NSRect r = [view frame];
1049     NSRect cr = [[view window] frame];
1050     /* If a large frame size is set, r may be larger than the window frame
1051        before constrained.  In that case don't change the clip path, as we
1052        will clear in to the tool bar and title bar.  */
1053     if (r.size.height
1054         + FRAME_NS_TITLEBAR_HEIGHT (f)
1055         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
1056       {
1057         bp = [[NSBezierPath bezierPathWithRect: r] retain];
1058         [bp setClip];
1059         [bp release];
1060       }
1061   }
1062 #endif
1064 #ifdef NS_IMPL_GNUSTEP
1065   uRect = NSMakeRect (0, 0, 0, 0);
1066 #endif
1070 static void
1071 ns_update_window_begin (struct window *w)
1072 /* --------------------------------------------------------------------------
1073    Prepare for a grouped sequence of drawing calls
1074    external (RIF) call; for one window, called after update_begin
1075    -------------------------------------------------------------------------- */
1077   struct frame *f = XFRAME (WINDOW_FRAME (w));
1078   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1080   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
1081   w->output_cursor = w->cursor;
1083   block_input ();
1085   if (f == hlinfo->mouse_face_mouse_frame)
1086     {
1087       /* Don't do highlighting for mouse motion during the update.  */
1088       hlinfo->mouse_face_defer = 1;
1090         /* If the frame needs to be redrawn,
1091            simply forget about any prior mouse highlighting.  */
1092       if (FRAME_GARBAGED_P (f))
1093         hlinfo->mouse_face_window = Qnil;
1095       /* (further code for mouse faces ifdef'd out in other terms elided) */
1096     }
1098   unblock_input ();
1102 static void
1103 ns_update_window_end (struct window *w, bool cursor_on_p,
1104                       bool mouse_face_overwritten_p)
1105 /* --------------------------------------------------------------------------
1106    Finished a grouped sequence of drawing calls
1107    external (RIF) call; for one window called before update_end
1108    -------------------------------------------------------------------------- */
1110   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1112   /* note: this fn is nearly identical in all terms */
1113   if (!w->pseudo_window_p)
1114     {
1115       block_input ();
1117       if (cursor_on_p)
1118         display_and_set_cursor (w, 1,
1119                                 w->output_cursor.hpos, w->output_cursor.vpos,
1120                                 w->output_cursor.x, w->output_cursor.y);
1122       if (draw_window_fringes (w, 1))
1123         {
1124           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1125             x_draw_right_divider (w);
1126           else
1127             x_draw_vertical_border (w);
1128         }
1130       unblock_input ();
1131     }
1133   /* If a row with mouse-face was overwritten, arrange for
1134      frame_up_to_date to redisplay the mouse highlight.  */
1135   if (mouse_face_overwritten_p)
1136     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1140 static void
1141 ns_update_end (struct frame *f)
1142 /* --------------------------------------------------------------------------
1143    Finished a grouped sequence of drawing calls
1144    external (RIF) call; for whole frame, called after update_window_end
1145    -------------------------------------------------------------------------- */
1147   EmacsView *view = FRAME_NS_VIEW (f);
1149   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1151 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1152   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1154   block_input ();
1156   [view unlockFocus];
1157   [[view window] flushWindow];
1159   unblock_input ();
1160   ns_updating_frame = NULL;
1163 static void
1164 ns_focus (struct frame *f, NSRect *r, int n)
1165 /* --------------------------------------------------------------------------
1166    Internal: Focus on given frame.  During small local updates this is used to
1167      draw, however during large updates, ns_update_begin and ns_update_end are
1168      called to wrap the whole thing, in which case these calls are stubbed out.
1169      Except, on GNUstep, we accumulate the rectangle being drawn into, because
1170      the back end won't do this automatically, and will just end up flushing
1171      the entire window.
1172    -------------------------------------------------------------------------- */
1174   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1175   if (r != NULL)
1176     {
1177       NSTRACE_RECT ("r", *r);
1178     }
1180   if (f != ns_updating_frame)
1181     {
1182       NSView *view = FRAME_NS_VIEW (f);
1183       if (view != focus_view)
1184         {
1185           if (focus_view != NULL)
1186             {
1187               [focus_view unlockFocus];
1188               [[focus_view window] flushWindow];
1189 /*debug_lock--; */
1190             }
1192           if (view)
1193             [view lockFocus];
1194           focus_view = view;
1195 /*if (view) debug_lock++; */
1196         }
1197     }
1199   /* clipping */
1200   if (r)
1201     {
1202       [[NSGraphicsContext currentContext] saveGraphicsState];
1203       if (n == 2)
1204         NSRectClipList (r, 2);
1205       else
1206         NSRectClip (*r);
1207       gsaved = YES;
1208     }
1212 static void
1213 ns_unfocus (struct frame *f)
1214 /* --------------------------------------------------------------------------
1215      Internal: Remove focus on given frame
1216    -------------------------------------------------------------------------- */
1218   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1220   if (gsaved)
1221     {
1222       [[NSGraphicsContext currentContext] restoreGraphicsState];
1223       gsaved = NO;
1224     }
1226   if (f != ns_updating_frame)
1227     {
1228       if (focus_view != NULL)
1229         {
1230           [focus_view unlockFocus];
1231           [[focus_view window] flushWindow];
1232           focus_view = NULL;
1233 /*debug_lock--; */
1234         }
1235     }
1239 static void
1240 ns_clip_to_row (struct window *w, struct glyph_row *row,
1241                 enum glyph_row_area area, BOOL gc)
1242 /* --------------------------------------------------------------------------
1243      Internal (but parallels other terms): Focus drawing on given row
1244    -------------------------------------------------------------------------- */
1246   struct frame *f = XFRAME (WINDOW_FRAME (w));
1247   NSRect clip_rect;
1248   int window_x, window_y, window_width;
1250   window_box (w, area, &window_x, &window_y, &window_width, 0);
1252   clip_rect.origin.x = window_x;
1253   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1254   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1255   clip_rect.size.width = window_width;
1256   clip_rect.size.height = row->visible_height;
1258   ns_focus (f, &clip_rect, 1);
1262 /* ==========================================================================
1264     Visible bell and beep.
1266    ========================================================================== */
1269 // This bell implementation shows the visual bell image asynchronously
1270 // from the rest of Emacs. This is done by adding a NSView to the
1271 // superview of the Emacs window and removing it using a timer.
1273 // Unfortunately, some Emacs operations, like scrolling, is done using
1274 // low-level primitives that copy the content of the window, including
1275 // the bell image. To some extent, this is handled by removing the
1276 // image prior to scrolling and marking that the window is in need for
1277 // redisplay.
1279 // To test this code, make sure that there is no artifacts of the bell
1280 // image in the following situations. Use a non-empty buffer (like the
1281 // tutorial) to ensure that a scroll is performed:
1283 // * Single-window: C-g C-v
1285 // * Side-by-windows: C-x 3 C-g C-v
1287 // * Windows above each other: C-x 2 C-g C-v
1289 @interface EmacsBell : NSImageView
1291   // Number of currently active bell:s.
1292   unsigned int nestCount;
1293   NSView * mView;
1294   bool isAttached;
1296 - (void)show:(NSView *)view;
1297 - (void)hide;
1298 - (void)remove;
1299 @end
1301 @implementation EmacsBell
1303 - (id)init;
1305   NSTRACE ("[EmacsBell init]");
1306   if ((self = [super init]))
1307     {
1308       nestCount = 0;
1309       isAttached = false;
1310 #ifdef NS_IMPL_GNUSTEP
1311       // GNUstep doesn't provide named images.  This was reported in
1312       // 2011, see https://savannah.gnu.org/bugs/?33396
1313       //
1314       // As a drop in replacement, a semitransparent gray square is used.
1315       self.image = [[NSImage alloc] initWithSize:NSMakeSize(32 * 5, 32 * 5)];
1316       [self.image lockFocus];
1317       [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1318       NSRectFill(NSMakeRect(0, 0, 32, 32));
1319       [self.image unlockFocus];
1320 #else
1321       self.image = [NSImage imageNamed:NSImageNameCaution];
1322       [self.image setSize:NSMakeSize(self.image.size.width * 5,
1323                                      self.image.size.height * 5)];
1324 #endif
1325     }
1326   return self;
1329 - (void)show:(NSView *)view
1331   NSTRACE ("[EmacsBell show:]");
1332   NSTRACE_MSG ("nestCount: %u", nestCount);
1334   // Show the image, unless it's already shown.
1335   if (nestCount == 0)
1336     {
1337       NSRect rect = [view bounds];
1338       NSPoint pos;
1339       pos.x = rect.origin.x + (rect.size.width  - self.image.size.width )/2;
1340       pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1342       [self setFrameOrigin:pos];
1343       [self setFrameSize:self.image.size];
1345       isAttached = true;
1346       mView = view;
1347       [[[view window] contentView] addSubview:self
1348                                    positioned:NSWindowAbove
1349                                    relativeTo:nil];
1350     }
1352   ++nestCount;
1354   [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1358 - (void)hide
1360   // Note: Trace output from this method isn't shown, reason unknown.
1361   // NSTRACE ("[EmacsBell hide]");
1363   if (nestCount > 0)
1364     --nestCount;
1366   // Remove the image once the last bell became inactive.
1367   if (nestCount == 0)
1368     {
1369       [self remove];
1370     }
1374 -(void)remove
1376   NSTRACE ("[EmacsBell remove]");
1377   if (isAttached)
1378     {
1379       NSTRACE_MSG ("removeFromSuperview");
1380       [self removeFromSuperview];
1381       mView.needsDisplay = YES;
1382       isAttached = false;
1383     }
1386 @end
1389 static EmacsBell * bell_view = nil;
1391 static void
1392 ns_ring_bell (struct frame *f)
1393 /* --------------------------------------------------------------------------
1394      "Beep" routine
1395    -------------------------------------------------------------------------- */
1397   NSTRACE ("ns_ring_bell");
1398   if (visible_bell)
1399     {
1400       struct frame *frame = SELECTED_FRAME ();
1401       NSView *view;
1403       if (bell_view == nil)
1404         {
1405           bell_view = [[EmacsBell alloc] init];
1406           [bell_view retain];
1407         }
1409       block_input ();
1411       view = FRAME_NS_VIEW (frame);
1412       if (view != nil)
1413         {
1414           [bell_view show:view];
1415         }
1417       unblock_input ();
1418     }
1419   else
1420     {
1421       NSBeep ();
1422     }
1426 static void hide_bell ()
1427 /* --------------------------------------------------------------------------
1428      Ensure the bell is hidden.
1429    -------------------------------------------------------------------------- */
1431   NSTRACE ("hide_bell");
1433   if (bell_view != nil)
1434     {
1435       [bell_view remove];
1436     }
1440 /* ==========================================================================
1442     Frame / window manager related functions
1444    ========================================================================== */
1447 static void
1448 ns_raise_frame (struct frame *f)
1449 /* --------------------------------------------------------------------------
1450      Bring window to foreground and make it active
1451    -------------------------------------------------------------------------- */
1453   NSView *view;
1455   check_window_system (f);
1456   view = FRAME_NS_VIEW (f);
1457   block_input ();
1458   if (FRAME_VISIBLE_P (f))
1459     [[view window] makeKeyAndOrderFront: NSApp];
1460   unblock_input ();
1464 static void
1465 ns_lower_frame (struct frame *f)
1466 /* --------------------------------------------------------------------------
1467      Send window to back
1468    -------------------------------------------------------------------------- */
1470   NSView *view;
1472   check_window_system (f);
1473   view = FRAME_NS_VIEW (f);
1474   block_input ();
1475   [[view window] orderBack: NSApp];
1476   unblock_input ();
1480 static void
1481 ns_frame_raise_lower (struct frame *f, bool raise)
1482 /* --------------------------------------------------------------------------
1483      External (hook)
1484    -------------------------------------------------------------------------- */
1486   NSTRACE ("ns_frame_raise_lower");
1488   if (raise)
1489     ns_raise_frame (f);
1490   else
1491     ns_lower_frame (f);
1495 static void
1496 ns_frame_rehighlight (struct frame *frame)
1497 /* --------------------------------------------------------------------------
1498      External (hook): called on things like window switching within frame
1499    -------------------------------------------------------------------------- */
1501   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1502   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1504   NSTRACE ("ns_frame_rehighlight");
1505   if (dpyinfo->x_focus_frame)
1506     {
1507       dpyinfo->x_highlight_frame
1508         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1509            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1510            : dpyinfo->x_focus_frame);
1511       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1512         {
1513           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1514           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1515         }
1516     }
1517   else
1518       dpyinfo->x_highlight_frame = 0;
1520   if (dpyinfo->x_highlight_frame &&
1521          dpyinfo->x_highlight_frame != old_highlight)
1522     {
1523       if (old_highlight)
1524         {
1525           x_update_cursor (old_highlight, 1);
1526           x_set_frame_alpha (old_highlight);
1527         }
1528       if (dpyinfo->x_highlight_frame)
1529         {
1530           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1531           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1532         }
1533     }
1537 void
1538 x_make_frame_visible (struct frame *f)
1539 /* --------------------------------------------------------------------------
1540      External: Show the window (X11 semantics)
1541    -------------------------------------------------------------------------- */
1543   NSTRACE ("x_make_frame_visible");
1544   /* XXX: at some points in past this was not needed, as the only place that
1545      called this (frame.c:Fraise_frame ()) also called raise_lower;
1546      if this ends up the case again, comment this out again. */
1547   if (!FRAME_VISIBLE_P (f))
1548     {
1549       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1551       SET_FRAME_VISIBLE (f, 1);
1552       ns_raise_frame (f);
1554       /* Making a new frame from a fullscreen frame will make the new frame
1555          fullscreen also.  So skip handleFS as this will print an error.  */
1556       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1557           && [view isFullscreen])
1558         return;
1560       if (f->want_fullscreen != FULLSCREEN_NONE)
1561         {
1562           block_input ();
1563           [view handleFS];
1564           unblock_input ();
1565         }
1566     }
1570 void
1571 x_make_frame_invisible (struct frame *f)
1572 /* --------------------------------------------------------------------------
1573      External: Hide the window (X11 semantics)
1574    -------------------------------------------------------------------------- */
1576   NSView *view;
1577   NSTRACE ("x_make_frame_invisible");
1578   check_window_system (f);
1579   view = FRAME_NS_VIEW (f);
1580   [[view window] orderOut: NSApp];
1581   SET_FRAME_VISIBLE (f, 0);
1582   SET_FRAME_ICONIFIED (f, 0);
1586 void
1587 x_iconify_frame (struct frame *f)
1588 /* --------------------------------------------------------------------------
1589      External: Iconify window
1590    -------------------------------------------------------------------------- */
1592   NSView *view;
1593   struct ns_display_info *dpyinfo;
1595   NSTRACE ("x_iconify_frame");
1596   check_window_system (f);
1597   view = FRAME_NS_VIEW (f);
1598   dpyinfo = FRAME_DISPLAY_INFO (f);
1600   if (dpyinfo->x_highlight_frame == f)
1601     dpyinfo->x_highlight_frame = 0;
1603   if ([[view window] windowNumber] <= 0)
1604     {
1605       /* the window is still deferred.  Make it very small, bring it
1606          on screen and order it out. */
1607       NSRect s = { { 100, 100}, {0, 0} };
1608       NSRect t;
1609       t = [[view window] frame];
1610       [[view window] setFrame: s display: NO];
1611       [[view window] orderBack: NSApp];
1612       [[view window] orderOut: NSApp];
1613       [[view window] setFrame: t display: NO];
1614     }
1616   /* Processing input while Emacs is being minimized can cause a
1617      crash, so block it for the duration. */
1618   block_input();
1619   [[view window] miniaturize: NSApp];
1620   unblock_input();
1623 /* Free X resources of frame F.  */
1625 void
1626 x_free_frame_resources (struct frame *f)
1628   NSView *view;
1629   struct ns_display_info *dpyinfo;
1630   Mouse_HLInfo *hlinfo;
1632   NSTRACE ("x_free_frame_resources");
1633   check_window_system (f);
1634   view = FRAME_NS_VIEW (f);
1635   dpyinfo = FRAME_DISPLAY_INFO (f);
1636   hlinfo = MOUSE_HL_INFO (f);
1638   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1640   block_input ();
1642   free_frame_menubar (f);
1643   free_frame_faces (f);
1645   if (f == dpyinfo->x_focus_frame)
1646     dpyinfo->x_focus_frame = 0;
1647   if (f == dpyinfo->x_highlight_frame)
1648     dpyinfo->x_highlight_frame = 0;
1649   if (f == hlinfo->mouse_face_mouse_frame)
1650     reset_mouse_highlight (hlinfo);
1652   if (f->output_data.ns->miniimage != nil)
1653     [f->output_data.ns->miniimage release];
1655   [[view window] close];
1656   [view release];
1658   xfree (f->output_data.ns);
1660   unblock_input ();
1663 void
1664 x_destroy_window (struct frame *f)
1665 /* --------------------------------------------------------------------------
1666      External: Delete the window
1667    -------------------------------------------------------------------------- */
1669   NSTRACE ("x_destroy_window");
1670   check_window_system (f);
1671   x_free_frame_resources (f);
1672   ns_window_num--;
1676 void
1677 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1678 /* --------------------------------------------------------------------------
1679      External: Position the window
1680    -------------------------------------------------------------------------- */
1682   NSView *view = FRAME_NS_VIEW (f);
1683   NSArray *screens = [NSScreen screens];
1684   NSScreen *fscreen = [screens objectAtIndex: 0];
1685   NSScreen *screen = [[view window] screen];
1687   NSTRACE ("x_set_offset");
1689   block_input ();
1691   f->left_pos = xoff;
1692   f->top_pos = yoff;
1694   if (view != nil && screen && fscreen)
1695     {
1696       f->left_pos = f->size_hint_flags & XNegative
1697         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1698         : f->left_pos;
1699       /* We use visibleFrame here to take menu bar into account.
1700          Ideally we should also adjust left/top with visibleFrame.origin.  */
1702       f->top_pos = f->size_hint_flags & YNegative
1703         ? ([screen visibleFrame].size.height + f->top_pos
1704            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1705            - FRAME_TOOLBAR_HEIGHT (f))
1706         : f->top_pos;
1707 #ifdef NS_IMPL_GNUSTEP
1708       if (f->left_pos < 100)
1709         f->left_pos = 100;  /* don't overlap menu */
1710 #endif
1711       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1712          menu bar.  */
1713       NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1714                                 SCREENMAXBOUND ([fscreen frame].size.height
1715                                                 - NS_TOP_POS (f)));
1716       NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1717       [[view window] setFrameTopLeftPoint: pt];
1718       f->size_hint_flags &= ~(XNegative|YNegative);
1719     }
1721   unblock_input ();
1725 void
1726 x_set_window_size (struct frame *f,
1727                    bool change_gravity,
1728                    int width,
1729                    int height,
1730                    bool pixelwise)
1731 /* --------------------------------------------------------------------------
1732      Adjust window pixel size based on given character grid size
1733      Impl is a bit more complex than other terms, need to do some
1734      internal clipping.
1735    -------------------------------------------------------------------------- */
1737   EmacsView *view = FRAME_NS_VIEW (f);
1738   NSWindow *window = [view window];
1739   NSRect wr = [window frame];
1740   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1741   int pixelwidth, pixelheight;
1742   int orig_height = wr.size.height;
1744   NSTRACE ("x_set_window_size");
1746   if (view == nil)
1747     return;
1749   NSTRACE_RECT ("current", wr);
1750   NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1751   NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1753   block_input ();
1755   if (pixelwise)
1756     {
1757       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1758       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1759     }
1760   else
1761     {
1762       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1763       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1764     }
1766   /* If we have a toolbar, take its height into account. */
1767   if (tb && ! [view isFullscreen])
1768     {
1769     /* NOTE: previously this would generate wrong result if toolbar not
1770              yet displayed and fixing toolbar_height=32 helped, but
1771              now (200903) seems no longer needed */
1772     FRAME_TOOLBAR_HEIGHT (f) =
1773       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1774         - FRAME_NS_TITLEBAR_HEIGHT (f);
1775 #if 0
1776       /* Only breaks things here, removed by martin 2015-09-30.  */
1777 #ifdef NS_IMPL_GNUSTEP
1778       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1779 #endif
1780 #endif
1781     }
1782   else
1783     FRAME_TOOLBAR_HEIGHT (f) = 0;
1785   wr.size.width = pixelwidth + f->border_width;
1786   wr.size.height = pixelheight;
1787   if (! [view isFullscreen])
1788     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1789       + FRAME_TOOLBAR_HEIGHT (f);
1791   /* Do not try to constrain to this screen.  We may have multiple
1792      screens, and want Emacs to span those.  Constraining to screen
1793      prevents that, and that is not nice to the user.  */
1794  if (f->output_data.ns->zooming)
1795    f->output_data.ns->zooming = 0;
1796  else
1797    wr.origin.y += orig_height - wr.size.height;
1799  frame_size_history_add
1800    (f, Qx_set_window_size_1, width, height,
1801     list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1802            Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1803            make_number (f->border_width),
1804            make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1805            make_number (FRAME_TOOLBAR_HEIGHT (f))));
1807   [window setFrame: wr display: YES];
1809   [view updateFrameSize: NO];
1810   unblock_input ();
1814 static void
1815 ns_fullscreen_hook (struct frame *f)
1817   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1819   NSTRACE ("ns_fullscreen_hook");
1821   if (!FRAME_VISIBLE_P (f))
1822     return;
1824    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1825     {
1826       /* Old style fs don't initiate correctly if created from
1827          init/default-frame alist, so use a timer (not nice...).
1828       */
1829       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1830                                      selector: @selector (handleFS)
1831                                      userInfo: nil repeats: NO];
1832       return;
1833     }
1835   block_input ();
1836   [view handleFS];
1837   unblock_input ();
1840 /* ==========================================================================
1842     Color management
1844    ========================================================================== */
1847 NSColor *
1848 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1850   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1851   if (idx < 1 || idx >= color_table->avail)
1852     return nil;
1853   return color_table->colors[idx];
1857 unsigned long
1858 ns_index_color (NSColor *color, struct frame *f)
1860   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1861   ptrdiff_t idx;
1862   ptrdiff_t i;
1864   if (!color_table->colors)
1865     {
1866       color_table->size = NS_COLOR_CAPACITY;
1867       color_table->avail = 1; /* skip idx=0 as marker */
1868       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1869       color_table->colors[0] = nil;
1870       color_table->empty_indices = [[NSMutableSet alloc] init];
1871     }
1873   /* Do we already have this color?  */
1874   for (i = 1; i < color_table->avail; i++)
1875     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1876       return i;
1878   if ([color_table->empty_indices count] > 0)
1879     {
1880       NSNumber *index = [color_table->empty_indices anyObject];
1881       [color_table->empty_indices removeObject: index];
1882       idx = [index unsignedLongValue];
1883     }
1884   else
1885     {
1886       if (color_table->avail == color_table->size)
1887         color_table->colors =
1888           xpalloc (color_table->colors, &color_table->size, 1,
1889                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1890       idx = color_table->avail++;
1891     }
1893   color_table->colors[idx] = color;
1894   [color retain];
1895 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1896   return idx;
1900 void
1901 ns_free_indexed_color (unsigned long idx, struct frame *f)
1903   struct ns_color_table *color_table;
1904   NSColor *color;
1905   NSNumber *index;
1907   if (!f)
1908     return;
1910   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1912   if (idx <= 0 || idx >= color_table->size) {
1913     message1 ("ns_free_indexed_color: Color index out of range.\n");
1914     return;
1915   }
1917   index = [NSNumber numberWithUnsignedInt: idx];
1918   if ([color_table->empty_indices containsObject: index]) {
1919     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1920     return;
1921   }
1923   color = color_table->colors[idx];
1924   [color release];
1925   color_table->colors[idx] = nil;
1926   [color_table->empty_indices addObject: index];
1927 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1931 static int
1932 ns_get_color (const char *name, NSColor **col)
1933 /* --------------------------------------------------------------------------
1934      Parse a color name
1935    -------------------------------------------------------------------------- */
1936 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1937    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1938    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1940   NSColor *new = nil;
1941   static char hex[20];
1942   int scaling = 0;
1943   float r = -1.0, g, b;
1944   NSString *nsname = [NSString stringWithUTF8String: name];
1946   NSTRACE ("ns_get_color(%s, **)", name);
1948   block_input ();
1950   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1951     {
1952 #ifdef NS_IMPL_COCOA
1953       NSString *defname = [[NSUserDefaults standardUserDefaults]
1954                             stringForKey: @"AppleHighlightColor"];
1955       if (defname != nil)
1956         nsname = defname;
1957       else
1958 #endif
1959       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1960         {
1961           *col = [new colorUsingDefaultColorSpace];
1962           unblock_input ();
1963           return 0;
1964         }
1965       else
1966         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1968       name = [nsname UTF8String];
1969     }
1970   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1971     {
1972       /* NOTE: OSX applications normally don't set foreground selection, but
1973          text may be unreadable if we don't.
1974       */
1975       if ((new = [NSColor selectedTextColor]) != nil)
1976         {
1977           *col = [new colorUsingDefaultColorSpace];
1978           unblock_input ();
1979           return 0;
1980         }
1982       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1983       name = [nsname UTF8String];
1984     }
1986   /* First, check for some sort of numeric specification. */
1987   hex[0] = '\0';
1989   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1990     {
1991       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1992       [scanner scanFloat: &r];
1993       [scanner scanFloat: &g];
1994       [scanner scanFloat: &b];
1995     }
1996   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1997     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1998   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1999     {
2000       int len = (strlen(name) - 1);
2001       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
2002       int i;
2003       scaling = strlen(name+start) / 3;
2004       for (i = 0; i < 3; i++)
2005         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
2006                  name + start + i * scaling);
2007       hex[3 * (scaling + 1) - 1] = '\0';
2008     }
2010   if (hex[0])
2011     {
2012       int rr, gg, bb;
2013       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
2014       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
2015         {
2016           r = rr / fscale;
2017           g = gg / fscale;
2018           b = bb / fscale;
2019         }
2020     }
2022   if (r >= 0.0F)
2023     {
2024       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
2025       unblock_input ();
2026       return 0;
2027     }
2029   /* Otherwise, color is expected to be from a list */
2030   {
2031     NSEnumerator *lenum, *cenum;
2032     NSString *name;
2033     NSColorList *clist;
2035 #ifdef NS_IMPL_GNUSTEP
2036     /* XXX: who is wrong, the requestor or the implementation? */
2037     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
2038         == NSOrderedSame)
2039       nsname = @"highlightColor";
2040 #endif
2042     lenum = [[NSColorList availableColorLists] objectEnumerator];
2043     while ( (clist = [lenum nextObject]) && new == nil)
2044       {
2045         cenum = [[clist allKeys] objectEnumerator];
2046         while ( (name = [cenum nextObject]) && new == nil )
2047           {
2048             if ([name compare: nsname
2049                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
2050               new = [clist colorWithKey: name];
2051           }
2052       }
2053   }
2055   if (new)
2056     *col = [new colorUsingDefaultColorSpace];
2057   unblock_input ();
2058   return new ? 0 : 1;
2063 ns_lisp_to_color (Lisp_Object color, NSColor **col)
2064 /* --------------------------------------------------------------------------
2065      Convert a Lisp string object to a NS color
2066    -------------------------------------------------------------------------- */
2068   NSTRACE ("ns_lisp_to_color");
2069   if (STRINGP (color))
2070     return ns_get_color (SSDATA (color), col);
2071   else if (SYMBOLP (color))
2072     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
2073   return 1;
2077 Lisp_Object
2078 ns_color_to_lisp (NSColor *col)
2079 /* --------------------------------------------------------------------------
2080      Convert a color to a lisp string with the RGB equivalent
2081    -------------------------------------------------------------------------- */
2083   EmacsCGFloat red, green, blue, alpha, gray;
2084   char buf[1024];
2085   const char *str;
2086   NSTRACE ("ns_color_to_lisp");
2088   block_input ();
2089   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
2091       if ((str =[[col colorNameComponent] UTF8String]))
2092         {
2093           unblock_input ();
2094           return build_string ((char *)str);
2095         }
2097     [[col colorUsingDefaultColorSpace]
2098         getRed: &red green: &green blue: &blue alpha: &alpha];
2099   if (red == green && red == blue)
2100     {
2101       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
2102             getWhite: &gray alpha: &alpha];
2103       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2104                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
2105       unblock_input ();
2106       return build_string (buf);
2107     }
2109   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2110             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
2112   unblock_input ();
2113   return build_string (buf);
2117 void
2118 ns_query_color(void *col, XColor *color_def, int setPixel)
2119 /* --------------------------------------------------------------------------
2120          Get ARGB values out of NSColor col and put them into color_def.
2121          If setPixel, set the pixel to a concatenated version.
2122          and set color_def pixel to the resulting index.
2123    -------------------------------------------------------------------------- */
2125   EmacsCGFloat r, g, b, a;
2127   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2128   color_def->red   = r * 65535;
2129   color_def->green = g * 65535;
2130   color_def->blue  = b * 65535;
2132   if (setPixel == YES)
2133     color_def->pixel
2134       = ARGB_TO_ULONG((int)(a*255),
2135                       (int)(r*255), (int)(g*255), (int)(b*255));
2139 bool
2140 ns_defined_color (struct frame *f,
2141                   const char *name,
2142                   XColor *color_def,
2143                   bool alloc,
2144                   bool makeIndex)
2145 /* --------------------------------------------------------------------------
2146          Return true if named color found, and set color_def rgb accordingly.
2147          If makeIndex and alloc are nonzero put the color in the color_table,
2148          and set color_def pixel to the resulting index.
2149          If makeIndex is zero, set color_def pixel to ARGB.
2150          Return false if not found
2151    -------------------------------------------------------------------------- */
2153   NSColor *col;
2154   NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2156   block_input ();
2157   if (ns_get_color (name, &col) != 0) /* Color not found  */
2158     {
2159       unblock_input ();
2160       return 0;
2161     }
2162   if (makeIndex && alloc)
2163     color_def->pixel = ns_index_color (col, f);
2164   ns_query_color (col, color_def, !makeIndex);
2165   unblock_input ();
2166   return 1;
2170 void
2171 x_set_frame_alpha (struct frame *f)
2172 /* --------------------------------------------------------------------------
2173      change the entire-frame transparency
2174    -------------------------------------------------------------------------- */
2176   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2177   double alpha = 1.0;
2178   double alpha_min = 1.0;
2180   NSTRACE ("x_set_frame_alpha");
2182   if (dpyinfo->x_highlight_frame == f)
2183     alpha = f->alpha[0];
2184   else
2185     alpha = f->alpha[1];
2187   if (FLOATP (Vframe_alpha_lower_limit))
2188     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2189   else if (INTEGERP (Vframe_alpha_lower_limit))
2190     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2192   if (alpha < 0.0)
2193     return;
2194   else if (1.0 < alpha)
2195     alpha = 1.0;
2196   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2197     alpha = alpha_min;
2199 #ifdef NS_IMPL_COCOA
2200   {
2201     EmacsView *view = FRAME_NS_VIEW (f);
2202   [[view window] setAlphaValue: alpha];
2203   }
2204 #endif
2208 /* ==========================================================================
2210     Mouse handling
2212    ========================================================================== */
2215 void
2216 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2217 /* --------------------------------------------------------------------------
2218      Programmatically reposition mouse pointer in pixel coordinates
2219    -------------------------------------------------------------------------- */
2221   NSTRACE ("frame_set_mouse_pixel_position");
2222   ns_raise_frame (f);
2223 #if 0
2224   /* FIXME: this does not work, and what about GNUstep? */
2225 #ifdef NS_IMPL_COCOA
2226   [FRAME_NS_VIEW (f) lockFocus];
2227   PSsetmouse ((float)pix_x, (float)pix_y);
2228   [FRAME_NS_VIEW (f) unlockFocus];
2229 #endif
2230 #endif
2233 static int
2234 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2235 /*   ------------------------------------------------------------------------
2236      Called by EmacsView on mouseMovement events.  Passes on
2237      to emacs mainstream code if we moved off of a rect of interest
2238      known as last_mouse_glyph.
2239      ------------------------------------------------------------------------ */
2241   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2242   NSRect *r;
2244 //  NSTRACE ("note_mouse_movement");
2246   dpyinfo->last_mouse_motion_frame = frame;
2247   r = &dpyinfo->last_mouse_glyph;
2249   /* Note, this doesn't get called for enter/leave, since we don't have a
2250      position.  Those are taken care of in the corresponding NSView methods. */
2252   /* has movement gone beyond last rect we were tracking? */
2253   if (x < r->origin.x || x >= r->origin.x + r->size.width
2254       || y < r->origin.y || y >= r->origin.y + r->size.height)
2255     {
2256       ns_update_begin (frame);
2257       frame->mouse_moved = 1;
2258       note_mouse_highlight (frame, x, y);
2259       remember_mouse_glyph (frame, x, y, r);
2260       ns_update_end (frame);
2261       return 1;
2262     }
2264   return 0;
2268 static void
2269 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2270                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2271                    Time *time)
2272 /* --------------------------------------------------------------------------
2273     External (hook): inform emacs about mouse position and hit parts.
2274     If a scrollbar is being dragged, set bar_window, part, x, y, time.
2275     x & y should be position in the scrollbar (the whole bar, not the handle)
2276     and length of scrollbar respectively
2277    -------------------------------------------------------------------------- */
2279   id view;
2280   NSPoint position;
2281   Lisp_Object frame, tail;
2282   struct frame *f;
2283   struct ns_display_info *dpyinfo;
2285   NSTRACE ("ns_mouse_position");
2287   if (*fp == NULL)
2288     {
2289       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2290       return;
2291     }
2293   dpyinfo = FRAME_DISPLAY_INFO (*fp);
2295   block_input ();
2297   /* Clear the mouse-moved flag for every frame on this display.  */
2298   FOR_EACH_FRAME (tail, frame)
2299     if (FRAME_NS_P (XFRAME (frame))
2300         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2301       XFRAME (frame)->mouse_moved = 0;
2303   dpyinfo->last_mouse_scroll_bar = nil;
2304   if (dpyinfo->last_mouse_frame
2305       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2306     f = dpyinfo->last_mouse_frame;
2307   else
2308     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2310   if (f && FRAME_NS_P (f))
2311     {
2312       view = FRAME_NS_VIEW (*fp);
2314       position = [[view window] mouseLocationOutsideOfEventStream];
2315       position = [view convertPoint: position fromView: nil];
2316       remember_mouse_glyph (f, position.x, position.y,
2317                             &dpyinfo->last_mouse_glyph);
2318       NSTRACE_POINT ("position", position);
2320       if (bar_window) *bar_window = Qnil;
2321       if (part) *part = scroll_bar_above_handle;
2323       if (x) XSETINT (*x, lrint (position.x));
2324       if (y) XSETINT (*y, lrint (position.y));
2325       if (time)
2326         *time = dpyinfo->last_mouse_movement_time;
2327       *fp = f;
2328     }
2330   unblock_input ();
2334 static void
2335 ns_frame_up_to_date (struct frame *f)
2336 /* --------------------------------------------------------------------------
2337     External (hook): Fix up mouse highlighting right after a full update.
2338     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2339    -------------------------------------------------------------------------- */
2341   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2343   if (FRAME_NS_P (f))
2344     {
2345       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2346       if (f == hlinfo->mouse_face_mouse_frame)
2347         {
2348           block_input ();
2349           ns_update_begin(f);
2350           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2351                                 hlinfo->mouse_face_mouse_x,
2352                                 hlinfo->mouse_face_mouse_y);
2353           ns_update_end(f);
2354           unblock_input ();
2355         }
2356     }
2360 static void
2361 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2362 /* --------------------------------------------------------------------------
2363     External (RIF): set frame mouse pointer type.
2364    -------------------------------------------------------------------------- */
2366   NSTRACE ("ns_define_frame_cursor");
2367   if (FRAME_POINTER_TYPE (f) != cursor)
2368     {
2369       EmacsView *view = FRAME_NS_VIEW (f);
2370       FRAME_POINTER_TYPE (f) = cursor;
2371       [[view window] invalidateCursorRectsForView: view];
2372       /* Redisplay assumes this function also draws the changed frame
2373          cursor, but this function doesn't, so do it explicitly.  */
2374       x_update_cursor (f, 1);
2375     }
2380 /* ==========================================================================
2382     Keyboard handling
2384    ========================================================================== */
2387 static unsigned
2388 ns_convert_key (unsigned code)
2389 /* --------------------------------------------------------------------------
2390     Internal call used by NSView-keyDown.
2391    -------------------------------------------------------------------------- */
2393   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2394   unsigned keysym;
2395   /* An array would be faster, but less easy to read. */
2396   for (keysym = 0; keysym < last_keysym; keysym += 2)
2397     if (code == convert_ns_to_X_keysym[keysym])
2398       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2399   return 0;
2400 /* if decide to use keyCode and Carbon table, use this line:
2401      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2405 char *
2406 x_get_keysym_name (int keysym)
2407 /* --------------------------------------------------------------------------
2408     Called by keyboard.c.  Not sure if the return val is important, except
2409     that it be unique.
2410    -------------------------------------------------------------------------- */
2412   static char value[16];
2413   NSTRACE ("x_get_keysym_name");
2414   sprintf (value, "%d", keysym);
2415   return value;
2420 /* ==========================================================================
2422     Block drawing operations
2424    ========================================================================== */
2427 static void
2428 ns_redraw_scroll_bars (struct frame *f)
2430   int i;
2431   id view;
2432   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2433   NSTRACE ("ns_redraw_scroll_bars");
2434   for (i =[subviews count]-1; i >= 0; i--)
2435     {
2436       view = [subviews objectAtIndex: i];
2437       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2438       [view display];
2439     }
2443 void
2444 ns_clear_frame (struct frame *f)
2445 /* --------------------------------------------------------------------------
2446       External (hook): Erase the entire frame
2447    -------------------------------------------------------------------------- */
2449   NSView *view = FRAME_NS_VIEW (f);
2450   NSRect r;
2452   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2454  /* comes on initial frame because we have
2455     after-make-frame-functions = select-frame */
2456  if (!FRAME_DEFAULT_FACE (f))
2457    return;
2459   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2461   r = [view bounds];
2463   block_input ();
2464   ns_focus (f, &r, 1);
2465   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2466   NSRectFill (r);
2467   ns_unfocus (f);
2469   /* as of 2006/11 or so this is now needed */
2470   ns_redraw_scroll_bars (f);
2471   unblock_input ();
2475 static void
2476 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2477 /* --------------------------------------------------------------------------
2478     External (RIF):  Clear section of frame
2479    -------------------------------------------------------------------------- */
2481   NSRect r = NSMakeRect (x, y, width, height);
2482   NSView *view = FRAME_NS_VIEW (f);
2483   struct face *face = FRAME_DEFAULT_FACE (f);
2485   if (!view || !face)
2486     return;
2488   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2490   r = NSIntersectionRect (r, [view frame]);
2491   ns_focus (f, &r, 1);
2492   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2494   NSRectFill (r);
2496   ns_unfocus (f);
2497   return;
2500 static void
2501 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2503   NSTRACE ("ns_copy_bits");
2505   if (FRAME_NS_VIEW (f))
2506     {
2507       hide_bell();              // Ensure the bell image isn't scrolled.
2509       ns_focus (f, &dest, 1);
2510       [FRAME_NS_VIEW (f) scrollRect: src
2511                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2512                                                  dest.origin.y - src.origin.y)];
2513       ns_unfocus (f);
2514     }
2517 static void
2518 ns_scroll_run (struct window *w, struct run *run)
2519 /* --------------------------------------------------------------------------
2520     External (RIF):  Insert or delete n lines at line vpos
2521    -------------------------------------------------------------------------- */
2523   struct frame *f = XFRAME (w->frame);
2524   int x, y, width, height, from_y, to_y, bottom_y;
2526   NSTRACE ("ns_scroll_run");
2528   /* begin copy from other terms */
2529   /* Get frame-relative bounding box of the text display area of W,
2530      without mode lines.  Include in this box the left and right
2531      fringe of W.  */
2532   window_box (w, ANY_AREA, &x, &y, &width, &height);
2534   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2535   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2536   bottom_y = y + height;
2538   if (to_y < from_y)
2539     {
2540       /* Scrolling up.  Make sure we don't copy part of the mode
2541          line at the bottom.  */
2542       if (from_y + run->height > bottom_y)
2543         height = bottom_y - from_y;
2544       else
2545         height = run->height;
2546     }
2547   else
2548     {
2549       /* Scrolling down.  Make sure we don't copy over the mode line.
2550          at the bottom.  */
2551       if (to_y + run->height > bottom_y)
2552         height = bottom_y - to_y;
2553       else
2554         height = run->height;
2555     }
2556   /* end copy from other terms */
2558   if (height == 0)
2559       return;
2561   block_input ();
2563   x_clear_cursor (w);
2565   {
2566     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2567     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2569     ns_copy_bits (f, srcRect , dstRect);
2570   }
2572   unblock_input ();
2576 static void
2577 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2578 /* --------------------------------------------------------------------------
2579     External (RIF): preparatory to fringe update after text was updated
2580    -------------------------------------------------------------------------- */
2582   struct frame *f;
2583   int width, height;
2585   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2587   /* begin copy from other terms */
2588   eassert (w);
2590   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2591     desired_row->redraw_fringe_bitmaps_p = 1;
2593   /* When a window has disappeared, make sure that no rest of
2594      full-width rows stays visible in the internal border.  */
2595   if (windows_or_buffers_changed
2596       && desired_row->full_width_p
2597       && (f = XFRAME (w->frame),
2598           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2599           width != 0)
2600       && (height = desired_row->visible_height,
2601           height > 0))
2602     {
2603       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2605       block_input ();
2606       ns_clear_frame_area (f, 0, y, width, height);
2607       ns_clear_frame_area (f,
2608                            FRAME_PIXEL_WIDTH (f) - width,
2609                            y, width, height);
2610       unblock_input ();
2611     }
2615 static void
2616 ns_shift_glyphs_for_insert (struct frame *f,
2617                            int x, int y, int width, int height,
2618                            int shift_by)
2619 /* --------------------------------------------------------------------------
2620     External (RIF): copy an area horizontally, don't worry about clearing src
2621    -------------------------------------------------------------------------- */
2623   NSRect srcRect = NSMakeRect (x, y, width, height);
2624   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2626   NSTRACE ("ns_shift_glyphs_for_insert");
2628   ns_copy_bits (f, srcRect, dstRect);
2633 /* ==========================================================================
2635     Character encoding and metrics
2637    ========================================================================== */
2640 static void
2641 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2642 /* --------------------------------------------------------------------------
2643      External (RIF); compute left/right overhang of whole string and set in s
2644    -------------------------------------------------------------------------- */
2646   struct font *font = s->font;
2648   if (s->char2b)
2649     {
2650       struct font_metrics metrics;
2651       unsigned int codes[2];
2652       codes[0] = *(s->char2b);
2653       codes[1] = *(s->char2b + s->nchars - 1);
2655       font->driver->text_extents (font, codes, 2, &metrics);
2656       s->left_overhang = -metrics.lbearing;
2657       s->right_overhang
2658         = metrics.rbearing > metrics.width
2659         ? metrics.rbearing - metrics.width : 0;
2660     }
2661   else
2662     {
2663       s->left_overhang = 0;
2664       if (EQ (font->driver->type, Qns))
2665         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2666           FONT_HEIGHT (font) * 0.2 : 0;
2667       else
2668         s->right_overhang = 0;
2669     }
2674 /* ==========================================================================
2676     Fringe and cursor drawing
2678    ========================================================================== */
2681 extern int max_used_fringe_bitmap;
2682 static void
2683 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2684                       struct draw_fringe_bitmap_params *p)
2685 /* --------------------------------------------------------------------------
2686     External (RIF); fringe-related
2687    -------------------------------------------------------------------------- */
2689   /* Fringe bitmaps comes in two variants, normal and periodic.  A
2690      periodic bitmap is used to create a continuous pattern.  Since a
2691      bitmap is rendered one text line at a time, the start offset (dh)
2692      of the bitmap varies.  Concretely, this is used for the empty
2693      line indicator.
2695      For a bitmap, "h + dh" is the full height and is always
2696      invariant.  For a normal bitmap "dh" is zero.
2698      For example, when the period is three and the full height is 72
2699      the following combinations exists:
2701        h=72 dh=0
2702        h=71 dh=1
2703        h=70 dh=2 */
2705   struct frame *f = XFRAME (WINDOW_FRAME (w));
2706   struct face *face = p->face;
2707   static EmacsImage **bimgs = NULL;
2708   static int nBimgs = 0;
2710   NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2711   NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2712                p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2714   /* grow bimgs if needed */
2715   if (nBimgs < max_used_fringe_bitmap)
2716     {
2717       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2718       memset (bimgs + nBimgs, 0,
2719               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2720       nBimgs = max_used_fringe_bitmap;
2721     }
2723   /* Must clip because of partially visible lines.  */
2724   ns_clip_to_row (w, row, ANY_AREA, YES);
2726   if (!p->overlay_p)
2727     {
2728       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2730       if (bx >= 0 && nx > 0)
2731         {
2732           NSRect r = NSMakeRect (bx, by, nx, ny);
2733           NSRectClip (r);
2734           [ns_lookup_indexed_color (face->background, f) set];
2735           NSRectFill (r);
2736         }
2737     }
2739   if (p->which)
2740     {
2741       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2742       EmacsImage *img = bimgs[p->which - 1];
2744       if (!img)
2745         {
2746           // Note: For "periodic" images, allocate one EmacsImage for
2747           // the base image, and use it for all dh:s.
2748           unsigned short *bits = p->bits;
2749           int full_height = p->h + p->dh;
2750           int i;
2751           unsigned char *cbits = xmalloc (full_height);
2753           for (i = 0; i < full_height; i++)
2754             cbits[i] = bits[i];
2755           img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2756                                          height: full_height
2757                                              fg: 0 bg: 0];
2758           bimgs[p->which - 1] = img;
2759           xfree (cbits);
2760         }
2762       NSTRACE_RECT ("r", r);
2764       NSRectClip (r);
2765       /* Since we composite the bitmap instead of just blitting it, we need
2766          to erase the whole background. */
2767       [ns_lookup_indexed_color(face->background, f) set];
2768       NSRectFill (r);
2770       {
2771         NSColor *bm_color;
2772         if (!p->cursor_p)
2773           bm_color = ns_lookup_indexed_color(face->foreground, f);
2774         else if (p->overlay_p)
2775           bm_color = ns_lookup_indexed_color(face->background, f);
2776         else
2777           bm_color = f->output_data.ns->cursor_color;
2778         [img setXBMColor: bm_color];
2779       }
2781 #ifdef NS_IMPL_COCOA
2782       // Note: For periodic images, the full image height is "h + hd".
2783       // By using the height h, a suitable part of the image is used.
2784       NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2786       NSTRACE_RECT ("fromRect", fromRect);
2788       [img drawInRect: r
2789               fromRect: fromRect
2790              operation: NSCompositeSourceOver
2791               fraction: 1.0
2792            respectFlipped: YES
2793                 hints: nil];
2794 #else
2795       {
2796         NSPoint pt = r.origin;
2797         pt.y += p->h;
2798         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2799       }
2800 #endif
2801     }
2802   ns_unfocus (f);
2806 static void
2807 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2808                        int x, int y, enum text_cursor_kinds cursor_type,
2809                        int cursor_width, bool on_p, bool active_p)
2810 /* --------------------------------------------------------------------------
2811      External call (RIF): draw cursor.
2812      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2813    -------------------------------------------------------------------------- */
2815   NSRect r, s;
2816   int fx, fy, h, cursor_height;
2817   struct frame *f = WINDOW_XFRAME (w);
2818   struct glyph *phys_cursor_glyph;
2819   struct glyph *cursor_glyph;
2820   struct face *face;
2821   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2823   /* If cursor is out of bounds, don't draw garbage.  This can happen
2824      in mini-buffer windows when switching between echo area glyphs
2825      and mini-buffer.  */
2827   NSTRACE ("ns_draw_window_cursor");
2829   if (!on_p)
2830     return;
2832   w->phys_cursor_type = cursor_type;
2833   w->phys_cursor_on_p = on_p;
2835   if (cursor_type == NO_CURSOR)
2836     {
2837       w->phys_cursor_width = 0;
2838       return;
2839     }
2841   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2842     {
2843       if (glyph_row->exact_window_width_line_p
2844           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2845         {
2846           glyph_row->cursor_in_fringe_p = 1;
2847           draw_fringe_bitmap (w, glyph_row, 0);
2848         }
2849       return;
2850     }
2852   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2853      (other terminals do it the other way round).  We must set
2854      w->phys_cursor_width to the cursor width.  For bar cursors, that
2855      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2856   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2858   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2859      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2860   if (cursor_type == BAR_CURSOR)
2861     {
2862       if (cursor_width < 1)
2863         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2864       w->phys_cursor_width = cursor_width;
2865     }
2866   /* If we have an HBAR, "cursor_width" MAY specify height. */
2867   else if (cursor_type == HBAR_CURSOR)
2868     {
2869       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2870       if (cursor_height > glyph_row->height)
2871         cursor_height = glyph_row->height;
2872       if (h > cursor_height) // Cursor smaller than line height, move down
2873         fy += h - cursor_height;
2874       h = cursor_height;
2875     }
2877   r.origin.x = fx, r.origin.y = fy;
2878   r.size.height = h;
2879   r.size.width = w->phys_cursor_width;
2881   /* Prevent the cursor from being drawn outside the text area. */
2882   ns_clip_to_row (w, glyph_row, TEXT_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2885   face = FACE_OPT_FROM_ID (f, phys_cursor_glyph->face_id);
2886   if (face && NS_FACE_BACKGROUND (face)
2887       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2888     {
2889       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2890       hollow_color = FRAME_CURSOR_COLOR (f);
2891     }
2892   else
2893     [FRAME_CURSOR_COLOR (f) set];
2895 #ifdef NS_IMPL_COCOA
2896   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2897            atomic.  Cleaner ways of doing this should be investigated.
2898            One way would be to set a global variable DRAWING_CURSOR
2899            when making the call to draw_phys..(), don't focus in that
2900            case, then move the ns_unfocus() here after that call. */
2901   NSDisableScreenUpdates ();
2902 #endif
2904   switch (cursor_type)
2905     {
2906     case DEFAULT_CURSOR:
2907     case NO_CURSOR:
2908       break;
2909     case FILLED_BOX_CURSOR:
2910       NSRectFill (r);
2911       break;
2912     case HOLLOW_BOX_CURSOR:
2913       NSRectFill (r);
2914       [hollow_color set];
2915       NSRectFill (NSInsetRect (r, 1, 1));
2916       [FRAME_CURSOR_COLOR (f) set];
2917       break;
2918     case HBAR_CURSOR:
2919       NSRectFill (r);
2920       break;
2921     case BAR_CURSOR:
2922       s = r;
2923       /* If the character under cursor is R2L, draw the bar cursor
2924          on the right of its glyph, rather than on the left.  */
2925       cursor_glyph = get_phys_cursor_glyph (w);
2926       if ((cursor_glyph->resolved_level & 1) != 0)
2927         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2929       NSRectFill (s);
2930       break;
2931     }
2932   ns_unfocus (f);
2934   /* draw the character under the cursor */
2935   if (cursor_type != NO_CURSOR)
2936     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2938 #ifdef NS_IMPL_COCOA
2939   NSEnableScreenUpdates ();
2940 #endif
2945 static void
2946 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2947 /* --------------------------------------------------------------------------
2948      External (RIF): Draw a vertical line.
2949    -------------------------------------------------------------------------- */
2951   struct frame *f = XFRAME (WINDOW_FRAME (w));
2952   struct face *face;
2953   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2955   NSTRACE ("ns_draw_vertical_window_border");
2957   face = FACE_OPT_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2958   if (face)
2959       [ns_lookup_indexed_color(face->foreground, f) set];
2961   ns_focus (f, &r, 1);
2962   NSRectFill(r);
2963   ns_unfocus (f);
2967 static void
2968 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2969 /* --------------------------------------------------------------------------
2970      External (RIF): Draw a window divider.
2971    -------------------------------------------------------------------------- */
2973   struct frame *f = XFRAME (WINDOW_FRAME (w));
2974   struct face *face;
2975   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2977   NSTRACE ("ns_draw_window_divider");
2979   face = FACE_OPT_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2980   if (face)
2981       [ns_lookup_indexed_color(face->foreground, f) set];
2983   ns_focus (f, &r, 1);
2984   NSRectFill(r);
2985   ns_unfocus (f);
2988 static void
2989 ns_show_hourglass (struct frame *f)
2991   /* TODO: add NSProgressIndicator to all frames.  */
2994 static void
2995 ns_hide_hourglass (struct frame *f)
2997   /* TODO: remove NSProgressIndicator from all frames.  */
3000 /* ==========================================================================
3002     Glyph drawing operations
3004    ========================================================================== */
3006 static int
3007 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
3008 /* --------------------------------------------------------------------------
3009     Wrapper utility to account for internal border width on full-width lines,
3010     and allow top full-width rows to hit the frame top.  nr should be pointer
3011     to two successive NSRects.  Number of rects actually used is returned.
3012    -------------------------------------------------------------------------- */
3014   int n = get_glyph_string_clip_rects (s, nr, 2);
3015   return n;
3018 /* --------------------------------------------------------------------
3019    Draw a wavy line under glyph string s. The wave fills wave_height
3020    pixels from y.
3022                     x          wave_length = 2
3023                                  --
3024                 y    *   *   *   *   *
3025                      |* * * * * * * * *
3026     wave_height = 3  | *   *   *   *
3027   --------------------------------------------------------------------- */
3029 static void
3030 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
3032   int wave_height = 3, wave_length = 2;
3033   int y, dx, dy, odd, xmax;
3034   NSPoint a, b;
3035   NSRect waveClip;
3037   dx = wave_length;
3038   dy = wave_height - 1;
3039   y =  s->ybase - wave_height + 3;
3040   xmax = x + width;
3042   /* Find and set clipping rectangle */
3043   waveClip = NSMakeRect (x, y, width, wave_height);
3044   [[NSGraphicsContext currentContext] saveGraphicsState];
3045   NSRectClip (waveClip);
3047   /* Draw the waves */
3048   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
3049   b.x = a.x + dx;
3050   odd = (int)(a.x/dx) % 2;
3051   a.y = b.y = y + 0.5;
3053   if (odd)
3054     a.y += dy;
3055   else
3056     b.y += dy;
3058   while (a.x <= xmax)
3059     {
3060       [NSBezierPath strokeLineFromPoint:a toPoint:b];
3061       a.x = b.x, a.y = b.y;
3062       b.x += dx, b.y = y + 0.5 + odd*dy;
3063       odd = !odd;
3064     }
3066   /* Restore previous clipping rectangle(s) */
3067   [[NSGraphicsContext currentContext] restoreGraphicsState];
3072 void
3073 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
3074                          NSColor *defaultCol, CGFloat width, CGFloat x)
3075 /* --------------------------------------------------------------------------
3076    Draw underline, overline, and strike-through on glyph string s.
3077    -------------------------------------------------------------------------- */
3079   if (s->for_overlaps)
3080     return;
3082   /* Do underline. */
3083   if (face->underline_p)
3084     {
3085       if (s->face->underline_type == FACE_UNDER_WAVE)
3086         {
3087           if (face->underline_defaulted_p)
3088             [defaultCol set];
3089           else
3090             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3092           ns_draw_underwave (s, width, x);
3093         }
3094       else if (s->face->underline_type == FACE_UNDER_LINE)
3095         {
3097           NSRect r;
3098           unsigned long thickness, position;
3100           /* If the prev was underlined, match its appearance. */
3101           if (s->prev && s->prev->face->underline_p
3102               && s->prev->face->underline_type == FACE_UNDER_LINE
3103               && s->prev->underline_thickness > 0)
3104             {
3105               thickness = s->prev->underline_thickness;
3106               position = s->prev->underline_position;
3107             }
3108           else
3109             {
3110               struct font *font;
3111               unsigned long descent;
3113               font=s->font;
3114               descent = s->y + s->height - s->ybase;
3116               /* Use underline thickness of font, defaulting to 1. */
3117               thickness = (font && font->underline_thickness > 0)
3118                 ? font->underline_thickness : 1;
3120               /* Determine the offset of underlining from the baseline. */
3121               if (x_underline_at_descent_line)
3122                 position = descent - thickness;
3123               else if (x_use_underline_position_properties
3124                        && font && font->underline_position >= 0)
3125                 position = font->underline_position;
3126               else if (font)
3127                 position = lround (font->descent / 2);
3128               else
3129                 position = underline_minimum_offset;
3131               position = max (position, underline_minimum_offset);
3133               /* Ensure underlining is not cropped. */
3134               if (descent <= position)
3135                 {
3136                   position = descent - 1;
3137                   thickness = 1;
3138                 }
3139               else if (descent < position + thickness)
3140                 thickness = 1;
3141             }
3143           s->underline_thickness = thickness;
3144           s->underline_position = position;
3146           r = NSMakeRect (x, s->ybase + position, width, thickness);
3148           if (face->underline_defaulted_p)
3149             [defaultCol set];
3150           else
3151             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3152           NSRectFill (r);
3153         }
3154     }
3155   /* Do overline. We follow other terms in using a thickness of 1
3156      and ignoring overline_margin. */
3157   if (face->overline_p)
3158     {
3159       NSRect r;
3160       r = NSMakeRect (x, s->y, width, 1);
3162       if (face->overline_color_defaulted_p)
3163         [defaultCol set];
3164       else
3165         [ns_lookup_indexed_color (face->overline_color, s->f) set];
3166       NSRectFill (r);
3167     }
3169   /* Do strike-through.  We follow other terms for thickness and
3170      vertical position.*/
3171   if (face->strike_through_p)
3172     {
3173       NSRect r;
3174       unsigned long dy;
3176       dy = lrint ((s->height - 1) / 2);
3177       r = NSMakeRect (x, s->y + dy, width, 1);
3179       if (face->strike_through_color_defaulted_p)
3180         [defaultCol set];
3181       else
3182         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3183       NSRectFill (r);
3184     }
3187 static void
3188 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3189              char left_p, char right_p)
3190 /* --------------------------------------------------------------------------
3191     Draw an unfilled rect inside r, optionally leaving left and/or right open.
3192     Note we can't just use an NSDrawRect command, because of the possibility
3193     of some sides not being drawn, and because the rect will be filled.
3194    -------------------------------------------------------------------------- */
3196   NSRect s = r;
3197   [col set];
3199   /* top, bottom */
3200   s.size.height = thickness;
3201   NSRectFill (s);
3202   s.origin.y += r.size.height - thickness;
3203   NSRectFill (s);
3205   s.size.height = r.size.height;
3206   s.origin.y = r.origin.y;
3208   /* left, right (optional) */
3209   s.size.width = thickness;
3210   if (left_p)
3211     NSRectFill (s);
3212   if (right_p)
3213     {
3214       s.origin.x += r.size.width - thickness;
3215       NSRectFill (s);
3216     }
3220 static void
3221 ns_draw_relief (NSRect r, int thickness, char raised_p,
3222                char top_p, char bottom_p, char left_p, char right_p,
3223                struct glyph_string *s)
3224 /* --------------------------------------------------------------------------
3225     Draw a relief rect inside r, optionally leaving some sides open.
3226     Note we can't just use an NSDrawBezel command, because of the possibility
3227     of some sides not being drawn, and because the rect will be filled.
3228    -------------------------------------------------------------------------- */
3230   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3231   NSColor *newBaseCol = nil;
3232   NSRect sr = r;
3234   NSTRACE ("ns_draw_relief");
3236   /* set up colors */
3238   if (s->face->use_box_color_for_shadows_p)
3239     {
3240       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3241     }
3242 /*     else if (s->first_glyph->type == IMAGE_GLYPH
3243            && s->img->pixmap
3244            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3245        {
3246          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
3247        } */
3248   else
3249     {
3250       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3251     }
3253   if (newBaseCol == nil)
3254     newBaseCol = [NSColor grayColor];
3256   if (newBaseCol != baseCol)  /* TODO: better check */
3257     {
3258       [baseCol release];
3259       baseCol = [newBaseCol retain];
3260       [lightCol release];
3261       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3262       [darkCol release];
3263       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3264     }
3266   [(raised_p ? lightCol : darkCol) set];
3268   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3270   /* top */
3271   sr.size.height = thickness;
3272   if (top_p) NSRectFill (sr);
3274   /* left */
3275   sr.size.height = r.size.height;
3276   sr.size.width = thickness;
3277   if (left_p) NSRectFill (sr);
3279   [(raised_p ? darkCol : lightCol) set];
3281   /* bottom */
3282   sr.size.width = r.size.width;
3283   sr.size.height = thickness;
3284   sr.origin.y += r.size.height - thickness;
3285   if (bottom_p) NSRectFill (sr);
3287   /* right */
3288   sr.size.height = r.size.height;
3289   sr.origin.y = r.origin.y;
3290   sr.size.width = thickness;
3291   sr.origin.x += r.size.width - thickness;
3292   if (right_p) NSRectFill (sr);
3296 static void
3297 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3298 /* --------------------------------------------------------------------------
3299       Function modeled after x_draw_glyph_string_box ().
3300       Sets up parameters for drawing.
3301    -------------------------------------------------------------------------- */
3303   int right_x, last_x;
3304   char left_p, right_p;
3305   struct glyph *last_glyph;
3306   NSRect r;
3307   int thickness;
3308   struct face *face;
3310   if (s->hl == DRAW_MOUSE_FACE)
3311     {
3312       face = FACE_OPT_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3313       if (!face)
3314         face = FACE_OPT_FROM_ID (s->f, MOUSE_FACE_ID);
3315     }
3316   else
3317     face = s->face;
3319   thickness = face->box_line_width;
3321   NSTRACE ("ns_dumpglyphs_box_or_relief");
3323   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3324             ? WINDOW_RIGHT_EDGE_X (s->w)
3325             : window_box_right (s->w, s->area));
3326   last_glyph = (s->cmp || s->img
3327                 ? s->first_glyph : s->first_glyph + s->nchars-1);
3329   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3330               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3332   left_p = (s->first_glyph->left_box_line_p
3333             || (s->hl == DRAW_MOUSE_FACE
3334                 && (s->prev == NULL || s->prev->hl != s->hl)));
3335   right_p = (last_glyph->right_box_line_p
3336              || (s->hl == DRAW_MOUSE_FACE
3337                  && (s->next == NULL || s->next->hl != s->hl)));
3339   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3341   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3342   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3343     {
3344       ns_draw_box (r, abs (thickness),
3345                    ns_lookup_indexed_color (face->box_color, s->f),
3346                   left_p, right_p);
3347     }
3348   else
3349     {
3350       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3351                      1, 1, left_p, right_p, s);
3352     }
3356 static void
3357 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3358 /* --------------------------------------------------------------------------
3359       Modeled after x_draw_glyph_string_background, which draws BG in
3360       certain cases.  Others are left to the text rendering routine.
3361    -------------------------------------------------------------------------- */
3363   NSTRACE ("ns_maybe_dumpglyphs_background");
3365   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3366     {
3367       int box_line_width = max (s->face->box_line_width, 0);
3368       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3369           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3370              dimensions, since the actual glyphs might be much
3371              smaller.  So in that case we always clear the rectangle
3372              with background color.  */
3373           || FONT_TOO_HIGH (s->font)
3374           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3375         {
3376           struct face *face;
3377           if (s->hl == DRAW_MOUSE_FACE)
3378             {
3379               face
3380                 = FACE_OPT_FROM_ID (s->f,
3381                                     MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3382               if (!face)
3383                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3384             }
3385           else
3386             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3387           if (!face->stipple)
3388             [(NS_FACE_BACKGROUND (face) != 0
3389               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3390               : FRAME_BACKGROUND_COLOR (s->f)) set];
3391           else
3392             {
3393               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3394               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3395             }
3397           if (s->hl != DRAW_CURSOR)
3398             {
3399               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3400                                     s->background_width,
3401                                     s->height-2*box_line_width);
3402               NSRectFill (r);
3403             }
3405           s->background_filled_p = 1;
3406         }
3407     }
3411 static void
3412 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3413 /* --------------------------------------------------------------------------
3414       Renders an image and associated borders.
3415    -------------------------------------------------------------------------- */
3417   EmacsImage *img = s->img->pixmap;
3418   int box_line_vwidth = max (s->face->box_line_width, 0);
3419   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3420   int bg_x, bg_y, bg_height;
3421   int th;
3422   char raised_p;
3423   NSRect br;
3424   struct face *face;
3425   NSColor *tdCol;
3427   NSTRACE ("ns_dumpglyphs_image");
3429   if (s->face->box != FACE_NO_BOX
3430       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3431     x += abs (s->face->box_line_width);
3433   bg_x = x;
3434   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3435   bg_height = s->height;
3436   /* other terms have this, but was causing problems w/tabbar mode */
3437   /* - 2 * box_line_vwidth; */
3439   if (s->slice.x == 0) x += s->img->hmargin;
3440   if (s->slice.y == 0) y += s->img->vmargin;
3442   /* Draw BG: if we need larger area than image itself cleared, do that,
3443      otherwise, since we composite the image under NS (instead of mucking
3444      with its background color), we must clear just the image area. */
3445   if (s->hl == DRAW_MOUSE_FACE)
3446     {
3447       face = FACE_OPT_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3448       if (!face)
3449        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3450     }
3451   else
3452     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3454   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3456   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3457       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3458     {
3459       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3460       s->background_filled_p = 1;
3461     }
3462   else
3463     {
3464       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3465     }
3467   NSRectFill (br);
3469   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3470   if (img != nil)
3471     {
3472 #ifdef NS_IMPL_COCOA
3473       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3474       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3475                               s->slice.width, s->slice.height);
3476       [img drawInRect: dr
3477              fromRect: ir
3478              operation: NSCompositeSourceOver
3479               fraction: 1.0
3480            respectFlipped: YES
3481                 hints: nil];
3482 #else
3483       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3484                   operation: NSCompositeSourceOver];
3485 #endif
3486     }
3488   if (s->hl == DRAW_CURSOR)
3489     {
3490     [FRAME_CURSOR_COLOR (s->f) set];
3491     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3492       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3493     else
3494       /* Currently on NS img->mask is always 0. Since
3495          get_window_cursor_type specifies a hollow box cursor when on
3496          a non-masked image we never reach this clause. But we put it
3497          in in anticipation of better support for image masks on
3498          NS. */
3499       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3500     }
3501   else
3502     {
3503       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3504     }
3506   /* Draw underline, overline, strike-through. */
3507   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3509   /* Draw relief, if requested */
3510   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3511     {
3512       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3513         {
3514           th = tool_bar_button_relief >= 0 ?
3515             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3516           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3517         }
3518       else
3519         {
3520           th = abs (s->img->relief);
3521           raised_p = (s->img->relief > 0);
3522         }
3524       r.origin.x = x - th;
3525       r.origin.y = y - th;
3526       r.size.width = s->slice.width + 2*th-1;
3527       r.size.height = s->slice.height + 2*th-1;
3528       ns_draw_relief (r, th, raised_p,
3529                       s->slice.y == 0,
3530                       s->slice.y + s->slice.height == s->img->height,
3531                       s->slice.x == 0,
3532                       s->slice.x + s->slice.width == s->img->width, s);
3533     }
3535   /* If there is no mask, the background won't be seen,
3536      so draw a rectangle on the image for the cursor.
3537      Do this for all images, getting transparency right is not reliable.  */
3538   if (s->hl == DRAW_CURSOR)
3539     {
3540       int thickness = abs (s->img->relief);
3541       if (thickness == 0) thickness = 1;
3542       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3543     }
3547 static void
3548 ns_dumpglyphs_stretch (struct glyph_string *s)
3550   NSRect r[2];
3551   int n, i;
3552   struct face *face;
3553   NSColor *fgCol, *bgCol;
3555   if (!s->background_filled_p)
3556     {
3557       n = ns_get_glyph_string_clip_rect (s, r);
3558       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3560       ns_focus (s->f, r, n);
3562       if (s->hl == DRAW_MOUSE_FACE)
3563        {
3564          face = FACE_OPT_FROM_ID (s->f,
3565                                   MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3566          if (!face)
3567            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3568        }
3569       else
3570        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3572       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3573       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3575       for (i = 0; i < n; ++i)
3576         {
3577           if (!s->row->full_width_p)
3578             {
3579               int overrun, leftoverrun;
3581               /* truncate to avoid overwriting fringe and/or scrollbar */
3582               overrun = max (0, (s->x + s->background_width)
3583                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3584                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3585               r[i].size.width -= overrun;
3587               /* truncate to avoid overwriting to left of the window box */
3588               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3589                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3591               if (leftoverrun > 0)
3592                 {
3593                   r[i].origin.x += leftoverrun;
3594                   r[i].size.width -= leftoverrun;
3595                 }
3597               /* XXX: Try to work between problem where a stretch glyph on
3598                  a partially-visible bottom row will clear part of the
3599                  modeline, and another where list-buffers headers and similar
3600                  rows erroneously have visible_height set to 0.  Not sure
3601                  where this is coming from as other terms seem not to show. */
3602               r[i].size.height = min (s->height, s->row->visible_height);
3603             }
3605           [bgCol set];
3607           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3608              overwriting cursor (usually when cursor on a tab) */
3609           if (s->hl == DRAW_CURSOR)
3610             {
3611               CGFloat x, width;
3613               x = r[i].origin.x;
3614               width = s->w->phys_cursor_width;
3615               r[i].size.width -= width;
3616               r[i].origin.x += width;
3618               NSRectFill (r[i]);
3620               /* Draw overlining, etc. on the cursor. */
3621               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3622                 ns_draw_text_decoration (s, face, bgCol, width, x);
3623               else
3624                 ns_draw_text_decoration (s, face, fgCol, width, x);
3625             }
3626           else
3627             {
3628               NSRectFill (r[i]);
3629             }
3631           /* Draw overlining, etc. on the stretch glyph (or the part
3632              of the stretch glyph after the cursor). */
3633           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3634                                    r[i].origin.x);
3635         }
3636       ns_unfocus (s->f);
3637       s->background_filled_p = 1;
3638     }
3642 static void
3643 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3645   int i, j, x;
3646   struct font *font = s->font;
3648   /* If first glyph of S has a left box line, start drawing the text
3649      of S to the right of that box line.  */
3650   if (s->face && s->face->box != FACE_NO_BOX
3651       && s->first_glyph->left_box_line_p)
3652     x = s->x + eabs (s->face->box_line_width);
3653   else
3654     x = s->x;
3656   /* S is a glyph string for a composition.  S->cmp_from is the index
3657      of the first character drawn for glyphs of this composition.
3658      S->cmp_from == 0 means we are drawing the very first character of
3659      this composition.  */
3661   /* Draw a rectangle for the composition if the font for the very
3662      first character of the composition could not be loaded.  */
3663   if (s->font_not_found_p)
3664     {
3665       if (s->cmp_from == 0)
3666         {
3667           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3668           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3669         }
3670     }
3671   else if (! s->first_glyph->u.cmp.automatic)
3672     {
3673       int y = s->ybase;
3675       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3676         /* TAB in a composition means display glyphs with padding
3677            space on the left or right.  */
3678         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3679           {
3680             int xx = x + s->cmp->offsets[j * 2];
3681             int yy = y - s->cmp->offsets[j * 2 + 1];
3683             font->driver->draw (s, j, j + 1, xx, yy, false);
3684             if (s->face->overstrike)
3685               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3686           }
3687     }
3688   else
3689     {
3690       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3691       Lisp_Object glyph;
3692       int y = s->ybase;
3693       int width = 0;
3695       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3696         {
3697           glyph = LGSTRING_GLYPH (gstring, i);
3698           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3699             width += LGLYPH_WIDTH (glyph);
3700           else
3701             {
3702               int xoff, yoff, wadjust;
3704               if (j < i)
3705                 {
3706                   font->driver->draw (s, j, i, x, y, false);
3707                   if (s->face->overstrike)
3708                     font->driver->draw (s, j, i, x + 1, y, false);
3709                   x += width;
3710                 }
3711               xoff = LGLYPH_XOFF (glyph);
3712               yoff = LGLYPH_YOFF (glyph);
3713               wadjust = LGLYPH_WADJUST (glyph);
3714               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3715               if (s->face->overstrike)
3716                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3717                                     false);
3718               x += wadjust;
3719               j = i + 1;
3720               width = 0;
3721             }
3722         }
3723       if (j < i)
3724         {
3725           font->driver->draw (s, j, i, x, y, false);
3726           if (s->face->overstrike)
3727             font->driver->draw (s, j, i, x + 1, y, false);
3728         }
3729     }
3732 static void
3733 ns_draw_glyph_string (struct glyph_string *s)
3734 /* --------------------------------------------------------------------------
3735       External (RIF): Main draw-text call.
3736    -------------------------------------------------------------------------- */
3738   /* TODO (optimize): focus for box and contents draw */
3739   NSRect r[2];
3740   int n, flags;
3741   char box_drawn_p = 0;
3742   struct font *font = s->face->font;
3743   if (! font) font = FRAME_FONT (s->f);
3745   NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3747   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3748     {
3749       int width;
3750       struct glyph_string *next;
3752       for (width = 0, next = s->next;
3753            next && width < s->right_overhang;
3754            width += next->width, next = next->next)
3755         if (next->first_glyph->type != IMAGE_GLYPH)
3756           {
3757             if (next->first_glyph->type != STRETCH_GLYPH)
3758               {
3759                 n = ns_get_glyph_string_clip_rect (s->next, r);
3760                 ns_focus (s->f, r, n);
3761                 ns_maybe_dumpglyphs_background (s->next, 1);
3762                 ns_unfocus (s->f);
3763               }
3764             else
3765               {
3766                 ns_dumpglyphs_stretch (s->next);
3767               }
3768             next->num_clips = 0;
3769           }
3770     }
3772   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3773         && (s->first_glyph->type == CHAR_GLYPH
3774             || s->first_glyph->type == COMPOSITE_GLYPH))
3775     {
3776       n = ns_get_glyph_string_clip_rect (s, r);
3777       ns_focus (s->f, r, n);
3778       ns_maybe_dumpglyphs_background (s, 1);
3779       ns_dumpglyphs_box_or_relief (s);
3780       ns_unfocus (s->f);
3781       box_drawn_p = 1;
3782     }
3784   switch (s->first_glyph->type)
3785     {
3787     case IMAGE_GLYPH:
3788       n = ns_get_glyph_string_clip_rect (s, r);
3789       ns_focus (s->f, r, n);
3790       ns_dumpglyphs_image (s, r[0]);
3791       ns_unfocus (s->f);
3792       break;
3794     case STRETCH_GLYPH:
3795       ns_dumpglyphs_stretch (s);
3796       break;
3798     case CHAR_GLYPH:
3799     case COMPOSITE_GLYPH:
3800       n = ns_get_glyph_string_clip_rect (s, r);
3801       ns_focus (s->f, r, n);
3803       if (s->for_overlaps || (s->cmp_from > 0
3804                               && ! s->first_glyph->u.cmp.automatic))
3805         s->background_filled_p = 1;
3806       else
3807         ns_maybe_dumpglyphs_background
3808           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3810       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3811         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3812          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3813           NS_DUMPGLYPH_NORMAL));
3815       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3816         {
3817           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3818           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3819           NS_FACE_FOREGROUND (s->face) = tmp;
3820         }
3822       {
3823         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3825         if (isComposite)
3826           ns_draw_composite_glyph_string_foreground (s);
3827         else
3828           font->driver->draw
3829             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3830              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3831              || flags == NS_DUMPGLYPH_MOUSEFACE);
3832       }
3834       {
3835         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3836                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3837                                                    s->f)
3838                         : FRAME_FOREGROUND_COLOR (s->f));
3839         [col set];
3841         /* Draw underline, overline, strike-through. */
3842         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3843       }
3845       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3846         {
3847           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3848           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3849           NS_FACE_FOREGROUND (s->face) = tmp;
3850         }
3852       ns_unfocus (s->f);
3853       break;
3855     case GLYPHLESS_GLYPH:
3856       n = ns_get_glyph_string_clip_rect (s, r);
3857       ns_focus (s->f, r, n);
3859       if (s->for_overlaps || (s->cmp_from > 0
3860                               && ! s->first_glyph->u.cmp.automatic))
3861         s->background_filled_p = 1;
3862       else
3863         ns_maybe_dumpglyphs_background
3864           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3865       /* ... */
3866       /* Not yet implemented.  */
3867       /* ... */
3868       ns_unfocus (s->f);
3869       break;
3871     default:
3872       emacs_abort ();
3873     }
3875   /* Draw box if not done already. */
3876   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3877     {
3878       n = ns_get_glyph_string_clip_rect (s, r);
3879       ns_focus (s->f, r, n);
3880       ns_dumpglyphs_box_or_relief (s);
3881       ns_unfocus (s->f);
3882     }
3884   s->num_clips = 0;
3889 /* ==========================================================================
3891     Event loop
3893    ========================================================================== */
3896 static void
3897 ns_send_appdefined (int value)
3898 /* --------------------------------------------------------------------------
3899     Internal: post an appdefined event which EmacsApp-sendEvent will
3900               recognize and take as a command to halt the event loop.
3901    -------------------------------------------------------------------------- */
3903   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3905 #ifdef NS_IMPL_GNUSTEP
3906   // GNUstep needs postEvent to happen on the main thread.
3907   if (! [[NSThread currentThread] isMainThread])
3908     {
3909       EmacsApp *app = (EmacsApp *)NSApp;
3910       app->nextappdefined = value;
3911       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3912                             withObject:nil
3913                          waitUntilDone:YES];
3914       return;
3915     }
3916 #endif
3918   /* Only post this event if we haven't already posted one.  This will end
3919        the [NXApp run] main loop after having processed all events queued at
3920        this moment.  */
3922 #ifdef NS_IMPL_COCOA
3923   if (! send_appdefined)
3924     {
3925       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3926          in certain situations (rapid incoming events).
3927          So check if we have one, if not add one.  */
3928       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3929                                           untilDate:[NSDate distantPast]
3930                                              inMode:NSDefaultRunLoopMode
3931                                             dequeue:NO];
3932       if (! appev) send_appdefined = YES;
3933     }
3934 #endif
3936   if (send_appdefined)
3937     {
3938       NSEvent *nxev;
3940       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3941       send_appdefined = NO;
3943       /* Don't need wakeup timer any more */
3944       if (timed_entry)
3945         {
3946           [timed_entry invalidate];
3947           [timed_entry release];
3948           timed_entry = nil;
3949         }
3951       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3952                                 location: NSMakePoint (0, 0)
3953                            modifierFlags: 0
3954                                timestamp: 0
3955                             windowNumber: [[NSApp mainWindow] windowNumber]
3956                                  context: [NSApp context]
3957                                  subtype: 0
3958                                    data1: value
3959                                    data2: 0];
3961       /* Post an application defined event on the event queue.  When this is
3962          received the [NXApp run] will return, thus having processed all
3963          events which are currently queued.  */
3964       [NSApp postEvent: nxev atStart: NO];
3965     }
3968 #ifdef HAVE_NATIVE_FS
3969 static void
3970 check_native_fs ()
3972   Lisp_Object frame, tail;
3974   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3975     return;
3977   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3979   FOR_EACH_FRAME (tail, frame)
3980     {
3981       struct frame *f = XFRAME (frame);
3982       if (FRAME_NS_P (f))
3983         {
3984           EmacsView *view = FRAME_NS_VIEW (f);
3985           [view updateCollectionBehavior];
3986         }
3987     }
3989 #endif
3991 /* GNUstep does not have cancelTracking.  */
3992 #ifdef NS_IMPL_COCOA
3993 /* Check if menu open should be canceled or continued as normal.  */
3994 void
3995 ns_check_menu_open (NSMenu *menu)
3997   /* Click in menu bar? */
3998   NSArray *a = [[NSApp mainMenu] itemArray];
3999   int i;
4000   BOOL found = NO;
4002   if (menu == nil) // Menu tracking ended.
4003     {
4004       if (menu_will_open_state == MENU_OPENING)
4005         menu_will_open_state = MENU_NONE;
4006       return;
4007     }
4009   for (i = 0; ! found && i < [a count]; i++)
4010     found = menu == [[a objectAtIndex:i] submenu];
4011   if (found)
4012     {
4013       if (menu_will_open_state == MENU_NONE && emacs_event)
4014         {
4015           NSEvent *theEvent = [NSApp currentEvent];
4016           struct frame *emacsframe = SELECTED_FRAME ();
4018           [menu cancelTracking];
4019           menu_will_open_state = MENU_PENDING;
4020           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
4021           EV_TRAILER (theEvent);
4023           CGEventRef ourEvent = CGEventCreate (NULL);
4024           menu_mouse_point = CGEventGetLocation (ourEvent);
4025           CFRelease (ourEvent);
4026         }
4027       else if (menu_will_open_state == MENU_OPENING)
4028         {
4029           menu_will_open_state = MENU_NONE;
4030         }
4031     }
4034 /* Redo saved menu click if state is MENU_PENDING.  */
4035 void
4036 ns_check_pending_open_menu ()
4038   if (menu_will_open_state == MENU_PENDING)
4039     {
4040       CGEventSourceRef source
4041         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
4043       CGEventRef event = CGEventCreateMouseEvent (source,
4044                                                   kCGEventLeftMouseDown,
4045                                                   menu_mouse_point,
4046                                                   kCGMouseButtonLeft);
4047       CGEventSetType (event, kCGEventLeftMouseDown);
4048       CGEventPost (kCGHIDEventTap, event);
4049       CFRelease (event);
4050       CFRelease (source);
4052       menu_will_open_state = MENU_OPENING;
4053     }
4055 #endif /* NS_IMPL_COCOA */
4057 static void
4058 unwind_apploopnr (Lisp_Object not_used)
4060   --apploopnr;
4061   n_emacs_events_pending = 0;
4062   ns_finish_events ();
4063   q_event_ptr = NULL;
4066 static int
4067 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
4068 /* --------------------------------------------------------------------------
4069      External (hook): Post an event to ourself and keep reading events until
4070      we read it back again.  In effect process all events which were waiting.
4071      From 21+ we have to manage the event buffer ourselves.
4072    -------------------------------------------------------------------------- */
4074   struct input_event ev;
4075   int nevents;
4077   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
4079 #ifdef HAVE_NATIVE_FS
4080   check_native_fs ();
4081 #endif
4083   if ([NSApp modalWindow] != nil)
4084     return -1;
4086   if (hold_event_q.nr > 0)
4087     {
4088       int i;
4089       for (i = 0; i < hold_event_q.nr; ++i)
4090         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4091       hold_event_q.nr = 0;
4092       return i;
4093     }
4095   block_input ();
4096   n_emacs_events_pending = 0;
4097   ns_init_events (&ev);
4098   q_event_ptr = hold_quit;
4100   /* we manage autorelease pools by allocate/reallocate each time around
4101      the loop; strict nesting is occasionally violated but seems not to
4102      matter.. earlier methods using full nesting caused major memory leaks */
4103   [outerpool release];
4104   outerpool = [[NSAutoreleasePool alloc] init];
4106   /* If have pending open-file requests, attend to the next one of those. */
4107   if (ns_pending_files && [ns_pending_files count] != 0
4108       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4109     {
4110       [ns_pending_files removeObjectAtIndex: 0];
4111     }
4112   /* Deal with pending service requests. */
4113   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4114     && [(EmacsApp *)
4115          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4116                       withArg: [ns_pending_service_args objectAtIndex: 0]])
4117     {
4118       [ns_pending_service_names removeObjectAtIndex: 0];
4119       [ns_pending_service_args removeObjectAtIndex: 0];
4120     }
4121   else
4122     {
4123       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4124       /* Run and wait for events.  We must always send one NX_APPDEFINED event
4125          to ourself, otherwise [NXApp run] will never exit.  */
4126       send_appdefined = YES;
4127       ns_send_appdefined (-1);
4129       if (++apploopnr != 1)
4130         {
4131           emacs_abort ();
4132         }
4133       record_unwind_protect (unwind_apploopnr, Qt);
4134       [NSApp run];
4135       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4136     }
4138   nevents = n_emacs_events_pending;
4139   n_emacs_events_pending = 0;
4140   ns_finish_events ();
4141   q_event_ptr = NULL;
4142   unblock_input ();
4144   return nevents;
4149 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4150            fd_set *exceptfds, struct timespec const *timeout,
4151            sigset_t const *sigmask)
4152 /* --------------------------------------------------------------------------
4153      Replacement for select, checking for events
4154    -------------------------------------------------------------------------- */
4156   int result;
4157   int t, k, nr = 0;
4158   struct input_event event;
4159   char c;
4161   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4163 #ifdef HAVE_NATIVE_FS
4164   check_native_fs ();
4165 #endif
4167   if (hold_event_q.nr > 0)
4168     {
4169       /* We already have events pending. */
4170       raise (SIGIO);
4171       errno = EINTR;
4172       return -1;
4173     }
4175   for (k = 0; k < nfds+1; k++)
4176     {
4177       if (readfds && FD_ISSET(k, readfds)) ++nr;
4178       if (writefds && FD_ISSET(k, writefds)) ++nr;
4179     }
4181   if (NSApp == nil
4182       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4183     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4185   [outerpool release];
4186   outerpool = [[NSAutoreleasePool alloc] init];
4189   send_appdefined = YES;
4190   if (nr > 0)
4191     {
4192       pthread_mutex_lock (&select_mutex);
4193       select_nfds = nfds;
4194       select_valid = 0;
4195       if (readfds)
4196         {
4197           select_readfds = *readfds;
4198           select_valid += SELECT_HAVE_READ;
4199         }
4200       if (writefds)
4201         {
4202           select_writefds = *writefds;
4203           select_valid += SELECT_HAVE_WRITE;
4204         }
4206       if (timeout)
4207         {
4208           select_timeout = *timeout;
4209           select_valid += SELECT_HAVE_TMO;
4210         }
4212       pthread_mutex_unlock (&select_mutex);
4214       /* Inform fd_handler that select should be called */
4215       c = 'g';
4216       emacs_write_sig (selfds[1], &c, 1);
4217     }
4218   else if (nr == 0 && timeout)
4219     {
4220       /* No file descriptor, just a timeout, no need to wake fd_handler  */
4221       double time = timespectod (*timeout);
4222       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4223                                                       target: NSApp
4224                                                     selector:
4225                                   @selector (timeout_handler:)
4226                                                     userInfo: 0
4227                                                      repeats: NO]
4228                       retain];
4229     }
4230   else /* No timeout and no file descriptors, can this happen?  */
4231     {
4232       /* Send appdefined so we exit from the loop */
4233       ns_send_appdefined (-1);
4234     }
4236   block_input ();
4237   ns_init_events (&event);
4238   if (++apploopnr != 1)
4239     {
4240       emacs_abort ();
4241     }
4243   {
4244     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4245     record_unwind_protect (unwind_apploopnr, Qt);
4246     [NSApp run];
4247     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4248   }
4250   ns_finish_events ();
4251   if (nr > 0 && readfds)
4252     {
4253       c = 's';
4254       emacs_write_sig (selfds[1], &c, 1);
4255     }
4256   unblock_input ();
4258   t = last_appdefined_event_data;
4260   if (t != NO_APPDEFINED_DATA)
4261     {
4262       last_appdefined_event_data = NO_APPDEFINED_DATA;
4264       if (t == -2)
4265         {
4266           /* The NX_APPDEFINED event we received was a timeout. */
4267           result = 0;
4268         }
4269       else if (t == -1)
4270         {
4271           /* The NX_APPDEFINED event we received was the result of
4272              at least one real input event arriving.  */
4273           errno = EINTR;
4274           result = -1;
4275         }
4276       else
4277         {
4278           /* Received back from select () in fd_handler; copy the results */
4279           pthread_mutex_lock (&select_mutex);
4280           if (readfds) *readfds = select_readfds;
4281           if (writefds) *writefds = select_writefds;
4282           pthread_mutex_unlock (&select_mutex);
4283           result = t;
4284         }
4285     }
4286   else
4287     {
4288       errno = EINTR;
4289       result = -1;
4290     }
4292   return result;
4297 /* ==========================================================================
4299     Scrollbar handling
4301    ========================================================================== */
4304 static void
4305 ns_set_vertical_scroll_bar (struct window *window,
4306                            int portion, int whole, int position)
4307 /* --------------------------------------------------------------------------
4308       External (hook): Update or add scrollbar
4309    -------------------------------------------------------------------------- */
4311   Lisp_Object win;
4312   NSRect r, v;
4313   struct frame *f = XFRAME (WINDOW_FRAME (window));
4314   EmacsView *view = FRAME_NS_VIEW (f);
4315   EmacsScroller *bar;
4316   int window_y, window_height;
4317   int top, left, height, width;
4318   BOOL update_p = YES;
4320   /* optimization; display engine sends WAY too many of these.. */
4321   if (!NILP (window->vertical_scroll_bar))
4322     {
4323       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4324       if ([bar checkSamePosition: position portion: portion whole: whole])
4325         {
4326           if (view->scrollbarsNeedingUpdate == 0)
4327             {
4328               if (!windows_or_buffers_changed)
4329                   return;
4330             }
4331           else
4332             view->scrollbarsNeedingUpdate--;
4333           update_p = NO;
4334         }
4335     }
4337   NSTRACE ("ns_set_vertical_scroll_bar");
4339   /* Get dimensions.  */
4340   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4341   top = window_y;
4342   height = window_height;
4343   width = NS_SCROLL_BAR_WIDTH (f);
4344   left = WINDOW_SCROLL_BAR_AREA_X (window);
4346   r = NSMakeRect (left, top, width, height);
4347   /* the parent view is flipped, so we need to flip y value */
4348   v = [view frame];
4349   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4351   XSETWINDOW (win, window);
4352   block_input ();
4354   /* we want at least 5 lines to display a scrollbar */
4355   if (WINDOW_TOTAL_LINES (window) < 5)
4356     {
4357       if (!NILP (window->vertical_scroll_bar))
4358         {
4359           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4360           [bar removeFromSuperview];
4361           wset_vertical_scroll_bar (window, Qnil);
4362           [bar release];
4363         }
4364       ns_clear_frame_area (f, left, top, width, height);
4365       unblock_input ();
4366       return;
4367     }
4369   if (NILP (window->vertical_scroll_bar))
4370     {
4371       if (width > 0 && height > 0)
4372         ns_clear_frame_area (f, left, top, width, height);
4374       bar = [[EmacsScroller alloc] initFrame: r window: win];
4375       wset_vertical_scroll_bar (window, make_save_ptr (bar));
4376       update_p = YES;
4377     }
4378   else
4379     {
4380       NSRect oldRect;
4381       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4382       oldRect = [bar frame];
4383       r.size.width = oldRect.size.width;
4384       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4385         {
4386           if (oldRect.origin.x != r.origin.x)
4387               ns_clear_frame_area (f, left, top, width, height);
4388           [bar setFrame: r];
4389         }
4390     }
4392   if (update_p)
4393     [bar setPosition: position portion: portion whole: whole];
4394   unblock_input ();
4398 static void
4399 ns_set_horizontal_scroll_bar (struct window *window,
4400                               int portion, int whole, int position)
4401 /* --------------------------------------------------------------------------
4402       External (hook): Update or add scrollbar
4403    -------------------------------------------------------------------------- */
4405   Lisp_Object win;
4406   NSRect r, v;
4407   struct frame *f = XFRAME (WINDOW_FRAME (window));
4408   EmacsView *view = FRAME_NS_VIEW (f);
4409   EmacsScroller *bar;
4410   int top, height, left, width;
4411   int window_x, window_width;
4412   BOOL update_p = YES;
4414   /* optimization; display engine sends WAY too many of these.. */
4415   if (!NILP (window->horizontal_scroll_bar))
4416     {
4417       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4418       if ([bar checkSamePosition: position portion: portion whole: whole])
4419         {
4420           if (view->scrollbarsNeedingUpdate == 0)
4421             {
4422               if (!windows_or_buffers_changed)
4423                   return;
4424             }
4425           else
4426             view->scrollbarsNeedingUpdate--;
4427           update_p = NO;
4428         }
4429     }
4431   NSTRACE ("ns_set_horizontal_scroll_bar");
4433   /* Get dimensions.  */
4434   window_box (window, ANY_AREA, &window_x, 0, &window_width, 0);
4435   left = window_x;
4436   width = window_width;
4437   height = NS_SCROLL_BAR_HEIGHT (f);
4438   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4440   r = NSMakeRect (left, top, width, height);
4441   /* the parent view is flipped, so we need to flip y value */
4442   v = [view frame];
4443   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4445   XSETWINDOW (win, window);
4446   block_input ();
4448   if (NILP (window->horizontal_scroll_bar))
4449     {
4450       if (width > 0 && height > 0)
4451         ns_clear_frame_area (f, left, top, width, height);
4453       bar = [[EmacsScroller alloc] initFrame: r window: win];
4454       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4455       update_p = YES;
4456     }
4457   else
4458     {
4459       NSRect oldRect;
4460       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4461       oldRect = [bar frame];
4462       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4463         {
4464           if (oldRect.origin.y != r.origin.y)
4465             ns_clear_frame_area (f, left, top, width, height);
4466           [bar setFrame: r];
4467           update_p = YES;
4468         }
4469     }
4471   /* If there are both horizontal and vertical scroll-bars they leave
4472      a square that belongs to neither. We need to clear it otherwise
4473      it fills with junk. */
4474   if (!NILP (window->vertical_scroll_bar))
4475     ns_clear_frame_area (f, WINDOW_SCROLL_BAR_AREA_X (window), top,
4476                          NS_SCROLL_BAR_HEIGHT (f), height);
4478   if (update_p)
4479     [bar setPosition: position portion: portion whole: whole];
4480   unblock_input ();
4484 static void
4485 ns_condemn_scroll_bars (struct frame *f)
4486 /* --------------------------------------------------------------------------
4487      External (hook): arrange for all frame's scrollbars to be removed
4488      at next call to judge_scroll_bars, except for those redeemed.
4489    -------------------------------------------------------------------------- */
4491   int i;
4492   id view;
4493   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4495   NSTRACE ("ns_condemn_scroll_bars");
4497   for (i =[subviews count]-1; i >= 0; i--)
4498     {
4499       view = [subviews objectAtIndex: i];
4500       if ([view isKindOfClass: [EmacsScroller class]])
4501         [view condemn];
4502     }
4506 static void
4507 ns_redeem_scroll_bar (struct window *window)
4508 /* --------------------------------------------------------------------------
4509      External (hook): arrange to spare this window's scrollbar
4510      at next call to judge_scroll_bars.
4511    -------------------------------------------------------------------------- */
4513   id bar;
4514   NSTRACE ("ns_redeem_scroll_bar");
4515   if (!NILP (window->vertical_scroll_bar)
4516       && WINDOW_HAS_VERTICAL_SCROLL_BAR (window))
4517     {
4518       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4519       [bar reprieve];
4520     }
4522   if (!NILP (window->horizontal_scroll_bar)
4523       && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (window))
4524     {
4525       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4526       [bar reprieve];
4527     }
4531 static void
4532 ns_judge_scroll_bars (struct frame *f)
4533 /* --------------------------------------------------------------------------
4534      External (hook): destroy all scrollbars on frame that weren't
4535      redeemed after call to condemn_scroll_bars.
4536    -------------------------------------------------------------------------- */
4538   int i;
4539   id view;
4540   EmacsView *eview = FRAME_NS_VIEW (f);
4541   NSArray *subviews = [[eview superview] subviews];
4542   BOOL removed = NO;
4544   NSTRACE ("ns_judge_scroll_bars");
4545   for (i = [subviews count]-1; i >= 0; --i)
4546     {
4547       view = [subviews objectAtIndex: i];
4548       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4549       if ([view judge])
4550         removed = YES;
4551     }
4553   if (removed)
4554     [eview updateFrameSize: NO];
4557 /* ==========================================================================
4559     Initialization
4561    ========================================================================== */
4564 x_display_pixel_height (struct ns_display_info *dpyinfo)
4566   NSArray *screens = [NSScreen screens];
4567   NSEnumerator *enumerator = [screens objectEnumerator];
4568   NSScreen *screen;
4569   NSRect frame;
4571   frame = NSZeroRect;
4572   while ((screen = [enumerator nextObject]) != nil)
4573     frame = NSUnionRect (frame, [screen frame]);
4575   return NSHeight (frame);
4579 x_display_pixel_width (struct ns_display_info *dpyinfo)
4581   NSArray *screens = [NSScreen screens];
4582   NSEnumerator *enumerator = [screens objectEnumerator];
4583   NSScreen *screen;
4584   NSRect frame;
4586   frame = NSZeroRect;
4587   while ((screen = [enumerator nextObject]) != nil)
4588     frame = NSUnionRect (frame, [screen frame]);
4590   return NSWidth (frame);
4594 static Lisp_Object ns_string_to_lispmod (const char *s)
4595 /* --------------------------------------------------------------------------
4596      Convert modifier name to lisp symbol
4597    -------------------------------------------------------------------------- */
4599   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4600     return Qmeta;
4601   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4602     return Qsuper;
4603   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4604     return Qcontrol;
4605   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4606     return Qalt;
4607   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4608     return Qhyper;
4609   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4610     return Qnone;
4611   else
4612     return Qnil;
4616 static void
4617 ns_default (const char *parameter, Lisp_Object *result,
4618            Lisp_Object yesval, Lisp_Object noval,
4619            BOOL is_float, BOOL is_modstring)
4620 /* --------------------------------------------------------------------------
4621       Check a parameter value in user's preferences
4622    -------------------------------------------------------------------------- */
4624   const char *value = ns_get_defaults_value (parameter);
4626   if (value)
4627     {
4628       double f;
4629       char *pos;
4630       if (c_strcasecmp (value, "YES") == 0)
4631         *result = yesval;
4632       else if (c_strcasecmp (value, "NO") == 0)
4633         *result = noval;
4634       else if (is_float && (f = strtod (value, &pos), pos != value))
4635         *result = make_float (f);
4636       else if (is_modstring && value)
4637         *result = ns_string_to_lispmod (value);
4638       else fprintf (stderr,
4639                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4640     }
4644 static void
4645 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4646 /* --------------------------------------------------------------------------
4647       Initialize global info and storage for display.
4648    -------------------------------------------------------------------------- */
4650     NSScreen *screen = [NSScreen mainScreen];
4651     NSWindowDepth depth = [screen depth];
4653     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4654     dpyinfo->resy = 72.27;
4655     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4656                                                   NSColorSpaceFromDepth (depth)]
4657                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4658                                                  NSColorSpaceFromDepth (depth)];
4659     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4660     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4661     dpyinfo->color_table->colors = NULL;
4662     dpyinfo->root_window = 42; /* a placeholder.. */
4663     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4664     dpyinfo->n_fonts = 0;
4665     dpyinfo->smallest_font_height = 1;
4666     dpyinfo->smallest_char_width = 1;
4668     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4672 /* This and next define (many of the) public functions in this file. */
4673 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4674          with using despite presence in the "system dependent" redisplay
4675          interface.  In addition, many of the ns_ methods have code that is
4676          shared with all terms, indicating need for further refactoring. */
4677 extern frame_parm_handler ns_frame_parm_handlers[];
4678 static struct redisplay_interface ns_redisplay_interface =
4680   ns_frame_parm_handlers,
4681   x_produce_glyphs,
4682   x_write_glyphs,
4683   x_insert_glyphs,
4684   x_clear_end_of_line,
4685   ns_scroll_run,
4686   ns_after_update_window_line,
4687   ns_update_window_begin,
4688   ns_update_window_end,
4689   0, /* flush_display */
4690   x_clear_window_mouse_face,
4691   x_get_glyph_overhangs,
4692   x_fix_overlapping_area,
4693   ns_draw_fringe_bitmap,
4694   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4695   0, /* destroy_fringe_bitmap */
4696   ns_compute_glyph_string_overhangs,
4697   ns_draw_glyph_string,
4698   ns_define_frame_cursor,
4699   ns_clear_frame_area,
4700   ns_draw_window_cursor,
4701   ns_draw_vertical_window_border,
4702   ns_draw_window_divider,
4703   ns_shift_glyphs_for_insert,
4704   ns_show_hourglass,
4705   ns_hide_hourglass
4709 static void
4710 ns_delete_display (struct ns_display_info *dpyinfo)
4712   /* TODO... */
4716 /* This function is called when the last frame on a display is deleted. */
4717 static void
4718 ns_delete_terminal (struct terminal *terminal)
4720   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4722   NSTRACE ("ns_delete_terminal");
4724   /* Protect against recursive calls.  delete_frame in
4725      delete_terminal calls us back when it deletes our last frame.  */
4726   if (!terminal->name)
4727     return;
4729   block_input ();
4731   x_destroy_all_bitmaps (dpyinfo);
4732   ns_delete_display (dpyinfo);
4733   unblock_input ();
4737 static struct terminal *
4738 ns_create_terminal (struct ns_display_info *dpyinfo)
4739 /* --------------------------------------------------------------------------
4740       Set up use of NS before we make the first connection.
4741    -------------------------------------------------------------------------- */
4743   struct terminal *terminal;
4745   NSTRACE ("ns_create_terminal");
4747   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4749   terminal->display_info.ns = dpyinfo;
4750   dpyinfo->terminal = terminal;
4752   terminal->clear_frame_hook = ns_clear_frame;
4753   terminal->ring_bell_hook = ns_ring_bell;
4754   terminal->update_begin_hook = ns_update_begin;
4755   terminal->update_end_hook = ns_update_end;
4756   terminal->read_socket_hook = ns_read_socket;
4757   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4758   terminal->mouse_position_hook = ns_mouse_position;
4759   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4760   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4761   terminal->fullscreen_hook = ns_fullscreen_hook;
4762   terminal->menu_show_hook = ns_menu_show;
4763   terminal->popup_dialog_hook = ns_popup_dialog;
4764   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4765   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4766   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4767   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4768   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4769   terminal->delete_frame_hook = x_destroy_window;
4770   terminal->delete_terminal_hook = ns_delete_terminal;
4771   /* Other hooks are NULL by default.  */
4773   return terminal;
4777 struct ns_display_info *
4778 ns_term_init (Lisp_Object display_name)
4779 /* --------------------------------------------------------------------------
4780      Start the Application and get things rolling.
4781    -------------------------------------------------------------------------- */
4783   struct terminal *terminal;
4784   struct ns_display_info *dpyinfo;
4785   static int ns_initialized = 0;
4786   Lisp_Object tmp;
4788   if (ns_initialized) return x_display_list;
4789   ns_initialized = 1;
4791   block_input ();
4793   NSTRACE ("ns_term_init");
4795   [outerpool release];
4796   outerpool = [[NSAutoreleasePool alloc] init];
4798   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4799   /*GSDebugAllocationActive (YES); */
4800   block_input ();
4802   baud_rate = 38400;
4803   Fset_input_interrupt_mode (Qnil);
4805   if (selfds[0] == -1)
4806     {
4807       if (emacs_pipe (selfds) != 0)
4808         {
4809           fprintf (stderr, "Failed to create pipe: %s\n",
4810                    emacs_strerror (errno));
4811           emacs_abort ();
4812         }
4814       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4815       FD_ZERO (&select_readfds);
4816       FD_ZERO (&select_writefds);
4817       pthread_mutex_init (&select_mutex, NULL);
4818     }
4820   ns_pending_files = [[NSMutableArray alloc] init];
4821   ns_pending_service_names = [[NSMutableArray alloc] init];
4822   ns_pending_service_args = [[NSMutableArray alloc] init];
4824 /* Start app and create the main menu, window, view.
4825      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4826      The view will then ask the NSApp to stop and return to Emacs. */
4827   [EmacsApp sharedApplication];
4828   if (NSApp == nil)
4829     return NULL;
4830   [NSApp setDelegate: NSApp];
4832   /* Start the select thread.  */
4833   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4834                            toTarget:NSApp
4835                          withObject:nil];
4837   /* debugging: log all notifications */
4838   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4839                                          selector: @selector (logNotification:)
4840                                              name: nil object: nil]; */
4842   dpyinfo = xzalloc (sizeof *dpyinfo);
4844   ns_initialize_display_info (dpyinfo);
4845   terminal = ns_create_terminal (dpyinfo);
4847   terminal->kboard = allocate_kboard (Qns);
4848   /* Don't let the initial kboard remain current longer than necessary.
4849      That would cause problems if a file loaded on startup tries to
4850      prompt in the mini-buffer.  */
4851   if (current_kboard == initial_kboard)
4852     current_kboard = terminal->kboard;
4853   terminal->kboard->reference_count++;
4855   dpyinfo->next = x_display_list;
4856   x_display_list = dpyinfo;
4858   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4860   terminal->name = xlispstrdup (display_name);
4862   unblock_input ();
4864   if (!inhibit_x_resources)
4865     {
4866       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4867                  Qt, Qnil, NO, NO);
4868       tmp = Qnil;
4869       /* this is a standard variable */
4870       ns_default ("AppleAntiAliasingThreshold", &tmp,
4871                  make_float (10.0), make_float (6.0), YES, NO);
4872       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4873     }
4875   NSTRACE_MSG ("Colors");
4877   {
4878     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4880     if ( cl == nil )
4881       {
4882         Lisp_Object color_file, color_map, color;
4883         unsigned long c;
4884         char *name;
4886         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4887                          Fsymbol_value (intern ("data-directory")));
4889         color_map = Fx_load_color_file (color_file);
4890         if (NILP (color_map))
4891           fatal ("Could not read %s.\n", SDATA (color_file));
4893         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4894         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4895           {
4896             color = XCAR (color_map);
4897             name = SSDATA (XCAR (color));
4898             c = XINT (XCDR (color));
4899             [cl setColor:
4900                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4901                                       green: GREEN_FROM_ULONG (c) / 255.0
4902                                        blue: BLUE_FROM_ULONG (c) / 255.0
4903                                       alpha: 1.0]
4904                   forKey: [NSString stringWithUTF8String: name]];
4905           }
4906         [cl writeToFile: nil];
4907       }
4908   }
4910   NSTRACE_MSG ("Versions");
4912   {
4913 #ifdef NS_IMPL_GNUSTEP
4914     Vwindow_system_version = build_string (gnustep_base_version);
4915 #else
4916     /*PSnextrelease (128, c); */
4917     char c[DBL_BUFSIZE_BOUND];
4918     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4919     Vwindow_system_version = make_unibyte_string (c, len);
4920 #endif
4921   }
4923   delete_keyboard_wait_descriptor (0);
4925   ns_app_name = [[NSProcessInfo processInfo] processName];
4927   /* Set up OS X app menu */
4929   NSTRACE_MSG ("Menu init");
4931 #ifdef NS_IMPL_COCOA
4932   {
4933     NSMenu *appMenu;
4934     NSMenuItem *item;
4935     /* set up the application menu */
4936     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4937     [svcsMenu setAutoenablesItems: NO];
4938     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4939     [appMenu setAutoenablesItems: NO];
4940     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4941     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4943     [appMenu insertItemWithTitle: @"About Emacs"
4944                           action: @selector (orderFrontStandardAboutPanel:)
4945                    keyEquivalent: @""
4946                          atIndex: 0];
4947     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4948     [appMenu insertItemWithTitle: @"Preferences..."
4949                           action: @selector (showPreferencesWindow:)
4950                    keyEquivalent: @","
4951                          atIndex: 2];
4952     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4953     item = [appMenu insertItemWithTitle: @"Services"
4954                                  action: @selector (menuDown:)
4955                           keyEquivalent: @""
4956                                 atIndex: 4];
4957     [appMenu setSubmenu: svcsMenu forItem: item];
4958     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4959     [appMenu insertItemWithTitle: @"Hide Emacs"
4960                           action: @selector (hide:)
4961                    keyEquivalent: @"h"
4962                          atIndex: 6];
4963     item =  [appMenu insertItemWithTitle: @"Hide Others"
4964                           action: @selector (hideOtherApplications:)
4965                    keyEquivalent: @"h"
4966                          atIndex: 7];
4967     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4968     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4969     [appMenu insertItemWithTitle: @"Quit Emacs"
4970                           action: @selector (terminate:)
4971                    keyEquivalent: @"q"
4972                          atIndex: 9];
4974     item = [mainMenu insertItemWithTitle: ns_app_name
4975                                   action: @selector (menuDown:)
4976                            keyEquivalent: @""
4977                                  atIndex: 0];
4978     [mainMenu setSubmenu: appMenu forItem: item];
4979     [dockMenu insertItemWithTitle: @"New Frame"
4980                            action: @selector (newFrame:)
4981                     keyEquivalent: @""
4982                           atIndex: 0];
4984     [NSApp setMainMenu: mainMenu];
4985     [NSApp setAppleMenu: appMenu];
4986     [NSApp setServicesMenu: svcsMenu];
4987     /* Needed at least on Cocoa, to get dock menu to show windows */
4988     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4990     [[NSNotificationCenter defaultCenter]
4991       addObserver: mainMenu
4992          selector: @selector (trackingNotification:)
4993              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4994     [[NSNotificationCenter defaultCenter]
4995       addObserver: mainMenu
4996          selector: @selector (trackingNotification:)
4997              name: NSMenuDidEndTrackingNotification object: mainMenu];
4998   }
4999 #endif /* MAC OS X menu setup */
5001   /* Register our external input/output types, used for determining
5002      applicable services and also drag/drop eligibility. */
5004   NSTRACE_MSG ("Input/output types");
5006   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
5007   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
5008                       retain];
5009   ns_drag_types = [[NSArray arrayWithObjects:
5010                             NSStringPboardType,
5011                             NSTabularTextPboardType,
5012                             NSFilenamesPboardType,
5013                             NSURLPboardType, nil] retain];
5015   /* If fullscreen is in init/default-frame-alist, focus isn't set
5016      right for fullscreen windows, so set this.  */
5017   [NSApp activateIgnoringOtherApps:YES];
5019   NSTRACE_MSG ("Call NSApp run");
5021   [NSApp run];
5022   ns_do_open_file = YES;
5024 #ifdef NS_IMPL_GNUSTEP
5025   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
5026      We must re-catch it so subprocess works.  */
5027   catch_child_signal ();
5028 #endif
5030   NSTRACE_MSG ("ns_term_init done");
5032   unblock_input ();
5034   return dpyinfo;
5038 void
5039 ns_term_shutdown (int sig)
5041   [[NSUserDefaults standardUserDefaults] synchronize];
5043   /* code not reached in emacs.c after this is called by shut_down_emacs: */
5044   if (STRINGP (Vauto_save_list_file_name))
5045     unlink (SSDATA (Vauto_save_list_file_name));
5047   if (sig == 0 || sig == SIGTERM)
5048     {
5049       [NSApp terminate: NSApp];
5050     }
5051   else // force a stack trace to happen
5052     {
5053       emacs_abort ();
5054     }
5058 /* ==========================================================================
5060     EmacsApp implementation
5062    ========================================================================== */
5065 @implementation EmacsApp
5067 - (id)init
5069   NSTRACE ("[EmacsApp init]");
5071   if ((self = [super init]))
5072     {
5073 #ifdef NS_IMPL_COCOA
5074       self->isFirst = YES;
5075 #endif
5076 #ifdef NS_IMPL_GNUSTEP
5077       self->applicationDidFinishLaunchingCalled = NO;
5078 #endif
5079     }
5081   return self;
5084 #ifdef NS_IMPL_COCOA
5085 - (void)run
5087   NSTRACE ("[EmacsApp run]");
5089 #ifndef NSAppKitVersionNumber10_9
5090 #define NSAppKitVersionNumber10_9 1265
5091 #endif
5093     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5094       {
5095         [super run];
5096         return;
5097       }
5099   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5101   if (isFirst) [self finishLaunching];
5102   isFirst = NO;
5104   shouldKeepRunning = YES;
5105   do
5106     {
5107       [pool release];
5108       pool = [[NSAutoreleasePool alloc] init];
5110       NSEvent *event =
5111         [self nextEventMatchingMask:NSAnyEventMask
5112                           untilDate:[NSDate distantFuture]
5113                              inMode:NSDefaultRunLoopMode
5114                             dequeue:YES];
5116       [self sendEvent:event];
5117       [self updateWindows];
5118     } while (shouldKeepRunning);
5120   [pool release];
5123 - (void)stop: (id)sender
5125   NSTRACE ("[EmacsApp stop:]");
5127     shouldKeepRunning = NO;
5128     // Stop possible dialog also.  Noop if no dialog present.
5129     // The file dialog still leaks 7k - 10k on 10.9 though.
5130     [super stop:sender];
5132 #endif /* NS_IMPL_COCOA */
5134 - (void)logNotification: (NSNotification *)notification
5136   NSTRACE ("[EmacsApp logNotification:]");
5138   const char *name = [[notification name] UTF8String];
5139   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5140       && !strstr (name, "WindowNumber"))
5141     NSLog (@"notification: '%@'", [notification name]);
5145 - (void)sendEvent: (NSEvent *)theEvent
5146 /* --------------------------------------------------------------------------
5147      Called when NSApp is running for each event received.  Used to stop
5148      the loop when we choose, since there's no way to just run one iteration.
5149    -------------------------------------------------------------------------- */
5151   int type = [theEvent type];
5152   NSWindow *window = [theEvent window];
5154   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5155   NSTRACE_MSG ("Type: %d", type);
5157 #ifdef NS_IMPL_GNUSTEP
5158   // Keyboard events aren't propagated to file dialogs for some reason.
5159   if ([NSApp modalWindow] != nil &&
5160       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5161     {
5162       [[NSApp modalWindow] sendEvent: theEvent];
5163       return;
5164     }
5165 #endif
5167   if (represented_filename != nil && represented_frame)
5168     {
5169       NSString *fstr = represented_filename;
5170       NSView *view = FRAME_NS_VIEW (represented_frame);
5171 #ifdef NS_IMPL_COCOA
5172       /* work around a bug observed on 10.3 and later where
5173          setTitleWithRepresentedFilename does not clear out previous state
5174          if given filename does not exist */
5175       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5176         [[view window] setRepresentedFilename: @""];
5177 #endif
5178       [[view window] setRepresentedFilename: fstr];
5179       [represented_filename release];
5180       represented_filename = nil;
5181       represented_frame = NULL;
5182     }
5184   if (type == NSApplicationDefined)
5185     {
5186       switch ([theEvent data2])
5187         {
5188 #ifdef NS_IMPL_COCOA
5189         case NSAPP_DATA2_RUNASSCRIPT:
5190           ns_run_ascript ();
5191           [self stop: self];
5192           return;
5193 #endif
5194         case NSAPP_DATA2_RUNFILEDIALOG:
5195           ns_run_file_dialog ();
5196           [self stop: self];
5197           return;
5198         }
5199     }
5201   if (type == NSCursorUpdate && window == nil)
5202     {
5203       fprintf (stderr, "Dropping external cursor update event.\n");
5204       return;
5205     }
5207   if (type == NSApplicationDefined)
5208     {
5209       /* Events posted by ns_send_appdefined interrupt the run loop here.
5210          But, if a modal window is up, an appdefined can still come through,
5211          (e.g., from a makeKeyWindow event) but stopping self also stops the
5212          modal loop. Just defer it until later. */
5213       if ([NSApp modalWindow] == nil)
5214         {
5215           last_appdefined_event_data = [theEvent data1];
5216           [self stop: self];
5217         }
5218       else
5219         {
5220           send_appdefined = YES;
5221         }
5222     }
5225 #ifdef NS_IMPL_COCOA
5226   /* If no dialog and none of our frames have focus and it is a move, skip it.
5227      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5228      such as Wifi, sound, date or similar.
5229      This prevents "spooky" highlighting in the frame under the menu.  */
5230   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5231     {
5232       struct ns_display_info *di;
5233       BOOL has_focus = NO;
5234       for (di = x_display_list; ! has_focus && di; di = di->next)
5235         has_focus = di->x_focus_frame != 0;
5236       if (! has_focus)
5237         return;
5238     }
5239 #endif
5241   NSTRACE_UNSILENCE();
5243   [super sendEvent: theEvent];
5247 - (void)showPreferencesWindow: (id)sender
5249   struct frame *emacsframe = SELECTED_FRAME ();
5250   NSEvent *theEvent = [NSApp currentEvent];
5252   if (!emacs_event)
5253     return;
5254   emacs_event->kind = NS_NONKEY_EVENT;
5255   emacs_event->code = KEY_NS_SHOW_PREFS;
5256   emacs_event->modifiers = 0;
5257   EV_TRAILER (theEvent);
5261 - (void)newFrame: (id)sender
5263   NSTRACE ("[EmacsApp newFrame:]");
5265   struct frame *emacsframe = SELECTED_FRAME ();
5266   NSEvent *theEvent = [NSApp currentEvent];
5268   if (!emacs_event)
5269     return;
5270   emacs_event->kind = NS_NONKEY_EVENT;
5271   emacs_event->code = KEY_NS_NEW_FRAME;
5272   emacs_event->modifiers = 0;
5273   EV_TRAILER (theEvent);
5277 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5278 - (BOOL) openFile: (NSString *)fileName
5280   NSTRACE ("[EmacsApp openFile:]");
5282   struct frame *emacsframe = SELECTED_FRAME ();
5283   NSEvent *theEvent = [NSApp currentEvent];
5285   if (!emacs_event)
5286     return NO;
5288   emacs_event->kind = NS_NONKEY_EVENT;
5289   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5290   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5291   ns_input_line = Qnil; /* can be start or cons start,end */
5292   emacs_event->modifiers =0;
5293   EV_TRAILER (theEvent);
5295   return YES;
5299 /* **************************************************************************
5301       EmacsApp delegate implementation
5303    ************************************************************************** */
5305 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5306 /* --------------------------------------------------------------------------
5307      When application is loaded, terminate event loop in ns_term_init
5308    -------------------------------------------------------------------------- */
5310   NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5312 #ifdef NS_IMPL_GNUSTEP
5313   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5314 #endif
5315   [NSApp setServicesProvider: NSApp];
5317   [self antialiasThresholdDidChange:nil];
5318 #ifdef NS_IMPL_COCOA
5319   [[NSNotificationCenter defaultCenter]
5320     addObserver:self
5321        selector:@selector(antialiasThresholdDidChange:)
5322            name:NSAntialiasThresholdChangedNotification
5323          object:nil];
5324 #endif
5326   ns_send_appdefined (-2);
5329 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5331 #ifdef NS_IMPL_COCOA
5332   macfont_update_antialias_threshold ();
5333 #endif
5337 /* Termination sequences:
5338     C-x C-c:
5339     Cmd-Q:
5340     MenuBar | File | Exit:
5341     Select Quit from App menubar:
5342         -terminate
5343         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5344         ns_term_shutdown()
5346     Select Quit from Dock menu:
5347     Logout attempt:
5348         -appShouldTerminate
5349           Cancel -> Nothing else
5350           Accept ->
5352           -terminate
5353           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5354           ns_term_shutdown()
5358 - (void) terminate: (id)sender
5360   NSTRACE ("[EmacsApp terminate:]");
5362   struct frame *emacsframe = SELECTED_FRAME ();
5364   if (!emacs_event)
5365     return;
5367   emacs_event->kind = NS_NONKEY_EVENT;
5368   emacs_event->code = KEY_NS_POWER_OFF;
5369   emacs_event->arg = Qt; /* mark as non-key event */
5370   EV_TRAILER ((id)nil);
5373 static bool
5374 runAlertPanel(NSString *title,
5375               NSString *msgFormat,
5376               NSString *defaultButton,
5377               NSString *alternateButton)
5379 #if !defined (NS_IMPL_COCOA) || \
5380   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5381   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5382     == NSAlertDefaultReturn;
5383 #else
5384   NSAlert *alert = [[NSAlert alloc] init];
5385   [alert setAlertStyle: NSCriticalAlertStyle];
5386   [alert setMessageText: msgFormat];
5387   [alert addButtonWithTitle: defaultButton];
5388   [alert addButtonWithTitle: alternateButton];
5389   NSInteger ret = [alert runModal];
5390   [alert release];
5391   return ret == NSAlertFirstButtonReturn;
5392 #endif
5396 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5398   NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5400   bool ret;
5402   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
5403     return NSTerminateNow;
5405     ret = runAlertPanel(ns_app_name,
5406                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
5407                         @"Save Buffers and Exit", @"Cancel");
5409     if (ret)
5410         return NSTerminateNow;
5411     else
5412         return NSTerminateCancel;
5413     return NSTerminateNow;  /* just in case */
5416 static int
5417 not_in_argv (NSString *arg)
5419   int k;
5420   const char *a = [arg UTF8String];
5421   for (k = 1; k < initial_argc; ++k)
5422     if (strcmp (a, initial_argv[k]) == 0) return 0;
5423   return 1;
5426 /*   Notification from the Workspace to open a file */
5427 - (BOOL)application: sender openFile: (NSString *)file
5429   if (ns_do_open_file || not_in_argv (file))
5430     [ns_pending_files addObject: file];
5431   return YES;
5435 /*   Open a file as a temporary file */
5436 - (BOOL)application: sender openTempFile: (NSString *)file
5438   if (ns_do_open_file || not_in_argv (file))
5439     [ns_pending_files addObject: file];
5440   return YES;
5444 /*   Notification from the Workspace to open a file noninteractively (?) */
5445 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5447   if (ns_do_open_file || not_in_argv (file))
5448     [ns_pending_files addObject: file];
5449   return YES;
5452 /*   Notification from the Workspace to open multiple files */
5453 - (void)application: sender openFiles: (NSArray *)fileList
5455   NSEnumerator *files = [fileList objectEnumerator];
5456   NSString *file;
5457   /* Don't open files from the command line unconditionally,
5458      Cocoa parses the command line wrong, --option value tries to open value
5459      if --option is the last option.  */
5460   while ((file = [files nextObject]) != nil)
5461     if (ns_do_open_file || not_in_argv (file))
5462       [ns_pending_files addObject: file];
5464   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5469 /* Handle dock menu requests.  */
5470 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5472   return dockMenu;
5476 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5477 - (void)applicationWillBecomeActive: (NSNotification *)notification
5479   NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5480   //ns_app_active=YES;
5483 - (void)applicationDidBecomeActive: (NSNotification *)notification
5485   NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5487 #ifdef NS_IMPL_GNUSTEP
5488   if (! applicationDidFinishLaunchingCalled)
5489     [self applicationDidFinishLaunching:notification];
5490 #endif
5491   //ns_app_active=YES;
5493   ns_update_auto_hide_menu_bar ();
5494   // No constraining takes place when the application is not active.
5495   ns_constrain_all_frames ();
5497 - (void)applicationDidResignActive: (NSNotification *)notification
5499   NSTRACE ("[EmacsApp applicationDidResignActive:]");
5501   //ns_app_active=NO;
5502   ns_send_appdefined (-1);
5507 /* ==========================================================================
5509     EmacsApp aux handlers for managing event loop
5511    ========================================================================== */
5514 - (void)timeout_handler: (NSTimer *)timedEntry
5515 /* --------------------------------------------------------------------------
5516      The timeout specified to ns_select has passed.
5517    -------------------------------------------------------------------------- */
5519   /*NSTRACE ("timeout_handler"); */
5520   ns_send_appdefined (-2);
5523 #ifdef NS_IMPL_GNUSTEP
5524 - (void)sendFromMainThread:(id)unused
5526   ns_send_appdefined (nextappdefined);
5528 #endif
5530 - (void)fd_handler:(id)unused
5531 /* --------------------------------------------------------------------------
5532      Check data waiting on file descriptors and terminate if so
5533    -------------------------------------------------------------------------- */
5535   int result;
5536   int waiting = 1, nfds;
5537   char c;
5539   fd_set readfds, writefds, *wfds;
5540   struct timespec timeout, *tmo;
5541   NSAutoreleasePool *pool = nil;
5543   /* NSTRACE ("fd_handler"); */
5545   for (;;)
5546     {
5547       [pool release];
5548       pool = [[NSAutoreleasePool alloc] init];
5550       if (waiting)
5551         {
5552           fd_set fds;
5553           FD_ZERO (&fds);
5554           FD_SET (selfds[0], &fds);
5555           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5556           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5557             waiting = 0;
5558         }
5559       else
5560         {
5561           pthread_mutex_lock (&select_mutex);
5562           nfds = select_nfds;
5564           if (select_valid & SELECT_HAVE_READ)
5565             readfds = select_readfds;
5566           else
5567             FD_ZERO (&readfds);
5569           if (select_valid & SELECT_HAVE_WRITE)
5570             {
5571               writefds = select_writefds;
5572               wfds = &writefds;
5573             }
5574           else
5575             wfds = NULL;
5576           if (select_valid & SELECT_HAVE_TMO)
5577             {
5578               timeout = select_timeout;
5579               tmo = &timeout;
5580             }
5581           else
5582             tmo = NULL;
5584           pthread_mutex_unlock (&select_mutex);
5586           FD_SET (selfds[0], &readfds);
5587           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5589           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5591           if (result == 0)
5592             ns_send_appdefined (-2);
5593           else if (result > 0)
5594             {
5595               if (FD_ISSET (selfds[0], &readfds))
5596                 {
5597                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5598                     waiting = 1;
5599                 }
5600               else
5601                 {
5602                   pthread_mutex_lock (&select_mutex);
5603                   if (select_valid & SELECT_HAVE_READ)
5604                     select_readfds = readfds;
5605                   if (select_valid & SELECT_HAVE_WRITE)
5606                     select_writefds = writefds;
5607                   if (select_valid & SELECT_HAVE_TMO)
5608                     select_timeout = timeout;
5609                   pthread_mutex_unlock (&select_mutex);
5611                   ns_send_appdefined (result);
5612                 }
5613             }
5614           waiting = 1;
5615         }
5616     }
5621 /* ==========================================================================
5623     Service provision
5625    ========================================================================== */
5627 /* called from system: queue for next pass through event loop */
5628 - (void)requestService: (NSPasteboard *)pboard
5629               userData: (NSString *)userData
5630                  error: (NSString **)error
5632   [ns_pending_service_names addObject: userData];
5633   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5634       SSDATA (ns_string_from_pasteboard (pboard))]];
5638 /* called from ns_read_socket to clear queue */
5639 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5641   struct frame *emacsframe = SELECTED_FRAME ();
5642   NSEvent *theEvent = [NSApp currentEvent];
5644   NSTRACE ("[EmacsApp fulfillService:withArg:]");
5646   if (!emacs_event)
5647     return NO;
5649   emacs_event->kind = NS_NONKEY_EVENT;
5650   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5651   ns_input_spi_name = build_string ([name UTF8String]);
5652   ns_input_spi_arg = build_string ([arg UTF8String]);
5653   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5654   EV_TRAILER (theEvent);
5656   return YES;
5660 @end  /* EmacsApp */
5664 /* ==========================================================================
5666     EmacsView implementation
5668    ========================================================================== */
5671 @implementation EmacsView
5673 /* needed to inform when window closed from LISP */
5674 - (void) setWindowClosing: (BOOL)closing
5676   NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5678   windowClosing = closing;
5682 - (void)dealloc
5684   NSTRACE ("[EmacsView dealloc]");
5685   [toolbar release];
5686   if (fs_state == FULLSCREEN_BOTH)
5687     [nonfs_window release];
5688   [super dealloc];
5692 /* called on font panel selection */
5693 - (void)changeFont: (id)sender
5695   NSEvent *e = [[self window] currentEvent];
5696   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5697   struct font *font = face->font;
5698   id newFont;
5699   CGFloat size;
5700   NSFont *nsfont;
5702   NSTRACE ("[EmacsView changeFont:]");
5704   if (!emacs_event)
5705     return;
5707 #ifdef NS_IMPL_GNUSTEP
5708   nsfont = ((struct nsfont_info *)font)->nsfont;
5709 #endif
5710 #ifdef NS_IMPL_COCOA
5711   nsfont = (NSFont *) macfont_get_nsctfont (font);
5712 #endif
5714   if ((newFont = [sender convertFont: nsfont]))
5715     {
5716       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5718       emacs_event->kind = NS_NONKEY_EVENT;
5719       emacs_event->modifiers = 0;
5720       emacs_event->code = KEY_NS_CHANGE_FONT;
5722       size = [newFont pointSize];
5723       ns_input_fontsize = make_number (lrint (size));
5724       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5725       EV_TRAILER (e);
5726     }
5730 - (BOOL)acceptsFirstResponder
5732   NSTRACE ("[EmacsView acceptsFirstResponder]");
5733   return YES;
5737 - (void)resetCursorRects
5739   NSRect visible = [self visibleRect];
5740   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5741   NSTRACE ("[EmacsView resetCursorRects]");
5743   if (currentCursor == nil)
5744     currentCursor = [NSCursor arrowCursor];
5746   if (!NSIsEmptyRect (visible))
5747     [self addCursorRect: visible cursor: currentCursor];
5748   [currentCursor setOnMouseEntered: YES];
5753 /*****************************************************************************/
5754 /* Keyboard handling. */
5755 #define NS_KEYLOG 0
5757 - (void)keyDown: (NSEvent *)theEvent
5759   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5760   int code;
5761   unsigned fnKeysym = 0;
5762   static NSMutableArray *nsEvArray;
5763   int left_is_none;
5764   unsigned int flags = [theEvent modifierFlags];
5766   NSTRACE ("[EmacsView keyDown:]");
5768   /* Rhapsody and OS X give up and down events for the arrow keys */
5769   if (ns_fake_keydown == YES)
5770     ns_fake_keydown = NO;
5771   else if ([theEvent type] != NSKeyDown)
5772     return;
5774   if (!emacs_event)
5775     return;
5777  if (![[self window] isKeyWindow]
5778      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5779      /* we must avoid an infinite loop here. */
5780      && (EmacsView *)[[theEvent window] delegate] != self)
5781    {
5782      /* XXX: There is an occasional condition in which, when Emacs display
5783          updates a different frame from the current one, and temporarily
5784          selects it, then processes some interrupt-driven input
5785          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5786          for some reason that window has its first responder set to the NSView
5787          most recently updated (I guess), which is not the correct one. */
5788      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5789      return;
5790    }
5792   if (nsEvArray == nil)
5793     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5795   [NSCursor setHiddenUntilMouseMoves: YES];
5797   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5798     {
5799       clear_mouse_face (hlinfo);
5800       hlinfo->mouse_face_hidden = 1;
5801     }
5803   if (!processingCompose)
5804     {
5805       /* When using screen sharing, no left or right information is sent,
5806          so use Left key in those cases.  */
5807       int is_left_key, is_right_key;
5809       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5810         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5812       /* (Carbon way: [theEvent keyCode]) */
5814       /* is it a "function key"? */
5815       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5816          flag set (this is probably a bug in the OS).
5817       */
5818       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5819         {
5820           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5821         }
5822       if (fnKeysym == 0)
5823         {
5824           fnKeysym = ns_convert_key (code);
5825         }
5827       if (fnKeysym)
5828         {
5829           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5830              because Emacs treats Delete and KP-Delete same (in simple.el). */
5831           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5832 #ifdef NS_IMPL_GNUSTEP
5833               /*  GNUstep uses incompatible keycodes, even for those that are
5834                   supposed to be hardware independent.  Just check for delete.
5835                   Keypad delete does not have keysym 0xFFFF.
5836                   See http://savannah.gnu.org/bugs/?25395
5837               */
5838               || (fnKeysym == 0xFFFF && code == 127)
5839 #endif
5840             )
5841             code = 0xFF08; /* backspace */
5842           else
5843             code = fnKeysym;
5844         }
5846       /* are there modifiers? */
5847       emacs_event->modifiers = 0;
5849       if (flags & NSHelpKeyMask)
5850           emacs_event->modifiers |= hyper_modifier;
5852       if (flags & NSShiftKeyMask)
5853         emacs_event->modifiers |= shift_modifier;
5855       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5856       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5857         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5859       if (is_right_key)
5860         emacs_event->modifiers |= parse_solitary_modifier
5861           (EQ (ns_right_command_modifier, Qleft)
5862            ? ns_command_modifier
5863            : ns_right_command_modifier);
5865       if (is_left_key)
5866         {
5867           emacs_event->modifiers |= parse_solitary_modifier
5868             (ns_command_modifier);
5870           /* if super (default), take input manager's word so things like
5871              dvorak / qwerty layout work */
5872           if (EQ (ns_command_modifier, Qsuper)
5873               && !fnKeysym
5874               && [[theEvent characters] length] != 0)
5875             {
5876               /* XXX: the code we get will be unshifted, so if we have
5877                  a shift modifier, must convert ourselves */
5878               if (!(flags & NSShiftKeyMask))
5879                 code = [[theEvent characters] characterAtIndex: 0];
5880 #if 0
5881               /* this is ugly and also requires linking w/Carbon framework
5882                  (for LMGetKbdType) so for now leave this rare (?) case
5883                  undealt with.. in future look into CGEvent methods */
5884               else
5885                 {
5886                   long smv = GetScriptManagerVariable (smKeyScript);
5887                   Handle uchrHandle = GetResource
5888                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5889                   UInt32 dummy = 0;
5890                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5891                                  [[theEvent characters] characterAtIndex: 0],
5892                                  kUCKeyActionDisplay,
5893                                  (flags & ~NSCommandKeyMask) >> 8,
5894                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5895                                  &dummy, 1, &dummy, &code);
5896                   code &= 0xFF;
5897                 }
5898 #endif
5899             }
5900         }
5902       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5903       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5904         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5906       if (is_right_key)
5907           emacs_event->modifiers |= parse_solitary_modifier
5908               (EQ (ns_right_control_modifier, Qleft)
5909                ? ns_control_modifier
5910                : ns_right_control_modifier);
5912       if (is_left_key)
5913         emacs_event->modifiers |= parse_solitary_modifier
5914           (ns_control_modifier);
5916       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5917           emacs_event->modifiers |=
5918             parse_solitary_modifier (ns_function_modifier);
5920       left_is_none = NILP (ns_alternate_modifier)
5921         || EQ (ns_alternate_modifier, Qnone);
5923       is_right_key = (flags & NSRightAlternateKeyMask)
5924         == NSRightAlternateKeyMask;
5925       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5926         || (! is_right_key
5927             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5929       if (is_right_key)
5930         {
5931           if ((NILP (ns_right_alternate_modifier)
5932                || EQ (ns_right_alternate_modifier, Qnone)
5933                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5934               && !fnKeysym)
5935             {   /* accept pre-interp alt comb */
5936               if ([[theEvent characters] length] > 0)
5937                 code = [[theEvent characters] characterAtIndex: 0];
5938               /*HACK: clear lone shift modifier to stop next if from firing */
5939               if (emacs_event->modifiers == shift_modifier)
5940                 emacs_event->modifiers = 0;
5941             }
5942           else
5943             emacs_event->modifiers |= parse_solitary_modifier
5944               (EQ (ns_right_alternate_modifier, Qleft)
5945                ? ns_alternate_modifier
5946                : ns_right_alternate_modifier);
5947         }
5949       if (is_left_key) /* default = meta */
5950         {
5951           if (left_is_none && !fnKeysym)
5952             {   /* accept pre-interp alt comb */
5953               if ([[theEvent characters] length] > 0)
5954                 code = [[theEvent characters] characterAtIndex: 0];
5955               /*HACK: clear lone shift modifier to stop next if from firing */
5956               if (emacs_event->modifiers == shift_modifier)
5957                 emacs_event->modifiers = 0;
5958             }
5959           else
5960               emacs_event->modifiers |=
5961                 parse_solitary_modifier (ns_alternate_modifier);
5962         }
5964   if (NS_KEYLOG)
5965     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5966              code, fnKeysym, flags, emacs_event->modifiers);
5968       /* if it was a function key or had modifiers, pass it directly to emacs */
5969       if (fnKeysym || (emacs_event->modifiers
5970                        && (emacs_event->modifiers != shift_modifier)
5971                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5972 /*[[theEvent characters] length] */
5973         {
5974           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5975           if (code < 0x20)
5976             code |= (1<<28)|(3<<16);
5977           else if (code == 0x7f)
5978             code |= (1<<28)|(3<<16);
5979           else if (!fnKeysym)
5980             emacs_event->kind = code > 0xFF
5981               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5983           emacs_event->code = code;
5984           EV_TRAILER (theEvent);
5985           processingCompose = NO;
5986           return;
5987         }
5988     }
5991   if (NS_KEYLOG && !processingCompose)
5992     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5994   processingCompose = YES;
5995   [nsEvArray addObject: theEvent];
5996   [self interpretKeyEvents: nsEvArray];
5997   [nsEvArray removeObject: theEvent];
6001 #ifdef NS_IMPL_COCOA
6002 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
6003    decided not to send key-down for.
6004    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
6005    This only applies on Tiger and earlier.
6006    If it matches one of these, send it on to keyDown. */
6007 -(void)keyUp: (NSEvent *)theEvent
6009   int flags = [theEvent modifierFlags];
6010   int code = [theEvent keyCode];
6012   NSTRACE ("[EmacsView keyUp:]");
6014   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
6015       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
6016     {
6017       if (NS_KEYLOG)
6018         fprintf (stderr, "keyUp: passed test");
6019       ns_fake_keydown = YES;
6020       [self keyDown: theEvent];
6021     }
6023 #endif
6026 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
6029 /* <NSTextInput>: called when done composing;
6030    NOTE: also called when we delete over working text, followed immed.
6031          by doCommandBySelector: deleteBackward: */
6032 - (void)insertText: (id)aString
6034   int code;
6035   int len = [(NSString *)aString length];
6036   int i;
6038   NSTRACE ("[EmacsView insertText:]");
6040   if (NS_KEYLOG)
6041     NSLog (@"insertText '%@'\tlen = %d", aString, len);
6042   processingCompose = NO;
6044   if (!emacs_event)
6045     return;
6047   /* first, clear any working text */
6048   if (workingText != nil)
6049     [self deleteWorkingText];
6051   /* now insert the string as keystrokes */
6052   for (i =0; i<len; i++)
6053     {
6054       code = [aString characterAtIndex: i];
6055       /* TODO: still need this? */
6056       if (code == 0x2DC)
6057         code = '~'; /* 0x7E */
6058       if (code != 32) /* Space */
6059         emacs_event->modifiers = 0;
6060       emacs_event->kind
6061         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6062       emacs_event->code = code;
6063       EV_TRAILER ((id)nil);
6064     }
6068 /* <NSTextInput>: inserts display of composing characters */
6069 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
6071   NSString *str = [aString respondsToSelector: @selector (string)] ?
6072     [aString string] : aString;
6074   NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6076   if (NS_KEYLOG)
6077     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6078            str, (unsigned long)[str length],
6079            (unsigned long)selRange.length,
6080            (unsigned long)selRange.location);
6082   if (workingText != nil)
6083     [self deleteWorkingText];
6084   if ([str length] == 0)
6085     return;
6087   if (!emacs_event)
6088     return;
6090   processingCompose = YES;
6091   workingText = [str copy];
6092   ns_working_text = build_string ([workingText UTF8String]);
6094   emacs_event->kind = NS_TEXT_EVENT;
6095   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6096   EV_TRAILER ((id)nil);
6100 /* delete display of composing characters [not in <NSTextInput>] */
6101 - (void)deleteWorkingText
6103   NSTRACE ("[EmacsView deleteWorkingText]");
6105   if (workingText == nil)
6106     return;
6107   if (NS_KEYLOG)
6108     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6109   [workingText release];
6110   workingText = nil;
6111   processingCompose = NO;
6113   if (!emacs_event)
6114     return;
6116   emacs_event->kind = NS_TEXT_EVENT;
6117   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6118   EV_TRAILER ((id)nil);
6122 - (BOOL)hasMarkedText
6124   NSTRACE ("[EmacsView hasMarkedText]");
6126   return workingText != nil;
6130 - (NSRange)markedRange
6132   NSTRACE ("[EmacsView markedRange]");
6134   NSRange rng = workingText != nil
6135     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6136   if (NS_KEYLOG)
6137     NSLog (@"markedRange request");
6138   return rng;
6142 - (void)unmarkText
6144   NSTRACE ("[EmacsView unmarkText]");
6146   if (NS_KEYLOG)
6147     NSLog (@"unmark (accept) text");
6148   [self deleteWorkingText];
6149   processingCompose = NO;
6153 /* used to position char selection windows, etc. */
6154 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6156   NSRect rect;
6157   NSPoint pt;
6158   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6160   NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6162   if (NS_KEYLOG)
6163     NSLog (@"firstRectForCharRange request");
6165   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6166   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6167   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6168   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6169                                        +FRAME_LINE_HEIGHT (emacsframe));
6171   pt = [self convertPoint: pt toView: nil];
6172   pt = [[self window] convertBaseToScreen: pt];
6173   rect.origin = pt;
6174   return rect;
6178 - (NSInteger)conversationIdentifier
6180   return (NSInteger)self;
6184 - (void)doCommandBySelector: (SEL)aSelector
6186   NSTRACE ("[EmacsView doCommandBySelector:]");
6188   if (NS_KEYLOG)
6189     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6191   processingCompose = NO;
6192   if (aSelector == @selector (deleteBackward:))
6193     {
6194       /* happens when user backspaces over an ongoing composition:
6195          throw a 'delete' into the event queue */
6196       if (!emacs_event)
6197         return;
6198       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6199       emacs_event->code = 0xFF08;
6200       EV_TRAILER ((id)nil);
6201     }
6204 - (NSArray *)validAttributesForMarkedText
6206   static NSArray *arr = nil;
6207   if (arr == nil) arr = [NSArray new];
6208  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6209   return arr;
6212 - (NSRange)selectedRange
6214   if (NS_KEYLOG)
6215     NSLog (@"selectedRange request");
6216   return NSMakeRange (NSNotFound, 0);
6219 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6220     GNUSTEP_GUI_MINOR_VERSION > 22
6221 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6222 #else
6223 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6224 #endif
6226   if (NS_KEYLOG)
6227     NSLog (@"characterIndexForPoint request");
6228   return 0;
6231 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6233   static NSAttributedString *str = nil;
6234   if (str == nil) str = [NSAttributedString new];
6235   if (NS_KEYLOG)
6236     NSLog (@"attributedSubstringFromRange request");
6237   return str;
6240 /* End <NSTextInput> impl. */
6241 /*****************************************************************************/
6244 /* This is what happens when the user presses a mouse button.  */
6245 - (void)mouseDown: (NSEvent *)theEvent
6247   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6248   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6250   NSTRACE ("[EmacsView mouseDown:]");
6252   [self deleteWorkingText];
6254   if (!emacs_event)
6255     return;
6257   dpyinfo->last_mouse_frame = emacsframe;
6258   /* appears to be needed to prevent spurious movement events generated on
6259      button clicks */
6260   emacsframe->mouse_moved = 0;
6262   if ([theEvent type] == NSScrollWheel)
6263     {
6264       CGFloat delta = [theEvent deltaY];
6265       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6266       if (delta == 0)
6267         {
6268           delta = [theEvent deltaX];
6269           if (delta == 0)
6270             {
6271               NSTRACE_MSG ("deltaIsZero");
6272               return;
6273             }
6274           emacs_event->kind = HORIZ_WHEEL_EVENT;
6275         }
6276       else
6277         emacs_event->kind = WHEEL_EVENT;
6279       emacs_event->code = 0;
6280       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6281         ((delta > 0) ? up_modifier : down_modifier);
6282     }
6283   else
6284     {
6285       emacs_event->kind = MOUSE_CLICK_EVENT;
6286       emacs_event->code = EV_BUTTON (theEvent);
6287       emacs_event->modifiers = EV_MODIFIERS (theEvent)
6288                              | EV_UDMODIFIERS (theEvent);
6289     }
6290   XSETINT (emacs_event->x, lrint (p.x));
6291   XSETINT (emacs_event->y, lrint (p.y));
6292   EV_TRAILER (theEvent);
6296 - (void)rightMouseDown: (NSEvent *)theEvent
6298   NSTRACE ("[EmacsView rightMouseDown:]");
6299   [self mouseDown: theEvent];
6303 - (void)otherMouseDown: (NSEvent *)theEvent
6305   NSTRACE ("[EmacsView otherMouseDown:]");
6306   [self mouseDown: theEvent];
6310 - (void)mouseUp: (NSEvent *)theEvent
6312   NSTRACE ("[EmacsView mouseUp:]");
6313   [self mouseDown: theEvent];
6317 - (void)rightMouseUp: (NSEvent *)theEvent
6319   NSTRACE ("[EmacsView rightMouseUp:]");
6320   [self mouseDown: theEvent];
6324 - (void)otherMouseUp: (NSEvent *)theEvent
6326   NSTRACE ("[EmacsView otherMouseUp:]");
6327   [self mouseDown: theEvent];
6331 - (void) scrollWheel: (NSEvent *)theEvent
6333   NSTRACE ("[EmacsView scrollWheel:]");
6334   [self mouseDown: theEvent];
6338 /* Tell emacs the mouse has moved. */
6339 - (void)mouseMoved: (NSEvent *)e
6341   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6342   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6343   Lisp_Object frame;
6344   NSPoint pt;
6346   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6348   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6349   pt = [self convertPoint: [e locationInWindow] fromView: nil];
6350   dpyinfo->last_mouse_motion_x = pt.x;
6351   dpyinfo->last_mouse_motion_y = pt.y;
6353   /* update any mouse face */
6354   if (hlinfo->mouse_face_hidden)
6355     {
6356       hlinfo->mouse_face_hidden = 0;
6357       clear_mouse_face (hlinfo);
6358     }
6360   /* tooltip handling */
6361   previous_help_echo_string = help_echo_string;
6362   help_echo_string = Qnil;
6364   if (!NILP (Vmouse_autoselect_window))
6365     {
6366       NSTRACE_MSG ("mouse_autoselect_window");
6367       static Lisp_Object last_mouse_window;
6368       Lisp_Object window
6369         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6371       if (WINDOWP (window)
6372           && !EQ (window, last_mouse_window)
6373           && !EQ (window, selected_window)
6374           && (focus_follows_mouse
6375               || (EQ (XWINDOW (window)->frame,
6376                       XWINDOW (selected_window)->frame))))
6377         {
6378           NSTRACE_MSG ("in_window");
6379           emacs_event->kind = SELECT_WINDOW_EVENT;
6380           emacs_event->frame_or_window = window;
6381           EV_TRAILER2 (e);
6382         }
6383       /* Remember the last window where we saw the mouse.  */
6384       last_mouse_window = window;
6385     }
6387   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6388     help_echo_string = previous_help_echo_string;
6390   XSETFRAME (frame, emacsframe);
6391   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6392     {
6393       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6394          (note_mouse_highlight), which is called through the
6395          note_mouse_movement () call above */
6396       any_help_event_p = YES;
6397       gen_help_event (help_echo_string, frame, help_echo_window,
6398                       help_echo_object, help_echo_pos);
6399     }
6401   if (emacsframe->mouse_moved && send_appdefined)
6402     ns_send_appdefined (-1);
6406 - (void)mouseDragged: (NSEvent *)e
6408   NSTRACE ("[EmacsView mouseDragged:]");
6409   [self mouseMoved: e];
6413 - (void)rightMouseDragged: (NSEvent *)e
6415   NSTRACE ("[EmacsView rightMouseDragged:]");
6416   [self mouseMoved: e];
6420 - (void)otherMouseDragged: (NSEvent *)e
6422   NSTRACE ("[EmacsView otherMouseDragged:]");
6423   [self mouseMoved: e];
6427 - (BOOL)windowShouldClose: (id)sender
6429   NSEvent *e =[[self window] currentEvent];
6431   NSTRACE ("[EmacsView windowShouldClose:]");
6432   windowClosing = YES;
6433   if (!emacs_event)
6434     return NO;
6435   emacs_event->kind = DELETE_WINDOW_EVENT;
6436   emacs_event->modifiers = 0;
6437   emacs_event->code = 0;
6438   EV_TRAILER (e);
6439   /* Don't close this window, let this be done from lisp code.  */
6440   return NO;
6443 - (void) updateFrameSize: (BOOL) delay;
6445   NSWindow *window = [self window];
6446   NSRect wr = [window frame];
6447   int extra = 0;
6448   int oldc = cols, oldr = rows;
6449   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6450   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6451   int neww, newh;
6453   NSTRACE ("[EmacsView updateFrameSize:]");
6454   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6455   NSTRACE_RECT ("Original frame", wr);
6456   NSTRACE_MSG  ("Original columns: %d", cols);
6457   NSTRACE_MSG  ("Original rows: %d", rows);
6459   if (! [self isFullscreen])
6460     {
6461 #ifdef NS_IMPL_GNUSTEP
6462       // GNUstep does not always update the tool bar height.  Force it.
6463       if (toolbar && [toolbar isVisible])
6464           update_frame_tool_bar (emacsframe);
6465 #endif
6467       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6468         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6469     }
6471   if (wait_for_tool_bar)
6472     {
6473       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6474         {
6475           NSTRACE_MSG ("Waiting for toolbar");
6476           return;
6477         }
6478       wait_for_tool_bar = NO;
6479     }
6481   neww = (int)wr.size.width - emacsframe->border_width;
6482   newh = (int)wr.size.height - extra;
6484   NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6485   NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6487   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6488   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6490   if (cols < MINWIDTH)
6491     cols = MINWIDTH;
6493   if (rows < MINHEIGHT)
6494     rows = MINHEIGHT;
6496   NSTRACE_MSG ("New columns: %d", cols);
6497   NSTRACE_MSG ("New rows: %d", rows);
6499   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6500     {
6501       NSView *view = FRAME_NS_VIEW (emacsframe);
6503       change_frame_size (emacsframe,
6504                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6505                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6506                          0, delay, 0, 1);
6507       SET_FRAME_GARBAGED (emacsframe);
6508       cancel_mouse_face (emacsframe);
6510       wr = NSMakeRect (0, 0, neww, newh);
6512       [view setFrame: wr];
6514       // to do: consider using [NSNotificationCenter postNotificationName:].
6515       [self windowDidMove: // Update top/left.
6516               [NSNotification notificationWithName:NSWindowDidMoveNotification
6517                                             object:[view window]]];
6518     }
6519   else
6520     {
6521       NSTRACE_MSG ("No change");
6522     }
6525 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6526 /* normalize frame to gridded text size */
6528   int extra = 0;
6530   NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6531            NSTRACE_ARG_SIZE (frameSize));
6532   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6533   NSTRACE_FSTYPE ("fs_state", fs_state);
6535   if (fs_state == FULLSCREEN_MAXIMIZED
6536       && (maximized_width != (int)frameSize.width
6537           || maximized_height != (int)frameSize.height))
6538     [self setFSValue: FULLSCREEN_NONE];
6539   else if (fs_state == FULLSCREEN_WIDTH
6540            && maximized_width != (int)frameSize.width)
6541     [self setFSValue: FULLSCREEN_NONE];
6542   else if (fs_state == FULLSCREEN_HEIGHT
6543            && maximized_height != (int)frameSize.height)
6544     [self setFSValue: FULLSCREEN_NONE];
6546   if (fs_state == FULLSCREEN_NONE)
6547     maximized_width = maximized_height = -1;
6549   if (! [self isFullscreen])
6550     {
6551       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6552         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6553     }
6555   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6556   if (cols < MINWIDTH)
6557     cols = MINWIDTH;
6559   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6560                                            frameSize.height - extra);
6561   if (rows < MINHEIGHT)
6562     rows = MINHEIGHT;
6563 #ifdef NS_IMPL_COCOA
6564   {
6565     /* this sets window title to have size in it; the wm does this under GS */
6566     NSRect r = [[self window] frame];
6567     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6568       {
6569         if (old_title != 0)
6570           {
6571             xfree (old_title);
6572             old_title = 0;
6573           }
6574       }
6575     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6576       {
6577         char *size_title;
6578         NSWindow *window = [self window];
6579         if (old_title == 0)
6580           {
6581             char *t = strdup ([[[self window] title] UTF8String]);
6582             char *pos = strstr (t, "  â€”  ");
6583             if (pos)
6584               *pos = '\0';
6585             old_title = t;
6586           }
6587         size_title = xmalloc (strlen (old_title) + 40);
6588         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6589         [window setTitle: [NSString stringWithUTF8String: size_title]];
6590         [window display];
6591         xfree (size_title);
6592       }
6593   }
6594 #endif /* NS_IMPL_COCOA */
6596   NSTRACE_MSG ("cols: %d  rows: %d", cols, rows);
6598   /* Restrict the new size to the text gird.
6600      Don't restrict the width if the user only adjusted the height, and
6601      vice versa.  (Without this, the frame would shrink, and move
6602      slightly, if the window was resized by dragging one of its
6603      borders.) */
6604   if (!frame_resize_pixelwise)
6605     {
6606       NSRect r = [[self window] frame];
6608       if (r.size.width != frameSize.width)
6609         {
6610           frameSize.width =
6611             FRAME_TEXT_COLS_TO_PIXEL_WIDTH  (emacsframe, cols);
6612         }
6614       if (r.size.height != frameSize.height)
6615         {
6616           frameSize.height =
6617             FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6618         }
6619     }
6621   NSTRACE_RETURN_SIZE (frameSize);
6623   return frameSize;
6627 - (void)windowDidResize: (NSNotification *)notification
6629   NSTRACE ("[EmacsView windowDidResize:]");
6630   if (!FRAME_LIVE_P (emacsframe))
6631     {
6632       NSTRACE_MSG ("Ignored (frame dead)");
6633       return;
6634     }
6635   if (emacsframe->output_data.ns->in_animation)
6636     {
6637       NSTRACE_MSG ("Ignored (in animation)");
6638       return;
6639     }
6641   if (! [self fsIsNative])
6642     {
6643       NSWindow *theWindow = [notification object];
6644       /* We can get notification on the non-FS window when in
6645          fullscreen mode.  */
6646       if ([self window] != theWindow) return;
6647     }
6649   NSTRACE_RECT ("frame", [[notification object] frame]);
6651 #ifdef NS_IMPL_GNUSTEP
6652   NSWindow *theWindow = [notification object];
6654    /* In GNUstep, at least currently, it's possible to get a didResize
6655       without getting a willResize.. therefore we need to act as if we got
6656       the willResize now */
6657   NSSize sz = [theWindow frame].size;
6658   sz = [self windowWillResize: theWindow toSize: sz];
6659 #endif /* NS_IMPL_GNUSTEP */
6661   if (cols > 0 && rows > 0)
6662     {
6663       [self updateFrameSize: YES];
6664     }
6666   ns_send_appdefined (-1);
6669 #ifdef NS_IMPL_COCOA
6670 - (void)viewDidEndLiveResize
6672   NSTRACE ("[EmacsView viewDidEndLiveResize]");
6674   [super viewDidEndLiveResize];
6675   if (old_title != 0)
6676     {
6677       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6678       xfree (old_title);
6679       old_title = 0;
6680     }
6681   maximizing_resize = NO;
6683 #endif /* NS_IMPL_COCOA */
6686 - (void)windowDidBecomeKey: (NSNotification *)notification
6687 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6689   [self windowDidBecomeKey];
6693 - (void)windowDidBecomeKey      /* for direct calls */
6695   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6696   struct frame *old_focus = dpyinfo->x_focus_frame;
6698   NSTRACE ("[EmacsView windowDidBecomeKey]");
6700   if (emacsframe != old_focus)
6701     dpyinfo->x_focus_frame = emacsframe;
6703   ns_frame_rehighlight (emacsframe);
6705   if (emacs_event)
6706     {
6707       emacs_event->kind = FOCUS_IN_EVENT;
6708       EV_TRAILER ((id)nil);
6709     }
6713 - (void)windowDidResignKey: (NSNotification *)notification
6714 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6716   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6717   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6718   NSTRACE ("[EmacsView windowDidResignKey:]");
6720   if (is_focus_frame)
6721     dpyinfo->x_focus_frame = 0;
6723   emacsframe->mouse_moved = 0;
6724   ns_frame_rehighlight (emacsframe);
6726   /* FIXME: for some reason needed on second and subsequent clicks away
6727             from sole-frame Emacs to get hollow box to show */
6728   if (!windowClosing && [[self window] isVisible] == YES)
6729     {
6730       x_update_cursor (emacsframe, 1);
6731       x_set_frame_alpha (emacsframe);
6732     }
6734   if (any_help_event_p)
6735     {
6736       Lisp_Object frame;
6737       XSETFRAME (frame, emacsframe);
6738       help_echo_string = Qnil;
6739       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6740     }
6742   if (emacs_event && is_focus_frame)
6743     {
6744       [self deleteWorkingText];
6745       emacs_event->kind = FOCUS_OUT_EVENT;
6746       EV_TRAILER ((id)nil);
6747     }
6751 - (void)windowWillMiniaturize: sender
6753   NSTRACE ("[EmacsView windowWillMiniaturize:]");
6757 - (void)setFrame:(NSRect)frameRect;
6759   NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6760            NSTRACE_ARG_RECT (frameRect));
6762   [super setFrame:(NSRect)frameRect];
6766 - (BOOL)isFlipped
6768   return YES;
6772 - (BOOL)isOpaque
6774   return NO;
6778 - initFrameFromEmacs: (struct frame *)f
6780   NSRect r, wr;
6781   Lisp_Object tem;
6782   NSWindow *win;
6783   NSColor *col;
6784   NSString *name;
6786   NSTRACE ("[EmacsView initFrameFromEmacs:]");
6787   NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6789   windowClosing = NO;
6790   processingCompose = NO;
6791   scrollbarsNeedingUpdate = 0;
6792   fs_state = FULLSCREEN_NONE;
6793   fs_before_fs = next_maximized = -1;
6794 #ifdef HAVE_NATIVE_FS
6795   fs_is_native = ns_use_native_fullscreen;
6796 #else
6797   fs_is_native = NO;
6798 #endif
6799   maximized_width = maximized_height = -1;
6800   nonfs_window = nil;
6802   ns_userRect = NSMakeRect (0, 0, 0, 0);
6803   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6804                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6805   [self initWithFrame: r];
6806   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6808   FRAME_NS_VIEW (f) = self;
6809   emacsframe = f;
6810 #ifdef NS_IMPL_COCOA
6811   old_title = 0;
6812   maximizing_resize = NO;
6813 #endif
6815   win = [[EmacsWindow alloc]
6816             initWithContentRect: r
6817                       styleMask: (NSResizableWindowMask |
6818 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6819                                   NSTitledWindowMask |
6820 #endif
6821                                   NSMiniaturizableWindowMask |
6822                                   NSClosableWindowMask)
6823                         backing: NSBackingStoreBuffered
6824                           defer: YES];
6826 #ifdef HAVE_NATIVE_FS
6827     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6828 #endif
6830   wr = [win frame];
6831   bwidth = f->border_width = wr.size.width - r.size.width;
6832   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6834   [win setAcceptsMouseMovedEvents: YES];
6835   [win setDelegate: self];
6836 #if !defined (NS_IMPL_COCOA) || \
6837   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6838   [win useOptimizedDrawing: YES];
6839 #endif
6841   [[win contentView] addSubview: self];
6843   if (ns_drag_types)
6844     [self registerForDraggedTypes: ns_drag_types];
6846   tem = f->name;
6847   name = [NSString stringWithUTF8String:
6848                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6849   [win setTitle: name];
6851   /* toolbar support */
6852   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6853                          [NSString stringWithFormat: @"Emacs Frame %d",
6854                                    ns_window_num]];
6855   [win setToolbar: toolbar];
6856   [toolbar setVisible: NO];
6858   /* Don't set frame garbaged until tool bar is up to date?
6859      This avoids an extra clear and redraw (flicker) at frame creation.  */
6860   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6861   else wait_for_tool_bar = NO;
6864 #ifdef NS_IMPL_COCOA
6865   {
6866     NSButton *toggleButton;
6867   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6868   [toggleButton setTarget: self];
6869   [toggleButton setAction: @selector (toggleToolbar: )];
6870   }
6871 #endif
6872   FRAME_TOOLBAR_HEIGHT (f) = 0;
6874   tem = f->icon_name;
6875   if (!NILP (tem))
6876     [win setMiniwindowTitle:
6877            [NSString stringWithUTF8String: SSDATA (tem)]];
6879   {
6880     NSScreen *screen = [win screen];
6882     if (screen != 0)
6883       {
6884         NSPoint pt = NSMakePoint
6885           (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6886            IN_BOUND (-SCREENMAX,
6887                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6889         [win setFrameTopLeftPoint: pt];
6891         NSTRACE_RECT ("new frame", [win frame]);
6892       }
6893   }
6895   [win makeFirstResponder: self];
6897   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6898                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6899   [win setBackgroundColor: col];
6900   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6901     [win setOpaque: NO];
6903 #if !defined (NS_IMPL_COCOA) || \
6904   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6905   [self allocateGState];
6906 #endif
6907   [NSApp registerServicesMenuSendTypes: ns_send_types
6908                            returnTypes: nil];
6910   ns_window_num++;
6911   return self;
6915 - (void)windowDidMove: sender
6917   NSWindow *win = [self window];
6918   NSRect r = [win frame];
6919   NSArray *screens = [NSScreen screens];
6920   NSScreen *screen = [screens objectAtIndex: 0];
6922   NSTRACE ("[EmacsView windowDidMove:]");
6924   if (!emacsframe->output_data.ns)
6925     return;
6926   if (screen != nil)
6927     {
6928       emacsframe->left_pos = r.origin.x;
6929       emacsframe->top_pos =
6930         [screen frame].size.height - (r.origin.y + r.size.height);
6931     }
6935 /* Called AFTER method below, but before our windowWillResize call there leads
6936    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6937    location so set_window_size moves the frame. */
6938 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6940   NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6941             NSTRACE_FMT_RETURN "YES"),
6942            NSTRACE_ARG_RECT (newFrame));
6944   emacsframe->output_data.ns->zooming = 1;
6945   return YES;
6949 /* Override to do something slightly nonstandard, but nice.  First click on
6950    zoom button will zoom vertically.  Second will zoom completely.  Third
6951    returns to original. */
6952 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6953                         defaultFrame:(NSRect)defaultFrame
6955   // TODO: Rename to "currentFrame" and assign "result" properly in
6956   // all paths.
6957   NSRect result = [sender frame];
6959   NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6960             NSTRACE_FMT_RECT "]"),
6961            NSTRACE_ARG_RECT (defaultFrame));
6962   NSTRACE_FSTYPE ("fs_state", fs_state);
6963   NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6964   NSTRACE_FSTYPE ("next_maximized", next_maximized);
6965   NSTRACE_RECT   ("ns_userRect", ns_userRect);
6966   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6968   if (fs_before_fs != -1) /* Entering fullscreen */
6969     {
6970       NSTRACE_MSG ("Entering fullscreen");
6971       result = defaultFrame;
6972     }
6973   else
6974     {
6975       // Save the window size and position (frame) before the resize.
6976       if (fs_state != FULLSCREEN_MAXIMIZED
6977           && fs_state != FULLSCREEN_WIDTH)
6978         {
6979           ns_userRect.size.width = result.size.width;
6980           ns_userRect.origin.x   = result.origin.x;
6981         }
6983       if (fs_state != FULLSCREEN_MAXIMIZED
6984           && fs_state != FULLSCREEN_HEIGHT)
6985         {
6986           ns_userRect.size.height = result.size.height;
6987           ns_userRect.origin.y    = result.origin.y;
6988         }
6990       NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6992       if (next_maximized == FULLSCREEN_HEIGHT
6993           || (next_maximized == -1
6994               && abs ((int)(defaultFrame.size.height - result.size.height))
6995               > FRAME_LINE_HEIGHT (emacsframe)))
6996         {
6997           /* first click */
6998           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6999           maximized_height = result.size.height = defaultFrame.size.height;
7000           maximized_width = -1;
7001           result.origin.y = defaultFrame.origin.y;
7002           if (ns_userRect.size.height != 0)
7003             {
7004               result.origin.x = ns_userRect.origin.x;
7005               result.size.width = ns_userRect.size.width;
7006             }
7007           [self setFSValue: FULLSCREEN_HEIGHT];
7008 #ifdef NS_IMPL_COCOA
7009           maximizing_resize = YES;
7010 #endif
7011         }
7012       else if (next_maximized == FULLSCREEN_WIDTH)
7013         {
7014           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7015           maximized_width = result.size.width = defaultFrame.size.width;
7016           maximized_height = -1;
7017           result.origin.x = defaultFrame.origin.x;
7018           if (ns_userRect.size.width != 0)
7019             {
7020               result.origin.y = ns_userRect.origin.y;
7021               result.size.height = ns_userRect.size.height;
7022             }
7023           [self setFSValue: FULLSCREEN_WIDTH];
7024         }
7025       else if (next_maximized == FULLSCREEN_MAXIMIZED
7026                || (next_maximized == -1
7027                    && abs ((int)(defaultFrame.size.width - result.size.width))
7028                    > FRAME_COLUMN_WIDTH (emacsframe)))
7029         {
7030           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7032           result = defaultFrame;  /* second click */
7033           maximized_width = result.size.width;
7034           maximized_height = result.size.height;
7035           [self setFSValue: FULLSCREEN_MAXIMIZED];
7036 #ifdef NS_IMPL_COCOA
7037           maximizing_resize = YES;
7038 #endif
7039         }
7040       else
7041         {
7042           /* restore */
7043           NSTRACE_MSG ("Restore");
7044           result = ns_userRect.size.height ? ns_userRect : result;
7045           NSTRACE_RECT ("restore (2)", result);
7046           ns_userRect = NSMakeRect (0, 0, 0, 0);
7047 #ifdef NS_IMPL_COCOA
7048           maximizing_resize = fs_state != FULLSCREEN_NONE;
7049 #endif
7050           [self setFSValue: FULLSCREEN_NONE];
7051           maximized_width = maximized_height = -1;
7052         }
7053     }
7055   if (fs_before_fs == -1) next_maximized = -1;
7057   NSTRACE_RECT   ("Final ns_userRect", ns_userRect);
7058   NSTRACE_MSG    ("Final maximized_width: %d", maximized_width);
7059   NSTRACE_MSG    ("Final maximized_height: %d", maximized_height);
7060   NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
7062   [self windowWillResize: sender toSize: result.size];
7064   NSTRACE_RETURN_RECT (result);
7066   return result;
7070 - (void)windowDidDeminiaturize: sender
7072   NSTRACE ("[EmacsView windowDidDeminiaturize:]");
7073   if (!emacsframe->output_data.ns)
7074     return;
7076   SET_FRAME_ICONIFIED (emacsframe, 0);
7077   SET_FRAME_VISIBLE (emacsframe, 1);
7078   windows_or_buffers_changed = 63;
7080   if (emacs_event)
7081     {
7082       emacs_event->kind = DEICONIFY_EVENT;
7083       EV_TRAILER ((id)nil);
7084     }
7088 - (void)windowDidExpose: sender
7090   NSTRACE ("[EmacsView windowDidExpose:]");
7091   if (!emacsframe->output_data.ns)
7092     return;
7094   SET_FRAME_VISIBLE (emacsframe, 1);
7095   SET_FRAME_GARBAGED (emacsframe);
7097   if (send_appdefined)
7098     ns_send_appdefined (-1);
7102 - (void)windowDidMiniaturize: sender
7104   NSTRACE ("[EmacsView windowDidMiniaturize:]");
7105   if (!emacsframe->output_data.ns)
7106     return;
7108   SET_FRAME_ICONIFIED (emacsframe, 1);
7109   SET_FRAME_VISIBLE (emacsframe, 0);
7111   if (emacs_event)
7112     {
7113       emacs_event->kind = ICONIFY_EVENT;
7114       EV_TRAILER ((id)nil);
7115     }
7118 #ifdef HAVE_NATIVE_FS
7119 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7120       willUseFullScreenPresentationOptions:
7121   (NSApplicationPresentationOptions)proposedOptions
7123   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7125 #endif
7127 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7129   NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7130   [self windowWillEnterFullScreen];
7132 - (void)windowWillEnterFullScreen /* provided for direct calls */
7134   NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7135   fs_before_fs = fs_state;
7138 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7140   NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7141   [self windowDidEnterFullScreen];
7144 - (void)windowDidEnterFullScreen /* provided for direct calls */
7146   NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7147   [self setFSValue: FULLSCREEN_BOTH];
7148   if (! [self fsIsNative])
7149     {
7150       [self windowDidBecomeKey];
7151       [nonfs_window orderOut:self];
7152     }
7153   else
7154     {
7155       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7156 #ifdef NS_IMPL_COCOA
7157 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7158       unsigned val = (unsigned)[NSApp presentationOptions];
7160       // OSX 10.7 bug fix, the menu won't appear without this.
7161       // val is non-zero on other OSX versions.
7162       if (val == 0)
7163         {
7164           NSApplicationPresentationOptions options
7165             = NSApplicationPresentationAutoHideDock
7166             | NSApplicationPresentationAutoHideMenuBar
7167             | NSApplicationPresentationFullScreen
7168             | NSApplicationPresentationAutoHideToolbar;
7170           [NSApp setPresentationOptions: options];
7171         }
7172 #endif
7173 #endif
7174       [toolbar setVisible:tbar_visible];
7175     }
7178 - (void)windowWillExitFullScreen:(NSNotification *)notification
7180   NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7181   [self windowWillExitFullScreen];
7184 - (void)windowWillExitFullScreen /* provided for direct calls */
7186   NSTRACE ("[EmacsView windowWillExitFullScreen]");
7187   if (!FRAME_LIVE_P (emacsframe))
7188     {
7189       NSTRACE_MSG ("Ignored (frame dead)");
7190       return;
7191     }
7192   if (next_maximized != -1)
7193     fs_before_fs = next_maximized;
7196 - (void)windowDidExitFullScreen:(NSNotification *)notification
7198   NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7199   [self windowDidExitFullScreen];
7202 - (void)windowDidExitFullScreen /* provided for direct calls */
7204   NSTRACE ("[EmacsView windowDidExitFullScreen]");
7205   if (!FRAME_LIVE_P (emacsframe))
7206     {
7207       NSTRACE_MSG ("Ignored (frame dead)");
7208       return;
7209     }
7210   [self setFSValue: fs_before_fs];
7211   fs_before_fs = -1;
7212 #ifdef HAVE_NATIVE_FS
7213   [self updateCollectionBehavior];
7214 #endif
7215   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7216     {
7217       [toolbar setVisible:YES];
7218       update_frame_tool_bar (emacsframe);
7219       [self updateFrameSize:YES];
7220       [[self window] display];
7221     }
7222   else
7223     [toolbar setVisible:NO];
7225   if (next_maximized != -1)
7226     [[self window] performZoom:self];
7229 - (BOOL)fsIsNative
7231   return fs_is_native;
7234 - (BOOL)isFullscreen
7236   BOOL res;
7238   if (! fs_is_native)
7239     {
7240       res = (nonfs_window != nil);
7241     }
7242   else
7243     {
7244 #ifdef HAVE_NATIVE_FS
7245       res = (([[self window] styleMask] & NSFullScreenWindowMask) != 0);
7246 #else
7247       res = NO;
7248 #endif
7249     }
7251   NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7252            (int) res);
7254   return res;
7257 #ifdef HAVE_NATIVE_FS
7258 - (void)updateCollectionBehavior
7260   NSTRACE ("[EmacsView updateCollectionBehavior]");
7262   if (! [self isFullscreen])
7263     {
7264       NSWindow *win = [self window];
7265       NSWindowCollectionBehavior b = [win collectionBehavior];
7266       if (ns_use_native_fullscreen)
7267         b |= NSWindowCollectionBehaviorFullScreenPrimary;
7268       else
7269         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7271       [win setCollectionBehavior: b];
7272       fs_is_native = ns_use_native_fullscreen;
7273     }
7275 #endif
7277 - (void)toggleFullScreen: (id)sender
7279   NSWindow *w, *fw;
7280   BOOL onFirstScreen;
7281   struct frame *f;
7282   NSRect r, wr;
7283   NSColor *col;
7285   NSTRACE ("[EmacsView toggleFullScreen:]");
7287   if (fs_is_native)
7288     {
7289 #ifdef HAVE_NATIVE_FS
7290       [[self window] toggleFullScreen:sender];
7291 #endif
7292       return;
7293     }
7295   w = [self window];
7296   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7297   f = emacsframe;
7298   wr = [w frame];
7299   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7300                                  (FRAME_DEFAULT_FACE (f)),
7301                                  f);
7303   if (fs_state != FULLSCREEN_BOTH)
7304     {
7305       NSScreen *screen = [w screen];
7307 #if defined (NS_IMPL_COCOA) && \
7308   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7309       /* Hide ghost menu bar on secondary monitor? */
7310       if (! onFirstScreen)
7311         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7312 #endif
7313       /* Hide dock and menubar if we are on the primary screen.  */
7314       if (onFirstScreen)
7315         {
7316 #ifdef NS_IMPL_COCOA
7317           NSApplicationPresentationOptions options
7318             = NSApplicationPresentationAutoHideDock
7319             | NSApplicationPresentationAutoHideMenuBar;
7321           [NSApp setPresentationOptions: options];
7322 #else
7323           [NSMenu setMenuBarVisible:NO];
7324 #endif
7325         }
7327       fw = [[EmacsFSWindow alloc]
7328                        initWithContentRect:[w contentRectForFrameRect:wr]
7329                                  styleMask:NSBorderlessWindowMask
7330                                    backing:NSBackingStoreBuffered
7331                                      defer:YES
7332                                     screen:screen];
7334       [fw setContentView:[w contentView]];
7335       [fw setTitle:[w title]];
7336       [fw setDelegate:self];
7337       [fw setAcceptsMouseMovedEvents: YES];
7338 #if !defined (NS_IMPL_COCOA) || \
7339   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7340       [fw useOptimizedDrawing: YES];
7341 #endif
7342       [fw setBackgroundColor: col];
7343       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7344         [fw setOpaque: NO];
7346       f->border_width = 0;
7347       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7348       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7349       FRAME_TOOLBAR_HEIGHT (f) = 0;
7351       nonfs_window = w;
7353       [self windowWillEnterFullScreen];
7354       [fw makeKeyAndOrderFront:NSApp];
7355       [fw makeFirstResponder:self];
7356       [w orderOut:self];
7357       r = [fw frameRectForContentRect:[screen frame]];
7358       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7359       [self windowDidEnterFullScreen];
7360       [fw display];
7361     }
7362   else
7363     {
7364       fw = w;
7365       w = nonfs_window;
7366       nonfs_window = nil;
7368       if (onFirstScreen)
7369         {
7370 #ifdef NS_IMPL_COCOA
7371           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7372 #else
7373           [NSMenu setMenuBarVisible:YES];
7374 #endif
7375         }
7377       [w setContentView:[fw contentView]];
7378       [w setBackgroundColor: col];
7379       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7380         [w setOpaque: NO];
7382       f->border_width = bwidth;
7383       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7384       if (FRAME_EXTERNAL_TOOL_BAR (f))
7385         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7387       // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7389       [self windowWillExitFullScreen];
7390       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7391       [fw close];
7392       [w makeKeyAndOrderFront:NSApp];
7393       [self windowDidExitFullScreen];
7394       [self updateFrameSize:YES];
7395     }
7398 - (void)handleFS
7400   NSTRACE ("[EmacsView handleFS]");
7402   if (fs_state != emacsframe->want_fullscreen)
7403     {
7404       if (fs_state == FULLSCREEN_BOTH)
7405         {
7406           NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7407           [self toggleFullScreen:self];
7408         }
7410       switch (emacsframe->want_fullscreen)
7411         {
7412         case FULLSCREEN_BOTH:
7413           NSTRACE_MSG ("FULLSCREEN_BOTH");
7414           [self toggleFullScreen:self];
7415           break;
7416         case FULLSCREEN_WIDTH:
7417           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7418           next_maximized = FULLSCREEN_WIDTH;
7419           if (fs_state != FULLSCREEN_BOTH)
7420             [[self window] performZoom:self];
7421           break;
7422         case FULLSCREEN_HEIGHT:
7423           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7424           next_maximized = FULLSCREEN_HEIGHT;
7425           if (fs_state != FULLSCREEN_BOTH)
7426             [[self window] performZoom:self];
7427           break;
7428         case FULLSCREEN_MAXIMIZED:
7429           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7430           next_maximized = FULLSCREEN_MAXIMIZED;
7431           if (fs_state != FULLSCREEN_BOTH)
7432             [[self window] performZoom:self];
7433           break;
7434         case FULLSCREEN_NONE:
7435           NSTRACE_MSG ("FULLSCREEN_NONE");
7436           if (fs_state != FULLSCREEN_BOTH)
7437             {
7438               next_maximized = FULLSCREEN_NONE;
7439               [[self window] performZoom:self];
7440             }
7441           break;
7442         }
7444       emacsframe->want_fullscreen = FULLSCREEN_NONE;
7445     }
7449 - (void) setFSValue: (int)value
7451   NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7452            NSTRACE_ARG_FSTYPE(value));
7454   Lisp_Object lval = Qnil;
7455   switch (value)
7456     {
7457     case FULLSCREEN_BOTH:
7458       lval = Qfullboth;
7459       break;
7460     case FULLSCREEN_WIDTH:
7461       lval = Qfullwidth;
7462       break;
7463     case FULLSCREEN_HEIGHT:
7464       lval = Qfullheight;
7465       break;
7466     case FULLSCREEN_MAXIMIZED:
7467       lval = Qmaximized;
7468       break;
7469     }
7470   store_frame_param (emacsframe, Qfullscreen, lval);
7471   fs_state = value;
7474 - (void)mouseEntered: (NSEvent *)theEvent
7476   NSTRACE ("[EmacsView mouseEntered:]");
7477   if (emacsframe)
7478     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7479       = EV_TIMESTAMP (theEvent);
7483 - (void)mouseExited: (NSEvent *)theEvent
7485   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7487   NSTRACE ("[EmacsView mouseExited:]");
7489   if (!hlinfo)
7490     return;
7492   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7493     = EV_TIMESTAMP (theEvent);
7495   if (emacsframe == hlinfo->mouse_face_mouse_frame)
7496     {
7497       clear_mouse_face (hlinfo);
7498       hlinfo->mouse_face_mouse_frame = 0;
7499     }
7503 - menuDown: sender
7505   NSTRACE ("[EmacsView menuDown:]");
7506   if (context_menu_value == -1)
7507     context_menu_value = [sender tag];
7508   else
7509     {
7510       NSInteger tag = [sender tag];
7511       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7512                                     emacsframe->menu_bar_vector,
7513                                     (void *)tag);
7514     }
7516   ns_send_appdefined (-1);
7517   return self;
7521 - (EmacsToolbar *)toolbar
7523   return toolbar;
7527 /* this gets called on toolbar button click */
7528 - toolbarClicked: (id)item
7530   NSEvent *theEvent;
7531   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7533   NSTRACE ("[EmacsView toolbarClicked:]");
7535   if (!emacs_event)
7536     return self;
7538   /* send first event (for some reason two needed) */
7539   theEvent = [[self window] currentEvent];
7540   emacs_event->kind = TOOL_BAR_EVENT;
7541   XSETFRAME (emacs_event->arg, emacsframe);
7542   EV_TRAILER (theEvent);
7544   emacs_event->kind = TOOL_BAR_EVENT;
7545 /*   XSETINT (emacs_event->code, 0); */
7546   emacs_event->arg = AREF (emacsframe->tool_bar_items,
7547                            idx + TOOL_BAR_ITEM_KEY);
7548   emacs_event->modifiers = EV_MODIFIERS (theEvent);
7549   EV_TRAILER (theEvent);
7550   return self;
7554 - toggleToolbar: (id)sender
7556   NSTRACE ("[EmacsView toggleToolbar:]");
7558   if (!emacs_event)
7559     return self;
7561   emacs_event->kind = NS_NONKEY_EVENT;
7562   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7563   EV_TRAILER ((id)nil);
7564   return self;
7568 - (void)drawRect: (NSRect)rect
7570   int x = NSMinX (rect), y = NSMinY (rect);
7571   int width = NSWidth (rect), height = NSHeight (rect);
7573   NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7574            NSTRACE_ARG_RECT(rect));
7576   if (!emacsframe || !emacsframe->output_data.ns)
7577     return;
7579   ns_clear_frame_area (emacsframe, x, y, width, height);
7580   block_input ();
7581   expose_frame (emacsframe, x, y, width, height);
7582   unblock_input ();
7584   /*
7585     drawRect: may be called (at least in OS X 10.5) for invisible
7586     views as well for some reason.  Thus, do not infer visibility
7587     here.
7589     emacsframe->async_visible = 1;
7590     emacsframe->async_iconified = 0;
7591   */
7595 /* NSDraggingDestination protocol methods.  Actually this is not really a
7596    protocol, but a category of Object.  O well...  */
7598 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7600   NSTRACE ("[EmacsView draggingEntered:]");
7601   return NSDragOperationGeneric;
7605 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7607   return YES;
7611 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7613   id pb;
7614   int x, y;
7615   NSString *type;
7616   NSEvent *theEvent = [[self window] currentEvent];
7617   NSPoint position;
7618   NSDragOperation op = [sender draggingSourceOperationMask];
7619   int modifiers = 0;
7621   NSTRACE ("[EmacsView performDragOperation:]");
7623   if (!emacs_event)
7624     return NO;
7626   position = [self convertPoint: [sender draggingLocation] fromView: nil];
7627   x = lrint (position.x);  y = lrint (position.y);
7629   pb = [sender draggingPasteboard];
7630   type = [pb availableTypeFromArray: ns_drag_types];
7632   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7633       // URL drags contain all operations (0xf), don't allow all to be set.
7634       (op & 0xf) != 0xf)
7635     {
7636       if (op & NSDragOperationLink)
7637         modifiers |= NSControlKeyMask;
7638       if (op & NSDragOperationCopy)
7639         modifiers |= NSAlternateKeyMask;
7640       if (op & NSDragOperationGeneric)
7641         modifiers |= NSCommandKeyMask;
7642     }
7644   modifiers = EV_MODIFIERS2 (modifiers);
7645   if (type == 0)
7646     {
7647       return NO;
7648     }
7649   else if ([type isEqualToString: NSFilenamesPboardType])
7650     {
7651       NSArray *files;
7652       NSEnumerator *fenum;
7653       NSString *file;
7655       if (!(files = [pb propertyListForType: type]))
7656         return NO;
7658       fenum = [files objectEnumerator];
7659       while ( (file = [fenum nextObject]) )
7660         {
7661           emacs_event->kind = DRAG_N_DROP_EVENT;
7662           XSETINT (emacs_event->x, x);
7663           XSETINT (emacs_event->y, y);
7664           ns_input_file = append2 (ns_input_file,
7665                                    build_string ([file UTF8String]));
7666           emacs_event->modifiers = modifiers;
7667           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
7668           EV_TRAILER (theEvent);
7669         }
7670       return YES;
7671     }
7672   else if ([type isEqualToString: NSURLPboardType])
7673     {
7674       NSURL *url = [NSURL URLFromPasteboard: pb];
7675       if (url == nil) return NO;
7677       emacs_event->kind = DRAG_N_DROP_EVENT;
7678       XSETINT (emacs_event->x, x);
7679       XSETINT (emacs_event->y, y);
7680       emacs_event->modifiers = modifiers;
7681       emacs_event->arg =  list2 (Qurl,
7682                                  build_string ([[url absoluteString]
7683                                                  UTF8String]));
7684       EV_TRAILER (theEvent);
7686       if ([url isFileURL] != NO)
7687         {
7688           NSString *file = [url path];
7689           ns_input_file = append2 (ns_input_file,
7690                                    build_string ([file UTF8String]));
7691         }
7692       return YES;
7693     }
7694   else if ([type isEqualToString: NSStringPboardType]
7695            || [type isEqualToString: NSTabularTextPboardType])
7696     {
7697       NSString *data;
7699       if (! (data = [pb stringForType: type]))
7700         return NO;
7702       emacs_event->kind = DRAG_N_DROP_EVENT;
7703       XSETINT (emacs_event->x, x);
7704       XSETINT (emacs_event->y, y);
7705       emacs_event->modifiers = modifiers;
7706       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7707       EV_TRAILER (theEvent);
7708       return YES;
7709     }
7710   else
7711     {
7712       fprintf (stderr, "Invalid data type in dragging pasteboard");
7713       return NO;
7714     }
7718 - (id) validRequestorForSendType: (NSString *)typeSent
7719                       returnType: (NSString *)typeReturned
7721   NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7722   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7723       && typeReturned == nil)
7724     {
7725       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7726         return self;
7727     }
7729   return [super validRequestorForSendType: typeSent
7730                                returnType: typeReturned];
7734 /* The next two methods are part of NSServicesRequests informal protocol,
7735    supposedly called when a services menu item is chosen from this app.
7736    But this should not happen because we override the services menu with our
7737    own entries which call ns-perform-service.
7738    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7739    So let's at least stub them out until further investigation can be done. */
7741 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7743   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7744      be written into the buffer in place of the existing selection..
7745      ordinary service calls go through functions defined in ns-win.el */
7746   return NO;
7749 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7751   NSArray *typesDeclared;
7752   Lisp_Object val;
7754   NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7756   /* We only support NSStringPboardType */
7757   if ([types containsObject:NSStringPboardType] == NO) {
7758     return NO;
7759   }
7761   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7762   if (CONSP (val) && SYMBOLP (XCAR (val)))
7763     {
7764       val = XCDR (val);
7765       if (CONSP (val) && NILP (XCDR (val)))
7766         val = XCAR (val);
7767     }
7768   if (! STRINGP (val))
7769     return NO;
7771   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7772   [pb declareTypes:typesDeclared owner:nil];
7773   ns_string_to_pasteboard (pb, val);
7774   return YES;
7778 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7779    (gives a miniaturized version of the window); currently we use the latter for
7780    frames whose active buffer doesn't correspond to any file
7781    (e.g., '*scratch*') */
7782 - setMiniwindowImage: (BOOL) setMini
7784   id image = [[self window] miniwindowImage];
7785   NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7787   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7788      about "AppleDockIconEnabled" notwithstanding, however the set message
7789      below has its effect nonetheless. */
7790   if (image != emacsframe->output_data.ns->miniimage)
7791     {
7792       if (image && [image isKindOfClass: [EmacsImage class]])
7793         [image release];
7794       [[self window] setMiniwindowImage:
7795                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7796     }
7798   return self;
7802 - (void) setRows: (int) r andColumns: (int) c
7804   NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7805   rows = r;
7806   cols = c;
7809 - (int) fullscreenState
7811   return fs_state;
7814 @end  /* EmacsView */
7818 /* ==========================================================================
7820     EmacsWindow implementation
7822    ========================================================================== */
7824 @implementation EmacsWindow
7826 #ifdef NS_IMPL_COCOA
7827 - (id)accessibilityAttributeValue:(NSString *)attribute
7829   Lisp_Object str = Qnil;
7830   struct frame *f = SELECTED_FRAME ();
7831   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7833   NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7835   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7836     return NSAccessibilityTextFieldRole;
7838   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7839       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7840     {
7841       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7842     }
7843   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7844     {
7845       if (! NILP (BVAR (curbuf, mark_active)))
7846           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7848       if (NILP (str))
7849         {
7850           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7851           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7852           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7854           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7855             str = make_uninit_multibyte_string (range, byte_range);
7856           else
7857             str = make_uninit_string (range);
7858           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7859              Is this a problem?  */
7860           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7861         }
7862     }
7865   if (! NILP (str))
7866     {
7867       if (CONSP (str) && SYMBOLP (XCAR (str)))
7868         {
7869           str = XCDR (str);
7870           if (CONSP (str) && NILP (XCDR (str)))
7871             str = XCAR (str);
7872         }
7873       if (STRINGP (str))
7874         {
7875           const char *utfStr = SSDATA (str);
7876           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7877           return nsStr;
7878         }
7879     }
7881   return [super accessibilityAttributeValue:attribute];
7883 #endif /* NS_IMPL_COCOA */
7885 /* Constrain size and placement of a frame.
7887    By returning the original "frameRect", the frame is not
7888    constrained. This can lead to unwanted situations where, for
7889    example, the menu bar covers the frame.
7891    The default implementation (accessed using "super") constrains the
7892    frame to the visible area of SCREEN, minus the menu bar (if
7893    present) and the Dock.  Note that default implementation also calls
7894    windowWillResize, with the frame it thinks should have.  (This can
7895    make the frame exit maximized mode.)
7897    Note that this should work in situations where multiple monitors
7898    are present.  Common configurations are side-by-side monitors and a
7899    monitor on top of another (e.g. when a laptop is placed under a
7900    large screen). */
7901 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7903   NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7904              NSTRACE_ARG_RECT (frameRect));
7906 #ifdef NS_IMPL_COCOA
7907 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7908   // If separate spaces is on, it is like each screen is independent.  There is
7909   // no spanning of frames across screens.
7910   if ([NSScreen screensHaveSeparateSpaces])
7911     {
7912       NSTRACE_MSG ("Screens have separate spaces");
7913       frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7914       NSTRACE_RETURN_RECT (frameRect);
7915       return frameRect;
7916     }
7917 #endif
7918 #endif
7920   return constrain_frame_rect(frameRect,
7921                               [(EmacsView *)[self delegate] isFullscreen]);
7925 - (void)performZoom:(id)sender
7927   NSTRACE ("[EmacsWindow performZoom:]");
7929   return [super performZoom:sender];
7932 - (void)zoom:(id)sender
7934   NSTRACE ("[EmacsWindow zoom:]");
7936   ns_update_auto_hide_menu_bar();
7938   // Below are three zoom implementations.  In the final commit, the
7939   // idea is that the last should be included.
7941 #if 0
7942   // Native zoom done using the standard zoom animation.  Size of the
7943   // resulting frame reduced to accommodate the Dock and, if present,
7944   // the menu-bar.
7945   [super zoom:sender];
7947 #elif 0
7948   // Native zoom done using the standard zoom animation, plus an
7949   // explicit resize to cover the full screen, except the menu-bar and
7950   // dock, if present.
7951   [super zoom:sender];
7953   // After the native zoom, resize the resulting frame to fill the
7954   // entire screen, except the menu-bar.
7955   //
7956   // This works for all practical purposes.  (The only minor oddity is
7957   // when transiting from full-height frame to a maximized, the
7958   // animation reduces the height of the frame slightly (to the 4
7959   // pixels needed to accommodate the Doc) before it snaps back into
7960   // full height.  The user would need a very trained eye to spot
7961   // this.)
7962   NSScreen * screen = [self screen];
7963   if (screen != nil)
7964     {
7965       int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7967       NSTRACE_FSTYPE ("fullscreenState", fs_state);
7969       NSRect sr = [screen frame];
7970       struct EmacsMargins margins
7971         = ns_screen_margins_ignoring_hidden_dock(screen);
7973       NSRect wr = [self frame];
7974       NSTRACE_RECT ("Rect after zoom", wr);
7976       NSRect newWr = wr;
7978       if (fs_state == FULLSCREEN_MAXIMIZED
7979           || fs_state == FULLSCREEN_HEIGHT)
7980         {
7981           newWr.origin.y = sr.origin.y + margins.bottom;
7982           newWr.size.height = sr.size.height - margins.top - margins.bottom;
7983         }
7985       if (fs_state == FULLSCREEN_MAXIMIZED
7986           || fs_state == FULLSCREEN_WIDTH)
7987         {
7988           newWr.origin.x = sr.origin.x + margins.left;
7989           newWr.size.width = sr.size.width - margins.right - margins.left;
7990         }
7992       if (newWr.size.width     != wr.size.width
7993           || newWr.size.height != wr.size.height
7994           || newWr.origin.x    != wr.origin.x
7995           || newWr.origin.y    != wr.origin.y)
7996         {
7997           NSTRACE_MSG ("New frame different");
7998           [self setFrame: newWr display: NO];
7999         }
8000     }
8001 #else
8002   // Non-native zoom which is done instantaneously.  The resulting
8003   // frame covers the entire screen, except the menu-bar and dock, if
8004   // present.
8005   NSScreen * screen = [self screen];
8006   if (screen != nil)
8007     {
8008       NSRect sr = [screen frame];
8009       struct EmacsMargins margins
8010         = ns_screen_margins_ignoring_hidden_dock(screen);
8012       sr.size.height -= (margins.top + margins.bottom);
8013       sr.size.width  -= (margins.left + margins.right);
8014       sr.origin.x += margins.left;
8015       sr.origin.y += margins.bottom;
8017       sr = [[self delegate] windowWillUseStandardFrame:self
8018                                           defaultFrame:sr];
8019       [self setFrame: sr display: NO];
8020     }
8021 #endif
8024 - (void)setFrame:(NSRect)windowFrame
8025          display:(BOOL)displayViews
8027   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
8028            NSTRACE_ARG_RECT (windowFrame), displayViews);
8030   [super setFrame:windowFrame display:displayViews];
8033 - (void)setFrame:(NSRect)windowFrame
8034          display:(BOOL)displayViews
8035          animate:(BOOL)performAnimation
8037   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
8038            " display:%d performAnimation:%d]",
8039            NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
8041   [super setFrame:windowFrame display:displayViews animate:performAnimation];
8044 - (void)setFrameTopLeftPoint:(NSPoint)point
8046   NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
8047            NSTRACE_ARG_POINT (point));
8049   [super setFrameTopLeftPoint:point];
8051 @end /* EmacsWindow */
8054 @implementation EmacsFSWindow
8056 - (BOOL)canBecomeKeyWindow
8058   return YES;
8061 - (BOOL)canBecomeMainWindow
8063   return YES;
8066 @end
8068 /* ==========================================================================
8070     EmacsScroller implementation
8072    ========================================================================== */
8075 @implementation EmacsScroller
8077 /* for repeat button push */
8078 #define SCROLL_BAR_FIRST_DELAY 0.5
8079 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
8081 + (CGFloat) scrollerWidth
8083   /* TODO: if we want to allow variable widths, this is the place to do it,
8084            however neither GNUstep nor Cocoa support it very well */
8085   CGFloat r;
8086 #if !defined (NS_IMPL_COCOA) || \
8087   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8088   r = [NSScroller scrollerWidth];
8089 #else
8090   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
8091                                 scrollerStyle: NSScrollerStyleLegacy];
8092 #endif
8093   return r;
8096 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8098   NSTRACE ("[EmacsScroller initFrame: window:]");
8100   if (r.size.width > r.size.height)
8101       horizontal = YES;
8102   else
8103       horizontal = NO;
8105   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8106   [self setContinuous: YES];
8107   [self setEnabled: YES];
8109   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8110      locked against the top and bottom edges, and right edge on OS X, where
8111      scrollers are on right. */
8112 #ifdef NS_IMPL_GNUSTEP
8113   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8114 #else
8115   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8116 #endif
8118   window = XWINDOW (nwin);
8119   condemned = NO;
8120   if (horizontal)
8121     pixel_length = NSWidth (r);
8122   else
8123     pixel_length = NSHeight (r);
8124   if (pixel_length == 0) pixel_length = 1;
8125   min_portion = 20 / pixel_length;
8127   frame = XFRAME (window->frame);
8128   if (FRAME_LIVE_P (frame))
8129     {
8130       int i;
8131       EmacsView *view = FRAME_NS_VIEW (frame);
8132       NSView *sview = [[view window] contentView];
8133       NSArray *subs = [sview subviews];
8135       /* disable optimization stopping redraw of other scrollbars */
8136       view->scrollbarsNeedingUpdate = 0;
8137       for (i =[subs count]-1; i >= 0; i--)
8138         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8139           view->scrollbarsNeedingUpdate++;
8140       [sview addSubview: self];
8141     }
8143 /*  [self setFrame: r]; */
8145   return self;
8149 - (void)setFrame: (NSRect)newRect
8151   NSTRACE ("[EmacsScroller setFrame:]");
8153 /*  block_input (); */
8154   if (horizontal)
8155     pixel_length = NSWidth (newRect);
8156   else
8157     pixel_length = NSHeight (newRect);
8158   if (pixel_length == 0) pixel_length = 1;
8159   min_portion = 20 / pixel_length;
8160   [super setFrame: newRect];
8161 /*  unblock_input (); */
8165 - (void)dealloc
8167   NSTRACE ("[EmacsScroller dealloc]");
8168   if (window)
8169     {
8170       if (horizontal)
8171         wset_horizontal_scroll_bar (window, Qnil);
8172       else
8173         wset_vertical_scroll_bar (window, Qnil);
8174     }
8175   window = 0;
8176   [super dealloc];
8180 - condemn
8182   NSTRACE ("[EmacsScroller condemn]");
8183   condemned =YES;
8184   return self;
8188 - reprieve
8190   NSTRACE ("[EmacsScroller reprieve]");
8191   condemned =NO;
8192   return self;
8196 -(bool)judge
8198   NSTRACE ("[EmacsScroller judge]");
8199   bool ret = condemned;
8200   if (condemned)
8201     {
8202       EmacsView *view;
8203       block_input ();
8204       /* ensure other scrollbar updates after deletion */
8205       view = (EmacsView *)FRAME_NS_VIEW (frame);
8206       if (view != nil)
8207         view->scrollbarsNeedingUpdate++;
8208       if (window)
8209         {
8210           if (horizontal)
8211             wset_horizontal_scroll_bar (window, Qnil);
8212           else
8213             wset_vertical_scroll_bar (window, Qnil);
8214         }
8215       window = 0;
8216       [self removeFromSuperview];
8217       [self release];
8218       unblock_input ();
8219     }
8220   return ret;
8224 - (void)resetCursorRects
8226   NSRect visible = [self visibleRect];
8227   NSTRACE ("[EmacsScroller resetCursorRects]");
8229   if (!NSIsEmptyRect (visible))
8230     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8231   [[NSCursor arrowCursor] setOnMouseEntered: YES];
8235 - (int) checkSamePosition: (int) position portion: (int) portion
8236                     whole: (int) whole
8238   return em_position ==position && em_portion ==portion && em_whole ==whole
8239     && portion != whole; /* needed for resize empty buf */
8243 - setPosition: (int)position portion: (int)portion whole: (int)whole
8245   NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8247   em_position = position;
8248   em_portion = portion;
8249   em_whole = whole;
8251   if (portion >= whole)
8252     {
8253 #ifdef NS_IMPL_COCOA
8254       [self setKnobProportion: 1.0];
8255       [self setDoubleValue: 1.0];
8256 #else
8257       [self setFloatValue: 0.0 knobProportion: 1.0];
8258 #endif
8259     }
8260   else
8261     {
8262       float pos;
8263       CGFloat por;
8264       portion = max ((float)whole*min_portion/pixel_length, portion);
8265       pos = (float)position / (whole - portion);
8266       por = (CGFloat)portion/whole;
8267 #ifdef NS_IMPL_COCOA
8268       [self setKnobProportion: por];
8269       [self setDoubleValue: pos];
8270 #else
8271       [self setFloatValue: pos knobProportion: por];
8272 #endif
8273     }
8275   return self;
8278 /* set up emacs_event */
8279 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8281   Lisp_Object win;
8283   NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8285   if (!emacs_event)
8286     return;
8288   emacs_event->part = last_hit_part;
8289   emacs_event->code = 0;
8290   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8291   XSETWINDOW (win, window);
8292   emacs_event->frame_or_window = win;
8293   emacs_event->timestamp = EV_TIMESTAMP (e);
8294   emacs_event->arg = Qnil;
8296   if (horizontal)
8297     {
8298       emacs_event->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
8299       XSETINT (emacs_event->x, em_whole * loc / pixel_length);
8300       XSETINT (emacs_event->y, em_whole);
8301     }
8302   else
8303     {
8304       emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8305       XSETINT (emacs_event->x, loc);
8306       XSETINT (emacs_event->y, pixel_length-20);
8307     }
8309   if (q_event_ptr)
8310     {
8311       n_emacs_events_pending++;
8312       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8313     }
8314   else
8315     hold_event (emacs_event);
8316   EVENT_INIT (*emacs_event);
8317   ns_send_appdefined (-1);
8321 /* called manually thru timer to implement repeated button action w/hold-down */
8322 - repeatScroll: (NSTimer *)scrollEntry
8324   NSEvent *e = [[self window] currentEvent];
8325   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
8326   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8328   NSTRACE ("[EmacsScroller repeatScroll:]");
8330   /* clear timer if need be */
8331   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8332     {
8333         [scroll_repeat_entry invalidate];
8334         [scroll_repeat_entry release];
8335         scroll_repeat_entry = nil;
8337         if (inKnob)
8338           return self;
8340         scroll_repeat_entry
8341           = [[NSTimer scheduledTimerWithTimeInterval:
8342                         SCROLL_BAR_CONTINUOUS_DELAY
8343                                             target: self
8344                                           selector: @selector (repeatScroll:)
8345                                           userInfo: 0
8346                                            repeats: YES]
8347               retain];
8348     }
8350   [self sendScrollEventAtLoc: 0 fromEvent: e];
8351   return self;
8355 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
8356    mouseDragged events without going into a modal loop. */
8357 - (void)mouseDown: (NSEvent *)e
8359   NSRect sr, kr;
8360   /* hitPart is only updated AFTER event is passed on */
8361   NSScrollerPart part = [self testPart: [e locationInWindow]];
8362   CGFloat inc = 0.0, loc, kloc, pos;
8363   int edge = 0;
8365   NSTRACE ("[EmacsScroller mouseDown:]");
8367   switch (part)
8368     {
8369     case NSScrollerDecrementPage:
8370       last_hit_part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle; break;
8371     case NSScrollerIncrementPage:
8372       last_hit_part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle; break;
8373     case NSScrollerDecrementLine:
8374       last_hit_part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow; break;
8375     case NSScrollerIncrementLine:
8376       last_hit_part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow; break;
8377     case NSScrollerKnob:
8378       last_hit_part = horizontal ? scroll_bar_horizontal_handle : scroll_bar_handle; break;
8379     case NSScrollerKnobSlot:  /* GNUstep-only */
8380       last_hit_part = scroll_bar_move_ratio; break;
8381     default:  /* NSScrollerNoPart? */
8382       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8383                (long) part);
8384       return;
8385     }
8387   if (part == NSScrollerKnob || part == NSScrollerKnobSlot)
8388     {
8389       /* handle, or on GNUstep possibly slot */
8390       NSEvent *fake_event;
8391       int length;
8393       /* compute float loc in slot and mouse offset on knob */
8394       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8395                       toView: nil];
8396       if (horizontal)
8397         {
8398           length = NSWidth (sr);
8399           loc = ([e locationInWindow].x - NSMinX (sr));
8400         }
8401       else
8402         {
8403           length = NSHeight (sr);
8404           loc = length - ([e locationInWindow].y - NSMinY (sr));
8405         }
8407       if (loc <= 0.0)
8408         {
8409           loc = 0.0;
8410           edge = -1;
8411         }
8412       else if (loc >= length)
8413         {
8414           loc = length;
8415           edge = 1;
8416         }
8418       if (edge)
8419         kloc = 0.5 * edge;
8420       else
8421         {
8422           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8423                           toView: nil];
8424           if (horizontal)
8425             kloc = ([e locationInWindow].x - NSMinX (kr));
8426           else
8427             kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8428         }
8429       last_mouse_offset = kloc;
8431       if (part != NSScrollerKnob)
8432         /* this is a slot click on GNUstep: go straight there */
8433         pos = loc;
8435       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8436       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8437                                       location: [e locationInWindow]
8438                                  modifierFlags: [e modifierFlags]
8439                                      timestamp: [e timestamp]
8440                                   windowNumber: [e windowNumber]
8441                                        context: [e context]
8442                                    eventNumber: [e eventNumber]
8443                                     clickCount: [e clickCount]
8444                                       pressure: [e pressure]];
8445       [super mouseUp: fake_event];
8446     }
8447   else
8448     {
8449       pos = 0;      /* ignored */
8451       /* set a timer to repeat, as we can't let superclass do this modally */
8452       scroll_repeat_entry
8453         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8454                                             target: self
8455                                           selector: @selector (repeatScroll:)
8456                                           userInfo: 0
8457                                            repeats: YES]
8458             retain];
8459     }
8461   if (part != NSScrollerKnob)
8462     [self sendScrollEventAtLoc: pos fromEvent: e];
8466 /* Called as we manually track scroller drags, rather than superclass. */
8467 - (void)mouseDragged: (NSEvent *)e
8469     NSRect sr;
8470     double loc, pos;
8471     int length;
8473     NSTRACE ("[EmacsScroller mouseDragged:]");
8475       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8476                       toView: nil];
8478       if (horizontal)
8479         {
8480           length = NSWidth (sr);
8481           loc = ([e locationInWindow].x - NSMinX (sr));
8482         }
8483       else
8484         {
8485           length = NSHeight (sr);
8486           loc = length - ([e locationInWindow].y - NSMinY (sr));
8487         }
8489       if (loc <= 0.0)
8490         {
8491           loc = 0.0;
8492         }
8493       else if (loc >= length + last_mouse_offset)
8494         {
8495           loc = length + last_mouse_offset;
8496         }
8498       pos = (loc - last_mouse_offset);
8499       [self sendScrollEventAtLoc: pos fromEvent: e];
8503 - (void)mouseUp: (NSEvent *)e
8505   NSTRACE ("[EmacsScroller mouseUp:]");
8507   if (scroll_repeat_entry)
8508     {
8509       [scroll_repeat_entry invalidate];
8510       [scroll_repeat_entry release];
8511       scroll_repeat_entry = nil;
8512     }
8513   last_hit_part = scroll_bar_above_handle;
8517 /* treat scrollwheel events in the bar as though they were in the main window */
8518 - (void) scrollWheel: (NSEvent *)theEvent
8520   NSTRACE ("[EmacsScroller scrollWheel:]");
8522   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8523   [view mouseDown: theEvent];
8526 @end  /* EmacsScroller */
8529 #ifdef NS_IMPL_GNUSTEP
8530 /* Dummy class to get rid of startup warnings.  */
8531 @implementation EmacsDocument
8533 @end
8534 #endif
8537 /* ==========================================================================
8539    Font-related functions; these used to be in nsfaces.m
8541    ========================================================================== */
8544 Lisp_Object
8545 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8547   struct font *font = XFONT_OBJECT (font_object);
8548   EmacsView *view = FRAME_NS_VIEW (f);
8549   int font_ascent, font_descent;
8551   if (fontset < 0)
8552     fontset = fontset_from_font (font_object);
8553   FRAME_FONTSET (f) = fontset;
8555   if (FRAME_FONT (f) == font)
8556     /* This font is already set in frame F.  There's nothing more to
8557        do.  */
8558     return font_object;
8560   FRAME_FONT (f) = font;
8562   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8563   FRAME_COLUMN_WIDTH (f) = font->average_width;
8564   get_font_ascent_descent (font, &font_ascent, &font_descent);
8565   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8567   /* Compute the scroll bar width in character columns.  */
8568   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8569     {
8570       int wid = FRAME_COLUMN_WIDTH (f);
8571       FRAME_CONFIG_SCROLL_BAR_COLS (f)
8572         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8573     }
8574   else
8575     {
8576       int wid = FRAME_COLUMN_WIDTH (f);
8577       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8578     }
8580   /* Compute the scroll bar height in character lines.  */
8581   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8582     {
8583       int height = FRAME_LINE_HEIGHT (f);
8584       FRAME_CONFIG_SCROLL_BAR_LINES (f)
8585         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8586     }
8587   else
8588     {
8589       int height = FRAME_LINE_HEIGHT (f);
8590       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8591     }
8593   /* Now make the frame display the given font.  */
8594   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8595     adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8596                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8597                        false, Qfont);
8599   return font_object;
8603 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8604 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8605          in 1.43. */
8607 const char *
8608 ns_xlfd_to_fontname (const char *xlfd)
8609 /* --------------------------------------------------------------------------
8610     Convert an X font name (XLFD) to an NS font name.
8611     Only family is used.
8612     The string returned is temporarily allocated.
8613    -------------------------------------------------------------------------- */
8615   char *name = xmalloc (180);
8616   int i, len;
8617   const char *ret;
8619   if (!strncmp (xlfd, "--", 2))
8620     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8621   else
8622     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8624   /* stopgap for malformed XLFD input */
8625   if (strlen (name) == 0)
8626     strcpy (name, "Monaco");
8628   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8629      also uppercase after '-' or ' ' */
8630   name[0] = c_toupper (name[0]);
8631   for (len =strlen (name), i =0; i<len; i++)
8632     {
8633       if (name[i] == '$')
8634         {
8635           name[i] = '-';
8636           if (i+1<len)
8637             name[i+1] = c_toupper (name[i+1]);
8638         }
8639       else if (name[i] == '_')
8640         {
8641           name[i] = ' ';
8642           if (i+1<len)
8643             name[i+1] = c_toupper (name[i+1]);
8644         }
8645     }
8646 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
8647   ret = [[NSString stringWithUTF8String: name] UTF8String];
8648   xfree (name);
8649   return ret;
8653 void
8654 syms_of_nsterm (void)
8656   NSTRACE ("syms_of_nsterm");
8658   ns_antialias_threshold = 10.0;
8660   /* from 23+ we need to tell emacs what modifiers there are.. */
8661   DEFSYM (Qmodifier_value, "modifier-value");
8662   DEFSYM (Qalt, "alt");
8663   DEFSYM (Qhyper, "hyper");
8664   DEFSYM (Qmeta, "meta");
8665   DEFSYM (Qsuper, "super");
8666   DEFSYM (Qcontrol, "control");
8667   DEFSYM (QUTF8_STRING, "UTF8_STRING");
8669   DEFSYM (Qfile, "file");
8670   DEFSYM (Qurl, "url");
8672   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8673   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8674   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8675   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8676   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8678   DEFVAR_LISP ("ns-input-file", ns_input_file,
8679               "The file specified in the last NS event.");
8680   ns_input_file =Qnil;
8682   DEFVAR_LISP ("ns-working-text", ns_working_text,
8683               "String for visualizing working composition sequence.");
8684   ns_working_text =Qnil;
8686   DEFVAR_LISP ("ns-input-font", ns_input_font,
8687               "The font specified in the last NS event.");
8688   ns_input_font =Qnil;
8690   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8691               "The fontsize specified in the last NS event.");
8692   ns_input_fontsize =Qnil;
8694   DEFVAR_LISP ("ns-input-line", ns_input_line,
8695                "The line specified in the last NS event.");
8696   ns_input_line =Qnil;
8698   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8699                "The service name specified in the last NS event.");
8700   ns_input_spi_name =Qnil;
8702   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8703                "The service argument specified in the last NS event.");
8704   ns_input_spi_arg =Qnil;
8706   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8707                "This variable describes the behavior of the alternate or option key.\n\
8708 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8709 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8710 at all, allowing it to be used at a lower level for accented character entry.");
8711   ns_alternate_modifier = Qmeta;
8713   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8714                "This variable describes the behavior of the right alternate or option key.\n\
8715 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8716 Set to left means be the same key as `ns-alternate-modifier'.\n\
8717 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8718 at all, allowing it to be used at a lower level for accented character entry.");
8719   ns_right_alternate_modifier = Qleft;
8721   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8722                "This variable describes the behavior of the command key.\n\
8723 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8724   ns_command_modifier = Qsuper;
8726   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8727                "This variable describes the behavior of the right command key.\n\
8728 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8729 Set to left means be the same key as `ns-command-modifier'.\n\
8730 Set to none means that the command / option key is not interpreted by Emacs\n\
8731 at all, allowing it to be used at a lower level for accented character entry.");
8732   ns_right_command_modifier = Qleft;
8734   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8735                "This variable describes the behavior of the control key.\n\
8736 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8737   ns_control_modifier = Qcontrol;
8739   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8740                "This variable describes the behavior of the right control key.\n\
8741 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8742 Set to left means be the same key as `ns-control-modifier'.\n\
8743 Set to none means that the control / option key is not interpreted by Emacs\n\
8744 at all, allowing it to be used at a lower level for accented character entry.");
8745   ns_right_control_modifier = Qleft;
8747   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8748                "This variable describes the behavior of the function key (on laptops).\n\
8749 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8750 Set to none means that the function key is not interpreted by Emacs at all,\n\
8751 allowing it to be used at a lower level for accented character entry.");
8752   ns_function_modifier = Qnone;
8754   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8755                "Non-nil (the default) means to render text antialiased.");
8756   ns_antialias_text = Qt;
8758   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8759                "Whether to confirm application quit using dialog.");
8760   ns_confirm_quit = Qnil;
8762   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8763                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8764 Only works on OSX 10.6 or later.  */);
8765   ns_auto_hide_menu_bar = Qnil;
8767   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8768      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8769 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
8770 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
8771 Default is t for OSX >= 10.7, nil otherwise.  */);
8772 #ifdef HAVE_NATIVE_FS
8773   ns_use_native_fullscreen = YES;
8774 #else
8775   ns_use_native_fullscreen = NO;
8776 #endif
8777   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8779   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8780      doc: /*Non-nil means use animation on non-native fullscreen.
8781 For native fullscreen, this does nothing.
8782 Default is nil.  */);
8783   ns_use_fullscreen_animation = NO;
8785   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8786      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8787 Note that this does not apply to images.
8788 This variable is ignored on OSX < 10.7 and GNUstep.  */);
8789   ns_use_srgb_colorspace = YES;
8791   /* TODO: move to common code */
8792   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8793                doc: /* Which toolkit scroll bars Emacs uses, if any.
8794 A value of nil means Emacs doesn't use toolkit scroll bars.
8795 With the X Window system, the value is a symbol describing the
8796 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
8797 With MS Windows or Nextstep, the value is t.  */);
8798   Vx_toolkit_scroll_bars = Qt;
8800   DEFVAR_BOOL ("x-use-underline-position-properties",
8801                x_use_underline_position_properties,
8802      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8803 A value of nil means ignore them.  If you encounter fonts with bogus
8804 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8805 to 4.1, set this to nil. */);
8806   x_use_underline_position_properties = 0;
8808   DEFVAR_BOOL ("x-underline-at-descent-line",
8809                x_underline_at_descent_line,
8810      doc: /* Non-nil means to draw the underline at the same place as the descent line.
8811 A value of nil means to draw the underline according to the value of the
8812 variable `x-use-underline-position-properties', which is usually at the
8813 baseline level.  The default value is nil.  */);
8814   x_underline_at_descent_line = 0;
8816   /* Tell Emacs about this window system.  */
8817   Fprovide (Qns, Qnil);
8819   DEFSYM (Qcocoa, "cocoa");
8820   DEFSYM (Qgnustep, "gnustep");
8822 #ifdef NS_IMPL_COCOA
8823   Fprovide (Qcocoa, Qnil);
8824   syms_of_macfont ();
8825 #else
8826   Fprovide (Qgnustep, Qnil);
8827   syms_of_nsfont ();
8828 #endif