Fix problems found by static checking --with-ns
[emacs.git] / src / nsterm.m
blob1b44a73cd8bffbe77d68bee842cb72264bb16cac
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
71 static EmacsMenu *dockMenu;
72 #ifdef NS_IMPL_COCOA
73 static EmacsMenu *mainMenu;
74 #endif
76 /* ==========================================================================
78    NSTRACE, Trace support.
80    ========================================================================== */
82 #if NSTRACE_ENABLED
84 /* The following use "volatile" since they can be accessed from
85    parallel threads. */
86 volatile int nstrace_num = 0;
87 volatile int nstrace_depth = 0;
89 /* When 0, no trace is emitted.  This is used by NSTRACE_WHEN and
90    NSTRACE_UNLESS to silence functions called.
92    TODO: This should really be a thread-local variable, to avoid that
93    a function with disabled trace thread silence trace output in
94    another.  However, in practice this seldom is a problem. */
95 volatile int nstrace_enabled_global = 1;
97 /* Called when nstrace_enabled goes out of scope. */
98 void nstrace_leave(int * pointer_to_nstrace_enabled)
100   if (*pointer_to_nstrace_enabled)
101     {
102       --nstrace_depth;
103     }
107 /* Called when nstrace_saved_enabled_global goes out of scope. */
108 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
110   nstrace_enabled_global = *pointer_to_saved_enabled_global;
114 char const * nstrace_fullscreen_type_name (int fs_type)
116   switch (fs_type)
117     {
118     case -1:                   return "-1";
119     case FULLSCREEN_NONE:      return "FULLSCREEN_NONE";
120     case FULLSCREEN_WIDTH:     return "FULLSCREEN_WIDTH";
121     case FULLSCREEN_HEIGHT:    return "FULLSCREEN_HEIGHT";
122     case FULLSCREEN_BOTH:      return "FULLSCREEN_BOTH";
123     case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
124     default:                   return "FULLSCREEN_?????";
125     }
127 #endif
130 /* ==========================================================================
132    NSColor, EmacsColor category.
134    ========================================================================== */
135 @implementation NSColor (EmacsColor)
136 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
137                          blue:(CGFloat)blue alpha:(CGFloat)alpha
139 #ifdef NS_IMPL_COCOA
140 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
141   if (ns_use_srgb_colorspace)
142       return [NSColor colorWithSRGBRed: red
143                                  green: green
144                                   blue: blue
145                                  alpha: alpha];
146 #endif
147 #endif
148   return [NSColor colorWithCalibratedRed: red
149                                    green: green
150                                     blue: blue
151                                    alpha: alpha];
154 - (NSColor *)colorUsingDefaultColorSpace
156 #ifdef NS_IMPL_COCOA
157 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
158   if (ns_use_srgb_colorspace)
159     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
160 #endif
161 #endif
162   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
165 @end
167 /* ==========================================================================
169     Local declarations
171    ========================================================================== */
173 /* Convert a symbol indexed with an NSxxx value to a value as defined
174    in keyboard.c (lispy_function_key). I hope this is a correct way
175    of doing things... */
176 static unsigned convert_ns_to_X_keysym[] =
178   NSHomeFunctionKey,            0x50,
179   NSLeftArrowFunctionKey,       0x51,
180   NSUpArrowFunctionKey,         0x52,
181   NSRightArrowFunctionKey,      0x53,
182   NSDownArrowFunctionKey,       0x54,
183   NSPageUpFunctionKey,          0x55,
184   NSPageDownFunctionKey,        0x56,
185   NSEndFunctionKey,             0x57,
186   NSBeginFunctionKey,           0x58,
187   NSSelectFunctionKey,          0x60,
188   NSPrintFunctionKey,           0x61,
189   NSClearLineFunctionKey,       0x0B,
190   NSExecuteFunctionKey,         0x62,
191   NSInsertFunctionKey,          0x63,
192   NSUndoFunctionKey,            0x65,
193   NSRedoFunctionKey,            0x66,
194   NSMenuFunctionKey,            0x67,
195   NSFindFunctionKey,            0x68,
196   NSHelpFunctionKey,            0x6A,
197   NSBreakFunctionKey,           0x6B,
199   NSF1FunctionKey,              0xBE,
200   NSF2FunctionKey,              0xBF,
201   NSF3FunctionKey,              0xC0,
202   NSF4FunctionKey,              0xC1,
203   NSF5FunctionKey,              0xC2,
204   NSF6FunctionKey,              0xC3,
205   NSF7FunctionKey,              0xC4,
206   NSF8FunctionKey,              0xC5,
207   NSF9FunctionKey,              0xC6,
208   NSF10FunctionKey,             0xC7,
209   NSF11FunctionKey,             0xC8,
210   NSF12FunctionKey,             0xC9,
211   NSF13FunctionKey,             0xCA,
212   NSF14FunctionKey,             0xCB,
213   NSF15FunctionKey,             0xCC,
214   NSF16FunctionKey,             0xCD,
215   NSF17FunctionKey,             0xCE,
216   NSF18FunctionKey,             0xCF,
217   NSF19FunctionKey,             0xD0,
218   NSF20FunctionKey,             0xD1,
219   NSF21FunctionKey,             0xD2,
220   NSF22FunctionKey,             0xD3,
221   NSF23FunctionKey,             0xD4,
222   NSF24FunctionKey,             0xD5,
224   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
225   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
226   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
228   NSTabCharacter,               0x09,
229   0x19,                         0x09,  /* left tab->regular since pass shift */
230   NSCarriageReturnCharacter,    0x0D,
231   NSNewlineCharacter,           0x0D,
232   NSEnterCharacter,             0x8D,
234   0x41|NSEventModifierFlagNumericPad,   0xAE,  /* KP_Decimal */
235   0x43|NSEventModifierFlagNumericPad,   0xAA,  /* KP_Multiply */
236   0x45|NSEventModifierFlagNumericPad,   0xAB,  /* KP_Add */
237   0x4B|NSEventModifierFlagNumericPad,   0xAF,  /* KP_Divide */
238   0x4E|NSEventModifierFlagNumericPad,   0xAD,  /* KP_Subtract */
239   0x51|NSEventModifierFlagNumericPad,   0xBD,  /* KP_Equal */
240   0x52|NSEventModifierFlagNumericPad,   0xB0,  /* KP_0 */
241   0x53|NSEventModifierFlagNumericPad,   0xB1,  /* KP_1 */
242   0x54|NSEventModifierFlagNumericPad,   0xB2,  /* KP_2 */
243   0x55|NSEventModifierFlagNumericPad,   0xB3,  /* KP_3 */
244   0x56|NSEventModifierFlagNumericPad,   0xB4,  /* KP_4 */
245   0x57|NSEventModifierFlagNumericPad,   0xB5,  /* KP_5 */
246   0x58|NSEventModifierFlagNumericPad,   0xB6,  /* KP_6 */
247   0x59|NSEventModifierFlagNumericPad,   0xB7,  /* KP_7 */
248   0x5B|NSEventModifierFlagNumericPad,   0xB8,  /* KP_8 */
249   0x5C|NSEventModifierFlagNumericPad,   0xB9,  /* KP_9 */
251   0x1B,                         0x1B   /* escape */
254 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
255    the maximum font size to NOT antialias.  On GNUstep there is currently
256    no way to control this behavior. */
257 float ns_antialias_threshold;
259 NSArray *ns_send_types = 0, *ns_return_types = 0;
260 static NSArray *ns_drag_types = 0;
261 NSString *ns_app_name = @"Emacs";  /* default changed later */
263 /* Display variables */
264 struct ns_display_info *x_display_list; /* Chain of existing displays */
265 long context_menu_value = 0;
267 /* display update */
268 static struct frame *ns_updating_frame;
269 static NSView *focus_view = NULL;
270 static int ns_window_num = 0;
271 #ifdef NS_IMPL_GNUSTEP
272 static NSRect uRect;            // TODO: This is dead, remove it?
273 #endif
274 static BOOL gsaved = NO;
275 static BOOL ns_fake_keydown = NO;
276 #ifdef NS_IMPL_COCOA
277 static BOOL ns_menu_bar_is_hidden = NO;
278 #endif
279 /*static int debug_lock = 0; */
281 /* event loop */
282 static BOOL send_appdefined = YES;
283 #define NO_APPDEFINED_DATA (-8)
284 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
285 static NSTimer *timed_entry = 0;
286 static NSTimer *scroll_repeat_entry = nil;
287 static fd_set select_readfds, select_writefds;
288 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
289 static int select_nfds = 0, select_valid = 0;
290 static struct timespec select_timeout = { 0, 0 };
291 static int selfds[2] = { -1, -1 };
292 static pthread_mutex_t select_mutex;
293 static int apploopnr = 0;
294 static NSAutoreleasePool *outerpool;
295 static struct input_event *emacs_event = NULL;
296 static struct input_event *q_event_ptr = NULL;
297 static int n_emacs_events_pending = 0;
298 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
299   *ns_pending_service_args;
300 static BOOL ns_do_open_file = NO;
301 static BOOL ns_last_use_native_fullscreen;
303 /* Non-zero means that a HELP_EVENT has been generated since Emacs
304    start.  */
306 static BOOL any_help_event_p = NO;
308 static struct {
309   struct input_event *q;
310   int nr, cap;
311 } hold_event_q = {
312   NULL, 0, 0
315 static NSString *represented_filename = nil;
316 static struct frame *represented_frame = 0;
318 #ifdef NS_IMPL_COCOA
320  * State for pending menu activation:
321  * MENU_NONE     Normal state
322  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
323  *               run lisp to update the menu.
324  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
325  *               will open.
326  */
327 #define MENU_NONE 0
328 #define MENU_PENDING 1
329 #define MENU_OPENING 2
330 static int menu_will_open_state = MENU_NONE;
332 /* Saved position for menu click.  */
333 static CGPoint menu_mouse_point;
334 #endif
336 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
337 #define NS_FUNCTION_KEY_MASK 0x800000
338 #define NSLeftControlKeyMask    (0x000001 | NSEventModifierFlagControl)
339 #define NSRightControlKeyMask   (0x002000 | NSEventModifierFlagControl)
340 #define NSLeftCommandKeyMask    (0x000008 | NSEventModifierFlagCommand)
341 #define NSRightCommandKeyMask   (0x000010 | NSEventModifierFlagCommand)
342 #define NSLeftAlternateKeyMask  (0x000020 | NSEventModifierFlagOption)
343 #define NSRightAlternateKeyMask (0x000040 | NSEventModifierFlagOption)
344 #define EV_MODIFIERS2(flags)                          \
345     (((flags & NSEventModifierFlagHelp) ?           \
346            hyper_modifier : 0)                        \
347      | (!EQ (ns_right_alternate_modifier, Qleft) && \
348         ((flags & NSRightAlternateKeyMask) \
349          == NSRightAlternateKeyMask) ? \
350            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
351      | ((flags & NSEventModifierFlagOption) ?                 \
352            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
353      | ((flags & NSEventModifierFlagShift) ?     \
354            shift_modifier : 0)                        \
355      | (!EQ (ns_right_control_modifier, Qleft) && \
356         ((flags & NSRightControlKeyMask) \
357          == NSRightControlKeyMask) ? \
358            parse_solitary_modifier (ns_right_control_modifier) : 0) \
359      | ((flags & NSEventModifierFlagControl) ?      \
360            parse_solitary_modifier (ns_control_modifier) : 0)     \
361      | ((flags & NS_FUNCTION_KEY_MASK) ?  \
362            parse_solitary_modifier (ns_function_modifier) : 0)    \
363      | (!EQ (ns_right_command_modifier, Qleft) && \
364         ((flags & NSRightCommandKeyMask) \
365          == NSRightCommandKeyMask) ? \
366            parse_solitary_modifier (ns_right_command_modifier) : 0) \
367      | ((flags & NSEventModifierFlagCommand) ?      \
368            parse_solitary_modifier (ns_command_modifier):0))
369 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
371 #define EV_UDMODIFIERS(e)                                      \
372     ((([e type] == NSEventTypeLeftMouseDown) ? down_modifier : 0)       \
373      | (([e type] == NSEventTypeRightMouseDown) ? down_modifier : 0)    \
374      | (([e type] == NSEventTypeOtherMouseDown) ? down_modifier : 0)    \
375      | (([e type] == NSEventTypeLeftMouseDragged) ? down_modifier : 0)  \
376      | (([e type] == NSEventTypeRightMouseDragged) ? down_modifier : 0) \
377      | (([e type] == NSEventTypeOtherMouseDragged) ? down_modifier : 0) \
378      | (([e type] == NSEventTypeLeftMouseUp)   ? up_modifier   : 0)     \
379      | (([e type] == NSEventTypeRightMouseUp)   ? up_modifier   : 0)    \
380      | (([e type] == NSEventTypeOtherMouseUp)   ? up_modifier   : 0))
382 #define EV_BUTTON(e)                                                         \
383     ((([e type] == NSEventTypeLeftMouseDown) || ([e type] == NSEventTypeLeftMouseUp)) ? 0 :    \
384       (([e type] == NSEventTypeRightMouseDown) || ([e type] == NSEventTypeRightMouseUp)) ? 2 : \
385      [e buttonNumber] - 1)
387 /* Convert the time field to a timestamp in milliseconds. */
388 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
390 /* This is a piece of code which is common to all the event handling
391    methods.  Maybe it should even be a function.  */
392 #define EV_TRAILER(e)                                                   \
393   {                                                                     \
394     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
395     EV_TRAILER2 (e);                                                    \
396   }
398 #define EV_TRAILER2(e)                                                  \
399   {                                                                     \
400       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
401       if (q_event_ptr)                                                  \
402         {                                                               \
403           Lisp_Object tem = Vinhibit_quit;                              \
404           Vinhibit_quit = Qt;                                           \
405           n_emacs_events_pending++;                                     \
406           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
407           Vinhibit_quit = tem;                                          \
408         }                                                               \
409       else                                                              \
410         hold_event (emacs_event);                                       \
411       EVENT_INIT (*emacs_event);                                        \
412       ns_send_appdefined (-1);                                          \
413     }
415 /* TODO: get rid of need for these forward declarations */
416 static void ns_condemn_scroll_bars (struct frame *f);
417 static void ns_judge_scroll_bars (struct frame *f);
420 /* ==========================================================================
422     Utilities
424    ========================================================================== */
426 void
427 ns_set_represented_filename (NSString* fstr, struct frame *f)
429   represented_filename = [fstr retain];
430   represented_frame = f;
433 void
434 ns_init_events (struct input_event* ev)
436   EVENT_INIT (*ev);
437   emacs_event = ev;
440 void
441 ns_finish_events (void)
443   emacs_event = NULL;
446 static void
447 hold_event (struct input_event *event)
449   if (hold_event_q.nr == hold_event_q.cap)
450     {
451       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
452       else hold_event_q.cap *= 2;
453       hold_event_q.q =
454         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
455     }
457   hold_event_q.q[hold_event_q.nr++] = *event;
458   /* Make sure ns_read_socket is called, i.e. we have input.  */
459   raise (SIGIO);
460   send_appdefined = YES;
463 static Lisp_Object
464 append2 (Lisp_Object list, Lisp_Object item)
465 /* --------------------------------------------------------------------------
466    Utility to append to a list
467    -------------------------------------------------------------------------- */
469   return CALLN (Fnconc, list, list1 (item));
473 const char *
474 ns_etc_directory (void)
475 /* If running as a self-contained app bundle, return as a string the
476    filename of the etc directory, if present; else nil.  */
478   NSBundle *bundle = [NSBundle mainBundle];
479   NSString *resourceDir = [bundle resourcePath];
480   NSString *resourcePath;
481   NSFileManager *fileManager = [NSFileManager defaultManager];
482   BOOL isDir;
484   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
485   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
486     {
487       if (isDir) return [resourcePath UTF8String];
488     }
489   return NULL;
493 const char *
494 ns_exec_path (void)
495 /* If running as a self-contained app bundle, return as a path string
496    the filenames of the libexec and bin directories, ie libexec:bin.
497    Otherwise, return nil.
498    Normally, Emacs does not add its own bin/ directory to the PATH.
499    However, a self-contained NS build has a different layout, with
500    bin/ and libexec/ subdirectories in the directory that contains
501    Emacs.app itself.
502    We put libexec first, because init_callproc_1 uses the first
503    element to initialize exec-directory.  An alternative would be
504    for init_callproc to check for invocation-directory/libexec.
507   NSBundle *bundle = [NSBundle mainBundle];
508   NSString *resourceDir = [bundle resourcePath];
509   NSString *binDir = [bundle bundlePath];
510   NSString *resourcePath, *resourcePaths;
511   NSRange range;
512   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
513   NSFileManager *fileManager = [NSFileManager defaultManager];
514   NSArray *paths;
515   NSEnumerator *pathEnum;
516   BOOL isDir;
518   range = [resourceDir rangeOfString: @"Contents"];
519   if (range.location != NSNotFound)
520     {
521       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
522 #ifdef NS_IMPL_COCOA
523       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
524 #endif
525     }
527   paths = [binDir stringsByAppendingPaths:
528                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
529   pathEnum = [paths objectEnumerator];
530   resourcePaths = @"";
532   while ((resourcePath = [pathEnum nextObject]))
533     {
534       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
535         if (isDir)
536           {
537             if ([resourcePaths length] > 0)
538               resourcePaths
539                 = [resourcePaths stringByAppendingString: pathSeparator];
540             resourcePaths
541               = [resourcePaths stringByAppendingString: resourcePath];
542           }
543     }
544   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
546   return NULL;
550 const char *
551 ns_load_path (void)
552 /* If running as a self-contained app bundle, return as a path string
553    the filenames of the site-lisp and lisp directories.
554    Ie, site-lisp:lisp.  Otherwise, return nil.  */
556   NSBundle *bundle = [NSBundle mainBundle];
557   NSString *resourceDir = [bundle resourcePath];
558   NSString *resourcePath, *resourcePaths;
559   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
560   NSFileManager *fileManager = [NSFileManager defaultManager];
561   BOOL isDir;
562   NSArray *paths = [resourceDir stringsByAppendingPaths:
563                               [NSArray arrayWithObjects:
564                                          @"site-lisp", @"lisp", nil]];
565   NSEnumerator *pathEnum = [paths objectEnumerator];
566   resourcePaths = @"";
568   /* Hack to skip site-lisp.  */
569   if (no_site_lisp) resourcePath = [pathEnum nextObject];
571   while ((resourcePath = [pathEnum nextObject]))
572     {
573       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
574         if (isDir)
575           {
576             if ([resourcePaths length] > 0)
577               resourcePaths
578                 = [resourcePaths stringByAppendingString: pathSeparator];
579             resourcePaths
580               = [resourcePaths stringByAppendingString: resourcePath];
581           }
582     }
583   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
585   return NULL;
589 void
590 ns_init_locale (void)
591 /* OS X doesn't set any environment variables for the locale when run
592    from the GUI. Get the locale from the OS and set LANG. */
594   NSLocale *locale = [NSLocale currentLocale];
596   NSTRACE ("ns_init_locale");
598   @try
599     {
600       /* It seems OS X should probably use UTF-8 everywhere.
601          'localeIdentifier' does not specify the encoding, and I can't
602          find any way to get the OS to tell us which encoding to use,
603          so hard-code '.UTF-8'. */
604       NSString *localeID = [NSString stringWithFormat:@"%@.UTF-8",
605                                      [locale localeIdentifier]];
607       /* Set LANG to locale, but not if LANG is already set. */
608       setenv("LANG", [localeID UTF8String], 0);
609     }
610   @catch (NSException *e)
611     {
612       NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
613     }
617 void
618 ns_release_object (void *obj)
619 /* --------------------------------------------------------------------------
620     Release an object (callable from C)
621    -------------------------------------------------------------------------- */
623     [(id)obj release];
627 void
628 ns_retain_object (void *obj)
629 /* --------------------------------------------------------------------------
630     Retain an object (callable from C)
631    -------------------------------------------------------------------------- */
633     [(id)obj retain];
637 void *
638 ns_alloc_autorelease_pool (void)
639 /* --------------------------------------------------------------------------
640      Allocate a pool for temporary objects (callable from C)
641    -------------------------------------------------------------------------- */
643   return [[NSAutoreleasePool alloc] init];
647 void
648 ns_release_autorelease_pool (void *pool)
649 /* --------------------------------------------------------------------------
650      Free a pool and temporary objects it refers to (callable from C)
651    -------------------------------------------------------------------------- */
653   ns_release_object (pool);
657 static BOOL
658 ns_menu_bar_should_be_hidden (void)
659 /* True, if the menu bar should be hidden.  */
661   return !NILP (ns_auto_hide_menu_bar)
662     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
666 struct EmacsMargins
668   CGFloat top;
669   CGFloat bottom;
670   CGFloat left;
671   CGFloat right;
675 static struct EmacsMargins
676 ns_screen_margins (NSScreen *screen)
677 /* The parts of SCREEN used by the operating system.  */
679   NSTRACE ("ns_screen_margins");
681   struct EmacsMargins margins;
683   NSRect screenFrame = [screen frame];
684   NSRect screenVisibleFrame = [screen visibleFrame];
686   /* Sometimes, visibleFrame isn't up-to-date with respect to a hidden
687      menu bar, check this explicitly.  */
688   if (ns_menu_bar_should_be_hidden())
689     {
690       margins.top = 0;
691     }
692   else
693     {
694       CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
695       CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
696                                  + screenVisibleFrame.size.height);
698       margins.top = frameTop - visibleFrameTop;
699     }
701   {
702     CGFloat frameRight = screenFrame.origin.x + screenFrame.size.width;
703     CGFloat visibleFrameRight = (screenVisibleFrame.origin.x
704                                  + screenVisibleFrame.size.width);
705     margins.right = frameRight - visibleFrameRight;
706   }
708   margins.bottom = screenVisibleFrame.origin.y - screenFrame.origin.y;
709   margins.left   = screenVisibleFrame.origin.x - screenFrame.origin.x;
711   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
712                margins.left,
713                margins.right,
714                margins.top,
715                margins.bottom);
717   return margins;
721 /* A screen margin between 1 and DOCK_IGNORE_LIMIT (inclusive) is
722    assumed to contain a hidden dock.  OS X currently use 4 pixels for
723    this, however, to be future compatible, a larger value is used.  */
724 #define DOCK_IGNORE_LIMIT 6
726 static struct EmacsMargins
727 ns_screen_margins_ignoring_hidden_dock (NSScreen *screen)
728 /* The parts of SCREEN used by the operating system, excluding the parts
729 reserved for an hidden dock.  */
731   NSTRACE ("ns_screen_margins_ignoring_hidden_dock");
733   struct EmacsMargins margins = ns_screen_margins(screen);
735   /* OS X (currently) reserved 4 pixels along the edge where a hidden
736      dock is located.  Unfortunately, it's not possible to find the
737      location and information about if the dock is hidden.  Instead,
738      it is assumed that if the margin of an edge is less than
739      DOCK_IGNORE_LIMIT, it contains a hidden dock.  */
740   if (margins.left <= DOCK_IGNORE_LIMIT)
741     {
742       margins.left = 0;
743     }
744   if (margins.right <= DOCK_IGNORE_LIMIT)
745     {
746       margins.right = 0;
747     }
748   if (margins.top <= DOCK_IGNORE_LIMIT)
749     {
750       margins.top = 0;
751     }
752   /* Note: This doesn't occur in current versions of OS X, but
753      included for completeness and future compatibility.  */
754   if (margins.bottom <= DOCK_IGNORE_LIMIT)
755     {
756       margins.bottom = 0;
757     }
759   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
760                margins.left,
761                margins.right,
762                margins.top,
763                margins.bottom);
765   return margins;
769 static CGFloat
770 ns_menu_bar_height (NSScreen *screen)
771 /* The height of the menu bar, if visible.
773    Note: Don't use this when fullscreen is enabled -- the screen
774    sometimes includes, sometimes excludes the menu bar area.  */
776   struct EmacsMargins margins = ns_screen_margins(screen);
778   CGFloat res = margins.top;
780   NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
782   return res;
786 /* ==========================================================================
788     Focus (clipping) and screen update
790    ========================================================================== */
793 // Window constraining
794 // -------------------
796 // To ensure that the windows are not placed under the menu bar, they
797 // are typically moved by the call-back constrainFrameRect. However,
798 // by overriding it, it's possible to inhibit this, leaving the window
799 // in it's original position.
801 // It's possible to hide the menu bar. However, technically, it's only
802 // possible to hide it when the application is active. To ensure that
803 // this work properly, the menu bar and window constraining are
804 // deferred until the application becomes active.
806 // Even though it's not possible to manually move a window above the
807 // top of the screen, it is allowed if it's done programmatically,
808 // when the menu is hidden. This allows the editable area to cover the
809 // full screen height.
811 // Test cases
812 // ----------
814 // Use the following extra files:
816 //    init.el:
817 //       ;; Hide menu and place frame slightly above the top of the screen.
818 //       (setq ns-auto-hide-menu-bar t)
819 //       (set-frame-position (selected-frame) 0 -20)
821 // Test 1:
823 //    emacs -Q -l init.el
825 //    Result: No menu bar, and the title bar should be above the screen.
827 // Test 2:
829 //    emacs -Q
831 //    Result: Menu bar visible, frame placed immediately below the menu.
834 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
836   NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
837              NSTRACE_ARG_RECT (frameRect));
839   // --------------------
840   // Collect information about the screen the frame is covering.
841   //
843   NSArray *screens = [NSScreen screens];
844   NSUInteger nr_screens = [screens count];
846   int i;
848   // The height of the menu bar, if present in any screen the frame is
849   // displayed in.
850   int menu_bar_height = 0;
852   // A rectangle covering all the screen the frame is displayed in.
853   NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
854   for (i = 0; i < nr_screens; ++i )
855     {
856       NSScreen *s = [screens objectAtIndex: i];
857       NSRect scrRect = [s frame];
859       NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
860                    i, NSTRACE_ARG_RECT (scrRect));
862       if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
863         {
864           multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
866           if (!isFullscreen)
867             {
868               CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
869               menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
870             }
871         }
872     }
874   NSTRACE_RECT ("multiscreenRect", multiscreenRect);
876   NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
878   if (multiscreenRect.size.width == 0
879       || multiscreenRect.size.height == 0)
880     {
881       // Failed to find any monitor, give up.
882       NSTRACE_MSG ("multiscreenRect empty");
883       NSTRACE_RETURN_RECT (frameRect);
884       return frameRect;
885     }
888   // --------------------
889   // Find a suitable placement.
890   //
892   if (ns_menu_bar_should_be_hidden())
893     {
894       // When the menu bar is hidden, the user may place part of the
895       // frame above the top of the screen, for example to hide the
896       // title bar.
897       //
898       // Hence, keep the original position.
899     }
900   else
901     {
902       // Ensure that the frame is below the menu bar, or below the top
903       // of the screen.
904       //
905       // This assume that the menu bar is placed at the top in the
906       // rectangle that covers the monitors.  (It doesn't have to be,
907       // but if it's not it's hard to do anything useful.)
908       CGFloat topOfWorkArea = (multiscreenRect.origin.y
909                                + multiscreenRect.size.height
910                                - menu_bar_height);
912       CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
913       if (topOfFrame > topOfWorkArea)
914         {
915           frameRect.origin.y -= topOfFrame - topOfWorkArea;
916           NSTRACE_RECT ("After placement adjust", frameRect);
917         }
918     }
920   // Include the following section to restrict frame to the screens.
921   // (If so, update it to allow the frame to stretch down below the
922   // screen.)
923 #if 0
924   // --------------------
925   // Ensure frame doesn't stretch below the screens.
926   //
928   CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
930   if (diff > 0)
931     {
932       frameRect.origin.y = multiscreenRect.origin.y;
933       frameRect.size.height -= diff;
934     }
935 #endif
937   NSTRACE_RETURN_RECT (frameRect);
938   return frameRect;
942 static void
943 ns_constrain_all_frames (void)
944 /* --------------------------------------------------------------------------
945      Ensure that the menu bar doesn't cover any frames.
946    -------------------------------------------------------------------------- */
948   Lisp_Object tail, frame;
950   NSTRACE ("ns_constrain_all_frames");
952   block_input ();
954   FOR_EACH_FRAME (tail, frame)
955     {
956       struct frame *f = XFRAME (frame);
957       if (FRAME_NS_P (f))
958         {
959           EmacsView *view = FRAME_NS_VIEW (f);
961           if (![view isFullscreen])
962             {
963               [[view window]
964                 setFrame:constrain_frame_rect([[view window] frame], false)
965                  display:NO];
966             }
967         }
968     }
970   unblock_input ();
974 static void
975 ns_update_auto_hide_menu_bar (void)
976 /* --------------------------------------------------------------------------
977      Show or hide the menu bar, based on user setting.
978    -------------------------------------------------------------------------- */
980 #ifdef NS_IMPL_COCOA
981   NSTRACE ("ns_update_auto_hide_menu_bar");
983   block_input ();
985   if (NSApp != nil && [NSApp isActive])
986     {
987       // Note, "setPresentationOptions" triggers an error unless the
988       // application is active.
989       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
991       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
992         {
993           NSApplicationPresentationOptions options
994             = NSApplicationPresentationDefault;
996           if (menu_bar_should_be_hidden)
997             options |= NSApplicationPresentationAutoHideMenuBar
998               | NSApplicationPresentationAutoHideDock;
1000           [NSApp setPresentationOptions: options];
1002           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
1004           if (!ns_menu_bar_is_hidden)
1005             {
1006               ns_constrain_all_frames ();
1007             }
1008         }
1009     }
1011   unblock_input ();
1012 #endif
1016 static void
1017 ns_update_begin (struct frame *f)
1018 /* --------------------------------------------------------------------------
1019    Prepare for a grouped sequence of drawing calls
1020    external (RIF) call; whole frame, called before update_window_begin
1021    -------------------------------------------------------------------------- */
1023   EmacsView *view = FRAME_NS_VIEW (f);
1024   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
1026   ns_update_auto_hide_menu_bar ();
1028 #ifdef NS_IMPL_COCOA
1029   if ([view isFullscreen] && [view fsIsNative])
1030   {
1031     // Fix reappearing tool bar in fullscreen for OSX 10.7
1032     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
1033     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
1034     if (! tbar_visible != ! [toolbar isVisible])
1035       [toolbar setVisible: tbar_visible];
1036   }
1037 #endif
1039   ns_updating_frame = f;
1040   [view lockFocus];
1042   /* drawRect may have been called for say the minibuffer, and then clip path
1043      is for the minibuffer.  But the display engine may draw more because
1044      we have set the frame as garbaged.  So reset clip path to the whole
1045      view.  */
1046 #ifdef NS_IMPL_COCOA
1047   {
1048     NSBezierPath *bp;
1049     NSRect r = [view frame];
1050     NSRect cr = [[view window] frame];
1051     /* If a large frame size is set, r may be larger than the window frame
1052        before constrained.  In that case don't change the clip path, as we
1053        will clear in to the tool bar and title bar.  */
1054     if (r.size.height
1055         + FRAME_NS_TITLEBAR_HEIGHT (f)
1056         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
1057       {
1058         bp = [[NSBezierPath bezierPathWithRect: r] retain];
1059         [bp setClip];
1060         [bp release];
1061       }
1062   }
1063 #endif
1065 #ifdef NS_IMPL_GNUSTEP
1066   uRect = NSMakeRect (0, 0, 0, 0);
1067 #endif
1071 static void
1072 ns_update_window_begin (struct window *w)
1073 /* --------------------------------------------------------------------------
1074    Prepare for a grouped sequence of drawing calls
1075    external (RIF) call; for one window, called after update_begin
1076    -------------------------------------------------------------------------- */
1078   struct frame *f = XFRAME (WINDOW_FRAME (w));
1079   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1081   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
1082   w->output_cursor = w->cursor;
1084   block_input ();
1086   if (f == hlinfo->mouse_face_mouse_frame)
1087     {
1088       /* Don't do highlighting for mouse motion during the update.  */
1089       hlinfo->mouse_face_defer = 1;
1091         /* If the frame needs to be redrawn,
1092            simply forget about any prior mouse highlighting.  */
1093       if (FRAME_GARBAGED_P (f))
1094         hlinfo->mouse_face_window = Qnil;
1096       /* (further code for mouse faces ifdef'd out in other terms elided) */
1097     }
1099   unblock_input ();
1103 static void
1104 ns_update_window_end (struct window *w, bool cursor_on_p,
1105                       bool mouse_face_overwritten_p)
1106 /* --------------------------------------------------------------------------
1107    Finished a grouped sequence of drawing calls
1108    external (RIF) call; for one window called before update_end
1109    -------------------------------------------------------------------------- */
1111   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1113   /* note: this fn is nearly identical in all terms */
1114   if (!w->pseudo_window_p)
1115     {
1116       block_input ();
1118       if (cursor_on_p)
1119         display_and_set_cursor (w, 1,
1120                                 w->output_cursor.hpos, w->output_cursor.vpos,
1121                                 w->output_cursor.x, w->output_cursor.y);
1123       if (draw_window_fringes (w, 1))
1124         {
1125           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1126             x_draw_right_divider (w);
1127           else
1128             x_draw_vertical_border (w);
1129         }
1131       unblock_input ();
1132     }
1134   /* If a row with mouse-face was overwritten, arrange for
1135      frame_up_to_date to redisplay the mouse highlight.  */
1136   if (mouse_face_overwritten_p)
1137     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1141 static void
1142 ns_update_end (struct frame *f)
1143 /* --------------------------------------------------------------------------
1144    Finished a grouped sequence of drawing calls
1145    external (RIF) call; for whole frame, called after update_window_end
1146    -------------------------------------------------------------------------- */
1148   EmacsView *view = FRAME_NS_VIEW (f);
1150   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1152 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1153   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1155   block_input ();
1157   [view unlockFocus];
1158   [[view window] flushWindow];
1160   unblock_input ();
1161   ns_updating_frame = NULL;
1164 static void
1165 ns_focus (struct frame *f, NSRect *r, int n)
1166 /* --------------------------------------------------------------------------
1167    Internal: Focus on given frame.  During small local updates this is used to
1168      draw, however during large updates, ns_update_begin and ns_update_end are
1169      called to wrap the whole thing, in which case these calls are stubbed out.
1170      Except, on GNUstep, we accumulate the rectangle being drawn into, because
1171      the back end won't do this automatically, and will just end up flushing
1172      the entire window.
1173    -------------------------------------------------------------------------- */
1175   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1176   if (r != NULL)
1177     {
1178       NSTRACE_RECT ("r", *r);
1179     }
1181   if (f != ns_updating_frame)
1182     {
1183       NSView *view = FRAME_NS_VIEW (f);
1184       if (view != focus_view)
1185         {
1186           if (focus_view != NULL)
1187             {
1188               [focus_view unlockFocus];
1189               [[focus_view window] flushWindow];
1190 /*debug_lock--; */
1191             }
1193           if (view)
1194             [view lockFocus];
1195           focus_view = view;
1196 /*if (view) debug_lock++; */
1197         }
1198     }
1200   /* clipping */
1201   if (r)
1202     {
1203       [[NSGraphicsContext currentContext] saveGraphicsState];
1204       if (n == 2)
1205         NSRectClipList (r, 2);
1206       else
1207         NSRectClip (*r);
1208       gsaved = YES;
1209     }
1213 static void
1214 ns_unfocus (struct frame *f)
1215 /* --------------------------------------------------------------------------
1216      Internal: Remove focus on given frame
1217    -------------------------------------------------------------------------- */
1219   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1221   if (gsaved)
1222     {
1223       [[NSGraphicsContext currentContext] restoreGraphicsState];
1224       gsaved = NO;
1225     }
1227   if (f != ns_updating_frame)
1228     {
1229       if (focus_view != NULL)
1230         {
1231           [focus_view unlockFocus];
1232           [[focus_view window] flushWindow];
1233           focus_view = NULL;
1234 /*debug_lock--; */
1235         }
1236     }
1240 static void
1241 ns_clip_to_row (struct window *w, struct glyph_row *row,
1242                 enum glyph_row_area area, BOOL gc)
1243 /* --------------------------------------------------------------------------
1244      Internal (but parallels other terms): Focus drawing on given row
1245    -------------------------------------------------------------------------- */
1247   struct frame *f = XFRAME (WINDOW_FRAME (w));
1248   NSRect clip_rect;
1249   int window_x, window_y, window_width;
1251   window_box (w, area, &window_x, &window_y, &window_width, 0);
1253   clip_rect.origin.x = window_x;
1254   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1255   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1256   clip_rect.size.width = window_width;
1257   clip_rect.size.height = row->visible_height;
1259   ns_focus (f, &clip_rect, 1);
1263 /* ==========================================================================
1265     Visible bell and beep.
1267    ========================================================================== */
1270 // This bell implementation shows the visual bell image asynchronously
1271 // from the rest of Emacs. This is done by adding a NSView to the
1272 // superview of the Emacs window and removing it using a timer.
1274 // Unfortunately, some Emacs operations, like scrolling, is done using
1275 // low-level primitives that copy the content of the window, including
1276 // the bell image. To some extent, this is handled by removing the
1277 // image prior to scrolling and marking that the window is in need for
1278 // redisplay.
1280 // To test this code, make sure that there is no artifacts of the bell
1281 // image in the following situations. Use a non-empty buffer (like the
1282 // tutorial) to ensure that a scroll is performed:
1284 // * Single-window: C-g C-v
1286 // * Side-by-windows: C-x 3 C-g C-v
1288 // * Windows above each other: C-x 2 C-g C-v
1290 @interface EmacsBell : NSImageView
1292   // Number of currently active bell:s.
1293   unsigned int nestCount;
1294   NSView * mView;
1295   bool isAttached;
1297 - (void)show:(NSView *)view;
1298 - (void)hide;
1299 - (void)remove;
1300 @end
1302 @implementation EmacsBell
1304 - (id)init;
1306   NSTRACE ("[EmacsBell init]");
1307   if ((self = [super init]))
1308     {
1309       nestCount = 0;
1310       isAttached = false;
1311 #ifdef NS_IMPL_GNUSTEP
1312       // GNUstep doesn't provide named images.  This was reported in
1313       // 2011, see https://savannah.gnu.org/bugs/?33396
1314       //
1315       // As a drop in replacement, a semitransparent gray square is used.
1316       self.image = [[NSImage alloc] initWithSize:NSMakeSize(32 * 5, 32 * 5)];
1317       [self.image lockFocus];
1318       [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1319       NSRectFill(NSMakeRect(0, 0, 32, 32));
1320       [self.image unlockFocus];
1321 #else
1322       self.image = [NSImage imageNamed:NSImageNameCaution];
1323       [self.image setSize:NSMakeSize(self.image.size.width * 5,
1324                                      self.image.size.height * 5)];
1325 #endif
1326     }
1327   return self;
1330 - (void)show:(NSView *)view
1332   NSTRACE ("[EmacsBell show:]");
1333   NSTRACE_MSG ("nestCount: %u", nestCount);
1335   // Show the image, unless it's already shown.
1336   if (nestCount == 0)
1337     {
1338       NSRect rect = [view bounds];
1339       NSPoint pos;
1340       pos.x = rect.origin.x + (rect.size.width  - self.image.size.width )/2;
1341       pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1343       [self setFrameOrigin:pos];
1344       [self setFrameSize:self.image.size];
1346       isAttached = true;
1347       mView = view;
1348       [[[view window] contentView] addSubview:self
1349                                    positioned:NSWindowAbove
1350                                    relativeTo:nil];
1351     }
1353   ++nestCount;
1355   [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1359 - (void)hide
1361   // Note: Trace output from this method isn't shown, reason unknown.
1362   // NSTRACE ("[EmacsBell hide]");
1364   if (nestCount > 0)
1365     --nestCount;
1367   // Remove the image once the last bell became inactive.
1368   if (nestCount == 0)
1369     {
1370       [self remove];
1371     }
1375 -(void)remove
1377   NSTRACE ("[EmacsBell remove]");
1378   if (isAttached)
1379     {
1380       NSTRACE_MSG ("removeFromSuperview");
1381       [self removeFromSuperview];
1382       mView.needsDisplay = YES;
1383       isAttached = false;
1384     }
1387 @end
1390 static EmacsBell * bell_view = nil;
1392 static void
1393 ns_ring_bell (struct frame *f)
1394 /* --------------------------------------------------------------------------
1395      "Beep" routine
1396    -------------------------------------------------------------------------- */
1398   NSTRACE ("ns_ring_bell");
1399   if (visible_bell)
1400     {
1401       struct frame *frame = SELECTED_FRAME ();
1402       NSView *view;
1404       if (bell_view == nil)
1405         {
1406           bell_view = [[EmacsBell alloc] init];
1407           [bell_view retain];
1408         }
1410       block_input ();
1412       view = FRAME_NS_VIEW (frame);
1413       if (view != nil)
1414         {
1415           [bell_view show:view];
1416         }
1418       unblock_input ();
1419     }
1420   else
1421     {
1422       NSBeep ();
1423     }
1427 static void
1428 hide_bell (void)
1429 /* --------------------------------------------------------------------------
1430      Ensure the bell is hidden.
1431    -------------------------------------------------------------------------- */
1433   NSTRACE ("hide_bell");
1435   if (bell_view != nil)
1436     {
1437       [bell_view remove];
1438     }
1442 /* ==========================================================================
1444     Frame / window manager related functions
1446    ========================================================================== */
1449 static void
1450 ns_raise_frame (struct frame *f)
1451 /* --------------------------------------------------------------------------
1452      Bring window to foreground and make it active
1453    -------------------------------------------------------------------------- */
1455   NSView *view;
1457   check_window_system (f);
1458   view = FRAME_NS_VIEW (f);
1459   block_input ();
1460   if (FRAME_VISIBLE_P (f))
1461     [[view window] makeKeyAndOrderFront: NSApp];
1462   unblock_input ();
1466 static void
1467 ns_lower_frame (struct frame *f)
1468 /* --------------------------------------------------------------------------
1469      Send window to back
1470    -------------------------------------------------------------------------- */
1472   NSView *view;
1474   check_window_system (f);
1475   view = FRAME_NS_VIEW (f);
1476   block_input ();
1477   [[view window] orderBack: NSApp];
1478   unblock_input ();
1482 static void
1483 ns_frame_raise_lower (struct frame *f, bool raise)
1484 /* --------------------------------------------------------------------------
1485      External (hook)
1486    -------------------------------------------------------------------------- */
1488   NSTRACE ("ns_frame_raise_lower");
1490   if (raise)
1491     ns_raise_frame (f);
1492   else
1493     ns_lower_frame (f);
1497 static void
1498 ns_frame_rehighlight (struct frame *frame)
1499 /* --------------------------------------------------------------------------
1500      External (hook): called on things like window switching within frame
1501    -------------------------------------------------------------------------- */
1503   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1504   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1506   NSTRACE ("ns_frame_rehighlight");
1507   if (dpyinfo->x_focus_frame)
1508     {
1509       dpyinfo->x_highlight_frame
1510         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1511            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1512            : dpyinfo->x_focus_frame);
1513       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1514         {
1515           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1516           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1517         }
1518     }
1519   else
1520       dpyinfo->x_highlight_frame = 0;
1522   if (dpyinfo->x_highlight_frame &&
1523          dpyinfo->x_highlight_frame != old_highlight)
1524     {
1525       if (old_highlight)
1526         {
1527           x_update_cursor (old_highlight, 1);
1528           x_set_frame_alpha (old_highlight);
1529         }
1530       if (dpyinfo->x_highlight_frame)
1531         {
1532           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1533           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1534         }
1535     }
1539 void
1540 x_make_frame_visible (struct frame *f)
1541 /* --------------------------------------------------------------------------
1542      External: Show the window (X11 semantics)
1543    -------------------------------------------------------------------------- */
1545   NSTRACE ("x_make_frame_visible");
1546   /* XXX: at some points in past this was not needed, as the only place that
1547      called this (frame.c:Fraise_frame ()) also called raise_lower;
1548      if this ends up the case again, comment this out again. */
1549   if (!FRAME_VISIBLE_P (f))
1550     {
1551       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1553       SET_FRAME_VISIBLE (f, 1);
1554       ns_raise_frame (f);
1556       /* Making a new frame from a fullscreen frame will make the new frame
1557          fullscreen also.  So skip handleFS as this will print an error.  */
1558       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1559           && [view isFullscreen])
1560         return;
1562       if (f->want_fullscreen != FULLSCREEN_NONE)
1563         {
1564           block_input ();
1565           [view handleFS];
1566           unblock_input ();
1567         }
1568     }
1572 void
1573 x_make_frame_invisible (struct frame *f)
1574 /* --------------------------------------------------------------------------
1575      External: Hide the window (X11 semantics)
1576    -------------------------------------------------------------------------- */
1578   NSView *view;
1579   NSTRACE ("x_make_frame_invisible");
1580   check_window_system (f);
1581   view = FRAME_NS_VIEW (f);
1582   [[view window] orderOut: NSApp];
1583   SET_FRAME_VISIBLE (f, 0);
1584   SET_FRAME_ICONIFIED (f, 0);
1588 void
1589 x_iconify_frame (struct frame *f)
1590 /* --------------------------------------------------------------------------
1591      External: Iconify window
1592    -------------------------------------------------------------------------- */
1594   NSView *view;
1595   struct ns_display_info *dpyinfo;
1597   NSTRACE ("x_iconify_frame");
1598   check_window_system (f);
1599   view = FRAME_NS_VIEW (f);
1600   dpyinfo = FRAME_DISPLAY_INFO (f);
1602   if (dpyinfo->x_highlight_frame == f)
1603     dpyinfo->x_highlight_frame = 0;
1605   if ([[view window] windowNumber] <= 0)
1606     {
1607       /* the window is still deferred.  Make it very small, bring it
1608          on screen and order it out. */
1609       NSRect s = { { 100, 100}, {0, 0} };
1610       NSRect t;
1611       t = [[view window] frame];
1612       [[view window] setFrame: s display: NO];
1613       [[view window] orderBack: NSApp];
1614       [[view window] orderOut: NSApp];
1615       [[view window] setFrame: t display: NO];
1616     }
1618   /* Processing input while Emacs is being minimized can cause a
1619      crash, so block it for the duration. */
1620   block_input();
1621   [[view window] miniaturize: NSApp];
1622   unblock_input();
1625 /* Free X resources of frame F.  */
1627 void
1628 x_free_frame_resources (struct frame *f)
1630   NSView *view;
1631   struct ns_display_info *dpyinfo;
1632   Mouse_HLInfo *hlinfo;
1634   NSTRACE ("x_free_frame_resources");
1635   check_window_system (f);
1636   view = FRAME_NS_VIEW (f);
1637   dpyinfo = FRAME_DISPLAY_INFO (f);
1638   hlinfo = MOUSE_HL_INFO (f);
1640   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1642   block_input ();
1644   free_frame_menubar (f);
1645   free_frame_faces (f);
1647   if (f == dpyinfo->x_focus_frame)
1648     dpyinfo->x_focus_frame = 0;
1649   if (f == dpyinfo->x_highlight_frame)
1650     dpyinfo->x_highlight_frame = 0;
1651   if (f == hlinfo->mouse_face_mouse_frame)
1652     reset_mouse_highlight (hlinfo);
1654   if (f->output_data.ns->miniimage != nil)
1655     [f->output_data.ns->miniimage release];
1657   [[view window] close];
1658   [view release];
1660   xfree (f->output_data.ns);
1662   unblock_input ();
1665 void
1666 x_destroy_window (struct frame *f)
1667 /* --------------------------------------------------------------------------
1668      External: Delete the window
1669    -------------------------------------------------------------------------- */
1671   NSTRACE ("x_destroy_window");
1672   check_window_system (f);
1673   x_free_frame_resources (f);
1674   ns_window_num--;
1678 void
1679 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1680 /* --------------------------------------------------------------------------
1681      External: Position the window
1682    -------------------------------------------------------------------------- */
1684   NSView *view = FRAME_NS_VIEW (f);
1685   NSArray *screens = [NSScreen screens];
1686   NSScreen *fscreen = [screens objectAtIndex: 0];
1687   NSScreen *screen = [[view window] screen];
1689   NSTRACE ("x_set_offset");
1691   block_input ();
1693   f->left_pos = xoff;
1694   f->top_pos = yoff;
1696   if (view != nil && screen && fscreen)
1697     {
1698       f->left_pos = f->size_hint_flags & XNegative
1699         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1700         : f->left_pos;
1701       /* We use visibleFrame here to take menu bar into account.
1702          Ideally we should also adjust left/top with visibleFrame.origin.  */
1704       f->top_pos = f->size_hint_flags & YNegative
1705         ? ([screen visibleFrame].size.height + f->top_pos
1706            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1707            - FRAME_TOOLBAR_HEIGHT (f))
1708         : f->top_pos;
1709 #ifdef NS_IMPL_GNUSTEP
1710       if (f->left_pos < 100)
1711         f->left_pos = 100;  /* don't overlap menu */
1712 #endif
1713       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1714          menu bar.  */
1715       NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1716                                 SCREENMAXBOUND ([fscreen frame].size.height
1717                                                 - NS_TOP_POS (f)));
1718       NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1719       [[view window] setFrameTopLeftPoint: pt];
1720       f->size_hint_flags &= ~(XNegative|YNegative);
1721     }
1723   unblock_input ();
1727 void
1728 x_set_window_size (struct frame *f,
1729                    bool change_gravity,
1730                    int width,
1731                    int height,
1732                    bool pixelwise)
1733 /* --------------------------------------------------------------------------
1734      Adjust window pixel size based on given character grid size
1735      Impl is a bit more complex than other terms, need to do some
1736      internal clipping.
1737    -------------------------------------------------------------------------- */
1739   EmacsView *view = FRAME_NS_VIEW (f);
1740   NSWindow *window = [view window];
1741   NSRect wr = [window frame];
1742   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1743   int pixelwidth, pixelheight;
1744   int orig_height = wr.size.height;
1746   NSTRACE ("x_set_window_size");
1748   if (view == nil)
1749     return;
1751   NSTRACE_RECT ("current", wr);
1752   NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1753   NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1755   block_input ();
1757   if (pixelwise)
1758     {
1759       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1760       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1761     }
1762   else
1763     {
1764       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1765       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1766     }
1768   /* If we have a toolbar, take its height into account. */
1769   if (tb && ! [view isFullscreen])
1770     {
1771     /* NOTE: previously this would generate wrong result if toolbar not
1772              yet displayed and fixing toolbar_height=32 helped, but
1773              now (200903) seems no longer needed */
1774     FRAME_TOOLBAR_HEIGHT (f) =
1775       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1776         - FRAME_NS_TITLEBAR_HEIGHT (f);
1777 #if 0
1778       /* Only breaks things here, removed by martin 2015-09-30.  */
1779 #ifdef NS_IMPL_GNUSTEP
1780       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1781 #endif
1782 #endif
1783     }
1784   else
1785     FRAME_TOOLBAR_HEIGHT (f) = 0;
1787   wr.size.width = pixelwidth + f->border_width;
1788   wr.size.height = pixelheight;
1789   if (! [view isFullscreen])
1790     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1791       + FRAME_TOOLBAR_HEIGHT (f);
1793   /* Do not try to constrain to this screen.  We may have multiple
1794      screens, and want Emacs to span those.  Constraining to screen
1795      prevents that, and that is not nice to the user.  */
1796  if (f->output_data.ns->zooming)
1797    f->output_data.ns->zooming = 0;
1798  else
1799    wr.origin.y += orig_height - wr.size.height;
1801  frame_size_history_add
1802    (f, Qx_set_window_size_1, width, height,
1803     list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1804            Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1805            make_number (f->border_width),
1806            make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1807            make_number (FRAME_TOOLBAR_HEIGHT (f))));
1809   [window setFrame: wr display: YES];
1811   [view updateFrameSize: NO];
1812   unblock_input ();
1816 static void
1817 ns_fullscreen_hook (struct frame *f)
1819   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1821   NSTRACE ("ns_fullscreen_hook");
1823   if (!FRAME_VISIBLE_P (f))
1824     return;
1826    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1827     {
1828       /* Old style fs don't initiate correctly if created from
1829          init/default-frame alist, so use a timer (not nice...).
1830       */
1831       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1832                                      selector: @selector (handleFS)
1833                                      userInfo: nil repeats: NO];
1834       return;
1835     }
1837   block_input ();
1838   [view handleFS];
1839   unblock_input ();
1842 /* ==========================================================================
1844     Color management
1846    ========================================================================== */
1849 NSColor *
1850 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1852   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1853   if (idx < 1 || idx >= color_table->avail)
1854     return nil;
1855   return color_table->colors[idx];
1859 unsigned long
1860 ns_index_color (NSColor *color, struct frame *f)
1862   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1863   ptrdiff_t idx;
1864   ptrdiff_t i;
1866   if (!color_table->colors)
1867     {
1868       color_table->size = NS_COLOR_CAPACITY;
1869       color_table->avail = 1; /* skip idx=0 as marker */
1870       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1871       color_table->colors[0] = nil;
1872       color_table->empty_indices = [[NSMutableSet alloc] init];
1873     }
1875   /* Do we already have this color?  */
1876   for (i = 1; i < color_table->avail; i++)
1877     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1878       return i;
1880   if ([color_table->empty_indices count] > 0)
1881     {
1882       NSNumber *index = [color_table->empty_indices anyObject];
1883       [color_table->empty_indices removeObject: index];
1884       idx = [index unsignedLongValue];
1885     }
1886   else
1887     {
1888       if (color_table->avail == color_table->size)
1889         color_table->colors =
1890           xpalloc (color_table->colors, &color_table->size, 1,
1891                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1892       idx = color_table->avail++;
1893     }
1895   color_table->colors[idx] = color;
1896   [color retain];
1897 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1898   return idx;
1902 static int
1903 ns_get_color (const char *name, NSColor **col)
1904 /* --------------------------------------------------------------------------
1905      Parse a color name
1906    -------------------------------------------------------------------------- */
1907 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1908    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1909    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1911   NSColor *new = nil;
1912   static char hex[20];
1913   int scaling = 0;
1914   float r = -1.0, g, b;
1915   NSString *nsname = [NSString stringWithUTF8String: name];
1917   NSTRACE ("ns_get_color(%s, **)", name);
1919   block_input ();
1921   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1922     {
1923 #ifdef NS_IMPL_COCOA
1924       NSString *defname = [[NSUserDefaults standardUserDefaults]
1925                             stringForKey: @"AppleHighlightColor"];
1926       if (defname != nil)
1927         nsname = defname;
1928       else
1929 #endif
1930       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1931         {
1932           *col = [new colorUsingDefaultColorSpace];
1933           unblock_input ();
1934           return 0;
1935         }
1936       else
1937         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1939       name = [nsname UTF8String];
1940     }
1941   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1942     {
1943       /* NOTE: OSX applications normally don't set foreground selection, but
1944          text may be unreadable if we don't.
1945       */
1946       if ((new = [NSColor selectedTextColor]) != nil)
1947         {
1948           *col = [new colorUsingDefaultColorSpace];
1949           unblock_input ();
1950           return 0;
1951         }
1953       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1954       name = [nsname UTF8String];
1955     }
1957   /* First, check for some sort of numeric specification. */
1958   hex[0] = '\0';
1960   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1961     {
1962       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1963       [scanner scanFloat: &r];
1964       [scanner scanFloat: &g];
1965       [scanner scanFloat: &b];
1966     }
1967   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1968     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1969   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1970     {
1971       int len = (strlen(name) - 1);
1972       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1973       int i;
1974       scaling = strlen(name+start) / 3;
1975       for (i = 0; i < 3; i++)
1976         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1977                  name + start + i * scaling);
1978       hex[3 * (scaling + 1) - 1] = '\0';
1979     }
1981   if (hex[0])
1982     {
1983       unsigned int rr, gg, bb;
1984       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1985       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1986         {
1987           r = rr / fscale;
1988           g = gg / fscale;
1989           b = bb / fscale;
1990         }
1991     }
1993   if (r >= 0.0F)
1994     {
1995       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1996       unblock_input ();
1997       return 0;
1998     }
2000   /* Otherwise, color is expected to be from a list */
2001   {
2002     NSEnumerator *lenum, *cenum;
2003     NSString *name;
2004     NSColorList *clist;
2006 #ifdef NS_IMPL_GNUSTEP
2007     /* XXX: who is wrong, the requestor or the implementation? */
2008     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
2009         == NSOrderedSame)
2010       nsname = @"highlightColor";
2011 #endif
2013     lenum = [[NSColorList availableColorLists] objectEnumerator];
2014     while ( (clist = [lenum nextObject]) && new == nil)
2015       {
2016         cenum = [[clist allKeys] objectEnumerator];
2017         while ( (name = [cenum nextObject]) && new == nil )
2018           {
2019             if ([name compare: nsname
2020                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
2021               new = [clist colorWithKey: name];
2022           }
2023       }
2024   }
2026   if (new)
2027     *col = [new colorUsingDefaultColorSpace];
2028   unblock_input ();
2029   return new ? 0 : 1;
2034 ns_lisp_to_color (Lisp_Object color, NSColor **col)
2035 /* --------------------------------------------------------------------------
2036      Convert a Lisp string object to a NS color
2037    -------------------------------------------------------------------------- */
2039   NSTRACE ("ns_lisp_to_color");
2040   if (STRINGP (color))
2041     return ns_get_color (SSDATA (color), col);
2042   else if (SYMBOLP (color))
2043     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
2044   return 1;
2048 void
2049 ns_query_color(void *col, XColor *color_def, int setPixel)
2050 /* --------------------------------------------------------------------------
2051          Get ARGB values out of NSColor col and put them into color_def.
2052          If setPixel, set the pixel to a concatenated version.
2053          and set color_def pixel to the resulting index.
2054    -------------------------------------------------------------------------- */
2056   EmacsCGFloat r, g, b, a;
2058   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2059   color_def->red   = r * 65535;
2060   color_def->green = g * 65535;
2061   color_def->blue  = b * 65535;
2063   if (setPixel == YES)
2064     color_def->pixel
2065       = ARGB_TO_ULONG((int)(a*255),
2066                       (int)(r*255), (int)(g*255), (int)(b*255));
2070 bool
2071 ns_defined_color (struct frame *f,
2072                   const char *name,
2073                   XColor *color_def,
2074                   bool alloc,
2075                   bool makeIndex)
2076 /* --------------------------------------------------------------------------
2077          Return true if named color found, and set color_def rgb accordingly.
2078          If makeIndex and alloc are nonzero put the color in the color_table,
2079          and set color_def pixel to the resulting index.
2080          If makeIndex is zero, set color_def pixel to ARGB.
2081          Return false if not found
2082    -------------------------------------------------------------------------- */
2084   NSColor *col;
2085   NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2087   block_input ();
2088   if (ns_get_color (name, &col) != 0) /* Color not found  */
2089     {
2090       unblock_input ();
2091       return 0;
2092     }
2093   if (makeIndex && alloc)
2094     color_def->pixel = ns_index_color (col, f);
2095   ns_query_color (col, color_def, !makeIndex);
2096   unblock_input ();
2097   return 1;
2101 void
2102 x_set_frame_alpha (struct frame *f)
2103 /* --------------------------------------------------------------------------
2104      change the entire-frame transparency
2105    -------------------------------------------------------------------------- */
2107   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2108   double alpha = 1.0;
2109   double alpha_min = 1.0;
2111   NSTRACE ("x_set_frame_alpha");
2113   if (dpyinfo->x_highlight_frame == f)
2114     alpha = f->alpha[0];
2115   else
2116     alpha = f->alpha[1];
2118   if (FLOATP (Vframe_alpha_lower_limit))
2119     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2120   else if (INTEGERP (Vframe_alpha_lower_limit))
2121     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2123   if (alpha < 0.0)
2124     return;
2125   else if (1.0 < alpha)
2126     alpha = 1.0;
2127   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2128     alpha = alpha_min;
2130 #ifdef NS_IMPL_COCOA
2131   {
2132     EmacsView *view = FRAME_NS_VIEW (f);
2133   [[view window] setAlphaValue: alpha];
2134   }
2135 #endif
2139 /* ==========================================================================
2141     Mouse handling
2143    ========================================================================== */
2146 void
2147 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2148 /* --------------------------------------------------------------------------
2149      Programmatically reposition mouse pointer in pixel coordinates
2150    -------------------------------------------------------------------------- */
2152   NSTRACE ("frame_set_mouse_pixel_position");
2153   ns_raise_frame (f);
2154 #if 0
2155   /* FIXME: this does not work, and what about GNUstep? */
2156 #ifdef NS_IMPL_COCOA
2157   [FRAME_NS_VIEW (f) lockFocus];
2158   PSsetmouse ((float)pix_x, (float)pix_y);
2159   [FRAME_NS_VIEW (f) unlockFocus];
2160 #endif
2161 #endif
2164 static int
2165 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2166 /*   ------------------------------------------------------------------------
2167      Called by EmacsView on mouseMovement events.  Passes on
2168      to emacs mainstream code if we moved off of a rect of interest
2169      known as last_mouse_glyph.
2170      ------------------------------------------------------------------------ */
2172   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2173   NSRect *r;
2175 //  NSTRACE ("note_mouse_movement");
2177   dpyinfo->last_mouse_motion_frame = frame;
2178   r = &dpyinfo->last_mouse_glyph;
2180   /* Note, this doesn't get called for enter/leave, since we don't have a
2181      position.  Those are taken care of in the corresponding NSView methods. */
2183   /* has movement gone beyond last rect we were tracking? */
2184   if (x < r->origin.x || x >= r->origin.x + r->size.width
2185       || y < r->origin.y || y >= r->origin.y + r->size.height)
2186     {
2187       ns_update_begin (frame);
2188       frame->mouse_moved = 1;
2189       note_mouse_highlight (frame, x, y);
2190       remember_mouse_glyph (frame, x, y, r);
2191       ns_update_end (frame);
2192       return 1;
2193     }
2195   return 0;
2199 static void
2200 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2201                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2202                    Time *time)
2203 /* --------------------------------------------------------------------------
2204     External (hook): inform emacs about mouse position and hit parts.
2205     If a scrollbar is being dragged, set bar_window, part, x, y, time.
2206     x & y should be position in the scrollbar (the whole bar, not the handle)
2207     and length of scrollbar respectively
2208    -------------------------------------------------------------------------- */
2210   id view;
2211   NSPoint position;
2212   Lisp_Object frame, tail;
2213   struct frame *f;
2214   struct ns_display_info *dpyinfo;
2216   NSTRACE ("ns_mouse_position");
2218   if (*fp == NULL)
2219     {
2220       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2221       return;
2222     }
2224   dpyinfo = FRAME_DISPLAY_INFO (*fp);
2226   block_input ();
2228   /* Clear the mouse-moved flag for every frame on this display.  */
2229   FOR_EACH_FRAME (tail, frame)
2230     if (FRAME_NS_P (XFRAME (frame))
2231         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2232       XFRAME (frame)->mouse_moved = 0;
2234   dpyinfo->last_mouse_scroll_bar = nil;
2235   if (dpyinfo->last_mouse_frame
2236       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2237     f = dpyinfo->last_mouse_frame;
2238   else
2239     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2241   if (f && FRAME_NS_P (f))
2242     {
2243       view = FRAME_NS_VIEW (*fp);
2245       position = [[view window] mouseLocationOutsideOfEventStream];
2246       position = [view convertPoint: position fromView: nil];
2247       remember_mouse_glyph (f, position.x, position.y,
2248                             &dpyinfo->last_mouse_glyph);
2249       NSTRACE_POINT ("position", position);
2251       if (bar_window) *bar_window = Qnil;
2252       if (part) *part = scroll_bar_above_handle;
2254       if (x) XSETINT (*x, lrint (position.x));
2255       if (y) XSETINT (*y, lrint (position.y));
2256       if (time)
2257         *time = dpyinfo->last_mouse_movement_time;
2258       *fp = f;
2259     }
2261   unblock_input ();
2265 static void
2266 ns_frame_up_to_date (struct frame *f)
2267 /* --------------------------------------------------------------------------
2268     External (hook): Fix up mouse highlighting right after a full update.
2269     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2270    -------------------------------------------------------------------------- */
2272   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2274   if (FRAME_NS_P (f))
2275     {
2276       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2277       if (f == hlinfo->mouse_face_mouse_frame)
2278         {
2279           block_input ();
2280           ns_update_begin(f);
2281           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2282                                 hlinfo->mouse_face_mouse_x,
2283                                 hlinfo->mouse_face_mouse_y);
2284           ns_update_end(f);
2285           unblock_input ();
2286         }
2287     }
2291 static void
2292 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2293 /* --------------------------------------------------------------------------
2294     External (RIF): set frame mouse pointer type.
2295    -------------------------------------------------------------------------- */
2297   NSTRACE ("ns_define_frame_cursor");
2298   if (FRAME_POINTER_TYPE (f) != cursor)
2299     {
2300       EmacsView *view = FRAME_NS_VIEW (f);
2301       FRAME_POINTER_TYPE (f) = cursor;
2302       [[view window] invalidateCursorRectsForView: view];
2303       /* Redisplay assumes this function also draws the changed frame
2304          cursor, but this function doesn't, so do it explicitly.  */
2305       x_update_cursor (f, 1);
2306     }
2311 /* ==========================================================================
2313     Keyboard handling
2315    ========================================================================== */
2318 static unsigned
2319 ns_convert_key (unsigned code)
2320 /* --------------------------------------------------------------------------
2321     Internal call used by NSView-keyDown.
2322    -------------------------------------------------------------------------- */
2324   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2325   unsigned keysym;
2326   /* An array would be faster, but less easy to read. */
2327   for (keysym = 0; keysym < last_keysym; keysym += 2)
2328     if (code == convert_ns_to_X_keysym[keysym])
2329       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2330   return 0;
2331 /* if decide to use keyCode and Carbon table, use this line:
2332      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2336 char *
2337 x_get_keysym_name (int keysym)
2338 /* --------------------------------------------------------------------------
2339     Called by keyboard.c.  Not sure if the return val is important, except
2340     that it be unique.
2341    -------------------------------------------------------------------------- */
2343   static char value[16];
2344   NSTRACE ("x_get_keysym_name");
2345   sprintf (value, "%d", keysym);
2346   return value;
2351 /* ==========================================================================
2353     Block drawing operations
2355    ========================================================================== */
2358 static void
2359 ns_redraw_scroll_bars (struct frame *f)
2361   int i;
2362   id view;
2363   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2364   NSTRACE ("ns_redraw_scroll_bars");
2365   for (i =[subviews count]-1; i >= 0; i--)
2366     {
2367       view = [subviews objectAtIndex: i];
2368       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2369       [view display];
2370     }
2374 void
2375 ns_clear_frame (struct frame *f)
2376 /* --------------------------------------------------------------------------
2377       External (hook): Erase the entire frame
2378    -------------------------------------------------------------------------- */
2380   NSView *view = FRAME_NS_VIEW (f);
2381   NSRect r;
2383   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2385  /* comes on initial frame because we have
2386     after-make-frame-functions = select-frame */
2387  if (!FRAME_DEFAULT_FACE (f))
2388    return;
2390   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2392   r = [view bounds];
2394   block_input ();
2395   ns_focus (f, &r, 1);
2396   [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2397                             (FACE_FROM_ID (f, DEFAULT_FACE_ID)), f) set];
2398   NSRectFill (r);
2399   ns_unfocus (f);
2401   /* as of 2006/11 or so this is now needed */
2402   ns_redraw_scroll_bars (f);
2403   unblock_input ();
2407 static void
2408 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2409 /* --------------------------------------------------------------------------
2410     External (RIF):  Clear section of frame
2411    -------------------------------------------------------------------------- */
2413   NSRect r = NSMakeRect (x, y, width, height);
2414   NSView *view = FRAME_NS_VIEW (f);
2415   struct face *face = FRAME_DEFAULT_FACE (f);
2417   if (!view || !face)
2418     return;
2420   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2422   r = NSIntersectionRect (r, [view frame]);
2423   ns_focus (f, &r, 1);
2424   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2426   NSRectFill (r);
2428   ns_unfocus (f);
2429   return;
2432 static void
2433 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2435   NSTRACE ("ns_copy_bits");
2437   if (FRAME_NS_VIEW (f))
2438     {
2439       hide_bell();              // Ensure the bell image isn't scrolled.
2441       ns_focus (f, &dest, 1);
2442       [FRAME_NS_VIEW (f) scrollRect: src
2443                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2444                                                  dest.origin.y - src.origin.y)];
2445       ns_unfocus (f);
2446     }
2449 static void
2450 ns_scroll_run (struct window *w, struct run *run)
2451 /* --------------------------------------------------------------------------
2452     External (RIF):  Insert or delete n lines at line vpos
2453    -------------------------------------------------------------------------- */
2455   struct frame *f = XFRAME (w->frame);
2456   int x, y, width, height, from_y, to_y, bottom_y;
2458   NSTRACE ("ns_scroll_run");
2460   /* begin copy from other terms */
2461   /* Get frame-relative bounding box of the text display area of W,
2462      without mode lines.  Include in this box the left and right
2463      fringe of W.  */
2464   window_box (w, ANY_AREA, &x, &y, &width, &height);
2466   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2467   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2468   bottom_y = y + height;
2470   if (to_y < from_y)
2471     {
2472       /* Scrolling up.  Make sure we don't copy part of the mode
2473          line at the bottom.  */
2474       if (from_y + run->height > bottom_y)
2475         height = bottom_y - from_y;
2476       else
2477         height = run->height;
2478     }
2479   else
2480     {
2481       /* Scrolling down.  Make sure we don't copy over the mode line.
2482          at the bottom.  */
2483       if (to_y + run->height > bottom_y)
2484         height = bottom_y - to_y;
2485       else
2486         height = run->height;
2487     }
2488   /* end copy from other terms */
2490   if (height == 0)
2491       return;
2493   block_input ();
2495   x_clear_cursor (w);
2497   {
2498     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2499     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2501     ns_copy_bits (f, srcRect , dstRect);
2502   }
2504   unblock_input ();
2508 static void
2509 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2510 /* --------------------------------------------------------------------------
2511     External (RIF): preparatory to fringe update after text was updated
2512    -------------------------------------------------------------------------- */
2514   struct frame *f;
2515   int width, height;
2517   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2519   /* begin copy from other terms */
2520   eassert (w);
2522   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2523     desired_row->redraw_fringe_bitmaps_p = 1;
2525   /* When a window has disappeared, make sure that no rest of
2526      full-width rows stays visible in the internal border.  */
2527   if (windows_or_buffers_changed
2528       && desired_row->full_width_p
2529       && (f = XFRAME (w->frame),
2530           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2531           width != 0)
2532       && (height = desired_row->visible_height,
2533           height > 0))
2534     {
2535       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2537       block_input ();
2538       ns_clear_frame_area (f, 0, y, width, height);
2539       ns_clear_frame_area (f,
2540                            FRAME_PIXEL_WIDTH (f) - width,
2541                            y, width, height);
2542       unblock_input ();
2543     }
2547 static void
2548 ns_shift_glyphs_for_insert (struct frame *f,
2549                            int x, int y, int width, int height,
2550                            int shift_by)
2551 /* --------------------------------------------------------------------------
2552     External (RIF): copy an area horizontally, don't worry about clearing src
2553    -------------------------------------------------------------------------- */
2555   NSRect srcRect = NSMakeRect (x, y, width, height);
2556   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2558   NSTRACE ("ns_shift_glyphs_for_insert");
2560   ns_copy_bits (f, srcRect, dstRect);
2565 /* ==========================================================================
2567     Character encoding and metrics
2569    ========================================================================== */
2572 static void
2573 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2574 /* --------------------------------------------------------------------------
2575      External (RIF); compute left/right overhang of whole string and set in s
2576    -------------------------------------------------------------------------- */
2578   struct font *font = s->font;
2580   if (s->char2b)
2581     {
2582       struct font_metrics metrics;
2583       unsigned int codes[2];
2584       codes[0] = *(s->char2b);
2585       codes[1] = *(s->char2b + s->nchars - 1);
2587       font->driver->text_extents (font, codes, 2, &metrics);
2588       s->left_overhang = -metrics.lbearing;
2589       s->right_overhang
2590         = metrics.rbearing > metrics.width
2591         ? metrics.rbearing - metrics.width : 0;
2592     }
2593   else
2594     {
2595       s->left_overhang = 0;
2596       if (EQ (font->driver->type, Qns))
2597         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2598           FONT_HEIGHT (font) * 0.2 : 0;
2599       else
2600         s->right_overhang = 0;
2601     }
2606 /* ==========================================================================
2608     Fringe and cursor drawing
2610    ========================================================================== */
2613 extern int max_used_fringe_bitmap;
2614 static void
2615 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2616                       struct draw_fringe_bitmap_params *p)
2617 /* --------------------------------------------------------------------------
2618     External (RIF); fringe-related
2619    -------------------------------------------------------------------------- */
2621   /* Fringe bitmaps comes in two variants, normal and periodic.  A
2622      periodic bitmap is used to create a continuous pattern.  Since a
2623      bitmap is rendered one text line at a time, the start offset (dh)
2624      of the bitmap varies.  Concretely, this is used for the empty
2625      line indicator.
2627      For a bitmap, "h + dh" is the full height and is always
2628      invariant.  For a normal bitmap "dh" is zero.
2630      For example, when the period is three and the full height is 72
2631      the following combinations exists:
2633        h=72 dh=0
2634        h=71 dh=1
2635        h=70 dh=2 */
2637   struct frame *f = XFRAME (WINDOW_FRAME (w));
2638   struct face *face = p->face;
2639   static EmacsImage **bimgs = NULL;
2640   static int nBimgs = 0;
2642   NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2643   NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2644                p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2646   /* grow bimgs if needed */
2647   if (nBimgs < max_used_fringe_bitmap)
2648     {
2649       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2650       memset (bimgs + nBimgs, 0,
2651               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2652       nBimgs = max_used_fringe_bitmap;
2653     }
2655   /* Must clip because of partially visible lines.  */
2656   ns_clip_to_row (w, row, ANY_AREA, YES);
2658   if (!p->overlay_p)
2659     {
2660       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2662       if (bx >= 0 && nx > 0)
2663         {
2664           NSRect r = NSMakeRect (bx, by, nx, ny);
2665           NSRectClip (r);
2666           [ns_lookup_indexed_color (face->background, f) set];
2667           NSRectFill (r);
2668         }
2669     }
2671   if (p->which)
2672     {
2673       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2674       EmacsImage *img = bimgs[p->which - 1];
2676       if (!img)
2677         {
2678           // Note: For "periodic" images, allocate one EmacsImage for
2679           // the base image, and use it for all dh:s.
2680           unsigned short *bits = p->bits;
2681           int full_height = p->h + p->dh;
2682           int i;
2683           unsigned char *cbits = xmalloc (full_height);
2685           for (i = 0; i < full_height; i++)
2686             cbits[i] = bits[i];
2687           img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2688                                          height: full_height
2689                                              fg: 0 bg: 0];
2690           bimgs[p->which - 1] = img;
2691           xfree (cbits);
2692         }
2694       NSTRACE_RECT ("r", r);
2696       NSRectClip (r);
2697       /* Since we composite the bitmap instead of just blitting it, we need
2698          to erase the whole background. */
2699       [ns_lookup_indexed_color(face->background, f) set];
2700       NSRectFill (r);
2702       {
2703         NSColor *bm_color;
2704         if (!p->cursor_p)
2705           bm_color = ns_lookup_indexed_color(face->foreground, f);
2706         else if (p->overlay_p)
2707           bm_color = ns_lookup_indexed_color(face->background, f);
2708         else
2709           bm_color = f->output_data.ns->cursor_color;
2710         [img setXBMColor: bm_color];
2711       }
2713 #ifdef NS_IMPL_COCOA
2714       // Note: For periodic images, the full image height is "h + hd".
2715       // By using the height h, a suitable part of the image is used.
2716       NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2718       NSTRACE_RECT ("fromRect", fromRect);
2720       [img drawInRect: r
2721               fromRect: fromRect
2722              operation: NSCompositingOperationSourceOver
2723               fraction: 1.0
2724            respectFlipped: YES
2725                 hints: nil];
2726 #else
2727       {
2728         NSPoint pt = r.origin;
2729         pt.y += p->h;
2730         [img compositeToPoint: pt operation: NSCompositingOperationSourceOver];
2731       }
2732 #endif
2733     }
2734   ns_unfocus (f);
2738 static void
2739 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2740                        int x, int y, enum text_cursor_kinds cursor_type,
2741                        int cursor_width, bool on_p, bool active_p)
2742 /* --------------------------------------------------------------------------
2743      External call (RIF): draw cursor.
2744      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2745    -------------------------------------------------------------------------- */
2747   NSRect r, s;
2748   int fx, fy, h, cursor_height;
2749   struct frame *f = WINDOW_XFRAME (w);
2750   struct glyph *phys_cursor_glyph;
2751   struct glyph *cursor_glyph;
2752   struct face *face;
2753   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2755   /* If cursor is out of bounds, don't draw garbage.  This can happen
2756      in mini-buffer windows when switching between echo area glyphs
2757      and mini-buffer.  */
2759   NSTRACE ("ns_draw_window_cursor");
2761   if (!on_p)
2762     return;
2764   w->phys_cursor_type = cursor_type;
2765   w->phys_cursor_on_p = on_p;
2767   if (cursor_type == NO_CURSOR)
2768     {
2769       w->phys_cursor_width = 0;
2770       return;
2771     }
2773   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2774     {
2775       if (glyph_row->exact_window_width_line_p
2776           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2777         {
2778           glyph_row->cursor_in_fringe_p = 1;
2779           draw_fringe_bitmap (w, glyph_row, 0);
2780         }
2781       return;
2782     }
2784   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2785      (other terminals do it the other way round).  We must set
2786      w->phys_cursor_width to the cursor width.  For bar cursors, that
2787      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2788   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2790   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2791      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2792   if (cursor_type == BAR_CURSOR)
2793     {
2794       if (cursor_width < 1)
2795         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2797       /* The bar cursor should never be wider than the glyph. */
2798       if (cursor_width < w->phys_cursor_width)
2799         w->phys_cursor_width = cursor_width;
2800     }
2801   /* If we have an HBAR, "cursor_width" MAY specify height. */
2802   else if (cursor_type == HBAR_CURSOR)
2803     {
2804       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2805       if (cursor_height > glyph_row->height)
2806         cursor_height = glyph_row->height;
2807       if (h > cursor_height) // Cursor smaller than line height, move down
2808         fy += h - cursor_height;
2809       h = cursor_height;
2810     }
2812   r.origin.x = fx, r.origin.y = fy;
2813   r.size.height = h;
2814   r.size.width = w->phys_cursor_width;
2816   /* Prevent the cursor from being drawn outside the text area. */
2817   ns_clip_to_row (w, glyph_row, TEXT_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2820   face = FACE_FROM_ID_OR_NULL (f, phys_cursor_glyph->face_id);
2821   if (face && NS_FACE_BACKGROUND (face)
2822       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2823     {
2824       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2825       hollow_color = FRAME_CURSOR_COLOR (f);
2826     }
2827   else
2828     [FRAME_CURSOR_COLOR (f) set];
2830 #ifdef NS_IMPL_COCOA
2831   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2832            atomic.  Cleaner ways of doing this should be investigated.
2833            One way would be to set a global variable DRAWING_CURSOR
2834            when making the call to draw_phys..(), don't focus in that
2835            case, then move the ns_unfocus() here after that call. */
2836   NSDisableScreenUpdates ();
2837 #endif
2839   switch (cursor_type)
2840     {
2841     case DEFAULT_CURSOR:
2842     case NO_CURSOR:
2843       break;
2844     case FILLED_BOX_CURSOR:
2845       NSRectFill (r);
2846       break;
2847     case HOLLOW_BOX_CURSOR:
2848       NSRectFill (r);
2849       [hollow_color set];
2850       NSRectFill (NSInsetRect (r, 1, 1));
2851       [FRAME_CURSOR_COLOR (f) set];
2852       break;
2853     case HBAR_CURSOR:
2854       NSRectFill (r);
2855       break;
2856     case BAR_CURSOR:
2857       s = r;
2858       /* If the character under cursor is R2L, draw the bar cursor
2859          on the right of its glyph, rather than on the left.  */
2860       cursor_glyph = get_phys_cursor_glyph (w);
2861       if ((cursor_glyph->resolved_level & 1) != 0)
2862         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2864       NSRectFill (s);
2865       break;
2866     }
2867   ns_unfocus (f);
2869   /* draw the character under the cursor */
2870   if (cursor_type != NO_CURSOR)
2871     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2873 #ifdef NS_IMPL_COCOA
2874   NSEnableScreenUpdates ();
2875 #endif
2880 static void
2881 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2882 /* --------------------------------------------------------------------------
2883      External (RIF): Draw a vertical line.
2884    -------------------------------------------------------------------------- */
2886   struct frame *f = XFRAME (WINDOW_FRAME (w));
2887   struct face *face;
2888   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2890   NSTRACE ("ns_draw_vertical_window_border");
2892   face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
2894   ns_focus (f, &r, 1);
2895   if (face)
2896     [ns_lookup_indexed_color(face->foreground, f) set];
2898   NSRectFill(r);
2899   ns_unfocus (f);
2903 static void
2904 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2905 /* --------------------------------------------------------------------------
2906      External (RIF): Draw a window divider.
2907    -------------------------------------------------------------------------- */
2909   struct frame *f = XFRAME (WINDOW_FRAME (w));
2910   struct face *face;
2911   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2913   NSTRACE ("ns_draw_window_divider");
2915   face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
2917   ns_focus (f, &r, 1);
2918   if (face)
2919     [ns_lookup_indexed_color(face->foreground, f) set];
2921   NSRectFill(r);
2922   ns_unfocus (f);
2925 static void
2926 ns_show_hourglass (struct frame *f)
2928   /* TODO: add NSProgressIndicator to all frames.  */
2931 static void
2932 ns_hide_hourglass (struct frame *f)
2934   /* TODO: remove NSProgressIndicator from all frames.  */
2937 /* ==========================================================================
2939     Glyph drawing operations
2941    ========================================================================== */
2943 static int
2944 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2945 /* --------------------------------------------------------------------------
2946     Wrapper utility to account for internal border width on full-width lines,
2947     and allow top full-width rows to hit the frame top.  nr should be pointer
2948     to two successive NSRects.  Number of rects actually used is returned.
2949    -------------------------------------------------------------------------- */
2951   int n = get_glyph_string_clip_rects (s, nr, 2);
2952   return n;
2955 /* --------------------------------------------------------------------
2956    Draw a wavy line under glyph string s. The wave fills wave_height
2957    pixels from y.
2959                     x          wave_length = 2
2960                                  --
2961                 y    *   *   *   *   *
2962                      |* * * * * * * * *
2963     wave_height = 3  | *   *   *   *
2964   --------------------------------------------------------------------- */
2966 static void
2967 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2969   int wave_height = 3, wave_length = 2;
2970   int y, dx, dy, odd, xmax;
2971   NSPoint a, b;
2972   NSRect waveClip;
2974   dx = wave_length;
2975   dy = wave_height - 1;
2976   y =  s->ybase - wave_height + 3;
2977   xmax = x + width;
2979   /* Find and set clipping rectangle */
2980   waveClip = NSMakeRect (x, y, width, wave_height);
2981   [[NSGraphicsContext currentContext] saveGraphicsState];
2982   NSRectClip (waveClip);
2984   /* Draw the waves */
2985   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2986   b.x = a.x + dx;
2987   odd = (int)(a.x/dx) % 2;
2988   a.y = b.y = y + 0.5;
2990   if (odd)
2991     a.y += dy;
2992   else
2993     b.y += dy;
2995   while (a.x <= xmax)
2996     {
2997       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2998       a.x = b.x, a.y = b.y;
2999       b.x += dx, b.y = y + 0.5 + odd*dy;
3000       odd = !odd;
3001     }
3003   /* Restore previous clipping rectangle(s) */
3004   [[NSGraphicsContext currentContext] restoreGraphicsState];
3009 static void
3010 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
3011                          NSColor *defaultCol, CGFloat width, CGFloat x)
3012 /* --------------------------------------------------------------------------
3013    Draw underline, overline, and strike-through on glyph string s.
3014    -------------------------------------------------------------------------- */
3016   if (s->for_overlaps)
3017     return;
3019   /* Do underline. */
3020   if (face->underline_p)
3021     {
3022       if (s->face->underline_type == FACE_UNDER_WAVE)
3023         {
3024           if (face->underline_defaulted_p)
3025             [defaultCol set];
3026           else
3027             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3029           ns_draw_underwave (s, width, x);
3030         }
3031       else if (s->face->underline_type == FACE_UNDER_LINE)
3032         {
3034           NSRect r;
3035           unsigned long thickness, position;
3037           /* If the prev was underlined, match its appearance. */
3038           if (s->prev && s->prev->face->underline_p
3039               && s->prev->face->underline_type == FACE_UNDER_LINE
3040               && s->prev->underline_thickness > 0)
3041             {
3042               thickness = s->prev->underline_thickness;
3043               position = s->prev->underline_position;
3044             }
3045           else
3046             {
3047               struct font *font;
3048               unsigned long descent;
3050               font=s->font;
3051               descent = s->y + s->height - s->ybase;
3053               /* Use underline thickness of font, defaulting to 1. */
3054               thickness = (font && font->underline_thickness > 0)
3055                 ? font->underline_thickness : 1;
3057               /* Determine the offset of underlining from the baseline. */
3058               if (x_underline_at_descent_line)
3059                 position = descent - thickness;
3060               else if (x_use_underline_position_properties
3061                        && font && font->underline_position >= 0)
3062                 position = font->underline_position;
3063               else if (font)
3064                 position = lround (font->descent / 2);
3065               else
3066                 position = underline_minimum_offset;
3068               position = max (position, underline_minimum_offset);
3070               /* Ensure underlining is not cropped. */
3071               if (descent <= position)
3072                 {
3073                   position = descent - 1;
3074                   thickness = 1;
3075                 }
3076               else if (descent < position + thickness)
3077                 thickness = 1;
3078             }
3080           s->underline_thickness = thickness;
3081           s->underline_position = position;
3083           r = NSMakeRect (x, s->ybase + position, width, thickness);
3085           if (face->underline_defaulted_p)
3086             [defaultCol set];
3087           else
3088             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3089           NSRectFill (r);
3090         }
3091     }
3092   /* Do overline. We follow other terms in using a thickness of 1
3093      and ignoring overline_margin. */
3094   if (face->overline_p)
3095     {
3096       NSRect r;
3097       r = NSMakeRect (x, s->y, width, 1);
3099       if (face->overline_color_defaulted_p)
3100         [defaultCol set];
3101       else
3102         [ns_lookup_indexed_color (face->overline_color, s->f) set];
3103       NSRectFill (r);
3104     }
3106   /* Do strike-through.  We follow other terms for thickness and
3107      vertical position.*/
3108   if (face->strike_through_p)
3109     {
3110       NSRect r;
3111       unsigned long dy;
3113       dy = lrint ((s->height - 1) / 2);
3114       r = NSMakeRect (x, s->y + dy, width, 1);
3116       if (face->strike_through_color_defaulted_p)
3117         [defaultCol set];
3118       else
3119         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3120       NSRectFill (r);
3121     }
3124 static void
3125 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3126              char left_p, char right_p)
3127 /* --------------------------------------------------------------------------
3128     Draw an unfilled rect inside r, optionally leaving left and/or right open.
3129     Note we can't just use an NSDrawRect command, because of the possibility
3130     of some sides not being drawn, and because the rect will be filled.
3131    -------------------------------------------------------------------------- */
3133   NSRect s = r;
3134   [col set];
3136   /* top, bottom */
3137   s.size.height = thickness;
3138   NSRectFill (s);
3139   s.origin.y += r.size.height - thickness;
3140   NSRectFill (s);
3142   s.size.height = r.size.height;
3143   s.origin.y = r.origin.y;
3145   /* left, right (optional) */
3146   s.size.width = thickness;
3147   if (left_p)
3148     NSRectFill (s);
3149   if (right_p)
3150     {
3151       s.origin.x += r.size.width - thickness;
3152       NSRectFill (s);
3153     }
3157 static void
3158 ns_draw_relief (NSRect r, int thickness, char raised_p,
3159                char top_p, char bottom_p, char left_p, char right_p,
3160                struct glyph_string *s)
3161 /* --------------------------------------------------------------------------
3162     Draw a relief rect inside r, optionally leaving some sides open.
3163     Note we can't just use an NSDrawBezel command, because of the possibility
3164     of some sides not being drawn, and because the rect will be filled.
3165    -------------------------------------------------------------------------- */
3167   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3168   NSColor *newBaseCol = nil;
3169   NSRect sr = r;
3171   NSTRACE ("ns_draw_relief");
3173   /* set up colors */
3175   if (s->face->use_box_color_for_shadows_p)
3176     {
3177       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3178     }
3179 /*     else if (s->first_glyph->type == IMAGE_GLYPH
3180            && s->img->pixmap
3181            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3182        {
3183          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
3184        } */
3185   else
3186     {
3187       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3188     }
3190   if (newBaseCol == nil)
3191     newBaseCol = [NSColor grayColor];
3193   if (newBaseCol != baseCol)  /* TODO: better check */
3194     {
3195       [baseCol release];
3196       baseCol = [newBaseCol retain];
3197       [lightCol release];
3198       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3199       [darkCol release];
3200       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3201     }
3203   [(raised_p ? lightCol : darkCol) set];
3205   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3207   /* top */
3208   sr.size.height = thickness;
3209   if (top_p) NSRectFill (sr);
3211   /* left */
3212   sr.size.height = r.size.height;
3213   sr.size.width = thickness;
3214   if (left_p) NSRectFill (sr);
3216   [(raised_p ? darkCol : lightCol) set];
3218   /* bottom */
3219   sr.size.width = r.size.width;
3220   sr.size.height = thickness;
3221   sr.origin.y += r.size.height - thickness;
3222   if (bottom_p) NSRectFill (sr);
3224   /* right */
3225   sr.size.height = r.size.height;
3226   sr.origin.y = r.origin.y;
3227   sr.size.width = thickness;
3228   sr.origin.x += r.size.width - thickness;
3229   if (right_p) NSRectFill (sr);
3233 static void
3234 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3235 /* --------------------------------------------------------------------------
3236       Function modeled after x_draw_glyph_string_box ().
3237       Sets up parameters for drawing.
3238    -------------------------------------------------------------------------- */
3240   int right_x, last_x;
3241   char left_p, right_p;
3242   struct glyph *last_glyph;
3243   NSRect r;
3244   int thickness;
3245   struct face *face;
3247   if (s->hl == DRAW_MOUSE_FACE)
3248     {
3249       face = FACE_FROM_ID_OR_NULL (s->f,
3250                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3251       if (!face)
3252         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3253     }
3254   else
3255     face = s->face;
3257   thickness = face->box_line_width;
3259   NSTRACE ("ns_dumpglyphs_box_or_relief");
3261   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3262             ? WINDOW_RIGHT_EDGE_X (s->w)
3263             : window_box_right (s->w, s->area));
3264   last_glyph = (s->cmp || s->img
3265                 ? s->first_glyph : s->first_glyph + s->nchars-1);
3267   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3268               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3270   left_p = (s->first_glyph->left_box_line_p
3271             || (s->hl == DRAW_MOUSE_FACE
3272                 && (s->prev == NULL || s->prev->hl != s->hl)));
3273   right_p = (last_glyph->right_box_line_p
3274              || (s->hl == DRAW_MOUSE_FACE
3275                  && (s->next == NULL || s->next->hl != s->hl)));
3277   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3279   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3280   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3281     {
3282       ns_draw_box (r, abs (thickness),
3283                    ns_lookup_indexed_color (face->box_color, s->f),
3284                   left_p, right_p);
3285     }
3286   else
3287     {
3288       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3289                      1, 1, left_p, right_p, s);
3290     }
3294 static void
3295 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3296 /* --------------------------------------------------------------------------
3297       Modeled after x_draw_glyph_string_background, which draws BG in
3298       certain cases.  Others are left to the text rendering routine.
3299    -------------------------------------------------------------------------- */
3301   NSTRACE ("ns_maybe_dumpglyphs_background");
3303   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3304     {
3305       int box_line_width = max (s->face->box_line_width, 0);
3306       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3307           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3308              dimensions, since the actual glyphs might be much
3309              smaller.  So in that case we always clear the rectangle
3310              with background color.  */
3311           || FONT_TOO_HIGH (s->font)
3312           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3313         {
3314           struct face *face;
3315           if (s->hl == DRAW_MOUSE_FACE)
3316             {
3317               face
3318                 = FACE_FROM_ID_OR_NULL (s->f,
3319                                         MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3320               if (!face)
3321                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3322             }
3323           else
3324             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3325           if (!face->stipple)
3326             [(NS_FACE_BACKGROUND (face) != 0
3327               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3328               : FRAME_BACKGROUND_COLOR (s->f)) set];
3329           else
3330             {
3331               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3332               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3333             }
3335           if (s->hl != DRAW_CURSOR)
3336             {
3337               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3338                                     s->background_width,
3339                                     s->height-2*box_line_width);
3340               NSRectFill (r);
3341             }
3343           s->background_filled_p = 1;
3344         }
3345     }
3349 static void
3350 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3351 /* --------------------------------------------------------------------------
3352       Renders an image and associated borders.
3353    -------------------------------------------------------------------------- */
3355   EmacsImage *img = s->img->pixmap;
3356   int box_line_vwidth = max (s->face->box_line_width, 0);
3357   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3358   int bg_x, bg_y, bg_height;
3359   int th;
3360   char raised_p;
3361   NSRect br;
3362   struct face *face;
3363   NSColor *tdCol;
3365   NSTRACE ("ns_dumpglyphs_image");
3367   if (s->face->box != FACE_NO_BOX
3368       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3369     x += abs (s->face->box_line_width);
3371   bg_x = x;
3372   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3373   bg_height = s->height;
3374   /* other terms have this, but was causing problems w/tabbar mode */
3375   /* - 2 * box_line_vwidth; */
3377   if (s->slice.x == 0) x += s->img->hmargin;
3378   if (s->slice.y == 0) y += s->img->vmargin;
3380   /* Draw BG: if we need larger area than image itself cleared, do that,
3381      otherwise, since we composite the image under NS (instead of mucking
3382      with its background color), we must clear just the image area. */
3383   if (s->hl == DRAW_MOUSE_FACE)
3384     {
3385       face = FACE_FROM_ID_OR_NULL (s->f,
3386                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3387       if (!face)
3388        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3389     }
3390   else
3391     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3393   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3395   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3396       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3397     {
3398       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3399       s->background_filled_p = 1;
3400     }
3401   else
3402     {
3403       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3404     }
3406   NSRectFill (br);
3408   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3409   if (img != nil)
3410     {
3411 #ifdef NS_IMPL_COCOA
3412       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3413       NSRect ir = NSMakeRect (s->slice.x,
3414                               s->img->height - s->slice.y - s->slice.height,
3415                               s->slice.width, s->slice.height);
3416       [img drawInRect: dr
3417              fromRect: ir
3418              operation: NSCompositingOperationSourceOver
3419               fraction: 1.0
3420            respectFlipped: YES
3421                 hints: nil];
3422 #else
3423       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3424                   operation: NSCompositingOperationSourceOver];
3425 #endif
3426     }
3428   if (s->hl == DRAW_CURSOR)
3429     {
3430     [FRAME_CURSOR_COLOR (s->f) set];
3431     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3432       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3433     else
3434       /* Currently on NS img->mask is always 0. Since
3435          get_window_cursor_type specifies a hollow box cursor when on
3436          a non-masked image we never reach this clause. But we put it
3437          in in anticipation of better support for image masks on
3438          NS. */
3439       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3440     }
3441   else
3442     {
3443       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3444     }
3446   /* Draw underline, overline, strike-through. */
3447   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3449   /* Draw relief, if requested */
3450   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3451     {
3452       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3453         {
3454           th = tool_bar_button_relief >= 0 ?
3455             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3456           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3457         }
3458       else
3459         {
3460           th = abs (s->img->relief);
3461           raised_p = (s->img->relief > 0);
3462         }
3464       r.origin.x = x - th;
3465       r.origin.y = y - th;
3466       r.size.width = s->slice.width + 2*th-1;
3467       r.size.height = s->slice.height + 2*th-1;
3468       ns_draw_relief (r, th, raised_p,
3469                       s->slice.y == 0,
3470                       s->slice.y + s->slice.height == s->img->height,
3471                       s->slice.x == 0,
3472                       s->slice.x + s->slice.width == s->img->width, s);
3473     }
3475   /* If there is no mask, the background won't be seen,
3476      so draw a rectangle on the image for the cursor.
3477      Do this for all images, getting transparency right is not reliable.  */
3478   if (s->hl == DRAW_CURSOR)
3479     {
3480       int thickness = abs (s->img->relief);
3481       if (thickness == 0) thickness = 1;
3482       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3483     }
3487 static void
3488 ns_dumpglyphs_stretch (struct glyph_string *s)
3490   NSRect r[2];
3491   int n, i;
3492   struct face *face;
3493   NSColor *fgCol, *bgCol;
3495   if (!s->background_filled_p)
3496     {
3497       n = ns_get_glyph_string_clip_rect (s, r);
3498       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3500       ns_focus (s->f, r, n);
3502       if (s->hl == DRAW_MOUSE_FACE)
3503        {
3504          face = FACE_FROM_ID_OR_NULL (s->f,
3505                                       MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3506          if (!face)
3507            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3508        }
3509       else
3510        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3512       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3513       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3515       for (i = 0; i < n; ++i)
3516         {
3517           if (!s->row->full_width_p)
3518             {
3519               int overrun, leftoverrun;
3521               /* truncate to avoid overwriting fringe and/or scrollbar */
3522               overrun = max (0, (s->x + s->background_width)
3523                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3524                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3525               r[i].size.width -= overrun;
3527               /* truncate to avoid overwriting to left of the window box */
3528               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3529                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3531               if (leftoverrun > 0)
3532                 {
3533                   r[i].origin.x += leftoverrun;
3534                   r[i].size.width -= leftoverrun;
3535                 }
3537               /* XXX: Try to work between problem where a stretch glyph on
3538                  a partially-visible bottom row will clear part of the
3539                  modeline, and another where list-buffers headers and similar
3540                  rows erroneously have visible_height set to 0.  Not sure
3541                  where this is coming from as other terms seem not to show. */
3542               r[i].size.height = min (s->height, s->row->visible_height);
3543             }
3545           [bgCol set];
3547           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3548              overwriting cursor (usually when cursor on a tab) */
3549           if (s->hl == DRAW_CURSOR)
3550             {
3551               CGFloat x, width;
3553               x = r[i].origin.x;
3554               width = s->w->phys_cursor_width;
3555               r[i].size.width -= width;
3556               r[i].origin.x += width;
3558               NSRectFill (r[i]);
3560               /* Draw overlining, etc. on the cursor. */
3561               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3562                 ns_draw_text_decoration (s, face, bgCol, width, x);
3563               else
3564                 ns_draw_text_decoration (s, face, fgCol, width, x);
3565             }
3566           else
3567             {
3568               NSRectFill (r[i]);
3569             }
3571           /* Draw overlining, etc. on the stretch glyph (or the part
3572              of the stretch glyph after the cursor). */
3573           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3574                                    r[i].origin.x);
3575         }
3576       ns_unfocus (s->f);
3577       s->background_filled_p = 1;
3578     }
3582 static void
3583 ns_draw_glyph_string_foreground (struct glyph_string *s)
3585   int x, flags;
3586   struct font *font = s->font;
3588   /* If first glyph of S has a left box line, start drawing the text
3589      of S to the right of that box line.  */
3590   if (s->face && s->face->box != FACE_NO_BOX
3591       && s->first_glyph->left_box_line_p)
3592     x = s->x + eabs (s->face->box_line_width);
3593   else
3594     x = s->x;
3596   flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3597     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3598      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3599       NS_DUMPGLYPH_NORMAL));
3601   font->driver->draw
3602     (s, s->cmp_from, s->nchars, x, s->ybase,
3603      (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3604      || flags == NS_DUMPGLYPH_MOUSEFACE);
3608 static void
3609 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3611   int i, j, x;
3612   struct font *font = s->font;
3614   /* If first glyph of S has a left box line, start drawing the text
3615      of S to the right of that box line.  */
3616   if (s->face && s->face->box != FACE_NO_BOX
3617       && s->first_glyph->left_box_line_p)
3618     x = s->x + eabs (s->face->box_line_width);
3619   else
3620     x = s->x;
3622   /* S is a glyph string for a composition.  S->cmp_from is the index
3623      of the first character drawn for glyphs of this composition.
3624      S->cmp_from == 0 means we are drawing the very first character of
3625      this composition.  */
3627   /* Draw a rectangle for the composition if the font for the very
3628      first character of the composition could not be loaded.  */
3629   if (s->font_not_found_p)
3630     {
3631       if (s->cmp_from == 0)
3632         {
3633           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3634           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3635         }
3636     }
3637   else if (! s->first_glyph->u.cmp.automatic)
3638     {
3639       int y = s->ybase;
3641       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3642         /* TAB in a composition means display glyphs with padding
3643            space on the left or right.  */
3644         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3645           {
3646             int xx = x + s->cmp->offsets[j * 2];
3647             int yy = y - s->cmp->offsets[j * 2 + 1];
3649             font->driver->draw (s, j, j + 1, xx, yy, false);
3650             if (s->face->overstrike)
3651               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3652           }
3653     }
3654   else
3655     {
3656       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3657       Lisp_Object glyph;
3658       int y = s->ybase;
3659       int width = 0;
3661       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3662         {
3663           glyph = LGSTRING_GLYPH (gstring, i);
3664           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3665             width += LGLYPH_WIDTH (glyph);
3666           else
3667             {
3668               int xoff, yoff, wadjust;
3670               if (j < i)
3671                 {
3672                   font->driver->draw (s, j, i, x, y, false);
3673                   if (s->face->overstrike)
3674                     font->driver->draw (s, j, i, x + 1, y, false);
3675                   x += width;
3676                 }
3677               xoff = LGLYPH_XOFF (glyph);
3678               yoff = LGLYPH_YOFF (glyph);
3679               wadjust = LGLYPH_WADJUST (glyph);
3680               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3681               if (s->face->overstrike)
3682                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3683                                     false);
3684               x += wadjust;
3685               j = i + 1;
3686               width = 0;
3687             }
3688         }
3689       if (j < i)
3690         {
3691           font->driver->draw (s, j, i, x, y, false);
3692           if (s->face->overstrike)
3693             font->driver->draw (s, j, i, x + 1, y, false);
3694         }
3695     }
3698 static void
3699 ns_draw_glyph_string (struct glyph_string *s)
3700 /* --------------------------------------------------------------------------
3701       External (RIF): Main draw-text call.
3702    -------------------------------------------------------------------------- */
3704   /* TODO (optimize): focus for box and contents draw */
3705   NSRect r[2];
3706   int n;
3707   char box_drawn_p = 0;
3708   struct font *font = s->face->font;
3709   if (! font) font = FRAME_FONT (s->f);
3711   NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3713   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3714     {
3715       int width;
3716       struct glyph_string *next;
3718       for (width = 0, next = s->next;
3719            next && width < s->right_overhang;
3720            width += next->width, next = next->next)
3721         if (next->first_glyph->type != IMAGE_GLYPH)
3722           {
3723             if (next->first_glyph->type != STRETCH_GLYPH)
3724               {
3725                 n = ns_get_glyph_string_clip_rect (s->next, r);
3726                 ns_focus (s->f, r, n);
3727                 ns_maybe_dumpglyphs_background (s->next, 1);
3728                 ns_unfocus (s->f);
3729               }
3730             else
3731               {
3732                 ns_dumpglyphs_stretch (s->next);
3733               }
3734             next->num_clips = 0;
3735           }
3736     }
3738   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3739         && (s->first_glyph->type == CHAR_GLYPH
3740             || s->first_glyph->type == COMPOSITE_GLYPH))
3741     {
3742       n = ns_get_glyph_string_clip_rect (s, r);
3743       ns_focus (s->f, r, n);
3744       ns_maybe_dumpglyphs_background (s, 1);
3745       ns_dumpglyphs_box_or_relief (s);
3746       ns_unfocus (s->f);
3747       box_drawn_p = 1;
3748     }
3750   switch (s->first_glyph->type)
3751     {
3753     case IMAGE_GLYPH:
3754       n = ns_get_glyph_string_clip_rect (s, r);
3755       ns_focus (s->f, r, n);
3756       ns_dumpglyphs_image (s, r[0]);
3757       ns_unfocus (s->f);
3758       break;
3760     case STRETCH_GLYPH:
3761       ns_dumpglyphs_stretch (s);
3762       break;
3764     case CHAR_GLYPH:
3765     case COMPOSITE_GLYPH:
3766       n = ns_get_glyph_string_clip_rect (s, r);
3767       ns_focus (s->f, r, n);
3769       if (s->for_overlaps || (s->cmp_from > 0
3770                               && ! s->first_glyph->u.cmp.automatic))
3771         s->background_filled_p = 1;
3772       else
3773         ns_maybe_dumpglyphs_background
3774           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3776       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3777         {
3778           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3779           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3780           NS_FACE_FOREGROUND (s->face) = tmp;
3781         }
3783       {
3784         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3786         if (isComposite)
3787           ns_draw_composite_glyph_string_foreground (s);
3788         else
3789           ns_draw_glyph_string_foreground (s);
3790       }
3792       {
3793         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3794                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3795                                                    s->f)
3796                         : FRAME_FOREGROUND_COLOR (s->f));
3797         [col set];
3799         /* Draw underline, overline, strike-through. */
3800         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3801       }
3803       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3804         {
3805           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3806           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3807           NS_FACE_FOREGROUND (s->face) = tmp;
3808         }
3810       ns_unfocus (s->f);
3811       break;
3813     case GLYPHLESS_GLYPH:
3814       n = ns_get_glyph_string_clip_rect (s, r);
3815       ns_focus (s->f, r, n);
3817       if (s->for_overlaps || (s->cmp_from > 0
3818                               && ! s->first_glyph->u.cmp.automatic))
3819         s->background_filled_p = 1;
3820       else
3821         ns_maybe_dumpglyphs_background
3822           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3823       /* ... */
3824       /* Not yet implemented.  */
3825       /* ... */
3826       ns_unfocus (s->f);
3827       break;
3829     default:
3830       emacs_abort ();
3831     }
3833   /* Draw box if not done already. */
3834   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3835     {
3836       n = ns_get_glyph_string_clip_rect (s, r);
3837       ns_focus (s->f, r, n);
3838       ns_dumpglyphs_box_or_relief (s);
3839       ns_unfocus (s->f);
3840     }
3842   s->num_clips = 0;
3847 /* ==========================================================================
3849     Event loop
3851    ========================================================================== */
3854 static void
3855 ns_send_appdefined (int value)
3856 /* --------------------------------------------------------------------------
3857     Internal: post an appdefined event which EmacsApp-sendEvent will
3858               recognize and take as a command to halt the event loop.
3859    -------------------------------------------------------------------------- */
3861   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3863   // GNUstep needs postEvent to happen on the main thread.
3864   // Cocoa needs nextEventMatchingMask to happen on the main thread too.
3865   if (! [[NSThread currentThread] isMainThread])
3866     {
3867       EmacsApp *app = (EmacsApp *)NSApp;
3868       app->nextappdefined = value;
3869       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3870                             withObject:nil
3871                          waitUntilDone:YES];
3872       return;
3873     }
3875   /* Only post this event if we haven't already posted one.  This will end
3876        the [NXApp run] main loop after having processed all events queued at
3877        this moment.  */
3879 #ifdef NS_IMPL_COCOA
3880   if (! send_appdefined)
3881     {
3882       /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3883          in certain situations (rapid incoming events).
3884          So check if we have one, if not add one.  */
3885       NSEvent *appev = [NSApp nextEventMatchingMask:NSEventMaskApplicationDefined
3886                                           untilDate:[NSDate distantPast]
3887                                              inMode:NSDefaultRunLoopMode
3888                                             dequeue:NO];
3889       if (! appev) send_appdefined = YES;
3890     }
3891 #endif
3893   if (send_appdefined)
3894     {
3895       NSEvent *nxev;
3897       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3898       send_appdefined = NO;
3900       /* Don't need wakeup timer any more */
3901       if (timed_entry)
3902         {
3903           [timed_entry invalidate];
3904           [timed_entry release];
3905           timed_entry = nil;
3906         }
3908       nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
3909                                 location: NSMakePoint (0, 0)
3910                            modifierFlags: 0
3911                                timestamp: 0
3912                             windowNumber: [[NSApp mainWindow] windowNumber]
3913                                  context: [NSApp context]
3914                                  subtype: 0
3915                                    data1: value
3916                                    data2: 0];
3918       /* Post an application defined event on the event queue.  When this is
3919          received the [NXApp run] will return, thus having processed all
3920          events which are currently queued.  */
3921       [NSApp postEvent: nxev atStart: NO];
3922     }
3925 #ifdef HAVE_NATIVE_FS
3926 static void
3927 check_native_fs ()
3929   Lisp_Object frame, tail;
3931   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3932     return;
3934   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3936   FOR_EACH_FRAME (tail, frame)
3937     {
3938       struct frame *f = XFRAME (frame);
3939       if (FRAME_NS_P (f))
3940         {
3941           EmacsView *view = FRAME_NS_VIEW (f);
3942           [view updateCollectionBehavior];
3943         }
3944     }
3946 #endif
3948 /* GNUstep does not have cancelTracking.  */
3949 #ifdef NS_IMPL_COCOA
3950 /* Check if menu open should be canceled or continued as normal.  */
3951 void
3952 ns_check_menu_open (NSMenu *menu)
3954   /* Click in menu bar? */
3955   NSArray *a = [[NSApp mainMenu] itemArray];
3956   int i;
3957   BOOL found = NO;
3959   if (menu == nil) // Menu tracking ended.
3960     {
3961       if (menu_will_open_state == MENU_OPENING)
3962         menu_will_open_state = MENU_NONE;
3963       return;
3964     }
3966   for (i = 0; ! found && i < [a count]; i++)
3967     found = menu == [[a objectAtIndex:i] submenu];
3968   if (found)
3969     {
3970       if (menu_will_open_state == MENU_NONE && emacs_event)
3971         {
3972           NSEvent *theEvent = [NSApp currentEvent];
3973           struct frame *emacsframe = SELECTED_FRAME ();
3975           [menu cancelTracking];
3976           menu_will_open_state = MENU_PENDING;
3977           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3978           EV_TRAILER (theEvent);
3980           CGEventRef ourEvent = CGEventCreate (NULL);
3981           menu_mouse_point = CGEventGetLocation (ourEvent);
3982           CFRelease (ourEvent);
3983         }
3984       else if (menu_will_open_state == MENU_OPENING)
3985         {
3986           menu_will_open_state = MENU_NONE;
3987         }
3988     }
3991 /* Redo saved menu click if state is MENU_PENDING.  */
3992 void
3993 ns_check_pending_open_menu ()
3995   if (menu_will_open_state == MENU_PENDING)
3996     {
3997       CGEventSourceRef source
3998         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
4000       CGEventRef event = CGEventCreateMouseEvent (source,
4001                                                   kCGEventLeftMouseDown,
4002                                                   menu_mouse_point,
4003                                                   kCGMouseButtonLeft);
4004       CGEventSetType (event, kCGEventLeftMouseDown);
4005       CGEventPost (kCGHIDEventTap, event);
4006       CFRelease (event);
4007       CFRelease (source);
4009       menu_will_open_state = MENU_OPENING;
4010     }
4012 #endif /* NS_IMPL_COCOA */
4014 static void
4015 unwind_apploopnr (Lisp_Object not_used)
4017   --apploopnr;
4018   n_emacs_events_pending = 0;
4019   ns_finish_events ();
4020   q_event_ptr = NULL;
4023 static int
4024 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
4025 /* --------------------------------------------------------------------------
4026      External (hook): Post an event to ourself and keep reading events until
4027      we read it back again.  In effect process all events which were waiting.
4028      From 21+ we have to manage the event buffer ourselves.
4029    -------------------------------------------------------------------------- */
4031   struct input_event ev;
4032   int nevents;
4034   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
4036   if (apploopnr > 0)
4037     return -1; /* Already within event loop. */
4039 #ifdef HAVE_NATIVE_FS
4040   check_native_fs ();
4041 #endif
4043   if ([NSApp modalWindow] != nil)
4044     return -1;
4046   if (hold_event_q.nr > 0)
4047     {
4048       int i;
4049       for (i = 0; i < hold_event_q.nr; ++i)
4050         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4051       hold_event_q.nr = 0;
4052       return i;
4053     }
4055   block_input ();
4056   n_emacs_events_pending = 0;
4057   ns_init_events (&ev);
4058   q_event_ptr = hold_quit;
4060   /* we manage autorelease pools by allocate/reallocate each time around
4061      the loop; strict nesting is occasionally violated but seems not to
4062      matter.. earlier methods using full nesting caused major memory leaks */
4063   [outerpool release];
4064   outerpool = [[NSAutoreleasePool alloc] init];
4066   /* If have pending open-file requests, attend to the next one of those. */
4067   if (ns_pending_files && [ns_pending_files count] != 0
4068       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4069     {
4070       [ns_pending_files removeObjectAtIndex: 0];
4071     }
4072   /* Deal with pending service requests. */
4073   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4074     && [(EmacsApp *)
4075          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4076                       withArg: [ns_pending_service_args objectAtIndex: 0]])
4077     {
4078       [ns_pending_service_names removeObjectAtIndex: 0];
4079       [ns_pending_service_args removeObjectAtIndex: 0];
4080     }
4081   else
4082     {
4083       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4084       /* Run and wait for events.  We must always send one NX_APPDEFINED event
4085          to ourself, otherwise [NXApp run] will never exit.  */
4086       send_appdefined = YES;
4087       ns_send_appdefined (-1);
4089       if (++apploopnr != 1)
4090         {
4091           emacs_abort ();
4092         }
4093       record_unwind_protect (unwind_apploopnr, Qt);
4094       [NSApp run];
4095       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4096     }
4098   nevents = n_emacs_events_pending;
4099   n_emacs_events_pending = 0;
4100   ns_finish_events ();
4101   q_event_ptr = NULL;
4102   unblock_input ();
4104   return nevents;
4109 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4110            fd_set *exceptfds, struct timespec const *timeout,
4111            sigset_t const *sigmask)
4112 /* --------------------------------------------------------------------------
4113      Replacement for select, checking for events
4114    -------------------------------------------------------------------------- */
4116   int result;
4117   int t, k, nr = 0;
4118   struct input_event event;
4119   char c;
4121   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4123   if (apploopnr > 0)
4124     return -1; /* Already within event loop. */
4126 #ifdef HAVE_NATIVE_FS
4127   check_native_fs ();
4128 #endif
4130   if (hold_event_q.nr > 0)
4131     {
4132       /* We already have events pending. */
4133       raise (SIGIO);
4134       errno = EINTR;
4135       return -1;
4136     }
4138   for (k = 0; k < nfds+1; k++)
4139     {
4140       if (readfds && FD_ISSET(k, readfds)) ++nr;
4141       if (writefds && FD_ISSET(k, writefds)) ++nr;
4142     }
4144   if (NSApp == nil
4145       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4146     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4148   [outerpool release];
4149   outerpool = [[NSAutoreleasePool alloc] init];
4152   send_appdefined = YES;
4153   if (nr > 0)
4154     {
4155       pthread_mutex_lock (&select_mutex);
4156       select_nfds = nfds;
4157       select_valid = 0;
4158       if (readfds)
4159         {
4160           select_readfds = *readfds;
4161           select_valid += SELECT_HAVE_READ;
4162         }
4163       if (writefds)
4164         {
4165           select_writefds = *writefds;
4166           select_valid += SELECT_HAVE_WRITE;
4167         }
4169       if (timeout)
4170         {
4171           select_timeout = *timeout;
4172           select_valid += SELECT_HAVE_TMO;
4173         }
4175       pthread_mutex_unlock (&select_mutex);
4177       /* Inform fd_handler that select should be called */
4178       c = 'g';
4179       emacs_write_sig (selfds[1], &c, 1);
4180     }
4181   else if (nr == 0 && timeout)
4182     {
4183       /* No file descriptor, just a timeout, no need to wake fd_handler  */
4184       double time = timespectod (*timeout);
4185       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4186                                                       target: NSApp
4187                                                     selector:
4188                                   @selector (timeout_handler:)
4189                                                     userInfo: 0
4190                                                      repeats: NO]
4191                       retain];
4192     }
4193   else /* No timeout and no file descriptors, can this happen?  */
4194     {
4195       /* Send appdefined so we exit from the loop */
4196       ns_send_appdefined (-1);
4197     }
4199   block_input ();
4200   ns_init_events (&event);
4201   if (++apploopnr != 1)
4202     {
4203       emacs_abort ();
4204     }
4206   {
4207     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4208     record_unwind_protect (unwind_apploopnr, Qt);
4209     [NSApp run];
4210     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4211   }
4213   ns_finish_events ();
4214   if (nr > 0 && readfds)
4215     {
4216       c = 's';
4217       emacs_write_sig (selfds[1], &c, 1);
4218     }
4219   unblock_input ();
4221   t = last_appdefined_event_data;
4223   if (t != NO_APPDEFINED_DATA)
4224     {
4225       last_appdefined_event_data = NO_APPDEFINED_DATA;
4227       if (t == -2)
4228         {
4229           /* The NX_APPDEFINED event we received was a timeout. */
4230           result = 0;
4231         }
4232       else if (t == -1)
4233         {
4234           /* The NX_APPDEFINED event we received was the result of
4235              at least one real input event arriving.  */
4236           errno = EINTR;
4237           result = -1;
4238         }
4239       else
4240         {
4241           /* Received back from select () in fd_handler; copy the results */
4242           pthread_mutex_lock (&select_mutex);
4243           if (readfds) *readfds = select_readfds;
4244           if (writefds) *writefds = select_writefds;
4245           pthread_mutex_unlock (&select_mutex);
4246           result = t;
4247         }
4248     }
4249   else
4250     {
4251       errno = EINTR;
4252       result = -1;
4253     }
4255   return result;
4260 /* ==========================================================================
4262     Scrollbar handling
4264    ========================================================================== */
4267 static void
4268 ns_set_vertical_scroll_bar (struct window *window,
4269                            int portion, int whole, int position)
4270 /* --------------------------------------------------------------------------
4271       External (hook): Update or add scrollbar
4272    -------------------------------------------------------------------------- */
4274   Lisp_Object win;
4275   NSRect r, v;
4276   struct frame *f = XFRAME (WINDOW_FRAME (window));
4277   EmacsView *view = FRAME_NS_VIEW (f);
4278   EmacsScroller *bar;
4279   int window_y, window_height;
4280   int top, left, height, width;
4281   BOOL update_p = YES;
4283   /* optimization; display engine sends WAY too many of these.. */
4284   if (!NILP (window->vertical_scroll_bar))
4285     {
4286       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4287       if ([bar checkSamePosition: position portion: portion whole: whole])
4288         {
4289           if (view->scrollbarsNeedingUpdate == 0)
4290             {
4291               if (!windows_or_buffers_changed)
4292                   return;
4293             }
4294           else
4295             view->scrollbarsNeedingUpdate--;
4296           update_p = NO;
4297         }
4298     }
4300   NSTRACE ("ns_set_vertical_scroll_bar");
4302   /* Get dimensions.  */
4303   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4304   top = window_y;
4305   height = window_height;
4306   width = NS_SCROLL_BAR_WIDTH (f);
4307   left = WINDOW_SCROLL_BAR_AREA_X (window);
4309   r = NSMakeRect (left, top, width, height);
4310   /* the parent view is flipped, so we need to flip y value */
4311   v = [view frame];
4312   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4314   XSETWINDOW (win, window);
4315   block_input ();
4317   /* we want at least 5 lines to display a scrollbar */
4318   if (WINDOW_TOTAL_LINES (window) < 5)
4319     {
4320       if (!NILP (window->vertical_scroll_bar))
4321         {
4322           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4323           [bar removeFromSuperview];
4324           wset_vertical_scroll_bar (window, Qnil);
4325           [bar release];
4326         }
4327       ns_clear_frame_area (f, left, top, width, height);
4328       unblock_input ();
4329       return;
4330     }
4332   if (NILP (window->vertical_scroll_bar))
4333     {
4334       if (width > 0 && height > 0)
4335         ns_clear_frame_area (f, left, top, width, height);
4337       bar = [[EmacsScroller alloc] initFrame: r window: win];
4338       wset_vertical_scroll_bar (window, make_save_ptr (bar));
4339       update_p = YES;
4340     }
4341   else
4342     {
4343       NSRect oldRect;
4344       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4345       oldRect = [bar frame];
4346       r.size.width = oldRect.size.width;
4347       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4348         {
4349           if (oldRect.origin.x != r.origin.x)
4350               ns_clear_frame_area (f, left, top, width, height);
4351           [bar setFrame: r];
4352         }
4353     }
4355   if (update_p)
4356     [bar setPosition: position portion: portion whole: whole];
4357   unblock_input ();
4361 static void
4362 ns_set_horizontal_scroll_bar (struct window *window,
4363                               int portion, int whole, int position)
4364 /* --------------------------------------------------------------------------
4365       External (hook): Update or add scrollbar
4366    -------------------------------------------------------------------------- */
4368   Lisp_Object win;
4369   NSRect r, v;
4370   struct frame *f = XFRAME (WINDOW_FRAME (window));
4371   EmacsView *view = FRAME_NS_VIEW (f);
4372   EmacsScroller *bar;
4373   int top, height, left, width;
4374   int window_x, window_width;
4375   BOOL update_p = YES;
4377   /* optimization; display engine sends WAY too many of these.. */
4378   if (!NILP (window->horizontal_scroll_bar))
4379     {
4380       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4381       if ([bar checkSamePosition: position portion: portion whole: whole])
4382         {
4383           if (view->scrollbarsNeedingUpdate == 0)
4384             {
4385               if (!windows_or_buffers_changed)
4386                   return;
4387             }
4388           else
4389             view->scrollbarsNeedingUpdate--;
4390           update_p = NO;
4391         }
4392     }
4394   NSTRACE ("ns_set_horizontal_scroll_bar");
4396   /* Get dimensions.  */
4397   window_box (window, ANY_AREA, &window_x, 0, &window_width, 0);
4398   left = window_x;
4399   width = window_width;
4400   height = NS_SCROLL_BAR_HEIGHT (f);
4401   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4403   r = NSMakeRect (left, top, width, height);
4404   /* the parent view is flipped, so we need to flip y value */
4405   v = [view frame];
4406   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4408   XSETWINDOW (win, window);
4409   block_input ();
4411   if (NILP (window->horizontal_scroll_bar))
4412     {
4413       if (width > 0 && height > 0)
4414         ns_clear_frame_area (f, left, top, width, height);
4416       bar = [[EmacsScroller alloc] initFrame: r window: win];
4417       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4418       update_p = YES;
4419     }
4420   else
4421     {
4422       NSRect oldRect;
4423       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4424       oldRect = [bar frame];
4425       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4426         {
4427           if (oldRect.origin.y != r.origin.y)
4428             ns_clear_frame_area (f, left, top, width, height);
4429           [bar setFrame: r];
4430           update_p = YES;
4431         }
4432     }
4434   /* If there are both horizontal and vertical scroll-bars they leave
4435      a square that belongs to neither. We need to clear it otherwise
4436      it fills with junk. */
4437   if (!NILP (window->vertical_scroll_bar))
4438     ns_clear_frame_area (f, WINDOW_SCROLL_BAR_AREA_X (window), top,
4439                          NS_SCROLL_BAR_HEIGHT (f), height);
4441   if (update_p)
4442     [bar setPosition: position portion: portion whole: whole];
4443   unblock_input ();
4447 static void
4448 ns_condemn_scroll_bars (struct frame *f)
4449 /* --------------------------------------------------------------------------
4450      External (hook): arrange for all frame's scrollbars to be removed
4451      at next call to judge_scroll_bars, except for those redeemed.
4452    -------------------------------------------------------------------------- */
4454   int i;
4455   id view;
4456   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4458   NSTRACE ("ns_condemn_scroll_bars");
4460   for (i =[subviews count]-1; i >= 0; i--)
4461     {
4462       view = [subviews objectAtIndex: i];
4463       if ([view isKindOfClass: [EmacsScroller class]])
4464         [view condemn];
4465     }
4469 static void
4470 ns_redeem_scroll_bar (struct window *window)
4471 /* --------------------------------------------------------------------------
4472      External (hook): arrange to spare this window's scrollbar
4473      at next call to judge_scroll_bars.
4474    -------------------------------------------------------------------------- */
4476   id bar;
4477   NSTRACE ("ns_redeem_scroll_bar");
4478   if (!NILP (window->vertical_scroll_bar)
4479       && WINDOW_HAS_VERTICAL_SCROLL_BAR (window))
4480     {
4481       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4482       [bar reprieve];
4483     }
4485   if (!NILP (window->horizontal_scroll_bar)
4486       && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (window))
4487     {
4488       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4489       [bar reprieve];
4490     }
4494 static void
4495 ns_judge_scroll_bars (struct frame *f)
4496 /* --------------------------------------------------------------------------
4497      External (hook): destroy all scrollbars on frame that weren't
4498      redeemed after call to condemn_scroll_bars.
4499    -------------------------------------------------------------------------- */
4501   int i;
4502   id view;
4503   EmacsView *eview = FRAME_NS_VIEW (f);
4504   NSArray *subviews = [[eview superview] subviews];
4505   BOOL removed = NO;
4507   NSTRACE ("ns_judge_scroll_bars");
4508   for (i = [subviews count]-1; i >= 0; --i)
4509     {
4510       view = [subviews objectAtIndex: i];
4511       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4512       if ([view judge])
4513         removed = YES;
4514     }
4516   if (removed)
4517     [eview updateFrameSize: NO];
4520 /* ==========================================================================
4522     Initialization
4524    ========================================================================== */
4527 x_display_pixel_height (struct ns_display_info *dpyinfo)
4529   NSArray *screens = [NSScreen screens];
4530   NSEnumerator *enumerator = [screens objectEnumerator];
4531   NSScreen *screen;
4532   NSRect frame;
4534   frame = NSZeroRect;
4535   while ((screen = [enumerator nextObject]) != nil)
4536     frame = NSUnionRect (frame, [screen frame]);
4538   return NSHeight (frame);
4542 x_display_pixel_width (struct ns_display_info *dpyinfo)
4544   NSArray *screens = [NSScreen screens];
4545   NSEnumerator *enumerator = [screens objectEnumerator];
4546   NSScreen *screen;
4547   NSRect frame;
4549   frame = NSZeroRect;
4550   while ((screen = [enumerator nextObject]) != nil)
4551     frame = NSUnionRect (frame, [screen frame]);
4553   return NSWidth (frame);
4557 static Lisp_Object ns_string_to_lispmod (const char *s)
4558 /* --------------------------------------------------------------------------
4559      Convert modifier name to lisp symbol
4560    -------------------------------------------------------------------------- */
4562   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4563     return Qmeta;
4564   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4565     return Qsuper;
4566   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4567     return Qcontrol;
4568   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4569     return Qalt;
4570   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4571     return Qhyper;
4572   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4573     return Qnone;
4574   else
4575     return Qnil;
4579 static void
4580 ns_default (const char *parameter, Lisp_Object *result,
4581            Lisp_Object yesval, Lisp_Object noval,
4582            BOOL is_float, BOOL is_modstring)
4583 /* --------------------------------------------------------------------------
4584       Check a parameter value in user's preferences
4585    -------------------------------------------------------------------------- */
4587   const char *value = ns_get_defaults_value (parameter);
4589   if (value)
4590     {
4591       double f;
4592       char *pos;
4593       if (c_strcasecmp (value, "YES") == 0)
4594         *result = yesval;
4595       else if (c_strcasecmp (value, "NO") == 0)
4596         *result = noval;
4597       else if (is_float && (f = strtod (value, &pos), pos != value))
4598         *result = make_float (f);
4599       else if (is_modstring && value)
4600         *result = ns_string_to_lispmod (value);
4601       else fprintf (stderr,
4602                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4603     }
4607 static void
4608 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4609 /* --------------------------------------------------------------------------
4610       Initialize global info and storage for display.
4611    -------------------------------------------------------------------------- */
4613     NSScreen *screen = [NSScreen mainScreen];
4614     NSWindowDepth depth = [screen depth];
4616     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4617     dpyinfo->resy = 72.27;
4618     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4619                                                   NSColorSpaceFromDepth (depth)]
4620                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4621                                                  NSColorSpaceFromDepth (depth)];
4622     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4623     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4624     dpyinfo->color_table->colors = NULL;
4625     dpyinfo->root_window = 42; /* a placeholder.. */
4626     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4627     dpyinfo->n_fonts = 0;
4628     dpyinfo->smallest_font_height = 1;
4629     dpyinfo->smallest_char_width = 1;
4631     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4635 /* This and next define (many of the) public functions in this file. */
4636 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4637          with using despite presence in the "system dependent" redisplay
4638          interface.  In addition, many of the ns_ methods have code that is
4639          shared with all terms, indicating need for further refactoring. */
4640 extern frame_parm_handler ns_frame_parm_handlers[];
4641 static struct redisplay_interface ns_redisplay_interface =
4643   ns_frame_parm_handlers,
4644   x_produce_glyphs,
4645   x_write_glyphs,
4646   x_insert_glyphs,
4647   x_clear_end_of_line,
4648   ns_scroll_run,
4649   ns_after_update_window_line,
4650   ns_update_window_begin,
4651   ns_update_window_end,
4652   0, /* flush_display */
4653   x_clear_window_mouse_face,
4654   x_get_glyph_overhangs,
4655   x_fix_overlapping_area,
4656   ns_draw_fringe_bitmap,
4657   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4658   0, /* destroy_fringe_bitmap */
4659   ns_compute_glyph_string_overhangs,
4660   ns_draw_glyph_string,
4661   ns_define_frame_cursor,
4662   ns_clear_frame_area,
4663   ns_draw_window_cursor,
4664   ns_draw_vertical_window_border,
4665   ns_draw_window_divider,
4666   ns_shift_glyphs_for_insert,
4667   ns_show_hourglass,
4668   ns_hide_hourglass
4672 static void
4673 ns_delete_display (struct ns_display_info *dpyinfo)
4675   /* TODO... */
4679 /* This function is called when the last frame on a display is deleted. */
4680 static void
4681 ns_delete_terminal (struct terminal *terminal)
4683   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4685   NSTRACE ("ns_delete_terminal");
4687   /* Protect against recursive calls.  delete_frame in
4688      delete_terminal calls us back when it deletes our last frame.  */
4689   if (!terminal->name)
4690     return;
4692   block_input ();
4694   x_destroy_all_bitmaps (dpyinfo);
4695   ns_delete_display (dpyinfo);
4696   unblock_input ();
4700 static struct terminal *
4701 ns_create_terminal (struct ns_display_info *dpyinfo)
4702 /* --------------------------------------------------------------------------
4703       Set up use of NS before we make the first connection.
4704    -------------------------------------------------------------------------- */
4706   struct terminal *terminal;
4708   NSTRACE ("ns_create_terminal");
4710   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4712   terminal->display_info.ns = dpyinfo;
4713   dpyinfo->terminal = terminal;
4715   terminal->clear_frame_hook = ns_clear_frame;
4716   terminal->ring_bell_hook = ns_ring_bell;
4717   terminal->update_begin_hook = ns_update_begin;
4718   terminal->update_end_hook = ns_update_end;
4719   terminal->read_socket_hook = ns_read_socket;
4720   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4721   terminal->mouse_position_hook = ns_mouse_position;
4722   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4723   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4724   terminal->fullscreen_hook = ns_fullscreen_hook;
4725   terminal->menu_show_hook = ns_menu_show;
4726   terminal->popup_dialog_hook = ns_popup_dialog;
4727   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4728   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4729   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4730   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4731   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4732   terminal->delete_frame_hook = x_destroy_window;
4733   terminal->delete_terminal_hook = ns_delete_terminal;
4734   /* Other hooks are NULL by default.  */
4736   return terminal;
4740 struct ns_display_info *
4741 ns_term_init (Lisp_Object display_name)
4742 /* --------------------------------------------------------------------------
4743      Start the Application and get things rolling.
4744    -------------------------------------------------------------------------- */
4746   struct terminal *terminal;
4747   struct ns_display_info *dpyinfo;
4748   static int ns_initialized = 0;
4749   Lisp_Object tmp;
4751   if (ns_initialized) return x_display_list;
4752   ns_initialized = 1;
4754   block_input ();
4756   NSTRACE ("ns_term_init");
4758   [outerpool release];
4759   outerpool = [[NSAutoreleasePool alloc] init];
4761   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4762   /*GSDebugAllocationActive (YES); */
4763   block_input ();
4765   baud_rate = 38400;
4766   Fset_input_interrupt_mode (Qnil);
4768   if (selfds[0] == -1)
4769     {
4770       if (emacs_pipe (selfds) != 0)
4771         {
4772           fprintf (stderr, "Failed to create pipe: %s\n",
4773                    emacs_strerror (errno));
4774           emacs_abort ();
4775         }
4777       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4778       FD_ZERO (&select_readfds);
4779       FD_ZERO (&select_writefds);
4780       pthread_mutex_init (&select_mutex, NULL);
4781     }
4783   ns_pending_files = [[NSMutableArray alloc] init];
4784   ns_pending_service_names = [[NSMutableArray alloc] init];
4785   ns_pending_service_args = [[NSMutableArray alloc] init];
4787 /* Start app and create the main menu, window, view.
4788      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4789      The view will then ask the NSApp to stop and return to Emacs. */
4790   [EmacsApp sharedApplication];
4791   if (NSApp == nil)
4792     return NULL;
4793   [NSApp setDelegate: NSApp];
4795   /* Start the select thread.  */
4796   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4797                            toTarget:NSApp
4798                          withObject:nil];
4800   /* debugging: log all notifications */
4801   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4802                                          selector: @selector (logNotification:)
4803                                              name: nil object: nil]; */
4805   dpyinfo = xzalloc (sizeof *dpyinfo);
4807   ns_initialize_display_info (dpyinfo);
4808   terminal = ns_create_terminal (dpyinfo);
4810   terminal->kboard = allocate_kboard (Qns);
4811   /* Don't let the initial kboard remain current longer than necessary.
4812      That would cause problems if a file loaded on startup tries to
4813      prompt in the mini-buffer.  */
4814   if (current_kboard == initial_kboard)
4815     current_kboard = terminal->kboard;
4816   terminal->kboard->reference_count++;
4818   dpyinfo->next = x_display_list;
4819   x_display_list = dpyinfo;
4821   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4823   terminal->name = xlispstrdup (display_name);
4825   unblock_input ();
4827   if (!inhibit_x_resources)
4828     {
4829       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4830                  Qt, Qnil, NO, NO);
4831       tmp = Qnil;
4832       /* this is a standard variable */
4833       ns_default ("AppleAntiAliasingThreshold", &tmp,
4834                  make_float (10.0), make_float (6.0), YES, NO);
4835       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4836     }
4838   NSTRACE_MSG ("Colors");
4840   {
4841     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4843     if ( cl == nil )
4844       {
4845         Lisp_Object color_file, color_map, color;
4846         unsigned long c;
4847         char *name;
4849         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4850                          Fsymbol_value (intern ("data-directory")));
4852         color_map = Fx_load_color_file (color_file);
4853         if (NILP (color_map))
4854           fatal ("Could not read %s.\n", SDATA (color_file));
4856         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4857         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4858           {
4859             color = XCAR (color_map);
4860             name = SSDATA (XCAR (color));
4861             c = XINT (XCDR (color));
4862             [cl setColor:
4863                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4864                                       green: GREEN_FROM_ULONG (c) / 255.0
4865                                        blue: BLUE_FROM_ULONG (c) / 255.0
4866                                       alpha: 1.0]
4867                   forKey: [NSString stringWithUTF8String: name]];
4868           }
4869         [cl writeToFile: nil];
4870       }
4871   }
4873   NSTRACE_MSG ("Versions");
4875   {
4876 #ifdef NS_IMPL_GNUSTEP
4877     Vwindow_system_version = build_string (gnustep_base_version);
4878 #else
4879     /*PSnextrelease (128, c); */
4880     char c[DBL_BUFSIZE_BOUND];
4881     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4882     Vwindow_system_version = make_unibyte_string (c, len);
4883 #endif
4884   }
4886   delete_keyboard_wait_descriptor (0);
4888   ns_app_name = [[NSProcessInfo processInfo] processName];
4890   /* Set up OS X app menu */
4892   NSTRACE_MSG ("Menu init");
4894 #ifdef NS_IMPL_COCOA
4895   {
4896     NSMenu *appMenu;
4897     NSMenuItem *item;
4898     /* set up the application menu */
4899     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4900     [svcsMenu setAutoenablesItems: NO];
4901     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4902     [appMenu setAutoenablesItems: NO];
4903     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4904     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4906     [appMenu insertItemWithTitle: @"About Emacs"
4907                           action: @selector (orderFrontStandardAboutPanel:)
4908                    keyEquivalent: @""
4909                          atIndex: 0];
4910     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4911     [appMenu insertItemWithTitle: @"Preferences..."
4912                           action: @selector (showPreferencesWindow:)
4913                    keyEquivalent: @","
4914                          atIndex: 2];
4915     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4916     item = [appMenu insertItemWithTitle: @"Services"
4917                                  action: @selector (menuDown:)
4918                           keyEquivalent: @""
4919                                 atIndex: 4];
4920     [appMenu setSubmenu: svcsMenu forItem: item];
4921     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4922     [appMenu insertItemWithTitle: @"Hide Emacs"
4923                           action: @selector (hide:)
4924                    keyEquivalent: @"h"
4925                          atIndex: 6];
4926     item =  [appMenu insertItemWithTitle: @"Hide Others"
4927                           action: @selector (hideOtherApplications:)
4928                    keyEquivalent: @"h"
4929                          atIndex: 7];
4930     [item setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
4931     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4932     [appMenu insertItemWithTitle: @"Quit Emacs"
4933                           action: @selector (terminate:)
4934                    keyEquivalent: @"q"
4935                          atIndex: 9];
4937     item = [mainMenu insertItemWithTitle: ns_app_name
4938                                   action: @selector (menuDown:)
4939                            keyEquivalent: @""
4940                                  atIndex: 0];
4941     [mainMenu setSubmenu: appMenu forItem: item];
4942     [dockMenu insertItemWithTitle: @"New Frame"
4943                            action: @selector (newFrame:)
4944                     keyEquivalent: @""
4945                           atIndex: 0];
4947     [NSApp setMainMenu: mainMenu];
4948     [NSApp setAppleMenu: appMenu];
4949     [NSApp setServicesMenu: svcsMenu];
4950     /* Needed at least on Cocoa, to get dock menu to show windows */
4951     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4953     [[NSNotificationCenter defaultCenter]
4954       addObserver: mainMenu
4955          selector: @selector (trackingNotification:)
4956              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4957     [[NSNotificationCenter defaultCenter]
4958       addObserver: mainMenu
4959          selector: @selector (trackingNotification:)
4960              name: NSMenuDidEndTrackingNotification object: mainMenu];
4961   }
4962 #endif /* MAC OS X menu setup */
4964   /* Register our external input/output types, used for determining
4965      applicable services and also drag/drop eligibility. */
4967   NSTRACE_MSG ("Input/output types");
4969   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4970   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4971                       retain];
4972   ns_drag_types = [[NSArray arrayWithObjects:
4973                             NSStringPboardType,
4974                             NSTabularTextPboardType,
4975                             NSFilenamesPboardType,
4976                             NSURLPboardType, nil] retain];
4978   /* If fullscreen is in init/default-frame-alist, focus isn't set
4979      right for fullscreen windows, so set this.  */
4980   [NSApp activateIgnoringOtherApps:YES];
4982   NSTRACE_MSG ("Call NSApp run");
4984   [NSApp run];
4985   ns_do_open_file = YES;
4987 #ifdef NS_IMPL_GNUSTEP
4988   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4989      We must re-catch it so subprocess works.  */
4990   catch_child_signal ();
4991 #endif
4993   NSTRACE_MSG ("ns_term_init done");
4995   unblock_input ();
4997   return dpyinfo;
5001 void
5002 ns_term_shutdown (int sig)
5004   [[NSUserDefaults standardUserDefaults] synchronize];
5006   /* code not reached in emacs.c after this is called by shut_down_emacs: */
5007   if (STRINGP (Vauto_save_list_file_name))
5008     unlink (SSDATA (Vauto_save_list_file_name));
5010   if (sig == 0 || sig == SIGTERM)
5011     {
5012       [NSApp terminate: NSApp];
5013     }
5014   else // force a stack trace to happen
5015     {
5016       emacs_abort ();
5017     }
5021 /* ==========================================================================
5023     EmacsApp implementation
5025    ========================================================================== */
5028 @implementation EmacsApp
5030 - (id)init
5032   NSTRACE ("[EmacsApp init]");
5034   if ((self = [super init]))
5035     {
5036 #ifdef NS_IMPL_COCOA
5037       self->isFirst = YES;
5038 #endif
5039 #ifdef NS_IMPL_GNUSTEP
5040       self->applicationDidFinishLaunchingCalled = NO;
5041 #endif
5042     }
5044   return self;
5047 #ifdef NS_IMPL_COCOA
5048 - (void)run
5050   NSTRACE ("[EmacsApp run]");
5052 #ifndef NSAppKitVersionNumber10_9
5053 #define NSAppKitVersionNumber10_9 1265
5054 #endif
5056     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5057       {
5058         [super run];
5059         return;
5060       }
5062   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5064   if (isFirst) [self finishLaunching];
5065   isFirst = NO;
5067   shouldKeepRunning = YES;
5068   do
5069     {
5070       [pool release];
5071       pool = [[NSAutoreleasePool alloc] init];
5073       NSEvent *event =
5074         [self nextEventMatchingMask:NSEventMaskAny
5075                           untilDate:[NSDate distantFuture]
5076                              inMode:NSDefaultRunLoopMode
5077                             dequeue:YES];
5079       [self sendEvent:event];
5080       [self updateWindows];
5081     } while (shouldKeepRunning);
5083   [pool release];
5086 - (void)stop: (id)sender
5088   NSTRACE ("[EmacsApp stop:]");
5090     shouldKeepRunning = NO;
5091     // Stop possible dialog also.  Noop if no dialog present.
5092     // The file dialog still leaks 7k - 10k on 10.9 though.
5093     [super stop:sender];
5095 #endif /* NS_IMPL_COCOA */
5097 - (void)logNotification: (NSNotification *)notification
5099   NSTRACE ("[EmacsApp logNotification:]");
5101   const char *name = [[notification name] UTF8String];
5102   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5103       && !strstr (name, "WindowNumber"))
5104     NSLog (@"notification: '%@'", [notification name]);
5108 - (void)sendEvent: (NSEvent *)theEvent
5109 /* --------------------------------------------------------------------------
5110      Called when NSApp is running for each event received.  Used to stop
5111      the loop when we choose, since there's no way to just run one iteration.
5112    -------------------------------------------------------------------------- */
5114   int type = [theEvent type];
5115   NSWindow *window = [theEvent window];
5117   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5118   NSTRACE_MSG ("Type: %d", type);
5120 #ifdef NS_IMPL_GNUSTEP
5121   // Keyboard events aren't propagated to file dialogs for some reason.
5122   if ([NSApp modalWindow] != nil &&
5123       (type == NSEventTypeKeyDown || type == NSEventTypeKeyUp || type == NSEventTypeFlagsChanged))
5124     {
5125       [[NSApp modalWindow] sendEvent: theEvent];
5126       return;
5127     }
5128 #endif
5130   if (represented_filename != nil && represented_frame)
5131     {
5132       NSString *fstr = represented_filename;
5133       NSView *view = FRAME_NS_VIEW (represented_frame);
5134 #ifdef NS_IMPL_COCOA
5135       /* work around a bug observed on 10.3 and later where
5136          setTitleWithRepresentedFilename does not clear out previous state
5137          if given filename does not exist */
5138       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5139         [[view window] setRepresentedFilename: @""];
5140 #endif
5141       [[view window] setRepresentedFilename: fstr];
5142       [represented_filename release];
5143       represented_filename = nil;
5144       represented_frame = NULL;
5145     }
5147   if (type == NSEventTypeApplicationDefined)
5148     {
5149       switch ([theEvent data2])
5150         {
5151 #ifdef NS_IMPL_COCOA
5152         case NSAPP_DATA2_RUNASSCRIPT:
5153           ns_run_ascript ();
5154           [self stop: self];
5155           return;
5156 #endif
5157         case NSAPP_DATA2_RUNFILEDIALOG:
5158           ns_run_file_dialog ();
5159           [self stop: self];
5160           return;
5161         }
5162     }
5164   if (type == NSEventTypeCursorUpdate && window == nil)
5165     {
5166       fprintf (stderr, "Dropping external cursor update event.\n");
5167       return;
5168     }
5170   if (type == NSEventTypeApplicationDefined)
5171     {
5172       /* Events posted by ns_send_appdefined interrupt the run loop here.
5173          But, if a modal window is up, an appdefined can still come through,
5174          (e.g., from a makeKeyWindow event) but stopping self also stops the
5175          modal loop. Just defer it until later. */
5176       if ([NSApp modalWindow] == nil)
5177         {
5178           last_appdefined_event_data = [theEvent data1];
5179           [self stop: self];
5180         }
5181       else
5182         {
5183           send_appdefined = YES;
5184         }
5185     }
5188 #ifdef NS_IMPL_COCOA
5189   /* If no dialog and none of our frames have focus and it is a move, skip it.
5190      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5191      such as Wifi, sound, date or similar.
5192      This prevents "spooky" highlighting in the frame under the menu.  */
5193   if (type == NSEventTypeMouseMoved && [NSApp modalWindow] == nil)
5194     {
5195       struct ns_display_info *di;
5196       BOOL has_focus = NO;
5197       for (di = x_display_list; ! has_focus && di; di = di->next)
5198         has_focus = di->x_focus_frame != 0;
5199       if (! has_focus)
5200         return;
5201     }
5202 #endif
5204   NSTRACE_UNSILENCE();
5206   [super sendEvent: theEvent];
5210 - (void)showPreferencesWindow: (id)sender
5212   struct frame *emacsframe = SELECTED_FRAME ();
5213   NSEvent *theEvent = [NSApp currentEvent];
5215   if (!emacs_event)
5216     return;
5217   emacs_event->kind = NS_NONKEY_EVENT;
5218   emacs_event->code = KEY_NS_SHOW_PREFS;
5219   emacs_event->modifiers = 0;
5220   EV_TRAILER (theEvent);
5224 - (void)newFrame: (id)sender
5226   NSTRACE ("[EmacsApp newFrame:]");
5228   struct frame *emacsframe = SELECTED_FRAME ();
5229   NSEvent *theEvent = [NSApp currentEvent];
5231   if (!emacs_event)
5232     return;
5233   emacs_event->kind = NS_NONKEY_EVENT;
5234   emacs_event->code = KEY_NS_NEW_FRAME;
5235   emacs_event->modifiers = 0;
5236   EV_TRAILER (theEvent);
5240 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5241 - (BOOL) openFile: (NSString *)fileName
5243   NSTRACE ("[EmacsApp openFile:]");
5245   struct frame *emacsframe = SELECTED_FRAME ();
5246   NSEvent *theEvent = [NSApp currentEvent];
5248   if (!emacs_event)
5249     return NO;
5251   emacs_event->kind = NS_NONKEY_EVENT;
5252   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5253   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5254   ns_input_line = Qnil; /* can be start or cons start,end */
5255   emacs_event->modifiers =0;
5256   EV_TRAILER (theEvent);
5258   return YES;
5262 /* **************************************************************************
5264       EmacsApp delegate implementation
5266    ************************************************************************** */
5268 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5269 /* --------------------------------------------------------------------------
5270      When application is loaded, terminate event loop in ns_term_init
5271    -------------------------------------------------------------------------- */
5273   NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5275 #ifdef NS_IMPL_GNUSTEP
5276   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5277 #endif
5278   [NSApp setServicesProvider: NSApp];
5280   [self antialiasThresholdDidChange:nil];
5281 #ifdef NS_IMPL_COCOA
5282   [[NSNotificationCenter defaultCenter]
5283     addObserver:self
5284        selector:@selector(antialiasThresholdDidChange:)
5285            name:NSAntialiasThresholdChangedNotification
5286          object:nil];
5287 #endif
5289   ns_send_appdefined (-2);
5292 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5294 #ifdef NS_IMPL_COCOA
5295   macfont_update_antialias_threshold ();
5296 #endif
5300 /* Termination sequences:
5301     C-x C-c:
5302     Cmd-Q:
5303     MenuBar | File | Exit:
5304     Select Quit from App menubar:
5305         -terminate
5306         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5307         ns_term_shutdown()
5309     Select Quit from Dock menu:
5310     Logout attempt:
5311         -appShouldTerminate
5312           Cancel -> Nothing else
5313           Accept ->
5315           -terminate
5316           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5317           ns_term_shutdown()
5321 - (void) terminate: (id)sender
5323   NSTRACE ("[EmacsApp terminate:]");
5325   struct frame *emacsframe = SELECTED_FRAME ();
5327   if (!emacs_event)
5328     return;
5330   emacs_event->kind = NS_NONKEY_EVENT;
5331   emacs_event->code = KEY_NS_POWER_OFF;
5332   emacs_event->arg = Qt; /* mark as non-key event */
5333   EV_TRAILER ((id)nil);
5336 static bool
5337 runAlertPanel(NSString *title,
5338               NSString *msgFormat,
5339               NSString *defaultButton,
5340               NSString *alternateButton)
5342 #if !defined (NS_IMPL_COCOA) || \
5343   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5344   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5345     == NSAlertDefaultReturn;
5346 #else
5347   NSAlert *alert = [[NSAlert alloc] init];
5348   [alert setAlertStyle: NSAlertStyleCritical];
5349   [alert setMessageText: msgFormat];
5350   [alert addButtonWithTitle: defaultButton];
5351   [alert addButtonWithTitle: alternateButton];
5352   NSInteger ret = [alert runModal];
5353   [alert release];
5354   return ret == NSAlertFirstButtonReturn;
5355 #endif
5359 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5361   NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5363   bool ret;
5365   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
5366     return NSTerminateNow;
5368   ret = runAlertPanel(ns_app_name,
5369                       @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
5370                       @"Save Buffers and Exit", @"Cancel");
5372   return ret ? NSTerminateNow : NSTerminateCancel;
5375 static int
5376 not_in_argv (NSString *arg)
5378   int k;
5379   const char *a = [arg UTF8String];
5380   for (k = 1; k < initial_argc; ++k)
5381     if (strcmp (a, initial_argv[k]) == 0) return 0;
5382   return 1;
5385 /*   Notification from the Workspace to open a file */
5386 - (BOOL)application: sender openFile: (NSString *)file
5388   if (ns_do_open_file || not_in_argv (file))
5389     [ns_pending_files addObject: file];
5390   return YES;
5394 /*   Open a file as a temporary file */
5395 - (BOOL)application: sender openTempFile: (NSString *)file
5397   if (ns_do_open_file || not_in_argv (file))
5398     [ns_pending_files addObject: file];
5399   return YES;
5403 /*   Notification from the Workspace to open a file noninteractively (?) */
5404 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5406   if (ns_do_open_file || not_in_argv (file))
5407     [ns_pending_files addObject: file];
5408   return YES;
5411 /*   Notification from the Workspace to open multiple files */
5412 - (void)application: sender openFiles: (NSArray *)fileList
5414   NSEnumerator *files = [fileList objectEnumerator];
5415   NSString *file;
5416   /* Don't open files from the command line unconditionally,
5417      Cocoa parses the command line wrong, --option value tries to open value
5418      if --option is the last option.  */
5419   while ((file = [files nextObject]) != nil)
5420     if (ns_do_open_file || not_in_argv (file))
5421       [ns_pending_files addObject: file];
5423   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5428 /* Handle dock menu requests.  */
5429 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5431   return dockMenu;
5435 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5436 - (void)applicationWillBecomeActive: (NSNotification *)notification
5438   NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5439   //ns_app_active=YES;
5442 - (void)applicationDidBecomeActive: (NSNotification *)notification
5444   NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5446 #ifdef NS_IMPL_GNUSTEP
5447   if (! applicationDidFinishLaunchingCalled)
5448     [self applicationDidFinishLaunching:notification];
5449 #endif
5450   //ns_app_active=YES;
5452   ns_update_auto_hide_menu_bar ();
5453   // No constraining takes place when the application is not active.
5454   ns_constrain_all_frames ();
5456 - (void)applicationDidResignActive: (NSNotification *)notification
5458   NSTRACE ("[EmacsApp applicationDidResignActive:]");
5460   //ns_app_active=NO;
5461   ns_send_appdefined (-1);
5466 /* ==========================================================================
5468     EmacsApp aux handlers for managing event loop
5470    ========================================================================== */
5473 - (void)timeout_handler: (NSTimer *)timedEntry
5474 /* --------------------------------------------------------------------------
5475      The timeout specified to ns_select has passed.
5476    -------------------------------------------------------------------------- */
5478   /*NSTRACE ("timeout_handler"); */
5479   ns_send_appdefined (-2);
5482 - (void)sendFromMainThread:(id)unused
5484   ns_send_appdefined (nextappdefined);
5487 - (void)fd_handler:(id)unused
5488 /* --------------------------------------------------------------------------
5489      Check data waiting on file descriptors and terminate if so
5490    -------------------------------------------------------------------------- */
5492   int result;
5493   int waiting = 1, nfds;
5494   char c;
5496   fd_set readfds, writefds, *wfds;
5497   struct timespec timeout, *tmo;
5498   NSAutoreleasePool *pool = nil;
5500   /* NSTRACE ("fd_handler"); */
5502   for (;;)
5503     {
5504       [pool release];
5505       pool = [[NSAutoreleasePool alloc] init];
5507       if (waiting)
5508         {
5509           fd_set fds;
5510           FD_ZERO (&fds);
5511           FD_SET (selfds[0], &fds);
5512           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5513           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5514             waiting = 0;
5515         }
5516       else
5517         {
5518           pthread_mutex_lock (&select_mutex);
5519           nfds = select_nfds;
5521           if (select_valid & SELECT_HAVE_READ)
5522             readfds = select_readfds;
5523           else
5524             FD_ZERO (&readfds);
5526           if (select_valid & SELECT_HAVE_WRITE)
5527             {
5528               writefds = select_writefds;
5529               wfds = &writefds;
5530             }
5531           else
5532             wfds = NULL;
5533           if (select_valid & SELECT_HAVE_TMO)
5534             {
5535               timeout = select_timeout;
5536               tmo = &timeout;
5537             }
5538           else
5539             tmo = NULL;
5541           pthread_mutex_unlock (&select_mutex);
5543           FD_SET (selfds[0], &readfds);
5544           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5546           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5548           if (result == 0)
5549             ns_send_appdefined (-2);
5550           else if (result > 0)
5551             {
5552               if (FD_ISSET (selfds[0], &readfds))
5553                 {
5554                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5555                     waiting = 1;
5556                 }
5557               else
5558                 {
5559                   pthread_mutex_lock (&select_mutex);
5560                   if (select_valid & SELECT_HAVE_READ)
5561                     select_readfds = readfds;
5562                   if (select_valid & SELECT_HAVE_WRITE)
5563                     select_writefds = writefds;
5564                   if (select_valid & SELECT_HAVE_TMO)
5565                     select_timeout = timeout;
5566                   pthread_mutex_unlock (&select_mutex);
5568                   ns_send_appdefined (result);
5569                 }
5570             }
5571           waiting = 1;
5572         }
5573     }
5578 /* ==========================================================================
5580     Service provision
5582    ========================================================================== */
5584 /* called from system: queue for next pass through event loop */
5585 - (void)requestService: (NSPasteboard *)pboard
5586               userData: (NSString *)userData
5587                  error: (NSString **)error
5589   [ns_pending_service_names addObject: userData];
5590   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5591       SSDATA (ns_string_from_pasteboard (pboard))]];
5595 /* called from ns_read_socket to clear queue */
5596 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5598   struct frame *emacsframe = SELECTED_FRAME ();
5599   NSEvent *theEvent = [NSApp currentEvent];
5601   NSTRACE ("[EmacsApp fulfillService:withArg:]");
5603   if (!emacs_event)
5604     return NO;
5606   emacs_event->kind = NS_NONKEY_EVENT;
5607   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5608   ns_input_spi_name = build_string ([name UTF8String]);
5609   ns_input_spi_arg = build_string ([arg UTF8String]);
5610   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5611   EV_TRAILER (theEvent);
5613   return YES;
5617 @end  /* EmacsApp */
5621 /* ==========================================================================
5623     EmacsView implementation
5625    ========================================================================== */
5628 @implementation EmacsView
5630 /* needed to inform when window closed from LISP */
5631 - (void) setWindowClosing: (BOOL)closing
5633   NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5635   windowClosing = closing;
5639 - (void)dealloc
5641   NSTRACE ("[EmacsView dealloc]");
5642   [toolbar release];
5643   if (fs_state == FULLSCREEN_BOTH)
5644     [nonfs_window release];
5645   [super dealloc];
5649 /* called on font panel selection */
5650 - (void)changeFont: (id)sender
5652   NSEvent *e = [[self window] currentEvent];
5653   struct face *face = FACE_FROM_ID (emacsframe, DEFAULT_FACE_ID);
5654   struct font *font = face->font;
5655   id newFont;
5656   CGFloat size;
5657   NSFont *nsfont;
5659   NSTRACE ("[EmacsView changeFont:]");
5661   if (!emacs_event)
5662     return;
5664 #ifdef NS_IMPL_GNUSTEP
5665   nsfont = ((struct nsfont_info *)font)->nsfont;
5666 #endif
5667 #ifdef NS_IMPL_COCOA
5668   nsfont = (NSFont *) macfont_get_nsctfont (font);
5669 #endif
5671   if ((newFont = [sender convertFont: nsfont]))
5672     {
5673       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5675       emacs_event->kind = NS_NONKEY_EVENT;
5676       emacs_event->modifiers = 0;
5677       emacs_event->code = KEY_NS_CHANGE_FONT;
5679       size = [newFont pointSize];
5680       ns_input_fontsize = make_number (lrint (size));
5681       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5682       EV_TRAILER (e);
5683     }
5687 - (BOOL)acceptsFirstResponder
5689   NSTRACE ("[EmacsView acceptsFirstResponder]");
5690   return YES;
5694 - (void)resetCursorRects
5696   NSRect visible = [self visibleRect];
5697   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5698   NSTRACE ("[EmacsView resetCursorRects]");
5700   if (currentCursor == nil)
5701     currentCursor = [NSCursor arrowCursor];
5703   if (!NSIsEmptyRect (visible))
5704     [self addCursorRect: visible cursor: currentCursor];
5705   [currentCursor setOnMouseEntered: YES];
5710 /*****************************************************************************/
5711 /* Keyboard handling. */
5712 #define NS_KEYLOG 0
5714 - (void)keyDown: (NSEvent *)theEvent
5716   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5717   int code;
5718   unsigned fnKeysym = 0;
5719   static NSMutableArray *nsEvArray;
5720   int left_is_none;
5721   unsigned int flags = [theEvent modifierFlags];
5723   NSTRACE ("[EmacsView keyDown:]");
5725   /* Rhapsody and OS X give up and down events for the arrow keys */
5726   if (ns_fake_keydown == YES)
5727     ns_fake_keydown = NO;
5728   else if ([theEvent type] != NSEventTypeKeyDown)
5729     return;
5731   if (!emacs_event)
5732     return;
5734  if (![[self window] isKeyWindow]
5735      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5736      /* we must avoid an infinite loop here. */
5737      && (EmacsView *)[[theEvent window] delegate] != self)
5738    {
5739      /* XXX: There is an occasional condition in which, when Emacs display
5740          updates a different frame from the current one, and temporarily
5741          selects it, then processes some interrupt-driven input
5742          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5743          for some reason that window has its first responder set to the NSView
5744          most recently updated (I guess), which is not the correct one. */
5745      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5746      return;
5747    }
5749   if (nsEvArray == nil)
5750     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5752   [NSCursor setHiddenUntilMouseMoves: YES];
5754   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5755     {
5756       clear_mouse_face (hlinfo);
5757       hlinfo->mouse_face_hidden = 1;
5758     }
5760   if (!processingCompose)
5761     {
5762       /* When using screen sharing, no left or right information is sent,
5763          so use Left key in those cases.  */
5764       int is_left_key, is_right_key;
5766       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5767         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5769       /* (Carbon way: [theEvent keyCode]) */
5771       /* is it a "function key"? */
5772       /* Note: Sometimes a plain key will have the NSEventModifierFlagNumericPad
5773          flag set (this is probably a bug in the OS).
5774       */
5775       if (code < 0x00ff && (flags&NSEventModifierFlagNumericPad))
5776         {
5777           fnKeysym = ns_convert_key ([theEvent keyCode] | NSEventModifierFlagNumericPad);
5778         }
5779       if (fnKeysym == 0)
5780         {
5781           fnKeysym = ns_convert_key (code);
5782         }
5784       if (fnKeysym)
5785         {
5786           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5787              because Emacs treats Delete and KP-Delete same (in simple.el). */
5788           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5789 #ifdef NS_IMPL_GNUSTEP
5790               /*  GNUstep uses incompatible keycodes, even for those that are
5791                   supposed to be hardware independent.  Just check for delete.
5792                   Keypad delete does not have keysym 0xFFFF.
5793                   See http://savannah.gnu.org/bugs/?25395
5794               */
5795               || (fnKeysym == 0xFFFF && code == 127)
5796 #endif
5797             )
5798             code = 0xFF08; /* backspace */
5799           else
5800             code = fnKeysym;
5801         }
5803       /* are there modifiers? */
5804       emacs_event->modifiers = 0;
5806       if (flags & NSEventModifierFlagHelp)
5807           emacs_event->modifiers |= hyper_modifier;
5809       if (flags & NSEventModifierFlagShift)
5810         emacs_event->modifiers |= shift_modifier;
5812       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5813       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5814         || (! is_right_key && (flags & NSEventModifierFlagCommand) == NSEventModifierFlagCommand);
5816       if (is_right_key)
5817         emacs_event->modifiers |= parse_solitary_modifier
5818           (EQ (ns_right_command_modifier, Qleft)
5819            ? ns_command_modifier
5820            : ns_right_command_modifier);
5822       if (is_left_key)
5823         {
5824           emacs_event->modifiers |= parse_solitary_modifier
5825             (ns_command_modifier);
5827           /* if super (default), take input manager's word so things like
5828              dvorak / qwerty layout work */
5829           if (EQ (ns_command_modifier, Qsuper)
5830               && !fnKeysym
5831               && [[theEvent characters] length] != 0)
5832             {
5833               /* XXX: the code we get will be unshifted, so if we have
5834                  a shift modifier, must convert ourselves */
5835               if (!(flags & NSEventModifierFlagShift))
5836                 code = [[theEvent characters] characterAtIndex: 0];
5837 #if 0
5838               /* this is ugly and also requires linking w/Carbon framework
5839                  (for LMGetKbdType) so for now leave this rare (?) case
5840                  undealt with.. in future look into CGEvent methods */
5841               else
5842                 {
5843                   long smv = GetScriptManagerVariable (smKeyScript);
5844                   Handle uchrHandle = GetResource
5845                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5846                   UInt32 dummy = 0;
5847                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5848                                  [[theEvent characters] characterAtIndex: 0],
5849                                  kUCKeyActionDisplay,
5850                                  (flags & ~NSEventModifierFlagCommand) >> 8,
5851                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5852                                  &dummy, 1, &dummy, &code);
5853                   code &= 0xFF;
5854                 }
5855 #endif
5856             }
5857         }
5859       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5860       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5861         || (! is_right_key && (flags & NSEventModifierFlagControl) == NSEventModifierFlagControl);
5863       if (is_right_key)
5864           emacs_event->modifiers |= parse_solitary_modifier
5865               (EQ (ns_right_control_modifier, Qleft)
5866                ? ns_control_modifier
5867                : ns_right_control_modifier);
5869       if (is_left_key)
5870         emacs_event->modifiers |= parse_solitary_modifier
5871           (ns_control_modifier);
5873       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5874           emacs_event->modifiers |=
5875             parse_solitary_modifier (ns_function_modifier);
5877       left_is_none = NILP (ns_alternate_modifier)
5878         || EQ (ns_alternate_modifier, Qnone);
5880       is_right_key = (flags & NSRightAlternateKeyMask)
5881         == NSRightAlternateKeyMask;
5882       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5883         || (! is_right_key
5884             && (flags & NSEventModifierFlagOption) == NSEventModifierFlagOption);
5886       if (is_right_key)
5887         {
5888           if ((NILP (ns_right_alternate_modifier)
5889                || EQ (ns_right_alternate_modifier, Qnone)
5890                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5891               && !fnKeysym)
5892             {   /* accept pre-interp alt comb */
5893               if ([[theEvent characters] length] > 0)
5894                 code = [[theEvent characters] characterAtIndex: 0];
5895               /*HACK: clear lone shift modifier to stop next if from firing */
5896               if (emacs_event->modifiers == shift_modifier)
5897                 emacs_event->modifiers = 0;
5898             }
5899           else
5900             emacs_event->modifiers |= parse_solitary_modifier
5901               (EQ (ns_right_alternate_modifier, Qleft)
5902                ? ns_alternate_modifier
5903                : ns_right_alternate_modifier);
5904         }
5906       if (is_left_key) /* default = meta */
5907         {
5908           if (left_is_none && !fnKeysym)
5909             {   /* accept pre-interp alt comb */
5910               if ([[theEvent characters] length] > 0)
5911                 code = [[theEvent characters] characterAtIndex: 0];
5912               /*HACK: clear lone shift modifier to stop next if from firing */
5913               if (emacs_event->modifiers == shift_modifier)
5914                 emacs_event->modifiers = 0;
5915             }
5916           else
5917               emacs_event->modifiers |=
5918                 parse_solitary_modifier (ns_alternate_modifier);
5919         }
5921   if (NS_KEYLOG)
5922     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5923              (unsigned) code, fnKeysym, flags, emacs_event->modifiers);
5925       /* if it was a function key or had modifiers, pass it directly to emacs */
5926       if (fnKeysym || (emacs_event->modifiers
5927                        && (emacs_event->modifiers != shift_modifier)
5928                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5929 /*[[theEvent characters] length] */
5930         {
5931           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5932           if (code < 0x20)
5933             code |= (1<<28)|(3<<16);
5934           else if (code == 0x7f)
5935             code |= (1<<28)|(3<<16);
5936           else if (!fnKeysym)
5937             emacs_event->kind = code > 0xFF
5938               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5940           emacs_event->code = code;
5941           EV_TRAILER (theEvent);
5942           processingCompose = NO;
5943           return;
5944         }
5945     }
5948   if (NS_KEYLOG && !processingCompose)
5949     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5951   processingCompose = YES;
5952   [nsEvArray addObject: theEvent];
5953   [self interpretKeyEvents: nsEvArray];
5954   [nsEvArray removeObject: theEvent];
5958 #ifdef NS_IMPL_COCOA
5959 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5960    decided not to send key-down for.
5961    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5962    This only applies on Tiger and earlier.
5963    If it matches one of these, send it on to keyDown. */
5964 -(void)keyUp: (NSEvent *)theEvent
5966   int flags = [theEvent modifierFlags];
5967   int code = [theEvent keyCode];
5969   NSTRACE ("[EmacsView keyUp:]");
5971   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5972       code == 0x30 && (flags & NSEventModifierFlagControl) && !(flags & NSEventModifierFlagCommand))
5973     {
5974       if (NS_KEYLOG)
5975         fprintf (stderr, "keyUp: passed test");
5976       ns_fake_keydown = YES;
5977       [self keyDown: theEvent];
5978     }
5980 #endif
5983 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5986 /* <NSTextInput>: called when done composing;
5987    NOTE: also called when we delete over working text, followed immed.
5988          by doCommandBySelector: deleteBackward: */
5989 - (void)insertText: (id)aString
5991   int code;
5992   int len = [(NSString *)aString length];
5993   int i;
5995   NSTRACE ("[EmacsView insertText:]");
5997   if (NS_KEYLOG)
5998     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5999   processingCompose = NO;
6001   if (!emacs_event)
6002     return;
6004   /* first, clear any working text */
6005   if (workingText != nil)
6006     [self deleteWorkingText];
6008   /* now insert the string as keystrokes */
6009   for (i =0; i<len; i++)
6010     {
6011       code = [aString characterAtIndex: i];
6012       /* TODO: still need this? */
6013       if (code == 0x2DC)
6014         code = '~'; /* 0x7E */
6015       if (code != 32) /* Space */
6016         emacs_event->modifiers = 0;
6017       emacs_event->kind
6018         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6019       emacs_event->code = code;
6020       EV_TRAILER ((id)nil);
6021     }
6025 /* <NSTextInput>: inserts display of composing characters */
6026 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
6028   NSString *str = [aString respondsToSelector: @selector (string)] ?
6029     [aString string] : aString;
6031   NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6033   if (NS_KEYLOG)
6034     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6035            str, (unsigned long)[str length],
6036            (unsigned long)selRange.length,
6037            (unsigned long)selRange.location);
6039   if (workingText != nil)
6040     [self deleteWorkingText];
6041   if ([str length] == 0)
6042     return;
6044   if (!emacs_event)
6045     return;
6047   processingCompose = YES;
6048   workingText = [str copy];
6049   ns_working_text = build_string ([workingText UTF8String]);
6051   emacs_event->kind = NS_TEXT_EVENT;
6052   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6053   EV_TRAILER ((id)nil);
6057 /* delete display of composing characters [not in <NSTextInput>] */
6058 - (void)deleteWorkingText
6060   NSTRACE ("[EmacsView deleteWorkingText]");
6062   if (workingText == nil)
6063     return;
6064   if (NS_KEYLOG)
6065     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6066   [workingText release];
6067   workingText = nil;
6068   processingCompose = NO;
6070   if (!emacs_event)
6071     return;
6073   emacs_event->kind = NS_TEXT_EVENT;
6074   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6075   EV_TRAILER ((id)nil);
6079 - (BOOL)hasMarkedText
6081   NSTRACE ("[EmacsView hasMarkedText]");
6083   return workingText != nil;
6087 - (NSRange)markedRange
6089   NSTRACE ("[EmacsView markedRange]");
6091   NSRange rng = workingText != nil
6092     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6093   if (NS_KEYLOG)
6094     NSLog (@"markedRange request");
6095   return rng;
6099 - (void)unmarkText
6101   NSTRACE ("[EmacsView unmarkText]");
6103   if (NS_KEYLOG)
6104     NSLog (@"unmark (accept) text");
6105   [self deleteWorkingText];
6106   processingCompose = NO;
6110 /* used to position char selection windows, etc. */
6111 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6113   NSRect rect;
6114   NSPoint pt;
6115   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6117   NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6119   if (NS_KEYLOG)
6120     NSLog (@"firstRectForCharRange request");
6122   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6123   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6124   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6125   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6126                                        +FRAME_LINE_HEIGHT (emacsframe));
6128   pt = [self convertPoint: pt toView: nil];
6129 #if !defined (NS_IMPL_COCOA) || \
6130   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
6131   pt = [[self window] convertBaseToScreen: pt];
6132   rect.origin = pt;
6133 #else
6134   rect.origin = pt;
6135   rect = [[self window] convertRectToScreen: rect];
6136 #endif
6137   return rect;
6141 - (NSInteger)conversationIdentifier
6143   return (NSInteger)self;
6147 - (void)doCommandBySelector: (SEL)aSelector
6149   NSTRACE ("[EmacsView doCommandBySelector:]");
6151   if (NS_KEYLOG)
6152     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6154   processingCompose = NO;
6155   if (aSelector == @selector (deleteBackward:))
6156     {
6157       /* happens when user backspaces over an ongoing composition:
6158          throw a 'delete' into the event queue */
6159       if (!emacs_event)
6160         return;
6161       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6162       emacs_event->code = 0xFF08;
6163       EV_TRAILER ((id)nil);
6164     }
6167 - (NSArray *)validAttributesForMarkedText
6169   static NSArray *arr = nil;
6170   if (arr == nil) arr = [NSArray new];
6171  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6172   return arr;
6175 - (NSRange)selectedRange
6177   if (NS_KEYLOG)
6178     NSLog (@"selectedRange request");
6179   return NSMakeRange (NSNotFound, 0);
6182 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6183     GNUSTEP_GUI_MINOR_VERSION > 22
6184 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6185 #else
6186 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6187 #endif
6189   if (NS_KEYLOG)
6190     NSLog (@"characterIndexForPoint request");
6191   return 0;
6194 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6196   static NSAttributedString *str = nil;
6197   if (str == nil) str = [NSAttributedString new];
6198   if (NS_KEYLOG)
6199     NSLog (@"attributedSubstringFromRange request");
6200   return str;
6203 /* End <NSTextInput> impl. */
6204 /*****************************************************************************/
6207 /* This is what happens when the user presses a mouse button.  */
6208 - (void)mouseDown: (NSEvent *)theEvent
6210   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6211   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6213   NSTRACE ("[EmacsView mouseDown:]");
6215   [self deleteWorkingText];
6217   if (!emacs_event)
6218     return;
6220   dpyinfo->last_mouse_frame = emacsframe;
6221   /* appears to be needed to prevent spurious movement events generated on
6222      button clicks */
6223   emacsframe->mouse_moved = 0;
6225   if ([theEvent type] == NSEventTypeScrollWheel)
6226     {
6227       CGFloat delta = [theEvent deltaY];
6228       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6229       if (delta == 0)
6230         {
6231           delta = [theEvent deltaX];
6232           if (delta == 0)
6233             {
6234               NSTRACE_MSG ("deltaIsZero");
6235               return;
6236             }
6237           emacs_event->kind = HORIZ_WHEEL_EVENT;
6238         }
6239       else
6240         emacs_event->kind = WHEEL_EVENT;
6242       emacs_event->code = 0;
6243       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6244         ((delta > 0) ? up_modifier : down_modifier);
6245     }
6246   else
6247     {
6248       emacs_event->kind = MOUSE_CLICK_EVENT;
6249       emacs_event->code = EV_BUTTON (theEvent);
6250       emacs_event->modifiers = EV_MODIFIERS (theEvent)
6251                              | EV_UDMODIFIERS (theEvent);
6252     }
6253   XSETINT (emacs_event->x, lrint (p.x));
6254   XSETINT (emacs_event->y, lrint (p.y));
6255   EV_TRAILER (theEvent);
6259 - (void)rightMouseDown: (NSEvent *)theEvent
6261   NSTRACE ("[EmacsView rightMouseDown:]");
6262   [self mouseDown: theEvent];
6266 - (void)otherMouseDown: (NSEvent *)theEvent
6268   NSTRACE ("[EmacsView otherMouseDown:]");
6269   [self mouseDown: theEvent];
6273 - (void)mouseUp: (NSEvent *)theEvent
6275   NSTRACE ("[EmacsView mouseUp:]");
6276   [self mouseDown: theEvent];
6280 - (void)rightMouseUp: (NSEvent *)theEvent
6282   NSTRACE ("[EmacsView rightMouseUp:]");
6283   [self mouseDown: theEvent];
6287 - (void)otherMouseUp: (NSEvent *)theEvent
6289   NSTRACE ("[EmacsView otherMouseUp:]");
6290   [self mouseDown: theEvent];
6294 - (void) scrollWheel: (NSEvent *)theEvent
6296   NSTRACE ("[EmacsView scrollWheel:]");
6297   [self mouseDown: theEvent];
6301 /* Tell emacs the mouse has moved. */
6302 - (void)mouseMoved: (NSEvent *)e
6304   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6305   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6306   Lisp_Object frame;
6307   NSPoint pt;
6309   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6311   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6312   pt = [self convertPoint: [e locationInWindow] fromView: nil];
6313   dpyinfo->last_mouse_motion_x = pt.x;
6314   dpyinfo->last_mouse_motion_y = pt.y;
6316   /* update any mouse face */
6317   if (hlinfo->mouse_face_hidden)
6318     {
6319       hlinfo->mouse_face_hidden = 0;
6320       clear_mouse_face (hlinfo);
6321     }
6323   /* tooltip handling */
6324   previous_help_echo_string = help_echo_string;
6325   help_echo_string = Qnil;
6327   if (!NILP (Vmouse_autoselect_window))
6328     {
6329       NSTRACE_MSG ("mouse_autoselect_window");
6330       static Lisp_Object last_mouse_window;
6331       Lisp_Object window
6332         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6334       if (WINDOWP (window)
6335           && !EQ (window, last_mouse_window)
6336           && !EQ (window, selected_window)
6337           && (focus_follows_mouse
6338               || (EQ (XWINDOW (window)->frame,
6339                       XWINDOW (selected_window)->frame))))
6340         {
6341           NSTRACE_MSG ("in_window");
6342           emacs_event->kind = SELECT_WINDOW_EVENT;
6343           emacs_event->frame_or_window = window;
6344           EV_TRAILER2 (e);
6345         }
6346       /* Remember the last window where we saw the mouse.  */
6347       last_mouse_window = window;
6348     }
6350   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6351     help_echo_string = previous_help_echo_string;
6353   XSETFRAME (frame, emacsframe);
6354   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6355     {
6356       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6357          (note_mouse_highlight), which is called through the
6358          note_mouse_movement () call above */
6359       any_help_event_p = YES;
6360       gen_help_event (help_echo_string, frame, help_echo_window,
6361                       help_echo_object, help_echo_pos);
6362     }
6364   if (emacsframe->mouse_moved && send_appdefined)
6365     ns_send_appdefined (-1);
6369 - (void)mouseDragged: (NSEvent *)e
6371   NSTRACE ("[EmacsView mouseDragged:]");
6372   [self mouseMoved: e];
6376 - (void)rightMouseDragged: (NSEvent *)e
6378   NSTRACE ("[EmacsView rightMouseDragged:]");
6379   [self mouseMoved: e];
6383 - (void)otherMouseDragged: (NSEvent *)e
6385   NSTRACE ("[EmacsView otherMouseDragged:]");
6386   [self mouseMoved: e];
6390 - (BOOL)windowShouldClose: (id)sender
6392   NSEvent *e =[[self window] currentEvent];
6394   NSTRACE ("[EmacsView windowShouldClose:]");
6395   windowClosing = YES;
6396   if (!emacs_event)
6397     return NO;
6398   emacs_event->kind = DELETE_WINDOW_EVENT;
6399   emacs_event->modifiers = 0;
6400   emacs_event->code = 0;
6401   EV_TRAILER (e);
6402   /* Don't close this window, let this be done from lisp code.  */
6403   return NO;
6406 - (void) updateFrameSize: (BOOL) delay;
6408   NSWindow *window = [self window];
6409   NSRect wr = [window frame];
6410   int extra = 0;
6411   int oldc = cols, oldr = rows;
6412   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6413   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6414   int neww, newh;
6416   NSTRACE ("[EmacsView updateFrameSize:]");
6417   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6418   NSTRACE_RECT ("Original frame", wr);
6419   NSTRACE_MSG  ("Original columns: %d", cols);
6420   NSTRACE_MSG  ("Original rows: %d", rows);
6422   if (! [self isFullscreen])
6423     {
6424 #ifdef NS_IMPL_GNUSTEP
6425       // GNUstep does not always update the tool bar height.  Force it.
6426       if (toolbar && [toolbar isVisible])
6427           update_frame_tool_bar (emacsframe);
6428 #endif
6430       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6431         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6432     }
6434   if (wait_for_tool_bar)
6435     {
6436       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6437         {
6438           NSTRACE_MSG ("Waiting for toolbar");
6439           return;
6440         }
6441       wait_for_tool_bar = NO;
6442     }
6444   neww = (int)wr.size.width - emacsframe->border_width;
6445   newh = (int)wr.size.height - extra;
6447   NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6448   NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6450   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6451   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6453   if (cols < MINWIDTH)
6454     cols = MINWIDTH;
6456   if (rows < MINHEIGHT)
6457     rows = MINHEIGHT;
6459   NSTRACE_MSG ("New columns: %d", cols);
6460   NSTRACE_MSG ("New rows: %d", rows);
6462   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6463     {
6464       NSView *view = FRAME_NS_VIEW (emacsframe);
6466       change_frame_size (emacsframe,
6467                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6468                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6469                          0, delay, 0, 1);
6470       SET_FRAME_GARBAGED (emacsframe);
6471       cancel_mouse_face (emacsframe);
6473       wr = NSMakeRect (0, 0, neww, newh);
6475       [view setFrame: wr];
6477       // to do: consider using [NSNotificationCenter postNotificationName:].
6478       [self windowDidMove: // Update top/left.
6479               [NSNotification notificationWithName:NSWindowDidMoveNotification
6480                                             object:[view window]]];
6481     }
6482   else
6483     {
6484       NSTRACE_MSG ("No change");
6485     }
6488 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6489 /* normalize frame to gridded text size */
6491   int extra = 0;
6493   NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6494            NSTRACE_ARG_SIZE (frameSize));
6495   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6496   NSTRACE_FSTYPE ("fs_state", fs_state);
6498   if (fs_state == FULLSCREEN_MAXIMIZED
6499       && (maximized_width != (int)frameSize.width
6500           || maximized_height != (int)frameSize.height))
6501     [self setFSValue: FULLSCREEN_NONE];
6502   else if (fs_state == FULLSCREEN_WIDTH
6503            && maximized_width != (int)frameSize.width)
6504     [self setFSValue: FULLSCREEN_NONE];
6505   else if (fs_state == FULLSCREEN_HEIGHT
6506            && maximized_height != (int)frameSize.height)
6507     [self setFSValue: FULLSCREEN_NONE];
6509   if (fs_state == FULLSCREEN_NONE)
6510     maximized_width = maximized_height = -1;
6512   if (! [self isFullscreen])
6513     {
6514       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6515         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6516     }
6518   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6519   if (cols < MINWIDTH)
6520     cols = MINWIDTH;
6522   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6523                                            frameSize.height - extra);
6524   if (rows < MINHEIGHT)
6525     rows = MINHEIGHT;
6526 #ifdef NS_IMPL_COCOA
6527   {
6528     /* this sets window title to have size in it; the wm does this under GS */
6529     NSRect r = [[self window] frame];
6530     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6531       {
6532         if (old_title != 0)
6533           {
6534             xfree (old_title);
6535             old_title = 0;
6536           }
6537       }
6538     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6539       {
6540         char *size_title;
6541         NSWindow *window = [self window];
6542         if (old_title == 0)
6543           {
6544             char *t = strdup ([[[self window] title] UTF8String]);
6545             char *pos = strstr (t, "  â€”  ");
6546             if (pos)
6547               *pos = '\0';
6548             old_title = t;
6549           }
6550         size_title = xmalloc (strlen (old_title) + 40);
6551         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6552         [window setTitle: [NSString stringWithUTF8String: size_title]];
6553         [window display];
6554         xfree (size_title);
6555       }
6556   }
6557 #endif /* NS_IMPL_COCOA */
6559   NSTRACE_MSG ("cols: %d  rows: %d", cols, rows);
6561   /* Restrict the new size to the text gird.
6563      Don't restrict the width if the user only adjusted the height, and
6564      vice versa.  (Without this, the frame would shrink, and move
6565      slightly, if the window was resized by dragging one of its
6566      borders.) */
6567   if (!frame_resize_pixelwise)
6568     {
6569       NSRect r = [[self window] frame];
6571       if (r.size.width != frameSize.width)
6572         {
6573           frameSize.width =
6574             FRAME_TEXT_COLS_TO_PIXEL_WIDTH  (emacsframe, cols);
6575         }
6577       if (r.size.height != frameSize.height)
6578         {
6579           frameSize.height =
6580             FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6581         }
6582     }
6584   NSTRACE_RETURN_SIZE (frameSize);
6586   return frameSize;
6590 - (void)windowDidResize: (NSNotification *)notification
6592   NSTRACE ("[EmacsView windowDidResize:]");
6593   if (!FRAME_LIVE_P (emacsframe))
6594     {
6595       NSTRACE_MSG ("Ignored (frame dead)");
6596       return;
6597     }
6598   if (emacsframe->output_data.ns->in_animation)
6599     {
6600       NSTRACE_MSG ("Ignored (in animation)");
6601       return;
6602     }
6604   if (! [self fsIsNative])
6605     {
6606       NSWindow *theWindow = [notification object];
6607       /* We can get notification on the non-FS window when in
6608          fullscreen mode.  */
6609       if ([self window] != theWindow) return;
6610     }
6612   NSTRACE_RECT ("frame", [[notification object] frame]);
6614 #ifdef NS_IMPL_GNUSTEP
6615   NSWindow *theWindow = [notification object];
6617    /* In GNUstep, at least currently, it's possible to get a didResize
6618       without getting a willResize.. therefore we need to act as if we got
6619       the willResize now */
6620   NSSize sz = [theWindow frame].size;
6621   sz = [self windowWillResize: theWindow toSize: sz];
6622 #endif /* NS_IMPL_GNUSTEP */
6624   if (cols > 0 && rows > 0)
6625     {
6626       [self updateFrameSize: YES];
6627     }
6629   ns_send_appdefined (-1);
6632 #ifdef NS_IMPL_COCOA
6633 - (void)viewDidEndLiveResize
6635   NSTRACE ("[EmacsView viewDidEndLiveResize]");
6637   [super viewDidEndLiveResize];
6638   if (old_title != 0)
6639     {
6640       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6641       xfree (old_title);
6642       old_title = 0;
6643     }
6644   maximizing_resize = NO;
6646 #endif /* NS_IMPL_COCOA */
6649 - (void)windowDidBecomeKey: (NSNotification *)notification
6650 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6652   [self windowDidBecomeKey];
6656 - (void)windowDidBecomeKey      /* for direct calls */
6658   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6659   struct frame *old_focus = dpyinfo->x_focus_frame;
6661   NSTRACE ("[EmacsView windowDidBecomeKey]");
6663   if (emacsframe != old_focus)
6664     dpyinfo->x_focus_frame = emacsframe;
6666   ns_frame_rehighlight (emacsframe);
6668   if (emacs_event)
6669     {
6670       emacs_event->kind = FOCUS_IN_EVENT;
6671       EV_TRAILER ((id)nil);
6672     }
6676 - (void)windowDidResignKey: (NSNotification *)notification
6677 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6679   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6680   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6681   NSTRACE ("[EmacsView windowDidResignKey:]");
6683   if (is_focus_frame)
6684     dpyinfo->x_focus_frame = 0;
6686   emacsframe->mouse_moved = 0;
6687   ns_frame_rehighlight (emacsframe);
6689   /* FIXME: for some reason needed on second and subsequent clicks away
6690             from sole-frame Emacs to get hollow box to show */
6691   if (!windowClosing && [[self window] isVisible] == YES)
6692     {
6693       x_update_cursor (emacsframe, 1);
6694       x_set_frame_alpha (emacsframe);
6695     }
6697   if (any_help_event_p)
6698     {
6699       Lisp_Object frame;
6700       XSETFRAME (frame, emacsframe);
6701       help_echo_string = Qnil;
6702       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6703     }
6705   if (emacs_event && is_focus_frame)
6706     {
6707       [self deleteWorkingText];
6708       emacs_event->kind = FOCUS_OUT_EVENT;
6709       EV_TRAILER ((id)nil);
6710     }
6714 - (void)windowWillMiniaturize: sender
6716   NSTRACE ("[EmacsView windowWillMiniaturize:]");
6720 - (void)setFrame:(NSRect)frameRect;
6722   NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6723            NSTRACE_ARG_RECT (frameRect));
6725   [super setFrame:(NSRect)frameRect];
6729 - (BOOL)isFlipped
6731   return YES;
6735 - (BOOL)isOpaque
6737   return NO;
6741 - initFrameFromEmacs: (struct frame *)f
6743   NSRect r, wr;
6744   Lisp_Object tem;
6745   NSWindow *win;
6746   NSColor *col;
6747   NSString *name;
6749   NSTRACE ("[EmacsView initFrameFromEmacs:]");
6750   NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6752   windowClosing = NO;
6753   processingCompose = NO;
6754   scrollbarsNeedingUpdate = 0;
6755   fs_state = FULLSCREEN_NONE;
6756   fs_before_fs = next_maximized = -1;
6757 #ifdef HAVE_NATIVE_FS
6758   fs_is_native = ns_use_native_fullscreen;
6759 #else
6760   fs_is_native = NO;
6761 #endif
6762   maximized_width = maximized_height = -1;
6763   nonfs_window = nil;
6765   ns_userRect = NSMakeRect (0, 0, 0, 0);
6766   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6767                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6768   [self initWithFrame: r];
6769   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6771   FRAME_NS_VIEW (f) = self;
6772   emacsframe = f;
6773 #ifdef NS_IMPL_COCOA
6774   old_title = 0;
6775   maximizing_resize = NO;
6776 #endif
6778   win = [[EmacsWindow alloc]
6779             initWithContentRect: r
6780                       styleMask: (NSWindowStyleMaskResizable |
6781 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6782                                   NSWindowStyleMaskTitled |
6783 #endif
6784                                   NSWindowStyleMaskMiniaturizable |
6785                                   NSWindowStyleMaskClosable)
6786                         backing: NSBackingStoreBuffered
6787                           defer: YES];
6789 #ifdef HAVE_NATIVE_FS
6790     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6791 #endif
6793   wr = [win frame];
6794   bwidth = f->border_width = wr.size.width - r.size.width;
6795   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6797   [win setAcceptsMouseMovedEvents: YES];
6798   [win setDelegate: self];
6799 #if !defined (NS_IMPL_COCOA) || \
6800   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6801   [win useOptimizedDrawing: YES];
6802 #endif
6804   [[win contentView] addSubview: self];
6806   if (ns_drag_types)
6807     [self registerForDraggedTypes: ns_drag_types];
6809   tem = f->name;
6810   name = [NSString stringWithUTF8String:
6811                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6812   [win setTitle: name];
6814   /* toolbar support */
6815   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6816                          [NSString stringWithFormat: @"Emacs Frame %d",
6817                                    ns_window_num]];
6818   [win setToolbar: toolbar];
6819   [toolbar setVisible: NO];
6821   /* Don't set frame garbaged until tool bar is up to date?
6822      This avoids an extra clear and redraw (flicker) at frame creation.  */
6823   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6824   else wait_for_tool_bar = NO;
6827 #ifdef NS_IMPL_COCOA
6828   {
6829     NSButton *toggleButton;
6830   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6831   [toggleButton setTarget: self];
6832   [toggleButton setAction: @selector (toggleToolbar: )];
6833   }
6834 #endif
6835   FRAME_TOOLBAR_HEIGHT (f) = 0;
6837   tem = f->icon_name;
6838   if (!NILP (tem))
6839     [win setMiniwindowTitle:
6840            [NSString stringWithUTF8String: SSDATA (tem)]];
6842   {
6843     NSScreen *screen = [win screen];
6845     if (screen != 0)
6846       {
6847         NSPoint pt = NSMakePoint
6848           (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6849            IN_BOUND (-SCREENMAX,
6850                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6852         [win setFrameTopLeftPoint: pt];
6854         NSTRACE_RECT ("new frame", [win frame]);
6855       }
6856   }
6858   [win makeFirstResponder: self];
6860   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6861                                  (FACE_FROM_ID (emacsframe, DEFAULT_FACE_ID)),
6862                                  emacsframe);
6863   [win setBackgroundColor: col];
6864   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6865     [win setOpaque: NO];
6867 #if !defined (NS_IMPL_COCOA) || \
6868   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6869   [self allocateGState];
6870 #endif
6871   [NSApp registerServicesMenuSendTypes: ns_send_types
6872                            returnTypes: nil];
6874   ns_window_num++;
6875   return self;
6879 - (void)windowDidMove: sender
6881   NSWindow *win = [self window];
6882   NSRect r = [win frame];
6883   NSArray *screens = [NSScreen screens];
6884   NSScreen *screen = [screens objectAtIndex: 0];
6886   NSTRACE ("[EmacsView windowDidMove:]");
6888   if (!emacsframe->output_data.ns)
6889     return;
6890   if (screen != nil)
6891     {
6892       emacsframe->left_pos = r.origin.x;
6893       emacsframe->top_pos =
6894         [screen frame].size.height - (r.origin.y + r.size.height);
6895     }
6899 /* Called AFTER method below, but before our windowWillResize call there leads
6900    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6901    location so set_window_size moves the frame. */
6902 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6904   NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6905             NSTRACE_FMT_RETURN "YES"),
6906            NSTRACE_ARG_RECT (newFrame));
6908   emacsframe->output_data.ns->zooming = 1;
6909   return YES;
6913 /* Override to do something slightly nonstandard, but nice.  First click on
6914    zoom button will zoom vertically.  Second will zoom completely.  Third
6915    returns to original. */
6916 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6917                         defaultFrame:(NSRect)defaultFrame
6919   // TODO: Rename to "currentFrame" and assign "result" properly in
6920   // all paths.
6921   NSRect result = [sender frame];
6923   NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6924             NSTRACE_FMT_RECT "]"),
6925            NSTRACE_ARG_RECT (defaultFrame));
6926   NSTRACE_FSTYPE ("fs_state", fs_state);
6927   NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6928   NSTRACE_FSTYPE ("next_maximized", next_maximized);
6929   NSTRACE_RECT   ("ns_userRect", ns_userRect);
6930   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6932   if (fs_before_fs != -1) /* Entering fullscreen */
6933     {
6934       NSTRACE_MSG ("Entering fullscreen");
6935       result = defaultFrame;
6936     }
6937   else
6938     {
6939       // Save the window size and position (frame) before the resize.
6940       if (fs_state != FULLSCREEN_MAXIMIZED
6941           && fs_state != FULLSCREEN_WIDTH)
6942         {
6943           ns_userRect.size.width = result.size.width;
6944           ns_userRect.origin.x   = result.origin.x;
6945         }
6947       if (fs_state != FULLSCREEN_MAXIMIZED
6948           && fs_state != FULLSCREEN_HEIGHT)
6949         {
6950           ns_userRect.size.height = result.size.height;
6951           ns_userRect.origin.y    = result.origin.y;
6952         }
6954       NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6956       if (next_maximized == FULLSCREEN_HEIGHT
6957           || (next_maximized == -1
6958               && abs ((int)(defaultFrame.size.height - result.size.height))
6959               > FRAME_LINE_HEIGHT (emacsframe)))
6960         {
6961           /* first click */
6962           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6963           maximized_height = result.size.height = defaultFrame.size.height;
6964           maximized_width = -1;
6965           result.origin.y = defaultFrame.origin.y;
6966           if (ns_userRect.size.height != 0)
6967             {
6968               result.origin.x = ns_userRect.origin.x;
6969               result.size.width = ns_userRect.size.width;
6970             }
6971           [self setFSValue: FULLSCREEN_HEIGHT];
6972 #ifdef NS_IMPL_COCOA
6973           maximizing_resize = YES;
6974 #endif
6975         }
6976       else if (next_maximized == FULLSCREEN_WIDTH)
6977         {
6978           NSTRACE_MSG ("FULLSCREEN_WIDTH");
6979           maximized_width = result.size.width = defaultFrame.size.width;
6980           maximized_height = -1;
6981           result.origin.x = defaultFrame.origin.x;
6982           if (ns_userRect.size.width != 0)
6983             {
6984               result.origin.y = ns_userRect.origin.y;
6985               result.size.height = ns_userRect.size.height;
6986             }
6987           [self setFSValue: FULLSCREEN_WIDTH];
6988         }
6989       else if (next_maximized == FULLSCREEN_MAXIMIZED
6990                || (next_maximized == -1
6991                    && abs ((int)(defaultFrame.size.width - result.size.width))
6992                    > FRAME_COLUMN_WIDTH (emacsframe)))
6993         {
6994           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6996           result = defaultFrame;  /* second click */
6997           maximized_width = result.size.width;
6998           maximized_height = result.size.height;
6999           [self setFSValue: FULLSCREEN_MAXIMIZED];
7000 #ifdef NS_IMPL_COCOA
7001           maximizing_resize = YES;
7002 #endif
7003         }
7004       else
7005         {
7006           /* restore */
7007           NSTRACE_MSG ("Restore");
7008           result = ns_userRect.size.height ? ns_userRect : result;
7009           NSTRACE_RECT ("restore (2)", result);
7010           ns_userRect = NSMakeRect (0, 0, 0, 0);
7011 #ifdef NS_IMPL_COCOA
7012           maximizing_resize = fs_state != FULLSCREEN_NONE;
7013 #endif
7014           [self setFSValue: FULLSCREEN_NONE];
7015           maximized_width = maximized_height = -1;
7016         }
7017     }
7019   if (fs_before_fs == -1) next_maximized = -1;
7021   NSTRACE_RECT   ("Final ns_userRect", ns_userRect);
7022   NSTRACE_MSG    ("Final maximized_width: %d", maximized_width);
7023   NSTRACE_MSG    ("Final maximized_height: %d", maximized_height);
7024   NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
7026   [self windowWillResize: sender toSize: result.size];
7028   NSTRACE_RETURN_RECT (result);
7030   return result;
7034 - (void)windowDidDeminiaturize: sender
7036   NSTRACE ("[EmacsView windowDidDeminiaturize:]");
7037   if (!emacsframe->output_data.ns)
7038     return;
7040   SET_FRAME_ICONIFIED (emacsframe, 0);
7041   SET_FRAME_VISIBLE (emacsframe, 1);
7042   windows_or_buffers_changed = 63;
7044   if (emacs_event)
7045     {
7046       emacs_event->kind = DEICONIFY_EVENT;
7047       EV_TRAILER ((id)nil);
7048     }
7052 - (void)windowDidExpose: sender
7054   NSTRACE ("[EmacsView windowDidExpose:]");
7055   if (!emacsframe->output_data.ns)
7056     return;
7058   SET_FRAME_VISIBLE (emacsframe, 1);
7059   SET_FRAME_GARBAGED (emacsframe);
7061   if (send_appdefined)
7062     ns_send_appdefined (-1);
7066 - (void)windowDidMiniaturize: sender
7068   NSTRACE ("[EmacsView windowDidMiniaturize:]");
7069   if (!emacsframe->output_data.ns)
7070     return;
7072   SET_FRAME_ICONIFIED (emacsframe, 1);
7073   SET_FRAME_VISIBLE (emacsframe, 0);
7075   if (emacs_event)
7076     {
7077       emacs_event->kind = ICONIFY_EVENT;
7078       EV_TRAILER ((id)nil);
7079     }
7082 #ifdef HAVE_NATIVE_FS
7083 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7084       willUseFullScreenPresentationOptions:
7085   (NSApplicationPresentationOptions)proposedOptions
7087   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7089 #endif
7091 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7093   NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7094   [self windowWillEnterFullScreen];
7096 - (void)windowWillEnterFullScreen /* provided for direct calls */
7098   NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7099   fs_before_fs = fs_state;
7102 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7104   NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7105   [self windowDidEnterFullScreen];
7108 - (void)windowDidEnterFullScreen /* provided for direct calls */
7110   NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7111   [self setFSValue: FULLSCREEN_BOTH];
7112   if (! [self fsIsNative])
7113     {
7114       [self windowDidBecomeKey];
7115       [nonfs_window orderOut:self];
7116     }
7117   else
7118     {
7119       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7120 #ifdef NS_IMPL_COCOA
7121 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7122       unsigned val = (unsigned)[NSApp presentationOptions];
7124       // OSX 10.7 bug fix, the menu won't appear without this.
7125       // val is non-zero on other OSX versions.
7126       if (val == 0)
7127         {
7128           NSApplicationPresentationOptions options
7129             = NSApplicationPresentationAutoHideDock
7130             | NSApplicationPresentationAutoHideMenuBar
7131             | NSApplicationPresentationFullScreen
7132             | NSApplicationPresentationAutoHideToolbar;
7134           [NSApp setPresentationOptions: options];
7135         }
7136 #endif
7137 #endif
7138       [toolbar setVisible:tbar_visible];
7139     }
7142 - (void)windowWillExitFullScreen:(NSNotification *)notification
7144   NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7145   [self windowWillExitFullScreen];
7148 - (void)windowWillExitFullScreen /* provided for direct calls */
7150   NSTRACE ("[EmacsView windowWillExitFullScreen]");
7151   if (!FRAME_LIVE_P (emacsframe))
7152     {
7153       NSTRACE_MSG ("Ignored (frame dead)");
7154       return;
7155     }
7156   if (next_maximized != -1)
7157     fs_before_fs = next_maximized;
7160 - (void)windowDidExitFullScreen:(NSNotification *)notification
7162   NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7163   [self windowDidExitFullScreen];
7166 - (void)windowDidExitFullScreen /* provided for direct calls */
7168   NSTRACE ("[EmacsView windowDidExitFullScreen]");
7169   if (!FRAME_LIVE_P (emacsframe))
7170     {
7171       NSTRACE_MSG ("Ignored (frame dead)");
7172       return;
7173     }
7174   [self setFSValue: fs_before_fs];
7175   fs_before_fs = -1;
7176 #ifdef HAVE_NATIVE_FS
7177   [self updateCollectionBehavior];
7178 #endif
7179   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7180     {
7181       [toolbar setVisible:YES];
7182       update_frame_tool_bar (emacsframe);
7183       [self updateFrameSize:YES];
7184       [[self window] display];
7185     }
7186   else
7187     [toolbar setVisible:NO];
7189   if (next_maximized != -1)
7190     [[self window] performZoom:self];
7193 - (BOOL)fsIsNative
7195   return fs_is_native;
7198 - (BOOL)isFullscreen
7200   BOOL res;
7202   if (! fs_is_native)
7203     {
7204       res = (nonfs_window != nil);
7205     }
7206   else
7207     {
7208 #ifdef HAVE_NATIVE_FS
7209       res = (([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0);
7210 #else
7211       res = NO;
7212 #endif
7213     }
7215   NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7216            (int) res);
7218   return res;
7221 #ifdef HAVE_NATIVE_FS
7222 - (void)updateCollectionBehavior
7224   NSTRACE ("[EmacsView updateCollectionBehavior]");
7226   if (! [self isFullscreen])
7227     {
7228       NSWindow *win = [self window];
7229       NSWindowCollectionBehavior b = [win collectionBehavior];
7230       if (ns_use_native_fullscreen)
7231         b |= NSWindowCollectionBehaviorFullScreenPrimary;
7232       else
7233         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7235       [win setCollectionBehavior: b];
7236       fs_is_native = ns_use_native_fullscreen;
7237     }
7239 #endif
7241 - (void)toggleFullScreen: (id)sender
7243   NSWindow *w, *fw;
7244   BOOL onFirstScreen;
7245   struct frame *f;
7246   NSRect r, wr;
7247   NSColor *col;
7249   NSTRACE ("[EmacsView toggleFullScreen:]");
7251   if (fs_is_native)
7252     {
7253 #ifdef HAVE_NATIVE_FS
7254       [[self window] toggleFullScreen:sender];
7255 #endif
7256       return;
7257     }
7259   w = [self window];
7260   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7261   f = emacsframe;
7262   wr = [w frame];
7263   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7264                                  (FACE_FROM_ID (f, DEFAULT_FACE_ID)),
7265                                  f);
7267   if (fs_state != FULLSCREEN_BOTH)
7268     {
7269       NSScreen *screen = [w screen];
7271 #if defined (NS_IMPL_COCOA) && \
7272   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7273       /* Hide ghost menu bar on secondary monitor? */
7274       if (! onFirstScreen)
7275         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7276 #endif
7277       /* Hide dock and menubar if we are on the primary screen.  */
7278       if (onFirstScreen)
7279         {
7280 #ifdef NS_IMPL_COCOA
7281           NSApplicationPresentationOptions options
7282             = NSApplicationPresentationAutoHideDock
7283             | NSApplicationPresentationAutoHideMenuBar;
7285           [NSApp setPresentationOptions: options];
7286 #else
7287           [NSMenu setMenuBarVisible:NO];
7288 #endif
7289         }
7291       fw = [[EmacsFSWindow alloc]
7292                        initWithContentRect:[w contentRectForFrameRect:wr]
7293                                  styleMask:NSWindowStyleMaskBorderless
7294                                    backing:NSBackingStoreBuffered
7295                                      defer:YES
7296                                     screen:screen];
7298       [fw setContentView:[w contentView]];
7299       [fw setTitle:[w title]];
7300       [fw setDelegate:self];
7301       [fw setAcceptsMouseMovedEvents: YES];
7302 #if !defined (NS_IMPL_COCOA) || \
7303   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7304       [fw useOptimizedDrawing: YES];
7305 #endif
7306       [fw setBackgroundColor: col];
7307       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7308         [fw setOpaque: NO];
7310       f->border_width = 0;
7311       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7312       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7313       FRAME_TOOLBAR_HEIGHT (f) = 0;
7315       nonfs_window = w;
7317       [self windowWillEnterFullScreen];
7318       [fw makeKeyAndOrderFront:NSApp];
7319       [fw makeFirstResponder:self];
7320       [w orderOut:self];
7321       r = [fw frameRectForContentRect:[screen frame]];
7322       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7323       [self windowDidEnterFullScreen];
7324       [fw display];
7325     }
7326   else
7327     {
7328       fw = w;
7329       w = nonfs_window;
7330       nonfs_window = nil;
7332       if (onFirstScreen)
7333         {
7334 #ifdef NS_IMPL_COCOA
7335           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7336 #else
7337           [NSMenu setMenuBarVisible:YES];
7338 #endif
7339         }
7341       [w setContentView:[fw contentView]];
7342       [w setBackgroundColor: col];
7343       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7344         [w setOpaque: NO];
7346       f->border_width = bwidth;
7347       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7348       if (FRAME_EXTERNAL_TOOL_BAR (f))
7349         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7351       // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7353       [self windowWillExitFullScreen];
7354       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7355       [fw close];
7356       [w makeKeyAndOrderFront:NSApp];
7357       [self windowDidExitFullScreen];
7358       [self updateFrameSize:YES];
7359     }
7362 - (void)handleFS
7364   NSTRACE ("[EmacsView handleFS]");
7366   if (fs_state != emacsframe->want_fullscreen)
7367     {
7368       if (fs_state == FULLSCREEN_BOTH)
7369         {
7370           NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7371           [self toggleFullScreen:self];
7372         }
7374       switch (emacsframe->want_fullscreen)
7375         {
7376         case FULLSCREEN_BOTH:
7377           NSTRACE_MSG ("FULLSCREEN_BOTH");
7378           [self toggleFullScreen:self];
7379           break;
7380         case FULLSCREEN_WIDTH:
7381           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7382           next_maximized = FULLSCREEN_WIDTH;
7383           if (fs_state != FULLSCREEN_BOTH)
7384             [[self window] performZoom:self];
7385           break;
7386         case FULLSCREEN_HEIGHT:
7387           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7388           next_maximized = FULLSCREEN_HEIGHT;
7389           if (fs_state != FULLSCREEN_BOTH)
7390             [[self window] performZoom:self];
7391           break;
7392         case FULLSCREEN_MAXIMIZED:
7393           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7394           next_maximized = FULLSCREEN_MAXIMIZED;
7395           if (fs_state != FULLSCREEN_BOTH)
7396             [[self window] performZoom:self];
7397           break;
7398         case FULLSCREEN_NONE:
7399           NSTRACE_MSG ("FULLSCREEN_NONE");
7400           if (fs_state != FULLSCREEN_BOTH)
7401             {
7402               next_maximized = FULLSCREEN_NONE;
7403               [[self window] performZoom:self];
7404             }
7405           break;
7406         }
7408       emacsframe->want_fullscreen = FULLSCREEN_NONE;
7409     }
7413 - (void) setFSValue: (int)value
7415   NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7416            NSTRACE_ARG_FSTYPE(value));
7418   Lisp_Object lval = Qnil;
7419   switch (value)
7420     {
7421     case FULLSCREEN_BOTH:
7422       lval = Qfullboth;
7423       break;
7424     case FULLSCREEN_WIDTH:
7425       lval = Qfullwidth;
7426       break;
7427     case FULLSCREEN_HEIGHT:
7428       lval = Qfullheight;
7429       break;
7430     case FULLSCREEN_MAXIMIZED:
7431       lval = Qmaximized;
7432       break;
7433     }
7434   store_frame_param (emacsframe, Qfullscreen, lval);
7435   fs_state = value;
7438 - (void)mouseEntered: (NSEvent *)theEvent
7440   NSTRACE ("[EmacsView mouseEntered:]");
7441   if (emacsframe)
7442     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7443       = EV_TIMESTAMP (theEvent);
7447 - (void)mouseExited: (NSEvent *)theEvent
7449   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7451   NSTRACE ("[EmacsView mouseExited:]");
7453   if (!hlinfo)
7454     return;
7456   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7457     = EV_TIMESTAMP (theEvent);
7459   if (emacsframe == hlinfo->mouse_face_mouse_frame)
7460     {
7461       clear_mouse_face (hlinfo);
7462       hlinfo->mouse_face_mouse_frame = 0;
7463     }
7467 - menuDown: sender
7469   NSTRACE ("[EmacsView menuDown:]");
7470   if (context_menu_value == -1)
7471     context_menu_value = [sender tag];
7472   else
7473     {
7474       NSInteger tag = [sender tag];
7475       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7476                                     emacsframe->menu_bar_vector,
7477                                     (void *)tag);
7478     }
7480   ns_send_appdefined (-1);
7481   return self;
7485 - (EmacsToolbar *)toolbar
7487   return toolbar;
7491 /* this gets called on toolbar button click */
7492 - toolbarClicked: (id)item
7494   NSEvent *theEvent;
7495   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7497   NSTRACE ("[EmacsView toolbarClicked:]");
7499   if (!emacs_event)
7500     return self;
7502   /* send first event (for some reason two needed) */
7503   theEvent = [[self window] currentEvent];
7504   emacs_event->kind = TOOL_BAR_EVENT;
7505   XSETFRAME (emacs_event->arg, emacsframe);
7506   EV_TRAILER (theEvent);
7508   emacs_event->kind = TOOL_BAR_EVENT;
7509 /*   XSETINT (emacs_event->code, 0); */
7510   emacs_event->arg = AREF (emacsframe->tool_bar_items,
7511                            idx + TOOL_BAR_ITEM_KEY);
7512   emacs_event->modifiers = EV_MODIFIERS (theEvent);
7513   EV_TRAILER (theEvent);
7514   return self;
7518 - toggleToolbar: (id)sender
7520   NSTRACE ("[EmacsView toggleToolbar:]");
7522   if (!emacs_event)
7523     return self;
7525   emacs_event->kind = NS_NONKEY_EVENT;
7526   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7527   EV_TRAILER ((id)nil);
7528   return self;
7532 - (void)drawRect: (NSRect)rect
7534   int x = NSMinX (rect), y = NSMinY (rect);
7535   int width = NSWidth (rect), height = NSHeight (rect);
7537   NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7538            NSTRACE_ARG_RECT(rect));
7540   if (!emacsframe || !emacsframe->output_data.ns)
7541     return;
7543   ns_clear_frame_area (emacsframe, x, y, width, height);
7544   block_input ();
7545   expose_frame (emacsframe, x, y, width, height);
7546   unblock_input ();
7548   /*
7549     drawRect: may be called (at least in OS X 10.5) for invisible
7550     views as well for some reason.  Thus, do not infer visibility
7551     here.
7553     emacsframe->async_visible = 1;
7554     emacsframe->async_iconified = 0;
7555   */
7559 /* NSDraggingDestination protocol methods.  Actually this is not really a
7560    protocol, but a category of Object.  O well...  */
7562 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7564   NSTRACE ("[EmacsView draggingEntered:]");
7565   return NSDragOperationGeneric;
7569 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7571   return YES;
7575 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7577   id pb;
7578   int x, y;
7579   NSString *type;
7580   NSEvent *theEvent = [[self window] currentEvent];
7581   NSPoint position;
7582   NSDragOperation op = [sender draggingSourceOperationMask];
7583   int modifiers = 0;
7585   NSTRACE ("[EmacsView performDragOperation:]");
7587   if (!emacs_event)
7588     return NO;
7590   position = [self convertPoint: [sender draggingLocation] fromView: nil];
7591   x = lrint (position.x);  y = lrint (position.y);
7593   pb = [sender draggingPasteboard];
7594   type = [pb availableTypeFromArray: ns_drag_types];
7596   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7597       // URL drags contain all operations (0xf), don't allow all to be set.
7598       (op & 0xf) != 0xf)
7599     {
7600       if (op & NSDragOperationLink)
7601         modifiers |= NSEventModifierFlagControl;
7602       if (op & NSDragOperationCopy)
7603         modifiers |= NSEventModifierFlagOption;
7604       if (op & NSDragOperationGeneric)
7605         modifiers |= NSEventModifierFlagCommand;
7606     }
7608   modifiers = EV_MODIFIERS2 (modifiers);
7609   if (type == 0)
7610     {
7611       return NO;
7612     }
7613   else if ([type isEqualToString: NSFilenamesPboardType])
7614     {
7615       NSArray *files;
7616       NSEnumerator *fenum;
7617       NSString *file;
7619       if (!(files = [pb propertyListForType: type]))
7620         return NO;
7622       fenum = [files objectEnumerator];
7623       while ( (file = [fenum nextObject]) )
7624         {
7625           emacs_event->kind = DRAG_N_DROP_EVENT;
7626           XSETINT (emacs_event->x, x);
7627           XSETINT (emacs_event->y, y);
7628           ns_input_file = append2 (ns_input_file,
7629                                    build_string ([file UTF8String]));
7630           emacs_event->modifiers = modifiers;
7631           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
7632           EV_TRAILER (theEvent);
7633         }
7634       return YES;
7635     }
7636   else if ([type isEqualToString: NSURLPboardType])
7637     {
7638       NSURL *url = [NSURL URLFromPasteboard: pb];
7639       if (url == nil) return NO;
7641       emacs_event->kind = DRAG_N_DROP_EVENT;
7642       XSETINT (emacs_event->x, x);
7643       XSETINT (emacs_event->y, y);
7644       emacs_event->modifiers = modifiers;
7645       emacs_event->arg =  list2 (Qurl,
7646                                  build_string ([[url absoluteString]
7647                                                  UTF8String]));
7648       EV_TRAILER (theEvent);
7650       if ([url isFileURL] != NO)
7651         {
7652           NSString *file = [url path];
7653           ns_input_file = append2 (ns_input_file,
7654                                    build_string ([file UTF8String]));
7655         }
7656       return YES;
7657     }
7658   else if ([type isEqualToString: NSStringPboardType]
7659            || [type isEqualToString: NSTabularTextPboardType])
7660     {
7661       NSString *data;
7663       if (! (data = [pb stringForType: type]))
7664         return NO;
7666       emacs_event->kind = DRAG_N_DROP_EVENT;
7667       XSETINT (emacs_event->x, x);
7668       XSETINT (emacs_event->y, y);
7669       emacs_event->modifiers = modifiers;
7670       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7671       EV_TRAILER (theEvent);
7672       return YES;
7673     }
7674   else
7675     {
7676       fprintf (stderr, "Invalid data type in dragging pasteboard");
7677       return NO;
7678     }
7682 - (id) validRequestorForSendType: (NSString *)typeSent
7683                       returnType: (NSString *)typeReturned
7685   NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7686   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7687       && typeReturned == nil)
7688     {
7689       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7690         return self;
7691     }
7693   return [super validRequestorForSendType: typeSent
7694                                returnType: typeReturned];
7698 /* The next two methods are part of NSServicesRequests informal protocol,
7699    supposedly called when a services menu item is chosen from this app.
7700    But this should not happen because we override the services menu with our
7701    own entries which call ns-perform-service.
7702    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7703    So let's at least stub them out until further investigation can be done. */
7705 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7707   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7708      be written into the buffer in place of the existing selection..
7709      ordinary service calls go through functions defined in ns-win.el */
7710   return NO;
7713 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7715   NSArray *typesDeclared;
7716   Lisp_Object val;
7718   NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7720   /* We only support NSStringPboardType */
7721   if ([types containsObject:NSStringPboardType] == NO) {
7722     return NO;
7723   }
7725   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7726   if (CONSP (val) && SYMBOLP (XCAR (val)))
7727     {
7728       val = XCDR (val);
7729       if (CONSP (val) && NILP (XCDR (val)))
7730         val = XCAR (val);
7731     }
7732   if (! STRINGP (val))
7733     return NO;
7735   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7736   [pb declareTypes:typesDeclared owner:nil];
7737   ns_string_to_pasteboard (pb, val);
7738   return YES;
7742 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7743    (gives a miniaturized version of the window); currently we use the latter for
7744    frames whose active buffer doesn't correspond to any file
7745    (e.g., '*scratch*') */
7746 - setMiniwindowImage: (BOOL) setMini
7748   id image = [[self window] miniwindowImage];
7749   NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7751   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7752      about "AppleDockIconEnabled" notwithstanding, however the set message
7753      below has its effect nonetheless. */
7754   if (image != emacsframe->output_data.ns->miniimage)
7755     {
7756       if (image && [image isKindOfClass: [EmacsImage class]])
7757         [image release];
7758       [[self window] setMiniwindowImage:
7759                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7760     }
7762   return self;
7766 - (void) setRows: (int) r andColumns: (int) c
7768   NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7769   rows = r;
7770   cols = c;
7773 - (int) fullscreenState
7775   return fs_state;
7778 @end  /* EmacsView */
7782 /* ==========================================================================
7784     EmacsWindow implementation
7786    ========================================================================== */
7788 @implementation EmacsWindow
7790 #ifdef NS_IMPL_COCOA
7791 - (id)accessibilityAttributeValue:(NSString *)attribute
7793   Lisp_Object str = Qnil;
7794   struct frame *f = SELECTED_FRAME ();
7795   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7797   NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7799   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7800     return NSAccessibilityTextFieldRole;
7802   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7803       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7804     {
7805       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7806     }
7807   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7808     {
7809       if (! NILP (BVAR (curbuf, mark_active)))
7810           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7812       if (NILP (str))
7813         {
7814           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7815           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7816           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7818           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7819             str = make_uninit_multibyte_string (range, byte_range);
7820           else
7821             str = make_uninit_string (range);
7822           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7823              Is this a problem?  */
7824           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7825         }
7826     }
7829   if (! NILP (str))
7830     {
7831       if (CONSP (str) && SYMBOLP (XCAR (str)))
7832         {
7833           str = XCDR (str);
7834           if (CONSP (str) && NILP (XCDR (str)))
7835             str = XCAR (str);
7836         }
7837       if (STRINGP (str))
7838         {
7839           const char *utfStr = SSDATA (str);
7840           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7841           return nsStr;
7842         }
7843     }
7845   return [super accessibilityAttributeValue:attribute];
7847 #endif /* NS_IMPL_COCOA */
7849 /* Constrain size and placement of a frame.
7851    By returning the original "frameRect", the frame is not
7852    constrained. This can lead to unwanted situations where, for
7853    example, the menu bar covers the frame.
7855    The default implementation (accessed using "super") constrains the
7856    frame to the visible area of SCREEN, minus the menu bar (if
7857    present) and the Dock.  Note that default implementation also calls
7858    windowWillResize, with the frame it thinks should have.  (This can
7859    make the frame exit maximized mode.)
7861    Note that this should work in situations where multiple monitors
7862    are present.  Common configurations are side-by-side monitors and a
7863    monitor on top of another (e.g. when a laptop is placed under a
7864    large screen). */
7865 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7867   NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7868              NSTRACE_ARG_RECT (frameRect));
7870 #ifdef NS_IMPL_COCOA
7871 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7872   // If separate spaces is on, it is like each screen is independent.  There is
7873   // no spanning of frames across screens.
7874   if ([NSScreen screensHaveSeparateSpaces])
7875     {
7876       NSTRACE_MSG ("Screens have separate spaces");
7877       frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7878       NSTRACE_RETURN_RECT (frameRect);
7879       return frameRect;
7880     }
7881 #endif
7882 #endif
7884   return constrain_frame_rect(frameRect,
7885                               [(EmacsView *)[self delegate] isFullscreen]);
7889 - (void)performZoom:(id)sender
7891   NSTRACE ("[EmacsWindow performZoom:]");
7893   return [super performZoom:sender];
7896 - (void)zoom:(id)sender
7898   NSTRACE ("[EmacsWindow zoom:]");
7900   ns_update_auto_hide_menu_bar();
7902   // Below are three zoom implementations.  In the final commit, the
7903   // idea is that the last should be included.
7905 #if 0
7906   // Native zoom done using the standard zoom animation.  Size of the
7907   // resulting frame reduced to accommodate the Dock and, if present,
7908   // the menu-bar.
7909   [super zoom:sender];
7911 #elif 0
7912   // Native zoom done using the standard zoom animation, plus an
7913   // explicit resize to cover the full screen, except the menu-bar and
7914   // dock, if present.
7915   [super zoom:sender];
7917   // After the native zoom, resize the resulting frame to fill the
7918   // entire screen, except the menu-bar.
7919   //
7920   // This works for all practical purposes.  (The only minor oddity is
7921   // when transiting from full-height frame to a maximized, the
7922   // animation reduces the height of the frame slightly (to the 4
7923   // pixels needed to accommodate the Doc) before it snaps back into
7924   // full height.  The user would need a very trained eye to spot
7925   // this.)
7926   NSScreen * screen = [self screen];
7927   if (screen != nil)
7928     {
7929       int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7931       NSTRACE_FSTYPE ("fullscreenState", fs_state);
7933       NSRect sr = [screen frame];
7934       struct EmacsMargins margins
7935         = ns_screen_margins_ignoring_hidden_dock(screen);
7937       NSRect wr = [self frame];
7938       NSTRACE_RECT ("Rect after zoom", wr);
7940       NSRect newWr = wr;
7942       if (fs_state == FULLSCREEN_MAXIMIZED
7943           || fs_state == FULLSCREEN_HEIGHT)
7944         {
7945           newWr.origin.y = sr.origin.y + margins.bottom;
7946           newWr.size.height = sr.size.height - margins.top - margins.bottom;
7947         }
7949       if (fs_state == FULLSCREEN_MAXIMIZED
7950           || fs_state == FULLSCREEN_WIDTH)
7951         {
7952           newWr.origin.x = sr.origin.x + margins.left;
7953           newWr.size.width = sr.size.width - margins.right - margins.left;
7954         }
7956       if (newWr.size.width     != wr.size.width
7957           || newWr.size.height != wr.size.height
7958           || newWr.origin.x    != wr.origin.x
7959           || newWr.origin.y    != wr.origin.y)
7960         {
7961           NSTRACE_MSG ("New frame different");
7962           [self setFrame: newWr display: NO];
7963         }
7964     }
7965 #else
7966   // Non-native zoom which is done instantaneously.  The resulting
7967   // frame covers the entire screen, except the menu-bar and dock, if
7968   // present.
7969   NSScreen * screen = [self screen];
7970   if (screen != nil)
7971     {
7972       NSRect sr = [screen frame];
7973       struct EmacsMargins margins
7974         = ns_screen_margins_ignoring_hidden_dock(screen);
7976       sr.size.height -= (margins.top + margins.bottom);
7977       sr.size.width  -= (margins.left + margins.right);
7978       sr.origin.x += margins.left;
7979       sr.origin.y += margins.bottom;
7981       sr = [[self delegate] windowWillUseStandardFrame:self
7982                                           defaultFrame:sr];
7983       [self setFrame: sr display: NO];
7984     }
7985 #endif
7988 - (void)setFrame:(NSRect)windowFrame
7989          display:(BOOL)displayViews
7991   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7992            NSTRACE_ARG_RECT (windowFrame), displayViews);
7994   [super setFrame:windowFrame display:displayViews];
7997 - (void)setFrame:(NSRect)windowFrame
7998          display:(BOOL)displayViews
7999          animate:(BOOL)performAnimation
8001   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
8002            " display:%d performAnimation:%d]",
8003            NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
8005   [super setFrame:windowFrame display:displayViews animate:performAnimation];
8008 - (void)setFrameTopLeftPoint:(NSPoint)point
8010   NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
8011            NSTRACE_ARG_POINT (point));
8013   [super setFrameTopLeftPoint:point];
8015 @end /* EmacsWindow */
8018 @implementation EmacsFSWindow
8020 - (BOOL)canBecomeKeyWindow
8022   return YES;
8025 - (BOOL)canBecomeMainWindow
8027   return YES;
8030 @end
8032 /* ==========================================================================
8034     EmacsScroller implementation
8036    ========================================================================== */
8039 @implementation EmacsScroller
8041 /* for repeat button push */
8042 #define SCROLL_BAR_FIRST_DELAY 0.5
8043 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
8045 + (CGFloat) scrollerWidth
8047   /* TODO: if we want to allow variable widths, this is the place to do it,
8048            however neither GNUstep nor Cocoa support it very well */
8049   CGFloat r;
8050 #if !defined (NS_IMPL_COCOA) || \
8051   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8052   r = [NSScroller scrollerWidth];
8053 #else
8054   r = [NSScroller scrollerWidthForControlSize: NSControlSizeRegular
8055                                 scrollerStyle: NSScrollerStyleLegacy];
8056 #endif
8057   return r;
8060 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8062   NSTRACE ("[EmacsScroller initFrame: window:]");
8064   if (r.size.width > r.size.height)
8065       horizontal = YES;
8066   else
8067       horizontal = NO;
8069   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8070   [self setContinuous: YES];
8071   [self setEnabled: YES];
8073   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8074      locked against the top and bottom edges, and right edge on OS X, where
8075      scrollers are on right. */
8076 #ifdef NS_IMPL_GNUSTEP
8077   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8078 #else
8079   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8080 #endif
8082   window = XWINDOW (nwin);
8083   condemned = NO;
8084   if (horizontal)
8085     pixel_length = NSWidth (r);
8086   else
8087     pixel_length = NSHeight (r);
8088   if (pixel_length == 0) pixel_length = 1;
8089   min_portion = 20 / pixel_length;
8091   frame = XFRAME (window->frame);
8092   if (FRAME_LIVE_P (frame))
8093     {
8094       int i;
8095       EmacsView *view = FRAME_NS_VIEW (frame);
8096       NSView *sview = [[view window] contentView];
8097       NSArray *subs = [sview subviews];
8099       /* disable optimization stopping redraw of other scrollbars */
8100       view->scrollbarsNeedingUpdate = 0;
8101       for (i =[subs count]-1; i >= 0; i--)
8102         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8103           view->scrollbarsNeedingUpdate++;
8104       [sview addSubview: self];
8105     }
8107 /*  [self setFrame: r]; */
8109   return self;
8113 - (void)setFrame: (NSRect)newRect
8115   NSTRACE ("[EmacsScroller setFrame:]");
8117 /*  block_input (); */
8118   if (horizontal)
8119     pixel_length = NSWidth (newRect);
8120   else
8121     pixel_length = NSHeight (newRect);
8122   if (pixel_length == 0) pixel_length = 1;
8123   min_portion = 20 / pixel_length;
8124   [super setFrame: newRect];
8125 /*  unblock_input (); */
8129 - (void)dealloc
8131   NSTRACE ("[EmacsScroller dealloc]");
8132   if (window)
8133     {
8134       if (horizontal)
8135         wset_horizontal_scroll_bar (window, Qnil);
8136       else
8137         wset_vertical_scroll_bar (window, Qnil);
8138     }
8139   window = 0;
8140   [super dealloc];
8144 - condemn
8146   NSTRACE ("[EmacsScroller condemn]");
8147   condemned =YES;
8148   return self;
8152 - reprieve
8154   NSTRACE ("[EmacsScroller reprieve]");
8155   condemned =NO;
8156   return self;
8160 -(bool)judge
8162   NSTRACE ("[EmacsScroller judge]");
8163   bool ret = condemned;
8164   if (condemned)
8165     {
8166       EmacsView *view;
8167       block_input ();
8168       /* ensure other scrollbar updates after deletion */
8169       view = (EmacsView *)FRAME_NS_VIEW (frame);
8170       if (view != nil)
8171         view->scrollbarsNeedingUpdate++;
8172       if (window)
8173         {
8174           if (horizontal)
8175             wset_horizontal_scroll_bar (window, Qnil);
8176           else
8177             wset_vertical_scroll_bar (window, Qnil);
8178         }
8179       window = 0;
8180       [self removeFromSuperview];
8181       [self release];
8182       unblock_input ();
8183     }
8184   return ret;
8188 - (void)resetCursorRects
8190   NSRect visible = [self visibleRect];
8191   NSTRACE ("[EmacsScroller resetCursorRects]");
8193   if (!NSIsEmptyRect (visible))
8194     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8195   [[NSCursor arrowCursor] setOnMouseEntered: YES];
8199 - (int) checkSamePosition: (int) position portion: (int) portion
8200                     whole: (int) whole
8202   return em_position ==position && em_portion ==portion && em_whole ==whole
8203     && portion != whole; /* needed for resize empty buf */
8207 - setPosition: (int)position portion: (int)portion whole: (int)whole
8209   NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8211   em_position = position;
8212   em_portion = portion;
8213   em_whole = whole;
8215   if (portion >= whole)
8216     {
8217 #ifdef NS_IMPL_COCOA
8218       [self setKnobProportion: 1.0];
8219       [self setDoubleValue: 1.0];
8220 #else
8221       [self setFloatValue: 0.0 knobProportion: 1.0];
8222 #endif
8223     }
8224   else
8225     {
8226       float pos;
8227       CGFloat por;
8228       portion = max ((float)whole*min_portion/pixel_length, portion);
8229       pos = (float)position / (whole - portion);
8230       por = (CGFloat)portion/whole;
8231 #ifdef NS_IMPL_COCOA
8232       [self setKnobProportion: por];
8233       [self setDoubleValue: pos];
8234 #else
8235       [self setFloatValue: pos knobProportion: por];
8236 #endif
8237     }
8239   return self;
8242 /* set up emacs_event */
8243 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8245   Lisp_Object win;
8247   NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8249   if (!emacs_event)
8250     return;
8252   emacs_event->part = last_hit_part;
8253   emacs_event->code = 0;
8254   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8255   XSETWINDOW (win, window);
8256   emacs_event->frame_or_window = win;
8257   emacs_event->timestamp = EV_TIMESTAMP (e);
8258   emacs_event->arg = Qnil;
8260   if (horizontal)
8261     {
8262       emacs_event->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
8263       XSETINT (emacs_event->x, em_whole * loc / pixel_length);
8264       XSETINT (emacs_event->y, em_whole);
8265     }
8266   else
8267     {
8268       emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8269       XSETINT (emacs_event->x, loc);
8270       XSETINT (emacs_event->y, pixel_length-20);
8271     }
8273   if (q_event_ptr)
8274     {
8275       n_emacs_events_pending++;
8276       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8277     }
8278   else
8279     hold_event (emacs_event);
8280   EVENT_INIT (*emacs_event);
8281   ns_send_appdefined (-1);
8285 /* called manually thru timer to implement repeated button action w/hold-down */
8286 - repeatScroll: (NSTimer *)scrollEntry
8288   NSEvent *e = [[self window] currentEvent];
8289   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
8290   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8292   NSTRACE ("[EmacsScroller repeatScroll:]");
8294   /* clear timer if need be */
8295   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8296     {
8297         [scroll_repeat_entry invalidate];
8298         [scroll_repeat_entry release];
8299         scroll_repeat_entry = nil;
8301         if (inKnob)
8302           return self;
8304         scroll_repeat_entry
8305           = [[NSTimer scheduledTimerWithTimeInterval:
8306                         SCROLL_BAR_CONTINUOUS_DELAY
8307                                             target: self
8308                                           selector: @selector (repeatScroll:)
8309                                           userInfo: 0
8310                                            repeats: YES]
8311               retain];
8312     }
8314   [self sendScrollEventAtLoc: 0 fromEvent: e];
8315   return self;
8319 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
8320    mouseDragged events without going into a modal loop. */
8321 - (void)mouseDown: (NSEvent *)e
8323   NSRect sr, kr;
8324   /* hitPart is only updated AFTER event is passed on */
8325   NSScrollerPart part = [self testPart: [e locationInWindow]];
8326   CGFloat loc, kloc, pos UNINIT;
8327   int edge = 0;
8329   NSTRACE ("[EmacsScroller mouseDown:]");
8331   switch (part)
8332     {
8333     case NSScrollerDecrementPage:
8334       last_hit_part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle; break;
8335     case NSScrollerIncrementPage:
8336       last_hit_part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle; break;
8337     case NSScrollerDecrementLine:
8338       last_hit_part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow; break;
8339     case NSScrollerIncrementLine:
8340       last_hit_part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow; break;
8341     case NSScrollerKnob:
8342       last_hit_part = horizontal ? scroll_bar_horizontal_handle : scroll_bar_handle; break;
8343     case NSScrollerKnobSlot:  /* GNUstep-only */
8344       last_hit_part = scroll_bar_move_ratio; break;
8345     default:  /* NSScrollerNoPart? */
8346       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8347                (long) part);
8348       return;
8349     }
8351   if (part == NSScrollerKnob || part == NSScrollerKnobSlot)
8352     {
8353       /* handle, or on GNUstep possibly slot */
8354       NSEvent *fake_event;
8355       int length;
8357       /* compute float loc in slot and mouse offset on knob */
8358       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8359                       toView: nil];
8360       if (horizontal)
8361         {
8362           length = NSWidth (sr);
8363           loc = ([e locationInWindow].x - NSMinX (sr));
8364         }
8365       else
8366         {
8367           length = NSHeight (sr);
8368           loc = length - ([e locationInWindow].y - NSMinY (sr));
8369         }
8371       if (loc <= 0.0)
8372         {
8373           loc = 0.0;
8374           edge = -1;
8375         }
8376       else if (loc >= length)
8377         {
8378           loc = length;
8379           edge = 1;
8380         }
8382       if (edge)
8383         kloc = 0.5 * edge;
8384       else
8385         {
8386           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8387                           toView: nil];
8388           if (horizontal)
8389             kloc = ([e locationInWindow].x - NSMinX (kr));
8390           else
8391             kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8392         }
8393       last_mouse_offset = kloc;
8395       if (part != NSScrollerKnob)
8396         /* this is a slot click on GNUstep: go straight there */
8397         pos = loc;
8399       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8400       fake_event = [NSEvent mouseEventWithType: NSEventTypeLeftMouseUp
8401                                       location: [e locationInWindow]
8402                                  modifierFlags: [e modifierFlags]
8403                                      timestamp: [e timestamp]
8404                                   windowNumber: [e windowNumber]
8405                                        context: [e context]
8406                                    eventNumber: [e eventNumber]
8407                                     clickCount: [e clickCount]
8408                                       pressure: [e pressure]];
8409       [super mouseUp: fake_event];
8410     }
8411   else
8412     {
8413       pos = 0;      /* ignored */
8415       /* set a timer to repeat, as we can't let superclass do this modally */
8416       scroll_repeat_entry
8417         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8418                                             target: self
8419                                           selector: @selector (repeatScroll:)
8420                                           userInfo: 0
8421                                            repeats: YES]
8422             retain];
8423     }
8425   if (part != NSScrollerKnob)
8426     [self sendScrollEventAtLoc: pos fromEvent: e];
8430 /* Called as we manually track scroller drags, rather than superclass. */
8431 - (void)mouseDragged: (NSEvent *)e
8433     NSRect sr;
8434     double loc, pos;
8435     int length;
8437     NSTRACE ("[EmacsScroller mouseDragged:]");
8439       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8440                       toView: nil];
8442       if (horizontal)
8443         {
8444           length = NSWidth (sr);
8445           loc = ([e locationInWindow].x - NSMinX (sr));
8446         }
8447       else
8448         {
8449           length = NSHeight (sr);
8450           loc = length - ([e locationInWindow].y - NSMinY (sr));
8451         }
8453       if (loc <= 0.0)
8454         {
8455           loc = 0.0;
8456         }
8457       else if (loc >= length + last_mouse_offset)
8458         {
8459           loc = length + last_mouse_offset;
8460         }
8462       pos = (loc - last_mouse_offset);
8463       [self sendScrollEventAtLoc: pos fromEvent: e];
8467 - (void)mouseUp: (NSEvent *)e
8469   NSTRACE ("[EmacsScroller mouseUp:]");
8471   if (scroll_repeat_entry)
8472     {
8473       [scroll_repeat_entry invalidate];
8474       [scroll_repeat_entry release];
8475       scroll_repeat_entry = nil;
8476     }
8477   last_hit_part = scroll_bar_above_handle;
8481 /* treat scrollwheel events in the bar as though they were in the main window */
8482 - (void) scrollWheel: (NSEvent *)theEvent
8484   NSTRACE ("[EmacsScroller scrollWheel:]");
8486   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8487   [view mouseDown: theEvent];
8490 @end  /* EmacsScroller */
8493 #ifdef NS_IMPL_GNUSTEP
8494 /* Dummy class to get rid of startup warnings.  */
8495 @implementation EmacsDocument
8497 @end
8498 #endif
8501 /* ==========================================================================
8503    Font-related functions; these used to be in nsfaces.m
8505    ========================================================================== */
8508 Lisp_Object
8509 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8511   struct font *font = XFONT_OBJECT (font_object);
8512   EmacsView *view = FRAME_NS_VIEW (f);
8513   int font_ascent, font_descent;
8515   if (fontset < 0)
8516     fontset = fontset_from_font (font_object);
8517   FRAME_FONTSET (f) = fontset;
8519   if (FRAME_FONT (f) == font)
8520     /* This font is already set in frame F.  There's nothing more to
8521        do.  */
8522     return font_object;
8524   FRAME_FONT (f) = font;
8526   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8527   FRAME_COLUMN_WIDTH (f) = font->average_width;
8528   get_font_ascent_descent (font, &font_ascent, &font_descent);
8529   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8531   /* Compute the scroll bar width in character columns.  */
8532   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8533     {
8534       int wid = FRAME_COLUMN_WIDTH (f);
8535       FRAME_CONFIG_SCROLL_BAR_COLS (f)
8536         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8537     }
8538   else
8539     {
8540       int wid = FRAME_COLUMN_WIDTH (f);
8541       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8542     }
8544   /* Compute the scroll bar height in character lines.  */
8545   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8546     {
8547       int height = FRAME_LINE_HEIGHT (f);
8548       FRAME_CONFIG_SCROLL_BAR_LINES (f)
8549         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8550     }
8551   else
8552     {
8553       int height = FRAME_LINE_HEIGHT (f);
8554       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8555     }
8557   /* Now make the frame display the given font.  */
8558   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8559     adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8560                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8561                        false, Qfont);
8563   return font_object;
8567 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8568 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8569          in 1.43. */
8571 const char *
8572 ns_xlfd_to_fontname (const char *xlfd)
8573 /* --------------------------------------------------------------------------
8574     Convert an X font name (XLFD) to an NS font name.
8575     Only family is used.
8576     The string returned is temporarily allocated.
8577    -------------------------------------------------------------------------- */
8579   char *name = xmalloc (180);
8580   int i, len;
8581   const char *ret;
8583   if (!strncmp (xlfd, "--", 2))
8584     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8585   else
8586     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8588   /* stopgap for malformed XLFD input */
8589   if (strlen (name) == 0)
8590     strcpy (name, "Monaco");
8592   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8593      also uppercase after '-' or ' ' */
8594   name[0] = c_toupper (name[0]);
8595   for (len =strlen (name), i =0; i<len; i++)
8596     {
8597       if (name[i] == '$')
8598         {
8599           name[i] = '-';
8600           if (i+1<len)
8601             name[i+1] = c_toupper (name[i+1]);
8602         }
8603       else if (name[i] == '_')
8604         {
8605           name[i] = ' ';
8606           if (i+1<len)
8607             name[i+1] = c_toupper (name[i+1]);
8608         }
8609     }
8610 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
8611   ret = [[NSString stringWithUTF8String: name] UTF8String];
8612   xfree (name);
8613   return ret;
8617 void
8618 syms_of_nsterm (void)
8620   NSTRACE ("syms_of_nsterm");
8622   ns_antialias_threshold = 10.0;
8624   /* from 23+ we need to tell emacs what modifiers there are.. */
8625   DEFSYM (Qmodifier_value, "modifier-value");
8626   DEFSYM (Qalt, "alt");
8627   DEFSYM (Qhyper, "hyper");
8628   DEFSYM (Qmeta, "meta");
8629   DEFSYM (Qsuper, "super");
8630   DEFSYM (Qcontrol, "control");
8631   DEFSYM (QUTF8_STRING, "UTF8_STRING");
8633   DEFSYM (Qfile, "file");
8634   DEFSYM (Qurl, "url");
8636   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8637   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8638   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8639   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8640   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8642   DEFVAR_LISP ("ns-input-file", ns_input_file,
8643               "The file specified in the last NS event.");
8644   ns_input_file =Qnil;
8646   DEFVAR_LISP ("ns-working-text", ns_working_text,
8647               "String for visualizing working composition sequence.");
8648   ns_working_text =Qnil;
8650   DEFVAR_LISP ("ns-input-font", ns_input_font,
8651               "The font specified in the last NS event.");
8652   ns_input_font =Qnil;
8654   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8655               "The fontsize specified in the last NS event.");
8656   ns_input_fontsize =Qnil;
8658   DEFVAR_LISP ("ns-input-line", ns_input_line,
8659                "The line specified in the last NS event.");
8660   ns_input_line =Qnil;
8662   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8663                "The service name specified in the last NS event.");
8664   ns_input_spi_name =Qnil;
8666   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8667                "The service argument specified in the last NS event.");
8668   ns_input_spi_arg =Qnil;
8670   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8671                "This variable describes the behavior of the alternate or option key.\n\
8672 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8673 that key.\n\
8674 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8675 at all, allowing it to be used at a lower level for accented character entry.");
8676   ns_alternate_modifier = Qmeta;
8678   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8679                "This variable describes the behavior of the right alternate or option key.\n\
8680 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8681 that key.\n\
8682 Set to left means be the same key as `ns-alternate-modifier'.\n\
8683 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8684 at all, allowing it to be used at a lower level for accented character entry.");
8685   ns_right_alternate_modifier = Qleft;
8687   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8688                "This variable describes the behavior of the command key.\n\
8689 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8690 that key.");
8691   ns_command_modifier = Qsuper;
8693   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8694                "This variable describes the behavior of the right command key.\n\
8695 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8696 that key.\n\
8697 Set to left means be the same key as `ns-command-modifier'.\n\
8698 Set to none means that the command / option key is not interpreted by Emacs\n\
8699 at all, allowing it to be used at a lower level for accented character entry.");
8700   ns_right_command_modifier = Qleft;
8702   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8703                "This variable describes the behavior of the control key.\n\
8704 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8705 that key.");
8706   ns_control_modifier = Qcontrol;
8708   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8709                "This variable describes the behavior of the right control key.\n\
8710 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8711 that key.\n\
8712 Set to left means be the same key as `ns-control-modifier'.\n\
8713 Set to none means that the control / option key is not interpreted by Emacs\n\
8714 at all, allowing it to be used at a lower level for accented character entry.");
8715   ns_right_control_modifier = Qleft;
8717   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8718                "This variable describes the behavior of the function key (on laptops).\n\
8719 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8720 that key.\n\
8721 Set to none means that the function key is not interpreted by Emacs at all,\n\
8722 allowing it to be used at a lower level for accented character entry.");
8723   ns_function_modifier = Qnone;
8725   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8726                "Non-nil (the default) means to render text antialiased.");
8727   ns_antialias_text = Qt;
8729   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8730                "Whether to confirm application quit using dialog.");
8731   ns_confirm_quit = Qnil;
8733   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8734                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8735 Only works on OSX 10.6 or later.  */);
8736   ns_auto_hide_menu_bar = Qnil;
8738   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8739      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8740 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
8741 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
8742 Default is t for OSX >= 10.7, nil otherwise.  */);
8743 #ifdef HAVE_NATIVE_FS
8744   ns_use_native_fullscreen = YES;
8745 #else
8746   ns_use_native_fullscreen = NO;
8747 #endif
8748   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8750   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8751      doc: /*Non-nil means use animation on non-native fullscreen.
8752 For native fullscreen, this does nothing.
8753 Default is nil.  */);
8754   ns_use_fullscreen_animation = NO;
8756   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8757      doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8758 Note that this does not apply to images.
8759 This variable is ignored on OSX < 10.7 and GNUstep.  */);
8760   ns_use_srgb_colorspace = YES;
8762   /* TODO: move to common code */
8763   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8764                doc: /* Which toolkit scroll bars Emacs uses, if any.
8765 A value of nil means Emacs doesn't use toolkit scroll bars.
8766 With the X Window system, the value is a symbol describing the
8767 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
8768 With MS Windows or Nextstep, the value is t.  */);
8769   Vx_toolkit_scroll_bars = Qt;
8771   DEFVAR_BOOL ("x-use-underline-position-properties",
8772                x_use_underline_position_properties,
8773      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8774 A value of nil means ignore them.  If you encounter fonts with bogus
8775 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8776 to 4.1, set this to nil. */);
8777   x_use_underline_position_properties = 0;
8779   DEFVAR_BOOL ("x-underline-at-descent-line",
8780                x_underline_at_descent_line,
8781      doc: /* Non-nil means to draw the underline at the same place as the descent line.
8782 A value of nil means to draw the underline according to the value of the
8783 variable `x-use-underline-position-properties', which is usually at the
8784 baseline level.  The default value is nil.  */);
8785   x_underline_at_descent_line = 0;
8787   /* Tell Emacs about this window system.  */
8788   Fprovide (Qns, Qnil);
8790   DEFSYM (Qcocoa, "cocoa");
8791   DEFSYM (Qgnustep, "gnustep");
8793 #ifdef NS_IMPL_COCOA
8794   Fprovide (Qcocoa, Qnil);
8795   syms_of_macfont ();
8796 #else
8797   Fprovide (Qgnustep, Qnil);
8798   syms_of_nsfont ();
8799 #endif